9

I'm looking for an emacs function that will delete all whitespace from the cursor position (including newlines) until the first non-whitespace character.

For example, if my cursor is positioned at the end of the first line:

main(arg1,
     arg2)

The delete function would result in:

main(arg1,arg2)

4 Answers 4

7

You might find the hungry-delete package useful. I personally bind C-cdelete to delete whitespace after point, and C-cbackspace to delete whitespace before point like so

(global-set-key (kbd "C-c <backspace>") 'hungry-delete-backward)
(global-set-key (kbd "C-c <deletechar>") 'hungry-delete-forward)

update: as of 12.2018 function definitions changed hence:

(global-set-key (kbd "C-c <backspace>") 'c-hungry-delete-backward)
(global-set-key (kbd "C-c <deletechar>") 'c-hungry-delete-forward)
4

I use this quite often:

(defun join-line* ()
  "Join this line with the next line deleting extra white space."
  (interactive)
  (join-line t))

(global-set-key (kbd "M-j") #'join-line*) ;; just key binding I use…
2
  • I think it would be nice to note that this is equivalent to vanilla C-u M-^.
    – Basil
    Commented Dec 28, 2018 at 11:15
  • Note also that join-line (aka delete-indentation) often leaves one space character after point.
    – Basil
    Commented Dec 28, 2018 at 11:18
3

C-k M-\

C-k - Kill rest of line or one or more lines (kill-line).

M-\ - Delete spaces and tabs around point (delete-horizontal-space).

2

Yet another solution

(defun foo ()
  (interactive)
  (delete-region (point)
                 (+ (save-excursion (skip-chars-forward " \n"))
                    (point))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.