Delete to Beginning of Line in Emacs to Rewrite Code
Ever since Brett Terpstra posted about ⌘← to jump to the first character of the line back in 2014, I’ve used behavior like this in Xcode. Nowadays, ⌘⌫ automatically deletes up to the beginning of the line, stopping at whitespace. That’s quite handy to rewrite the current line.
The default key bindings in Emacs were always a bit too eager for my taste, because Control-based deletion would delete the whole line, and Meta-based deletion would delete to to the beginning of the sentence.
To make this a bit more “sane” for my habits, here’s a function that kills to the beginning of the actual line in programming modes, and to the beginning of the visual line in other modes – for me, that’s mostly prose editing like this Markdown document, but we’ll see if I can come up with a better predicate.
(defun ct/kill-to-beginning-of-line-dwim ()
"Kill from point to beginning of line.
In `prog-mode', delete up to beginning of actual, not visual
line, stopping at whitespace. Repeat to delete whitespace. In
other modes, e.g. when editing prose, delete to beginning of
visual line only."
(interactive)
(let ((current-point (point)))
(if (not (derived-mode-p 'prog-mode))
;; In prose editing, kill to beginning of (visual) line.
(if visual-line-mode
(kill-visual-line 0)
(kill-line 0))
;; When there's whitespace at the beginning of the line, go to
;; before the first non-whitespace char.
(beginning-of-line)
(when (search-forward-regexp (rx (not space)) (point-at-eol) t)
;; `search-forward' puts point after the find, i.e. first
;; non-whitespace char. Step back to capture it, too.
(backward-char))
(kill-region (point) current-point))))
I bound my Command key to “Super”, so this is my shortcut of choice now:
(global-set-key (kbd "s-<backspace>") #'ct/kill-to-beginning-of-line-dwim)