How do I create an empty file in emacs?

2019-01-21 10:35发布

How can I create an empty file from emacs, ideally from within a dired buffer?

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.

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.

Thanks

15条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-21 10:39

If you want Emacs to treat all new files as modified, you can automate the solution like this:

(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)))
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-21 10:39

Emacs won't allow you to save a buffer unless it thinks the contents have changed. The quickest, though possibly not cleanest is to open the file using C-x C-f, then press (say) space and backspace, then you should be able to save a file with no contents.

There are other ways of changing the "buffer has been modified" flag, but I don't think there's any easier.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-21 10:39

The best option would be:

(with-temp-file "filename"
  (insert ""))
查看更多
不美不萌又怎样
5楼-- · 2019-01-21 10:45

You can use the touch command:

M-! touch __init__.py RET
查看更多
走好不送
6楼-- · 2019-01-21 10:46

The shortest way

M-! > __init__.py RET

查看更多
趁早两清
7楼-- · 2019-01-21 10:48

I've modified answer from MrBones and created custom function with keybinding:

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

This is very useful to not spend time on recurring action of creating init.py everywhere in new Python project folder.

查看更多
登录 后发表回答