Avijit Gupta
Avijit Gupta

Reputation: 5766

How to do an invert selection in emacs?

I currently have a region of text selected. I want to kill/yank (or format in any other way) the whole buffer except the selected region. Is there any way in which I can do an invert selection in emacs and accomplish the same?

Upvotes: 1

Views: 700

Answers (3)

Devon
Devon

Reputation: 1093

Non-contiguous regions can't exist. However, this puts the opposite command on C-c DEL

(global-set-key "\^C\^?"        ; help edit mail files, etc.
        (defun erase-buffer-except-region (beg end)
          "Erase the buffer except for the region."
          (interactive "r")
          (when (< end beg)
            (cl-rotatef beg end))
          (delete-region end (point-max))
          (delete-region (point-min) beg)))

Upvotes: 1

phils
phils

Reputation: 73345

(defun my-copy-inverted-region-as-kill (beginning end)
  "Copy to the kill ring everything except the marked region."
  (interactive "r")
  (let ((srcbuf (current-buffer))
        (offset (point-min)))
    (with-temp-buffer
      (insert-buffer-substring srcbuf)
      (delete-region (- beginning offset) (- end offset))
      (copy-region-as-kill (point-min) (point-max)))))

Upvotes: 1

abo-abo
abo-abo

Reputation: 20362

  1. C-w kill-region the text in the middle.
  2. C-x h mark-whole-buffer the rest of the text.
  3. do your thing.
  4. C-y yank the middle text.

Upvotes: 1

Related Questions