如何在emacs中创建一个空文件,最好是在dired缓冲区内创建?
例如,我刚刚在dired模式下打开了一个Python模块,创建了一个新的目录,以dired模式打开该目录,现在需要在该目录中添加一个空的__init__.py
文件。
如果我使用C-x C-f __init__.py RET C-x C-s
,那么emacs不会创建该文件,因为它没有被修改过。我必须输入该文件名、保存它、删除我的输入,然后再次保存才能实现。
谢谢!
M-! touch __init__.py RET
C-x b __init__.py RET C-x C-w RET如果您在dired缓冲区中,则文件将保存在此处显示的目录中。
(add-hook 'find-file-hooks 'assume-new-is-modified)
(defun assume-new-is-modified ()
(when (not (file-exists-p (buffer-file-name)))
(set-buffer-modified-p t)))
M-! touch __init__.py
更短,不涉及打开和关闭缓冲区。 - SingletonedC-x C-f
创建新文件时,它都会显示在dired中。这比每次键入shell命令(touch
)更快。 - metakermit通过编程且不依赖于touch
,这非常容易:
(with-temp-buffer (write-file "path/to/empty/file/"))
在这个线程之后,Emacs 增加了两个新的命令:
这些命令将在 Emacs 27.1 发布版本中提供。
make-empty-file
使用的方法来创建空文件的:(write-region "" nil filename nil 0)
。 - Hubisan如果Emacs认为文本内容没有变化,它将不允许你保存缓冲区。最快的方法是使用C-x C-f打开文件,然后按下空格和退格键,这样就能够保存一个没有任何内容的文件。尽管这种方法可能不是最干净的。
还有其他改变“缓冲区已被修改”标志的方法,但我认为没有更简单的方法了。
(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))))))
M-! touch __init__.py RET
最简单的方法
通过shell操作创建一个空文件(但不打开它):
M-! > __init__.py
RET
打开新文件:
C-x C-f RET
(注意:我们不必再次输入文件名,因为新文件自动成为第一选择)
_
后跟__init__.py
。 - Singletoned(shell-command (concat "touch " (buffer-file-name)))
C-x C-f __init__.py RET C-x C-s
对我来说很好用(版本24.5.1
),所以也许这个问题在最初提问时已经解决了。 - JianC-x j
绑定为打开dired,然后_
用于创建一个新文件,这相当简短。 - Singletoned