Skip to content

Instantly share code, notes, and snippets.

@glucas
Last active August 29, 2015 14:21
Show Gist options
  • Save glucas/309fe3d43bd9cf00533f to your computer and use it in GitHub Desktop.
Save glucas/309fe3d43bd9cf00533f to your computer and use it in GitHub Desktop.
(defun my/fix-space ()
"Delete all spaces and tabs around point, leaving one space except at the beginning of a line."
(interactive)
(just-one-space)
(when (looking-back "^[[:space:]]+") (delete-horizontal-space)))
(defun my/delete-backward ()
"When there is an active region, delete it and then fix up the whitespace."
(interactive)
(when (use-region-p)
(delete-region (region-beginning) (region-end))
(my/fix-space)))
;; Same as above, but using (interactive "r") to get the bounds of the region
(defun my/delete-backward-2 (beg end)
(interactive "r")
(when (use-region-p)
(delete-region beg end)
(my/fix-space)))
;;
;; Variant that deletes backward one char unless the region is active:
;;
(defun my/delete-backward ()
(interactive)
(if (use-region-p) ; IF
(progn ; THEN
(delete-region (region-beginning) (region-end))
(my/fix-space))
(delete-backward-char 1))) ; ELSE
;;
;; Improved version of the last example that handles a prefix arg the same way as `delete-backward-char.
;; - If there is no region: delete backward one character, or N characters with a prefix argument.
;; - If the region is active and the prefix arugment is 1 (or not set), delete the region and fix space.
;; - If the region is active you can use a prefix arg to delete a certain number of chars instead of the region.
(defun my/delete-backward (n)
(interactive "p")
(if (and (use-region-p) (= n 1))
(progn
(delete-region (region-beginning) (region-end))
(my/fix-space))
(delete-backward-char n)))
@incandescentman
Copy link

I think this should do it:

(defun my/fix-space ()
"Delete all spaces and tabs around point, leaving one space except at the beginning of a line and before a punctuation mark."
(interactive)
(just-one-space)
(when (or (looking-back "^[[:space:]]+")
(looking-at "[[:punct:]]"))
(delete-horizontal-space)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment