Fixing gx for Neovim with a Ruby Script
Maybe it’s my setup, but I have always had problems with gx
since ever since I started using vim/MacVim/Neovim.
I wrote a Ruby script, and map gx
to it like this:
vim.cmd([[nnoremap gx :execute '!echo ' . shellescape(getline('.'), 1) . "\| openurls &"<CR><CR>]])
The Ruby script: openurls
:
#!/usr/bin/env ruby
# Opens URLs embedded in STDIN (so it's useful in vim by selecting text and running it)
require 'uri'
input = $stdin.read.split("\n")
# The closing parenthesis character might or might not be valid, but we remove it if it's the end since it might be part of a URL specified in Markdown like this "[label](url)" or "[label](url),"
urls = input.map do |line|
URI.extract(line, ['http', 'https'])
end.flatten.map { |e| e.chomp('.').chomp(',').chomp(')') }
urls.each do |each|
`open "#{each}"`
end
# Echo the input so we can run this in vim and the original text will be there
puts input
With that, gx
will open all URLs on the current line instead of just the one under the cursor.
openurls
itself handles multiple lines, so you can actually select multiple lines in visual mode and then do:
'<,'>!openurls
to open all the URLs in the selection.
(We lose the ability to open local files with it, but there’s still gf
)