I have a file full of text (say Markdown or LaTeX). I would like to count the number of words in a part of this file. I know I can do :! wc -w % to run wc -w on the current buffer. And I know that I can yank the section of interest into a named register. I'm guessing there's a way to send a named register to the operating system for use in a command or pipe, but I haven't been able to find one. Or is there a better way to count the words in a register?My use case is that I do a lot of non-programming writing (notes, thesis, etc) in vim, and I would like to count how many words I've added to a given section of the file in the middle of an editing session.
How do I count the words in a part of a file, without leaving vim?
external command;count
You can use gCTRL+g, which will give you:Col 1 of 118-121; Line 1 of 5; Word 1 of 142; Byte 1 of 678You can also use this from visual mode, if you want to get the word count for just the selection, which is especially useful combined with text objects such as ip. (e.g. you can use vipg<C-g> to get the word count of the current paragraph).See: :help word-count and :help text-objects.The above option is probably better, but you can also use wc utility to count the number of words in a section. Aside from the :! wc -w % form you use, you can also use:%!wc -w. This will filter a motion to a shell tool (in this case %, the entire buffer), but you can also use other ranges (such as :1,5!wc -w for the first 5 lines, !,+5!wc -w for the current and next 5 lines, etc.). You can also select text in visual mode, and type :!wc -w to filter your selection.Note that this will replace the motion with the output of the shell tool, but you can u to undo this.See :help :range!, :help range, and this answer where I give more examples of ranges.