A Vim question!
A great one, too!
In Vim, :wd! is a write command with some interesting twists. Let's break it down:
:w is the basic write command, which saves the current buffer (i.e., the file you're editing) to disk. Think of it as "write the changes to the file".
d is not a command by itself, but rather a directory specification. When you add d after :w, Vim interprets it as write to directory. Specifically, :wd means write the file to the current working directory.
Now, here's where it gets juicy:
! is Vim's force or override modifier. When appended to a command, it tells Vim: "Do this, even if it seems crazy or might cause issues". Think of it as "override any warnings or checks".
So, putting it all together:
:wd! means:
Write the current buffer (:w) to the Directory (d) where Vim thinks the file originally came from (more on this in a sec) ! (override any checks, just do it).
Here's the magic part: when you use :wd!, Vim will:
- Discard the current file path: Forget the original file path (e.g.,
/path/to/original/file.txt) associated with the buffer.
- Write to the current working directory: Save the file to the current working directory (CWD), which you can see with
:pwd (print working directory). If the CWD is, say, ~/Documents, Vim will write the file there.
- Use the original file name: Keep the original file name (e.g.,
file.txt).
In short, :wd! saves the file to the current working directory, using the original file name, and overrides any checks.
Example:
- You're editing
/path/to/original/file.txt in Vim.
- Your current working directory (
:pwd) is ~/Documents.
- You run
:wd!.
- Vim will save the file as
~/Documents/file.txt, not modifying the original /path/to/original/file.txt.
Why is this useful?
- Quickly save a temp version: If you're experimenting with changes and want to save a temporary copy of the file in your CWD,
:wd! is faster than :w new_path/new_file.txt.
- Duplicate a file: Open a file, make some changes, and use
:wd! to create a copy of the modified file in your CWD, without altering the original.
- Save a file when permissions are dodgy: If Vim complains about not being able to write to the original file (e.g., due to permissions issues),
:wd! saves the file to your CWD, bypassing those issues.
Now, go ahead and wield :wd! like a Vim ninja!
Bonus tip: If you just use :w!, it forces Vim to overwrite the original file (if possible), whereas :wd! saves a new copy in the CWD.
Happy Vimming!