How can I capture text edited interactively in Vim from a shell script?

0
1
Asked By QuietMaple42 On

I have a shell script that creates a temporary file, opens it in a new terminal with Vim, and then prints the edited contents before deleting the file. I would like to assign that resulting text to a shell variable using command substitution, but Vim does not seem to start when invoked that way. Is there a proper way to run an interactive editor and capture the edited contents, or should I leave cleanup to the calling script instead? Also, an mpv Lua plugin launches the script in a separate terminal. When mpv exits, the terminal and Vim process remain open. I expected the child process to terminate with mpv, so what is the correct way to handle that process lifetime?

4 Answers

Answered By CopperLynx7 On

For this use case, `vipe` from the moreutils package is probably the simplest solution. It lets you send text through Vim and receive the edited result without having to manage the temporary file yourself. You can also reproduce the same basic idea in your own script if you need custom behavior.

Answered By SilverNoodle31 On

If you only need to transform text, a noninteractive tool such as `sed` or `awk` may be a better fit. But if the requirement is specifically Vim’s buffer and key bindings, those tools cannot replace it; use a terminal-aware wrapper such as `vipe` or explicitly connect Vim to a TTY.

BrightCedar5 -

That approach works for automated substitutions, but it does not provide an interactive Vim-style editing buffer, so it is not equivalent when the user needs to edit manually.

Answered By MildOrbit_8 On

Command substitution can run interactive programs, but editors need access to a real terminal. Their input and display may involve the terminal device directly rather than just standard input and output, so redirecting the editor’s input or output to `/dev/tty` may be necessary. Another option is to use a tool such as `script` to provide a pseudo-terminal, although that can also capture terminal control sequences rather than only the edited text.

Answered By AmberKite_64 On

Closing mpv does not automatically terminate every descendant process it started. Once the new terminal or Vim process has detached, it can continue running unless it receives a signal or is placed in a process group that you explicitly clean up. If the terminal is intentionally launched separately, have the launcher retain its PID or process-group ID and send a termination signal during cleanup; otherwise, make sure Vim stays attached to the parent’s lifecycle rather than daemonizing.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.