Killing the whole word in Emacs
April 21st, 2007
Emacs has two methods of killing words: kill-word kills from the point to the end of the word, kill-word-backward kills from the beginning of the word to the point. More often than not I’d like to kill the whole word with one key-stroke. Here is my implementation of this functionality:
(defcustom brutal-word-regex "s_|sw"
"Regular expression that defines a character
allowed in a word, i.e., not word boundary. Should
match only one character at a time."
:type 'regexp
:group 'user)
(defun brutally-kill-word ()
"Kills the whole word (as defined by the
brutal-word-regex) regardless of where the point is in it."
(interactive)
; Work only if point is inside of a word
(if (looking-at brutal-word-regex)
(save-excursion
; Back up till the word boundary, one char at a time.
(while (looking-at brutal-word-regex) (backward-char))
; Search for the whole word ...
(search-forward-regexp (concat "(" brutal-word-regex ")+") nil t)
; ... and replace it with empty string
(replace-match "")
; Remove extra spaces if they are there
(if (eq (char-after) ? ) (just-one-space)))))
(global-set-key "M-d" 'brutally-kill-word)