JafarAbdi / myconfigs

My dotfiles
0 stars 0 forks source link

Run executables improvements #11

Closed JafarAbdi closed 2 years ago

JafarAbdi commented 2 years ago

Take a look at https://github.com/mfussenegger/nvim-dap/blob/master/lua/dap/session.lua on how to use a terminal rather than copen for the executable outputs https://github.com/mfussenegger/nvim-dap/blob/master/lua/dap/session.lua#L203-L286

JafarAbdi commented 2 years ago
local api = vim.api

local terminal_buf, terminal_width, terminal_height
local function create_terminal_buf(terminal_win_cmd)
  local cur_win = api.nvim_get_current_win()
  if type(terminal_win_cmd) == "string" then
    api.nvim_command(terminal_win_cmd)
    local bufnr = api.nvim_get_current_buf()
    local win = api.nvim_get_current_win()
    api.nvim_set_current_win(cur_win)
    return bufnr, win
  else
    assert(type(terminal_win_cmd) == "function", "terminal_win_cmd must be a string or a function")
    return terminal_win_cmd()
  end
end

local cur_buf = api.nvim_get_current_buf()
if terminal_buf and api.nvim_buf_is_valid(terminal_buf) then
  api.nvim_buf_set_option(terminal_buf, "modified", false)
else
  local terminal_win
  terminal_buf, terminal_win = create_terminal_buf("belowright new")
  if terminal_win then
    vim.wo[terminal_win].number = false
    vim.wo[terminal_win].relativenumber = false
    vim.wo[terminal_win].signcolumn = "no"
  end
  api.nvim_win_set_height(terminal_win, 10)
  terminal_width = terminal_win and api.nvim_win_get_width(terminal_win) or 30
  terminal_height = terminal_win and api.nvim_win_get_height(terminal_win) or 40
  api.nvim_buf_set_name(terminal_buf, "[dap-terminal] " .. terminal_buf)
end
local ok, path = pcall(api.nvim_buf_get_option, cur_buf, "path")
if ok then
  api.nvim_buf_set_option(terminal_buf, "path", path)
end
local jobid

local chan = api.nvim_open_term(terminal_buf, {
  on_input = function(_, _, _, data)
    pcall(api.nvim_chan_send, jobid, data)
  end,
})
local opts = {
  -- env = next(body.env or {}) and body.env or vim.empty_dict(),
  -- cwd = (body.cwd and body.cwd ~= "") and body.cwd or nil,
  height = terminal_height,
  width = terminal_width,
  pty = true,
  on_stdout = function(_, data)
    api.nvim_chan_send(chan, table.concat(data, "\n"))
  end,
  on_exit = function(_, exit_code)
    api.nvim_chan_send(chan, "\r\n[Process exited " .. tostring(exit_code) .. "]")
    api.nvim_buf_set_keymap(
      terminal_buf,
      "t",
      "<CR>",
      "<cmd>bd!<CR>",
      { noremap = true, silent = true }
    )
  end,
}
jobid = vim.fn.jobstart("/home/jafar/workspaces/cpp/scratches/test.out", opts)
local focus_terminal = true
if focus_terminal then
  for _, win in pairs(api.nvim_tabpage_list_wins(0)) do
    if api.nvim_win_get_buf(win) == terminal_buf then
      api.nvim_set_current_win(win)
      break
    end
  end
end
if jobid == 0 or jobid == -1 then
  vim.notify("Could not spawn terminal", jobid)
else
  vim.notify("Hola")
end