Opening a Terminal in Vim


Sometimes it is useful to run a shell inside Vim. This outputs to a Vim buffer, this allows searching the output with regular expressions, the output can be saved, and the output can be easily copied to a new buffer where it can be edited.


Here are the basic moves.


Open a Terminal in a New Tab


After opening Vim, you can open a terminal in a new Vim tab using the ex command below. This will automatically switch you to the new tab. Here, I open PowerShell.


:tab terminal pwsh

Switch to Terminal-Normal Mode


You can use your terminal normally in Vim.


But if you want to start using Vim commands, you will have to break out of the focus on the shell.


The keystroke 'Ctrl-w, N' will pause the shell and switch Vim to Normal mode. Note the trailing N must be capitalized.


In Normal mode, you can search the buffer with '/' or save it with ':w {file}'.


While in Terminal-Normal mode, you can copy the contents of the terminal buffer to a new buffer with the commands below. In the new buffer, you can edit with normal Vim commands. The terminal tab cannot be edited directly.


:% yank
:tabnew
:0 put

Switch Vim Tabs


To switch between Vim tabs, use the keystrokes 'gt'. If you're using the terminal, you will have to switch to Terminal-Normal mode to use 'gt'. Or, you can use 'Ctrl-w, gt' while focus is still on the shell.


If you have mouse support enabled or if you are using gVim then you can click on the tabs near the top of the window to switch tabs.


Return to Terminal


To switch back to the terminal and resume processing, use 'i' for Insert mode: as if you were going to edit the buffer. If you previously switched tabs, you will have to switch back to the terminal tab first.


Exit Terminal


You must exit the terminal process before closing the buffer. Exit the shell normally. And, then, exit Vim normally.


exit
:q

References


Terminal-Mode


Created: Wednesday, May 11, 2022

Updated: Wednesday, May 11, 2022



/gemlog/