Copy Only What You See: Teaching M-w a Prefix Argument

Select a region in a folded Org buffer, press M-w, and you get more than you bargained for: the kill ring receives the hidden text as well. Folding is only a display trick - the text is still in the buffer, and kill-ring-save dutifully copies every character between the region boundaries, ellipsis and all. Paste that into an email or a chat and the hidden notes come along for the ride.

The fix, in my config, is a prefix argument: C-u M-w copies only the visible text of the region, leaving everything folded or hidden behind. Plain M-w is unchanged.

20260924135500-emacs--Copy-Only-What-You-See-Teaching-M-w-a-Prefix-Argument.jpg

I have been a fan of org-copy-visible ever since I discovered it works outside Org - back in 2023 I was using it in dired with dired-hide-details-mode to copy just the filenames. The only friction was having to remember M-x org-copy-visible instead of my muscle-memory M-w. So I taught my existing my/kill-ring-save wrapper a another trick: hand it a prefix argument and it copies only the visible text.

M-w has been remapped to a small wrapper for a while, mainly so that pressing it with no active region copies the current line. The new version forwards the prefix argument into a second branch:

(defun my/kill-ring-save (beg end &optional copy-visible)
  "Save the region to the kill ring.
With a prefix argument, copy only the visible text between BEG
and END, skipping folded or hidden text, like `org-copy-visible'."
  (interactive (if (use-region-p)
                   (list (region-beginning) (region-end) current-prefix-arg)
                 (list (line-beginning-position)
                       (line-beginning-position 2) current-prefix-arg)))
  (if copy-visible
      (org-copy-visible beg end)
    (kill-ring-save beg end)))
    
(global-set-key [remap kill-ring-save] 'my/kill-ring-save)

[remap kill-ring-save] keeps M-w working everywhere.

So why org-copy-visible?, I could have written my own invisible-text walker, but org-copy-visible already is one and it ships with Emacs!