Search code examples
vimcountcharacterstatusbar

How to check if function is active on statusbar?


I added this function in _vimrc to count characters while typing:

   function! Count2Cursor()
      let mycount2cursor = strlen(substitute(join(add(getline(1,line('.')-1),strpart(getline('.'),0,col('.')-1)),'.'),'.','.','g'))+1
      return mycount2cursor
    endfunction

This is the code to activate it on the statusbar:

:set statusline+=%1*\ Chars2Cursor:\%{Count2Cursor()}

This is the code to disable it on the statusbar:

:set statusline-=%1*\ Chars2Cursor:\%{Count2Cursor()}

What I want to do is to integrate both lines (activate/disable) in one line: Toggle Chars2Cursor.
How can I check if the code is activated/disabled on the statusbar?


Solution

  • You can access the current value of 'statusline' option via &statusline. Pattern matching will then tell you whether it already contains your function.

    :command! ToggleChars2Cursor
    \   if &statusline =~# 'Chars2Cursor' |
    \       set statusline-=%1*\ Chars2Cursor:\%{Count2Cursor()} |
    \   else |
    \       set statusline+=%1*\ Chars2Cursor:\%{Count2Cursor()} |
    \   endif