Editing in vim from anywhere*
May 22, 2020I love vim. Once you start using it (properly), you want it everywhere. The modal editing is…
…wait, I don't need to sell vim to you, you came here because you already know how great it is!
(*)
This should work if you are using X11.
How
What would you do if you wanted shift what you were typing to vim?
This is what comes to mind:
- Copy the text
- Open vim and paste it there
- Edit
- Copy it to the system clipboard
- Paste
Hmmm. Only if I could automate this…
Enter xdotool
What is xdotool?
This tool lets you simulate keyboard input and mouse activity, move and resize windows, etc. It does this using X11’s XTEST extension and other Xlib functions.
Requirements
- xdotool: for simulating copy/paste actions
- xclip: for getting/setting clipboard content
Code
#!/bin/bash
# you can set this to the one you use
TERMINAL=uxterm
file=`mktemp`
# a small delay is usually required when dealing with xdotool
sleep 0.5s
# copy whatever was selected
xdotool key ctrl+c
# put clipboard contents inside a file
xclip -selection clipboard -o > $file
# open preferred text editor (vim!)
"$TERMINAL" -e "$EDITOR $file"
# when done with editing, copy contents to clipboard
xclip -selection clipboard -i < $file
sleep 0.1s
# replace the selection which was just copied
xdotool key ctrl+v
rm $file
How to use
- Save this file somewhere and make sure it can be executed (
chmod +x
) - If not already present, add the directory to
PATH
(not exactly a necessity but now it's easier to run it manually too) - Make this accessible by a keyboard shortcut. (e.g. for ubuntu)
- Enjoy
Now, whenever I want to edit something in vim, I select the desired portion and press the hotkey and voila, my text is in vim! Edit, save and close, and the original text gets replaced by this!
i3 users
A bindsym will do the job. You might want to use a terminal which you don't use regularly and make it a floating window.
Here's what I did (i3conf):
bindsym $mod+q exec vimedit
for_window [class="UXTerm"] floating enable
This made the script available to me with super+q
. I don't have to specify the whole path to the file since I update PATH
before loading i3.
Demo
This, along with various other cool stuff can be found in my dotfiles repo.
So, did you like it? Did I miss something? Did I do something in the wrong way? Please comment below and improve my knowledge!