Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

function - 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, '$'), "
")
    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).

question from:https://stackoverflow.com/questions/66051261/how-to-the-display-the-number-of-instances-of-a-string-in-vim-statusline

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...