3

To turn on syntax we normally use: :syntax on and to turn it off we do: :syntax off. I would like to define a single key, maybe using <expr> to toggle syntax. My problem is how to get the current syntax state, so I can use it in a ternary operator.

Something like this:

nnoremap <expr> <Leader>s SyntaxState() ? ":syntax off" : ":syntax on"
4

You actually want syntax enable (for good reasons which I’ll leave to the :help to explain).

I created this custom command to toggle syntax; you could adjust the mapping similarly:

command SynToggle
      \ if exists("g:syntax_on") |
      \   syntax off |
      \ else |
      \   syntax enable |
      \ endif

This leaves you with

nnoremap <expr> <leader>s exists('g:syntax_on') ? ':syntax off<CR>' : ':syntax enable<CR>'
| improve this answer | |
  • Thanks! My actual command turned out to be: :nnoremap <expr> <Leader>s exists('g:syntax_on') ? ':syntax off<cr>' : ':syntax enable<cr>' . The idea is to leave more free keys to use in other situations. – SergioAraujo Apr 2 at 13:54
  • @SergioAraujo of course; keys was just a placeholder – D. Ben Knoble Apr 2 at 13:56
  • 1
    The big thing here is exists('g:syntax_on') all the rest depends on how we know vimscript, its logic etc. But anyway, our vimrc is becoming smarter, I think. Our community is growing because we have people willing to help, always! – SergioAraujo Apr 2 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.