How to create new file from dired mode?

前端 未结 6 1268
眼角桃花
眼角桃花 2021-02-06 20:52

I want to create a new file in dired mode. Is there \"create new file\" command in dired mode ? For example, When I type \"c\" in dired mode, it creates \"untitled.txt\". It\'s

6条回答
  •  佛祖请我去吃肉
    2021-02-06 21:09

    The following contains two (2) options, one of which requires that touch be in the $PATH -- alternatively, the absolute path may be used. touch is usually available on unix flavor systems, e.g., OSX, etc. This function will automatically number the files / buffers successively -- e.g., untitled.txt; untitled1.txt; untitled2.txt, etc.

    (define-key dired-mode-map (kbd "c") 'dired-new-file)
    
    (defun dired-new-file ()
    (interactive)
      (let* (
          (n 0)
          lawlist-filename
          (dired-buffer-name (buffer-name)))
        (catch 'done
          (while t
            (setq lawlist-filename (concat "untitled"
              (if (= n 0) "" (int-to-string n))
                ".txt"))
            (setq n (1+ n))
            (if (not (file-exists-p lawlist-filename))
              (throw 'done nil)) ))
        (message "[b]uffer + file (maybe) | [f]ile + buffer (maybe)")
        (let ((file-or-buffer (read-char-exclusive)))
          (cond
            ((eq file-or-buffer ?b)
              (switch-to-buffer (get-buffer-create lawlist-filename))
              (text-mode)
              (or (y-or-n-p (format "Save Buffer `%s'? "lawlist-filename))
                (error "Done."))
              (write-file lawlist-filename)
              (with-current-buffer dired-buffer-name
                (revert-buffer)))
            ((eq file-or-buffer ?f)
              (start-process "touch-file" nil "touch" lawlist-filename)
              (revert-buffer)
              (or (y-or-n-p (format "Open `%s'? "lawlist-filename))
                (error "Done."))
              (find-file lawlist-filename)
              (text-mode))
            (t (message "You have exited the function.")) )) ))
    

提交回复
热议问题