Vim Recipes Display Redefining Highlight Groups

Redefining Highlight Groups

Problem

You want to change the colours of specific elements of the display. For example, you want text to be white on a black background.

Solution

Use the :highight group definition command.

A highlight group (group) is an element of the display whose colours can be customised. Some of the default highlight groups are:

Is a list the right way to present this?

Cursor
Character under the cursor.
ErrorMsg
Command line error messages.
Normal
Normal text.
Visual
Text selected under Visual mode.

The definition is a list of key-value pairs. For example, the following sets the terminal foreground colour to black and the terminal background colour to yellow:

:highlight Normal ctermfg=black ctermbg=yellow

These are some common arguments:

ctermfg
Terminal foreground colour.
ctermbg
Terminal background colour.
term
Terminal font style, e.g. bold, italic, underline.
guifg
GUI foreground colour.
guibg
GUI background colour.

Apart from term, these arguments take a colour name or number as a value. Recognised colour names include black, brown, grey, blue, green, cyan, magenta, yellow, and white.

The arguments that are not supplied retain their previous values. For example, :highlight Normal\ ctermbg=white changes the background colour to white, but keeps the previous foreground colour.

Let's look at some examples:

Discussion

Normally you'll select a colour scheme, and not define highlighting groups at all. Occasionally, though, you want more control over colours or need to edit a syntax file. That's where the :highlight command comes in.

Before you change highlight groups you may like to check their current values. You can do this with :highlight group. To view all current settings use :highlight.

Defining a Highlight Group

You can define your own highlight group by using the :highlight command as described above with a group name of your choice. To select what is highlighted you use :match group /pattern/. For example:

:highlight Elephant ctermbg=grey ctermfg=white
  :match Elephant /\celephant/

This renders all occurrences of the word elephant, regardless of case due to the \c escape, in white on grey.