如何在 emacs 中创建一个空文件? [英] How do I create an empty file in emacs?
问题描述
我怎样才能从 emacs 创建一个空文件,最好是从一个 dired 缓冲区中创建?
How can I create an empty file from emacs, ideally from within a dired buffer?
例如,我刚刚在 dired 模式下打开了一个 Python 模块,创建了一个新目录,在 dired 中打开了它,现在需要在目录中添加一个空的 __init__.py
文件.
For example, I've just opened a Python module in dired mode, created a new directory, opened that in dired, and now need to add an empty __init__.py
file in the directory.
如果我使用 C-x C-f __init__.py RET C-x C-s
那么 emacs 不会创建该文件,因为没有对其进行任何更改.我必须输入文件,保存它,删除我的输入,然后再次保存它才能工作.
If I use C-x C-f __init__.py RET C-x C-s
then emacs doesn't create the file because no changes have been made to it. I would have to type in the file, save it, delete my typing and then save it again for that to work.
谢谢
推荐答案
这是对 dired-create-directory
的改编.它的工作方式相同,因此除了普通文件名外,您还可以为文件指定新的父目录(将在当前目录下创建)(例如 foo/bar/filename
).
Here's an adaptation of dired-create-directory
. It works the same way, so as well as a plain filename, you can also specify new parent directories (to be created under the current directory) for the file (e.g. foo/bar/filename
).
(eval-after-load 'dired
'(progn
(define-key dired-mode-map (kbd "C-c n") 'my-dired-create-file)
(defun my-dired-create-file (file)
"Create a file called FILE.
If FILE already exists, signal an error."
(interactive
(list (read-file-name "Create file: " (dired-current-directory))))
(let* ((expanded (expand-file-name file))
(try expanded)
(dir (directory-file-name (file-name-directory expanded)))
new)
(if (file-exists-p expanded)
(error "Cannot create file %s: file exists" expanded))
;; Find the topmost nonexistent parent dir (variable `new')
(while (and try (not (file-exists-p try)) (not (equal new try)))
(setq new try
try (directory-file-name (file-name-directory try))))
(when (not (file-exists-p dir))
(make-directory dir t))
(write-region "" nil expanded t)
(when new
(dired-add-file new)
(dired-move-to-filename))))))
这篇关于如何在 emacs 中创建一个空文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!