Skip to content

Instantly share code, notes, and snippets.

@PeterRincker
Last active January 27, 2017 23:37
Show Gist options
  • Save PeterRincker/6946a8152316ce6578d998e273eb9570 to your computer and use it in GitHub Desktop.
Save PeterRincker/6946a8152316ce6578d998e273eb9570 to your computer and use it in GitHub Desktop.
Backtick support for matchit in markdown files
" Put inside ~/after/plugin/matchit.vim
if exists('g:loaded_after_matchit') || !has('syntax') || &cp || v:version < 700
finish
endif
let g:loaded_after_matchit = 1
function! s:synnames(...) abort
if a:0
let [line, col] = [a:1, a:2]
else
let [line, col] = [line('.'), col('.')]
endif
return reverse(map(synstack(line, col), 'synIDattr(v:val,"name")'))
endfunction
function! s:lift_mapping(name, mode, target)
let mapping = maparg(a:name, a:mode, '', 1)
execute mapping.mode . (mapping.noremap ? 'noremap' : 'map') .
\ join(map(['buffer', 'expr', 'nowait', 'silent'], 'mapping[v:val] ? "<" . v:val . ">": ""')) .
\ a:target . ' ' .
\ substitute(mapping.rhs, '<SID>', '<SNR>' . mapping.sid . '_', 'g')
endfunction
call s:lift_mapping("%", "n", '<Plug>(matchit-%)')
function! s:find_delim_or_matchit(pat, delim_syn, region_syn, matchit, ...)
let view = a:0 ? a:1 : winsaveview()
let syn = join(s:synnames(), ' ')
let fwd = (syn =~# a:delim_syn && syn =~# a:region_syn) || (syn !~# a:delim_syn && syn !~ a:region_syn)
let flags = (fwd ? '' : 'be') . 'W'
let pats = [a:delim_syn] + (fwd ? [] : [a:region_syn])
let line = search(a:pat, flags . 's')
while line != 0
let syn = join(s:synnames(), ' ')
if min(map(pats, 'syn =~# v:val')) == 1
return
endif
let line = search(a:pat, flags)
endwhile
if a:0
call winrestview(view)
execute "normal " . a:matchit
else
normal! 0
call s:find_delim_or_matchit(a:pat, a:delim_syn, a:region_syn, a:matchit, view)
endif
endfunction
nnoremap <silent> <Plug>(markdown-tick-%) :call <SID>find_delim_or_matchit('`', 'CodeDelimiter\>', 'Code\>', '<Plug>(matchit-%)')<cr>
augroup MatchItBacktick
autocmd!
autocmd FileType markdown nmap <buffer> % <Plug>(markdown-tick-%)
augroup END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment