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

How do I toggle a boolean Vim option on and off without typing the full :set option or :set nooption each time?

Answer

:set option!

Explanation

For any boolean option, appending ! to :set inverts its current value. This compact syntax is ideal for toggle keymaps in your vimrc and avoids the awkward pattern of checking the current state before deciding whether to set or unset the option.

How it works

  • :set {option}! flips the boolean option from on to off or from off to on
  • This is equivalent to :set {option} when off, or :set no{option} when on — Vim figures out which one to apply
  • Works with any boolean option: number, wrap, spell, hlsearch, list, cursorline, and more

Example

:set number!      " toggle line numbers
:set wrap!        " toggle soft line wrapping
:set spell!       " toggle spell checking
:set hlsearch!    " toggle search highlight

A common vimrc pattern is to bind frequently toggled options to a leader key:

nnoremap <leader>n :set number!<CR>
nnoremap <leader>w :set wrap!<CR>
nnoremap <leader>s :set spell!<CR>

Tips

  • To check the current state of an option without changing it, use :set {option}?
  • :set {option}& resets the option back to its compiled-in default value
  • For non-boolean options, ! has no effect — only boolean options can be toggled this way
  • In a mapping, combine with <silent> to suppress the status line echo: nnoremap <silent> <leader>n :set number!<CR>

Next

How do I run normal mode commands in a script without triggering user-defined key mappings?