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

How do I quickly delete all lines in the current buffer?

Answer

:%d

Explanation

The % range address in Ex commands stands for the entire file — it is shorthand for 1,$ (first line to last line). This makes :%d the fastest way to wipe a buffer clean, but the same principle unlocks many other powerful whole-file operations.

How it works

  • % is an Ex range meaning "all lines in the buffer"
  • It can be combined with any Ex command that accepts a range

Common uses:

:%d           " delete all lines (clear the buffer)
:%y           " yank (copy) the entire file into the unnamed register
:%s/foo/bar/g " substitute across every line (most common use)
:%!sort -u    " filter the whole file through an external command
:%!python3 -m json.tool  " format JSON in place

Example

To replace the content of the current buffer with formatted JSON:

{"name":"alice","age":30}

Run :%!python3 -m json.tool to get:

{
    "name": "alice",
    "age": 30
}

Tips

  • :%y + yanks the whole file into the system clipboard register (+)
  • :%!sort sorts all lines alphabetically in place — no visual selection needed
  • Combine with line-address modifiers: :%s/^/ / adds two-space indentation to every line
  • Use 1,$ as an explicit equivalent if you want to make the range visible in your command history

Next

How do I get just the filename without its path or extension to use in a command?