Hubro
Hubro

Reputation: 59333

Vim: How do I override a command with a new command that uses the old command?

My Ruby folding expression is causing auto-completion (<C-n>/<C-p>) to slow down dramatically, which is a massive pain. When I switch to manual folding, auto-completion becomes instant.

To work around that I'd like the folding to be "on demand", i.e. it only calculates folds when i do zx or zX. The plan:

  1. Set Ruby code default folding method to manual
  2. When opening a Ruby file, locally map zx to switch folding method to expr and run zx, then switch folding method back to manual
  3. Repeat #2 for zX

The issue is, when I've overridden zx, how do I call the "old" zx?


Perfect answer by Kent, here's my final working solution (ftplugin/ruby.vim):

if &filetype == 'ruby'
    setlocal foldmethod=manual
    nn <buffer> <silent> zx :set foldmethod=expr<CR>:norm! zx<CR>:set foldmethod=manual<CR>
    nn <buffer> <silent> zX :set foldmethod=expr<CR>:norm! zX<CR>:set foldmethod=manual<CR>
end

Upvotes: 0

Views: 222

Answers (2)

Ben
Ben

Reputation: 8905

Using the :noremap series of commands, rather than plain :map, you prevent any mappings from firing recursively. So you can safely call the "old" zx inside your mapping just by using zx directly. Example for your case:

nnoremap <buffer> <silent> zx :set foldmethod=expr<CR>zx:set foldmethod=manual<CR>

Upvotes: 3

Kent
Kent

Reputation: 195049

with :normal command, you can execute NORMAL mode command. And if you added a !, you will bypass mappings. For the example from yours,

:norm! zx

may help.

Upvotes: 2

Related Questions