¿Cómo puedo crear un archivo vacío en emacs?


¿Cómo puedo crear un archivo vacío desde emacs, idealmente desde un buffer dired?

Por ejemplo, acabo de abrir un módulo Python en modo dired, he creado un nuevo directorio, lo he abierto en dired, y ahora necesito añadir un archivo __init__.py vacío en el directorio.

Si utilizo C-x C-f __init__.py RET C-x C-s entonces emacs no crea el archivo porque no se han realizado cambios en él. Tendría que escribir en el archivo, guardarlo, eliminar mi escritura y luego guardarlo de nuevo para que funcione.

Gracias

Author: Singletoned, 2010-04-07

15 answers

Aquí hay una adaptación de dired-create-directory. Funciona de la misma manera, así que además de un nombre de archivo simple, también puede especificar nuevos directorios padre (que se crearán bajo el directorio actual) para el archivo (por ejemplo, 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))))))
 10
Author: phils,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 02:49:44

Puede usar el comando touch:

M-! touch __init__.py RET
 53
Author: Dani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-18 16:55:39

Las siguientes obras:

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

Si está en un búfer dired el archivo se guardará en el directorio show here.

El truco es crear primero un búfer vacío cambiando a un nombre que no existe. Luego escribe el archivo.

 27
Author: slu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-08 18:57:50

Si desea que Emacs trate todos los archivos nuevos como modificados, puede automatizar la solución de esta manera:

(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)))
 20
Author: Kilian Foth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 00:17:41

Emacs no le permitirá guardar un buffer a menos que piense que el contenido ha cambiado. Lo más rápido, aunque posiblemente no lo más limpio, es abrir el archivo usando C-x C-f, luego presione (digamos) espacio y retroceso, entonces debería poder guardar un archivo sin contenido.

Hay otras formas de cambiar la bandera "buffer ha sido modificado", pero no creo que sea más fácil.

 12
Author: Vatine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-07 12:03:50

Programáticamente y sin ninguna dependencia de touch, es bastante fácil:

(with-temp-buffer (write-file "path/to/empty/file/"))
 10
Author: Joao Tavora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-06 20:19:13

Utilice el comando touch.

M-! touch __init__.py RET
 5
Author: Uchenna Nwanyanwu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-16 15:36:51

El camino más corto

M-! > __init__.py RET

 4
Author: thanhpk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-02 02:45:42

(shell-command (concat "touch " (buffer-file-name))) hará lo que quieras, si ya has abierto el archivo vacío.

 3
Author: Squidly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-16 15:33:29

Además De otras respuestas en la página, puede utilizar f.el'la función s f-touch:

M-:(f-touch "__init__.py")RET

 2
Author: Mirzhan Irkegulov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-18 10:34:25

Después de este hilo, Emacs ha añadido dos nuevos comandos:

  1. make-empty-file
  2. dired-create-empty-file

Estos comandos estarán disponibles en la versión 27.1 de emacs.

 2
Author: Tino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 04:43:14

Puede marcar un búfer vacío como modificado ejecutando set-buffer-modified-p. Luego, cuando lo guarde, Emacs escribirá el archivo.

M-;                         ; Eval
(set-buffer-modified-p t)   ; Mark modified
C-x C-s                     ; Save buffer
 1
Author: Ian Mackinnon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-05 12:18:31

Utilizo el siguiente enlace a t en 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))
 1
Author: jenesaisquoi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 17:25:16

He modificado la respuesta de MrBones y he creado una función personalizada con 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)

Esto es muy útil para no gastar tiempo en la acción recurrente de crear init. py en todas partes en la nueva carpeta del proyecto Python.

 0
Author: alex_koval,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-06 07:52:33

La mejor opción sería:

(with-temp-file "filename"
  (insert ""))
 0
Author: Marcin Antczak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-25 13:07:12