Subject: bug#15821: a better M-SPC

From: Toomas Rosin <[email-masked]>
Date: Wed, 06 Nov 2013 11:36:55 +0200

Hello,

I hope this is the right place for the following suggestion.

My version of M-SPC is an improvement over the original Emacs one in two respects: it operates both horizontally and vertically, and it takes a numeric argument.  See the docstring for details.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun adjust-space-2d (&optional arg)
  "Adjust horizontal or vertical whitespace.

On a non-empty blank line, leave exactly ARG spaces on it (without
ARG, make it empty).

On an empty line, delete all blank lines above and below it, leaving
ARG empty lines.  When there is no ARG, the default is to leave no
empty lines at the beginning or the end of the buffer or at a single
blank line, and leave one empty line elsewhere.

At the beginning or end of a non-blank line, delete all leading
resp. trailing whitespace, leaving ARG (by default, zero) spaces.

Elsewhere, insert and/or delete blanks, leaving ARG spaces (by
default, one space)."
  
  (interactive "*P")
  (let ((num (if arg (prefix-numeric-value arg)))
        (pos (point)))
    (cond
     ;;; Empty line at the beginning of the buffer.
     ((and (bobp) (looking-at "$"))
      (delete-blank-lines)
      (if (looking-at "[ \t]*$") (kill-line))
      (when num (open-line num)))
     ;;; Empty line elsewhere.
     ((save-excursion (beginning-of-line) (looking-at "$"))
      (delete-blank-lines)
      (when num (delete-blank-lines) (open-line num)))
     ;;; Beginning of line.
     ((save-excursion (skip-chars-backward " \t") (bolp))
      (beginning-of-line)
      (while (looking-at "[ \t]") (delete-char 1))
      (when num (insert (make-string num ? )) (beginning-of-line)))
     ;;; End of line.
     ((save-excursion (skip-chars-forward " \t") (eolp))
      (skip-chars-backward " \t")
      (while (not (eolp)) (delete-char 1))
      (when num (insert (make-string num ? ))))
     ;;; Anywhere else.
     (t
      (just-one-space)
      (when num (delete-char -1) (insert (make-string num ? )))))))

(global-set-key (kbd "M-SPC") 'adjust-space-2d)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Best regards,
T.