Vim Recipes Basics Saving a File

Saving a File

Problem

You want to save the file you've been working on.

After you've made changes to a file you typically want to save them. For example, if you've written up a turkey recipe to send to your daughter, you'd open Vim, type the recipe, save it to turkey-recipe.txt, then e-mail turkey-recipe.txt to your hungry child.

Solution

The :up[date] command saves the current buffer if it has been modifiedThe more common command to save a file is :w, however this always saves the file, even if it hasn't been changed. :up preserves timestamps and saves needless disk access.. If your file doesn't have a name yet, you'll need to follow :up with a filename. This is conceptually similar to most word processors' Save function.

To change the name of an existing file, use :saveas file. If file already exists and you want to overwrite it, use :saveas! file. This is conceptually the same as most word processors' Save As function.

Discussion

There are a number of situations where it can be useful to have Vim save your file for you automatically. One is when you're working with files in multiple buffers and cycling between them. By default, every time you switch to a buffer Vim prompts you to save the current one first. Another is when you execute an external command on the current file. The command is passed the file's name, so if your buffer contains unsaved changes, the command won't see them. The solution is to :set autowrite. This causes files to be automatically saved when you switch buffers and execute external commands. If you also want files automatically saved when you quit Vim, use :set autowriteall.

The :autowrite functionality is not related to some word processor's concept of auto-saving a file periodically in case of a crash. Vim does this automatically.

You can also "write" a specific portion of a file to a new filename. By prefixing the :up command with a line range only the specified lines are written to the named file. For example, :20,30up 20-30.txt saves lines twenty to thirty of the current buffer to a file named 20-30.txt. Alternatively, select a portion of a file visually then execute :up filename and the text you selected will be written to a file named filename.