我希望在Emacs中做到以下几点:将当前缓冲区保存到一个新文件中,同时保留当前文件的打开状态。当我执行C-x C-w时,当前缓冲区会被替换掉,但我想要保持两个缓冲区都打开。这可以在不重新打开原始文件的情况下实现吗?
我认为没有内置的功能,但编写起来很容易:
(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))
我有一段时间用来做这个的代码片段,可以实现以下功能:
;;;======================================================================
;;; 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))
我发现将Scott和Chris的答案结合起来很有帮助。用户可以调用“另存为”功能,然后在提示是否切换到新文件时回答“y”或“n”。(或者,用户可以通过函数名save-as-and-switch或save-as-but-do-not-switch选择所需的功能,但这需要更多的按键操作。但是,这些名称仍然可供以后的其他函数调用。)
;; 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
M-x write-region
将区域(在本例中为整个缓冲区)写入另一个文件。
编辑:此函数可实现您需要的功能。
(defun write-and-open ( filename )
(interactive "GClone to file:")
(progn
(write-region (point-min) (point-max) filename )
(find-file filename ))
)
这段代码有点粗糙,但是可以根据您的需求进行修改。
交互式代码“G”会提示输入文件名,并将其作为“filename”参数。
将这段代码放入您的.emacs文件中,并通过M-x write-and-open调用它(或定义一个键序列)。