0

Objective

I am working on writing a keymap through lua script in Neovim:

  • First, selecting some words in visual mode and, in the corresponding lua script, trying to get the value of vim.fn.wordcount().visual_words which I expect it return the word count in my selected region for later usage.
  • Then, (keep the selected text in visual mode from the previous step,) use the keymap to do something.

I've found some information as follows

  1. https://neovim.io/doc/user/builtin.html#wordcount()
  2. https://neovim.io/doc/user/editing.html#v_g_CTRL-G

What I tried

For trial, for instance, in a file containing the text

,,,, ,,, ,,,,, ,,  ,,,

:lua print(vim.fn.wordcount().words) gives 5 in status massage (v:statusmsg).

However, when I tried to get vim.fn.wordcount().visual_words after selecting some text (shown by being surrounded by a pair of |) as follows

,,,, ,,, |,,,,, ,,  ,,,|

both of :'< '> lua print(vim.fn.wordcount().visual_words) or :lua print(vim.fn.wordcount().visual_words) (manually delete '< '>) give nil.

For the same selected text (in visual mode), the keystroke g<C-g> and then :echo v:statusmsg gives the result Selected 1 of 1 Lines; 3 of Words; 13 of 25 Bytes.


It seems that I use vim.fn.wordcount().visual_words in the wrong way but the manual https://neovim.io/doc/user/builtin.html#wordcount() doesn't explicitly guide us the correct way to use.

How can I use the information from vim.fn.wordcount().visual_words in lua? Could someone help? Thanks.

2
  • 1
    help topic for wordcount is a direct replica of what vim has and in vim it might be called using <cmd>, e.g. xnoremap <c-l> <cmd>echow wordcount()<CR>.
    – Maxim Kim
    Apr 2 at 6:45
  • Thanks! It helps!
    – HRC
    Apr 7 at 10:21

1 Answer 1

0

As Maxim Kim commented, using : exits visual mode, and wordcount() will not have the key .visual_words (since that is only available in visual mode). The workaround is to use <cmd> in the mapping, such as

xnoremap <C-l> <cmd>echo wordcount().visual_words)<CR>

In lua, this would be

vim.keymap.set('x', '<C-l>', "<cmd>lua print(vim.fn.wordcount().visual_words)<CR>")
1
  • Thanks for replying; it really helps!
    – HRC
    Apr 7 at 10:22

Your Answer

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

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