# Context sensitive insert mode mapping or abbreviation

I'm planning to implement some utility mappings for my LaTeX plugin to simplify typing of mathematics. For instance, I want to create abbreviations similar to

a : \alpha
b : \beta
-> : \to
=> : \Rightarrow


And similar. I want (some of) the mappings only to be available inside math environments, and not outside.

I know that I can recognize math environments through the syntax groups, i.e. texMathZoneE and texMathZoneX. However, I do not know how to use this in order to make context sensitive mappings or abbreviations.

Perhaps like this:

let s:TeXmaps = {
\ 'a': '\alpha',
\ 'b': '\beta',
\ '->': '\to',
\ '=>': '\Rightarrow' }

function! <SID>IsTeXMath()
return &ft ==# 'tex' && match(map( synstack(line('.'), col('.')), 'synIDattr(v:val, "name")' ), '\m^texMathZone[EX]\$') >= 0
endfunction

for s:k in keys(s:TeXmaps)
silent! exec 'inoremap <silent> ' . s:k . ' <C-r>=<SID>IsTeXMath()?' . string(s:TeXmaps[s:k]) . ':' . string(s:k) . '<CR>'
endfor

• It would probably be better to use buffer-local abbreviations on just tex filetypes instead of a global abbreviation that checking 'filetype'. – Peter Rincker May 27 '15 at 17:27
• @Peter Rincker: Yes, it's just a proof of concept. It can be optimised in many ways, f.i. by finding the numeric IDs for texMathZoneE and texMathZoneX beforehand. – lcd047 May 27 '15 at 18:16

lh-brackets provides the Map4TheseContexts() function that takes care of detecting the context to do different things.

" To be defined in a tex ftplugin -> ~/.vim/ftplugin/tex/your-shortcuts.vim
:inoremap <buffer> <silent> a <c-r>=Map4TheseContexts('a', 'texMathZone', '\\alpha', 'a')<cr>
" or:
:inoremap <buffer> <silent> <expr> a Map4TheseContexts('a', 'texMathZone', '\\alpha', 'a')


Note: If you have installed latex-suite, you'll have instead to use its IMAP() function to define your new mappings -- this is because latex-suite is quite intrusive regarding mappings.

• I'm developing my own LaTeX-plugin (see link in the question). I've found latex-suite is way to complex and intrusive in general. The IMAP-functionality is not that bad, although I prefer to instead use something like UltiSnips for complex snippets. – Karl Yngve Lervåg May 27 '15 at 10:59
• IMAP() was interesting to define mappings, but mappings are harder to maintain than snippets/templates. – Luc Hermitte May 27 '15 at 11:14