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