linuxvimcommand-lineterminalxfce

Select text within terminal output using VIM


Let's say I have the following output in my terminal window now:

1. vsud@vsud:~$ pwd
2. /home/vsud
3. vsud@vsud:~$ echo "Hello, world!"
4. Hello, world!

I want to copy to clipboard the 1st and 2nd lines.

vsud@vsud:~$ pwd
/home/vsud

With mouse - I can do that by selecting those 2 lines and pressing Ctrl + Shift + C. But can I enter into VIM mode somehow and work with that whole output in my terminal as with pure text - so to copy 2 lines I will need to type just "H2yy" ? Do I need to install some specific Terminal Emulator for that?

Now I'm using terminal emulator which is built in XFCE.


Solution

  • There are two ways to do that: (1) Using tmux, and using (2) ':term' inside vim

    tmux

    If you are using your terminal from within tmux, you can enter copy mode and select and copy lines from your terminal. Assuming tmux Prefix is Ctrl-b, the precise steps to do this are:

    1. Enter copy mode: Ctrl-b [

    2. Start selecting: Space

    3. Extend selection: use arrow keys

    4. Store selection in buffer: Enter

    5. Transfer selection to system clipboard: Ctrl-b : run-shell "tmux save buffer - | xsel -i -b"

    6. Paste the selection into a vim buffer(+ register): "+p

    Additional Notes:

    a. tmux offers a command called "capture-pane", with which you can copy an entire pane(terminal).

    b. You need xsel to be installed for step 5 above to work. Step 5 can be shortened by using a keybinding. For that have the following command in your .tmux.conf (or, entering this command on your tmux command line Ctrl-b :)

    bind C-c run-shell "tmux save-buffer - | xsel -i -b"

    Now step 5 is equivalent to pressing Ctrl-c.

    c. You can use vim keys for navigation in copy mode: Ctrl-b :setw -g mode-keys vi

    :term

    If you fire terminal from inside vim using the ex command ':term', you can enter "normal" mode using: Ctrl-W Shift-n. Then you can navigate (and copy in) the terminal with vim keys as if it were a regular vim buffer.