Execute <Plug> commands in vim

20,811

<Plug> mappings are meant to be mapped and called via the map. A <Plug> map is a device to expose a clean interface of plugin actions to the user.


Example: Instead of mapping some key to some plugin function in the plugin's hard code, such as "map zz to the action 'center cursor aesthetically'":

nnoremap <expr> zz 'zz'.float2nr(winheight(0)*0.1).'<C-E>'

it is better to expose only a named <Plug> mapping from the plugin:

nnoremap <expr> <Plug>NiceCenterCursor 'zz'.float2nr(winheight(0)*0.1).'<C-E>'

that the user can then remap in their config, without having to copy and paste the "action":

nmap zz <Plug>NiceCenterCursor

This is then easy to override, reuse, plug into by the user.


<Plug> mappings are active only in the modes they have been defined for. To execute a <Plug> mapping that is defined for normal mode, you can do as with any normal command: use :normal (without the exclamation mark).

:execute "normal \<Plug>NiceCenterCursor"

Since <Plug> actually represents a special magic key, we need to use :normal together with :execute and escape the <Plug>.

The <Plug> mechanism is described in depth at :h 41.11. See also this article about this topic by a Vim master.

Share:
20,811
Tarrasch
Author by

Tarrasch

I'm interested in functional programming, utilizing type systems and big data. I'm also the chief maintainer of the popular Luigi task orchestrator

Updated on June 16, 2021

Comments

  • Tarrasch
    Tarrasch almost 3 years

    I've recently found a vim plugin using something called <Plug>. For example there is a command <Plug>abc_def which I would like to execute.

    I've tried everything like :<Plug>abc_def and similar. Nothing worked. And :help <Plug> gave no information.

    However, I've been able to execute it by creating a mapping :map x <Plug>(unite_redraw). Then I can execute it by pressing x.

    Now, is there any way to execute :<Plug>abc_def without creating a dummy mapping just to run it? The actual plugin I use is Unite.

  • Tarrasch
    Tarrasch over 10 years
    Oh, so it's essential that the nmap is nmap and not nnoremap, because it will think of <Plug>NiceCenterCursor as just another mapping. Correct?
  • glts
    glts over 10 years
    @Tarrasch Exactly, the right-hand side of the map must be remapped for this to work. Same with :normal: it's essential to use the (remapping) :normal, not the non-remapping :normal!.
  • jdhao
    jdhao about 5 years
    The specific part about <Plug> is here.
  • roachsinai
    roachsinai almost 3 years
    Thanks for your post! But, how is it compare with create a command?