2008-10-30 31 views

Respuesta

110
C-u M-! date 
+17

Cuán increíblemente intuitivo :) – msandiford

+50

Para completar: 'M-!' Es el atajo de teclado para la función 'shell-command'. Entonces 'M-! date' llamará al comando de shell 'date', y lo mostrará en el área de salida (el minibúfer, ya que la salida es lo suficientemente corta como para caber). El 'C-u' es un argumento de prefijo que hace que' M-! 'Ponga su salida en el búfer actual en su lugar. – ShreevatsaR

+10

Obtendrá resultados sorprendentes con esto si usa Windows, "fecha" es un comando para cambiar la fecha del sistema. Las respuestas que manejan esta pregunta con elisp no dependen de un sistema operativo Unix, Unix o incluso Linux. –

32

poner en su archivo .emacs:

;; ==================== 
;; insert date and time 

(defvar current-date-time-format "%a %b %d %H:%M:%S %Z %Y" 
    "Format of date to insert with `insert-current-date-time' func 
See help of `format-time-string' for possible replacements") 

(defvar current-time-format "%a %H:%M:%S" 
    "Format of date to insert with `insert-current-time' func. 
Note the weekly scope of the command's precision.") 

(defun insert-current-date-time() 
    "insert the current date and time into current buffer. 
Uses `current-date-time-format' for the formatting the date/time." 
     (interactive) 
     (insert "==========\n") 
;  (insert (let() (comment-start))) 
     (insert (format-time-string current-date-time-format (current-time))) 
     (insert "\n") 
     ) 

(defun insert-current-time() 
    "insert the current time (1-week scope) into the current buffer." 
     (interactive) 
     (insert (format-time-string current-time-format (current-time))) 
     (insert "\n") 
     ) 

(global-set-key "\C-c\C-d" 'insert-current-date-time) 
(global-set-key "\C-c\C-t" 'insert-current-time) 

Reference

+1

Utilizo algo parecido a esto, pero lo cambio de C-c C-t a C-x C-t porque C-c C-t se interpone en el enlace de org-mode "Marcar elemento TODO". Lo cual desafortunadamente está conectado a la memoria muscular para mí. :) – AssembledGhost

+0

'" \ C-c \ C-d "' no pasa nada por mí. En realidad, elimina la línea actual cuando se escribe 'C-d'. Pero creo que por eso 'C-c' no está funcionando. – Jack

13

Puede instalar yasnippet, que le permitirá escribir "tiempo" y la tecla de tabulación, y lo hace mucho más. Simplemente llama current-time-string detrás de las escenas, por lo que puede controlar el formato utilizando format-time-string.

+1

yasnippet es una fuente de recursos en comparación con las plantillas incorporadas y hippie-expand. –

25

he utilizado estos fragmentos cortos:

(defun now() 
    "Insert string for the current time formatted like '2:34 PM'." 
    (interactive)     ; permit invocation in minibuffer 
    (insert (format-time-string "%D %-I:%M %p"))) 

(defun today() 
    "Insert string for today's date nicely formatted in American style, 
e.g. Sunday, September 17, 2000." 
    (interactive)     ; permit invocation in minibuffer 
    (insert (format-time-string "%A, %B %e, %Y"))) 

provienen originalmente journal.el

+0

dulce, hace el trabajo muy bien :) – ljs

+1

gracias. muy agradable. para cualquiera que sea completamente novato en emacs: use esto agregándolo a su archivo '.emacs' y guárdelo, y luego mueva su cursor (punto) al paréntesis final de cada función y luego' Mx Me' para cada uno . Ahora puedes insertar usando 'M-x ahora' o' M-x hoy' donde quieras. – celwell

1

M-1 M-! fecha

esto hace que el comando shell ejecuta a ser insertado en el búfer que actualmente está editando en lugar de un nuevo buffer.

1

Gracias, CMS! Mi variación, por lo que vale la pena - me hace bastante feliz:

(defvar bjk-timestamp-format "%Y-%m-%d %H:%M" 
    "Format of date to insert with `bjk-timestamp' function 
%Y-%m-%d %H:%M will produce something of the form YYYY-MM-DD HH:MM 
Do C-h f on `format-time-string' for more info") 


(defun bjk-timestamp() 
    "Insert a timestamp at the current point. 
Note no attempt to go to beginning of line and no added carriage return. 
Uses `bjk-timestamp-format' for formatting the date/time." 
     (interactive) 
     (insert (format-time-string bjk-timestamp-format (current-time))) 
     ) 

que poner esto en un archivo que se llama por mi .emacs usando:

(load "c:/bjk/elisp/bjk-timestamp.el") 

la que tanto hace que sea más fácil de modificar sin arriesgarme a romper algo más en mis archivos .emacs, y me permitió un punto de entrada fácil en tal vez algún día en realidad aprendiendo de qué se trata esta programación de Emacs Lisp.

P.S. Las críticas con respecto a mi técnica n00b son bienvenidas.

1

Para obtener una respuesta similar a las ya publicadas, junto con explicaciones y más extensiones, como abrir automáticamente un archivo e insertar la fecha actual al final (como un diario), consulte Paul Ford's discussion of his emacs utilities.

10

Para insertar fecha: M-x org-sello de tiempo Por fecha y hora de inserción: C-u M-x org-sello de tiempo

Puede ser que usted puede vincular una clave global para este comando.

El método del modo org es muy fácil de usar, puede seleccionar cualquier fecha del calendario.

+0

Exactamente lo que estaba buscando, gracias @tangxinfa! Lo puse en una macro con algunas 'entradas', le puse un nombre y lo conecté con un teclado. – ragerdl

0

Aquí está mi opinión sobre esto.

(defun modi/insert-time-stamp (option) 
    "Insert date, time, user name - DWIM. 

If the point is NOT in a comment/string, the time stamp is inserted prefixed 
with `comment-start' characters. 

If the point is IN a comment/string, the time stamp is inserted without the 
`comment-start' characters. If the time stamp is not being inserted immediately 
after the `comment-start' characters (followed by optional space), 
the time stamp is inserted with “--” prefix. 

If the buffer is in a major mode where `comment-start' var is nil, no prefix is 
added regardless. 

Additional control: 

     C-u -> Only `comment-start'/`--' prefixes are NOT inserted 
    C-u C-u -> Only user name is NOT inserted 
C-u C-u C-u -> Both prefix and user name are not inserted." 
    (interactive "P") 
    (let ((current-date-time-format "%a %b %d %H:%M:%S %Z %Y")) 
    ;; Insert a space if there is no space to the left of the current point 
    ;; and it's not at the beginning of a line 
    (when (and (not (looking-back "^ *")) 
       (not (looking-back " "))) 
     (insert " ")) 
    ;; Insert prefix only if `comment-start' is defined for the major mode 
    (when (stringp comment-start) 
     (if (or (nth 3 (syntax-ppss)) ; string 
       (nth 4 (syntax-ppss))) ; comment 
      ;; If the point is already in a comment/string 
      (progn 
      ;; If the point is not immediately after `comment-start' chars 
      ;; (followed by optional space) 
      (when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u 
           (equal option '(64)))) 
         (not (looking-back (concat comment-start " *"))) 
         (not (looking-back "^ *"))) 
       (insert "--"))) 
     ;; If the point is NOT in a comment 
     (progn 
      (when (not (or (equal option '(4)) ; C-u or C-u C-u C-u 
         (equal option '(64)))) 
      (insert comment-start))))) 
    ;; Insert a space if there is no space to the left of the current point 
    ;; and it's not at the beginning of a line 
    (when (and (not (looking-back "^ *")) 
       (not (looking-back " "))) 
     (insert " ")) 
    (insert (format-time-string current-date-time-format (current-time))) 
    (when (not (equal option '(16))) ; C-u C-u 
     (insert (concat " - " (getenv "USER")))) 
    ;; Insert a space after the time stamp if not at the end of the line 
    (when (not (looking-at " *$")) 
     (insert " ")))) 

Prefiero vincular esto a C-c d.

Cuestiones relacionadas