Last active
September 27, 2024 06:24
-
-
Save Konfekt/848ea56a3e748324fb6a9b9fa6cf2e5f to your computer and use it in GitHub Desktop.
Open links and files 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. | |
" | |
" 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 | |
" URL regexes | |
let s:regex_url = '\%(\%(http\|ftp\|irc\)s\?\|file\)://\S\{-}' | |
func! s:GetURL() abort | |
" markdown URL such as [link text](http://ya.ru 'yandex search') | |
try | |
let save_view = winsaveview() | |
if searchpair('\[.\{-}\](', '', ')\zs', 'cbW', '', line('.')) > 0 | |
return matchstr(getline('.')[col('.')-1:], '\[.\{-}\](\zs'..s:regex_url..'\ze\(\s\+.\{-}\)\?)') | |
endif | |
finally | |
call winrestview(save_view) | |
endtry | |
" HTML URL such as <a href='http://www.python.org'>Python is here</a> | |
" <a href="http://www.python.org"/> | |
try | |
let save_view = winsaveview() | |
if searchpair('<a\s\+href=', '', '\%(</a>\|/>\)\zs', 'cbW', '', line('.')) > 0 | |
return matchstr(getline('.')[col('.') - 1 : ], | |
\ 'href=["'.."'"..']\?\zs\S\{-}\ze["'.."'"..']\?/\?>') | |
endif | |
finally | |
call winrestview(save_view) | |
endtry | |
" URL with leading or closing parenthesis (http://google.com) | |
let URL = matchstr(expand("<cWORD>"), '^(\?\zs'..s:regex_url..'\ze)\?$') | |
if !empty(URL) | return URL | endif | |
" Is it a file in the current work dir? | |
let file = expand("<cfile>") | |
if filereadable(file) | return file | endif | |
" .. or that of the current buffer? | |
let path = expand('%') | |
if isdirectory(path) | |
let dir = fnamemodify(path, ':p') | |
elseif filereadable(path) | |
let dir = fnamemodify(path, ':p:h') | |
endif | |
if exists('dir') && filereadable(dir..'/'..file) | return dir..'/'..file | endif | |
return '' | |
endf | |
func! s:BetterGx() abort | |
let URL = s:GetURL() | |
if !empty(URL) | exe 'Open' escape(URL, '#%') | endif | |
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