Note #2025-12-15-001

Srijan Choudhary Srijan Choudhary

A small elisp snippet that I found useful. I often switch between terminals and #Emacs, and they have slightly different behaviors for C-w. This makes it behave the same in Emacs as it does in bash/zsh/fish etc - deletes the last word. It retains the kill-region behavior if a region is actually selected.

(defun kill-region-or-backward-word ()
  "If the region is active and non-empty, call `kill-region'.
Otherwise, call `backward-kill-word'."
  (interactive)
  (call-interactively
   (if (use-region-p) 'kill-region 'backward-kill-word)))
(global-set-key (kbd "C-w") 'kill-region-or-backward-word)

Ref: https://stackoverflow.com/questions/13844453/how-do-i-make-c-w-behave-the-same-as-bash

Interactions

👍 2 likes

  • darius
    darius

    kill-region-dwim is a new user option that lets you do exactly that :3

    Behavior when ‘kill-region’ is invoked without an active region.
    If set to nil (default), kill the region even if it is inactive,
    signaling an error if there is no region.
    If set to ‘emacs-word’, kill the last word as defined by the
    current major mode.
    If set to ‘unix-word’, kill the last word in the style of a shell like
    Bash. This ignores the major mode like ‘unix-word-rubout’ (which see).

    This variable was introduced, or its default value was changed, in
    version 31.1 of Emacs.

    Reply