Write multiple copies at different paths, when you write to a buffer.

2 Points

Steven Fernandez Steven Fernandez

10 years ago

This is basically a copy of my tip at

http://vim.wikia.com/wiki/Write_multiple_copies_of_the_currently_edited_file

Sometimes you may need to keep multiple copies of the same file at different locations in sync. For instance, if you are editing the file ...

src/mysite/index.html

And you need to sync the changes in this file to ...

/var/www/mysite/index.html

...after each edit, or you have mounted two hosts using sshfs as:

/mnt/sshfs/host0/ and /mnt/sshfs/host1/

...and you'd like to simultaneously edit a file path/to/file.txt at the same location under the two directories.

Normally you would open -> edit -> :w <path1> <path2> ...etc. Instead you can simply open one of the files in vim and then before any edits, run the command

:autocmd BufWritePost <buffer> w! <path where the duplicate would be written>/%

This will ensure that everytime you write the changes to the current buffer, the same changes will also be written to the duplicate of the file.

If you happen to need this functionality often, you can add a custom command mentioned in the snippet section to your vimrc.

This will define a new command DuplicateAt which can be invoked as

:DuplicateAt /path/to/duplicate/at/

After which any writes to the current buffer will also be written to the file path of the current buffer under the directory /path/to/duplicate/at/.

Important Note: Using this snippet assumes the same file path as it was for the currently opened buffer. For example, opening a file, like so:

$ vi myproject/code/src.py

...and then doing...

:DuplicateAt /some/other/path

...will result in the files ./myproject/code/src.py and /some/other/path/myproject/code/src.py. This may or may not be what you expect.

command -nargs=1 -complete=dir DuplicateAt autocmd BufWritePost <buffer> w! <args>/%