how to save a file or buffer in emacs editor

If you have worked with emacs then you might be familiar with the concept of buffers. It is similar to what other editors might call tabs or files. In emacs, it refers to the contents of some file or directory that you had opened and it is a copy of the contents of those files. So the contents of the file does not change until you save the buffer.

saving buffer to file

More often than not, the buffer is usually backed by a file in the file system of the same name. Having said that, it is quite possible to have a buffer that does not have the backing file in the file system…such as the *scratch*.

To save the current active buffer to disk, you will use the save-buffer command. This will save the buffer if it has been modified. The command is bound to the shortcut C-x C-s, so you can use that as well.

M-x save-buffer # saves the current buffer to disk

saving buffer to a new file

If the currently active buffer does not have a backing file, then the save-buffer command will prompt you for a file name and location. If it does have a backing file, but you want to save it to a different file then you will use the write-file command. This is equivalent to the “Save as” functionality that you see in other editors.

M-x write-file # Save to a different file

This is an interactive command and will prompt you for a file name. Executing this command will make the buffer write the contents to the new file, then visit that file and mark it as not modified. It will then rename the buffer based on the new filename, making it unique if needed.

The command is bound to C-x C-w and you can use the shortcut instead to save the buffer to a new file.

Another option you have is to change the file name under which the current buffer will be saved in the future. This is a way to change the backing file of the buffer.

M-x set-visited-file-name

saving all open buffers

If you have multiple buffers that are open and modified then you can save all of them using the save-some-buffers command. This is an interactive command that will prompt you before saving each of the modified buffers. You will have the option to save it, not save it or view the diff of the changes etc.

M-x save-some-buffers

The command is bound to C-x s.

You can close the buffer after saving with the kill-buffer command. It is bound to C-x k.

If you would like to save all the buffers and then shutdown emacs, then use the save-buffer-kill-emacs command.

M-x save-buffer-kill-emacs

Depending on how your emacs is configured, it should prompt you to save the open buffers when you shutdown emacs. So you need not have to execute the command explicitly, but it is a good one to know.