Emacs: Delete Whitespace around Cursor

By Xah Lee. Date: . Last updated: .

In emacs, the following commands lets you delete whitespaces around cursor.

Here's a command xah-shrink-whitespaces that combine most of them into one.

(defun xah-shrink-whitespaces ()
  "Remove whitespaces around cursor to just one or none.
Call this command again to shrink more. 3 calls will remove all whitespaces.
URL `http://ergoemacs.org/emacs/emacs_shrink_whitespace.html'
Version 2016-12-18"
  (interactive)
  (let (($p0 (point))
        $line-has-char-p ; current line contains non-white space chars
        $has-space-tab-neighbor-p
        $space-or-tab-begin $space-or-tab-end
        )
    (save-excursion
      (setq $has-space-tab-neighbor-p
            (or (looking-at " \\|\t") (looking-back " \\|\t" 1)))
      (beginning-of-line)
      (setq $line-has-char-p (re-search-forward "[[:graph:]]" (line-end-position) t))
      (goto-char $p0)
      (skip-chars-backward "\t ")
      (setq $space-or-tab-begin (point))
      (goto-char $p0)
      (skip-chars-forward "\t ")
      (setq $space-or-tab-end (point)))
    (if $line-has-char-p
        (if $has-space-tab-neighbor-p
            (let ($deleted-text)
              ;; remove all whitespaces in the range
              (setq $deleted-text
                    (delete-and-extract-region $space-or-tab-begin $space-or-tab-end))
              ;; insert a whitespace only if we have removed something different than a simple whitespace
              (when (not (string= $deleted-text " "))
                (insert " ")))
          (progn
            (when (equal (char-before) 10) (delete-char -1))
            (when (equal (char-after) 10) (delete-char 1))))
      (progn (delete-blank-lines)))))

Give it a easy key. 〔►see Emacs: How to Define Keys

Whitespace Topic

  1. Emacs: Clean Empty Lines
  2. Emacs: Delete Trailing Whitespace
  3. Emacs: Delete Whitespace around Cursor
  4. Emacs: Tabs, Space, Indentation Setup
  5. Emacs: Make Whitespaces Visible
  6. Emacs: Newline Representation ^M ^J ^L
  7. Emacs: Batch Convert Line Ending in Dired

Enhanced Editing Commands Topic

  1. Emacs: Select Line, between Quotes, Extend Selection
  2. Emacs: Copy/Cut Current Line If No Selection
  3. Emacs: Copy/Cut All or Selection
  4. Emacs: Paste or Paste Previous
  5. Emacs: Delete Whitespace around Cursor
  6. Emacs: Move Cursor to Beginning of Line/Paragraph
  7. Emacs: Move Cursor by Text Block
  8. Emacs: Move Cursor to Bracket/Quote
  9. Emacs: Move Cursor to Punctuation
  10. Emacs: Delete Text Block
  11. Emacs: Toggle Comment Current Line
  12. Emacs: Insert Date Time

Working with Brackets Topic

  1. Emacs: Highlight Brackets ({[]})
  2. Emacs: Insert Brackets by Pair
  3. Emacs: Delete Bracket ({[]}) by Pair
  4. Emacs: Select Line, between Quotes, Extend Selection
  5. Emacs: Move Cursor to Bracket/Quote
Like it? Buy Xah Emacs Tutorial. Thanks.