Search code examples
vim

Vim yank span given column start and end position


I'm wondering in vim, when given a start and end column position, is there a way to yank corresponding content starts from the start position to end.

for example, given a line in vim

aaaabbbbcccc
  • start = 4
  • end = 8

I want the yanked content is bbbb

The visual mode does finish it, but I think there may a vim command for it


Solution

  • I think there may a vim command for it

    The v to enter visual mode, the motions to extend the area, and the y to yank are all "vim commands".

    Assuming the cursor is somewhere on the line, you can do this with visual mode:

    5|
    v8|
    y
    

    In command-line mode, it would look like this:

    :call feedkeys('5|v8|y')
    

    In a script, assuming the start and end are variable, it would look like this:

    call feedkeys(start .. '|v' .. end .. '|y')
    

    See :help | and :help feedkeys().

    Of note, yanking is exclusive in operator-pending mode so, if you want to yank up to and including column 8, you need to involve visual mode somehow, where yanking is inclusive. Explicitly, as above, or implicitly, with 5|yv8|. It doesn't really change anything to the problem at hand but it is a feature I don't often see mentioned. See :help forced-motion.