org-duration.el 15 KB

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