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

How do I show context lines around each match when using the :global command?

Answer

:g/pattern/z#.5

Explanation

The :global command is great for finding lines matching a pattern, but by default it only shows the matching lines themselves. By combining :g with the :z command, you can display surrounding context for each match — similar to grep -C in the shell. This is invaluable when reviewing matches in a large file where you need to understand the context around each hit.

How it works

  • :g/pattern/ — for every line matching the pattern, execute the following command
  • z — the "page" command that displays a window of lines around the current line
  • # — include line numbers in the output
  • .5 — show a window of 5 lines above and below the current line (the . means center on the current line)

Example

Given a config file where you want to find all timeout settings with context:

:g/timeout/z#.3

Output shows each match centered with 3 lines of context and line numbers:

 12  [database]
 13  host = localhost
 14  port = 5432
 15  timeout = 30
 16  max_connections = 100
 17  pool_size = 5
 18
---
 45  [cache]
 46  backend = redis
 47  timeout = 60
 48  max_memory = 256mb
 49

Tips

  • Change the number after . to control how many context lines appear (e.g., .10 for 10 lines)
  • Omit # if you do not need line numbers: :g/pattern/z.5
  • Combine with | to chain: :g/TODO/z#.3 | echo '---' adds separators between matches

Next

How do I ignore whitespace changes when using Vim's diff mode?