Add times in buffer

2019-09-04 15:28发布

问题:

Suppose I have an emacs buffer which contains times in the format minutes'seconds'' and in the format minutes' as well as seconds'' for example 5'30'', 6'15'', 10' and 1''. Is it possible to add all times in the buffer automatically with output (in the minibuffer) in the format minutes'seconds'' (here = 21'46'')?

回答1:

Is this what you want?

(defun add-times ()                 
  (interactive)                                
  (let ((minutes 0) (seconds 0))     
    (save-excursion                        
      (goto-char (point-min))
      (while (re-search-forward "\\([0-9]+\\)'\\('\\)?" (point-max) t)
        (if (match-string 2)
            (setq seconds (+ seconds (string-to-number (match-string 1))))
          (setq minutes (+ minutes (string-to-number (match-string 1)))))))
    (insert (format "%d'%d''"(+ minutes (/ seconds 60)) (% seconds 60)))))


回答2:

You can use:

(defun add-times ()
  (interactive)
  (save-excursion
    (let ((mins 0) (secs 0) 
          (accum-nums 
           (lambda (regexp)
             (let ((value 0))
               (beginning-of-buffer)
               (while (re-search-forward regexp nil t)
                 (setq value (+ value (string-to-int (match-string-no-properties 1)))))
               value))))
      (setq mins (funcall accum-nums "\\([0-9]+\\)'\\([^']\\|$\\)"))
      (setq secs (funcall accum-nums "\\([0-9]+\\)''"))
      ; adjust > 60 seconds
      (setq mins (+ mins (/ secs 60)))
      (setq secs (mod secs 60))
      (format "%d'%d''" mins secs))))

And you can use it like this: In the buffer of the file with the times, you type ESC: and then evaluate:

(insert (add-times))

If you want a function that does this also, asking for the buffer:

(defun insert-add-times-to-buffer-at-point (buffer)
  (interactive "BBuffer to add and insert times: ")
  (with-current-buffer buffer
    (insert (add-times))))


标签: emacs lisp elisp