|
| 1 | +local orgmode = require('orgmode.api') |
| 2 | + |
| 3 | +local pickers = require("telescope.pickers") |
| 4 | +local finders = require("telescope.finders") |
| 5 | +local conf = require("telescope.config").values |
| 6 | + |
| 7 | +local function get_entries(opts) |
| 8 | + |
| 9 | + local file_results = vim.tbl_map(function(file) |
| 10 | + return { file = file, filename = file.filename } |
| 11 | + end, orgmode.load()) |
| 12 | + |
| 13 | + if not opts.archived then |
| 14 | + file_results = vim.tbl_filter(function(entry) |
| 15 | + return not entry.file.is_archive_file |
| 16 | + end, file_results) |
| 17 | + end |
| 18 | + |
| 19 | + if opts.max_depth == 0 then |
| 20 | + return file_results |
| 21 | + end |
| 22 | + |
| 23 | + local results = {} |
| 24 | + for _, file_entry in ipairs(file_results) do |
| 25 | + local agenda_file = orgmode.load(file_entry.filename) |
| 26 | + for _, headline in ipairs(agenda_file.headlines) do |
| 27 | + |
| 28 | + local allowed_depth = opts.max_depth == nil or headline._section.level <= opts.max_depth |
| 29 | + local allowed_archive = opts.archived or not headline._section:is_archived() |
| 30 | + if allowed_depth and allowed_archive then |
| 31 | + local entry = { |
| 32 | + file = file_entry.file, |
| 33 | + filename = file_entry.filename, |
| 34 | + headline = headline |
| 35 | + } |
| 36 | + |
| 37 | + assert(headline.position.start_line == headline._section.line_number) |
| 38 | + table.insert(results, entry) |
| 39 | + end |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + return results |
| 44 | +end |
| 45 | + |
| 46 | +local function search_headings(opts) |
| 47 | + opts = opts or {} |
| 48 | + |
| 49 | + pickers.new(opts, { |
| 50 | + prompt_title = "Search Headings", |
| 51 | + finder = finders.new_table { |
| 52 | + results = get_entries(opts), |
| 53 | + entry_maker = opts.entry_maker or function (entry) |
| 54 | + |
| 55 | + local headline = entry.headline |
| 56 | + |
| 57 | + local display = entry.filename |
| 58 | + local lnum = nil |
| 59 | + |
| 60 | + if headline then |
| 61 | + lnum = headline.position.start_line |
| 62 | + |
| 63 | + local text = string.format('%s %s', string.rep('*', headline._section.level), headline.title) |
| 64 | + local line = string.format('%s:%i:%s', entry.filename, lnum, text) |
| 65 | + display = line |
| 66 | + |
| 67 | + end |
| 68 | + |
| 69 | + return { |
| 70 | + value = display, |
| 71 | + ordinal = display, |
| 72 | + display = display, |
| 73 | + filename = entry.filename, |
| 74 | + lnum = lnum |
| 75 | + } |
| 76 | + end, |
| 77 | + }, |
| 78 | + sorter = conf.generic_sorter(opts), |
| 79 | + previewer = conf.grep_previewer(opts), |
| 80 | + }):find() |
| 81 | +end |
| 82 | + |
| 83 | +return require("telescope").register_extension { |
| 84 | + exports = { |
| 85 | + search_headings = search_headings |
| 86 | + }, |
| 87 | +} |
0 commit comments