Basically I want to access the last \w\+ in my current insertion. (Hence I asked this question.)

Another solution I thought of was something like the following (I'm echoing, but clearly I'd pass it to a function in my real usecase¹):

augroup Foo
  autocmd TextChangedI,TextChangedP * echo '<' . expand('<cword>') . '>'
augroup END

but it doesn't, as it prints <> while I type, and it does put some word in between < and > when I go insert mode, ... but not always. So I think I've not really understood what <cword> is and what makes it change.

(¹) I have come up with a fairly complex solution, whereby I pass col('.') to the function in the autocmd (the one taking the palce of the echo in the toy example above) and use that to regex-match the last word being written.

  • You might try <C-r><C-w>?
    – D. Ben Knoble
    Jun 4, 2023 at 13:54

1 Answer 1


<cword> is mostly a command-line mode thing, not an insert mode thing. I don't think it is reliable in this context.

Here is how I would approach the initial problem:

augroup Foo
  autocmd TextChangedI,TextChangedP * echom getline('.')->matchstr('\w\+\%.c')
augroup END


  • :help getline() grabs the text of the given line,
  • :help matchstr() returns the part of it that matches the given pattern,
  • \w\+\%.c matches as many word characters as possible (\w\+) before the cursor (\%.c is a zero-width match).

Issues left for OP to figure out:

  • This grabs the word before the cursor, which is not necessarily the word that is being inserted. Leaving a mark on InsertEnter and using that to anchor the pattern might help.
  • "pettern"… sigh.
    – romainl
    Jun 5, 2023 at 16:15

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.