Search code examples
vim

Inline comments in vimrc mappings


(I've asked the same question on superuser, but realized it wasn't the appropriate page for this question)

I'm cleaning up my .vimrc config and noticed that the section with mappings is excessively sparse due to some mappings having comments (for maintainability and future reference).

The problem is that you can't add a comment on the same line as a mapping, because it will be interpreted as continuation of right-hand side.

Example of current state (sparse):

" Do foo
nmap <Leader>f :foo<Return>

" Do bar
nmap <Leader>b :bar<Return>

Desired state (wrong!):

nmap <Leader>f :foo<Return>  " Do foo
nmap <Leader>b :bar<Return>  " Do bar

Is there a nice way of containing comment in the same line as the mapping?


Solution

  • You can use this method, but be sure to do not include space before |, because it will be the part of the mapping:

    nmap <Leader>f :foo<Return>|  " Do foo
    nmap <Leader>b :bar<Return>|  " Do bar
    

    The | separates commands in vim, thus the lines above works like this:

    nmap <Leader>f :foo<Return>
    " Do foo
    nmap <Leader>b :bar<Return>
    " Do bar
    

    If you want to use the | char in the mapping itself, then see the help of map_bar for additional information:

                                                            *map_bar*
    Since the '|' character is used to separate a map command from the next
    command, you will have to do something special to include  a '|' in {rhs}.
    There are three methods:
      use       works when                    example      ~
      <Bar>     '<' is not in 'cpoptions'     :map _l :!ls <Bar> more^M
      \|        'b' is not in 'cpoptions'     :map _l :!ls \| more^M
      ^V|       always, in Vim and Vi         :map _l :!ls ^V| more^M
    
    (here ^V stands for CTRL-V; to get one CTRL-V you have to type it twice; you
    cannot use the <> notation "<C-V>" here).
    
    All three work when you use the default setting for 'cpoptions'.
    
    When 'b' is present in 'cpoptions', "\|" will be recognized as a mapping
    ending in a '\' and then another command.  This is Vi compatible, but
    illogical when compared to other commands.