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