Skip to content

Linux Foundations / Find your way around Linux ยท Step 56 of 63

Lesson: Emacs Manipulate FilesSwitch
โ† Linux Foundations

Shell and files

Emacs Manipulate Files

Open, save and switch between files, buffers and windows in Emacs.

In Emacs you can keep many files open at once. Each one lives in a buffer, and you view buffers through windows. In this lesson, C- means Ctrl and M- means Alt (Meta).

Opening files

Press C-x C-f (find-file). The minibuffer asks for a path:

text
Find file: ~/notes.txt

Press Tab to complete names. If the file does not exist, Emacs gives you an empty buffer, and the file is created when you save.

Saving

  • C-x C-s saves the current buffer.
  • C-x C-w writes it under a name you choose ("save as").
  • C-x s offers to save each modified file buffer, asking about them one by one.

After a save, the echo area reports something like:

text
Wrote /home/sam/notes.txt

After C-x C-w, the buffer is attached to the new name, so later saves go there.

To copy the contents of another file into the current buffer at the cursor, use C-x i.

Buffers

  • C-x b switches to another buffer. Type its name, or press Enter for the suggested one.
  • C-x C-b lists all buffers.
  • C-x k kills (closes) a buffer. It asks for confirmation if a file buffer has unsaved changes.

Killing a buffer does not delete the file on disk.

Windows

An Emacs "window" is a pane inside the screen.

  • C-x 2 splits into one above the other.
  • C-x 3 splits side by side.
  • C-x o moves to the other window.
  • C-x 0 closes the current window.
  • C-x 1 keeps only the current window.

Closing a window leaves its buffer open.

Extra files you may notice

By default Emacs often leaves a backup of the previous version, named with a trailing tilde, such as notes.txt~. While you have unsaved edits it may also write an auto-save file such as #notes.txt#. After a crash, M-x recover-file can use the auto-save file. Distributions and personal settings can change where these go.

Editing system files

Do not start the whole editor as root just to change one file. Use sudoedit, with the editor variable set to Emacs:

bash
SUDO_EDITOR="emacs -nw" sudoedit /etc/hosts

Try it

  1. Run emacs -nw.
  2. Press C-x C-f, type one.txt, add a line, and save with C-x C-s.
  3. Open two.txt the same way.
  4. Press C-x 2, then C-x o, then C-x b and pick one.txt.
  5. Return to a single window with C-x 1.
  6. Exit with C-x C-c.

For a live Linux shell, there is the files and links lab.

Check your understanding

Emacs Manipulate Files

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.