Skip to content

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

Lesson: Emacs EditingSwitch
โ† Linux Foundations

Shell and files

Emacs Editing

Cut, copy, paste, undo and replace text in Emacs.

Typing text in Emacs is straightforward. This lesson covers changing what is already there. C- means Ctrl and M- means Alt (Meta).

Deleting and killing

  • Backspace deletes the character before the cursor.
  • C-d deletes the character at the cursor.
  • M-d kills the word after the cursor.
  • C-k kills from the cursor to the end of the line.

"Kill" is Emacs for cut. Killed text is saved in the kill ring, so you can get it back. Single characters removed with C-d are not saved there.

C-k stops before the line break. If you started at the beginning of the line, press it again to remove the now empty line.

Selecting a region

Press C-SPC (Ctrl and space) to set the mark, then move the cursor. The text between the mark and the cursor is the region.

  • C-w kills (cuts) the region.
  • M-w copies the region.

C-x h selects the whole buffer.

Yanking

C-y yanks (pastes) the most recently killed text. Straight after C-y, press M-y to swap it for an older entry in the kill ring. Press M-y again to go further back.

Note the clash with Vim: there, "yank" means copy. In Emacs it means paste.

Undo

Use C-/, C-_ or C-x u. Repeat to keep undoing. Which of these your terminal passes through can differ, and C-x u is a reliable choice.

To redo, Emacs 28 and later offer M-x undo-redo. On any version you can break the undo sequence, for example with C-f, and then undo again, which reverses your undos.

Search and replace

Press M-% (query-replace). Enter the old text, then the new:

text
Query replace: http
Query replace http with: https

At each match you answer:

  • y replace this one
  • n skip it
  • ! replace all the rest
  • q stop

Replacement starts at the cursor, so go to the top with M-< first if you want the whole buffer.

To replace everything from the cursor onwards without questions, use M-x replace-string.

Save your work

Edits exist only in the buffer until you press C-x C-s.

Try it

  1. Run printf 'one http\ntwo http\nthree\n' > edit.txt, then emacs -nw edit.txt.
  2. On the first line press C-k twice, move down with C-n, and press C-y.
  3. Undo with C-x u until the file looks as it did.
  4. Press M-<, then M-%, replace http with https, and answer !.
  5. Save with C-x C-s, exit with C-x C-c, and run cat edit.txt.

Check your understanding

Emacs Editing

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.