vim-markdown
vim-markdown copied to clipboard
Create markdown link if not exist yet
You can follow a markdown link with vim-markdown-ge or ge. Is there a way to create a link if it not exist yet? A behaviour like pressing Enter in vimwiki.
A command to change link to [link](link).
@BirgerNi place this as after/ftplugin/markdown.vim and press gr in normal or visual-mode.
function! s:link_surround(mode)
if a:mode == 'n'
let l:str = expand('<cword>')
let [l:bufnum, l:lnum, l:col, l:off, _] = getcurpos()
let l:len = strchars(l:str)
let l:line = getline(l:lnum)
let l:idx = strridx(l:line, l:str, l:col)
elseif a:mode == 'v'
let [l:bufnum, l:lnum, l:col_start, l:off] = getpos("'<")
let [l:line_end, l:col_end] = getpos("'>")[1:2]
if l:lnum != l:line_end
throw 'Toggle link on multiple lines is not supported.'
endif
let l:idx = l:col_start - 1
let l:len = l:col_end - l:idx
let l:line = getline(l:lnum)
endif
let l:new = strcharpart(l:line, 0, l:idx)
\ . '[' . strcharpart(l:line, l:idx, l:len) . ']()'
\ . strcharpart(l:line, l:idx + l:len)
call setline(l:lnum, l:new)
call setpos('.', [l:bufnum, l:lnum, l:idx + l:len + 4, l:off])
startinsert
endfunction
nnoremap <buffer><silent> gr :<C-u>call <SID>link_surround('n')<CR>
vnoremap <buffer><silent> gr :call <SID>link_surround('v')<CR>