Module: NA
- Extended by:
- Editor
- Defined in:
- lib/na/colors.rb,
lib/na.rb,
lib/na/todo.rb,
lib/na/pager.rb,
lib/na/theme.rb,
lib/na/types.rb,
lib/na/action.rb,
lib/na/editor.rb,
lib/na/prompt.rb,
lib/na/actions.rb,
lib/na/plugins.rb,
lib/na/project.rb,
lib/na/benchmark.rb,
lib/na/next_action.rb
Overview
Next Action methods
Defined Under Namespace
Modules: Benchmark, Color, Editor, Pager, Plugins, Prompt, Theme, Types Classes: Action, Actions, Project, Todo
Class Attribute Summary collapse
-
.command ⇒ Object
Returns the value of attribute command.
-
.command_line ⇒ Object
Returns the value of attribute command_line.
-
.cwd ⇒ Object
Returns the value of attribute cwd.
-
.cwd_is ⇒ Object
Returns the value of attribute cwd_is.
-
.debug ⇒ Object
Returns the value of attribute debug.
-
.extension ⇒ Object
Returns the value of attribute extension.
-
.global_file ⇒ Object
Returns the value of attribute global_file.
-
.globals ⇒ Object
Returns the value of attribute globals.
-
.include_ext ⇒ Object
Returns the value of attribute include_ext.
-
.na_tag ⇒ Object
Returns the value of attribute na_tag.
-
.show_cwd_indicator ⇒ Object
Returns the value of attribute show_cwd_indicator.
-
.stdin ⇒ Object
Returns the value of attribute stdin.
-
.verbose ⇒ Object
Returns the value of attribute verbose.
Class Method Summary collapse
-
.add_action(file, project, action, note = [], priority: 0, finish: false, append: false, started_at: nil, done_at: nil, duration_seconds: nil) ⇒ void
Add an action to a todo file.
-
.apply_plugin_result(io_hash) ⇒ Object
Apply a plugin result hash back to the underlying file - Move if parents changed (project path differs) - Update text/note/tags.
-
.backup_file(target) ⇒ void
Create a backup file.
-
.backup_files ⇒ Array<String>
Get list of backed up files.
-
.backup_path(file) ⇒ String
Get the backup file path for a file.
-
.choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) ⇒ String, Array
Generate a menu of options and allow user selection.
-
.color_single_options(choices = %w[y n])) ⇒ String
Helper function to colorize the Y/N prompt.
-
.create_todo(target, basename, template: nil) ⇒ Object
Create a new todo file.
-
.database_path(file: 'tdlist.txt') ⇒ String
Get path to database of known todo files.
-
.delete_search(strings = nil) ⇒ void
Delete saved search definitions by name.
-
.edit_file(file: nil, app: nil) ⇒ void
Open a file in the specified editor/application.
-
.edit_searches ⇒ void
Edit saved search definitions in the default editor.
-
.evaluate_taskpaper_search(expr, file: nil, options: {}) ⇒ Array(NA::Actions, Array<String>, Array<Hash>)
Evaluate a TaskPaper-style @search() expression and return matching actions and files, without printing.
-
.find_actions(target, search, tagged = nil, all: false, done: false, project: nil, search_note: true, target_line: nil) ⇒ Array
Find actions in a todo file matching criteria.
-
.find_exact_dir(dirs, search) ⇒ Array<String>
Find a directory with an exact match from a list.
-
.find_files(depth: 1, include_hidden: false) ⇒ Array<String>
Locate files matching NA.extension up to a given depth.
-
.find_files_matching(options = {}) ⇒ Array<String>
Find files matching criteria and containing actions.
-
.find_projects(target) ⇒ Array<NA::Project>
Find all projects in a todo file.
-
.insert_project(target, project) ⇒ NA::Project
Insert a new project into a todo file.
-
.item_path_step_match?(step, proj) ⇒ Boolean
Check if a project matches a single item-path step.
-
.last_modified_file(search: nil) ⇒ String?
Get the last modified file from the database.
-
.list_projects(query: [], file_path: nil, depth: 1, paths: true) ⇒ void
List projects in a todo file or matching query.
-
.list_todos(query: []) ⇒ void
List todo files matching a query.
-
.load_searches ⇒ Hash
Load saved search definitions from YAML file.
-
.load_taskpaper_searches(depth: 1) ⇒ Hash{String=>Hash}
Load TaskPaper-style saved searches from todo files.
-
.match_working_dir(search, distance: 1, require_last: true) ⇒ Array<String>
Find a matching path using semi-fuzzy matching.
-
.move_deprecated_backups ⇒ void
Move deprecated backup files to new backup folder.
-
.notify(msg, exit_code: false, debug: false) ⇒ void
Print a message to stderr, optionally exit or debug.
-
.old_backup_path(file) ⇒ String
Get the old backup file path for a file.
-
.os_open(file, app: nil) ⇒ void
Platform-agnostic open command.
-
.output_children(children, level = 1) ⇒ Object
Output an Omnifocus-friendly action list.
-
.parse_item_path(path) ⇒ Object
Parse a TaskPaper-style item path string into steps with axis and text.
-
.parse_taskpaper_search(expr) ⇒ Hash
Parse a TaskPaper-style @search() expression into NA search components.
-
.parse_taskpaper_search_clause(clause, out) ⇒ Hash
Internal: parse a single (AND-joined) TaskPaper clause into search components.
-
.parse_taskpaper_search_clauses(expr) ⇒ Array<Hash>
Parse a TaskPaper-style @search() expression into multiple OR-joined clauses.
-
.priority_map ⇒ Hash{String=>Integer}
Returns a map of priority levels to numeric values.
-
.project_hierarchy(actions) ⇒ Hash
Build a nested hash representing project hierarchy from actions.
-
.request_input(options, prompt: 'Enter text') ⇒ Object
Request terminal input from user, readline style.
-
.resolve_item_path(path:, file: nil, depth: 1) ⇒ Array<String>
Resolve a TaskPaper-style item path (subset) into NA project paths.
-
.resolve_path_in_projects(projects, steps) ⇒ Array<NA::Project>
Resolve a parsed item path against a list of NA::Project objects from a single file.
-
.restore_last_modified_file(search: nil) ⇒ void
Get last modified file and restore a backup.
-
.restore_modified_file(file) ⇒ void
Restore a file from backup.
-
.run_taskpaper_search(expr, file: nil, options: {}) ⇒ void
Execute a TaskPaper-style @search() expression using NA::Todo and output results with the standard formatting options.
-
.save_modified_file(file) ⇒ void
Save a backed-up file to the database.
-
.save_search(title, search) ⇒ void
Save a search definition to the database.
-
.save_working_dir(todo_file) ⇒ void
Save a todo file path to the database.
-
.select_actions(file: nil, depth: 1, search: [], tagged: [], include_done: false) ⇒ Array<NA::Action>
Select actions across files using existing search pipeline.
-
.select_file(files, multiple: false) ⇒ String+
Select from multiple files.
-
.shift_index_after(projects, idx, length = 1) ⇒ Array<NA::Project>
Shift project indices after a given index by a length.
-
.theme ⇒ Hash
Returns the current theme hash for color and style settings.
-
.update_action(target, search, search_note: true, add: nil, add_tag: [], all: false, append: false, delete: false, done: false, edit: false, finish: false, note: [], overwrite: false, priority: 0, project: nil, move: nil, remove_tag: [], replace: nil, tagged: nil, started_at: nil, done_at: nil, duration_seconds: nil, suppress_prompt: false) ⇒ void
Update actions in a todo file (add, edit, delete, move, etc.).
-
.weed_cache_file ⇒ Object
Remove entries from cache database that no longer exist.
-
.weed_modified_files(file = nil) ⇒ void
Remove entries for missing backup files from the database.
-
.yn(prompt, default: true) ⇒ Boolean
Display and read a Yes/No prompt.
Methods included from Editor
args_for_editor, default_editor, editor_with_args, fork_editor, format_input, format_multi_action_input, parse_multi_action_output
Class Attribute Details
.command ⇒ Object
Returns the value of attribute command.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def command @command end |
.command_line ⇒ Object
Returns the value of attribute command_line.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def command_line @command_line end |
.cwd ⇒ Object
Returns the value of attribute cwd.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def cwd @cwd end |
.cwd_is ⇒ Object
Returns the value of attribute cwd_is.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def cwd_is @cwd_is end |
.debug ⇒ Object
Returns the value of attribute debug.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def debug @debug end |
.extension ⇒ Object
Returns the value of attribute extension.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def extension @extension end |
.global_file ⇒ Object
Returns the value of attribute global_file.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def global_file @global_file end |
.globals ⇒ Object
Returns the value of attribute globals.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def globals @globals end |
.include_ext ⇒ Object
Returns the value of attribute include_ext.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def include_ext @include_ext end |
.na_tag ⇒ Object
Returns the value of attribute na_tag.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def na_tag @na_tag end |
.show_cwd_indicator ⇒ Object
Returns the value of attribute show_cwd_indicator.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def show_cwd_indicator @show_cwd_indicator end |
.stdin ⇒ Object
Returns the value of attribute stdin.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def stdin @stdin end |
.verbose ⇒ Object
Returns the value of attribute verbose.
6 7 8 |
# File 'lib/na/next_action.rb', line 6 def verbose @verbose end |
Class Method Details
.add_action(file, project, action, note = [], priority: 0, finish: false, append: false, started_at: nil, done_at: nil, duration_seconds: nil) ⇒ void
This method returns an undefined value.
Add an action to a todo file
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
# File 'lib/na/next_action.rb', line 711 def add_action(file, project, action, note = [], priority: 0, finish: false, append: false, started_at: nil, done_at: nil, duration_seconds: nil) parent = project.split(%r{[:/]}) file_project = File.basename(file, ".#{NA.extension}") if NA.global_file if NA.cwd_is == :tag add_tag = [NA.cwd] else project = NA.cwd end end action = Action.new(file, file_project, parent, action, nil, note) update_action(file, nil, add: action, project: project, add_tag: add_tag, priority: priority, finish: finish, append: append, started_at: started_at, done_at: done_at, duration_seconds: duration_seconds) end |
.apply_plugin_result(io_hash) ⇒ Object
Apply a plugin result hash back to the underlying file
-
Move if parents changed (project path differs)
-
Update text/note/tags
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/na/next_action.rb', line 28 def apply_plugin_result(io_hash) file = io_hash['file_path'] line = io_hash['line'].to_i parents = Array(io_hash['parents']).map(&:to_s) text = io_hash['text'].to_s note = io_hash['note'].to_s = Array(io_hash['tags']).to_h { |t| [t['name'].to_s, t['value'].to_s] } action_block = io_hash['action'] || { 'action' => 'UPDATE', 'arguments' => [] } action_name = action_block['action'].to_s.upcase action_args = Array(action_block['arguments']) # Load current action _projects, actions = find_actions(file, nil, nil, all: true, done: true, project: nil, search_note: true, target_line: line) action = actions&.first return unless action # Determine new project path from parents array new_project = '' new_parent_chain = [] if parents.any? new_project = parents.first.to_s new_parent_chain = parents[1..] || [] end case action_name when 'DELETE' update_action(file, { target_line: line }, delete: true, all: true) return when 'COMPLETE' update_action(file, { target_line: line }, finish: true, all: true) return when 'RESTORE' update_action(file, { target_line: line }, restore: true, all: true) return when 'ARCHIVE' update_action(file, { target_line: line }, finish: true, move: 'Archive', all: true) return when 'ADD_TAG' = action_args.map { |t| t.sub(/^@/, '') } update_action(file, { target_line: line }, add: action, add_tag: , all: true) return when 'DELETE_TAG', 'REMOVE_TAG' = action_args.map { |t| t.sub(/^@/, '') } update_action(file, { target_line: line }, add: action, remove_tag: , all: true) return when 'MOVE' move_to = action_args.first.to_s update_action(file, { target_line: line }, add: action, move: move_to, all: true, suppress_prompt: true) return end # Replace content on the existing action then write back in-place original_line = action.file_line original_project = action.project original_parent_chain = action.parent.dup # Update action content action.action = text action.note = note.to_s.split("\n") action.action.gsub!(/(?<=\A| )@[^( \s\n]+(?:\(.*?\))?/, '') unless .empty? tag_str = .map { |k, v| v.to_s.empty? ? "@#{k}" : "@#{k}(#{v})" }.join(' ') action.action = action.action.strip + (tag_str.empty? ? "" : " #{tag_str}") end # Check if parents changed parents_changed = new_project.to_s.strip != original_project || new_parent_chain != original_parent_chain move_to = parents_changed ? ([new_project] + new_parent_chain).join(':') : nil # Update in-place (with move if parents changed) update_action(file, { target_line: original_line }, add: action, move: move_to, all: true, suppress_prompt: true) end |
.backup_file(target) ⇒ void
This method returns an undefined value.
Create a backup file
2075 2076 2077 2078 2079 |
# File 'lib/na/next_action.rb', line 2075 def backup_file(target) FileUtils.cp(target, backup_path(target)) save_modified_file(target) NA.notify("#{NA.theme[:warning]}Backup file created for #{target.highlight_filename}", debug: true) end |
.backup_files ⇒ Array<String>
Get list of backed up files
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 |
# File 'lib/na/next_action.rb', line 1013 def backup_files db = database_path(file: 'last_modified.txt') if File.exist?(db) File.read(db).strip.split("\n").map(&:strip) else NA.notify("#{NA.theme[:error]}Backup database not found") File.open(db, 'w', &:puts) [] end end |
.backup_path(file) ⇒ String
Get the backup file path for a file
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 |
# File 'lib/na/next_action.rb', line 1048 def backup_path(file) backup_home = File.('~/.local/share/na/backup') backup = old_backup_path(file) backup_dir = File.join(backup_home, File.dirname(backup)) FileUtils.mkdir_p(backup_dir) unless File.directory?(backup_dir) backup_target = File.join(backup_home, backup) FileUtils.mv(backup, backup_target) if File.exist?(backup) backup_target end |
.choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) ⇒ String, Array
Generate a menu of options and allow user selection
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 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 |
# File 'lib/na/next_action.rb', line 2111 def choose_from(, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) return nil unless $stdout.isatty .sort! if sorted res = if TTY::Which.exist?('fzf') default_args = [%(--prompt="#{prompt}"), "--height=#{.count + 2}", '--info=inline'] default_args << '--multi' if multiple default_args << '--bind ctrl-a:select-all' if multiple header = "esc: cancel,#{' tab: multi-select, ctrl-a: select all,' if multiple} return: confirm" default_args << %(--header="#{header}") default_args.concat(fzf_args) = NA::Color.uncolor(NA::Color.template(.join("\n"))) `echo #{Shellwords.escape()}|#{TTY::Which.which('fzf')} #{default_args.join(' ')}`.strip elsif TTY::Which.exist?('gum') args = [ '--cursor.foreground="151"', '--item.foreground=""' ] args.push '--no-limit' if multiple puts NA::Color.template("#{NA.theme[:prompt]}#{prompt}{x}") = NA::Color.uncolor(NA::Color.template(.join("\n"))) `echo #{Shellwords.escape()}|#{TTY::Which.which('gum')} choose #{args.join(' ')}`.strip else reader = TTY::Reader.new puts .each.with_index do |f, i| puts NA::Color.template(format( "#{NA.theme[:prompt]}%<idx> 2d{xw}) #{NA.theme[:filename]}%<action>s{x}\n", idx: i + 1, action: f )) end result = reader.read_line(NA::Color.template("#{NA.theme[:prompt]}#{prompt}{x}")).strip if multiple mult_res = [] result = result.gsub(',', ' ').gsub(/ +/, ' ').split(/ /) result.each do |r| mult_res << [r.to_i - 1] if r.to_i.positive? end mult_res.join("\n") else result.to_i.positive? ? [result.to_i - 1] : nil end end return false if res&.strip&.empty? # pp NA::Color.uncolor(NA::Color.template(res)) multiple ? NA::Color.uncolor(NA::Color.template(res)).split("\n") : NA::Color.uncolor(NA::Color.template(res)) end |
.color_single_options(choices = %w[y n])) ⇒ String
Helper function to colorize the Y/N prompt
168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/na/next_action.rb', line 168 def (choices = %w[y n]) out = [] choices.each do |choice| case choice when /[A-Z]/ out.push(NA::Color.template("{bw}#{choice}{x}")) else out.push(NA::Color.template("{dw}#{choice}{xg}")) end end NA::Color.template("{xg}[#{out.join('/')}{xg}]{x}") end |
.create_todo(target, basename, template: nil) ⇒ Object
Create a new todo file
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/na/next_action.rb', line 187 def create_todo(target, basename, template: nil) File.open(target, 'w') do |f| content = if template && File.exist?(template) File.read(template) else <<~ENDCONTENT Inbox: #{basename}: \tFeature Requests: \tIdeas: \tBugs: Archive: Search Definitions: \tTop Priority @search(@priority = 5 and not @done) \tHigh Priority @search(@priority > 3 and not @done) \tMaybe @search(@maybe) \tNext @search(@#{NA.na_tag} and not @done and not project = "Archive") ENDCONTENT end f.puts(content) end save_working_dir(target) notify("#{NA.theme[:warning]}Created #{NA.theme[:file]}#{target}") end |
.database_path(file: 'tdlist.txt') ⇒ String
Get path to database of known todo files
1093 1094 1095 1096 1097 1098 |
# File 'lib/na/next_action.rb', line 1093 def database_path(file: 'tdlist.txt') db_dir = File.('~/.local/share/na') # Create directory if needed FileUtils.mkdir_p(db_dir) unless File.directory?(db_dir) File.join(db_dir, file) end |
.delete_search(strings = nil) ⇒ void
This method returns an undefined value.
Delete saved search definitions by name
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 |
# File 'lib/na/next_action.rb', line 2028 def delete_search(strings = nil) NA.notify("#{NA.theme[:error]}Name of search required", exit_code: 1) if strings.nil? || strings.empty? file = database_path(file: 'saved_searches.yml') NA.notify("#{NA.theme[:error]}No search definitions file found", exit_code: 1) unless File.exist?(file) strings = [strings] unless strings.is_a? Array searches = YAML.load(file.read_file) keys = searches.keys.delete_if { |k| k !~ /(#{strings.map(&:wildcard_to_rx).join('|')})/ } NA.notify("#{NA.theme[:error]}No search named #{strings.join(', ')} found", exit_code: 1) if keys.empty? res = yn(NA::Color.template(%(#{NA.theme[:warning]}Remove #{keys.count > 1 ? 'searches' : 'search'} #{NA.theme[:filename]}"#{keys.join(', ')}"{x})), default: false) NA.notify("#{NA.theme[:error]}Cancelled", exit_code: 1) unless res searches.delete_if { |k| keys.include?(k) } File.open(file, 'w') { |f| f.puts(YAML.dump(searches)) } NA.notify( "#{NA.theme[:warning]}Deleted {bw}#{keys.count}{x}#{NA.theme[:warning]} #{keys.count > 1 ? 'searches' : 'search'}", exit_code: 0 ) end |
.edit_file(file: nil, app: nil) ⇒ void
This method returns an undefined value.
Open a file in the specified editor/application
798 799 800 |
# File 'lib/na/next_action.rb', line 798 def edit_file(file: nil, app: nil) os_open(file, app: app) if file && File.exist?(file) end |
.edit_searches ⇒ void
This method returns an undefined value.
Edit saved search definitions in the default editor
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 |
# File 'lib/na/next_action.rb', line 2058 def edit_searches file = database_path(file: 'saved_searches.yml') searches = load_searches NA.notify("#{NA.theme[:error]}No search definitions found", exit_code: 1) unless searches.any? editor = NA.default_editor NA.notify("#{NA.theme[:error]}No $EDITOR defined", exit_code: 1) unless editor && TTY::Which.exist?(editor) system %(#{editor} "#{file}") NA.notify("#{NA.theme[:success]}Opened #{file} in #{editor}", exit_code: 0) end |
.evaluate_taskpaper_search(expr, file: nil, options: {}) ⇒ Array(NA::Actions, Array<String>, Array<Hash>)
Evaluate a TaskPaper-style @search() expression and return matching actions and files, without printing.
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 |
# File 'lib/na/next_action.rb', line 1853 def evaluate_taskpaper_search(expr, file: nil, options: {}) clauses = parse_taskpaper_search_clauses(expr) NA.notify("TP DEBUG clauses: #{clauses.inspect}", debug: true) if NA.verbose return [NA::Actions.new, [], []] if clauses.empty? depth = [:depth] || 1 all_actions = NA::Actions.new all_files = [] clauses.each do |parsed| search_tokens = parsed[:tokens] = parsed[:tags] include_done = parsed[:include_done] exclude_projects = parsed[:exclude_projects] || [] project = parsed[:project] || [:project] slice = parsed[:slice] # Resolve any item-path filters declared on this clause item_paths = Array(parsed[:item_paths]).compact resolved_paths = [] item_paths.each do |p| resolved_paths.concat(resolve_item_path(path: p, file: file, depth: depth)) end = { depth: depth, done: include_done.nil? ? [:done] : include_done, query: nil, search: search_tokens, search_note: .fetch(:search_notes, true), tag: , negate: .fetch(:invert, false), regex: .fetch(:regex, false), project: project, require_na: .fetch(:require_na, false) } [:file_path] = file if file todo = NA::Todo.new() # Start from the full action list for this clause clause_actions = todo.actions.to_a if NA.verbose NA.notify("TP DEBUG initial actions count: #{clause_actions.size}", debug: true) clause_actions.each do |a| NA.notify("TP DEBUG action: #{a.action.inspect} parents=#{Array(a.parent).inspect}", debug: true) end end # Apply project exclusions (e.g. "not project = \"Archive\"") unless exclude_projects.empty? before = clause_actions.size clause_actions.delete_if do |action| parents = Array(action.parent) last = parents.last.to_s full = parents.join(':') exclude_projects.any? do |proj| proj_rx = Regexp.new(Regexp.escape(proj), Regexp::IGNORECASE) last =~ proj_rx || full =~ /(^|:)#{Regexp.escape(proj)}$/i end end NA.notify("TP DEBUG after exclude_projects: #{clause_actions.size} (was #{before})", debug: true) if NA.verbose end # Apply item-path project filters, if any unless resolved_paths.empty? before = clause_actions.size clause_actions.delete_if do |action| parents = Array(action.parent) path = parents.join(':') resolved_paths.none? do |p| path =~ /\A#{Regexp.escape(p)}(?::|\z)/i end end NA.notify("TP DEBUG after item_path filter: #{clause_actions.size} (was #{before})", debug: true) if NA.verbose end # Apply slice, if present, to the filtered clause actions if slice before = clause_actions.size if slice[:index] idx = slice[:index].to_i clause_actions = idx.negative? ? [] : [clause_actions[idx]].compact else start_idx = slice[:start] || 0 end_idx = slice[:end] || clause_actions.length clause_actions = clause_actions[start_idx...end_idx] || [] end NA.notify("TP DEBUG after slice #{slice.inspect}: #{clause_actions.size} (was #{before})", debug: true) if NA.verbose end all_files.concat(todo.files) clause_actions.each { |a| all_actions.push(a) } end # De-duplicate actions across clauses seen = {} merged_actions = NA::Actions.new all_actions.each do |a| key = "#{a.file_path}:#{a.file_line}" next if seen[key] seen[key] = true merged_actions.push(a) end if NA.verbose NA.notify("TP DEBUG merged_actions count: #{merged_actions.size}", debug: true) merged_actions.each do |a| NA.notify("TP DEBUG merged action: #{a.file_path}:#{a.file_line} #{a.action.inspect}", debug: true) end end [merged_actions, all_files.uniq, clauses] end |
.find_actions(target, search, tagged = nil, all: false, done: false, project: nil, search_note: true, target_line: nil) ⇒ Array
Find actions in a todo file matching criteria
266 267 268 269 270 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 307 308 309 310 311 312 313 |
# File 'lib/na/next_action.rb', line 266 def find_actions(target, search, tagged = nil, all: false, done: false, project: nil, search_note: true, target_line: nil) todo = NA::Todo.new({ search: search, search_note: search_note, require_na: false, file_path: target, project: project, tag: tagged, done: done }) unless todo.actions.any? NA.notify("#{NA.theme[:error]}No matching actions found in #{File.basename(target, ".#{NA.extension}").highlight_filename}") return [todo.projects, NA::Actions.new] end return [todo.projects, todo.actions] if todo.actions.one? || all # If target_line is specified, find the action at that specific line if target_line matching_action = todo.actions.find { |a| a.line == target_line } return [todo.projects, NA::Actions.new([matching_action])] if matching_action NA.notify("#{NA.theme[:error]}No action found at line #{target_line}", exit_code: 1) return [todo.projects, NA::Actions.new] end = todo.actions.map { |action| "#{action.file} : #{action.action}" } res = choose_from(, prompt: 'Make a selection: ', multiple: true, sorted: true) unless res&.length&.positive? NA.notify("#{NA.theme[:error]}Cancelled", exit_code: 1) return [todo.projects, NA::Actions.new] end selected = NA::Actions.new res.each do |result| # Extract file:line from result (e.g., "./todo.taskpaper:21 : action text") match = result.match(/^(.+?):(\d+) : /) next unless match file_path = match[1] line_num = match[2].to_i action = todo.actions.select { |a| a.file_path == file_path && a.file_line == line_num }.first selected.push(action) if action end [todo.projects, selected] end |
.find_exact_dir(dirs, search) ⇒ Array<String>
Find a directory with an exact match from a list.
943 944 945 946 947 948 949 950 951 952 953 |
# File 'lib/na/next_action.rb', line 943 def find_exact_dir(dirs, search) terms = search.filter { |s| !s[:negate] }.map { |t| t[:token] }.join(' ') out = dirs dirs.each do |dir| if File.basename(dir).sub(/\.#{NA.extension}$/, '') =~ /^#{terms}$/ out = [dir] break end end out end |
.find_files(depth: 1, include_hidden: false) ⇒ Array<String>
Locate files matching NA.extension up to a given depth
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 |
# File 'lib/na/next_action.rb', line 807 def find_files(depth: 1, include_hidden: false) NA::Benchmark.measure("find_files (depth=#{depth})") do return [NA.global_file] if NA.global_file # Build a brace-expanded pattern list covering 1..depth levels, e.g.: # depth=1 -> "*.ext" # depth=3 -> "{*.ext,*/*.ext,*/*/*.ext}" ext = NA.extension patterns = (1..[depth.to_i, 1].max).map do |d| prefix = d > 1 ? ('*/' * (d - 1)) : '' "#{prefix}*.#{ext}" end pattern = patterns.length == 1 ? patterns.first : "{#{patterns.join(',')}}" files = Dir.glob(pattern, File::FNM_DOTMATCH) # Exclude hidden directories/files unless explicitly requested unless include_hidden files.reject! do |f| # reject any path segment beginning with '.' (excluding '.' and '..') f.split('/').any? { |seg| seg.start_with?('.') && seg !~ /^\.\.?$/ } end end files.map! { |f| f.sub(%r{\A\./}, '') } files.each { |f| save_working_dir(File.(f)) } files.uniq end end |
.find_files_matching(options = {}) ⇒ Array<String>
Find files matching criteria and containing actions.
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 |
# File 'lib/na/next_action.rb', line 848 def find_files_matching( = {}) defaults = { depth: 1, done: false, file_path: nil, negate: false, hidden: false, project: nil, query: nil, regex: false, search: nil, tag: nil } = defaults.merge() files = find_files(depth: [:depth], include_hidden: [:hidden]) return [] if files.nil? || files.empty? files.delete_if do |file| = { depth: [:depth], done: [:done], file_path: file, negate: [:negate], project: [:project], query: [:query], regex: [:regex], require_na: [:require_na], search: [:search], tag: [:tag] } todo = NA::Todo.new() todo.actions.empty? end files end |
.find_projects(target) ⇒ Array<NA::Project>
Find all projects in a todo file
250 251 252 253 |
# File 'lib/na/next_action.rb', line 250 def find_projects(target) todo = NA::Todo.new(require_na: false, file_path: target) todo.projects end |
.insert_project(target, project) ⇒ NA::Project
Insert a new project into a todo file
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
# File 'lib/na/next_action.rb', line 320 def insert_project(target, project) path = project.split(%r{[:/]}) todo = NA::Todo.new(file_path: target) built = [] last_match = nil final_match = nil new_path = [] matches = nil path.each_with_index do |part, i| built.push(part) built_path = built.join(':') matches = todo.projects.select { |proj| proj.project =~ /^#{Regexp.escape(built_path)}/i } exact_match = matches.find { |proj| proj.project.casecmp(built_path).zero? } if exact_match last_match = exact_match else final_match = last_match new_path = path.slice(i, path.count - i) break end end content = target.read_file if final_match.nil? indent = 0 input = [] new_path.each do |part| input.push("#{"\t" * indent}#{part.cap_first}:") indent += 1 end if new_path.join =~ /Archive/i line = todo.projects.last&.last_line || 0 content = content.split("\n").insert(line, input.join("\n")).join("\n") else split = content.split("\n") line = todo.projects.first&.line || 0 before = split.slice(0, line).join("\n") after = split.slice(line, split.count - 0).join("\n") content = "#{before}\n#{input.join("\n")}\n#{after}" end new_project = NA::Project.new(path.map(&:cap_first).join(':'), indent - 1, line, line) else line = final_match.last_line + 1 indent = final_match.indent + 1 input = [] new_path.each do |part| input.push("#{"\t" * indent}#{part.cap_first}:") indent += 1 end content = content.split("\n").insert(line, input.join("\n")).join("\n") new_project = NA::Project.new(path.map(&:cap_first).join(':'), indent - 1, line + input.count - 1, line + input.count - 1) end File.open(target, 'w') do |f| f.puts content end new_project end |
.item_path_step_match?(step, proj) ⇒ Boolean
Check if a project matches a single item-path step.
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 |
# File 'lib/na/next_action.rb', line 1314 def item_path_step_match?(step, proj) return true if step[:wildcard] name = proj.project.split(':').last.to_s txt = step[:text] return false if txt.nil? || txt.empty? if txt =~ /[*?]/ rx = Regexp.new(txt.wildcard_to_rx, Regexp::IGNORECASE) !!(name =~ rx) else name.downcase.include?(txt.downcase) end end |
.last_modified_file(search: nil) ⇒ String?
Get the last modified file from the database
991 992 993 994 995 |
# File 'lib/na/next_action.rb', line 991 def last_modified_file(search: nil) files = backup_files files.delete_if { |f| f !~ Regexp.new(search.dir_to_rx(require_last: true)) } if search files.last end |
.list_projects(query: [], file_path: nil, depth: 1, paths: true) ⇒ void
This method returns an undefined value.
List projects in a todo file or matching query.
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 |
# File 'lib/na/next_action.rb', line 1137 def list_projects(query: [], file_path: nil, depth: 1, paths: true) files = if NA.global_file [NA.global_file] elsif !file_path.nil? [file_path] elsif query.nil? NA.find_files(depth: depth) else match_working_dir(query) end target = files.count > 1 ? NA.select_file(files) : files[0] return if target.nil? projects = find_projects(target) projects.each do |proj| parts = proj.project.split(':') output = if paths "{bg}#{parts.join('{bw}/{bg}')}{x}" else parts.fill('{bw}—{bg}', 0..-2) "{bg}#{parts.join(' ')}{x}" end puts NA::Color.template(output) end end |
.list_todos(query: []) ⇒ void
This method returns an undefined value.
List todo files matching a query.
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 |
# File 'lib/na/next_action.rb', line 1332 def list_todos(query: []) dirs = if query match_working_dir(query, distance: 2, require_last: false) else file = database_path content = File.exist?(file) ? file.read_file.strip : '' notify("#{NA.theme[:error]}Database empty", exit_code: 1) if content.empty? content.split("\n") end dirs.map!(&:highlight_filename) puts NA::Color.template(dirs.join("\n")) end |
.load_searches ⇒ Hash
Load saved search definitions from YAML file
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 |
# File 'lib/na/next_action.rb', line 2008 def load_searches file = database_path(file: 'saved_searches.yml') if File.exist?(file) searches = YAML.load(file.read_file) else searches = { 'soon' => 'tagged "due<in 2 days,due>yesterday"', 'overdue' => 'tagged "due<now"', 'high' => 'tagged "prio>3"', 'maybe' => 'tagged "maybe"' } File.open(file, 'w') { |f| f.puts(YAML.dump(searches)) } end searches end |
.load_taskpaper_searches(depth: 1) ⇒ Hash{String=>Hash}
Load TaskPaper-style saved searches from todo files.
Scans all lines in each file for:
[WHITESPACE]TITLE @search(PARAMS)
regardless of project name or indentation. This allows searches to live in any project (e.g. “Searches”) or even at top level.
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 |
# File 'lib/na/next_action.rb', line 1824 def load_taskpaper_searches(depth: 1) searches = {} files = find_files(depth: depth) return searches if files.nil? || files.empty? files.each do |file| content = file.read_file next if content.nil? || content.empty? content.each_line do |line| next if line.strip.empty? next unless line =~ /^\s*(.+?)\s+@search\((.+)\)\s*$/ title = Regexp.last_match(1).strip expr = "@search(#{Regexp.last_match(2).strip})" searches[title] = { expr: expr, file: file } end end searches end |
.match_working_dir(search, distance: 1, require_last: true) ⇒ Array<String>
Find a matching path using semi-fuzzy matching. Search tokens can include ! and + to negate or make required.
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 |
# File 'lib/na/next_action.rb', line 892 def match_working_dir(search, distance: 1, require_last: true) file = database_path NA.notify("#{NA.theme[:error]}No na database found", exit_code: 1) unless File.exist?(file) dirs = file.read_file.split("\n") optional = search.filter { |s| !s[:negate] }.map { |t| t[:token] } required = search.filter { |s| s[:required] && !s[:negate] }.map { |t| t[:token] } negated = search.filter { |s| s[:negate] }.map { |t| t[:token] } optional.push('*') if optional.none? && required.none? && negated.any? if optional == negated required = ['*'] optional = ['*'] end NA.notify("Optional directory regex: {x}#{optional.map { |t| t.dir_to_rx(distance: distance) }}", debug: true) NA.notify("Required directory regex: {x}#{required.map { |t| t.dir_to_rx(distance: distance) }}", debug: true) NA.notify("Negated directory regex: {x}#{negated.map do |t| t.dir_to_rx(distance: distance, require_last: false) end}", debug: true) if require_last dirs.delete_if do |d| !d.sub(/\.#{NA.extension}$/, '') .dir_matches?(any: optional, all: required, none: negated, require_last: true, distance: distance) end else dirs.delete_if do |d| !d.sub(/\.#{NA.extension}$/, '') .dir_matches?(any: optional, all: required, none: negated, distance: 2, require_last: false) end end dirs = dirs.sort_by { |d| File.basename(d) }.uniq dirs = find_exact_dir(dirs, search) unless optional == ['*'] if dirs.empty? && require_last NA.notify("#{NA.theme[:warning]}No matches, loosening search", debug: true) match_working_dir(search, distance: 2, require_last: false) else NA.notify("Matched files: {x}#{dirs.join(', ')}", debug: true) dirs end end |
.move_deprecated_backups ⇒ void
This method returns an undefined value.
Move deprecated backup files to new backup folder
1027 1028 1029 1030 1031 1032 1033 1034 |
# File 'lib/na/next_action.rb', line 1027 def move_deprecated_backups backup_files.each do |file| if File.exist?(old_backup_path(file)) NA.notify("Moving deprecated backup to new backup folder (#{file})", debug: true) backup_path(file) end end end |
.notify(msg, exit_code: false, debug: false) ⇒ void
This method returns an undefined value.
Print a message to stderr, optionally exit or debug.
113 114 115 116 117 118 119 120 121 122 |
# File 'lib/na/next_action.rb', line 113 def notify(msg, exit_code: false, debug: false) return if debug && !NA.verbose if debug warn NA::Color.template("{x}#{NA.theme[:debug]}#{msg}{x}") else warn NA::Color.template("{x}#{msg}{x}") end Process.exit exit_code if exit_code end |
.old_backup_path(file) ⇒ String
Get the old backup file path for a file
1040 1041 1042 |
# File 'lib/na/next_action.rb', line 1040 def old_backup_path(file) File.join(File.dirname(file), ".#{File.basename(file)}.bak") end |
.os_open(file, app: nil) ⇒ void
This method returns an undefined value.
Platform-agnostic open command
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 |
# File 'lib/na/next_action.rb', line 1105 def os_open(file, app: nil) os = RbConfig::CONFIG['target_os'] case os when /darwin.*/i darwin_open(file, app: app) when /mingw|mswin/i win_open(file) else linux_open(file) end end |
.output_children(children, level = 1) ⇒ Object
Output an Omnifocus-friendly action list
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 |
# File 'lib/na/next_action.rb', line 761 def output_children(children, level = 1) out = [] indent = "\t" * level return out if children.nil? || children.empty? children.each do |k, v| if k.to_s =~ /actions/ indent += "\t" v&.each do |a| item = "#{indent}- #{a.action}" unless a..nil? || a..empty? = [] a..each do |key, val| next if key =~ /^(due|flagged|done)$/ tag = key tag += "-#{val}" unless val.nil? || val.empty? .push(tag) end item += " @tags(#{.join(',')})" unless .empty? end item += "\n#{indent}\t#{a.note.join("\n#{indent}\t")}" unless a.note.empty? out.push(item) end else out.push("#{indent}#{k}:") out.concat(output_children(v, level + 1)) end end out end |
.parse_item_path(path) ⇒ Object
Parse a TaskPaper-style item path string into steps with axis and text. Returns an Array of Hashes: { axis: :child|:desc, text: String, wildcard: Boolean }.
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
# File 'lib/na/next_action.rb', line 1208 def parse_item_path(path) s = path.to_s.strip return [] unless s.start_with?('/') steps = [] i = 0 len = s.length while i < len break unless s[i] == '/' axis = :child if i + 1 < len && s[i + 1] == '/' axis = :desc i += 1 end i += 1 text = +'' quote = nil while i < len ch = s[i] if quote text << ch quote = nil if ch == quote i += 1 next end if ch == '"' || ch == "'" quote = ch text << ch i += 1 next end break if ch == '/' text << ch i += 1 end t = text.strip wildcard = t.empty? || t == '*' steps << { axis: axis, text: t, wildcard: wildcard } end steps end |
.parse_taskpaper_search(expr) ⇒ Hash
Parse a TaskPaper-style @search() expression into NA search components.
TaskPaper expressions are of the form (subset of full syntax):
@search(@tag, @tag = 1, @tag contains 1, not @tag, project = "Name", not project = "Name", plain, "text")
Supported operators (mapped from TaskPaper searches, see: guide.taskpaper.com/reference/searches/):
- boolean: and / not (or/parentheses are not yet fully supported)
- @tag, not @tag
- @tag = VALUE, @tag > VALUE, @tag < VALUE, @tag >= VALUE, @tag <= VALUE, @tag =~ VALUE
- @tag contains VALUE, beginswith VALUE, endswith VALUE, matches VALUE
- @text REL VALUE (treated as plain-text search on the line)
- project = "Name", not project = "Name"
The result can be passed directly to NA::Todo via the returned clause hashes, which include keys :tokens, :tags, :project, :include_done, and :exclude_projects.
1388 1389 1390 1391 |
# File 'lib/na/next_action.rb', line 1388 def parse_taskpaper_search(expr) clauses = parse_taskpaper_search_clauses(expr) clauses.first || { tokens: [], tags: [], project: nil, include_done: nil, exclude_projects: [] } end |
.parse_taskpaper_search_clause(clause, out) ⇒ Hash
Internal: parse a single (AND-joined) TaskPaper clause into search components.
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 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 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 1493 1494 |
# File 'lib/na/next_action.rb', line 1399 def parse_taskpaper_search_clause(clause, out) parts = clause.split(/\band\b/i).map(&:strip).reject(&:empty?) parts.each do |raw_part| part = raw_part.dup neg = false if part =~ /\Anot\s+(.+)\z/i neg = true part = Regexp.last_match(1).strip end # @tag, @tag OP VALUE, or @attribute OP VALUE if part =~ /\A@([A-Za-z0-9_\-:.]+)\s*(?:(=|==|!=|>=|<=|>|<|=~|contains(?:\[[^\]]+\])?|beginswith(?:\[[^\]]+\])?|endswith(?:\[[^\]]+\])?|matches(?:\[[^\]]+\])?)\s*(.+))?\z/i tag = Regexp.last_match(1) op = Regexp.last_match(2) val = Regexp.last_match(3)&.strip val = val[1..-2] if val && ((val.start_with?('"') && val.end_with?('"')) || (val.start_with?("'") && val.end_with?("'"))) # Handle @text as a plain-text predicate on the line if tag.casecmp('text').zero? if val token_val = val out[:tokens] << { token: token_val, required: !neg, negate: neg } end next end if tag.casecmp('done').zero? # Handle done specially via :include_done; do NOT add a tag filter, # otherwise Todo.parse would force include @done actions. out[:include_done] = !neg next end # Normalize operator: strip TaskPaper relation modifiers and map # relation names to our internal comparison codes. op = op.to_s.downcase # Strip relation modifiers like [i], [sl], [dn], etc. op = op.sub(/\[.*\]\z/, '') # Translate "!=" into a negated equality check if op == '!=' op = '=' neg = true elsif op == 'contains' op = '*=' elsif op == 'beginswith' op = '^=' elsif op == 'endswith' op = '$=' elsif op == 'matches' op = '=~' end tag_hash = { tag: tag.wildcard_to_rx, comp: op, value: val, required: !neg, negate: neg } out[:tags] << tag_hash next end # project = "Name", project != "Name" if part =~ /\Aproject\s*(=|==|!=)\s*(.+)\z/i op = Regexp.last_match(1) val = Regexp.last_match(2).strip val = val[1..-2] if (val.start_with?('"') && val.end_with?('"')) || (val.start_with?("'") && val.end_with?("'")) if neg || op == '!=' out[:exclude_projects] << val else out[:project] = val end next end # Fallback: treat as a plain text token token = part token = token[1..-2] if (token.start_with?('"') && token.end_with?('"')) || (token.start_with?("'") && token.end_with?("'")) out[:tokens] << { token: token, required: !neg, negate: neg } end out end |
.parse_taskpaper_search_clauses(expr) ⇒ Array<Hash>
Parse a TaskPaper-style @search() expression into multiple OR-joined clauses. Each clause is an AND-joined set of predicates represented as a hash compatible with NA::Todo options. Supports nested boolean expressions with parentheses using and / or. The unary not operator is handled inside individual predicates.
Also supports an optional leading item path (subset) before predicates, e.g.:
@search(/Inbox//Testing and not @done)
The leading path is exposed on each clause as :item_paths and is later resolved via resolve_item_path in run_taskpaper_search.
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 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 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 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 |
# File 'lib/na/next_action.rb', line 1509 def parse_taskpaper_search_clauses(expr) return [] if expr.nil? NA.notify("TP DEBUG expr: #{expr.inspect}", debug: true) if NA.verbose inner = expr.to_s.strip inner = Regexp.last_match(1).strip if inner =~ /\A@search\((.*)\)\s*\z/i NA.notify("TP DEBUG inner after @search strip: #{inner.inspect}", debug: true) if NA.verbose return [] if inner.empty? # Extract optional leading item path (must start with '/'). The remaining # content is treated as the boolean expression for predicates. We allow # spaces inside the path and stop at the first unquoted AND/OR keyword. item_path = nil if inner.start_with?('/') i = 0 quote = nil sep_index = nil sep_len = nil while i < inner.length ch = inner[i] if quote quote = nil if ch == quote i += 1 next end if ch == '"' || ch == "'" quote = ch i += 1 next end # Look for unquoted AND/OR separators rest = inner[i..] if rest =~ /\A\s+and\b/i sep_index = i sep_len = rest.match(/\A\s+and\b/i)[0].length break elsif rest =~ /\A\s+or\b/i sep_index = i sep_len = rest.match(/\A\s+or\b/i)[0].length break end i += 1 end if sep_index item_path = inner[0...sep_index].strip inner = inner[(sep_index + sep_len)..].to_s.strip else item_path = inner.strip inner = '' end end NA.notify("TP DEBUG item_path: #{item_path.inspect} inner now: #{inner.inspect}", debug: true) if NA.verbose # Extract optional trailing slice, e.g.: # [index], [start:end], [start:], [:end], [:] # from the entire inner expression (including parenthesized forms like # (expr)[0]). slice = nil if inner =~ /\A(.+)\[(\d*:?(\d*)?)\]\s*\z/m expr_part = Regexp.last_match(1).strip slice_str = Regexp.last_match(2) if slice_str.include?(':') start_str, end_str = slice_str.split(':', 2) slice = { start: (start_str.nil? || start_str.empty? ? nil : start_str.to_i), end: (end_str.nil? || end_str.empty? ? nil : end_str.to_i) } else slice = { index: slice_str.to_i } end inner = expr_part end NA.notify("TP DEBUG slice: #{slice.inspect} inner after slice: #{inner.inspect}", debug: true) if NA.verbose # If the entire expression is wrapped in a single pair of parentheses, # strip them so shortcuts like `project Inbox and @na` can be recognized. if inner.start_with?('(') && inner.end_with?(')') depth = 0 balanced = true inner.chars.each_with_index do |ch, idx| depth += 1 if ch == '(' depth -= 1 if ch == ')' if depth.zero? && idx < inner.length - 1 balanced = false break end end inner = inner[1..-2].strip if balanced end # Expand TaskPaper type shortcuts at the start of the predicate expression: # project NAME -> project = "NAME" # task NAME -> NAME (we only search tasks anyway) # note NAME -> NAME (approximate) if inner =~ /\A(project|task|note)\s+(.+)\z/i kind = Regexp.last_match(1).downcase rest = Regexp.last_match(2).strip case kind when 'project' # If this is just `project NAME`, treat it as a project constraint. # If it contains additional boolean logic (and/or), drop the # `project NAME` prefix and leave the rest of the expression # unchanged for normal predicate parsing. if rest =~ /\b(and|or)\b/i # Drop leading "NAME and" and keep the remainder, e.g. # "Inbox and @na and not @done" -> "@na and not @done" # then strip the leading "and" to leave "@na and not @done". inner = if rest =~ /\A(\S+)\s+and\s+(.+)\z/mi Regexp.last_match(2).strip else rest end else name = rest # Strip surrounding quotes if present name = name[1..-2] if (name.start_with?('"') && name.end_with?('"')) || (name.start_with?("'") && name.end_with?("'")) inner = %(project = "#{name}") end when 'task', 'note' # For now, treat as a plain text search on the rest inner = rest end end NA.notify("TP DEBUG inner before tokenizing: #{inner.inspect}", debug: true) if NA.verbose # Tokenize expression into TEXT, AND, OR, '(', ')', preserving quoted # strings and leaving `not` to be handled inside predicates. tokens = [] current = +'' quote = nil i = 0 boundary = lambda do |str, idx, len| before = idx.positive? ? str[idx - 1] : nil after = (idx + len) < str.length ? str[idx + len] : nil before_ok = before.nil? || before =~ /\s|\(/ after_ok = after.nil? || after =~ /\s|\)/ before_ok && after_ok end while i < inner.length ch = inner[i] if quote current << ch quote = nil if ch == quote i += 1 next end if ch == '"' || ch == "'" quote = ch current << ch i += 1 next end if ch == '(' || ch == ')' tokens << [:TEXT, current] unless current.strip.empty? current = +'' tokens << [ch, ch] i += 1 next end if ch =~ /\s/ unless current.strip.empty? tokens << [:TEXT, current] current = +'' end i += 1 next end rest = inner[i..] if rest.downcase.start_with?('and') && boundary.call(inner, i, 3) tokens << [:TEXT, current] unless current.strip.empty? current = +'' tokens << [:AND, 'and'] i += 3 next elsif rest.downcase.start_with?('or') && boundary.call(inner, i, 2) tokens << [:TEXT, current] unless current.strip.empty? current = +'' tokens << [:OR, 'or'] i += 2 next else current << ch i += 1 end end tokens << [:TEXT, current] unless current.strip.empty? # Recursive-descent parser producing DNF (array of AND-clauses) index = 0 current_token = lambda { tokens[index] } advance = lambda { index += 1 } # Declare parse_or in outer scope so it's visible inside parse_primary parse_or = nil parse_primary = lambda do tok = current_token.call return [] unless tok type, = tok if type == '(' advance.call clauses = parse_or.call advance.call if current_token.call && current_token.call[0] == ')' clauses elsif type == :TEXT parts = [] while current_token.call && current_token.call[0] == :TEXT parts << current_token.call[1].strip advance.call end pred = parts.join(' ').strip return [] if pred.empty? [parse_taskpaper_search_clause(pred, { tokens: [], tags: [], project: nil, include_done: nil, exclude_projects: [], item_paths: [], slice: slice })] else advance.call [] end end parse_and = lambda do clauses = parse_primary.call while current_token.call && current_token.call[0] == :AND advance.call right = parse_primary.call combined = [] clauses.each do |left_clause| right.each do |right_clause| combined << { tokens: left_clause[:tokens] + right_clause[:tokens], tags: left_clause[:tags] + right_clause[:tags], project: right_clause[:project] || left_clause[:project], include_done: right_clause[:include_done].nil? ? left_clause[:include_done] : right_clause[:include_done], exclude_projects: left_clause[:exclude_projects] + right_clause[:exclude_projects], item_paths: Array(left_clause[:item_paths]) + Array(right_clause[:item_paths]), slice: right_clause[:slice] || left_clause[:slice] } end end clauses = combined end clauses end parse_or = lambda do clauses = parse_and.call while current_token.call && current_token.call[0] == :OR advance.call right = parse_and.call clauses.concat(right) end clauses end clauses = parse_or.call # If there was only an item path and no predicates, create a single # empty clause to carry the path. if clauses.empty? && item_path clauses = [{ tokens: [], tags: [], project: nil, include_done: nil, exclude_projects: [], item_paths: [], slice: slice }] end # Attach leading item path (if any) to all clauses if item_path clauses.each do |clause| clause[:item_paths] ||= [] clause[:item_paths] << item_path end end clauses end |
.priority_map ⇒ Hash{String=>Integer}
Returns a map of priority levels to numeric values.
126 127 128 129 130 131 132 |
# File 'lib/na/next_action.rb', line 126 def priority_map { 'h' => 5, 'm' => 3, 'l' => 1 } end |
.project_hierarchy(actions) ⇒ Hash
Build a nested hash representing project hierarchy from actions
741 742 743 744 745 746 747 748 749 750 751 752 753 754 |
# File 'lib/na/next_action.rb', line 741 def project_hierarchy(actions) parents = { actions: [] } actions.each do |a| parent = a.parent current_parent = parents parent.each do |par| current_parent[par] = { actions: [] } unless current_parent.key?(par) current_parent = current_parent[par] end current_parent[:actions].push(a) end parents end |
.request_input(options, prompt: 'Enter text') ⇒ Object
Request terminal input from user, readline style
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 |
# File 'lib/na/next_action.rb', line 2087 def request_input(, prompt: 'Enter text') if $stdin.isatty && TTY::Which.exist?('gum') && ([:tagged].nil? || [:tagged].empty?) opts = [%(--placeholder "#{prompt}"), '--char-limit=500', "--width=#{TTY::Screen.columns}"] `gum input #{opts.join(' ')}`.strip elsif $stdin.isatty && [:tagged].empty? NA.notify("#{NA.theme[:prompt]}#{prompt}:") reader.read_line(NA::Color.template("#{NA.theme[:filename]}> #{NA.theme[:action]}")).strip end end |
.resolve_item_path(path:, file: nil, depth: 1) ⇒ Array<String>
Resolve a TaskPaper-style item path (subset) into NA project paths.
Supported subset:
- Child axis: /Project/Sub
- Descendant axis: //Sub (e.g. /Inbox//Bugs)
- Wildcard step: * (matches any project name in that position)
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 |
# File 'lib/na/next_action.rb', line 1176 def resolve_item_path(path:, file: nil, depth: 1) return [] if path.nil? steps = parse_item_path(path) return [] if steps.empty? files = if file [File.(file)] else find_files(depth: depth) end return [] if files.nil? || files.empty? matches = [] files.each do |f| todo = NA::Todo.new(require_na: false, file_path: f) projects = todo.projects next if projects.empty? current = resolve_path_in_projects(projects, steps) current.each do |proj| matches << proj.project end end matches.uniq end |
.resolve_path_in_projects(projects, steps) ⇒ Array<NA::Project>
Resolve a parsed item path against a list of NA::Project objects from a single file.
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 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 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
# File 'lib/na/next_action.rb', line 1265 def resolve_path_in_projects(projects, steps) return [] if steps.empty? || projects.empty? # First step: from a virtual root; child axis means top-level projects # (no ':' in path), descendant axis means any project in the file. first = steps.first current = [] projects.each do |proj| case first[:axis] when :child next unless proj.project.split(':').length == 1 when :desc # any project is a descendant of the virtual root end current << proj if item_path_step_match?(first, proj) end steps[1..].each do |step| next_current = [] current.each do |parent| parent_path = parent.project parent_depth = parent_path.split(':').length projects.each do |proj| next if proj.equal?(parent) case step[:axis] when :child next unless proj.project.start_with?("#{parent_path}:") next unless proj.project.split(':').length == parent_depth + 1 when :desc next unless proj.project.start_with?("#{parent_path}:") end next unless item_path_step_match?(step, proj) next_current << proj pp next_current.inspect end end current = next_current.uniq break if current.empty? end current end |
.restore_last_modified_file(search: nil) ⇒ void
This method returns an undefined value.
Get last modified file and restore a backup
1001 1002 1003 1004 1005 1006 1007 1008 |
# File 'lib/na/next_action.rb', line 1001 def restore_last_modified_file(search: nil) file = last_modified_file(search: search) if file restore_modified_file(file) else NA.notify("#{NA.theme[:error]}No matching file found") end end |
.restore_modified_file(file) ⇒ void
This method returns an undefined value.
Restore a file from backup
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 |
# File 'lib/na/next_action.rb', line 1077 def restore_modified_file(file) bak_file = backup_path(file) if File.exist?(bak_file) FileUtils.mv(bak_file, file) NA.notify("#{NA.theme[:success]}Backup restored for #{file.highlight_filename}") else NA.notify("#{NA.theme[:error]}Backup file for #{file.highlight_filename} not found") end weed_modified_files(file) end |
.run_taskpaper_search(expr, file: nil, options: {}) ⇒ void
This method returns an undefined value.
Execute a TaskPaper-style @search() expression using NA::Todo and output results with the standard formatting options.
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 |
# File 'lib/na/next_action.rb', line 1976 def run_taskpaper_search(expr, file: nil, options: {}) actions, files, clauses = evaluate_taskpaper_search(expr, file: file, options: ) depth = [:depth] || 1 # Build regexes for highlighting from all positive tokens across clauses regexes = [] clauses.each do |parsed| sts = parsed[:tokens] if sts.is_a?(Array) regexes.concat(sts.delete_if { |token| token[:negate] }.map { |token| token[:token].wildcard_to_rx }) elsif sts regexes << sts end end regexes.uniq! actions.output(depth, { files: files, regexes: regexes, notes: .fetch(:notes, false), nest: .fetch(:nest, false), nest_projects: .fetch(:omnifocus, false), no_files: .fetch(:no_file, false), times: .fetch(:times, false), human: .fetch(:human, false) }) end |
.save_modified_file(file) ⇒ void
This method returns an undefined value.
Save a backed-up file to the database
974 975 976 977 978 979 980 981 982 983 984 985 |
# File 'lib/na/next_action.rb', line 974 def save_modified_file(file) db = database_path(file: 'last_modified.txt') file = File.(file) if File.exist? db files = File.read(db).split("\n").map(&:strip) files.delete(file) files << file File.open(db, 'w') { |f| f.puts(files.join("\n")) } else File.open(db, 'w') { |f| f.puts(file) } end end |
.save_search(title, search) ⇒ void
This method returns an undefined value.
Save a search definition to the database.
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 |
# File 'lib/na/next_action.rb', line 1352 def save_search(title, search) file = database_path(file: 'saved_searches.yml') searches = load_searches title = title.gsub(/[^a-zA-Z0-9]/, '_').gsub(/_+/, '_').downcase if searches.key?(title) res = yn('Overwrite existing definition?', default: true) notify("#{NA.theme[:error]}Cancelled", exit_code: 0) unless res end searches[title] = search File.open(file, 'w') { |f| f.puts(YAML.dump(searches)) } NA.notify("#{NA.theme[:success]}Search #{NA.theme[:filename]}#{title}#{NA.theme[:success]} saved", exit_code: 0) end |
.save_working_dir(todo_file) ⇒ void
This method returns an undefined value.
Save a todo file path to the database
959 960 961 962 963 964 965 966 967 968 |
# File 'lib/na/next_action.rb', line 959 def save_working_dir(todo_file) NA::Benchmark.measure('save_working_dir') do file = database_path content = File.exist?(file) ? file.read_file : '' dirs = content.split("\n") dirs.push(File.(todo_file)) dirs.sort!.uniq! File.open(file, 'w') { |f| f.puts dirs.join("\n") } end end |
.select_actions(file: nil, depth: 1, search: [], tagged: [], include_done: false) ⇒ Array<NA::Action>
Select actions across files using existing search pipeline
11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/na/next_action.rb', line 11 def select_actions(file: nil, depth: 1, search: [], tagged: [], include_done: false) files = if file [file] else find_files(depth: depth) end out = [] files.each do |f| _projects, actions = find_actions(f, search, tagged, done: include_done, all: true) out.concat(actions) if actions end out end |
.select_file(files, multiple: false) ⇒ String+
Select from multiple files
If gum or fzf are available, they’ll be used (in that order).
219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/na/next_action.rb', line 219 def select_file(files, multiple: false) res = choose_from(files, prompt: multiple ? 'Select files' : 'Select a file', multiple: multiple) if res.nil? || res == false || (res.respond_to?(:length) && res.empty?) notify("#{NA.theme[:error]}No file selected, cancelled", exit_code: 1) return nil end if multiple res else res.is_a?(Array) ? res.first : res end end |
.shift_index_after(projects, idx, length = 1) ⇒ Array<NA::Project>
Shift project indices after a given index by a length.
237 238 239 240 241 242 243 244 |
# File 'lib/na/next_action.rb', line 237 def shift_index_after(projects, idx, length = 1) projects.map do |proj| proj.line = proj.line - length if proj.line > idx proj.last_line = proj.last_line - length if proj.last_line > idx proj end end |
.theme ⇒ Hash
Returns the current theme hash for color and style settings.
104 105 106 |
# File 'lib/na/next_action.rb', line 104 def theme @theme ||= NA::Theme.load_theme end |
.update_action(target, search, search_note: true, add: nil, add_tag: [], all: false, append: false, delete: false, done: false, edit: false, finish: false, note: [], overwrite: false, priority: 0, project: nil, move: nil, remove_tag: [], replace: nil, tagged: nil, started_at: nil, done_at: nil, duration_seconds: nil, suppress_prompt: false) ⇒ void
This method returns an undefined value.
Update actions in a todo file (add, edit, delete, move, etc.)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 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 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 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 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 |
# File 'lib/na/next_action.rb', line 406 def update_action(target, search, search_note: true, add: nil, add_tag: [], all: false, append: false, delete: false, done: false, edit: false, finish: false, note: [], overwrite: false, priority: 0, project: nil, move: nil, remove_tag: [], replace: nil, tagged: nil, started_at: nil, done_at: nil, duration_seconds: nil, suppress_prompt: false) # Coerce date/time inputs if passed as strings begin started_at = NA::Types.parse_date_begin(started_at) if started_at && !started_at.is_a?(Time) rescue StandardError # leave as-is end begin done_at = NA::Types.parse_date_end(done_at) if done_at && !done_at.is_a?(Time) rescue StandardError # leave as-is end NA.notify("UPDATE parsed started_at=#{started_at.inspect} done_at=#{done_at.inspect} duration=#{duration_seconds.inspect}", debug: true) # Expand target to absolute path to avoid path resolution issues target = File.(target) unless Pathname.new(target).absolute? projects = find_projects(target) affected_actions = [] target_proj = nil if move move = move.sub(/:$/, '') target_proj = projects.select { |pr| pr.project =~ /#{move.gsub(':', '.*?:.*?')}/i }.first if target_proj.nil? if suppress_prompt || !$stdout.isatty target_proj = insert_project(target, move) projects << target_proj else res = NA.yn( NA::Color.template("#{NA.theme[:warning]}Project #{NA.theme[:file]}#{move}#{NA.theme[:warning]} doesn't exist, add it"), default: true ) if res target_proj = insert_project(target, move) projects << target_proj else NA.notify("#{NA.theme[:error]}Cancelled", exit_code: 1) end end end end contents = target.read_file.split("\n") if add.is_a?(Action) # NOTE: Edit is handled in the update command before calling update_action # So we don't need to handle it here - the action is already edited add_tag ||= [] NA.notify("PROCESS before add.process started_at=#{started_at.inspect} done_at=#{done_at.inspect}", debug: true) add.process(priority: priority, finish: finish, add_tag: add_tag, remove_tag: remove_tag, started_at: started_at, done_at: done_at, duration_seconds: duration_seconds) NA.notify("PROCESS after add.process action=\"#{add.action}\"", debug: true) # Remove the original action and its notes if this is an existing action action_line = add.file_line note_lines = add.note.is_a?(Array) ? add.note.count : 0 contents.slice!(action_line, note_lines + 1) if action_line.is_a?(Integer) # Prepare updated note note = note.to_s.split("\n") unless note.is_a?(Array) updated_note = if note.empty? add.note else overwrite ? note : add.note.concat(note) end # Prepare indentation projects = find_projects(target) # If move is set, update add.parent to the target project add.parent = target_proj.project.split(':') if move && target_proj project_path = add.parent.join(':') target_proj ||= projects.select { |proj| proj.project =~ /^#{Regexp.escape(project_path)}$/i }.first if target_proj.nil? && !project_path.empty? && !project_path.include?(':') # Fallback: if a bare leaf name was provided and it uniquely matches # the final segment of an existing nested project, use that project candidates = projects.select do |proj| leaf = proj.project.to_s.split(':').last leaf&.casecmp?(project_path) end target_proj = candidates.first if candidates.size == 1 end if target_proj.nil? && !project_path.empty? display_path = project_path.tr(':', '/') prompt = NA::Color.template( "#{NA.theme[:warning]}Project #{NA.theme[:file]}#{display_path}#{NA.theme[:warning]} doesn't exist, create it?" ) should_create = NA.yn(prompt, default: true) NA.notify("#{NA.theme[:error]}Cancelled", exit_code: 1) unless should_create created_proj = insert_project(target, project_path) contents = target.read_file.split("\n") projects = find_projects(target) target_proj = projects.select { |proj| proj.project =~ /^#{Regexp.escape(project_path)}$/i }.first || created_proj end add.parent = target_proj.project.split(':') if target_proj indent = target_proj ? ("\t" * target_proj.indent) : '' # Format note for insertion note_str = updated_note.empty? ? '' : "\n#{indent}\t\t#{updated_note.join("\n#{indent}\t\t").strip}" # If delete was requested in this direct update path, do not re-insert if delete affected_actions << { action: add, desc: 'deleted' } else # Insert at correct location if target_proj insert_line = if append # End of project target_proj.last_line + 1 else # Start of project (after project header) target_proj.line + 1 end # Ensure @started tag persists if provided final_action = add.action.dup if started_at && final_action !~ /(?<=\A| )@start(?:ed)?\(/i final_action = final_action.gsub(/(?<=\A| )@start(?:ed)?\(.*?\)/i, '').strip final_action = "#{final_action} @started(#{started_at.strftime('%Y-%m-%d %H:%M')})" end NA.notify("INSERT at #{insert_line} final_action=\"#{final_action}\"", debug: true) contents.insert(insert_line, "#{indent}\t- #{final_action}#{note_str}") else # Fallback: append to end of file final_action = add.action.dup if started_at && final_action !~ /(?<=\A| )@start(?:ed)?\(/i final_action = final_action.gsub(/(?<=\A| )@start(?:ed)?\(.*?\)/i, '').strip final_action = "#{final_action} @started(#{started_at.strftime('%Y-%m-%d %H:%M')})" end NA.notify("APPEND final_action=\"#{final_action}\"", debug: true) contents << "#{indent}\t- #{final_action}#{note_str}" end notify(add.pretty) end # Track affected action and description unless delete changes = ['updated'] changes << 'finished' if finish changes << "priority=#{priority}" if priority.to_i.positive? changes << "tags+#{add_tag.join(',')}" unless add_tag.nil? || add_tag.empty? changes << "tags-#{remove_tag.join(',')}" unless remove_tag.nil? || remove_tag.empty? changes << 'note updated' unless note.nil? || note.empty? changes << "moved to #{target_proj.project}" if move && target_proj affected_actions << { action: add, desc: changes.join(', ') } end else # Check if search is actually target_line target_line = search.is_a?(Hash) && search[:target_line] ? search[:target_line] : nil _, actions = find_actions(target, search, tagged, done: done, all: all, project: project, search_note: search_note, target_line: target_line) return if actions.nil? # Handle edit (single or multi-action) if edit editor_content = Editor.format_multi_action_input(actions) edited_content = Editor.fork_editor(editor_content) edited_actions = Editor.parse_multi_action_output(edited_content) # Map edited content back to actions actions.each do |action| # Use file_path:file_line as the key key = "#{action.file_path}:#{action.file_line}" action.action, action.note = edited_actions[key] if edited_actions[key] end end actions.sort_by(&:file_line).reverse.each do |action| contents.slice!(action.file_line, action.note.count + 1) if delete # Track deletion before skipping re-insert affected_actions << { action: action, desc: 'deleted' } next end projects = shift_index_after(projects, action.file_line, action.note.count + 1) # If replace is defined, use search to search and replace text in action action.action.sub!(Regexp.new(Regexp.escape(search), Regexp::IGNORECASE), replace) if replace action.process(priority: priority, finish: finish, add_tag: add_tag, remove_tag: remove_tag, started_at: started_at, done_at: done_at, duration_seconds: duration_seconds) target_proj = if target_proj projects.select { |proj| proj.project =~ /^#{target_proj.project}$/ }.first else projects.select { |proj| proj.project =~ /^#{action.parent.join(':')}$/ }.first end indent = "\t" * target_proj.indent note = note.split("\n") unless note.is_a?(Array) note = if note.empty? action.note else overwrite ? note : action.note.concat(note) end note = note.empty? ? '' : "\n#{indent}\t\t#{note.join("\n#{indent}\t\t").strip}" if append this_idx = 0 projects.each_with_index do |proj, idx| if proj.line == target_proj.line this_idx = idx break end end target_line = if this_idx == projects.length - 1 contents.count else projects[this_idx].last_line + 1 end else target_line = target_proj.line + 1 end contents.insert(target_line, "#{indent}\t- #{action.action}#{note}") notify(action.pretty) # Track affected action and description changes = [] changes << 'finished' if finish changes << 'edited' if edit changes << "priority=#{priority}" if priority.to_i.positive? changes << "tags+#{add_tag.join(',')}" unless add_tag.nil? || add_tag.empty? changes << "tags-#{remove_tag.join(',')}" unless remove_tag.nil? || remove_tag.empty? changes << 'text replaced' if replace changes << "moved to #{target_proj.project}" if target_proj changes << 'note updated' unless note.nil? || note.empty? changes = ['updated'] if changes.empty? affected_actions << { action: action, desc: changes.join(', ') } end end backup_file(target) File.open(target, 'w') { |f| f.puts contents.join("\n") } if affected_actions.any? if affected_actions.all? { |e| e[:desc] =~ /^deleted/ } notify("#{NA.theme[:success]}Task deleted in #{NA.theme[:filename]}#{target}") elsif add notify("#{NA.theme[:success]}Task added to #{NA.theme[:filename]}#{target}") else notify("#{NA.theme[:success]}Task updated in #{NA.theme[:filename]}#{target}") end affected_actions.reverse.each do |entry| action_color = delete ? NA.theme[:error] : NA.theme[:success] notify(" #{entry[:action].to_s_pretty} — #{action_color}#{entry[:desc]}") end elsif add notify("#{NA.theme[:success]}Task added to #{NA.theme[:filename]}#{target}") else notify("#{NA.theme[:success]}Task updated in #{NA.theme[:filename]}#{target}") end end |
.weed_cache_file ⇒ Object
Remove entries from cache database that no longer exist
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 |
# File 'lib/na/next_action.rb', line 1120 def weed_cache_file db_dir = File.('~/.local/share/na') db_file = 'tdlist.txt' file = File.join(db_dir, db_file) return unless File.exist?(file) dirs = file.read_file.split("\n") dirs.delete_if { |f| !File.exist?(f) } File.open(file, 'w') { |f| f.puts dirs.join("\n") } end |
.weed_modified_files(file = nil) ⇒ void
This method returns an undefined value.
Remove entries for missing backup files from the database
1063 1064 1065 1066 1067 1068 1069 1070 1071 |
# File 'lib/na/next_action.rb', line 1063 def weed_modified_files(file = nil) files = backup_files files.delete_if { |f| f =~ /#{file}/ } if file files.delete_if { |f| !File.exist?(backup_path(f)) } File.open(database_path(file: 'last_modified.txt'), 'w') { |f| f.puts files.join("\n") } end |
.yn(prompt, default: true) ⇒ Boolean
Display and read a Yes/No prompt
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/na/next_action.rb', line 144 def yn(prompt, default: true) return default if ENV['NA_TEST'] == '1' return default unless $stdout.isatty tty_state = `stty -g` system 'stty raw -echo cbreak isig' yn = (default ? %w[Y n] : %w[y N]) $stdout.syswrite "\e[1;37m#{prompt} #{yn}\e[1;37m? \e[0m" res = $stdin.sysread 1 res.chomp! puts system 'stty cooked' system "stty #{tty_state}" res.empty? ? default : res =~ /y/i end |