'How to toggle automatic formatting with a single keybind in vim?

I'm trying to toggle automatic formatting in vim (e.g. enable with fo+=a if not enabled, disable with fo-=a otherwise) with a single keybind like so:

nnoremap <leader>a "magic goes here"

I thought about using some exists check with conditionals but I couldn't find any. How can I do this?

vim


Solution 1:[1]

The magic is the '&' in the snippet below

:help expr-option

nnoremap <leader>a call ToggleFormat()

function! toggleFormat()
      if &formatoptions !~ 'a'
          set fo+=a
      else
          set fo-=a
      endif
  return 0 
endfunction

Solution 2:[2]

Updated version of Lighthart's answer, incorporating a few tweaks:

function! ToggleFormat()
      if &formatoptions !~ 'a'
          set fo+=a
      else
          set fo-=a
      endif
      "" print the value of formatoptions once we're done
      set formatoptions
endfunction

"" End with <CR> to instantly run the function when triggered.
nnoremap <leader>a :call ToggleFormat()<CR>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lighthart
Solution 2 daviewales