I'd like to write a visually selected area to a file.

For example:

prefix [sample text
more text] suffix

[] is the selected block which should be taken, resulting in a new file containing:

sample text
more text

The normal w command uses lines so '<,'>w! /tmp/test would include the prefix/suffix (and `<,`>w! /tmp/test is not allowed).


First, copy (also called 'yank' in vim parlance) your visual selection to the register of your choice. For example, to copy to register 'z', make your visual selection, and then type "zy.

In the case you give, you could do this without moving the cursor, by putting the cursor on the first square brace, and then typing v%"zy.

Breakdown: v -> start visual selection; % -> move to matching brace; "z -> use register 'z'; y -> yank (copy) the selection (in this case, into register 'z').

Once you have copied your visual selection to register 'z', go to the command line, and type

call writefile(getreg('z', 1, 1), "some-file")

If you want to append the text, rather than overwrite, you can use the "a" flag as follows

call writefile(getreg('z', 1, 1), "some-file", "a") 
  • So that means there is no builtin command that can do this? – laktak Apr 6 '17 at 11:59
  • @laktak Not that I could find ... A split()? getreg(.., 1, 1) returns a list, so a split() isn't needed. – muru Apr 6 '17 at 11:59
  • Thanks - you are too fast :) I just realized my mistake and edited the comment while you responded. – laktak Apr 6 '17 at 12:01

You can also copy your content and create a new window

Ctrl-w n ........... create a new window
p .................. paste

Then you can save as you want

  1. Vim help says (:h 10.3):

    Note: When using Visual mode to select part of a line, or using CTRL-V to select a block of text, the colon commands will still apply to whole lines. This might change in a future version of Vim.

  2. The plugin vis (#1195) by Charles Campbell offers the command :B {cmd} to apply a {cmd} only to the visual (block) selection.

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.