summary refs log tree commit diff
path: root/.config/nvim/lua/mod/jobs.lua
blob: a4dea6f2ca657dd0d3f1c2567a736a8a2efc5f0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
-- this plugin provides an API to register and recall jobs.

local M = {
  _jobs = {},
}

local function format_jobcmd(cmd)
  if type(cmd) == 'table' then
    return table.concat(cmd, ' ')
  end
  return cmd
end

local function register(id, cmd)
  table.insert(M._jobs, id, cmd)
  vim.notify_once(string.format('started job %d (%s)', id, format_jobcmd(M._jobs[id])))
end

local function deregister(id)
  local cmd = M._jobs[id]
  table.insert(M._jobs, id, nil)
  vim.notify_once(string.format('stopped job %d (%s)', id, format_jobcmd(cmd)))
end

function M.start(opts)
  local previous_on_exit = opts.on_exit or function() end
  opts.on_exit = function(id, exitcode, event)
    deregister(id)
    return previous_on_exit(id, exitcode, event)
  end

  local id = vim.fn.jobstart(opts.cmd, opts)

  register(id, opts.cmd)
end

function M.select()
  if #M._jobs == 0 then
    vim.notify('No running jobs', vim.log.levels.WARN)
    return
  end

  local function provider(cb)
    for id, cmd in pairs(M._jobs) do
      cb(string.format('[%d] %s', id, format_jobcmd(cmd)))
    end
    cb(nil)
  end
  local function parse_jobid(entry)
    return tonumber(string.match(entry, '%[([0-9]*)%]'))
  end

  require('fzf-lua').fzf_exec(provider, {
    prompt = 'Jobs❯',
    actions = {
      ['ctrl-x'] = {
        fn = function(selected)
          for _, entry in pairs(selected) do
            vim.fn.jobstop(parse_jobid(entry))
          end
        end,
        reload = true,
      },
    },
  })
end

return M