Emacs: how to delete text without kill ring?

Viewed 22686

I'd like to just delete some text so I can yank some other text instead of it. How can I do that? C-w cuts the selected text to kill ring and I end up without the text I wanted to yank.

Also, is it possible to yank text directly instead of some text without even pressing buttons to kill it?

15 Answers

I type M-x delete-region quite often, but you can bind it it to a key.

With Delete Selection Mode in newer versions of Emacs you don't have to type a command just start typing:

By default, text insertion occurs normally even if the mark is active—for example, typing a inserts the character ‘a’, then deactivates the mark. Delete Selection mode, a minor mode, modifies this behavior: if you enable that mode, then inserting text while the mark is active causes the text in the region to be deleted first. Also, commands that normally delete just one character, such as C-d or DEL, will delete the entire region instead. To toggle Delete Selection mode on or off, type M-x delete-selection-mode.

For your second question, alternatively to DeleteSelectionMode you can enable CUA Mode which additionally gives you a nice rectangle selection mode enabled by C-Return. CUA mode is part of emacs since 22.1.

(defun copy-to-register-z (p1 p2)
  "Copy text selection to register named “z”."
  (interactive "r")
  (copy-to-register ?z p1 p2))
(defun replace-register-content-z (p1 p2)
  "Replace register named “z”'s content."
  (interactive "r")
  (delete-region p1 p2)
  (insert-register ?z))
(global-set-key (kbd "C-c c") 'copy-to-register-z)
(global-set-key (kbd "C-c v") 'replace-register-content-z)

As a complement to all answers. If you write elisp code to delete, you can call functions that kill as long as you use a local kill-ring object like this:

(defun delete-something()
  "Delete something without storing in kill ring."
  (let (kill-ring)
     (kill-something)))

Use any function that kill something in place of the kill-something. The function will then delete and nothing will be remembered in the real kill-ring.

Related