Emacs:将缓冲区写入新文件,但保持该文件打开

10
我希望在Emacs中做到以下几点:将当前缓冲区保存到一个新文件中,同时保留当前文件的打开状态。当我执行C-x C-w时,当前缓冲区会被替换掉,但我想要保持两个缓冲区都打开。这可以在不重新打开原始文件的情况下实现吗?
4个回答

12

我认为没有内置的功能,但编写起来很容易:

(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))

7

我有一段时间用来做这个的代码片段,可以实现以下功能:

;;;======================================================================
;;; 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))

不,这不是我想要的。我想要同时打开两个文件。[尽管这是一个不错的代码片段,我也会将其添加到我的.emacs中] - Ocaso Protal
1
我之前就注意到了这个问题,所以我修改了帖子,使用了find-file-noselect函数。两个缓冲区都保持加载状态,但原始缓冲区仍然是焦点。如果你想同时看到两个缓冲区,请使用find-file-other-window函数。 - Chris McMahan
哈哈,我的评论太快了。谢谢! - Ocaso Protal
注意:此代码片段将在没有警告的情况下覆盖现有文件。 - JS.

5

我发现将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)))

2
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调用它(或定义一个键序列)。


1
糟糕!这并没有像您要求的那样保持新文件处于打开状态。 - Juancho
是的,这是我的主要问题:保持两个文件/缓冲区打开。 - Ocaso Protal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接