In the buffer
You are writing a README and the usage text already exists in usage.txt. The cursor is on the ## Options heading. Before:
# deploy
Ships the site to S3.
## Options
^
## License
After typing :r usage.txt and <CR>:
# deploy
Ships the site to S3.
## Options
Usage: deploy [--dry-run] <env>
^
--dry-run print actions, change nothing
## License
Both lines of usage.txt appear below the cursor line, and the cursor moves to the first of them. usage.txt is not changed, and the buffer is only modified, not saved.
When you would reach for it
The text you need is already in a file: a license header, a boilerplate block, a saved snippet, a log you want to quote. The usual route is to open it in another window, yank, switch back, and paste, which costs a register and a few window hops. :r does it in one command without leaving the buffer, and because it is an ordinary change, one u takes it all back out.
Gotchas
:ralways inserts whole lines below a line. It never splits the current line at the cursor, so the cursor column does not matter. To put text above line 1, use:0r.- A bare
:rwith no file name reads the current file from disk. In a buffer that matches the file, you end up with the whole file doubled. In a modified buffer, it pulls in the last saved version, which is handy for comparing, and surprising if you hit enter too early. - If the file does not exist, vim reports
E484: Can't open fileand the buffer is left alone. Relative paths are resolved from vim’s working directory (:pwd), not from the directory of the file you are editing. Use%:h/usage.txtto read relative to the current file. - The file’s line endings and encoding are detected the same way they are when opening a file. If a Windows file brings in
^Mcharacters, read it with:r ++ff=dos usage.txt.
Variants
:0r LICENSE
Puts the file above line 1. The quickest way to prepend a license header to a source file.
:$r footer.txt
Appends the file after the last line, wherever the cursor is. Any line number or mark works as the address, such as :'ar notes.txt.
:r !date
Reads the output of a shell command instead of a file. Note the space before !. :r!date works too, but :w !cmd and :w!cmd mean very different things, so the spaced habit is worth keeping. This runs a program on your machine, so read the command before you press enter.