This is a very interesting question, but I'm not sure that your suggested approach is the best way! I have attempted an answer, but this first iteration may not be perfect. I am assuming that a LaTeX environment is simply delimited by \begin
and \end
commands (my LaTeX is a bit rusty!).
Firstly you need a function to return the environment of the cursor position. My function below jumps to the previous \begin
command, then jumps forward to the matching \end
command, calculates whether the cursor is inside this region, and continues the process until a containing environment is found. It should handle nested environments. If not in a LaTeX environment, an empty string is returned.
function! GetTeXEnv()
let pos = getpos('.')
let win = winsaveview()
let env = ''
let carry_on = 1
let search_ops = 'bWc'
let b_start = line('.')
while carry_on
keepjumps let b_start = search('\\begin{',search_ops)
let search_ops = 'bW'
" Only accept a match at the cursor position on the
" first cycle, otherwise we wouldn't go anywhere!
let env = matchstr(getline('.'),'\\begin{\zs.\{-}\ze}')
let env_esc = escape(env,'*')
keepjumps let b_end = search('\\end{\s*' . env_esc . '\s*}','Wn')
if b_start == 0
" finished searching; stop
let carry_on = 0
elseif b_end > b_start && b_end < pos[1]
" not inside this env; carry on
let env = ''
elseif b_end > b_start && b_end >= pos[1] && b_start <= pos[1]
" found it; stop
let carry_on = 0
endif
endwhile
call setpos('.',pos)
call winrestview(win)
return env
endfunction
Now you can enquire the environment of the cursor using :echo GetTeXEnv()
.
To change the behaviour of the =
key, you need to create another function which returns &=
in the align environment, and =
otherwise:
function! TeXEquals()
return GetTeXEnv() =~ 'align\*\?' ? "&=" : "="
endfunction
Then you can remap =
in insert mode (for TeX files only)
autocmd FileType tex inoremap <silent> = <c-r>=TeXEquals()<CR>
This seems to work in my example LaTeX file. Let me know if you find any problems, or have any ideas for improvements.