Enable Syntax Highlighting in Vim
Using Vim for reading or writing scripts and code? Enable syntax highlighting in Vim for a better experience.
— Team LHB
When you have to edit multiple files in Vim from your terminal, it is nice to have the syntax of the file contents to be highlighted.
To enable syntax highlighting in Vim while you are using it, enter the normal mode using Esc key and then type:
:syntax on
That's easy, right? Let me provide more details on how it works and how you can make this change permanent.
Syntax highlighting in Vim
Syntax highlighting refers to coloring a group of words, like keywords, differently than other groups of words, like variable names etc.
With that, you can easily differentiate between two words, if it's a keyword, data, variable, constant etc.
Syntax highlighting in Vim is not only limited to scripting languages (like sh
, bash
etc) and programming languages (like python
, rust
, c
, cpp
etc).
I used Vim to edit my apache2.conf
and smb.conf
, I can tell you that it works with pretty much all file types.
If you already have opened a file in Vim, below are the steps to turn on syntax highlighting:
- Press the Escape (Esc) key to enter Normal mode in Vim.
- Type the colon
:
symbol to indicate that you're typing a command. - After the colon, type
syntax on
.
Here, you can see the plain white lines changing colors after turning on syntax highlighting in Vim.
Enable syntax highlighting by default
If you end up liking syntax highlighting and want to make this change permanent, you can add the following line in your 'vimrc' (should be located at ~/.vimrc):
syntax on
If you are having troubles with Vim not detecting certain file types, add the following line to your 'vimrc':
syntax on
filetype on
Turn off syntax highlighting
For whatever reason, if you dislike the syntax highlighting, you can turn it off by following the steps given below:
- Press the Escape (Esc) key to enter Normal mode.
- Type the colon
:
symbol to tell Vim to interpret next keyboard strokes as a command. - Now, type
syntax off
.
Conclusion
Vim has the feature to highlight syntax of a particular file type using different colors. We went through how to enable it, make it permanent and how to disable it as well.
If you are interested in learning more than just the Vim Basics, I highly recommend using this program by Jovica Ilic.
Team LHB indicates the effort of a single or multiple members of the core Linux Handbook team.