Enter image description here

This is my code in Vim. As the code comment describes, I want to remove highlight when the cursor moved. Currently, I highlight will remove when entering insert mode, but it can still be annoying.

Why doesn’t the code work? (I am very new to Vim script.)


2 Answers 2


Your code can't work because the while loop will be evaluated when your code is sourced (if you put it in your vimrc, it will be evaluated when vim starts and it sources your config). At this point it doesn't make sense to do stuff with highlighting.

The other issue is your use of getchar(): you can use it to detect which move the user is doing.

Instead you probably want to start by reading :h autocmd. Auto-commands are a way to execute some code on a specific event.

For example the auto command event :h CursorMoved triggers your code when the cursor moves. This is probably what you want to you.

The doc shows how to use auto commands and there are a lot of other questions on this site about how to use and debug them, I think now that you know about them you should be able to create one which will do what you want.

  • Thank you for your suggestion, Actually :h CursorMoved don't work as expected, when you searching the cursor is treated as moving. Feb 9, 2023 at 15:17
  • @Solarisending Why doesn't it work as you expect? Maybe if more context we can find a way to use it for what you want. But still my main point is that you can't use a while loop as you described in your question to do what you want.
    – statox
    Feb 10, 2023 at 13:39

I don't know how to fix your code, but I recommend https://github.com/romainl/vim-cool as a solution.

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.