1

Similarly, I want to delete word backward when C-u C-w is pressed.

I would also value recommendation on cut/paste/kill conventions.

I tried to bind C-w to delete-backward-char, but kill-region stopped working. Please help as I find it irritating to stretch my fingers to tap DEL key and I commit a lot of mistakes while typing. Thank You

3

Taking you at your word, that you want to delete, and not kill, for the char and word cases, try this.

(Killing is like "cut" - it not only deletes the text but puts it on the kill-ring, which means it's available for yanking ("pasting"). Just deleting does not make the deleted text available for yanking.)

But if backward killing words is OK, then you don't need my-backward-delete-word - just use backward-kill-word in its place.

(defun my-C-w-dwim (&optional arg)
  "`delete-backward-char`, but if region is active then kill region.
With prefix arg N, delete backward to the start of the Nth word."
  (interactive "P")
  (cond (arg
         (my-backward-delete-word (prefix-numeric-value arg)))
        ((use-region-p)
         (kill-region (region-beginning) (region-end)))
        (t (delete-backward-char 1))))
    

(defun my-backward-delete-word (arg)
  "Like `backward-kill-word`, but just delete."
  (interactive "p")
  (delete-region (point) (progn (backward-word arg) (point))))

(global-set-key (kbd "C-w") 'my-C-w-dwim)

4
  • Maybe explain the difference between deleting and killing?
    – NickD
    Sep 7 at 17:37
  • 2
    Good point, @NickD. So: killing removes text and places it on the kill-ring, ready to yank. This is roughly the same as what most apps call cutting and pasting. Deleting just removes text; the only way to get it back is to undo. Sep 7 at 19:21
  • 1
    Thanks for taking time to read such a big question (for me at least), Your code worked perfectly but the only addition I did was to assign your 'my-backward-delete-word function to 'M-w' to delete word backward. I believe I will be able to understand your code one day.
    – deepanshu
    Sep 7 at 19:52
  • @NickD. Done. Thx.
    – Drew
    Sep 7 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.