How might one write a command that toggles between the settings hi Normal ctermfg=8
and hi Normal ctermfg=12
?
1 Answer
I think you could add this code to your $MYVIMRC
file :
nnoremap <leader>t :call ToggleForegroundColor()<CR>
function! ToggleForegroundColor()
let fgcolor=synIDattr(hlID('Normal'), 'fg#')
if fgcolor == 8
hi Normal ctermfg=12
else
hi Normal ctermfg=8
endif
endfunction
After saving and sourcing it, you should be able to toggle between the two values by pressing <leader>t
.
If your <leader>
is the comma key, it would be ,t
.
You can define your <leader>
key in your $MYVIMRC
file with something like this :
let mapleader = ","
To explain the code :
nnoremap <leader>t :call ToggleForegroundColor()<CR>
This line maps <leader>t
to a function called ToggleForegroundColor
.
The function is defined just afterwards and is responsible for toggling the value of the ctermfg
argument.
let fgcolor=synIDattr(hlID('Normal'), 'fg#')
This line assigns to the variable fgcolor
the value of the foreground color number of the Normal highlight group (ctermfg
if you're inside a terminal, guifg
if you're inside gvim).
For more information about the built-in functions used here, you can have a look inside the help : :h synIDattr
and :h hlID
.
The rest of the code is a simple if else endif
structure which tests the value of fgcolor
to change the value of ctermfg
accordingly.