I want to do the following in Emacs: Save the current buffer to a new file, but also keep the current file open. When I do C-x C-w then current buffer gets replaced, but I want to keep open both buffer. Is this possible without reopening the original file?
I don't think there's anything built in, but it's easy enough to write:
(defun my-clone-and-open-file (filename)
"Clone the current buffer writing it into FILENAME and open it"
(interactive "FClone to file: ")
(save-restriction
(widen)
(write-region (point-min) (point-max) filename nil nil nil 'confirm))
(find-file-noselect filename))
Here's a snippet I've had for a while to do just this
;;;======================================================================
;;; provide save-as functionality without renaming the current buffer
(defun save-as (new-filename)
(interactive "FFilename:")
(write-region (point-min) (point-max) new-filename)
(find-file-noselect new-filename))
I found it helpful to combine Scott's and Chris's answers above. The user can call save-as and then answer "y" or "n" when prompted whether to switch to the new file. (Alternatively, the user can select the desired functionality via the function name save-as-and-switch or save-as-but-do-not-switch, but this requires more keystrokes. Those names are still available for being called by other functions in the future, however.)
;; based on scottfrazer's code
(defun save-as-and-switch (filename)
"Clone the current buffer and switch to the clone"
(interactive "FCopy and switch to file: ")
(save-restriction
(widen)
(write-region (point-min) (point-max) filename nil nil nil 'confirm))
(find-file filename))
;; based on Chris McMahan's code
(defun save-as-but-do-not-switch (filename)
"Clone the current buffer but don't switch to the clone"
(interactive "FCopy (without switching) to file:")
(write-region (point-min) (point-max) filename)
(find-file-noselect filename))
;; My own function for combining the two above.
(defun save-as (filename)
"Prompt user whether to switch to the clone."
(interactive "FCopy to file: ")
(if (y-or-n-p "Switch to new file?")
(save-as-and-switch filename)
(save-as-but-do-not-switch filename)))
C-x h
selects all the buffer, then
M-x write-region
writes the region (whole buffer in this example) to another file.
Edit: this function does what you need
(defun write-and-open ( filename )
(interactive "GClone to file:")
(progn
(write-region (point-min) (point-max) filename )
(find-file filename ))
)
It's a bit crude, but modify to your will.
The interactive code 'G' prompts for a filename which goes into the 'filename' argument.
Drop this into your .emacs and call with M-x write-and-open (or define a key sequence).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With