10

I try to save some selected text (part of a line) from Vim. Here is the line:

THIS TEST STRING - SELECTED_TARGET_WORLD

where the bold represents the select text. I do this:

:'<,'> w! test/selected_text

but in the file selected_text I find the string:

THIS TEST STRING - SELECTED_TARGET_WORLD

How do I make it save only the selected part of the line?

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
mgramin
  • 431
  • 8
  • 19

3 Answers3

5

:[range]w filename only works with lines so… you have to put the selected text on its own line.

An alternative using :help :redir:

:'<,'>"ay
:redir filename
:echo @a
:redir END
romainl
  • 186,200
  • 21
  • 280
  • 313
4

That case isn't documented in the help (:h :w) but :w handles only line ranges (you would have seen that on a example of multiple lines).

To do what you want, you will have to first paste your selection to a temporary buffer (or on its own line and then put it back in place) and then save that buffer. That can easily be automatized if it's something you're gonna do often.

rks
  • 920
  • 5
  • 12
  • 6
    It is documented, but it's mixed with the rich history of vi: All Ex commands only work on full line ranges; the visual selection is a Vim extension, and therefore somewhat at odds with the underlying model. – Ingo Karkat Sep 05 '12 at 14:09
4

I do it like this, FYR~

Once you've selected partial of your content by "Visual mode", press Ctrl-C to trigger it

vmap <C-c> y:new ~/.vimbuf<CR>VGp:x<CR>
chenkaie
  • 549
  • 3
  • 7
  • I've looked for an answer to this partial line question, and this is the easiest, fastest and most integrated with the vim function that work without weird caveats. Yes, you lose your "previous buffer" shortcut, but it's worth it. – Troy Fletcher Jul 10 '18 at 14:40
  • glad you like this easy approach, a complete Ctrl-C and Ctl-P way for my daily usage, FYI @TroyFletcher https://github.com/chenkaie/DotFiles/blob/9f61fb619553ef838dba3750861fd1efd56388c8/.vimrc#L470-L483 – chenkaie Apr 07 '21 at 01:48