Created
September 18, 2024 06:11
-
-
Save Konfekt/848ea56a3e748324fb6a9b9fa6cf2e5f to your computer and use it in GitHub Desktop.
Open URLs such as markdown links in browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" Better gx to open URLs in Vim. | |
" | |
" Adapted from https://github.com/habamax/.vim/blob/d5087779fee4a7372c1dd2c407674997fdb1268d/autoload/os.vim | |
" to use in particular :Open command from https://gist.github.com/Konfekt/8e484af2955a0c7bfe82114df683ce0f | |
" See also https://gist.github.com/AndrewRadev/1ba9eba62df82d616fc8040338c4c4e1 | |
func! s:BetterGx() abort | |
" URL regexes | |
let rx_base = '\%(\%(http\|ftp\|irc\)s\?\|file\)://\S' | |
let rx_bare = rx_base . '\+' | |
let rx_embd = rx_base . '\{-}' | |
let URL = '' | |
" cursor on | |
" markdown URL such as [link text](http://ya.ru 'yandex search') | |
try | |
let save_view = winsaveview() | |
if searchpair('\[.\{-}\](', '', ')\zs', 'cbW', '', line('.')) > 0 | |
let URL = matchstr(getline('.')[col('.')-1:], '\[.\{-}\](\zs'.rx_embd.'\ze\(\s\+.\{-}\)\?)') | |
endif | |
finally | |
call winrestview(save_view) | |
endtry | |
" asciidoc URL such as http://yandex.ru[yandex search] | |
if empty(URL) | |
try | |
let save_view = winsaveview() | |
if searchpair('\[.\{-}\](', '', ')\zs', 'cbW', '', line('.')) > 0 | |
let URL = matchstr(getline('.')[col('.') - 1 : ], '\[.\{-}\](\zs' . rx_embd . '\ze\(\s\+.\{-}\)\?)') | |
endif | |
finally | |
call winrestview(save_view) | |
endtry | |
endif | |
" HTML URL such as <a href='http://www.python.org'>Python is here</a> | |
" <a href="http://www.python.org"/> | |
if empty(URL) | |
try | |
let save_view = winsaveview() | |
if searchpair('<a\s\+href=', '', '\%(</a>\|/>\)\zs', 'cbW', '', line('.')) > 0 | |
let URL = matchstr(getline('.')[col('.') - 1 : ], | |
\ 'href=["' . "'" . ']\?\zs\S\{-}\ze["' . "'" . ']\?/\?>') | |
endif | |
finally | |
call winrestview(save_view) | |
endtry | |
endif | |
" URL (http://google.com) | |
if empty(URL) | |
let URL = matchstr(expand("<cWORD>"), '^(\zs' . rx_bare . '\ze)$') | |
endif | |
" barebone URL http://google.com | |
if empty(URL) | |
let URL = matchstr(expand("<cWORD>"), rx_bare) | |
endif | |
if empty(URL) | |
return | |
endif | |
exe 'Open! ' . escape(URL, '#%') | |
endfunc | |
nnoremap <silent> gx :<c-u>call <SID>BetterGx()<CR> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment