Emacs Advent Calendar 07: Basic File Handling

Mon 2015-12-07

Some Emacs terminology first: When the content of a file is displayed in an Emacs buffer, the buffer is said to be visiting the corresponding file. Emacs has multiple commands to read files from disk and save a modified buffer back to a file.

To visit a file, invoke find-file by pressing C-x C-f.

Note that also non-existent files can be visited. In this case, an empty buffer is displayd. The file on disk will be created when the buffer is saved for the first time. If the file resides in a non-existent sub-directory, Emacs will ask you to create the directory first by executing M-x make-directory.

To open a file in read-only mode, visit it with C-x C-r. Another command is useful in cases where the wrong file was opened initially. With C-x C-v an alternate file name is read, the corresponding file is opened and the former file is closed.

(Did you notice that all the three keys for opening files (F, R, V) are in the same column of the keyboard?)

When visiting a file, the buffer name is set to the name of the file. If this one is not unique, emacs starts appending directory names to the buffer name until it becomes unique.

To save a file, use the C-x C-s command. To save a file under another name, use C-x C-w, this will ask for a new name before saving. To save all buffers to their respective files in one go, use the C-x s command. It will ask for a response for every file: the most important answers are 'y' to save and 'n' to not save. Other answers are possible, see the reference manual for them. Note that the answer 'd' will display a diff of the buffer's content against the file on disk.

To intentionally not save a file, it can be marked as unmodified with M-~. Neither C-x s or C-x C-c will ask about it again.

You can undo all unsaved changes in the buffer by reverting it to the file on disk: M-x revert-buffer will ask for confirmation before doing so. Note that reverting a buffer can not be undone.

More information on handling files can be found in sections 18.2 (Visiting), 18.3 (Saving) and 18.4 (Reverting) of the Emacs Reference Manual.

Tags:

This text by Ludger Sandig is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.