How can I "Save As..." in Emacs without visiting the new file?

Select the entire buffer with C-xh, then use M-xwrite-region.


This is based on Inaimathi's answer and my comment to that, plus some additional tweaks:

  • Offer the current filename for editing by default, as personally I often want a variation on that, and it's slightly annoying not having it there to begin with.
  • Don't overwrite an existing file without asking the user, and never overwrite the current buffer's file.
  • If the region is active, write the region; otherwise write the entire (widened) buffer.
(defun my-write-copy-to-file ()
  "Write a copy of the current buffer or region to a file."
  (interactive)
  (let* ((curr (buffer-file-name))
         (new (read-file-name
               "Copy to file: " nil nil nil
               (and curr (file-name-nondirectory curr))))
         (mustbenew (if (and curr (file-equal-p new curr)) 'excl t)))
    (if (use-region-p)
        (write-region (region-beginning) (region-end) new nil nil nil mustbenew)
      (save-restriction
        (widen)
        (write-region (point-min) (point-max) new nil nil nil mustbenew)))))

(global-set-key (kbd "C-c w") 'my-write-copy-to-file)

Tags:

Emacs

File Io