如何在Emacs中插入当前日期和时间到文件中?

97

在Emacs中,我可以使用哪些命令将当前日期和时间插入到文件的文本缓冲区中?

(例如,在记事本中相当于只需按F5,这几乎是唯一有用的功能!)


2
在记事本中按 Ctrl+G 可以打开“转到行”对话框,这也很有用! - cfeduke
12个回答

0

这是我的看法。

(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 " "))))

我更喜欢将其绑定到C-c d


0
这篇帖子出现在我想要一个简单的方法来插入当前日期和时间的时候。但是没有一个答案显示了最简单的插入时间的方法。然后我继续搜索,找到了答案...
使用C-u C-c . 插入带有当前日期和时间的活动时间戳。
使用C-u C-c ! 插入带有当前日期和时间的非活动时间戳。
省略C-u只插入日期,不包括时间,就像Misho发布的那样。
这种方法没有eclecticx的回答所带来的副作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接