How do I enable syntax highlighting in Vim?
Answer
:syntax on
Explanation
The :syntax on command enables syntax highlighting in Vim, colorizing your code based on the file type. This makes code dramatically easier to read by visually distinguishing keywords, strings, comments, functions, and other language elements.
How it works
:syntax ontells Vim to detect the file type and apply syntax highlighting rules- Vim uses the file extension, shebang line, or modeline to determine the file type
- Highlighting colors are determined by your current colorscheme
Example
Open a Python file and run:
:syntax on
Keywords like def, class, import are highlighted in one color, strings in another, comments in another, and so on. The exact colors depend on your colorscheme.
Making it permanent
Add this to your ~/.vimrc to enable syntax highlighting every time Vim starts:
syntax on
Most modern Vim distributions already have this enabled by default.
Tips
- Use
:syntax offto disable syntax highlighting - Use
:set syntax=pythonto manually set the syntax type if Vim does not detect it correctly - Use
:colorscheme desert(or any other scheme) to change the color theme — see all available schemes with:colorscheme <Tab> - Use
:highlightto view all current highlight groups and their colors - Use
:filetype onalongsidesyntax onfor better file type detection - If highlighting looks wrong, try
:syntax sync fromstartto re-synchronize from the beginning of the file - Use
:set background=darkor:set background=lightto tell Vim your terminal background color — this adjusts the colorscheme for better contrast - For large files, syntax highlighting can slow down scrolling — use
:syntax offtemporarily if you experience lag