" this script (markdown.vim) must be placed in ~/.vim/after/ftplugin " requires https://github.com/plasticboy/vim-markdown function! s:markdownGotoHeader() let pos = getpos('.') call search('(', 'bcW', line('.')) if !search('#', 'cW', line('.')) echohl ErrorMsg echo 'No link found on rest of line' echohl NONE call setpos('.', pos) return endif let asav = @a normal! "ayib let targ = @a let @a = asav let targ = substitute(targ, '^#\+', '', '') let targ = substitute(targ, '^\s\+\|\s\+$', '', 'g') if empty(targ) echohl ErrorMsg echo 'target is empty' echohl NONE call setpos('.', pos) return endif let targ = split(targ)[0] let targ = '\[[:punct:][:space:]]\*'.join(map(split(targ, '-'), { _,str -> join(map(split(str, '\zs'), { _,chr -> chr == '\' ? '\\' : chr }), '\[[:punct:]]\*') }), '\[[:punct:][:space:]]\+').'\[[:punct:][:space:]]\*' let pat = '\V\c\^\%(\s\*'.targ.'\n\[-=]\|#\+\s\*'.targ.'\)' let lnr = search(pat, 'cnw') if lnr == 0 echohl ErrorMsg echo 'target /'.targ.'/ not found' echohl NONE call setpos('.', pos) return endif call setpos("''", pos) call setpos('.', [bufnr(), lnr, 1, 1]) endfunction nnoremap K :call markdownGotoHeader()