How can I delete the current line in Emacs?
Another method to delete the line without placing it into the kill ring:
(defun delete-current-line ()
"Deletes the current line"
(interactive)
(delete-region
(line-beginning-position)
(line-end-position)))
This will leave the point at the beginning of a blank line. To get rid of this also, you may wish to add something like (delete-blank-lines)
to the end of the function, as in this example, which is perhaps a little less intuitive:
(defun delete-current-line ()
"Deletes the current line"
(interactive)
(forward-line 0)
(delete-char (- (line-end-position) (point)))
(delete-blank-lines))
In case you don't want to kill the line (which would put it into the OS clipboard and kill ring) but simply delete it:
(defun delete-current-line ()
"Delete (not kill) the current line."
(interactive)
(save-excursion
(delete-region
(progn (forward-visible-line 0) (point))
(progn (forward-visible-line 1) (point)))))
C-a # Go to beginning of line
C-k # Kill line from current point
There is also
C-S-backspace # Ctrl-Shift-Backspace
which invokes M-x kill-whole-line
.
If you'd like to set a different global key binding, you'd put this in ~/.emacs:
(global-set-key "\C-cd" 'kill-whole-line) # Sets `C-c d` to `M-x kill-whole-line`
If you want to delete a number of whole lines, you can prefix the command with a number:
C-u 5 C-S-backspace # deletes 5 whole lines
M-5 C-S-backspace # deletes 5 whole lines
C-u C-S-backspace # delete 4 whole lines. C-u without a number defaults to 4
C-u -5 C-S-backspace # deletes previous 5 whole lines
M--5 C-S-backspace # deletes previous 5 whole lines
Sometimes I also find C-x z
helpful:
C-S-backspace # delete 1 whole line
C-x z # repeat last command
z # repeat last command again.
# Press z as many times as you wish.
# Any other key acts normally, and ends the repeat command.
Rather than having separate key to delete line, or having to invoke
prefix-argument. You can use crux-smart-kill-line
which will "kill to the end of the line and kill whole line on the next
call". But if you prefer delete
instead of kill
, you can use the
code below.
For point-to-string operation (kill/delete) I recommend to use zop-to-char
(defun aza-delete-line ()
"Delete from current position to end of line without pushing to `kill-ring'."
(interactive)
(delete-region (point) (line-end-position)))
(defun aza-delete-whole-line ()
"Delete whole line without pushing to kill-ring."
(interactive)
(delete-region (line-beginning-position) (line-end-position)))
(defun crux-smart-delete-line ()
"Kill to the end of the line and kill whole line on the next call."
(interactive)
(let ((orig-point (point)))
(move-end-of-line 1)
(if (= orig-point (point))
(aza-delete-whole-line)
(goto-char orig-point)
(aza-delete-line))))
source