I would like to have a mapping based on the latex environment I am in.

For example, I currently have ;b mapped (in insert mode) to add \textbf{} and put my cursor inside the curley brackets.

At the moment I have ;B mapped to do the same but with \mathbf{}. Unfortunately, I keep typing the wrong one. I'm sure in time I could get used to it but was wondering if it were possible to have one mapping, say ;b, and have it normally add \textbf{} but if I were in a maths environment it would add \mathbf{}.

To start with, if it added the maths version if it were between $ $ symbols on the same line or between \begin{equation} and \end{equation} on seperate lines, I should be able to extend it for other variations.


I would like to add that I work on a lot of different machines, often without internet access. I keep a copy of my vimrc on me at all times but I try to do as much as possible without plugins. It looks like vimtex might be an option but does anyone know how I could do it without a plugin?


One possibility is to use vimtex, which provides this possibility through the imaps feature, see :h vimtex-imaps, :h vimtex#imaps#add_map and e.g. :h vimtex#imaps#wrap_math. You could also use the internal API directly, if you know some vimscript, but I think the imaps feature might be easier to use. An example:

call vimtex#imaps#add_map({
  \ 'lhs' : 'alph',
  \ 'rhs' : '\alpha',
  \ 'wrapper' : 'vimtex#imaps#wrap_math'

call vimtex#imaps#add_map({
  \ 'lhs' : 'draw',
  \ 'rhs' : '\draw',
  \ 'wrapper' : 'vimtex#imaps#wrap_environment',
  \ 'context' : ['tikzpicture'],
| improve this answer | |
  • Thanks for your answer. Vimtex looks great but do you know of an option without plugins? – Jonathan Hodgson Apr 27 '17 at 12:42
  • No, sorry. The vimtex implementation relies on some relatively advanced code to parse the LaTeX structure, either through syntax or through text parsing, in order to determine if we are in mathmode or inside a given environment. That is, it is not too difficult to check for math mode, so you could try to extract the necessary code from vimtex with the wrap_math version. – Karl Yngve Lervåg Apr 28 '17 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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