akinsho / toggleterm.nvim

A neovim lua plugin to help easily manage multiple terminal windows
GNU General Public License v3.0
4.21k stars 170 forks source link

[Feature Request] Next/Previous Terminal #525

Open Rizhiy opened 8 months ago

Rizhiy commented 8 months ago

I like to have multiple terminals active at once, but only one visible at a time. Switching between them is much easier if I can just go to previous/next terminal rather than opening them by their number.

Would be great to have dedicated Next/Prev Terminal action/function which is also accessible when a terminal is opened.

MonstrousOgre commented 7 months ago

I would love this as well. It's how I was using floaterm, but toggleterm seems to offer much more than floaterm.

jemag commented 4 months ago

I currently get around this with the following code:

local function get_term_index(current_id, terms)
  local idx
  for i, v in ipairs(terms) do
    if v.id == current_id then
      idx = i
    end
  end
  return idx
end

local function go_prev_term()
  local current_id = vim.b.toggle_number
  if current_id == nil then
    return
  end

  local terms = require("toggleterm.terminal").get_all(true)
  local prev_index

  local index = get_term_index(current_id, terms)
  if index > 1 then
    prev_index = index - 1
  else
    prev_index = #terms
  end
  require("toggleterm").toggle(terms[index].id)
  require("toggleterm").toggle(terms[prev_index].id)
end

local function go_next_term()
  local current_id = vim.b.toggle_number
  if current_id == nil then
    return
  end

  local terms = require("toggleterm.terminal").get_all(true)
  local next_index

  local index = get_term_index(current_id, terms)
  if index == #terms then
    next_index = 1
  else
    next_index = index + 1
  end
  require("toggleterm").toggle(terms[index].id)
  require("toggleterm").toggle(terms[next_index].id)
end

vim.keymap.set({ "n", "t" }, "<F9>", "<cmd>ToggleTerm<cr>", { desc = "Toggle term" })
vim.keymap.set({ "n", "t" }, "<F8>", function()
  go_next_term()
end, { desc = "Toggle term" })

vim.keymap.set({ "n", "t" }, "<F7>", function()
  go_prev_term()
end, { desc = "Toggle term" })

or see: https://github.com/jemag/dotfiles/blob/bf5de9b82679a75eb37b271f5e45b7389860a3b5/neovim/.config/nvim/lua/plugin-configs/toggleterm.lua?plain=1