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.

2 Answers 2


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

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>'
  • It would probably be better to use buffer-local abbreviations on just tex filetypes instead of a global abbreviation that checking 'filetype'. Commented May 27, 2015 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
    Commented May 27, 2015 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. Commented May 27, 2015 at 10:59
  • 1
    IMAP() was interesting to define mappings, but mappings are harder to maintain than snippets/templates. Commented May 27, 2015 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.