Search code examples
vimex

How to automate an EX command in vim?


I have an EX command that I use pretty regularly to remove multi-line comments.

:%s,/\*\_.\{-}\*/\n,,g

Is there any way I can make it an EX alias (if such a thing exists?) in vimrc file?

The goal would be something like:

:nocomments

Then it would run that regex search and replace. Thanks!


Solution

  • The relevant help is :help usr_40.txt entitled 'Make New Commands'.

    Just put either of the below options in your .vimrc to make it permanent.

    40.1 Defining command-line commands

    For your question you can do this (note that user defined commands must begin with a capital letter):

    command! Nocomments :%s,/\*\_.\{-}\*/\n,,g

    40.2 Key mapping

    You can also define custom normal mode commands with nmap and nnoremap:

    nnoremap <LEADER>n :%s,/\*\_.\{-}\*/\n,,g<CR>

    Then in normal mode you can press your leader key (default is \ unless you remapped it) followed by the letter n and the substitute command will happen (note the carriage return had to be added).