Open external URL in Vim vsplit with w3m
Starting from version 8.1 Vim has a terminal function. It lets you open a Vim window that acts like a terminal.
With ":terminal" you open a terminal in the current window.
To create a vertical split, with a terminal in the newly opened window, use ":vertical terminal".
With some easy Vim scripting you can open the external URL that is under the cursor with the awesome textmode browser w3m in a Vim terminal. I liked to have that in a vertical split.
This is what I came up with:
function s:vertopen_url() normal! "uyiW let mycommand = "w3m " . @u execute "vertical terminal " . mycommand endfunction
This is what this function does:
- yank the inner Word into the register "u".
- create a string with "w3m" folowed by a space and the url
- open a vertical split terminal and run this string as command
This works fine, but could use some improvements:
- The contents of the register "u" are overwritten
- After closing w3m, the user has to close the window with :q
So perhaps we need to add something to save the contents of register "u" and restore it after calling w3m.
Also, perhaps we can add something to close the newly opened window.
But for now, this function is good enough.
Put this function in a file under ~/.vim/plugin and add the following line to this file:
noremap <Plug>vertopen_url : call <SID>vertopen_url()<CR>
In your .vimrc you can map this function to a command. I have binded this function to [leader]-x:
nmap <Leader>x <Plug>vertopen_url
This it how it works:
- Go to an URL somewhere in your Vim edit session
- Put the cursor somewhere on this URL
- Hit [leader]-x
- Vim opens a window in a vertical split and starts w3m with this URL
Update on automagicly closing of the terminal
R. Tyler Croy notified me of the option to add
++close to the
terminal command. This will
automagicly close the terminal window after the
initial command has finished.
So the function will become:
function s:vertopen_url() normal! "uyiW let mycommand = "w3m " . @u execute "vertical terminal++close " . mycommand endfunction
It works great, so a big thank you to R. Tyler Croy :)