I met the problem in VIM that `[y`] yanked the text between `[ and `] but lost the last character.

To reproduce:

  1. put the cursor on some word in normal mode.
  2. press yiw
  3. run :echom @@ to see the word is yanked correctly
  4. press `[ and `] to see the marked positions, normally `[ is at the start of the word, `] is at the end of the word.
  5. press `[y`]
  6. run :echom @@ again. This time the word is yanked but last character lost.

Any ideas about this? Thanks :)

(VIM version: 7.4 and 8.1)

(Gnome Terminal and tmux tested on Ubuntu 18.04 and 16.04)

  • Not reproducible with vim 8.1 – wurtel Jul 30 '19 at 7:45
  • 1
    Really? I just updated my vim to version 8.1, but still found the problem existed. @wurtel – Porcupine Andrew Jul 30 '19 at 9:19
  • @wurtel It's possible you didn't reproduce it because you used yw (which will place the <code>`[</code> mark at the start of the next work) instead of yiw (which will place it at the end of the current one.) See my answer for more details. – filbranden Jul 30 '19 at 21:26
  • @PorcupineAndrew You might want to check out the Vi and Vim Stack Exchange for questions on Vim! – filbranden Jul 30 '19 at 21:27
  • @filbranden I misread, I did y1w. I need to increase the font size on my browser :( – wurtel Jul 31 '19 at 7:18

This is actually expected. TL;DR: Use `[v`]y instead.

The `[ motion is exclusive. See :help mark-motions, which says:

With ` (backtick): The cursor is positioned at the specified location and the motion is exclusive.

Using visual mode instead, with `[v`]y, will typically work. It is actually controlled by the 'selection' option, but that defaults to "inclusive", so it's typically fine. (And if you want to make sure, you can temporarily reset it inside a function.)

See an example in Vim's manual under :help g@, which uses:

function! CountSpaces(type, ...)
  let sel_save = &selection
  let &selection = "inclusive"
  silent exe "normal! `[v`]y"
  let &selection = sel_save

Also, this section from Learn Vimscript the Hard Way, which briefly touches on the subject. (More importantly, it uses the same idiom. You'll also find this same idiom in many Vim plug-ins.)

  • 1
    Thanks for you help! Pitifully I couldn't vote for your answer for now due to my poor reputation. Actually this question was raised just after I read Learn Vimscript the Hard Way, one chapter after what you mentioned, where the author changed `` [v]y `` to `` [y] `` but didn't mention this feature, so I was confused. I should have checked manual first. – Porcupine Andrew Jul 31 '19 at 2:06
  • @PorcupineAndrew Glad this helped! It wasn't that easy finding the right part of the manual that explains this behavior, so don't worry. Cheers! – filbranden Jul 31 '19 at 2:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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