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 11:01

Use touch command.

M-! touch __init__.py RET
查看更多
倾城 Initia
3楼-- · 2019-01-21 11:03

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))))))
查看更多
Luminary・发光体
4楼-- · 2019-01-21 11:03

I use the following bound to t in 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))
查看更多
登录 后发表回答