how to rename a buffer and file in emacs editor

One of the features you will need to use repeatedly while using a text editor is the ability to save the buffer or the file to the disk. In Emacs, saving the file or buffer to disk is easy enough but how do you rename the current buffer or save it to different file on the disk.

save buffer to new file

The emacs command to save the current buffer to a new file is write-file. The default shortcut for the write-file command is C-x C-w.

M-x write-file

Executing the write-file command will prompt you to enter a new file name for the active buffer. This is equivalent to renaming the buffer as well as renaming the backing file on disk.

save region to a new file

Another useful variation of this is the ability to save only a region or part of the buffer to the new file. The command to do it is write-region. This will save the current region to a new file.

M-x write-region

Using the write-file command will not only write the content to a new file, but will also switch the current buffer to the newly created file. If you want to continue working on the current buffer, but only want to write the contents to a new file then you can select all contents of the buffer (C-x h) and use the write-region to save the copy.