org-duration.el 15 KB

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