org-duration.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. ;;; org-duration.el --- Library handling durations -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2017-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This library provides tools to manipulate durations. A duration
  18. ;; can have multiple formats:
  19. ;;
  20. ;; - 3:12
  21. ;; - 1:23:45
  22. ;; - 1y 3d 3h 4min
  23. ;; - 1d3h5min
  24. ;; - 3d 13:35
  25. ;; - 2.35h
  26. ;;
  27. ;; More accurately, it consists of numbers and units, as defined in
  28. ;; variable `org-duration-units', possibly separated with white
  29. ;; spaces, and an optional "H:MM" or "H:MM:SS" part, which always
  30. ;; comes last. White spaces are tolerated between the number and its
  31. ;; relative unit. Variable `org-duration-format' controls durations
  32. ;; default representation.
  33. ;;
  34. ;; The library provides functions allowing to convert a duration to,
  35. ;; and from, a number of minutes: `org-duration-to-minutes' and
  36. ;; `org-duration-from-minutes'. It also provides two lesser tools:
  37. ;; `org-duration-p', and `org-duration-h:mm-only-p'.
  38. ;;
  39. ;; Users can set the number of minutes per unit, or define new units,
  40. ;; in `org-duration-units'. The library also supports canonical
  41. ;; duration, i.e., a duration that doesn't depend on user's settings,
  42. ;; through optional arguments.
  43. ;;; Code:
  44. (require 'org-macs)
  45. (org-assert-version)
  46. (require 'cl-lib)
  47. (require 'org-macs)
  48. ;;; Public variables
  49. (defconst org-duration-canonical-units
  50. `(("min" . 1)
  51. ("h" . 60)
  52. ("d" . ,(* 60 24)))
  53. "Canonical time duration units.
  54. See `org-duration-units' for details.")
  55. (defcustom org-duration-units
  56. `(("min" . 1)
  57. ("h" . 60)
  58. ("d" . ,(* 60 24))
  59. ("w" . ,(* 60 24 7))
  60. ("m" . ,(* 60 24 30))
  61. ("y" . ,(* 60 24 365.25)))
  62. "Conversion factor to minutes for a duration.
  63. Each entry has the form (UNIT . MODIFIER).
  64. In a duration string, a number followed by UNIT is multiplied by
  65. the specified number of MODIFIER to obtain a duration in minutes.
  66. For example, the following value
  67. \\=`((\"min\" . 1)
  68. (\"h\" . 60)
  69. (\"d\" . ,(* 60 8))
  70. (\"w\" . ,(* 60 8 5))
  71. (\"m\" . ,(* 60 8 5 4))
  72. (\"y\" . ,(* 60 8 5 4 10)))
  73. is meaningful if you work an average of 8 hours per day, 5 days
  74. a week, 4 weeks a month and 10 months a year.
  75. When setting this variable outside the Customize interface, make
  76. sure to call the following command:
  77. \\[org-duration-set-regexps]"
  78. :group 'org-agenda
  79. :version "26.1"
  80. :package-version '(Org . "9.1")
  81. :set (lambda (var val)
  82. (set-default-toplevel-value var val)
  83. ;; Avoid recursive load at startup.
  84. (when (featurep 'org-duration)
  85. (org-duration-set-regexps)))
  86. :initialize 'custom-initialize-changed
  87. :type '(choice
  88. (const :tag "H:MM" h:mm)
  89. (const :tag "H:MM:SS" h:mm:ss)
  90. (alist :key-type (string :tag "Unit")
  91. :value-type (number :tag "Modifier"))))
  92. (defcustom org-duration-format '(("d" . nil) (special . h:mm))
  93. "Format definition for a duration.
  94. The value can be set to, respectively, the symbols `h:mm:ss' or
  95. `h:mm', which means a duration is expressed as, respectively,
  96. a \"H:MM:SS\" or \"H:MM\" string.
  97. Alternatively, the value can be a list of entries following the
  98. pattern:
  99. (UNIT . REQUIRED?)
  100. UNIT is a unit string, as defined in `org-duration-units'. The
  101. time duration is formatted using only the time components that
  102. are specified here.
  103. Units with a zero value are skipped, unless REQUIRED? is non-nil.
  104. In that case, the unit is always used.
  105. The list can also contain one of the following special entries:
  106. (special . h:mm)
  107. (special . h:mm:ss)
  108. Units shorter than an hour are ignored. The hours and
  109. minutes part of the duration is expressed unconditionally
  110. with H:MM, or H:MM:SS, pattern.
  111. (special . PRECISION)
  112. A duration is expressed with a single unit, PRECISION being
  113. the number of decimal places to show. The unit chosen is the
  114. first one required or with a non-zero integer part. If there
  115. is no such unit, the smallest one is used.
  116. Eventually, if the list contains the symbol `compact', the
  117. duration is expressed in a compact form, without any white space
  118. between units.
  119. For example,
  120. ((\"d\" . nil) (\"h\" . t) (\"min\" . t))
  121. means a duration longer than a day is expressed in days, hours
  122. and minutes, whereas a duration shorter than a day is always
  123. expressed in hours and minutes, even when shorter than an hour.
  124. On the other hand, the value
  125. ((\"d\" . nil) (\"min\" . nil))
  126. means a duration longer than a day is expressed in days and
  127. minutes, whereas a duration shorter than a day is expressed
  128. entirely in minutes, even when longer than an hour.
  129. The following format
  130. ((\"d\" . nil) (special . h:mm))
  131. means that any duration longer than a day is expressed with both
  132. a \"d\" unit and a \"H:MM\" part, whereas a duration shorter than
  133. a day is expressed only as a \"H:MM\" string.
  134. Eventually,
  135. ((\"d\" . nil) (\"h\" . nil) (special . 2))
  136. expresses a duration longer than a day as a decimal number, with
  137. a 2-digits fractional part, of \"d\" unit. A duration shorter
  138. than a day uses \"h\" unit instead."
  139. :group 'org-time
  140. :group 'org-clock
  141. :package-version '(Org . "9.1")
  142. :type '(choice
  143. (const :tag "Use H:MM" h:mm)
  144. (const :tag "Use H:MM:SS" h:mm:ss)
  145. (repeat :tag "Use units"
  146. (choice
  147. (cons :tag "Use units"
  148. (string :tag "Unit")
  149. (choice (const :tag "Skip when zero" nil)
  150. (const :tag "Always used" t)))
  151. (cons :tag "Use a single decimal unit"
  152. (const special)
  153. (integer :tag "Number of decimals"))
  154. (cons :tag "Use both units and H:MM"
  155. (const special)
  156. (const h:mm))
  157. (cons :tag "Use both units and H:MM:SS"
  158. (const special)
  159. (const h:mm:ss))
  160. (const :tag "Use compact form" compact)))))
  161. ;;; Internal variables and functions
  162. (defconst org-duration--h:mm-re
  163. "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{1,2\\}[ \t]*\\'"
  164. "Regexp matching a duration expressed with H:MM or H:MM:SS format.
  165. See `org-duration--h:mm:ss-re' to only match the latter. Hours
  166. can use any number of digits.")
  167. (defconst org-duration--h:mm:ss-re
  168. "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{2\\}[ \t]*\\'"
  169. "Regexp matching a duration expressed H:MM:SS format.
  170. See `org-duration--h:mm-re' to also support H:MM format. Hours
  171. can use any number of digits.")
  172. (defvar org-duration--unit-re nil
  173. "Regexp matching a duration with an unit.
  174. Allowed units are defined in `org-duration-units'. Match group
  175. 1 contains the bare number. Match group 2 contains the unit.")
  176. (defvar org-duration--full-re nil
  177. "Regexp matching a duration expressed with units.
  178. Allowed units are defined in `org-duration-units'.")
  179. (defvar org-duration--mixed-re nil
  180. "Regexp matching a duration expressed with units and H:MM or H:MM:SS format.
  181. Allowed units are defined in `org-duration-units'. Match group
  182. 1 contains units part. Match group 2 contains H:MM or H:MM:SS
  183. part.")
  184. (defun org-duration--modifier (unit &optional canonical)
  185. "Return modifier associated to string UNIT.
  186. When optional argument CANONICAL is non-nil, refer to
  187. `org-duration-canonical-units' instead of `org-duration-units'."
  188. (or (cdr (assoc unit (if canonical
  189. org-duration-canonical-units
  190. org-duration-units)))
  191. (error "Unknown unit: %S" unit)))
  192. ;;; Public functions
  193. ;;;###autoload
  194. (defun org-duration-set-regexps ()
  195. "Set duration related regexps."
  196. (interactive)
  197. (setq org-duration--unit-re
  198. (concat "\\([0-9]+\\(?:\\.[0-9]*\\)?\\)[ \t]*"
  199. ;; Since user-defined units in `org-duration-units'
  200. ;; can differ from canonical units in
  201. ;; `org-duration-canonical-units', include both in
  202. ;; regexp.
  203. (regexp-opt (mapcar #'car (append org-duration-canonical-units
  204. org-duration-units))
  205. t)))
  206. (setq org-duration--full-re
  207. (format "\\`\\(?:[ \t]*%s\\)+[ \t]*\\'" org-duration--unit-re))
  208. (setq org-duration--mixed-re
  209. (format "\\`\\(?1:\\([ \t]*%s\\)+\\)[ \t]*\
  210. \\(?2:[0-9]+\\(?::[0-9][0-9]\\)\\{1,2\\}\\)[ \t]*\\'"
  211. org-duration--unit-re)))
  212. ;;;###autoload
  213. (defun org-duration-p (s)
  214. "Non-nil when string S is a time duration."
  215. (and (stringp s)
  216. (or (string-match-p org-duration--full-re s)
  217. (string-match-p org-duration--mixed-re s)
  218. (string-match-p org-duration--h:mm-re s))))
  219. ;;;###autoload
  220. (defun org-duration-to-minutes (duration &optional canonical)
  221. "Return number of minutes of DURATION string.
  222. When optional argument CANONICAL is non-nil, ignore
  223. `org-duration-units' and use standard time units value.
  224. A bare number is translated into minutes. The empty string is
  225. translated into 0.0.
  226. Return value as a float. Raise an error if duration format is
  227. not recognized."
  228. (save-match-data
  229. (cond
  230. ((equal duration "") 0.0)
  231. ((numberp duration) (float duration))
  232. ((string-match-p org-duration--h:mm-re duration)
  233. (pcase-let ((`(,hours ,minutes ,seconds)
  234. (mapcar #'string-to-number (split-string duration ":"))))
  235. (+ (/ (or seconds 0) 60.0) minutes (* 60 hours))))
  236. ((string-match-p org-duration--full-re duration)
  237. (let ((minutes 0)
  238. (s 0))
  239. (while (string-match org-duration--unit-re duration s)
  240. (setq s (match-end 0))
  241. (let ((value (string-to-number (match-string 1 duration)))
  242. (unit (match-string 2 duration)))
  243. (cl-incf minutes (* value (org-duration--modifier unit canonical)))))
  244. (float minutes)))
  245. ((string-match org-duration--mixed-re duration)
  246. (let ((units-part (match-string 1 duration))
  247. (hms-part (match-string 2 duration)))
  248. (+ (org-duration-to-minutes units-part)
  249. (org-duration-to-minutes hms-part))))
  250. ((string-match-p "\\`[0-9]+\\(\\.[0-9]*\\)?\\'" duration)
  251. (float (string-to-number duration)))
  252. (t (error "Invalid duration format: %S" duration)))))
  253. ;;;###autoload
  254. (defun org-duration-from-minutes (minutes &optional fmt canonical)
  255. "Return duration string for a given number of MINUTES.
  256. Format duration according to `org-duration-format' or FMT, when
  257. non-nil.
  258. When optional argument CANONICAL is non-nil, ignore
  259. `org-duration-units' and use standard time units value.
  260. Raise an error if expected format is unknown."
  261. (pcase (or fmt org-duration-format)
  262. (`h:mm
  263. (format "%d:%02d" (/ minutes 60) (mod minutes 60)))
  264. (`h:mm:ss
  265. (let* ((whole-minutes (floor minutes))
  266. (seconds (mod (* 60 minutes) 60)))
  267. (format "%s:%02d"
  268. (org-duration-from-minutes whole-minutes 'h:mm)
  269. seconds)))
  270. ((pred atom) (error "Invalid duration format specification: %S" fmt))
  271. ;; Mixed format. Call recursively the function on both parts.
  272. ((and duration-format
  273. (let `(special . ,(and mode (or `h:mm:ss `h:mm)))
  274. (assq 'special duration-format)))
  275. (let* ((truncated-format
  276. ;; Remove "special" mode from duration format in order to
  277. ;; recurse properly. Also remove units smaller or equal
  278. ;; to an hour since H:MM part takes care of it.
  279. (cl-remove-if-not
  280. (lambda (pair)
  281. (pcase pair
  282. (`(,(and unit (pred stringp)) . ,_)
  283. (> (org-duration--modifier unit canonical) 60))
  284. (_ nil)))
  285. duration-format))
  286. (min-modifier ;smallest modifier above hour
  287. (and truncated-format
  288. (apply #'min
  289. (mapcar (lambda (p)
  290. (org-duration--modifier (car p) canonical))
  291. truncated-format)))))
  292. (if (or (null min-modifier) (< minutes min-modifier))
  293. ;; There is not unit above the hour or the smallest unit
  294. ;; above the hour is too large for the number of minutes we
  295. ;; need to represent. Use H:MM or H:MM:SS syntax.
  296. (org-duration-from-minutes minutes mode canonical)
  297. ;; Represent minutes above hour using provided units and H:MM
  298. ;; or H:MM:SS below.
  299. (let* ((units-part (* min-modifier (/ (floor minutes) min-modifier)))
  300. (minutes-part (- minutes units-part))
  301. (compact (memq 'compact duration-format)))
  302. (concat
  303. (org-duration-from-minutes units-part truncated-format canonical)
  304. (and (not compact) " ")
  305. (org-duration-from-minutes minutes-part mode))))))
  306. ;; Units format.
  307. (duration-format
  308. (let* ((fractional
  309. (let ((digits (cdr (assq 'special duration-format))))
  310. (and digits
  311. (or (wholenump digits)
  312. (error "Unknown formatting directive: %S" digits))
  313. (format "%%.%df" digits))))
  314. (selected-units
  315. (sort (cl-remove-if
  316. ;; Ignore special format cells and compact option.
  317. (lambda (pair)
  318. (pcase pair
  319. ((or `compact `(special . ,_)) t)
  320. (_ nil)))
  321. duration-format)
  322. (lambda (a b)
  323. (> (org-duration--modifier (car a) canonical)
  324. (org-duration--modifier (car b) canonical)))))
  325. (separator (if (memq 'compact duration-format) "" " ")))
  326. (cond
  327. ;; Fractional duration: use first unit that is either required
  328. ;; or smaller than MINUTES.
  329. (fractional
  330. (let* ((unit (car
  331. (or (cl-find-if
  332. (lambda (pair)
  333. (pcase pair
  334. (`(,u . ,req?)
  335. (or req?
  336. (<= (org-duration--modifier u canonical)
  337. minutes)))))
  338. selected-units)
  339. ;; Fall back to smallest unit.
  340. (org-last selected-units))))
  341. (modifier (org-duration--modifier unit canonical)))
  342. (concat (format fractional (/ (float minutes) modifier)) unit)))
  343. ;; Otherwise build duration string according to available
  344. ;; units.
  345. ((org-string-nw-p
  346. (org-trim
  347. (mapconcat
  348. (lambda (units)
  349. (pcase-let* ((`(,unit . ,required?) units)
  350. (modifier (org-duration--modifier unit canonical)))
  351. (cond ((<= modifier minutes)
  352. (let ((value (floor minutes modifier)))
  353. (cl-decf minutes (* value modifier))
  354. (format "%s%d%s" separator value unit)))
  355. (required? (concat separator "0" unit))
  356. (t ""))))
  357. selected-units
  358. ""))))
  359. ;; No unit can properly represent MINUTES. Use the smallest
  360. ;; one anyway.
  361. (t
  362. (pcase-let ((`((,unit . ,_)) (last selected-units)))
  363. (concat "0" unit))))))))
  364. ;;;###autoload
  365. (defun org-duration-h:mm-only-p (times)
  366. "Non-nil when every duration in TIMES has \"H:MM\" or \"H:MM:SS\" format.
  367. TIMES is a list of duration strings.
  368. Return nil if any duration is expressed with units, as defined in
  369. `org-duration-units'. Otherwise, if any duration is expressed
  370. with \"H:MM:SS\" format, return `h:mm:ss'. Otherwise, return
  371. `h:mm'."
  372. (let (hms-flag)
  373. (catch :exit
  374. (dolist (time times)
  375. (cond ((string-match-p org-duration--full-re time)
  376. (throw :exit nil))
  377. ((string-match-p org-duration--mixed-re time)
  378. (throw :exit nil))
  379. (hms-flag nil)
  380. ((string-match-p org-duration--h:mm:ss-re time)
  381. (setq hms-flag 'h:mm:ss))))
  382. (or hms-flag 'h:mm))))
  383. ;;; Initialization
  384. (org-duration-set-regexps)
  385. (provide 'org-duration)
  386. ;; Local variables:
  387. ;; generated-autoload-file: "org-loaddefs.el"
  388. ;; End:
  389. ;;; org-duration.el ends here