Backward-kill-word-or-join-lines
posted on 2022-05-08
I don’t remember where I encountered it, or what editor had this feature built-in, but I always felt that backward-kill-word should not kill the word on the previous line if executed and there is no word to delete on the current line. It should rather join the lines.
Couldn’t find any ready-made customization to borrow, like any self respecting Igor from the Terry Pratchett’s novells would do, so I have written one after inspecting the Emacs built-in.
(defun backward-kill-word-or-join-lines () "Backward-kill-word that will join lines if there is no word on a current line to kill." (interactive) (let ((orig-point (point)) (orig-column (current-column)) (start-line (line-number-at-pos))) (backward-word) (if (> start-line (line-number-at-pos)) (progn (goto-char orig-point) (delete-backward-char orig-column) (when (= orig-column 0) (delete-char -1))) (kill-region (point) orig-point))))
and you can bind it to C-W
with general.el like this:
(general-define-key :keymaps '(override emacs) "C-w" 'backward-kill-word-or-join-lines)
Putting it here just for reference. Happy hacking!
Update 2022-09-18: Updated the function - if only whitespace characters are before the cursor and the end of line, those will be deleted first. Joining of lines are then performed on next delete-kill-word-or-join-lines call. Also added example how to bind the function to C-W
.