Last active
September 29, 2024 20:07
Open a markdown link under the cursor (proof-of-concept)
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
" Save in ~/.vim/ftplugin/markdown_open_link.vim | |
nnoremap <buffer> gx :call <SID>OpenLink()<cr> | |
function! s:OpenLink() | |
let saved_view = winsaveview() | |
defer winrestview(saved_view) | |
let syntax_under_cursor = synIDattr(synID(line("."), col("."), 0), "name") | |
let url = '' | |
if syntax_under_cursor == 'markdownLinkText' | |
" we're on the text, move to the closing bracket, over the opening bracket | |
" of the group, and into the text | |
normal! f]ll | |
let syntax_under_cursor = synIDattr(synID(line("."), col("."), 0), "name") | |
endif | |
if syntax_under_cursor == 'markdownUrl' | |
" [Text](https://example.com) | |
let url = s:GetMotion('vi(') | |
elseif syntax_under_cursor == 'markdownAutomaticLink' | |
" <https://example.com> | |
let url = s:GetMotion('vi<') | |
elseif syntax_under_cursor == 'markdownId' | |
" [Text][42] | |
" [42]: https://example.com | |
let id = s:GetMotion('vi[') | |
let url_lineno = search('^\['..id..'\]: ', 'n') | |
let url = matchstr(getline(url_lineno), '^\['..id..'\]: \zs.*$') | |
endif | |
if url != '' | |
call system('xdg-open '..shellescape(url)) | |
" (or some other way of opening) | |
endif | |
endfunction | |
function s:GetMotion(motion) | |
let saved_register = getreg('a') | |
defer setreg('a', saved_register) | |
exe 'normal! ' .. a:motion .. '"ay' | |
return @a | |
endfunction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment