How do I insert the contents of another file into the current buffer?
Answer
:r filename
Explanation
The :r filename command reads the contents of filename and inserts them into the current buffer below the cursor line. This is a quick way to pull in content from another file without leaving Vim or opening a new buffer.
How it works
:ris the read commandfilenameis the path to the file you want to insert- The file's contents are inserted on the line below the cursor
- The cursor moves to the first line of the inserted content
Example
Given the current buffer:
line one
line two
With the cursor on line one, running :r header.txt (where header.txt contains # My Header) results in:
line one
# My Header
line two
The contents of header.txt are inserted between the two existing lines.
Reading at a specific line
You can specify a line number before :r to insert the content after that line:
:0r filename— inserts the file contents at the very top of the buffer (before line 1):$r filename— inserts the file contents at the very end of the buffer:5r filename— inserts after line 5
Tips
- Use
:r !commandto insert the output of a shell command instead of a file — for example,:r !dateinserts the current date and time - Use
:r !lsto insert a directory listing into the buffer - Tab completion works with
:r— press<Tab>after typing part of the filename - Use
:rwith a URL if you havenetrwconfigured — e.g.,:r https://example.com/file.txt - The inserted content inherits the current buffer's filetype settings for syntax highlighting
- Combine with
:r !to capture command output for documentation, README files, or code generation