functionvimstatusline

How to the display the number of instances of a string in vim statusline


A while ago I got to find a function to use in .vimrc to show if there ocurrances of " TODO " in the current buffer and show TD in the statusline. This is the function:

...
hi If_TODO_COLOR ctermbg=0 ctermfg=175 cterm=bold
set statusline+=%#If_TODO_COLOR#%{If_TODO()}
...

function! If_TODO()
    let todos = join(getline(1, '$'), "\n")
    if todos =~? " TODO "
        return " TD "
    else
        return ""
    endif
endfunction

My question is how can I modify the function to also return how many times the string has appeared in the buffer - somthing like TD (6).


Solution

  • You could :help filter() the lines to get a list of lines containing TODO:

    let lines = getline(1, '$')
    let todos = filter(lines, 'v:val =~? " TODO "')
    return len(todos) > 0 ? 'TD' : ''
    

    The same thing, expressed in a slightly more "modern" way:

    return getline(1, '$')
        \ ->filter('v:val =~? " TODO "')
        \ ->len() > 0 ? 'TD' : ''
    

    See :help method.