### Install toggleterm.nvim with Plugin Managers Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Instructions for installing the plugin using popular Neovim package managers like packer.nvim, lazy.nvim, and vim-plug. Each method ensures the plugin is correctly loaded and initialized. ```lua use {"akinsho/toggleterm.nvim", tag = '*', config = function() require("toggleterm").setup() end} ``` ```lua { 'akinsho/toggleterm.nvim', version = "*", config = true } ``` ```vim Plug 'akinsho/toggleterm.nvim', {'tag' : '*'} lua require("toggleterm").setup() ``` -------------------------------- ### ToggleTerm Setup API Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Configuration options for the toggleterm.nvim plugin. ```APIDOC ## setup() ### Description Configures the toggleterm.nvim plugin with various options. ### Method `require("toggleterm").setup(options) ### Parameters #### Request Body - **size** (number | function) - Optional - The size of the terminal window. Can be a fixed number or a function that calculates size based on direction. - **open_mapping** (string | table) - Optional - Key mapping to open/close terminals. - **on_create** (fun(t: Terminal)) - Optional - Callback function executed when a terminal is created. - **on_open** (fun(t: Terminal)) - Optional - Callback function executed when a terminal is opened. - **on_close** (fun(t: Terminal)) - Optional - Callback function executed when a terminal is closed. - **on_stdout** (fun(t: Terminal, job: number, data: string[], name: string)) - Optional - Callback for processing stdout data. - **on_stderr** (fun(t: Terminal, job: number, data: string[], name: string)) - Optional - Callback for processing stderr data. - **on_exit** (fun(t: Terminal, job: number, exit_code: number, name: string)) - Optional - Callback executed when the terminal process exits. - **hide_numbers** (boolean) - Optional - Whether to hide the number column in terminal buffers. - **shade_filetypes** (table) - Optional - Filetypes to apply shading to. - **autochdir** (boolean) - Optional - Automatically change terminal directory when Neovim's current directory changes. - **highlights** (table) - Optional - Custom highlight groups for terminal windows. - **shade_terminals** (boolean) - Optional - Whether to shade terminals (takes priority over `highlights`). - **shading_factor** (string) - Optional - Percentage to lighten dark terminal backgrounds. - **shading_ratio** (string) - Optional - Ratio of shading factor for light/dark terminal backgrounds. - **start_in_insert** (boolean) - Optional - Whether to start in insert mode. - **insert_mappings** (boolean) - Optional - Whether open mapping applies in insert mode. - **terminal_mappings** (boolean) - Optional - Whether open mapping applies in opened terminals. - **persist_size** (boolean) - Optional - Persist terminal window size. - **persist_mode** (boolean) - Optional - Persist terminal mode. - **direction** (string) - Optional - Default direction for new terminals ('vertical', 'horizontal', 'tab', 'float'). - **close_on_exit** (boolean) - Optional - Close terminal window when process exits. - **clear_env** (boolean) - Optional - Use only environment variables from `env`. - **shell** (string | function) - Optional - The default shell to use. - **auto_scroll** (boolean) - Optional - Automatically scroll to the bottom on terminal output. - **float_opts** (table) - Optional - Options for floating terminals (border, width, height, etc.). - **winbar** (table) - Optional - Configuration for the winbar. - **responsiveness** (table) - Optional - Breakpoint for terminal stacking behavior. ### Request Example ```lua require("toggleterm").setup{ size = 20 | function(term) if term.direction == "horizontal" then return 15 elseif term.direction == "vertical" then return vim.o.columns * 0.4 end end, open_mapping = [[]], direction = 'vertical', float_opts = { border = 'double', winblend = 3 } } ``` ### Response This function does not return a value. ``` -------------------------------- ### Configure Toggleterm.nvim Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Initializes the plugin with custom settings including window sizing, key mappings, and lifecycle event callbacks. This setup function is required to enable the plugin's features. ```lua require("toggleterm").setup({ size = function(term) if term.direction == "horizontal" then return 15 elseif term.direction == "vertical" then return vim.o.columns * 0.4 end end, open_mapping = [[]], hide_numbers = true, shade_terminals = true, shading_factor = -30, start_in_insert = true, insert_mappings = true, terminal_mappings = true, persist_size = true, persist_mode = true, direction = "horizontal", close_on_exit = true, shell = vim.o.shell, auto_scroll = true, float_opts = { border = "curved", width = 80, height = 20, winblend = 3, }, winbar = { enabled = true, name_formatter = function(term) return term.name end, }, on_create = function(term) print("Terminal " .. term.id .. " created") end, on_open = function(term) vim.cmd("startinsert!") end, on_close = function(term) print("Terminal closed") end, on_exit = function(term, job, exit_code, name) print("Process exited with code: " .. exit_code) end, }) ``` -------------------------------- ### Terminal Window Mappings Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Example mappings for easier navigation in and out of terminal windows. ```APIDOC ## Terminal window mappings It can be helpful to add mappings to make moving in and out of a terminal easier once toggled, whilst still keeping it open. ```lua function _G.set_terminal_keymaps() local opts = {buffer = 0} vim.keymap.set('t', '', [[]], opts) vim.keymap.set('t', 'jk', [[]], opts) vim.keymap.set('t', '', [[wincmd h]], opts) vim.keymap.set('t', '', [[wincmd j]], opts) vim.keymap.set('t', '', [[wincmd k]], opts) vim.keymap.set('t', '', [[wincmd l]], opts) vim.keymap.set('t', '', [[]], opts) end -- if you only want these mappings for toggle term use term://*toggleterm#* instead vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()') ``` ``` -------------------------------- ### Create and Toggle Custom LazyGit Terminal Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This example demonstrates how to create a custom terminal instance for lazygit using the `Terminal` class. It includes setting the command, hiding the terminal initially, and defining a keymap to toggle its visibility. ```lua local Terminal = require('toggleterm.terminal').Terminal local lazygit = Terminal:new({ cmd = "lazygit", hidden = true }) function _lazygit_toggle() lazygit:toggle() end vim.api.nvim_set_keymap("n", "g", "lua _lazygit_toggle()", {noremap = true, silent = true}) ``` -------------------------------- ### Configure toggleterm.nvim Setup Options Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This Lua code snippet demonstrates the extensive configuration options available for the toggleterm.nvim plugin. It covers terminal sizing, key mappings, callbacks for terminal events, display settings, and floating window options. ```lua require("toggleterm").setup{ -- size can be a number or function which is passed the current terminal size = 20 | function(term) { if term.direction == "horizontal" then return 15 elseif term.direction == "vertical" then return vim.o.columns * 0.4 end end, open_mapping = [[]], -- or { [[]], [[]] } if you also use a Japanese keyboard. on_create = fun(t: Terminal), -- function to run when the terminal is first created on_open = fun(t: Terminal), -- function to run when the terminal opens on_close = fun(t: Terminal), -- function to run when the terminal closes on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits hide_numbers = true, -- hide the number column in toggleterm buffers shade_filetypes = {}, autochdir = false, -- when neovim changes it current directory the terminal will change it's own when next it's opened highlights = { -- highlights which map to a highlight group name and a table of it's values -- NOTE: this is only a subset of values, any group placed here will be set for the terminal window split Normal = { guibg = "", }, NormalFloat = { link = 'Normal' }, FloatBorder = { guifg = "", guibg = "", }, }, shade_terminals = true, -- NOTE: this option takes priority over highlights specified so if you specify Normal highlights you should set this to false shading_factor = '', -- the percentage by which to lighten dark terminal background, default: -30 shading_ratio = '', -- the ratio of shading factor for light/dark terminal background, default: -3 start_in_insert = true, insert_mappings = true, -- whether or not the open mapping applies in insert mode terminal_mappings = true, -- whether or not the open mapping applies in the opened terminals persist_size = true, persist_mode = true, -- if set to true (default) the previous terminal mode will be remembered direction = 'vertical' | 'horizontal' | 'tab' | 'float', close_on_exit = true, -- close the terminal window when the process exits clear_env = false, -- use only environmental variables from `env`, passed to jobstart() -- Change the default shell. Can be a string or a function returning a string shell = vim.o.shell, auto_scroll = true, -- automatically scroll to the bottom on terminal output -- This field is only relevant if direction is set to 'float' float_opts = { -- The border key is *almost* the same as 'nvim_open_win' -- see :h nvim_open_win for details on borders however -- the 'curved' border is a custom border type -- not natively supported but implemented in this plugin. border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open -- like `size`, width, height, row, and col can be a number or function which is passed the current terminal width = , height = , row = , col = , winblend = 3, zindex = , title_pos = 'left' | 'center' | 'right', position of the title of the floating window }, winbar = { enabled = false, name_formatter = function(term) -- term: Terminal return term.name end }, responsiveness = { -- breakpoint in terms of `vim.o.columns` at which terminals will start to stack on top of each other -- instead of next to each other -- default = 0 which means the feature is turned off horizontal_breakpoint = 135, } } ``` -------------------------------- ### Execute Commands in Terminals Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Shows how to programmatically execute commands within terminals using the toggleterm API. Includes examples for both Vimscript command definitions and Lua user commands. ```lua local toggleterm = require("toggleterm") toggleterm.exec("git push", 1, 12, nil, "horizontal", "git", true, true) vim.cmd([[ command! -count=1 TermGitPush lua require'toggleterm'.exec("git push", , 12) command! -count=1 TermGitStatus lua require'toggleterm'.exec("git status", , 12) command! -count=1 TermNpmTest lua require'toggleterm'.exec("npm test", , 20, nil, "horizontal") ]]) vim.api.nvim_create_user_command("TermGitLog", function() require("toggleterm").exec("git log --oneline -20", 1, 15, nil, "horizontal", "git-log") end, {}) vim.api.nvim_create_user_command("TermMake", function(opts) local target = opts.args ~= "" and opts.args or "all" require("toggleterm").exec("make " .. target, 2, 20, nil, "horizontal", "make") end, { nargs = "?" }) ``` -------------------------------- ### ToggleTerm Command Usage Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This Vimscript example shows how to use the `:ToggleTerm` command directly. It illustrates how to specify arguments like size, directory, direction, and name to control the terminal's behavior and appearance when opened. ```vim :ToggleTerm size=40 dir=~/Desktop direction=horizontal name=desktop ``` -------------------------------- ### Statusline Integration for ToggleTerm Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt An example of how to integrate toggleterm.nvim into your Neovim statusline. It shows how to display the terminal number if the current buffer is a toggleterm buffer. ```vim " this is pseudo code let statusline .= '%{&ft == "toggleterm" ? "terminal (".b:toggle_number.")" : ""}' ``` -------------------------------- ### Configure PowerShell for Toggleterm Source: https://github.com/akinsho/toggleterm.nvim/wiki/Tips-and-Tricks Sets the necessary shell options for PowerShell integration within Neovim. These settings must be applied before the plugin setup to ensure correct encoding and execution policies. ```vim let &shell = has('win32') ? 'powershell' : 'pwsh' let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;' let &shellredir = '-RedirectStandardOutput %s -NoNewWindow -Wait' let &shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' set shellquote= shellxquote= ``` ```lua local powershell_options = { shell = vim.fn.executable "pwsh" == 1 and "pwsh" or "powershell", shellcmdflag = "-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;", shellredir = "-RedirectStandardOutput %s -NoNewWindow -Wait", shellpipe = "2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode", shellquote = "", shellxquote = "", } for option, value in pairs(powershell_options) do vim.opt[option] = value end ``` -------------------------------- ### Create Custom Terminal with Count in ToggleTerm Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This snippet shows how to create a custom terminal instance and assign it a specific count. This count can be used to trigger the terminal, for example, by calling `:5ToggleTerm`. ```lua local lazygit = Terminal:new({ cmd = "lazygit", count = 5 }) ``` -------------------------------- ### Integrate Terminal Status in Statusline Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Example of how to access the terminal buffer variable to display the terminal number in a custom statusline. ```vim let statusline .= '%{&ft == "toggleterm" ? "terminal (" . b:toggle_number . ")" : ""}' ``` -------------------------------- ### Integrate Terminal Info into Statusline Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Provides examples for displaying terminal IDs in the statusline using Lualine or native Vimscript buffer variables. ```lua require("lualine").setup({ sections = { lualine_x = { { function() local terms = require("toggleterm.terminal") local term = terms.get(terms.get_focused_id()) if term then return "Terminal " .. term.id end return "" end, cond = function() return vim.bo.filetype == "toggleterm" end, }, }, }, }) ``` ```vim let statusline .= '%{&ft == "toggleterm" ? "terminal (".b:toggle_number.")" : ""}' ``` -------------------------------- ### Vimscript Terminal Mappings for ToggleTerm Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Configures Vimscript mappings to toggle terminals with counts for specific window selection. This setup allows opening specific terminal windows using a count prefix before the mapping. ```vimscript autocmd TermEnter term://*toggleterm#* \ tnoremap exe v:count1 . "ToggleTerm" noremap exe v:count1 . "ToggleTerm" inoremap exe v:count1 . "ToggleTerm" ``` -------------------------------- ### Create Custom Terminal Instances Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Demonstrates how to instantiate the Terminal class with custom configurations such as commands, directions, and lifecycle hooks like on_open and on_close. ```lua local Terminal = require("toggleterm.terminal").Terminal local lazygit = Terminal:new({ cmd = "lazygit", dir = "git_dir", direction = "float", hidden = true, float_opts = { border = "double", width = function() return math.floor(vim.o.columns * 0.9) end, height = function() return math.floor(vim.o.lines * 0.9) end, }, on_open = function(term) vim.cmd("startinsert!") vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "close", { noremap = true, silent = true }) end, on_close = function(term) vim.cmd("startinsert!") end, }) function _lazygit_toggle() lazygit:toggle() end vim.keymap.set("n", "g", _lazygit_toggle, { desc = "Toggle Lazygit" }) ``` -------------------------------- ### Implement Toggleable Custom Terminal Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Demonstrates how to instantiate a custom terminal and bind it to a Neovim keymap for toggling visibility. ```lua local Terminal = require('toggleterm.terminal').Terminal local lazygit = Terminal:new({ cmd = "lazygit", hidden = true }) function _lazygit_toggle() lazygit:toggle() end vim.api.nvim_set_keymap("n", "g", "lua _lazygit_toggle()", {noremap = true, silent = true}) ``` -------------------------------- ### Define Terminal with Custom Layout and Callbacks Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Shows how to create a floating terminal with custom border options and lifecycle hooks to manage Neovim insert mode. ```lua local lazygit = Terminal:new({ cmd = "lazygit", dir = "git_dir", direction = "float", float_opts = { border = "double", }, on_open = function(term) vim.cmd("startinsert!") vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "close", {noremap = true, silent = true}) end, on_close = function(term) vim.cmd("startinsert!") end, }) ``` -------------------------------- ### Terminal:new Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Creates a new custom terminal instance with specific command, layout, and lifecycle configuration. ```APIDOC ## Terminal:new ### Description Instantiates a new terminal object. This allows for creating specialized terminals for tools like lazygit or htop. ### Method Lua Constructor ### Parameters #### Request Body - **cmd** (string) - Optional - Command to execute. - **display_name** (string) - Optional - Name of the terminal. - **direction** (string) - Optional - Layout direction (horizontal, vertical, float). - **dir** (string) - Optional - Working directory. - **close_on_exit** (bool) - Optional - Close window on process exit. - **env** (table) - Optional - Environment variables. - **on_open** (function) - Optional - Callback on open. - **on_close** (function) - Optional - Callback on close. ### Request Example Terminal:new({ cmd = "lazygit", direction = "float", hidden = true }) ### Response #### Success Response (200) - **Terminal Object** (object) - The created terminal instance. ``` -------------------------------- ### Manage Terminal Instances Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Commands for creating new terminal instances, selecting terminals interactively, and toggling the state of all terminals simultaneously. ```vim :TermNew :TermNew direction=float :TermNew dir=~/projects/api name=api-server :TermSelect :TermSelect! :ToggleTermToggleAll :ToggleTermToggleAll! ``` -------------------------------- ### Configure and Toggle LazyGit Terminal Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Sets up a floating terminal for LazyGit using toggleterm.nvim. It defines the command, directory, and floating window options. It also includes functions to toggle the terminal and set keymaps for opening/closing and triggering the toggle action. ```lua local lazygit = Terminal:new({ cmd = "lazygit", dir = "git_dir", direction = "float", float_opts = { border = "double", }, -- function to run on opening the terminal on_open = function(term) vim.cmd("startinsert!") vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "close", {noremap = true, silent = true}) end, -- function to run on closing the terminal on_close = function(term) vim.cmd("startinsert!") end, }) function _lazygit_toggle() lazygit:toggle() end vim.api.nvim_set_keymap("n", "g", "lua _lazygit_toggle()", {noremap = true, silent = true}) ``` -------------------------------- ### Terminal Class API Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Demonstrates how to create and configure custom terminal instances using the Terminal class. ```APIDOC ## Terminal Class API The Terminal class allows creating custom terminal instances with full control over behavior and appearance. ### Example: Creating a lazygit terminal ```lua local Terminal = require("toggleterm.terminal").Terminal local lazygit = Terminal:new({ cmd = "lazygit", dir = "git_dir", direction = "float", hidden = true, -- Won't be toggled by :ToggleTerm float_opts = { border = "double", width = function() return math.floor(vim.o.columns * 0.9) end, height = function() return math.floor(vim.o.lines * 0.9) end, }, on_open = function(term) vim.cmd("startinsert!") vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "close", { noremap = true, silent = true, }) end, on_close = function(term) vim.cmd("startinsert!") end, }) -- Toggle function function _lazygit_toggle() lazygit:toggle() end -- Create keymap vim.keymap.set("n", "g", _lazygit_toggle, { desc = "Toggle Lazygit" }) ``` ### Example: Creating an htop terminal ```lua local htop = Terminal:new({ cmd = "htop", direction = "float", hidden = true, }) function _htop_toggle() htop:toggle() end vim.keymap.set("n", "h", _htop_toggle, { desc = "Toggle Htop" }) ``` ### Example: Terminal with specific count ```lua local python_repl = Terminal:new({ cmd = "python3", count = 5, direction = "horizontal", display_name = "Python REPL", }) ``` ``` -------------------------------- ### Configure Terminal Window Mappings Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Sets up keybindings to navigate between terminal windows and exit terminal mode efficiently. Uses an autocmd to apply these mappings automatically to all toggleterm buffers. ```lua function _G.set_terminal_keymaps() local opts = { buffer = 0 } vim.keymap.set("t", "", [[]], opts) vim.keymap.set("t", "jk", [[]], opts) vim.keymap.set("t", "", [[wincmd h]], opts) vim.keymap.set("t", "", [[wincmd j]], opts) vim.keymap.set("t", "", [[wincmd k]], opts) vim.keymap.set("t", "", [[wincmd l]], opts) vim.keymap.set("t", "", [[]], opts) end vim.cmd("autocmd! TermOpen term://*toggleterm#* lua set_terminal_keymaps()") ``` -------------------------------- ### Configure Persistent Terminal Size in ToggleTerm Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This configuration option controls whether toggleterm.nvim persists the size of horizontal and vertical terminals. Setting `persist_size = false` disables this behavior, forcing terminals to use the `size` defined in the setup. ```lua require'toggleterm'.setup{ persist_size = false } ``` -------------------------------- ### Terminal Instance Methods Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Provides details on methods available on Terminal instances for programmatic control. ```APIDOC ## Terminal Instance Methods Methods available on Terminal instances for programmatic control. ### Example: Opening and closing a terminal ```lua local Terminal = require("toggleterm.terminal").Terminal local term = Terminal:new({ cmd = "bash", direction = "horizontal" }) -- Open the terminal term:open() -- Open with specific size and direction term:open(20, "vertical") -- Close the terminal term:close() ``` ### Example: Toggling and sending commands ```lua -- Toggle open/closed state term:toggle() -- Send a command to the terminal term:send("echo 'Hello World'") -- Send multiple commands term:send({ "cd ~/projects", "ls -la", "git status" }) ``` ### Example: Managing terminal state ```lua -- Clear the terminal term:clear() -- Change directory term:change_dir("~/projects") -- Resize the terminal (splits only) term:resize(30) -- Focus the terminal window term:focus() ``` ### Example: Checking terminal status ```lua -- Check if terminal is open if term:is_open() then print("Terminal is visible") end -- Check terminal type if term:is_float() then print("Floating terminal") elseif term:is_split() then print("Split terminal") elseif term:is_tab() then print("Tab terminal") end ``` ### Example: Shutting down and spawning ```lua -- Shutdown terminal completely term:shutdown() -- Spawn terminal in background without opening window term:spawn() ``` ``` -------------------------------- ### Configure Keymaps for Sending Text to Terminals Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Demonstrates how to use the toggleterm Lua API to send visual selections, lines, or entire files to a terminal buffer. These mappings provide fine-grained control over terminal interaction. ```lua local trim_spaces = true vim.keymap.set("v", "s", function() require("toggleterm").send_lines_to_terminal("single_line", trim_spaces, { args = vim.v.count }) end) -- Send motion to terminal vim.keymap.set("n", [[]], function() set_opfunc(function(motion_type) require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count }) end) vim.api.nvim_feedkeys("g@", "n", false) end) -- Double the command to send line to terminal vim.keymap.set("n", [[]], function() set_opfunc(function(motion_type) require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count }) end) vim.api.nvim_feedkeys("g@_", "n", false) end) -- Send whole file vim.keymap.set("n", [[]], function() set_opfunc(function(motion_type) require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count }) end) vim.api.nvim_feedkeys("ggg@G''", "n", false) end) ``` -------------------------------- ### Create Custom Commands with ToggleTerm Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Demonstrates how to create custom Vim commands that execute specific terminal commands using the toggleterm.nvim plugin's `exec` function. This allows for quick execution of common terminal tasks. ```vim command! -count=1 TermGitPush lua require'toggleterm'.exec("git push", , 12) command! -count=1 TermGitPushF lua require'toggleterm'.exec("git push -f", , 12) ``` -------------------------------- ### Sending Lines to Terminal Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Explains how to send code from the current buffer to a terminal, useful for REPL-driven development. ```APIDOC ## Sending Lines to Terminal Send code from the current buffer to a terminal. Useful for REPL-driven development. ### Example: Using Vim commands ```vim " Send current line to terminal 1 vim.cmd("ToggleTermSendCurrentLine 1") " Send visual selection (lines) to terminal 2 vim.cmd("'<,'>ToggleTermSendVisualLines 2") " Send visual selection (exact text) to terminal 1 vim.cmd("'<,'>ToggleTermSendVisualSelection 1") ``` ### Example: Using Lua API for sending lines ```lua local toggleterm = require("toggleterm") local trim_spaces = true -- Visual selection mapping with trimmed spaces vim.keymap.set("v", "s", function() toggleterm.send_lines_to_terminal("single_line", trim_spaces, { args = vim.v.count }) end) -- Send visual lines vim.keymap.set("v", "sl", function() toggleterm.send_lines_to_terminal("visual_lines", trim_spaces, { args = vim.v.count }) end) -- Send exact visual selection vim.keymap.set("v", "ss", function() toggleterm.send_lines_to_terminal("visual_selection", trim_spaces, { args = vim.v.count }) end) -- For whitespace-sensitive languages like Python, disable trim_spaces vim.keymap.set("v", "sp", function() toggleterm.send_lines_to_terminal("visual_lines", false, { args = vim.v.count }) end) ``` ``` -------------------------------- ### Configure GitBash for Toggleterm Source: https://github.com/akinsho/toggleterm.nvim/wiki/Tips-and-Tricks Configures Neovim to use GitBash as the default shell for terminal operations. Requires specifying the absolute path to the GitBash executable. ```lua require'toggleterm'.setup({ open_mapping = '', start_in_insert = true, direction = 'float', }) vim.cmd [[let &shell = '""']] vim.cmd [[let &shellcmdflag = '-s']] ``` -------------------------------- ### Terminal Instance Control Methods Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Provides a reference for methods available on Terminal objects to manage state, execute commands, and inspect terminal properties. ```lua local Terminal = require("toggleterm.terminal").Terminal local term = Terminal:new({ cmd = "bash", direction = "horizontal" }) term:open() term:send("echo 'Hello World'") term:resize(30) if term:is_open() then print("Terminal is visible") end term:shutdown() ``` -------------------------------- ### Configure Terminal Shading Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Demonstrates how to enable or disable automatic terminal shading and specify which filetypes should be excluded from shading effects. ```lua require'toggleterm'.setup { shade_terminals = false } require'toggleterm'.setup { shade_filetypes = { "none", "fzf" } } ``` -------------------------------- ### Configure Manual Terminal Mappings Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Manual configuration for terminal toggle mappings using Vimscript. This allows users to pass counts to open specific terminal windows. ```vim autocmd TermEnter term://*toggleterm#* \ tnoremap exe v:count1 . "ToggleTerm" nnoremap exe v:count1 . "ToggleTerm" inoremap exe v:count1 . "ToggleTerm" ``` -------------------------------- ### Terminal Module Query Functions Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Explains how to use the module-level API to retrieve, find, and identify terminal instances by ID or predicate. ```lua local terms = require("toggleterm.terminal") local term = terms.get(1) local all_terms = terms.get_all() local python_term = terms.find(function(term) return term.cmd and term.cmd:match("python") end) local term, is_new = terms.get_or_create_term(3, "~/projects", "float", "My Term") ``` -------------------------------- ### TermSelect Command Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Allows users to select a terminal to open or focus using vim.ui.select. ```APIDOC ## TermSelect Command ### Description Provides an interface to select a terminal to open or focus using `vim.ui.select`. This is useful for managing multiple terminals. ### Method Nvim command ### Endpoint :TermSelect ### Parameters None ### Request Example ``` :TermSelect ``` ### Response #### Success Response (200) No specific response body, a selection interface is presented. #### Response Example (No response body) ``` -------------------------------- ### Send Buffer Content to Terminal Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Shows how to send lines or visual selections from the current buffer to a specific terminal instance, useful for REPL workflows. ```lua local toggleterm = require("toggleterm") -- Send visual lines to terminal vim.keymap.set("v", "sl", function() toggleterm.send_lines_to_terminal("visual_lines", true, { args = vim.v.count }) end) ``` -------------------------------- ### Configure Custom Terminal Instance Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Defines the structure and available configuration options for the Terminal class in toggleterm.nvim, including callbacks for lifecycle events and output processing. ```lua Terminal:new { cmd = string, display_name = string, direction = string, dir = string, close_on_exit = bool, highlights = table, env = table, clear_env = bool, on_open = fun(t: Terminal), on_close = fun(t: Terminal), auto_scroll = boolean, on_stdout = fun(t: Terminal, job: number, data: string[], name: string), on_stderr = fun(t: Terminal, job: number, data: string[], name: string), on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) } ``` -------------------------------- ### TermNew Command Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Opens a new terminal at the next available count. Supports arguments for size, direction, and name. ```APIDOC ## TermNew Command ### Description Opens a new terminal. It assigns the next available terminal number, which is helpful when used with `TermSelect`. ### Method Nvim command ### Endpoint :TermNew ### Parameters #### Query Parameters - **size** (number) - Optional - Specifies the height or width of the terminal split. - **dir** (string) - Optional - The directory in which to open the terminal. - **direction** (string) - Optional - Specifies the direction of the terminal split ('horizontal' or 'vertical'). - **name** (string) - Optional - Sets a display name for the terminal. ### Request Example ``` :TermNew size=25 direction=vertical name=new-term ``` ### Response #### Success Response (200) No specific response body, a new terminal is opened. #### Response Example (No response body) ``` -------------------------------- ### Manage Terminal Names Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Demonstrates how to assign display names to terminal instances using the ToggleTermSetName command, which helps identify terminals in the winbar or selection menus. ```vim :ToggleTermSetName :2ToggleTermSetName build-server :ToggleTermSetName api-server ``` -------------------------------- ### Configure Dynamic Shell Selection in toggleterm.nvim Source: https://github.com/akinsho/toggleterm.nvim/wiki/Per-file-type-shell This snippet demonstrates how to define a shell function that inspects the current buffer's filetype. It caches the determined shell to ensure the correct environment is launched when the terminal buffer is initialized. ```lua local shell = nil require("toggleterm").setup({ shell = function() local ft = vim.bo.filetype vim.print("File type: "..ft) if ft == "r" then shell = "radian" elseif ft == "python" then shell = "ipython" elseif ft == "toggleterm" then return shell else shell = vim.o.shell end return shell end }) ``` -------------------------------- ### Configure PowerShell for Windows Source: https://context7.com/akinsho/toggleterm.nvim/llms.txt Configures shell options to ensure compatibility with PowerShell on Windows systems, including encoding and execution policies. ```lua local powershell_options = { shell = vim.fn.executable("pwsh") == 1 and "pwsh" or "powershell", shellcmdflag = "-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;", shellredir = "-RedirectStandardOutput %s -NoNewWindow -Wait", shellpipe = "2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode", shellquote = "", shellxquote = "", } for option, value in pairs(powershell_options) do vim.opt[option] = value end require("toggleterm").setup({ shell = vim.o.shell, direction = "float", }) ``` -------------------------------- ### Initialize or Toggle Terminal Utility Source: https://github.com/akinsho/toggleterm.nvim/wiki/Tips-and-Tricks A helper function to check for existing toggleterm buffers and create a new one if none are found. This ensures that terminal commands always have an active buffer to interact with. ```lua local M = {} M.init_or_toggle = function() vim.cmd([[ ToggleTermToggleAll ]]) local buffers = vim.api.nvim_list_bufs() local toggleterm_exists = false for _, buf in ipairs(buffers) do local buf_name = vim.api.nvim_buf_get_name(buf) if buf_name:find("toggleterm#") then toggleterm_exists = true break end end if not toggleterm_exists then vim.cmd([[ exe 1 . "ToggleTerm" ]]) end end return M ``` -------------------------------- ### toggleterm.exec Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Executes a shell command directly in a terminal buffer without requiring a manual toggle. ```APIDOC ## toggleterm.exec ### Description Executes a command string within a specific terminal buffer context. ### Method Lua Function ### Parameters #### Arguments - **command** (string) - Required - The shell command to run. - **count** (number) - Required - The terminal ID. - **size** (number) - Required - The size of the terminal. ### Request Example require'toggleterm'.exec("git push", 1, 12) ### Response #### Success Response (200) - **nil** - Executes the command in the background or specified buffer. ``` -------------------------------- ### Open Multiple Terminals Side-by-Side Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Explains how to open multiple terminals side-by-side using toggleterm.nvim. It details the key mapping sequence and the concept of terminal numbers for referencing specific instances. ```vim Inyour first terminal, you need to leave the `TERMINAL` mode using C-\C-N which can be remapped to Esc for ease of use. Then you type on: `2`, and the result: Explain: - `2`this is the terminal’s number (or ID), your first terminal is `1` (e.g. your 3rd terminal will be `3`, so on). - C- his is the combined key mapping to the command `:ToggleTerm`. ``` -------------------------------- ### Define ToggleTerm Terminal Class Structure Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt This snippet defines the structure of the `Terminal` class used in toggleterm.nvim for creating custom terminals. It outlines the various arguments that can be passed when initializing a new terminal instance, such as the command to run, display name, direction, and callbacks. ```lua Terminal:new { cmd = string, -- command to execute when creating the terminal e.g. 'top' display_name = string, -- the name of the terminal direction = string, -- the layout for the terminal, same as the main config options dir = string, -- the directory for the terminal close_on_exit = bool, -- close the terminal window when the process exits highlights = table, -- a table with highlights env = table, -- key:value table with environmental variables passed to jobstart() clear_env = bool, -- use only environmental variables from `env`, passed to jobstart() on_open = fun(t: Terminal), -- function to run when the terminal opens on_close = fun(t: Terminal), -- function to run when the terminal closes auto_scroll = boolean, -- automatically scroll to the bottom on terminal output -- callbacks for processing the output on_stdout = fun(t: Terminal, job: number, data: string[], name: string), -- callback for processing output on stdout on_stderr = fun(t: Terminal, job: number, data: string[], name: string), -- callback for processing output on stderr on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits } ``` -------------------------------- ### TermSelect Command for Selecting and Focusing Terminals Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md TermSelect utilizes vim.ui.select to provide an interactive way to select and open a terminal, or focus it if it's already open. This is particularly useful when managing multiple terminals without remembering their specific numbers. ```vimscript :TermSelect ``` -------------------------------- ### TermExec Command Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Opens a terminal and executes a specific command within it. Supports arguments for command, directory, size, direction, and name. ```APIDOC ## TermExec Command ### Description Opens a terminal and executes a specified command within it. This command is useful for running specific tasks in a dedicated terminal. ### Method Nvim command ### Endpoint :TermExec ### Parameters #### Query Parameters - **cmd** (string) - Required - The command to execute. Must be quoted. Can expand special keywords. - **dir** (string) - Optional - The directory in which to execute the command. Can be optionally quoted if it contains spaces. Can expand special keywords. - **size** (number) - Optional - Specifies the height or width of the terminal split. - **direction** (string) - Optional - Specifies the direction of the terminal split ('horizontal' or 'vertical'). - **name** (string) - Optional - Sets a display name for the terminal. - **go_back** (number) - Optional - If set to 0, focus is not returned to the original window after execution (default is 1, focus is returned, except for floating terminals). - **open** (number) - Optional - If set to 0, commands can be sent to a terminal without opening its window. ### Request Example ``` :TermExec cmd="git status" dir=~/ :TermExec cmd="echo %" dir=~/ size=30 ``` ### Response #### Success Response (200) No specific response body, the command is executed in a terminal. #### Response Example (No response body) ``` -------------------------------- ### ToggleTerm Command API Source: https://github.com/akinsho/toggleterm.nvim/blob/main/doc/toggleterm.txt Directly calling the ToggleTerm command with arguments. ```APIDOC ## ToggleTerm Command ### Description Manually invoke the ToggleTerm command, optionally specifying arguments like size, direction, and name. ### Method `:ToggleTerm [arguments]` ### Endpoint N/A (Vim command) ### Parameters #### Query Parameters - **size** (number) - Optional - The desired size of the terminal window. - **dir** (string) - Optional - The directory to open the terminal in. - **direction** (string) - Optional - The direction of the terminal ('horizontal', 'vertical', etc.). - **name** (string) - Optional - A custom name for the terminal. ### Request Example ```vim :ToggleTerm size=40 dir=~/Desktop direction=horizontal name=desktop ``` ### Response Opens or manages a terminal instance based on the provided arguments. ``` -------------------------------- ### Set Terminal Navigation Mappings Source: https://github.com/akinsho/toggleterm.nvim/blob/main/README.md Defines custom key mappings for terminal buffers to facilitate easier navigation between windows and exiting terminal mode. ```lua function _G.set_terminal_keymaps() local opts = {buffer = 0} vim.keymap.set('t', '', [[]], opts) vim.keymap.set('t', 'jk', [[]], opts) vim.keymap.set('t', '', [[wincmd h]], opts) vim.keymap.set('t', '', [[wincmd j]], opts) vim.keymap.set('t', '', [[wincmd k]], opts) vim.keymap.set('t', '', [[wincmd l]], opts) vim.keymap.set('t', '', [[]], opts) end vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()') ```