summary refs log tree commit diff
path: root/.config/nvim/lua/mod/termopen.lua
blob: f8117f1bc6f607b84666099b8b4a92d85da6bc98 (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
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
100
101
102
-- this plugin provides a popup terminal.
local jobs = require('mod.jobs')

local M = {}

function M.termopen(opts)
  opts = opts or {}

  -- setup the buffer
  local buf = vim.api.nvim_create_buf(false, true)
  vim.api.nvim_set_option_value('bufhidden', 'wipe', { buf = buf })
  vim.api.nvim_set_option_value('modifiable', false, { buf = buf })

  -- setup keymappings
  vim.keymap.set('n', 'q', '<cmd>close<cr>', { buffer = buf })
  vim.keymap.set('n', '<esc>', '<cmd>close<cr>', { buffer = buf })

  -- setup the window
  -- local w = math.ceil(vim.o.columns * 1.0)
  -- local h = math.ceil(vim.o.lines * 0.4)
  local win = vim.api.nvim_open_win(buf, true, {
    -- style = 'minimal',
    -- relative = 'editor',
    -- width = w,
    -- height = h,
    -- row = math.ceil(vim.o.lines - h),
    -- col = vim.o.columns,
    -- border = { ' ', '─', ' ', ' ', ' ', '─', ' ', ' ' },
    split = 'below',
    win = -1,
  })
  vim.api.nvim_set_current_win(win)

  -- spawn the command
  if #opts.cmd == 0 then
    opts.cmd = { vim.env.SHELL }
  end

  -- vim.notify('termopen: running ' .. vim.inspect(opts.cmd), vim.log.levels.DEBUG)

  jobs.start(vim.tbl_deep_extend('error', opts, {
    term = true,
    env = {
      -- we need this to avoid opening in the term buffer
      NVR_PRE_CMD = 'close',
    },
    on_exit = function()
      -- if vim.api.nvim_win_is_valid(win) then
      --   vim.api.nvim_win_close(win, true)
      -- end
    end,
  }))

  -- put into insert mode
  vim.cmd.startinsert()
end

-- wrappers convenience

function M.term(a)
  local cwd = nil
  local args = a.fargs

  if #args > 0 then
    if args[1]:sub(0, 4) == 'cwd=' then
      cwd = args[1]:sub(5)
      args = vim.list_slice(args, 2)
    end
  end

  for i = 0, #args do
    if args[i] == '%' then
      args[i] = vim.fn.expand(args[i])
    end
  end

  M.termopen({ cmd = args, cwd = cwd })
end

function M.make(a)
  if vim.opt_local.makeprg == nil then
    vim.ui.input({ prompt = 'Enter makeprg: ' }, function(input)
      vim.opt_local.makeprg = input
    end)
  end

  local makeprg = vim.opt_local.makeprg:get()
  if string.match(makeprg, [[%$%*]]) == nil then
    makeprg = makeprg .. ' ' .. a.args
  end

  local cmd = vim.split(makeprg, ' ')
  cmd = vim.tbl_map(function(p)
    p, _ = string.gsub(p, [[%$%*]], a.args)
    p, _ = vim.fn.expand(p)
    return p
  end, cmd)

  M.termopen({ cmd = cmd })
end

return M