views:

244

answers:

4

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

+6  A: 

can you use touch command ?

Dani
yep -- `M-! touch __init__.py RET`
offby1
@offby1, if you add that as a proper answer, I'll choose it, as that's the one that works best for me. It even uses whatever directory dired is in as the cwd.
Singletoned
I like that very much, too! I just don't like typing the M-! bit, but I guess I can change the keybinding :)
Vivi
+5  A: 

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.

Vatine
+6  A: 

If you want emacs to treat all new files as modified, you can auomate 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)))
Kilian Foth
I like this, and I think I'll probably set it anyway, because it seems a saner in the general case, but the `M-! touch __init__.py` is shorter and doesn't involve opening and closing a buffer.
Singletoned
+3  A: 

The following works:

C-x b __init__.py RET C-x C-w RET

If you're in a dired buffer the file will be saved in the directory show here.

The trick is to first create an empty buffer by switching to a name that doesn't exist. Then write out the file.

slu