vimtricks.wiki Concise Vim tricks, one at a time.

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

  • :r is the read command
  • filename is 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 !command to insert the output of a shell command instead of a file — for example, :r !date inserts the current date and time
  • Use :r !ls to insert a directory listing into the buffer
  • Tab completion works with :r — press <Tab> after typing part of the filename
  • Use :r with a URL if you have netrw configured — 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

Next

How do I edit multiple lines at once using multiple cursors in Vim?