|
| 1 | +local pickers = require('telescope.pickers') |
| 2 | +local finders = require('telescope.finders') |
| 3 | +local conf = require('telescope.config').values |
| 4 | +local action_set = require('telescope.actions.set') |
| 5 | +local actions = require('telescope.actions') |
| 6 | +local action_state = require('telescope.actions.state') |
| 7 | +local state = require('telescope.state') |
| 8 | + |
| 9 | +local utils = require('telescope-orgmode.utils') |
| 10 | + |
| 11 | +local api = require('orgmode.api') |
| 12 | + |
| 13 | +return function(opts) |
| 14 | + opts = opts or {} |
| 15 | + |
| 16 | + local closest_headline = api.current():get_closest_headline() |
| 17 | + |
| 18 | + local function refile(prompt_bufnr) |
| 19 | + local entry = action_state.get_selected_entry() |
| 20 | + actions.close(prompt_bufnr) |
| 21 | + |
| 22 | + -- Refile to the file by default |
| 23 | + local destination = entry.value.file |
| 24 | + |
| 25 | + -- Refile to a specific heading if is set |
| 26 | + if entry.value.headline then |
| 27 | + destination = entry.value.headline |
| 28 | + end |
| 29 | + |
| 30 | + return api.refile({ |
| 31 | + source = closest_headline, |
| 32 | + destination = destination, |
| 33 | + }) |
| 34 | + end |
| 35 | + |
| 36 | + local function gen_depth_toggle(opts, prompt_bufnr) |
| 37 | + local status = state.get_status(prompt_bufnr) |
| 38 | + status._ot_current_depth = opts.max_depth |
| 39 | + status._ot_next_depth = nil |
| 40 | + if status._ot_current_depth ~= 0 then |
| 41 | + status._ot_next_depth = 0 |
| 42 | + end |
| 43 | + |
| 44 | + return function() |
| 45 | + local current_picker = action_state.get_current_picker(prompt_bufnr) |
| 46 | + |
| 47 | + local aux = status._ot_current_depth |
| 48 | + status._ot_current_depth = status._ot_next_depth |
| 49 | + status._ot_next_depth = aux |
| 50 | + |
| 51 | + opts.max_depth = status._ot_current_depth |
| 52 | + local new_finder = finders.new_table({ |
| 53 | + results = utils.get_entries(opts), |
| 54 | + entry_maker = opts.entry_maker or utils.make_entry(opts), |
| 55 | + }) |
| 56 | + |
| 57 | + current_picker:refresh(new_finder, opts) |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + pickers |
| 62 | + .new(opts, { |
| 63 | + -- TODO: alter prompt title when depth is 0: Refile under file, Refile |
| 64 | + -- under Headline |
| 65 | + prompt_title = 'Refile Destination', |
| 66 | + finder = finders.new_table({ |
| 67 | + results = utils.get_entries(opts), |
| 68 | + entry_maker = opts.entry_maker or utils.make_entry(opts), |
| 69 | + }), |
| 70 | + sorter = conf.generic_sorter(opts), |
| 71 | + previewer = conf.grep_previewer(opts), |
| 72 | + attach_mappings = function(prompt_bufnr, map) |
| 73 | + action_set.select:replace(refile) |
| 74 | + map('i', '<c-space>', gen_depth_toggle(opts, prompt_bufnr)) |
| 75 | + return true |
| 76 | + end, |
| 77 | + }) |
| 78 | + :find() |
| 79 | +end |
0 commit comments