Ori Popowski
Ori Popowski

Reputation: 10662

How to specify the line under cursor in Vim?

I want to count number of occurrences of the line under the cursor. I intend to do it with the

:%s/pattern/&/gn

command. So how do I specify the line under cursor in place of pattern?

Upvotes: 1

Views: 497

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172520

If you're looking for a canned plugin solution, my SearchPosition plugin can count occurrences. With it, V<A-m> will show a summary like this:

On sole match in this line, 8 following, 2 in previous lines; total 10 for /this line\n/

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172520

You can insert the current line via the expression register. For a literal match, switch the regular expression to very nomagic mode (\V), and escape any backslashes and the separator in the line:

:%s/\V<C-r>=escape(getline('.'), '/\')<CR>/&/gn

Depending on what you want to count exactly, you may also need to anchor (\^...\$ in very nomagic mode) the pattern.

Instead of direct insertion via <C-r>, you can also build the command via :execute. This is more suitable in a function.

:execute '%s/\V' . escape(getline('.'), '/\') . '/&/gn'

Upvotes: 3

Related Questions