TransWikia.com

How to recover the color to previous status?

Vi and Vim Asked on August 31, 2021

I wrote a function to show some special characters with red color:

function! ShowChar()
    set list
    set listchars=tab:→ ,space:·,nbsp:␣,eol:¶
    highlight SpecialKey ctermfg=blue ctermbg=red guifg=blue guibg=red
endfunction
map <f5> :call ShowChar()<CR>

When to press f5, the characters — tab, space, nbsp, eol will be shown with red color, now I want to design a new function key f6, when to press f6 after pressing f5, all the special characters will be shown as previous status, not with red color.
Should I write a new function which called by f6?

3 Answers

set listchars=tab:→ ,space:·,nbsp:␣,eol:¶
highlight SpecialKey ctermfg=blue ctermbg=red guifg=blue guibg=red
nnoremap <f5> :set list!<CR>

Answered by showkey on August 31, 2021

I assume you use termguicolors:

if has("termguicolors")
  set termguicolors
endif

You can use this to store the colors of the SpecialKey group each time your colorscheme changes:

augroup SaveSpecialKeyColors
  au!
  au ColorScheme,VimEnter *
         let g:specialkey_fg = synIDattr(hlID('SpecialKey'), "fg#") |
         let g:specialkey_bg = synIDattr(hlID('SpecialKey'), "bg#")
augroup end

And a function to toggle:

set listchars=tab:→ ,space:·,nbsp:␣,eol:¶

function! SpecialKeyToggle()
  if &list == ""
    set list
    highlight SpecialKey guifg=blue guibg=red
  else
    exe "highlight SpecialKey guifg= " g:specialkey_bg "guibg= " g:specialkey_bg
  endif
endfunction

nnoremap <f6> :call SpecialKeyToggle()<CR>

You could have a mapping to toggle list (stole this one from tpope's unimpaired):

nnoremap yol setlocal list!

nnoremap is good practice: you only need this function in normal mode (n), and don't want it to be recursive (nore).

Answered by Biggybi on August 31, 2021

function! SpecialKeyWarning()
    set list
    set listchars=tab:→ ,space:·,nbsp:␣,eol:¶
    highlight SpecialKey ctermfg=blue ctermbg=red guifg=blue guibg=red
endfunction
map <f5> :call SpecialKeyWarning()<CR>

function! SpecialKeyNormal()
    set  nolist 
endfunction
map <f6> :call SpecialKeyNormal()<CR>

Answered by showkey on August 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP