In this recipe, we will explore how to spawn an external editor (Vim) from within the TUI app. This
example demonstrates how to temporarily exit the TUI, run an external command, and then return back
to our TUI app.
Full code:
Setup
First, let’s look at the main function and the event handling logic:
After initializing the terminal in main function, we enter a loop in run function where we draw
the UI and handle events. The handle_events function listens for key events and returns an
Action based on the key pressed. Here, we are calling run_editor function on Action::EditFile
which we will define in next section.
Spawning Vim
Now, let’s define the function run_editor function attached to Action::EditFile action.
To spawn Vim from our TUI app, we first need to relinquish control of input and output, allowing Vim
to have full control over the terminal.
The run_editor function handles the logic for spawning vim. First, we leave the alternate screen
and disable raw mode to restore terminal to it’s original state. This part is similar to what
ratatui::restore function does in the
main function. Next, we spawn a child process with
Command::new("vim").arg("/tmp/a.txt").status() which launches vim to edit the given file. At
this point, we have given up control of our TUI app to vim. Our TUI app will now wait for the exit
status of the child process. Once the user exits Vim, our TUI app regains control over the terminal
by re-entering alternate screen and enabling raw mode. Lastly, we clear the terminal to ensure the
TUI is displayed correctly.
Running code
Running this program will display “Hello ratatui! (press ‘q’ to quit, ‘e’ to edit a file)” in the
terminal. Pressing ‘e’ will spawn a child process to spawn Vim for editing a temporary file and then
return to the ratatui application after Vim is closed.
Feel free to adapt this example to use other editors like nvim, nano, etc., by changing the
command in the Action::EditFile arm.