org-duration.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. ;;; org-duration.el --- Library handling durations -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2017 Nicolas Goaziou
  3. ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This program is free software; you can redistribute it and/or modify
  6. ;; it under the terms of the GNU General Public License as published by
  7. ;; the Free Software Foundation, either version 3 of the License, or
  8. ;; (at your option) any later version.
  9. ;; This program is distributed in the hope that it will be useful,
  10. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ;; GNU General Public License for more details.
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;; This library provides tools to manipulate durations. A duration
  17. ;; can have multiple formats:
  18. ;;
  19. ;; - 3:12
  20. ;; - 1:23:45
  21. ;; - 1y 3d 3h 4min
  22. ;; - 3d 13:35
  23. ;; - 2.35h
  24. ;;
  25. ;; More accurately, it consists of numbers and units, as defined in
  26. ;; variable `org-duration-units', separated with white spaces, and
  27. ;; a "H:MM" or "H:MM:SS" part. White spaces are tolerated between the
  28. ;; number and its relative unit. Variable `org-duration-format'
  29. ;; controls durations default representation.
  30. ;;
  31. ;; The library provides functions allowing to convert a duration to,
  32. ;; and from, a number of minutes: `org-duration-to-minutes' and
  33. ;; `org-duration-from-minutes'. It also provides two lesser tools:
  34. ;; `org-duration-p', and `org-duration-h:mm-only-p'.
  35. ;;
  36. ;; Users can set the number of minutes per unit, or define new units,
  37. ;; in `org-duration-units'. The library also supports canonical
  38. ;; duration, i.e., a duration that doesn't depend on user's settings,
  39. ;; through optional arguments.
  40. ;;; Code:
  41. (require 'cl-lib)
  42. (require 'org-macs)
  43. (declare-function org-trim "org-trim" (s &optional keep-lead))
  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, `h:mm:ss' or `h:mm', which
  87. means a duration is expressed as, respectively, a \"H:MM:SS\" or
  88. \"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. If a time unit in missing, it falls back to
  95. the next smallest unit.
  96. A non-nil REQUIRED? value for these keys indicates that the
  97. corresponding time component should always be included, even if
  98. its value is 0.
  99. Eventually, the list can contain one of the following special
  100. entries:
  101. (special . h:mm)
  102. (special . h:mm:ss)
  103. Units shorter than an hour are ignored. The hours and
  104. minutes part of the duration is expressed unconditionally
  105. with H:MM, or H:MM:SS, pattern.
  106. (special . PRECISION)
  107. A duration is expressed with a single unit, PRECISION being
  108. the number of decimal places to show. The unit chosen is the
  109. first one required or with a non-zero integer part. If there
  110. is no such unit, the smallest one is used.
  111. For example,
  112. ((\"d\" . nil) (\"h\" . t) (\"min\" . t))
  113. means a duration longer than a day is expressed in days, hours
  114. and minutes, whereas a duration shorter than a day is always
  115. expressed in hours and minutes, even when shorter than an hour.
  116. On the other hand, the value
  117. ((\"d\" . nil) (\"min\" . nil))
  118. means a duration longer than a day is expressed in days and
  119. minutes, whereas a duration shorter than a day is expressed
  120. entirely in minutes, even when longer than an hour.
  121. The following format
  122. ((\"d\" . nil) (special . h:mm))
  123. means that any duration longer than a day is expressed with both
  124. a \"d\" unit and a \"H:MM\" part, whereas a duration shorter than
  125. a day is expressed only as a \"H:MM\" string.
  126. Eventually,
  127. ((\"d\" . nil) (\"h\" . nil) (special . 2))
  128. expresses a duration longer than a day as a decimal number, with
  129. a 2-digits fractional part, of \"d\" unit. A duration shorter
  130. than a day uses \"h\" unit instead."
  131. :group 'org-time
  132. :group 'org-clock
  133. :version "26.1"
  134. :package-version '(Org . "9.1")
  135. :type '(choice
  136. (const :tag "Use H:MM" h:mm)
  137. (const :tag "Use H:MM:SS" h:mm:ss)
  138. (repeat :tag "Use units"
  139. (choice
  140. (cons :tag "Use units"
  141. (string :tag "Unit")
  142. (choice (const :tag "Skip when zero" nil)
  143. (const :tag "Always used" t)))
  144. (cons :tag "Use a single decimal unit"
  145. (const special)
  146. (integer :tag "Number of decimals"))
  147. (cons :tag "Use both units and H:MM"
  148. (const special)
  149. (const h:mm))
  150. (cons :tag "Use both units and H:MM:SS"
  151. (const special)
  152. (const h:mm:ss))))))
  153. ;;; Internal variables and functions
  154. (defconst org-duration--h:mm-re
  155. "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{1,2\\}[ \t]*\\'"
  156. "Regexp matching a duration expressed with H:MM or H:MM:SS format.
  157. See `org-duration--h:mm:ss-re' to only match the latter. Hours
  158. can use any number of digits.")
  159. (defconst org-duration--h:mm:ss-re
  160. "\\`[ \t]*[0-9]+\\(?::[0-9]\\{2\\}\\)\\{2\\}[ \t]*\\'"
  161. "Regexp matching a duration expressed H:MM:SS format.
  162. See `org-duration--h:mm-re' to also support H:MM format. Hours
  163. can use any number of digits.")
  164. (defvar org-duration--unit-re nil
  165. "Regexp matching a duration with an unit.
  166. Allowed units are defined in `org-duration-units'. Match group
  167. 1 contains the bare number. Match group 2 contains the unit.")
  168. (defvar org-duration--full-re nil
  169. "Regexp matching a duration expressed with units.
  170. Allowed units are defined in `org-duration-units'.")
  171. (defvar org-duration--mixed-re nil
  172. "Regexp matching a duration expressed with units and H:MM or H:MM:SS format.
  173. Allowed units are defined in `org-duration-units'. Match group
  174. 1 contains units part. Match group 2 contains H:MM or H:MM:SS
  175. part.")
  176. (defun org-duration--modifier (unit &optional canonical)
  177. "Return modifier associated to string UNIT.
  178. When optional argument CANONICAL is non-nil, refer to
  179. `org-duration-canonical-units' instead of `org-duration-units'."
  180. (or (cdr (assoc unit (if canonical
  181. org-duration-canonical-units
  182. org-duration-units)))
  183. (error "Unknown unit: %S" unit)))
  184. ;;; Public functions
  185. ;;;###autoload
  186. (defun org-duration-set-regexps ()
  187. "Set duration related regexps."
  188. (interactive)
  189. (setq org-duration--unit-re
  190. (concat "\\([0-9]+\\(?:\\.[0-9]*\\)?\\)[ \t]*"
  191. ;; Since user-defined units in `org-duration-units'
  192. ;; can differ from canonical units in
  193. ;; `org-duration-canonical-units', include both in
  194. ;; regexp.
  195. (regexp-opt (mapcar #'car (append org-duration-canonical-units
  196. org-duration-units))
  197. t)))
  198. (setq org-duration--full-re
  199. (format "\\`[ \t]*%s\\(?:[ \t]+%s\\)*[ \t]*\\'"
  200. org-duration--unit-re
  201. org-duration--unit-re))
  202. (setq org-duration--mixed-re
  203. (format "\\`[ \t]*\\(?1:%s\\(?:[ \t]+%s\\)*\\)[ \t]+\
  204. \\(?2:[0-9]+\\(?::[0-9][0-9]\\)\\{1,2\\}\\)[ \t]*\\'"
  205. org-duration--unit-re
  206. org-duration--unit-re)))
  207. ;;;###autoload
  208. (defun org-duration-p (s)
  209. "Non-nil when string S is a time duration."
  210. (and (stringp s)
  211. (or (string-match-p org-duration--full-re s)
  212. (string-match-p org-duration--mixed-re s)
  213. (string-match-p org-duration--h:mm-re s))))
  214. ;;;###autoload
  215. (defun org-duration-to-minutes (duration &optional canonical)
  216. "Return number of minutes of DURATION string.
  217. When optional argument CANONICAL is non-nil, ignore
  218. `org-duration-units' and use standard time units value.
  219. As a special case, a bare number represents minutes.
  220. Return value as a float. Raise an error if duration format is
  221. not recognized."
  222. (cond
  223. ((string-match-p org-duration--h:mm-re duration)
  224. (pcase-let ((`(,hours ,minutes ,seconds)
  225. (mapcar #'string-to-number (split-string duration ":"))))
  226. (+ (/ (or seconds 0) 60.0) minutes (* 60 hours))))
  227. ((string-match-p org-duration--full-re duration)
  228. (let ((minutes 0)
  229. (s 0))
  230. (while (string-match org-duration--unit-re duration s)
  231. (setq s (match-end 0))
  232. (let ((value (string-to-number (match-string 1 duration)))
  233. (unit (match-string 2 duration)))
  234. (cl-incf minutes (* value (org-duration--modifier unit canonical)))))
  235. (float minutes)))
  236. ((string-match org-duration--mixed-re duration)
  237. (let ((units-part (match-string 1 duration))
  238. (hms-part (match-string 2 duration)))
  239. (+ (org-duration-to-minutes units-part)
  240. (org-duration-to-minutes hms-part))))
  241. ((string-match-p "\\`[0-9]+\\(\\.[0-9]*\\)?\\'" duration)
  242. (float (string-to-number duration)))
  243. (t (error "Invalid duration format: %S" duration))))
  244. ;;;###autoload
  245. (defun org-duration-from-minutes (minutes &optional fmt canonical)
  246. "Return duration string for a given number of MINUTES.
  247. Format duration according to `org-duration-format' or FMT, when
  248. non-nil.
  249. When optional argument CANONICAL is non-nil, ignore
  250. `org-duration-units' and use standard time units value.
  251. Raise an error if expected format is unknown."
  252. (pcase (or fmt org-duration-format)
  253. (`h:mm
  254. (let ((minutes (floor minutes)))
  255. (format "%d:%02d" (/ minutes 60) (mod minutes 60))))
  256. (`h:mm:ss
  257. (let ((seconds (floor (* 60 minutes)) ))
  258. (format "%s:%02d"
  259. (org-duration-from-minutes (/ seconds 60) 'h:mm)
  260. (mod seconds 60))))
  261. ((pred atom) (error "Invalid duration format specification: %S" fmt))
  262. ;; Mixed format. Call recursively the function on both parts.
  263. ((and duration-format
  264. (let `(special . ,(and mode (or `h:mm:ss `h:mm)))
  265. (assq 'special duration-format)))
  266. (let* ((truncated-format
  267. ;; Remove "special" mode from duration format in order to
  268. ;; recurse properly. Also remove units smaller or equal
  269. ;; to an hour since H:MM part takes care of it.
  270. (cl-remove-if-not
  271. (lambda (pair)
  272. (pcase pair
  273. (`(,(and unit (pred stringp)) . ,_)
  274. (> (org-duration--modifier unit canonical) 60))
  275. (_ nil)))
  276. duration-format))
  277. (min-modifier ;smallest modifier above hour
  278. (and truncated-format
  279. (apply #'min
  280. (mapcar (lambda (p)
  281. (org-duration--modifier (car p) canonical))
  282. truncated-format)))))
  283. (if (or (null min-modifier) (< minutes min-modifier))
  284. ;; There is not unit above the hour or the smallest unit
  285. ;; above the hour is too large for the number of minutes we
  286. ;; need to represent. Use H:MM or H:MM:SS syntax.
  287. (org-duration-from-minutes minutes mode canonical)
  288. ;; Represent minutes above hour using provided units and H:MM
  289. ;; or H:MM:SS below.
  290. (let* ((units-part (* min-modifier (floor (/ minutes min-modifier))))
  291. (minutes-part (- minutes units-part)))
  292. (concat
  293. (org-duration-from-minutes units-part truncated-format canonical)
  294. " "
  295. (org-duration-from-minutes minutes-part mode))))))
  296. ;; Units format.
  297. (duration-format
  298. (let* ((fractional
  299. (let ((digits (cdr (assq 'special duration-format))))
  300. (and digits
  301. (or (wholenump digits)
  302. (error "Unknown formatting directive: %S" digits))
  303. (format "%%.%df" digits))))
  304. (selected-units
  305. (sort (cl-remove-if
  306. ;; Ignore special format cells.
  307. (lambda (pair) (pcase pair (`(special . ,_) t) (_ nil)))
  308. duration-format)
  309. (lambda (a b)
  310. (> (org-duration--modifier (car a) canonical)
  311. (org-duration--modifier (car b) canonical))))))
  312. (cond
  313. ;; Fractional duration: use first unit that is either required
  314. ;; or smaller than MINUTES.
  315. (fractional
  316. (let* ((unit (car
  317. (or (cl-find-if
  318. (lambda (pair)
  319. (pcase pair
  320. (`(,u . ,req?)
  321. (or req?
  322. (<= (org-duration--modifier u canonical)
  323. minutes)))))
  324. selected-units)
  325. ;; Fall back to smallest unit.
  326. (org-last selected-units))))
  327. (modifier (org-duration--modifier unit canonical)))
  328. (concat (format fractional (/ (float minutes) modifier)) unit)))
  329. ;; Otherwise build duration string according to available
  330. ;; units.
  331. ((org-string-nw-p
  332. (org-trim
  333. (mapconcat
  334. (lambda (units)
  335. (pcase-let* ((`(,unit . ,required?) units)
  336. (modifier (org-duration--modifier unit canonical)))
  337. (cond ((<= modifier minutes)
  338. (let ((value (floor (/ minutes modifier))))
  339. (cl-decf minutes (* value modifier))
  340. (format " %d%s" value unit)))
  341. (required? (concat " 0" unit))
  342. (t ""))))
  343. selected-units
  344. ""))))
  345. ;; No unit can properly represent MINUTES. Use the smallest
  346. ;; one anyway.
  347. (t
  348. (pcase-let ((`((,unit . ,_)) (last selected-units)))
  349. (concat
  350. (if (not fractional) "0"
  351. (let ((modifier (org-duration--modifier unit canonical)))
  352. (format fractional (/ (float minutes) modifier))))
  353. 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