Terminal mode

Historically, you can run shell commands from Vim by using :! followed by a shell command. For example, we could execute our Python program as follows:

:!python3 animal_farm.py cat dog sheep

Vim will pause, and you'll see the output in the Terminal:

Things have got better since then.

In version 8.1, Vim introduced the terminal mode. The terminal mode is effectively a Terminal emulator running within your Vim session. Unlike with tmux, terminal mode plays with Vim out of the box. It's great for running long running commands while you continue to work in Vim.

Terminal mode can be invoked by executing the following:

:term

This opens a horizontal split with your default shell running:

The Terminal window is treated like any other window, and can be resized and moved as usual (see the Windows section in Chapter 10, Neovim). The window is running in a terminal-job mode, something akin to an insert mode. But there are a few specific key bindings:

  • Ctrl + wenters a terminal-normal mode, which behaves just like a normal mode. Operations that take you back to insert mode (such as i or a) will take you back to a terminal-job mode.
  • Ctrl + w" followed by a register will paste the contents of a register into a terminal. For example, to paste something you yanked with yw, you can execute Ctrl + w" to paste from the default register.
  • Ctrl + w, Ctrl + c sends Ctrl + c to the running command in a Terminal.

The best feature of a terminal mode is that you can invoke terminal mode with a specific command, and get full access to the output. Try running the following from within Vim:

:term python3 animal_farm.py cat dog sheep

This will execute a command and, once it is done running, open a buffer with the resultant output:

If you so desire, you can open a Terminal in a vertical split by running :vert term

If you use the Ctrl + hjkl shortcuts from Chapter 2Advanced Editing and Navigation,to navigate your Vim windows, you may want to add an additional set of bindings to your .vimrc file to work with the terminal mode:


tnoremap <c-j> <c-w><c-j>
tnoremap <c-k> <c-w><c-k>
tnoremap <c-l> <c-w><c-l>
tnoremap <c-h> <c-w><c-h>

For best results, you can combine Vim terminal mode with tmux: tmux can manage your sessions for you (for when you need to switch focus between tasks), while terminal mode can manage windows. For instance, you could use Vim terminal windows to organize work on your project and tmux windows (or tabs in Vim terminology) to switch focus and work on different tasks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.22