Chong
Chong

Reputation: 963

How to use prewritten commands in Vim

Sometimes it's boring to rewrite similar commands over and over again, so I want to prewrite all of them, saving them into one customized command and use it once and for all. However, as the new command I'll use is only needed for the file I'm currently using, I really don't want to bother changing vimrc file. So here is my question, is it possible to prewrite a command into a file and load it into vim then use it for one time use? If possible, how to do it?

Thanks.

Upvotes: 1

Views: 140

Answers (4)

Ingo Karkat
Ingo Karkat

Reputation: 172540

To repeat a previous command quickly, you can try my redocommand plugin. It repeats the last command from the history that contains the passed pattern. Example:

:%substitute/foo/bar/g
" ... some time later ...
:R %s

With the built-in commands, you can start repeating the command (:%s), then complete the last such command with .

Upvotes: 1

Billy Chan
Billy Chan

Reputation: 24815

Well, if it's only for one time, there is a natural(normal) way

  1. Write your command in a single line in any file. You can yank it to any other file you want to work on.
  2. On this line, ^y$ to yank the code. Don't yy otherwise carriage will be yanked
  3. Go to command line by :, hit C-r " to paste it to command line. <CR> to profit.

A bit hassle but it works. I do that sometime as well:)

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172540

Without a concrete example, it's hard to advise. It sounds like you would like to define custom commands for a particular filetype, like this:

:command -buffer ComplexSubstitute %substitute/foo/bar/g

See :help user-commands. For the buffer-scope, put them into ~/.vim/ftplugin/<filetype>_commands.vim or so. With :filetype plugin on, these files are sourced automatically. Alternatively, you can define buffer-local :mappings in much the same way there.

Upvotes: 2

William Pursell
William Pursell

Reputation: 212248

Just source the file:

:source /p/a/t/h

Also, you can use an autocmd in .vimrc:

autocmd BufRead,BufNewFile *.whatever source /p/a/t/h

Or, rather than sourcing the file, just put the commands directly in the autocmd.

Upvotes: 5

Related Questions