Vim 切换映射

Vim 切换映射

我已设置映射如下:

"Set up mappings for LaTeX files 
let b:myEngine=0
let g:myEngineList=["pdflatex","texexec"] "pdflatex or context
function! ToggleEngine()
  if b:myEngine == "pdflatex"
        let b:myEngine = "context"
        execute "imap <F5> :! pdflatex %;<CR>"
        execute "map ;new \begin{document}<CR><CR>\end{document}"
  else
        let b:myEngine = "pdflatex"
        execute "imap <F5> :! context %;<CR>"
        execute "map ;new \starttext<CR><CR>\stoptext"
  fi
  echo "compilation engine:" g:myEngineList[b:myEngine]
endfunction

然而,这完全不符合我的预期;它拒绝重新映射按键。最初没有按键被映射,一旦被映射,它们就会保持映射状态。我该如何解决这个问题?

我按如下方式调用 ToggleEngine():nmap <silent> <F7> :call ToggleSpell()<CR>

答案1

你什麼時候call ToggleEngine()

建议:

"Set up mappings for LaTeX files 
let g:myEngineList=["pdflatex","texexec"] "pdflatex or context
function! ToggleEngine()
  if b:myEngine == "pdflatex"
     let b:myEngine = "context"
  else
     let b:myEngine = "pdflatex"
  fi
  execute 'inoremap <F5> :!' . b:myEngine . ' %<cr>'
  echo "spell checking language: " . b:myEngine
endfunction

答案2

基于lh-vim-lib,这里是另一个定义菜单和命令的解决方案(添加映射变得像从映射中调用命令一样简单)。

对于你来说,它看起来应该是这样的:

function! s:getSNR()
  if !exists("s:SNR")
    let s:SNR=matchstr(expand("<sfile>"), "<SNR>\\d\\+_\\zegetSNR$")
  endif
  return s:SNR 
endfunction


function! s:UsePdfLaTeX()
  set makeprg=pdflatex\ $*
  inoremap <buffer> <localleader>new \begin{document}<CR><CR>\end{document}
endfunction

function! s:UseContext()
  set makeprg=context\ $*
  inoremap <buffer> <localleader>new \startext<CR><CR>\stoptext
endfunction

let s:Data = {
      \ "variable": "myengine",
      \ "values": [ 'pdflatex', 'context' ],
      \ "actions": [ function(s:getSNR()."UsePdfLaTeX"), function(s:getSNR()."UseContext") ],
      \ "menu": { "priority": '42.42', "name": '&LaTeX.&Engine'}
      \}
call lh#menu#def_toggle_item(s:Data)
nnoremap <silent> <F7> :Toggle LaTeXEngine<cr>

注意:它可以扩展以支持您希望的任意多种替代方案。

相关内容