Search code examples
vim

Is there a way to get string representation of boolean option in vim?


I'm using AppendModeline function to add a modeline to my vim files:

" Append modeline after last line in buffer.
" Use substitute() instead of printf() to handle '%%s' modeline in LaTeX
" files.
function! AppendModeline()
  let l:modeline = printf(" vim: set ts=%d sw=%d tw=%d :",
        \ &tabstop, &shiftwidth, &textwidth)
  let l:modeline = substitute(&commentstring, "%s", l:modeline, "")
  call append(line("$"), l:modeline)
endfunction

But I want to extend it. It shall support adding the current value of expandtab.
Using &expandtab, I can get a numeric representation of the current value. But something like set et=0 isn't supported by vim. It has to be set [no]expandtab.
Do I really have to test for &expandtab and append expandtab or noexpandtab to l:modeline or is there a way to get a string representation of the current value?
set expandtab? shows [no]expandtab, but I don't know how to use this in a script (or if it's even possible).


Solution

  • Yes, you have to do this. With :redir it is possible to capture output, but :redir-based solution is at least four lines long with regex to grab the value. Using &et is much cleaner:

    … printf("… %set …", …, &expandtab ? '' : 'no', …)
    

    Note: %set is %s followed by et (short for expandtab). Word set here is just an accident.