org-duration.el 15 KB

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