Emacs: Delete Whitespace around Cursor 🚀
In emacs, the following commands lets you delete whitespaces around cursor.
delete-blank-lines
【Ctrl+x Ctrl+o】just-one-space
【Alt+Space】delete-indentation
【Alt+^】delete-horizontal-space
【Alt+\】fixup-whitespace
cycle-spacing
(emacs 24.4)
Here's a command that combine most of them into one.
put this in your Emacs Init File:
(defun xah-delete-blank-lines () "Delete all newline around cursor. URL `http://xahlee.info/emacs/emacs/emacs_shrink_whitespace.html' Version: 2018-04-02" (interactive) (let (xp3 xp4) (skip-chars-backward "\n") (setq xp3 (point)) (skip-chars-forward "\n") (setq xp4 (point)) (delete-region xp3 xp4))) (defun xah-fly-delete-spaces () "Delete space, tab, IDEOGRAPHIC SPACE (U+3000) around cursor. Version: 2019-06-13" (interactive) (let (xp1 xp2) (skip-chars-forward " \t ") (setq xp2 (point)) (skip-chars-backward " \t ") (setq xp1 (point)) (delete-region xp1 xp2))) (defun xah-shrink-whitespaces () "Remove whitespaces around cursor . Shrink neighboring spaces, then newlines, then spaces again, leaving one space or newline at each step, till no more white space. URL `http://xahlee.info/emacs/emacs/emacs_shrink_whitespace.html' Version: 2014-10-21 2021-11-26 2021-11-30 2023-07-12" (interactive) (let ((xeol-count 0) (xp0 (point)) xp1 ; whitespace begin xp2 ; whitespace end (xcharBefore (char-before)) (xcharAfter (char-after)) xspace-neighbor-p) (setq xspace-neighbor-p (or (eq xcharBefore 32) (eq xcharBefore 9) (eq xcharAfter 32) (eq xcharAfter 9))) (skip-chars-backward " \n\t ") (setq xp1 (point)) (goto-char xp0) (skip-chars-forward " \n\t ") (setq xp2 (point)) (goto-char xp1) (while (search-forward "\n" xp2 t) (setq xeol-count (1+ xeol-count))) (goto-char xp0) (cond ((eq xeol-count 0) (if (> (- xp2 xp1) 1) (progn (delete-horizontal-space) (insert " ")) (progn (delete-horizontal-space)))) ((eq xeol-count 1) (if xspace-neighbor-p (xah-fly-delete-spaces) (progn (xah-delete-blank-lines) (insert " ")))) ((eq xeol-count 2) (if xspace-neighbor-p (xah-fly-delete-spaces) (progn (xah-delete-blank-lines) (insert "\n")))) ((> xeol-count 2) (if xspace-neighbor-p (xah-fly-delete-spaces) (progn (goto-char xp2) (search-backward "\n") (delete-region xp1 (point)) (insert "\n")))) (t (progn (message "nothing done. logic error 40873. shouldn't reach here"))))))
Give it a easy key. [see Emacs: Define Keybinding]