2

I'm using vim to write documents and trying to get word count to exclude anything that is delimited by brackets, which I use for notes or comments that are not a part of the document. So I don't want them to be counted.

Is there a tool or way to customize the word count so that it will exclude any text delimited by brackets?

For example, [I want this part to NOT be included in the count].

3
  • Do you mean the wordcount() function? If so, probably the simplest thing to do is filter the buffer to remove the bracketed text, run the wordcount, then restore the removed text. Otherwise I'm not sure what you mean by word count. wc? Another tool?
    – D. Ben Knoble
    Jul 10, 2021 at 19:58
  • I use g Ctrl-g for the word count. I don't know which function it uses behind the scenes.
    – aris
    Jul 11, 2021 at 1:29
  • not really possible, except for clunky work-arounds like actually filtering your buffer, or copying all your text and post-process it Jul 12, 2021 at 9:23

1 Answer 1

1

You'll have to write a bit of custom code for this:

:echo getline(1, '$')->join(' ')->substitute('\[.\{-}]', ' ', 'g')->split('')->len()

getline(1, '$') gets all lines as an array, join(' ') joins all the lines to a single string, substitute('\[.\{-}]', ' ', 'g') replaces everything between […] with a space, split('') splits the string to an array on whitespace, and len() gets the array length (i.e. the word count).

You can of course map this to a command or keybind:

:command WordCount :echo getline(1, '$')->join(' ')->substitute('\[.\{-}]', ' ', 'g')->split('')->len()

nnoremap <Leader>w :echo getline(1, '$')->join(' ')->substitute('\[.\{-}]', ' ', 'g')->split('')->len()<CR>

You can, if you want to, also override the default g<C-g> mapping, and use a bit more advanced code to duplicate the functionality from g<C-g>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.