如何从 emacs 创建一个空文件,最好是在 dired 缓冲区中?
例如,我刚刚在 dired 模式下打开了一个 Python 模块,创建了一个新目录,在 dired 中打开它,现在需要__init__.py
在目录中添加一个空文件。
如果我使用C-x C-f __init__.py RET C-x C-s
,则 emacs 不会创建该文件,因为没有对其进行任何更改。我必须输入文件,保存它,删除我的输入,然后再次保存它才能工作。
谢谢
您可以使用 touch 命令:
M-! touch __init__.py RET
以下作品:
Cx b __init__.py RET Cx Cw RET
如果您在 dired 缓冲区中,该文件将保存在此处显示的目录中。
诀窍是首先通过切换到一个不存在的名称来创建一个空缓冲区。然后写出文件。
如果您希望 Emacs 将所有新文件视为已修改,您可以像这样自动化解决方案:
(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)))
以编程方式并且不依赖于touch
,这很容易:
(with-temp-buffer (write-file "path/to/empty/file/"))
在这个线程之后,Emacs 添加了两个新命令:
这些命令将在 emacs 27.1 版本中可用。
Emacs 不允许您保存缓冲区,除非它认为内容已更改。最快但可能不是最干净的方法是使用 打开文件C-x C-f,然后按(比如说)空格和退格键,然后您应该能够保存没有内容的文件。
还有其他方法可以更改“缓冲区已被修改”标志,但我认为没有更简单的方法。
这里是改编的dired-create-directory
。它的工作方式相同,因此除了普通文件名外,您还可以为文件(例如 )指定新的父目录(将在当前目录下创建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))))))
使用触摸命令。
M-! touch __init__.py RET
最短的路
通过 shell 操作创建一个空文件(但不打开它):
M-! > __init__.py
RET
打开新文件:
C-x C-f RET
(注意:我们不必再次输入名称,因为新文件会自动成为首选)
(shell-command (concat "touch " (buffer-file-name)))
如果您已经打开了空文件,它将做您想做的事。
您可以通过运行将空缓冲区标记为已修改set-buffer-modified-p
。然后当你保存它时,Emacs 将写入该文件。
M-; ; Eval
(set-buffer-modified-p t) ; Mark modified
C-x C-s ; Save buffer
我使用以下绑定到t
dired。
(defun my-dired-touch (filename)
(interactive (list (read-string "Filename: " ".gitkeep")))
(with-temp-buffer
(write-file filename)))
;; optionally bind it in dired
(with-eval-after-load 'dired
(define-key dired-mode-map "t" 'my-dired-touch))
我已经修改了 MrBones 的答案并使用键绑定创建了自定义函数:
; create empty __init__.py at the place
(defun create-empty-init-py()
(interactive)
(shell-command "touch __init__.py")
)
(global-set-key (kbd "C-c p i") 'create-empty-init-py)
这对于不花时间在新的 Python 项目文件夹中到处创建init .py 的重复操作非常有用。
最好的选择是:
(with-temp-file "filename"
(insert ""))