1 ;;; org-colview.el --- Column View in Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the column view for Org.
34 (declare-function org-agenda-redo
"org-agenda" (&optional all
))
35 (declare-function org-agenda-do-context-action
"org-agenda" ())
36 (declare-function org-clock-sum-today
"org-clock" (&optional headline-filter
))
37 (declare-function org-element-extract-element
"org-element" (element))
38 (declare-function org-element-interpret-data
"org-element" (data))
39 (declare-function org-element-map
"org-element" (data types fun
&optional info first-match no-recursion with-affiliated
))
40 (declare-function org-element-parse-secondary-string
"org-element" (string restriction
&optional parent
))
41 (declare-function org-element-property
"org-element" (property element
))
42 (declare-function org-element-restriction
"org-element" (element))
43 (declare-function org-element-type
"org-element" (element))
44 (declare-function org-dynamic-block-define
"org" (type func
))
45 (declare-function org-link-display-format
"ol" (s))
46 (declare-function org-link-open-from-string
"ol" (s &optional arg
))
48 (defvar org-agenda-columns-add-appointments-to-effort-sum
)
49 (defvar org-agenda-columns-compute-summary-properties
)
50 (defvar org-agenda-columns-show-summaries
)
51 (defvar org-agenda-view-columns-initially
)
52 (defvar org-inlinetask-min-level
)
57 (defcustom org-columns-modify-value-for-display-function nil
58 "Function that modifies values for display in column view.
59 For example, it can be used to cut out a certain part from a time stamp.
60 The function must take 2 arguments:
62 column-title The title of the column (*not* the property name)
63 value The value that should be modified.
65 The function should return the value that should be displayed,
66 or nil if the normal value should be used."
67 :group
'org-properties
68 :type
'(choice (const nil
) (function)))
70 (defcustom org-columns-summary-types nil
71 "Alist between operators and summarize functions.
73 Each association follows the pattern (LABEL . SUMMARIZE),
74 or (LABEL SUMMARIZE COLLECT) where
76 LABEL is a string used in #+COLUMNS definition describing the
77 summary type. It can contain any character but \"}\". It is
80 SUMMARIZE is a function called with two arguments. The first
81 argument is a non-empty list of values, as non-empty strings.
82 The second one is a format string or nil. It has to return
83 a string summarizing the list of values.
85 COLLECT is a function called with one argument, a property
86 name. It is called in the context of a headline and must
87 return the collected property, or the empty string. You can
88 use this to only collect a property if a related conditional
89 properties is set, e.g., to return VACATION_DAYS only if
92 Note that the return value can become one value for an higher
93 order summary, so the function is expected to handle its own
96 Types defined in this variable take precedence over those defined
97 in `org-columns-summary-types-default', which see."
98 :group
'org-properties
100 :package-version
'(Org .
"9.0")
101 :type
'(alist :key-type
(string :tag
" Label")
103 (choice (function :tag
"Summarize")
104 (list :tag
"Collect and summarize"
105 (function :tag
"Summarize")
106 (function :tag
"Collect")))))
112 (defvar-local org-columns-overlays nil
113 "Holds the list of current column overlays.")
115 (defvar-local org-columns-current-fmt nil
116 "Local variable, holds the currently active column format.")
118 (defvar-local org-columns-current-fmt-compiled nil
119 "Local variable, holds the currently active column format.
120 This is the compiled version of the format.")
122 (defvar-local org-columns-current-maxwidths nil
123 "Currently active maximum column widths, as a vector.")
125 (defvar-local org-columns-begin-marker nil
126 "Points to the position where last a column creation command was called.")
128 (defvar-local org-columns-top-level-marker nil
129 "Points to the position where current columns region starts.")
131 (defvar org-columns--time
0.0
132 "Number of seconds since the epoch, as a floating point number.")
134 (defvar org-columns-map
(make-sparse-keymap)
135 "The keymap valid in column display.")
137 (defconst org-columns-summary-types-default
138 '(("+" . org-columns--summary-sum
)
139 ("$" . org-columns--summary-currencies
)
140 ("X" . org-columns--summary-checkbox
)
141 ("X/" . org-columns--summary-checkbox-count
)
142 ("X%" . org-columns--summary-checkbox-percent
)
143 ("max" . org-columns--summary-max
)
144 ("mean" . org-columns--summary-mean
)
145 ("min" . org-columns--summary-min
)
146 (":" . org-columns--summary-sum-times
)
147 (":max" . org-columns--summary-max-time
)
148 (":mean" . org-columns--summary-mean-time
)
149 (":min" . org-columns--summary-min-time
)
150 ("@max" . org-columns--summary-max-age
)
151 ("@mean" . org-columns--summary-mean-age
)
152 ("@min" . org-columns--summary-min-age
)
153 ("est+" . org-columns--summary-estimate
))
154 "Map operators to summarize functions.
155 See `org-columns-summary-types' for details.")
157 (defun org-columns-content ()
158 "Switch to contents view while in columns view."
163 (org-defkey org-columns-map
"c" 'org-columns-content
)
164 (org-defkey org-columns-map
"o" 'org-overview
)
165 (org-defkey org-columns-map
"e" 'org-columns-edit-value
)
166 (org-defkey org-columns-map
"\C-c\C-t" 'org-columns-todo
)
167 (org-defkey org-columns-map
"\C-c\C-c" 'org-columns-set-tags-or-toggle
)
168 (org-defkey org-columns-map
"\C-c\C-o" 'org-columns-open-link
)
169 (org-defkey org-columns-map
"v" 'org-columns-show-value
)
170 (org-defkey org-columns-map
"q" 'org-columns-quit
)
171 (org-defkey org-columns-map
"r" 'org-columns-redo
)
172 (org-defkey org-columns-map
"g" 'org-columns-redo
)
173 (org-defkey org-columns-map
[left] 'backward-char)
174 (org-defkey org-columns-map "\M-b" 'backward-char)
175 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
176 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
177 (org-defkey org-columns-map "\M-f"
178 (lambda () (interactive) (goto-char (1+ (point)))))
179 (org-defkey org-columns-map [right]
180 (lambda () (interactive) (goto-char (1+ (point)))))
181 (org-defkey org-columns-map [down]
182 (lambda () (interactive)
183 (let ((col (current-column)))
184 (beginning-of-line 2)
185 (while (and (org-invisible-p2) (not (eobp)))
186 (beginning-of-line 2))
188 (if (eq major-mode 'org-agenda-mode)
189 (org-agenda-do-context-action)))))
190 (org-defkey org-columns-map [up]
191 (lambda () (interactive)
192 (let ((col (current-column)))
193 (beginning-of-line 0)
194 (while (and (org-invisible-p2) (not (bobp)))
195 (beginning-of-line 0))
197 (if (eq major-mode 'org-agenda-mode)
198 (org-agenda-do-context-action)))))
199 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
200 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
201 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
202 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
203 (org-defkey org-columns-map "<" 'org-columns-narrow)
204 (org-defkey org-columns-map ">" 'org-columns-widen)
205 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
206 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
207 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
208 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
210 (org-defkey org-columns-map (number-to-string i)
211 `(lambda () (interactive)
212 (org-columns-next-allowed-value nil ,i))))
214 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
216 ["Edit property" org-columns-edit-value t]
217 ["Next allowed value" org-columns-next-allowed-value t]
218 ["Previous allowed value" org-columns-previous-allowed-value t]
219 ["Show full value" org-columns-show-value t]
220 ["Edit allowed values" org-columns-edit-allowed t]
222 ["Edit column attributes" org-columns-edit-attributes t]
223 ["Increase column width" org-columns-widen t]
224 ["Decrease column width" org-columns-narrow t]
226 ["Move column right" org-columns-move-right t]
227 ["Move column left" org-columns-move-left t]
228 ["Add column" org-columns-new t]
229 ["Delete column" org-columns-delete t]
231 ["CONTENTS" org-columns-content t]
232 ["OVERVIEW" org-overview t]
233 ["Refresh columns display" org-columns-redo t]
235 ["Open link" org-columns-open-link t]
237 ["Quit" org-columns-quit t]))
239 (defun org-columns--displayed-value (spec value &optional no-star)
240 "Return displayed value for specification SPEC in current entry.
242 SPEC is a column format specification as stored in
243 `org-columns-current-fmt-compiled'. VALUE is the real value to
244 display, as a string.
246 When NO-STAR is non-nil, do not add asterisks before displayed
247 value for ITEM property."
248 (or (and (functionp org-columns-modify-value-for-display-function)
249 (funcall org-columns-modify-value-for-display-function
250 (nth 1 spec) ;column name
256 (concat (make-string (1- (org-current-level))
257 (if org-hide-leading-stars ?\s ?*))
259 (concat stars (org-link-display-format value))))
260 (`(,_ ,_ ,_ ,_ nil) value)
261 ;; If PRINTF is set, assume we are displaying a number and
262 ;; obey to the format string.
263 (`(,_ ,_ ,_ ,_ ,printf) (format printf (string-to-number value)))
264 (_ (error "Invalid column specification format: %S" spec)))))
266 (defun org-columns--collect-values (&optional compiled-fmt)
267 "Collect values for columns on the current line.
269 Return a list of triplets (SPEC VALUE DISPLAYED) suitable for
270 `org-columns--display-here'.
272 This function assumes `org-columns-current-fmt-compiled' is
273 initialized is set in the current buffer. However, it is
274 possible to override it with optional argument COMPILED-FMT."
275 (let ((summaries (get-text-property (point) 'org-summaries)))
280 (let* ((v (or (cdr (assoc spec summaries))
281 (org-entry-get (point) p 'selective t)
282 (and compiled-fmt ;assume `org-agenda-columns'
283 ;; Effort property is not defined. Try
284 ;; to use appointment duration.
285 org-agenda-columns-add-appointments-to-effort-sum
286 (string= p (upcase org-effort-property))
287 (get-text-property (point) 'duration)
288 (propertize (org-duration-from-minutes
289 (get-text-property (point) 'duration))
292 ;; A non-nil COMPILED-FMT means we're calling from Org
293 ;; Agenda mode, where we do not want leading stars for
294 ;; ITEM. Hence the optional argument for
295 ;; `org-columns--displayed-value'.
296 (list spec v (org-columns--displayed-value spec v compiled-fmt))))))
297 (or compiled-fmt org-columns-current-fmt-compiled))))
299 (defun org-columns--set-widths (cache)
300 "Compute the maximum column widths from the format and CACHE.
301 This function sets `org-columns-current-maxwidths' as a vector of
302 integers greater than 0."
303 (setq org-columns-current-maxwidths
308 (`(,_ ,_ ,(and width (pred wholenump)) . ,_) width)
310 ;; No width is specified in the columns format.
311 ;; Compute it by checking all possible values for
313 (let ((width (length name)))
314 (dolist (entry cache width)
315 (let ((value (nth 2 (assoc spec (cdr entry)))))
316 (setq width (max (length value) width))))))))
317 org-columns-current-fmt-compiled))))
319 (defun org-columns--new-overlay (beg end &optional string face)
320 "Create a new column overlay and add it to the list."
321 (let ((ov (make-overlay beg end)))
322 (overlay-put ov 'face (or face 'secondary-selection))
323 (org-overlay-display ov string face)
324 (push ov org-columns-overlays)
327 (defun org-columns--summarize (operator)
328 "Return summary function associated to string OPERATOR."
329 (pcase (or (assoc operator org-columns-summary-types)
330 (assoc operator org-columns-summary-types-default))
331 (`nil (error "Unknown %S operator" operator))
332 (`(,_ . ,(and (pred functionp) summarize)) summarize)
333 (`(,_ ,summarize ,_) summarize)
334 (_ (error "Invalid definition for operator %S" operator))))
336 (defun org-columns--collect (operator)
337 "Return collect function associated to string OPERATOR.
338 Return nil if no collect function is associated to OPERATOR."
339 (pcase (or (assoc operator org-columns-summary-types)
340 (assoc operator org-columns-summary-types-default))
341 (`nil (error "Unknown %S operator" operator))
342 (`(,_ . ,(pred functionp)) nil) ;default value
343 (`(,_ ,_ ,collect) collect)
344 (_ (error "Invalid definition for operator %S" operator))))
346 (defun org-columns--overlay-text (value fmt width property original)
347 "Return decorated VALUE string for columns overlay display.
348 FMT is a format string. WIDTH is the width of the column, as an
349 integer. PROPERTY is the property being displayed, as a string.
350 ORIGINAL is the real string, i.e., before it is modified by
351 `org-columns--displayed-value'."
353 (let ((v (org-columns-add-ellipses value width)))
356 (propertize v 'face (org-get-priority-face original)))
358 (if (not org-tags-special-faces-re)
359 (propertize v 'face 'org-tag)
360 (replace-regexp-in-string
361 org-tags-special-faces-re
362 (lambda (m) (propertize m 'face (org-get-tag-face m)))
364 ("TODO" (propertize v 'face (org-get-todo-face original)))
367 (defun org-columns--display-here (columns &optional dateline)
368 "Overlay the current line with column display.
369 COLUMNS is an alist (SPEC VALUE DISPLAYED). Optional argument
370 DATELINE is non-nil when the face used should be
371 `org-agenda-column-dateline'."
374 (let* ((level-face (and (looking-at "\\(\\**\\)\\(\\* \\)")
375 (org-get-level-face 2)))
376 (ref-face (or level-face
377 (and (eq major-mode 'org-agenda-mode)
378 (org-get-at-bol 'face))
380 (color (list :foreground (face-attribute ref-face :foreground)))
381 (font (list :height (face-attribute 'default :height)
382 :family (face-attribute 'default :family)))
383 (face (list color font 'org-column ref-face))
384 (face1 (list color font 'org-agenda-column-dateline ref-face)))
385 ;; Each column is an overlay on top of a character. So there has
386 ;; to be at least as many characters available on the line as
387 ;; columns to display.
388 (let ((columns (length org-columns-current-fmt-compiled))
389 (chars (- (line-end-position) (line-beginning-position))))
390 (when (> columns chars)
393 (let ((inhibit-read-only t))
394 (insert (make-string (- columns chars) ?\s))))))
395 ;; Display columns. Create and install the overlay for the
396 ;; current column on the next character.
398 (last (1- (length columns))))
399 (dolist (column columns)
401 (`(,spec ,original ,value)
402 (let* ((property (car spec))
403 (width (aref org-columns-current-maxwidths i))
404 (fmt (format (if (= i last) "%%-%d.%ds |"
407 (ov (org-columns--new-overlay
409 (org-columns--overlay-text
410 value fmt width property original)
411 (if dateline face1 face))))
412 (overlay-put ov 'keymap org-columns-map)
413 (overlay-put ov 'org-columns-key property)
414 (overlay-put ov 'org-columns-value original)
415 (overlay-put ov 'org-columns-value-modified value)
416 (overlay-put ov 'org-columns-format fmt)
417 (overlay-put ov 'line-prefix "")
418 (overlay-put ov 'wrap-prefix "")
421 ;; Make the rest of the line disappear.
422 (let ((ov (org-columns--new-overlay (point) (line-end-position))))
423 (overlay-put ov 'invisible t)
424 (overlay-put ov 'keymap org-columns-map)
425 (overlay-put ov 'line-prefix "")
426 (overlay-put ov 'wrap-prefix ""))
427 (let ((ov (make-overlay (1- (line-end-position))
428 (line-beginning-position 2))))
429 (overlay-put ov 'keymap org-columns-map)
430 (push ov org-columns-overlays))
431 (with-silent-modifications
432 (let ((inhibit-read-only t))
434 (line-end-position 0)
435 (line-beginning-position 2)
437 (substitute-command-keys
438 "Type \\<org-columns-map>`\\[org-columns-edit-value]' \
439 to edit property")))))))
441 (defun org-columns-add-ellipses (string width)
442 "Truncate STRING with WIDTH characters, with ellipses."
444 ((<= (length string) width) string)
445 ((<= width (length org-columns-ellipses))
446 (substring org-columns-ellipses 0 width))
447 (t (concat (substring string 0 (- width (length org-columns-ellipses)))
448 org-columns-ellipses))))
450 (defvar org-columns-full-header-line-format nil
451 "The full header line format, will be shifted by horizontal scrolling." )
452 (defvar org-previous-header-line-format nil
453 "The header line format before column view was turned on.")
454 (defvar org-columns-inhibit-recalculation nil
455 "Inhibit recomputing of columns on column view startup.")
456 (defvar org-columns-flyspell-was-active nil
457 "Remember the state of `flyspell-mode' before column view.
458 Flyspell-mode can cause problems in columns view, so it is turned off
459 for the duration of the command.")
461 (defvar header-line-format)
462 (defvar org-columns-previous-hscroll 0)
464 (defun org-columns--display-here-title ()
465 "Overlay the newline before the current line with the table title."
468 (linum-offset (org-line-number-display-width 'columns))
470 (dolist (column org-columns-current-fmt-compiled)
472 (`(,property ,name . ,_)
473 (let* ((width (aref org-columns-current-maxwidths i))
474 (fmt (format "%%-%d.%ds | " width width)))
475 (setq title (concat title (format fmt (or name property)))))))
477 (setq-local org-previous-header-line-format header-line-format)
478 (setq org-columns-full-header-line-format
480 (org-add-props " " nil 'display `(space :align-to ,linum-offset))
481 (org-add-props (substring title 0 -1) nil 'face 'org-column-title)))
482 (setq org-columns-previous-hscroll -1)
483 (add-hook 'post-command-hook 'org-columns-hscroll-title nil 'local)))
485 (defun org-columns-hscroll-title ()
486 "Set the `header-line-format' so that it scrolls along with the table."
487 (sit-for .0001) ; need to force a redisplay to update window-hscroll
488 (let ((hscroll (window-hscroll)))
489 (when (/= org-columns-previous-hscroll hscroll)
490 (setq header-line-format
491 (concat (substring org-columns-full-header-line-format 0 1)
492 (substring org-columns-full-header-line-format
493 (min (length org-columns-full-header-line-format)
495 org-columns-previous-hscroll hscroll)
496 (force-mode-line-update))))
498 (defvar org-colview-initial-truncate-line-value nil
499 "Remember the value of `truncate-lines' across colview.")
502 (defun org-columns-remove-overlays ()
503 "Remove all currently active column overlays."
505 (when org-columns-overlays
506 (when (local-variable-p 'org-previous-header-line-format)
507 (setq header-line-format org-previous-header-line-format)
508 (kill-local-variable 'org-previous-header-line-format)
509 (remove-hook 'post-command-hook 'org-columns-hscroll-title 'local))
510 (set-marker org-columns-begin-marker nil)
511 (when (markerp org-columns-top-level-marker)
512 (set-marker org-columns-top-level-marker nil))
513 (with-silent-modifications
514 (mapc #'delete-overlay org-columns-overlays)
515 (setq org-columns-overlays nil)
516 (let ((inhibit-read-only t))
517 (remove-text-properties (point-min) (point-max) '(read-only t))))
518 (when org-columns-flyspell-was-active
520 (when (local-variable-p 'org-colview-initial-truncate-line-value)
521 (setq truncate-lines org-colview-initial-truncate-line-value))))
523 (defun org-columns-show-value ()
524 "Show the full value of the property."
526 (let ((value (get-char-property (point) 'org-columns-value)))
527 (message "Value is: %s" (or value ""))))
529 (defvar org-agenda-columns-active) ;; defined in org-agenda.el
531 (defun org-columns-quit ()
532 "Remove the column overlays and in this way exit column editing."
534 (with-silent-modifications
535 (org-columns-remove-overlays)
536 (let ((inhibit-read-only t))
537 (remove-text-properties (point-min) (point-max) '(read-only t))))
538 (if (not (eq major-mode 'org-agenda-mode))
539 (setq org-columns-current-fmt nil)
540 (setq org-agenda-columns-active nil)
542 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
544 (defun org-columns-check-computed ()
545 "Throw an error if current column value is computed."
546 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
549 (assoc spec (get-text-property (line-beginning-position) 'org-summaries))
550 (error "This value is computed from the entry's children"))))
552 (defun org-columns-todo (&optional _arg)
553 "Change the TODO state during column view."
555 (org-columns-edit-value "TODO"))
557 (defun org-columns-set-tags-or-toggle (&optional _arg)
558 "Toggle checkbox at point, or set tags for current headline."
560 (if (string-match "\\`\\[[ xX-]\\]\\'"
561 (get-char-property (point) 'org-columns-value))
562 (org-columns-next-allowed-value)
563 (org-columns-edit-value "TAGS")))
565 (defvar org-overriding-columns-format nil
566 "When set, overrides any other format definition for the agenda.
567 Don't set this, this is meant for dynamic scoping. Set
568 `org-local-columns-format' instead.")
570 (defvar-local org-local-columns-format nil
571 "When set, overrides any other format definition for the agenda.
572 This can be set as a buffer local value to avoid interfering with
573 dynamic scoping for `org-overriding-columns-format'.")
575 (defun org-columns-edit-value (&optional key)
576 "Edit the value of the property at point in column view.
577 Where possible, use the standard interface for changing this line."
579 (org-columns-check-computed)
580 (let* ((col (current-column))
581 (bol (line-beginning-position))
582 (eol (line-end-position))
583 (pom (or (get-text-property bol 'org-hd-marker) (point)))
584 (key (or key (get-char-property (point) 'org-columns-key)))
585 (org-columns--time (float-time))
589 (user-error "This special column cannot be edited"))
591 (lambda () (org-with-point-at pom (org-edit-headline))))
594 (org-with-point-at pom (call-interactively #'org-todo))))
597 (org-with-point-at pom
598 (call-interactively #'org-priority))))
601 (org-with-point-at pom
602 (let ((org-fast-tag-selection-single-key
603 (if (eq org-fast-tag-selection-single-key 'expert)
605 org-fast-tag-selection-single-key)))
606 (call-interactively #'org-set-tags-command)))))
609 (org-with-point-at pom (call-interactively #'org-deadline))))
612 (org-with-point-at pom (call-interactively #'org-schedule))))
615 (org-with-point-at pom
616 (call-interactively #'org-beamer-select-environment))))
618 (let* ((allowed (org-property-get-allowed-values pom key 'table))
619 (value (get-char-property (point) 'org-columns-value))
621 (if (null allowed) (read-string "Edit: " value)
623 "Value: " allowed nil
624 (not (get-text-property
625 0 'org-unrestricted (caar allowed))))))))
626 (and (not (equal nval value))
627 (lambda () (org-entry-put pom key nval))))))))
630 ((eq major-mode 'org-agenda-mode)
631 (org-columns--call action)
632 ;; The following let preserves the current format, and makes
633 ;; sure that in only a single file things need to be updated.
634 (let* ((org-overriding-columns-format org-columns-current-fmt)
635 (buffer (marker-buffer pom))
636 (org-agenda-contributing-files
637 (list (with-current-buffer buffer
638 (buffer-file-name (buffer-base-buffer))))))
639 (org-agenda-columns)))
641 (let ((inhibit-read-only t))
642 (with-silent-modifications
643 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t)))
644 (org-columns--call action))
645 ;; Some properties can modify headline (e.g., "TODO"), and
646 ;; possible shuffle overlays. Make sure they are still all at
647 ;; the right place on the current line.
648 (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
649 (org-columns-update key)
650 (org-move-to-column col)))))
652 (defun org-columns-edit-allowed ()
653 "Edit the list of allowed values for the current property."
655 (let* ((pom (or (org-get-at-bol 'org-marker)
656 (org-get-at-bol 'org-hd-marker)
658 (key (concat (or (get-char-property (point) 'org-columns-key)
659 (user-error "No column to edit at point"))
661 (allowed (org-entry-get pom key t))
662 (new-value (read-string "Allowed: " allowed)))
663 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
664 ;; FIXME: Write back to #+PROPERTY setting if that is needed.
666 (cond ((marker-position org-entry-property-inherited-from)
667 org-entry-property-inherited-from)
668 ((marker-position org-columns-top-level-marker)
669 org-columns-top-level-marker)
673 (defun org-columns--call (fun)
674 "Call function FUN while preserving heading visibility.
675 FUN is a function called with no argument."
676 (let ((hide-body (and (/= (line-end-position) (point-max))
678 (move-beginning-of-line 2)
679 (org-at-heading-p t)))))
680 (unwind-protect (funcall fun)
681 (when hide-body (outline-hide-entry)))))
683 (defun org-columns-previous-allowed-value ()
684 "Switch to the previous allowed value for this column."
686 (org-columns-next-allowed-value t))
688 (defun org-columns-next-allowed-value (&optional previous nth)
689 "Switch to the next allowed value for this column.
690 When PREVIOUS is set, go to the previous value. When NTH is
691 an integer, select that value."
693 (org-columns-check-computed)
694 (let* ((column (current-column))
695 (key (get-char-property (point) 'org-columns-key))
696 (value (get-char-property (point) 'org-columns-value))
697 (pom (or (get-text-property (line-beginning-position) 'org-hd-marker)
701 (or (org-property-get-allowed-values pom key)
702 (pcase (nth column org-columns-current-fmt-compiled)
703 (`(,_ ,_ ,_ ,(or "X" "X/" "X%") ,_) '("[ ]" "[X]")))
704 (org-colview-construct-allowed-dates value))))
705 (if previous (reverse all) all))))
706 (when (equal key "ITEM") (error "Cannot edit item headline from here"))
707 (unless (or allowed (member key '("SCHEDULED" "DEADLINE" "CLOCKSUM")))
708 (error "Allowed values for this property have not been defined"))
709 (let* ((l (length allowed))
712 ((member key '("SCHEDULED" "DEADLINE" "CLOCKSUM"))
713 (if previous 'earlier 'later))
715 (when (> (abs nth) l)
716 (user-error "Only %d allowed values for property `%s'" l key))
717 (nth (mod (1- nth) l) allowed))
718 ((member value allowed)
719 (when (= l 1) (error "Only one allowed value for this property"))
720 (or (nth 1 (member value allowed)) (car allowed)))
722 (action (lambda () (org-entry-put pom key new))))
724 ((eq major-mode 'org-agenda-mode)
725 (org-columns--call action)
726 ;; The following let preserves the current format, and makes
727 ;; sure that in only a single file things need to be updated.
728 (let* ((org-overriding-columns-format org-columns-current-fmt)
729 (buffer (marker-buffer pom))
730 (org-agenda-contributing-files
731 (list (with-current-buffer buffer
732 (buffer-file-name (buffer-base-buffer))))))
733 (org-agenda-columns)))
735 (let ((inhibit-read-only t))
736 (remove-text-properties (line-end-position 0) (line-end-position)
738 (org-columns--call action))
739 ;; Some properties can modify headline (e.g., "TODO"), and
740 ;; possible shuffle overlays. Make sure they are still all at
741 ;; the right place on the current line.
742 (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
743 (org-columns-update key)
744 (org-move-to-column column))))))
746 (defun org-colview-construct-allowed-dates (s)
747 "Construct a list of three dates around the date in S.
748 This respects the format of the time stamp in S, active or non-active,
749 and also including time or not. S must be just a time stamp, no text
751 (when (and s (string-match (concat "^" org-ts-regexp3 "$") s))
752 (let* ((time (org-parse-time-string s 'nodefaults))
753 (active (equal (string-to-char s) ?<))
754 (fmt (funcall (if (nth 1 time) 'cdr 'car) org-time-stamp-formats))
755 time-before time-after)
756 (unless active (setq fmt (concat "[" (substring fmt 1 -1) "]")))
757 (setf (car time) (or (car time) 0))
758 (setf (nth 1 time) (or (nth 1 time) 0))
759 (setf (nth 2 time) (or (nth 2 time) 0))
760 (setq time-before (copy-sequence time))
761 (setq time-after (copy-sequence time))
762 (setf (nth 3 time-before) (1- (nth 3 time)))
763 (setf (nth 3 time-after) (1+ (nth 3 time)))
764 (mapcar (lambda (x) (format-time-string fmt (apply 'encode-time x)))
765 (list time-before time time-after)))))
767 (defun org-columns-open-link (&optional arg)
769 (let ((value (get-char-property (point) 'org-columns-value)))
770 (org-link-open-from-string value arg)))
773 (defun org-columns-get-format-and-top-level ()
774 (let ((fmt (org-columns-get-format)))
775 (org-columns-goto-top-level)
778 (defun org-columns-get-format (&optional fmt-string)
779 "Return columns format specifications.
780 When optional argument FMT-STRING is non-nil, use it as the
781 current specifications. This function also sets
782 `org-columns-current-fmt-compiled' and
783 `org-columns-current-fmt'."
787 (org-entry-get nil "COLUMNS" t)
788 (org-with-wide-buffer
789 (goto-char (point-min))
791 (let ((case-fold-search t))
792 (while (re-search-forward "^[ \t]*#\\+COLUMNS: .+$" nil t)
793 (let ((element (org-element-at-point)))
794 (when (eq (org-element-type element) 'keyword)
795 (throw :found (org-element-property :value element)))))
797 org-columns-default-format)))
798 (setq org-columns-current-fmt format)
799 (org-columns-compile-format format)
802 (defun org-columns-goto-top-level ()
803 "Move to the beginning of the column view area.
804 Also sets `org-columns-top-level-marker' to the new position."
805 (unless (markerp org-columns-top-level-marker)
806 (setq org-columns-top-level-marker (make-marker)))
809 org-columns-top-level-marker
810 (cond ((org-before-first-heading-p) (point-min))
811 ((org-entry-get nil "COLUMNS" t) org-entry-property-inherited-from)
812 (t (org-back-to-heading) (point))))))
815 (defun org-columns (&optional global columns-fmt-string)
816 "Turn on column view on an Org mode file.
818 Column view applies to the whole buffer if point is before the
819 first headline. Otherwise, it applies to the first ancestor
820 setting \"COLUMNS\" property. If there is none, it defaults to
821 the current headline. With a `\\[universal-argument]' prefix \
822 argument, turn on column
823 view for the whole buffer unconditionally.
825 When COLUMNS-FMT-STRING is non-nil, use it as the column format."
827 (org-columns-remove-overlays)
829 (when global (goto-char (point-min)))
830 (if (markerp org-columns-begin-marker)
831 (move-marker org-columns-begin-marker (point))
832 (setq org-columns-begin-marker (point-marker)))
833 (org-columns-goto-top-level)
834 ;; Initialize `org-columns-current-fmt' and
835 ;; `org-columns-current-fmt-compiled'.
836 (let ((org-columns--time (float-time)))
837 (org-columns-get-format columns-fmt-string)
838 (unless org-columns-inhibit-recalculation (org-columns-compute-all))
840 (when (and (not global) (org-at-heading-p))
841 (narrow-to-region (point) (org-end-of-subtree t t)))
842 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
844 (when (assoc "CLOCKSUM_T" org-columns-current-fmt-compiled)
845 (org-clock-sum-today))
847 ;; Collect contents of columns ahead of time so as to
848 ;; compute their maximum width.
850 (lambda () (cons (point) (org-columns--collect-values)))
851 nil nil (and org-columns-skip-archived-trees 'archive))))
853 (org-columns--set-widths cache)
854 (org-columns--display-here-title)
855 (when (setq-local org-columns-flyspell-was-active
856 (bound-and-true-p flyspell-mode))
858 (unless (local-variable-p 'org-colview-initial-truncate-line-value)
859 (setq-local org-colview-initial-truncate-line-value
861 (setq truncate-lines t)
862 (dolist (entry cache)
863 (goto-char (car entry))
864 (org-columns--display-here (cdr entry)))))))))
866 (defun org-columns-new (&optional spec &rest attributes)
867 "Insert a new column, to the left of the current column.
868 Interactively fill attributes for new column. When column format
869 specification SPEC is provided, edit it instead.
871 When optional argument attributes can be a list of columns
872 specifications attributes to create the new column
873 non-interactively. See `org-columns-compile-format' for
876 (let ((new (or attributes
880 (mapcar #'list (org-buffer-property-keys t nil t))
881 nil nil (nth 0 spec))))
883 (read-string (format "Column title [%s]: " prop)
885 ;; Use `read-string' instead of `read-number'
886 ;; to allow empty width.
887 (let ((w (read-string
890 (number-to-string (nth 2 spec))))))
891 (and (org-string-nw-p w) (string-to-number w)))
896 (cons '("") ;Allow empty operator.
897 (mapcar (lambda (x) (list (car x)))
899 org-columns-summary-types
900 org-columns-summary-types-default))))
903 (read-string "Format: " (nth 4 spec))))))))
905 (progn (setcar spec (car new))
906 (setcdr spec (cdr new)))
907 (push new (nthcdr (current-column) org-columns-current-fmt-compiled)))
908 (org-columns-store-format)
911 (defun org-columns-delete ()
912 "Delete the column at point from columns view."
914 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
915 (when (y-or-n-p (format "Are you sure you want to remove column %S? "
917 (setq org-columns-current-fmt-compiled
918 (delq spec org-columns-current-fmt-compiled))
919 (org-columns-store-format)
920 ;; This may leave a now wrong value in a node property. However
921 ;; updating it may prove counter-intuitive. See comments in
922 ;; `org-columns-move-right' for details.
923 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
924 (when (>= (current-column) (length org-columns-current-fmt-compiled))
927 (defun org-columns-edit-attributes ()
928 "Edit the attributes of the current column."
930 (org-columns-new (nth (current-column) org-columns-current-fmt-compiled)))
932 (defun org-columns-widen (arg)
933 "Make the column wider by ARG characters."
935 (let* ((n (current-column))
936 (entry (nth n org-columns-current-fmt-compiled))
937 (width (aref org-columns-current-maxwidths n)))
938 (setq width (max 1 (+ width arg)))
939 (setcar (nthcdr 2 entry) width)
940 (org-columns-store-format)
941 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))))
943 (defun org-columns-narrow (arg)
944 "Make the column narrower by ARG characters."
946 (org-columns-widen (- arg)))
948 (defun org-columns-move-right ()
949 "Swap this column with the one to the right."
951 (let* ((n (current-column))
952 (cell (nthcdr n org-columns-current-fmt-compiled))
954 (when (>= n (1- (length org-columns-current-fmt-compiled)))
955 (error "Cannot shift this column further to the right"))
957 (setcar cell (car (cdr cell)))
958 (setcdr cell (cons e (cdr (cdr cell))))
959 (org-columns-store-format)
960 ;; Do not compute again properties, since we're just moving
961 ;; columns around. It can put a property value a bit off when
962 ;; switching between an non-computed and a computed value for the
963 ;; same property, e.g. from "%A %A{+}" to "%A{+} %A".
965 ;; In this case, the value needs to be updated since the first
966 ;; column related to a property determines how its value is
967 ;; computed. However, (correctly) updating the value could be
968 ;; surprising, so we leave it as-is nonetheless.
969 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
972 (defun org-columns-move-left ()
973 "Swap this column with the one to the left."
975 (let* ((n (current-column)))
977 (error "Cannot shift this column further to the left"))
979 (org-columns-move-right)
982 (defun org-columns-store-format ()
983 "Store the text version of the current columns format.
984 The format is stored either in the COLUMNS property of the node
985 starting the current column display, or in a #+COLUMNS line of
987 (let ((fmt (org-columns-uncompile-format org-columns-current-fmt-compiled)))
988 (setq-local org-columns-current-fmt fmt)
989 (when org-columns-overlays
990 (org-with-point-at org-columns-top-level-marker
991 (if (and (org-at-heading-p) (org-entry-get nil "COLUMNS"))
992 (org-entry-put nil "COLUMNS" fmt)
993 (goto-char (point-min))
994 (let ((case-fold-search t))
995 ;; Try to replace the first COLUMNS keyword available.
997 (while (re-search-forward "^[ \t]*#\\+COLUMNS:\\(.*\\)" nil t)
998 (let ((element (save-match-data (org-element-at-point))))
999 (when (and (eq (org-element-type element) 'keyword)
1000 (equal (org-element-property :key element)
1002 (replace-match (concat " " fmt) t t nil 1)
1003 (throw :found nil))))
1004 ;; No COLUMNS keyword in the buffer. Insert one at the
1005 ;; beginning, right before the first heading, if any.
1006 (goto-char (point-min))
1007 (unless (org-at-heading-p t) (outline-next-heading))
1008 (let ((inhibit-read-only t))
1009 (insert-before-markers "#+COLUMNS: " fmt "\n"))))
1010 (setq-local org-columns-default-format fmt))))))
1012 (defun org-columns-update (property)
1013 "Recompute PROPERTY, and update the columns display for it."
1014 (org-columns-compute property)
1015 (org-with-wide-buffer
1016 (let ((p (upcase property)))
1017 (dolist (ov org-columns-overlays)
1018 (let ((key (overlay-get ov 'org-columns-key)))
1019 (when (and key (equal key p) (overlay-start ov))
1020 (goto-char (overlay-start ov))
1021 (let* ((spec (nth (current-column) org-columns-current-fmt-compiled))
1023 (or (cdr (assoc spec
1024 (get-text-property (line-beginning-position)
1026 (org-entry-get (point) key))))
1028 (let ((displayed (org-columns--displayed-value spec value))
1029 (format (overlay-get ov 'org-columns-format))
1031 (aref org-columns-current-maxwidths (current-column))))
1032 (overlay-put ov 'org-columns-value value)
1033 (overlay-put ov 'org-columns-value-modified displayed)
1036 (org-columns--overlay-text
1037 displayed format width property value)))))))))))
1039 (defun org-columns-redo ()
1040 "Construct the column display again."
1042 (when org-columns-overlays
1043 (message "Recomputing columns...")
1044 (org-with-point-at org-columns-begin-marker
1045 (org-columns-remove-overlays)
1046 (if (derived-mode-p 'org-mode)
1047 ;; Since we already know the columns format, provide it
1048 ;; instead of computing again.
1049 (call-interactively #'org-columns org-columns-current-fmt)
1051 (call-interactively #'org-agenda-columns)))
1052 (message "Recomputing columns...done")))
1054 (defun org-columns-uncompile-format (compiled)
1055 "Turn the compiled columns format back into a string representation.
1057 COMPILED is an alist, as returned by `org-columns-compile-format'."
1061 (`(,prop ,title ,width ,op ,printf)
1063 (and width (number-to-string width))
1065 (and title (not (equal prop title)) (format "(%s)" title))
1066 (cond ((not op) nil)
1067 (printf (format "{%s;%s}" op printf))
1068 (t (format "{%s}" op)))))))
1071 (defun org-columns-compile-format (fmt)
1072 "Turn a column format string FMT into an alist of specifications.
1074 The alist has one entry for each column in the format. The elements of
1076 property the property name, as an upper-case string
1077 title the title field for the columns, as a string
1078 width the column width in characters, can be nil for automatic width
1079 operator the summary operator, as a string, or nil
1080 printf a printf format for computed values, as a string, or nil
1082 This function updates `org-columns-current-fmt-compiled'."
1083 (setq org-columns-current-fmt-compiled nil)
1085 (while (string-match
1086 "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\
1087 \\(?:{\\([^}]+\\)}\\)?\\s-*"
1089 (setq start (match-end 0))
1090 (let* ((width (and (match-end 1) (string-to-number (match-string 1 fmt))))
1091 (prop (match-string-no-properties 2 fmt))
1092 (title (or (match-string-no-properties 3 fmt) prop))
1093 (operator (match-string-no-properties 4 fmt)))
1094 (push (if (not operator) (list (upcase prop) title width nil nil)
1096 (when (string-match ";" operator)
1097 (setq printf (substring operator (match-end 0)))
1098 (setq operator (substring operator 0 (match-beginning 0))))
1099 (list (upcase prop) title width operator printf)))
1100 org-columns-current-fmt-compiled)))
1101 (setq org-columns-current-fmt-compiled
1102 (nreverse org-columns-current-fmt-compiled))))
1105 ;;;; Column View Summary
1107 (defun org-columns--age-to-minutes (s)
1108 "Turn age string S into a number of minutes.
1109 An age is either computed from a given time-stamp, or indicated
1110 as a canonical duration, i.e., using units defined in
1111 `org-duration-canonical-units'."
1113 ((string-match-p org-ts-regexp s)
1114 (/ (- org-columns--time
1115 (float-time (apply #'encode-time (org-parse-time-string s))))
1117 ((org-duration-p s) (org-duration-to-minutes s t)) ;skip user units
1118 (t (user-error "Invalid age: %S" s))))
1120 (defun org-columns--format-age (minutes)
1121 "Format MINUTES float as an age string."
1122 (org-duration-from-minutes minutes
1123 '(("d" . nil) ("h" . nil) ("min" . nil))
1124 t)) ;ignore user's custom units
1126 (defun org-columns--summary-apply-times (fun times)
1127 "Apply FUN to time values TIMES.
1128 Return the result as a duration."
1129 (org-duration-from-minutes
1130 (apply fun (mapcar #'org-duration-to-minutes times))
1131 (org-duration-h:mm-only-p times)))
1133 (defun org-columns--compute-spec (spec &optional update)
1134 "Update tree according to SPEC.
1135 SPEC is a column format specification. When optional argument
1136 UPDATE is non-nil, summarized values can replace existing ones in
1137 properties drawers."
1138 (let* ((lmax (if (bound-and-true-p org-inlinetask-min-level)
1139 org-inlinetask-min-level
1140 29)) ;Hard-code deepest level.
1141 (lvals (make-vector (1+ lmax) nil))
1145 (property (car spec))
1146 (printf (nth 4 spec))
1147 (operator (nth 3 spec))
1148 (collect (and operator (org-columns--collect operator)))
1149 (summarize (and operator (org-columns--summarize operator))))
1150 (org-with-wide-buffer
1151 ;; Find the region to compute.
1152 (goto-char org-columns-top-level-marker)
1153 (goto-char (condition-case nil (org-end-of-subtree t) (error (point-max))))
1154 ;; Walk the tree from the back and do the computations.
1155 (while (re-search-backward
1156 org-outline-regexp-bol org-columns-top-level-marker t)
1157 (unless (or (= level 0) (eq level inminlevel))
1158 (setq last-level level))
1159 (setq level (org-reduced-level (org-outline-level)))
1160 (let* ((pos (match-beginning 0))
1161 (value (if collect (funcall collect property)
1162 (org-entry-get (point) property)))
1163 (value-set (org-string-nw-p value)))
1165 ((< level last-level)
1166 ;; Collect values from lower levels and inline tasks here
1167 ;; and summarize them using SUMMARIZE. Store them in text
1168 ;; property `org-summaries', in alist whose key is SPEC.
1171 (let ((values (append (and (/= last-level inminlevel)
1172 (aref lvals last-level))
1173 (aref lvals inminlevel))))
1174 (and values (funcall summarize values printf))))))
1175 ;; Leaf values are not summaries: do not mark them.
1177 (let* ((summaries-alist (get-text-property pos 'org-summaries))
1178 (old (assoc spec summaries-alist)))
1179 (if old (setcdr old summary)
1180 (push (cons spec summary) summaries-alist)
1181 (with-silent-modifications
1182 (add-text-properties
1183 pos (1+ pos) (list 'org-summaries summaries-alist)))))
1184 ;; When PROPERTY exists in current node, even if empty,
1185 ;; but its value doesn't match the one computed, use
1186 ;; the latter instead.
1188 ;; Ignore leading or trailing white spaces that might
1189 ;; have been introduced in summary, since those are not
1190 ;; significant in properties value.
1191 (let ((new-value (org-trim summary)))
1192 (when (and update value (not (equal value new-value)))
1193 (org-entry-put (point) property new-value))))
1194 ;; Add current to current level accumulator.
1195 (when (or summary value-set)
1196 (push (or summary value) (aref lvals level)))
1197 ;; Clear accumulators for deeper levels.
1198 (cl-loop for l from (1+ level) to lmax do (aset lvals l nil))))
1199 (value-set (push value (aref lvals level)))
1203 (defun org-columns-compute (property)
1204 "Summarize the values of PROPERTY hierarchically.
1205 Also update existing values for PROPERTY according to the first
1206 column specification."
1209 (upcase-prop (upcase property)))
1210 (dolist (spec org-columns-current-fmt-compiled)
1212 (`(,(pred (equal upcase-prop)) . ,_)
1213 (org-columns--compute-spec spec main-flag)
1214 ;; Only the first summary can update the property value.
1215 (when main-flag (setq main-flag nil)))))))
1217 (defun org-columns-compute-all ()
1218 "Compute all columns that have operators defined."
1219 (with-silent-modifications
1220 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1221 (let ((org-columns--time (float-time))
1223 (dolist (spec org-columns-current-fmt-compiled)
1224 (let ((property (car spec)))
1225 ;; Property value is updated only the first time a given
1226 ;; property is encountered.
1227 (org-columns--compute-spec spec (not (member property seen)))
1228 (push property seen)))))
1230 (defun org-columns--summary-sum (values printf)
1231 "Compute the sum of VALUES.
1232 When PRINTF is non-nil, use it to format the result."
1233 (format (or printf "%s") (apply #'+ (mapcar #'string-to-number values))))
1235 (defun org-columns--summary-currencies (values _)
1236 "Compute the sum of VALUES, with two decimals."
1237 (format "%.2f" (apply #'+ (mapcar #'string-to-number values))))
1239 (defun org-columns--summary-checkbox (check-boxes _)
1240 "Summarize CHECK-BOXES with a check-box."
1241 (let ((done (cl-count "[X]" check-boxes :test #'equal))
1242 (all (length check-boxes)))
1243 (cond ((= done all) "[X]")
1247 (defun org-columns--summary-checkbox-count (check-boxes _)
1248 "Summarize CHECK-BOXES with a check-box cookie."
1250 (cl-count-if (lambda (b) (or (equal b "[X]")
1251 (string-match-p "\\[\\([1-9]\\)/\\1\\]" b)))
1253 (length check-boxes)))
1255 (defun org-columns--summary-checkbox-percent (check-boxes _)
1256 "Summarize CHECK-BOXES with a check-box percent."
1258 (round (* 100.0 (cl-count-if (lambda (b) (member b '("[X]" "[100%]")))
1260 (length check-boxes))))
1262 (defun org-columns--summary-min (values printf)
1263 "Compute the minimum of VALUES.
1264 When PRINTF is non-nil, use it to format the result."
1265 (format (or printf "%s")
1266 (apply #'min (mapcar #'string-to-number values))))
1268 (defun org-columns--summary-max (values printf)
1269 "Compute the maximum of VALUES.
1270 When PRINTF is non-nil, use it to format the result."
1271 (format (or printf "%s")
1272 (apply #'max (mapcar #'string-to-number values))))
1274 (defun org-columns--summary-mean (values printf)
1275 "Compute the mean of VALUES.
1276 When PRINTF is non-nil, use it to format the result."
1277 (format (or printf "%s")
1278 (/ (apply #'+ (mapcar #'string-to-number values))
1279 (float (length values)))))
1281 (defun org-columns--summary-sum-times (times _)
1283 (org-columns--summary-apply-times #'+ times))
1285 (defun org-columns--summary-min-time (times _)
1286 "Compute the minimum time among TIMES."
1287 (org-columns--summary-apply-times #'min times))
1289 (defun org-columns--summary-max-time (times _)
1290 "Compute the maximum time among TIMES."
1291 (org-columns--summary-apply-times #'max times))
1293 (defun org-columns--summary-mean-time (times _)
1294 "Compute the mean time among TIMES."
1295 (org-columns--summary-apply-times
1296 (lambda (&rest values) (/ (apply #'+ values) (float (length values))))
1299 (defun org-columns--summary-min-age (ages _)
1300 "Compute the minimum age among AGES."
1301 (org-columns--format-age
1302 (apply #'min (mapcar #'org-columns--age-to-minutes ages))))
1304 (defun org-columns--summary-max-age (ages _)
1305 "Compute the maximum age among AGES."
1306 (org-columns--format-age
1307 (apply #'max (mapcar #'org-columns--age-to-minutes ages))))
1309 (defun org-columns--summary-mean-age (ages _)
1310 "Compute the mean age among AGES."
1311 (org-columns--format-age
1312 (/ (apply #'+ (mapcar #'org-columns--age-to-minutes ages))
1313 (float (length ages)))))
1315 (defun org-columns--summary-estimate (estimates _)
1316 "Combine a list of estimates, using mean and variance.
1317 The mean and variance of the result will be the sum of the means
1318 and variances (respectively) of the individual estimates."
1321 (dolist (e estimates)
1322 (pcase (mapcar #'string-to-number (split-string e "-"))
1324 (let ((m (/ (+ low high) 2.0)))
1326 (cl-incf var (- (/ (+ (* low low) (* high high)) 2.0) (* m m)))))
1327 (`(,value) (cl-incf mean value))))
1328 (let ((sd (sqrt var)))
1330 (format "%.0f" (- mean sd))
1331 (format "%.0f" (+ mean sd))))))
1335 ;;; Dynamic block for Column view
1337 (defun org-columns--capture-view (maxlevel match skip-empty exclude-tags format local)
1338 "Get the column view of the current buffer.
1340 MAXLEVEL sets the level limit. SKIP-EMPTY tells whether to skip
1341 empty rows, an empty row being one where all the column view
1342 specifiers but ITEM are empty. EXCLUDE-TAGS is a list of tags
1343 that will be excluded from the resulting view. FORMAT is a
1344 format string for columns, or nil. When LOCAL is non-nil, only
1345 capture headings in current subtree.
1347 This function returns a list containing the title row and all
1348 other rows. Each row is a list of fields, as strings, or
1350 (org-columns (not local) format)
1351 (goto-char org-columns-top-level-marker)
1352 (let ((columns (length org-columns-current-fmt-compiled))
1353 (has-item (assoc "ITEM" org-columns-current-fmt-compiled))
1357 (when (get-char-property (point) 'org-columns-key)
1359 (dotimes (i columns)
1360 (let* ((col (+ (line-beginning-position) i))
1361 (p (get-char-property col 'org-columns-key)))
1362 (push (org-quote-vert
1363 (get-char-property col
1364 (if (string= p "ITEM")
1366 'org-columns-value-modified)))
1370 (let ((r (delete-dups (remove "" row))))
1371 (or (null r) (and has-item (= (length r) 1)))))
1373 (cl-some (lambda (tag) (member tag exclude-tags))
1375 (push (cons (org-reduced-level (org-current-level)) (nreverse row))
1377 (or (and maxlevel (format "LEVEL<=%d" maxlevel))
1382 ;; Add column titles and a horizontal rule in front of the table.
1383 (cons (mapcar #'cadr org-columns-current-fmt-compiled)
1384 (cons 'hline (nreverse table)))))
1386 (defun org-columns--clean-item (item)
1387 "Remove sensitive contents from string ITEM.
1388 This includes objects that may not be duplicated within
1389 a document, e.g., a target, or those forbidden in tables, e.g.,
1390 an inline src-block."
1391 (let ((data (org-element-parse-secondary-string
1392 item (org-element-restriction 'headline))))
1393 (org-element-map data
1394 '(footnote-reference inline-babel-call inline-src-block target
1395 radio-target statistics-cookie)
1396 #'org-element-extract-element)
1397 (org-no-properties (org-element-interpret-data data))))
1400 (defun org-dblock-write:columnview (params)
1401 "Write the column view table.
1403 PARAMS is a property list of parameters:
1407 The ID property of the entry where the columns view should be
1408 built. When the symbol `local', call locally. When `global'
1409 call column view with the cursor at the beginning of the
1410 buffer (usually this means that the whole buffer switches to
1411 column view). When \"file:path/to/file.org\", invoke column
1412 view at the start of that file. Otherwise, the ID is located
1413 using `org-id-find'.
1417 List of tags to exclude from column view table.
1421 When non-nil, specify the column view format to use.
1425 When non-nil, insert a hline before each item. When
1426 a number, insert a hline before each level inferior or equal
1431 When non-nil, indent each ITEM field according to its level.
1435 When set to a string, use this as a tags/property match filter.
1439 When set to a number, don't capture headlines below this level.
1443 When non-nil, skip rows where all specifiers other than ITEM
1448 When non-nil, make each column a column group to enforce
1451 (let ((id (plist-get params :id))
1455 ((or `local `nil) (setq view-pos (point)))
1456 ((and (let id-string (format "%s" id))
1457 (guard (string-match "^file:\\(.*\\)" id-string)))
1458 (setq view-file (match-string-no-properties 1 id-string))
1459 (unless (file-exists-p view-file)
1460 (user-error "No such file: %S" id-string)))
1461 ((and (let idpos (org-find-entry-with-id id)) (guard idpos))
1462 (setq view-pos idpos))
1463 ((let `(,filename . ,position) (org-id-find id))
1464 (setq view-file filename)
1465 (setq view-pos position))
1466 (_ (user-error "Cannot find entry with :ID: %s" id)))
1467 (with-current-buffer (if view-file (get-file-buffer view-file)
1469 (org-with-wide-buffer
1470 (when view-pos (goto-char view-pos))
1471 (org-columns--capture-view (plist-get params :maxlevel)
1472 (plist-get params :match)
1473 (plist-get params :skip-empty-rows)
1474 (plist-get params :exclude-tags)
1475 (plist-get params :format)
1478 ;; Prune level information from the table. Also normalize
1479 ;; headings: remove stars, add indentation entities, if
1480 ;; required, and possibly precede some of them with a horizontal
1483 (let ((p (assoc "ITEM" org-columns-current-fmt-compiled)))
1484 (and p (cl-position p
1485 org-columns-current-fmt-compiled
1487 (hlines (plist-get params :hlines))
1488 (indent (plist-get params :indent))
1490 ;; Copy header and first rule.
1491 (push (pop table) new-table)
1492 (push (pop table) new-table)
1493 (dolist (row table (setq table (nreverse new-table)))
1494 (let ((level (car row)))
1495 (when (and (not (eq (car new-table) 'hline))
1497 (and (numberp hlines) (<= level hlines))))
1498 (push 'hline new-table))
1500 (let ((item (org-columns--clean-item (nth item-index (cdr row)))))
1501 (setf (nth item-index (cdr row))
1502 (if (and indent (> level 1))
1503 (concat "\\_" (make-string (* 2 (1- level)) ?\s) item)
1505 (push (cdr row) new-table))))
1506 (when (plist-get params :vlines)
1508 (let ((size (length org-columns-current-fmt-compiled)))
1509 (append (mapcar (lambda (x) (if (eq 'hline x) x (cons "" x)))
1511 (list (cons "/" (make-list size "<>")))))))
1512 (let ((content-lines (org-split-string (plist-get params :content) "\n"))
1514 ;; Insert affiliated keywords before the table.
1516 (while (string-match-p "\\`[ \t]*#\\+" (car content-lines))
1517 (insert (pop content-lines) "\n")))
1519 ;; Insert table at point.
1521 (mapconcat (lambda (row)
1522 (if (eq row 'hline) "|-|"
1523 (format "|%s|" (mapconcat #'identity row "|"))))
1526 ;; Insert TBLFM lines following table.
1527 (let ((case-fold-search t))
1528 (dolist (line content-lines)
1529 (when (string-match-p "\\`[ \t]*#\\+TBLFM:" line)
1531 (unless recalc (setq recalc t))))))
1532 (when recalc (org-table-recalculate 'all t))
1533 (org-table-align)))))
1536 (defun org-columns-insert-dblock ()
1537 "Create a dynamic block capturing a column view table."
1539 (let ((id (completing-read
1540 "Capture columns (local, global, entry with :ID: property) [local]: "
1541 (append '(("global") ("local"))
1542 (mapcar #'list (org-property-values "ID"))))))
1544 (list :name "columnview"
1546 :id (cond ((string= id "global") 'global)
1547 ((member id '("" "local")) 'local)
1549 (org-update-dblock))
1551 (org-dynamic-block-define "columnview" #'org-columns-insert-dblock)
1554 ;;; Column view in the agenda
1557 (defun org-agenda-columns ()
1558 "Turn on or update column view in the agenda."
1560 (org-columns-remove-overlays)
1561 (if (markerp org-columns-begin-marker)
1562 (move-marker org-columns-begin-marker (point))
1563 (setq org-columns-begin-marker (point-marker)))
1564 (let* ((org-columns--time (float-time))
1567 ((bound-and-true-p org-overriding-columns-format))
1568 ((bound-and-true-p org-local-columns-format))
1569 ((let ((m (org-get-at-bol 'org-hd-marker)))
1571 (or (org-entry-get m "COLUMNS" t)
1572 (with-current-buffer (marker-buffer m)
1573 org-columns-default-format)))))
1574 ((and (local-variable-p 'org-columns-current-fmt)
1575 org-columns-current-fmt))
1576 ((let ((m (next-single-property-change (point-min) 'org-hd-marker)))
1578 (let ((m (get-text-property m 'org-hd-marker)))
1579 (or (org-entry-get m "COLUMNS" t)
1580 (with-current-buffer (marker-buffer m)
1581 org-columns-default-format))))))
1582 (t org-columns-default-format)))
1583 (compiled-fmt (org-columns-compile-format fmt)))
1584 (setq org-columns-current-fmt fmt)
1585 (when org-agenda-columns-compute-summary-properties
1586 (org-agenda-colview-compute org-columns-current-fmt-compiled))
1588 ;; Collect properties for each headline in current view.
1589 (goto-char (point-min))
1592 (let ((m (org-get-at-bol 'org-hd-marker)))
1594 (push (cons (line-beginning-position)
1595 ;; `org-columns-current-fmt-compiled' is
1596 ;; initialized but only set locally to the
1597 ;; agenda buffer. Since current buffer is
1598 ;; changing, we need to force the original
1599 ;; compiled-fmt there.
1600 (org-with-point-at m
1601 (org-columns--collect-values compiled-fmt)))
1605 (org-columns--set-widths cache)
1606 (org-columns--display-here-title)
1607 (when (setq-local org-columns-flyspell-was-active
1608 (bound-and-true-p flyspell-mode))
1610 (dolist (entry cache)
1611 (goto-char (car entry))
1612 (org-columns--display-here (cdr entry)))
1613 (when org-agenda-columns-show-summaries
1614 (org-agenda-colview-summarize cache)))))))
1616 (defun org-agenda-colview-summarize (cache)
1617 "Summarize the summarizable columns in column view in the agenda.
1618 This will add overlays to the date lines, to show the summary for each day."
1622 (`(,property ,title ,width . ,_)
1623 (if (member property '("CLOCKSUM" "CLOCKSUM_T"))
1624 (list property title width ":" nil)
1626 org-columns-current-fmt-compiled)))
1627 ;; Ensure there's at least one summation column.
1628 (when (cl-some (lambda (spec) (nth 3 spec)) fmt)
1629 (goto-char (point-max))
1632 (when (or (get-text-property (point) 'org-date-line)
1633 (eq (get-text-property (point) 'face)
1634 'org-agenda-structure))
1635 ;; OK, this is a date line that should be used.
1639 (if (> (car c) (point))
1643 ;; ENTRIES contains entries below the current one.
1644 ;; CACHE is the rest. Compute the summaries for the
1645 ;; properties we want, set nil properties for the rest.
1646 (when (setq entries (mapcar #'cdr entries))
1647 (org-columns--display-here
1652 ;; Replace ITEM with current date. Preserve
1653 ;; properties for fontification.
1654 (let ((date (buffer-substring
1655 (line-beginning-position)
1656 (line-end-position))))
1657 (list spec date date)))
1658 (`(,_ ,_ ,_ nil ,_) (list spec "" ""))
1659 (`(,_ ,_ ,_ ,operator ,printf)
1660 (let* ((summarize (org-columns--summarize operator))
1662 ;; Use real values for summary, not
1663 ;; those prepared for display.
1666 (lambda (e) (org-string-nw-p
1667 (nth 1 (assoc spec e))))
1670 (funcall summarize values printf)
1672 (unless (equal final "")
1673 (put-text-property 0 (length final)
1675 (list spec final final)))))
1678 (setq-local org-agenda-columns-active t))))
1679 (if (bobp) (throw :complete t) (forward-line -1)))))))
1681 (defun org-agenda-colview-compute (fmt)
1682 "Compute the relevant columns in the contributing source buffers."
1683 (dolist (file org-agenda-contributing-files)
1684 (let ((b (find-buffer-visiting file)))
1685 (with-current-buffer (or (buffer-base-buffer b) b)
1686 (org-with-wide-buffer
1687 (with-silent-modifications
1688 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1689 (goto-char (point-min))
1690 (org-columns-get-format-and-top-level)
1692 (let ((prop (car spec)))
1694 ((equal prop "CLOCKSUM") (org-clock-sum))
1695 ((equal prop "CLOCKSUM_T") (org-clock-sum-today))
1697 (let ((a (assoc prop org-columns-current-fmt-compiled)))
1698 (equal (nth 3 a) (nth 3 spec))))
1699 (org-columns-compute prop))))))))))
1702 (provide 'org-colview)
1704 ;;; org-colview.el ends here