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

How do I fix broken or incorrect syntax highlighting in Vim?

Answer

:syn sync fromstart

Explanation

When syntax highlighting goes wrong — miscoloring a function as a string, or treating half your file as a comment — it usually means Vim's syntax engine has lost track of context. Running :syn sync fromstart forces Vim to re-parse syntax from the very beginning of the file, restoring correct highlighting.

How it works

Vim uses sync rules to decide how much of the file to re-parse when you scroll. By default, it may only look back a fixed number of lines. In files with multi-line strings, heredocs, or deeply nested constructs, this shortcut can cause the parser to start mid-context and misidentify regions.

  • :syn sync fromstart instructs Vim to always re-parse from line 1, which is accurate but slower on very large files
  • :syn sync minlines=200 is a lighter alternative — tells Vim to look back at least 200 lines for context
  • :syntax reset followed by :syntax on is a more aggressive reset (reloads all syntax rules for the filetype)

Example

You open a Python file and see this:

result = calculate(
    data,           <- highlighted as string (wrong!)
    config           <- highlighted as string (wrong!)
)

After running :syn sync fromstart:

result = calculate(
    data,           <- highlighted as identifier (correct)
    config           <- highlighted as identifier (correct)
)

Tips

  • Map it to a key for quick access: :nnoremap <F12> :syn sync fromstart<CR>
  • Add :syn sync minlines=500 to your vimrc to make highlighting more robust by default for all files
  • For Neovim users, Treesitter-based highlighting rarely has this problem, but the command still works for non-Treesitter filetypes

Next

How do I refer to the matched text in a Vim substitution replacement?