Use ‘eq’ instead of ‘equal’ for symbols
[org-mode.git] / lisp / org-colview.el
blob7bf077a3d1a290d961b44171d94101fecc2dc8ef
1 ;;; org-colview.el --- Column View in Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
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 <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the column view for Org.
29 ;;; Code:
31 (require 'cl-lib)
32 (require '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))
45 (defvar org-agenda-columns-add-appointments-to-effort-sum)
46 (defvar org-agenda-columns-compute-summary-properties)
47 (defvar org-agenda-columns-show-summaries)
48 (defvar org-agenda-view-columns-initially)
49 (defvar org-inlinetask-min-level)
52 ;;; Configuration
54 (defcustom org-columns-modify-value-for-display-function nil
55 "Function that modifies values for display in column view.
56 For example, it can be used to cut out a certain part from a time stamp.
57 The function must take 2 arguments:
59 column-title The title of the column (*not* the property name)
60 value The value that should be modified.
62 The function should return the value that should be displayed,
63 or nil if the normal value should be used."
64 :group 'org-properties
65 :type '(choice (const nil) (function)))
67 (defcustom org-columns-summary-types nil
68 "Alist between operators and summarize functions.
70 Each association follows the pattern (LABEL . SUMMARIZE) where
72 LABEL is a string used in #+COLUMNS definition describing the
73 summary type. It can contain any character but \"}\". It is
74 case-sensitive.
76 SUMMARIZE is a function called with two arguments. The first
77 argument is a non-empty list of values, as non-empty strings.
78 The second one is a format string or nil. It has to return
79 a string summarizing the list of values.
81 Note that the return value can become one value for an higher
82 order summary, so the function is expected to handle its own
83 output.
85 Types defined in this variable take precedence over those defined
86 in `org-columns-summary-types-default', which see."
87 :group 'org-properties
88 :version "25.1"
89 :package-version '(Org . "9.0")
90 :type '(alist :key-type (string :tag " Label")
91 :value-type (function :tag "Summarize")))
95 ;;; Column View
97 (defvar org-columns-overlays nil
98 "Holds the list of current column overlays.")
100 (defvar org-columns--time 0.0
101 "Number of seconds since the epoch, as a floating point number.")
103 (defvar-local org-columns-current-fmt nil
104 "Local variable, holds the currently active column format.")
106 (defvar-local org-columns-current-fmt-compiled nil
107 "Local variable, holds the currently active column format.
108 This is the compiled version of the format.")
110 (defvar-local org-columns-current-maxwidths nil
111 "Currently active maximum column widths, as a vector.")
113 (defvar org-columns-begin-marker (make-marker)
114 "Points to the position where last a column creation command was called.")
116 (defvar org-columns-top-level-marker (make-marker)
117 "Points to the position where current columns region starts.")
119 (defvar org-columns-map (make-sparse-keymap)
120 "The keymap valid in column display.")
122 (defconst org-columns-summary-types-default
123 '(("+" . org-columns--summary-sum)
124 ("$" . org-columns--summary-currencies)
125 ("X" . org-columns--summary-checkbox)
126 ("X/" . org-columns--summary-checkbox-count)
127 ("X%" . org-columns--summary-checkbox-percent)
128 ("max" . org-columns--summary-max)
129 ("mean" . org-columns--summary-mean)
130 ("min" . org-columns--summary-min)
131 (":" . org-columns--summary-sum-times)
132 (":max" . org-columns--summary-max-time)
133 (":mean" . org-columns--summary-mean-time)
134 (":min" . org-columns--summary-min-time)
135 ("@max" . org-columns--summary-max-age)
136 ("@mean" . org-columns--summary-mean-age)
137 ("@min" . org-columns--summary-min-age)
138 ("est+" . org-columns--summary-estimate))
139 "Map operators to summarize functions.
140 See `org-columns-summary-types' for details.")
142 (defun org-columns-content ()
143 "Switch to contents view while in columns view."
144 (interactive)
145 (org-overview)
146 (org-content))
148 (org-defkey org-columns-map "c" 'org-columns-content)
149 (org-defkey org-columns-map "o" 'org-overview)
150 (org-defkey org-columns-map "e" 'org-columns-edit-value)
151 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
152 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
153 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
154 (org-defkey org-columns-map "v" 'org-columns-show-value)
155 (org-defkey org-columns-map "q" 'org-columns-quit)
156 (org-defkey org-columns-map "r" 'org-columns-redo)
157 (org-defkey org-columns-map "g" 'org-columns-redo)
158 (org-defkey org-columns-map [left] 'backward-char)
159 (org-defkey org-columns-map "\M-b" 'backward-char)
160 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
161 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
162 (org-defkey org-columns-map "\M-f"
163 (lambda () (interactive) (goto-char (1+ (point)))))
164 (org-defkey org-columns-map [right]
165 (lambda () (interactive) (goto-char (1+ (point)))))
166 (org-defkey org-columns-map [down]
167 (lambda () (interactive)
168 (let ((col (current-column)))
169 (beginning-of-line 2)
170 (while (and (org-invisible-p2) (not (eobp)))
171 (beginning-of-line 2))
172 (move-to-column col)
173 (if (eq major-mode 'org-agenda-mode)
174 (org-agenda-do-context-action)))))
175 (org-defkey org-columns-map [up]
176 (lambda () (interactive)
177 (let ((col (current-column)))
178 (beginning-of-line 0)
179 (while (and (org-invisible-p2) (not (bobp)))
180 (beginning-of-line 0))
181 (move-to-column col)
182 (if (eq major-mode 'org-agenda-mode)
183 (org-agenda-do-context-action)))))
184 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
185 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
186 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
187 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
188 (org-defkey org-columns-map "<" 'org-columns-narrow)
189 (org-defkey org-columns-map ">" 'org-columns-widen)
190 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
191 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
192 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
193 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
194 (dotimes (i 10)
195 (org-defkey org-columns-map (number-to-string i)
196 `(lambda () (interactive)
197 (org-columns-next-allowed-value nil ,i))))
199 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
200 '("Column"
201 ["Edit property" org-columns-edit-value t]
202 ["Next allowed value" org-columns-next-allowed-value t]
203 ["Previous allowed value" org-columns-previous-allowed-value t]
204 ["Show full value" org-columns-show-value t]
205 ["Edit allowed values" org-columns-edit-allowed t]
206 "--"
207 ["Edit column attributes" org-columns-edit-attributes t]
208 ["Increase column width" org-columns-widen t]
209 ["Decrease column width" org-columns-narrow t]
210 "--"
211 ["Move column right" org-columns-move-right t]
212 ["Move column left" org-columns-move-left t]
213 ["Add column" org-columns-new t]
214 ["Delete column" org-columns-delete t]
215 "--"
216 ["CONTENTS" org-columns-content t]
217 ["OVERVIEW" org-overview t]
218 ["Refresh columns display" org-columns-redo t]
219 "--"
220 ["Open link" org-columns-open-link t]
221 "--"
222 ["Quit" org-columns-quit t]))
224 (defun org-columns--displayed-value (spec value)
225 "Return displayed value for specification SPEC in current entry.
227 SPEC is a column format specification as stored in
228 `org-columns-current-fmt-compiled'. VALUE is the real value to
229 display, as a string."
230 (cond
231 ((and (functionp org-columns-modify-value-for-display-function)
232 (funcall org-columns-modify-value-for-display-function
233 (nth 1 spec)
234 value)))
235 ((equal (car spec) "ITEM")
236 (concat (make-string (1- (org-current-level))
237 (if org-hide-leading-stars ?\s ?*))
238 "* "
239 (org-columns-compact-links value)))
240 (value)))
242 (defun org-columns--collect-values (&optional agenda)
243 "Collect values for columns on the current line.
245 When optional argument AGENDA is non-nil, assume the value is
246 meant for the agenda, i.e., caller is `org-agenda-columns'.
248 Return a list of triplets (SPEC VALUE DISPLAYED) suitable for
249 `org-columns--display-here'.
251 This function assumes `org-columns-current-fmt-compiled' is
252 initialized."
253 (let ((summaries (get-text-property (point) 'org-summaries)))
254 (mapcar
255 (lambda (spec)
256 (pcase spec
257 (`(,p . ,_)
258 (let* ((v (or (cdr (assoc spec summaries))
259 (org-entry-get (point) p 'selective t)
260 (and agenda
261 ;; Effort property is not defined. Try
262 ;; to use appointment duration.
263 org-agenda-columns-add-appointments-to-effort-sum
264 (string= p (upcase org-effort-property))
265 (get-text-property (point) 'duration)
266 (propertize
267 (org-minutes-to-clocksum-string
268 (get-text-property (point) 'duration))
269 'face 'org-warning))
270 "")))
271 (list spec v (org-columns--displayed-value spec v))))))
272 org-columns-current-fmt-compiled)))
274 (defun org-columns--set-widths (cache)
275 "Compute the maximum column widths from the format and CACHE.
276 This function sets `org-columns-current-maxwidths' as a vector of
277 integers greater than 0."
278 (setq org-columns-current-maxwidths
279 (apply #'vector
280 (mapcar
281 (lambda (spec)
282 (pcase spec
283 (`(,_ ,_ ,(and width (pred wholenump)) . ,_) width)
284 (`(,_ ,name . ,_)
285 ;; No width is specified in the columns format.
286 ;; Compute it by checking all possible values for
287 ;; PROPERTY.
288 (let ((width (length name)))
289 (dolist (entry cache width)
290 (let ((value (nth 2 (assoc spec (cdr entry)))))
291 (setq width (max (length value) width))))))))
292 org-columns-current-fmt-compiled))))
294 (defun org-columns--new-overlay (beg end &optional string face)
295 "Create a new column overlay and add it to the list."
296 (let ((ov (make-overlay beg end)))
297 (overlay-put ov 'face (or face 'secondary-selection))
298 (org-overlay-display ov string face)
299 (push ov org-columns-overlays)
300 ov))
302 (defun org-columns--summarize (operator)
303 "Return summary function associated to string OPERATOR."
304 (if (not operator) nil
305 (cdr (or (assoc operator org-columns-summary-types)
306 (assoc operator org-columns-summary-types-default)
307 (error "Unknown %S operator" operator)))))
309 (defun org-columns--overlay-text (value fmt width property original)
310 "Return text "
311 (format fmt
312 (let ((v (org-columns-add-ellipses value width)))
313 (pcase property
314 ("PRIORITY"
315 (propertize v 'face (org-get-priority-face original)))
316 ("TAGS"
317 (if (not org-tags-special-faces-re)
318 (propertize v 'face 'org-tag)
319 (replace-regexp-in-string
320 org-tags-special-faces-re
321 (lambda (m) (propertize m 'face (org-get-tag-face m)))
322 v nil nil 1)))
323 ("TODO" (propertize v 'face (org-get-todo-face original)))
324 (_ v)))))
326 (defun org-columns--display-here (columns &optional dateline)
327 "Overlay the current line with column display.
328 COLUMNS is an alist (SPEC VALUE DISPLAYED). Optional argument
329 DATELINE is non-nil when the face used should be
330 `org-agenda-column-dateline'."
331 (save-excursion
332 (beginning-of-line)
333 (let* ((level-face (and (looking-at "\\(\\**\\)\\(\\* \\)")
334 (org-get-level-face 2)))
335 (ref-face (or level-face
336 (and (eq major-mode 'org-agenda-mode)
337 (org-get-at-bol 'face))
338 'default))
339 (color (list :foreground (face-attribute ref-face :foreground)))
340 (font (list :height (face-attribute 'default :height)
341 :family (face-attribute 'default :family)))
342 (face (list color font 'org-column ref-face))
343 (face1 (list color font 'org-agenda-column-dateline ref-face)))
344 ;; Each column is an overlay on top of a character. So there has
345 ;; to be at least as many characters available on the line as
346 ;; columns to display.
347 (let ((columns (length org-columns-current-fmt-compiled))
348 (chars (- (line-end-position) (line-beginning-position))))
349 (when (> columns chars)
350 (save-excursion
351 (end-of-line)
352 (let ((inhibit-read-only t))
353 (insert (make-string (- columns chars) ?\s))))))
354 ;; Display columns. Create and install the overlay for the
355 ;; current column on the next character.
356 (let ((i 0)
357 (last (1- (length columns))))
358 (dolist (column columns)
359 (pcase column
360 (`(,spec ,original ,value)
361 (let* ((property (car spec))
362 (width (aref org-columns-current-maxwidths i))
363 (fmt (format (if (= i last) "%%-%d.%ds |"
364 "%%-%d.%ds | ")
365 width width))
366 (ov (org-columns--new-overlay
367 (point) (1+ (point))
368 (org-columns--overlay-text
369 value fmt width property original)
370 (if dateline face1 face))))
371 (overlay-put ov 'keymap org-columns-map)
372 (overlay-put ov 'org-columns-key property)
373 (overlay-put ov 'org-columns-value original)
374 (overlay-put ov 'org-columns-value-modified value)
375 (overlay-put ov 'org-columns-format fmt)
376 (overlay-put ov 'line-prefix "")
377 (overlay-put ov 'wrap-prefix "")
378 (forward-char))))
379 (cl-incf i)))
380 ;; Make the rest of the line disappear.
381 (let ((ov (org-columns--new-overlay (point) (line-end-position))))
382 (overlay-put ov 'invisible t)
383 (overlay-put ov 'keymap org-columns-map)
384 (overlay-put ov 'line-prefix "")
385 (overlay-put ov 'wrap-prefix ""))
386 (let ((ov (make-overlay (1- (line-end-position))
387 (line-beginning-position 2))))
388 (overlay-put ov 'keymap org-columns-map)
389 (push ov org-columns-overlays))
390 (org-with-silent-modifications
391 (let ((inhibit-read-only t))
392 (put-text-property
393 (line-end-position 0)
394 (line-beginning-position 2)
395 'read-only
396 (substitute-command-keys
397 "Type \\<org-columns-map>\\[org-columns-edit-value] \
398 to edit property")))))))
400 (defun org-columns-add-ellipses (string width)
401 "Truncate STRING with WIDTH characters, with ellipses."
402 (cond
403 ((<= (length string) width) string)
404 ((<= width (length org-columns-ellipses))
405 (substring org-columns-ellipses 0 width))
406 (t (concat (substring string 0 (- width (length org-columns-ellipses)))
407 org-columns-ellipses))))
409 (defvar org-columns-full-header-line-format nil
410 "The full header line format, will be shifted by horizontal scrolling." )
411 (defvar org-previous-header-line-format nil
412 "The header line format before column view was turned on.")
413 (defvar org-columns-inhibit-recalculation nil
414 "Inhibit recomputing of columns on column view startup.")
415 (defvar org-columns-flyspell-was-active nil
416 "Remember the state of `flyspell-mode' before column view.
417 Flyspell-mode can cause problems in columns view, so it is turned off
418 for the duration of the command.")
420 (defvar header-line-format)
421 (defvar org-columns-previous-hscroll 0)
423 (defun org-columns--display-here-title ()
424 "Overlay the newline before the current line with the table title."
425 (interactive)
426 (let ((title "")
427 (i 0))
428 (dolist (column org-columns-current-fmt-compiled)
429 (pcase column
430 (`(,property ,name . ,_)
431 (let* ((width (aref org-columns-current-maxwidths i))
432 (fmt (format "%%-%d.%ds | " width width)))
433 (setq title (concat title (format fmt (or name property)))))))
434 (cl-incf i))
435 (setq-local org-previous-header-line-format header-line-format)
436 (setq org-columns-full-header-line-format
437 (concat
438 (org-add-props " " nil 'display '(space :align-to 0))
439 (org-add-props (substring title 0 -1) nil 'face 'org-column-title)))
440 (setq org-columns-previous-hscroll -1)
441 (add-hook 'post-command-hook 'org-columns-hscroll-title nil 'local)))
443 (defun org-columns-hscroll-title ()
444 "Set the `header-line-format' so that it scrolls along with the table."
445 (sit-for .0001) ; need to force a redisplay to update window-hscroll
446 (when (not (= (window-hscroll) org-columns-previous-hscroll))
447 (setq header-line-format
448 (concat (substring org-columns-full-header-line-format 0 1)
449 (substring org-columns-full-header-line-format
450 (1+ (window-hscroll))))
451 org-columns-previous-hscroll (window-hscroll))
452 (force-mode-line-update)))
454 (defvar org-colview-initial-truncate-line-value nil
455 "Remember the value of `truncate-lines' across colview.")
457 ;;;###autoload
458 (defun org-columns-remove-overlays ()
459 "Remove all currently active column overlays."
460 (interactive)
461 (when (marker-buffer org-columns-begin-marker)
462 (with-current-buffer (marker-buffer org-columns-begin-marker)
463 (when (local-variable-p 'org-previous-header-line-format)
464 (setq header-line-format org-previous-header-line-format)
465 (kill-local-variable 'org-previous-header-line-format)
466 (remove-hook 'post-command-hook 'org-columns-hscroll-title 'local))
467 (move-marker org-columns-begin-marker nil)
468 (move-marker org-columns-top-level-marker nil)
469 (org-with-silent-modifications
470 (mapc 'delete-overlay org-columns-overlays)
471 (setq org-columns-overlays nil)
472 (let ((inhibit-read-only t))
473 (remove-text-properties (point-min) (point-max) '(read-only t))))
474 (when org-columns-flyspell-was-active
475 (flyspell-mode 1))
476 (when (local-variable-p 'org-colview-initial-truncate-line-value)
477 (setq truncate-lines org-colview-initial-truncate-line-value)))))
479 (defun org-columns-compact-links (s)
480 "Replace [[link][desc]] with [desc] or [link]."
481 (while (string-match org-bracket-link-regexp s)
482 (setq s (replace-match
483 (concat "[" (match-string (if (match-end 3) 3 1) s) "]")
484 t t s)))
487 (defun org-columns-show-value ()
488 "Show the full value of the property."
489 (interactive)
490 (let ((value (get-char-property (point) 'org-columns-value)))
491 (message "Value is: %s" (or value ""))))
493 (defvar org-agenda-columns-active) ;; defined in org-agenda.el
495 (defun org-columns-quit ()
496 "Remove the column overlays and in this way exit column editing."
497 (interactive)
498 (org-with-silent-modifications
499 (org-columns-remove-overlays)
500 (let ((inhibit-read-only t))
501 (remove-text-properties (point-min) (point-max) '(read-only t))))
502 (if (not (eq major-mode 'org-agenda-mode))
503 (setq org-columns-current-fmt nil)
504 (setq org-agenda-columns-active nil)
505 (message
506 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
508 (defun org-columns-check-computed ()
509 "Throw an error if current column value is computed."
510 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
511 (and
512 (nth 3 spec)
513 (assoc spec (get-text-property (line-beginning-position) 'org-summaries))
514 (error "This value is computed from the entry's children"))))
516 (defun org-columns-todo (&optional _arg)
517 "Change the TODO state during column view."
518 (interactive "P")
519 (org-columns-edit-value "TODO"))
521 (defun org-columns-set-tags-or-toggle (&optional _arg)
522 "Toggle checkbox at point, or set tags for current headline."
523 (interactive "P")
524 (if (string-match "\\`\\[[ xX-]\\]\\'"
525 (get-char-property (point) 'org-columns-value))
526 (org-columns-next-allowed-value)
527 (org-columns-edit-value "TAGS")))
529 (defvar org-agenda-overriding-columns-format nil
530 "When set, overrides any other format definition for the agenda.
531 Don't set this, this is meant for dynamic scoping.")
533 (defun org-columns-edit-value (&optional key)
534 "Edit the value of the property at point in column view.
535 Where possible, use the standard interface for changing this line."
536 (interactive)
537 (org-columns-check-computed)
538 (let* ((col (current-column))
539 (bol (line-beginning-position))
540 (eol (line-end-position))
541 (pom (or (get-text-property bol 'org-hd-marker) (point)))
542 (key (or key (get-char-property (point) 'org-columns-key)))
543 (org-columns--time (float-time (current-time)))
544 (action
545 (pcase key
546 ("CLOCKSUM"
547 (error "This special column cannot be edited"))
548 ("ITEM"
549 (lambda () (org-with-point-at pom (org-edit-headline))))
550 ("TODO"
551 (lambda ()
552 (org-with-point-at pom (call-interactively #'org-todo))))
553 ("PRIORITY"
554 (lambda ()
555 (org-with-point-at pom
556 (call-interactively #'org-priority))))
557 ("TAGS"
558 (lambda ()
559 (org-with-point-at pom
560 (let ((org-fast-tag-selection-single-key
561 (if (eq org-fast-tag-selection-single-key 'expert)
563 org-fast-tag-selection-single-key)))
564 (call-interactively #'org-set-tags)))))
565 ("DEADLINE"
566 (lambda ()
567 (org-with-point-at pom (call-interactively #'org-deadline))))
568 ("SCHEDULED"
569 (lambda ()
570 (org-with-point-at pom (call-interactively #'org-schedule))))
571 ("BEAMER_ENV"
572 (lambda ()
573 (org-with-point-at pom
574 (call-interactively #'org-beamer-select-environment))))
576 (let* ((allowed (org-property-get-allowed-values pom key 'table))
577 (value (get-char-property (point) 'org-columns-value))
578 (nval (org-trim
579 (if (null allowed) (read-string "Edit: " value)
580 (completing-read
581 "Value: " allowed nil
582 (not (get-text-property
583 0 'org-unrestricted (caar allowed))))))))
584 (and (not (equal nval value))
585 (lambda () (org-entry-put pom key nval))))))))
586 (cond
587 ((null action))
588 ((eq major-mode 'org-agenda-mode)
589 (org-columns--call action)
590 ;; The following let preserves the current format, and makes
591 ;; sure that in only a single file things need to be updated.
592 (let* ((org-agenda-overriding-columns-format org-columns-current-fmt)
593 (buffer (marker-buffer pom))
594 (org-agenda-contributing-files
595 (list (with-current-buffer buffer
596 (buffer-file-name (buffer-base-buffer))))))
597 (org-agenda-columns)))
599 (let ((inhibit-read-only t))
600 (org-with-silent-modifications
601 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t)))
602 (org-columns--call action))
603 ;; Some properties can modify headline (e.g., "TODO"), and
604 ;; possible shuffle overlays. Make sure they are still all at
605 ;; the right place on the current line.
606 (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
607 (org-columns-update key)
608 (org-move-to-column col)))))
610 (defun org-columns-edit-allowed ()
611 "Edit the list of allowed values for the current property."
612 (interactive)
613 (let* ((pom (or (org-get-at-bol 'org-marker)
614 (org-get-at-bol 'org-hd-marker)
615 (point)))
616 (key (get-char-property (point) 'org-columns-key))
617 (key1 (concat key "_ALL"))
618 (allowed (org-entry-get pom key1 t))
619 nval)
620 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
621 ;; FIXME: Write back to #+PROPERTY setting if that is needed.
622 (setq nval (read-string "Allowed: " allowed))
623 (org-entry-put
624 (cond ((marker-position org-entry-property-inherited-from)
625 org-entry-property-inherited-from)
626 ((marker-position org-columns-top-level-marker)
627 org-columns-top-level-marker)
628 (t pom))
629 key1 nval)))
631 (defun org-columns--call (fun)
632 "Call function FUN while preserving heading visibility.
633 FUN is a function called with no argument."
634 (let ((hide-body (and (/= (line-end-position) (point-max))
635 (save-excursion
636 (move-beginning-of-line 2)
637 (org-at-heading-p t)))))
638 (unwind-protect (funcall fun)
639 (when hide-body (outline-hide-entry)))))
641 (defun org-columns-previous-allowed-value ()
642 "Switch to the previous allowed value for this column."
643 (interactive)
644 (org-columns-next-allowed-value t))
646 (defun org-columns-next-allowed-value (&optional previous nth)
647 "Switch to the next allowed value for this column.
648 When PREVIOUS is set, go to the previous value. When NTH is
649 an integer, select that value."
650 (interactive)
651 (org-columns-check-computed)
652 (let* ((column (current-column))
653 (key (get-char-property (point) 'org-columns-key))
654 (value (get-char-property (point) 'org-columns-value))
655 (pom (or (get-text-property (line-beginning-position) 'org-hd-marker)
656 (point)))
657 (allowed
658 (let ((all
659 (or (org-property-get-allowed-values pom key)
660 (pcase (nth column org-columns-current-fmt-compiled)
661 (`(,_ ,_ ,_ ,(or "X" "X/" "X%") ,_) '("[ ]" "[X]")))
662 (org-colview-construct-allowed-dates value))))
663 (if previous (reverse all) all))))
664 (when (equal key "ITEM") (error "Cannot edit item headline from here"))
665 (unless (or allowed (member key '("SCHEDULED" "DEADLINE" "CLOCKSUM")))
666 (error "Allowed values for this property have not been defined"))
667 (let* ((l (length allowed))
668 (new
669 (cond
670 ((member key '("SCHEDULED" "DEADLINE" "CLOCKSUM"))
671 (if previous 'earlier 'later))
672 ((integerp nth)
673 (when (> (abs nth) l)
674 (user-error "Only %d allowed values for property `%s'" l key))
675 (nth (mod (1- nth) l) allowed))
676 ((member value allowed)
677 (when (= l 1) (error "Only one allowed value for this property"))
678 (or (nth 1 (member value allowed)) (car allowed)))
679 (t (car allowed))))
680 (action (lambda () (org-entry-put pom key new))))
681 (cond
682 ((eq major-mode 'org-agenda-mode)
683 (org-columns--call action)
684 ;; The following let preserves the current format, and makes
685 ;; sure that in only a single file things need to be updated.
686 (let* ((org-agenda-overriding-columns-format org-columns-current-fmt)
687 (buffer (marker-buffer pom))
688 (org-agenda-contributing-files
689 (list (with-current-buffer buffer
690 (buffer-file-name (buffer-base-buffer))))))
691 (org-agenda-columns)))
693 (let ((inhibit-read-only t))
694 (remove-text-properties (line-end-position 0) (line-end-position)
695 '(read-only t))
696 (org-columns--call action))
697 ;; Some properties can modify headline (e.g., "TODO"), and
698 ;; possible shuffle overlays. Make sure they are still all at
699 ;; the right place on the current line.
700 (let ((org-columns-inhibit-recalculation)) (org-columns-redo))
701 (org-columns-update key)
702 (org-move-to-column column))))))
704 (defun org-colview-construct-allowed-dates (s)
705 "Construct a list of three dates around the date in S.
706 This respects the format of the time stamp in S, active or non-active,
707 and also including time or not. S must be just a time stamp, no text
708 around it."
709 (when (and s (string-match (concat "^" org-ts-regexp3 "$") s))
710 (let* ((time (org-parse-time-string s 'nodefaults))
711 (active (equal (string-to-char s) ?<))
712 (fmt (funcall (if (nth 1 time) 'cdr 'car) org-time-stamp-formats))
713 time-before time-after)
714 (unless active (setq fmt (concat "[" (substring fmt 1 -1) "]")))
715 (setf (car time) (or (car time) 0))
716 (setf (nth 1 time) (or (nth 1 time) 0))
717 (setf (nth 2 time) (or (nth 2 time) 0))
718 (setq time-before (copy-sequence time))
719 (setq time-after (copy-sequence time))
720 (setf (nth 3 time-before) (1- (nth 3 time)))
721 (setf (nth 3 time-after) (1+ (nth 3 time)))
722 (mapcar (lambda (x) (format-time-string fmt (apply 'encode-time x)))
723 (list time-before time time-after)))))
725 (defun org-columns-open-link (&optional arg)
726 (interactive "P")
727 (let ((value (get-char-property (point) 'org-columns-value)))
728 (org-open-link-from-string value arg)))
730 ;;;###autoload
731 (defun org-columns-get-format-and-top-level ()
732 (let ((fmt (org-columns-get-format)))
733 (org-columns-goto-top-level)
734 fmt))
736 (defun org-columns-get-format (&optional fmt-string)
737 "Return columns format specifications.
738 When optional argument FMT-STRING is non-nil, use it as the
739 current specifications. This function also sets
740 `org-columns-current-fmt-compiled' and
741 `org-columns-current-fmt'."
742 (interactive)
743 (let ((format
744 (or fmt-string
745 (org-entry-get nil "COLUMNS" t)
746 (org-with-wide-buffer
747 (goto-char (point-min))
748 (catch :found
749 (let ((case-fold-search t))
750 (while (re-search-forward "^[ \t]*#\\+COLUMNS: .+$" nil t)
751 (let ((element (org-element-at-point)))
752 (when (eq (org-element-type element) 'keyword)
753 (throw :found (org-element-property :value element)))))
754 nil)))
755 org-columns-default-format)))
756 (setq org-columns-current-fmt format)
757 (org-columns-compile-format format)
758 format))
760 (defun org-columns-goto-top-level ()
761 "Move to the beginning of the column view area.
762 Also sets `org-columns-top-level-marker' to the new position."
763 (goto-char
764 (move-marker
765 org-columns-top-level-marker
766 (cond ((org-before-first-heading-p) (point-min))
767 ((org-entry-get nil "COLUMNS" t) org-entry-property-inherited-from)
768 (t (org-back-to-heading) (point))))))
770 ;;;###autoload
771 (defun org-columns (&optional global columns-fmt-string)
772 "Turn on column view on an Org mode file.
774 Column view applies to the whole buffer if point is before the
775 first headline. Otherwise, it applies to the first ancestor
776 setting \"COLUMNS\" property. If there is none, it defaults to
777 the current headline. With a \\[universal-argument] prefix \
778 argument, turn on column
779 view for the whole buffer unconditionally.
781 When COLUMNS-FMT-STRING is non-nil, use it as the column format."
782 (interactive "P")
783 (org-columns-remove-overlays)
784 (move-marker org-columns-begin-marker (point))
785 (org-columns-goto-top-level)
786 ;; Initialize `org-columns-current-fmt' and
787 ;; `org-columns-current-fmt-compiled'.
788 (let ((org-columns--time (float-time (current-time))))
789 (org-columns-get-format columns-fmt-string)
790 (unless org-columns-inhibit-recalculation (org-columns-compute-all))
791 (save-excursion
792 (save-restriction
793 (when (and (not global) (org-at-heading-p))
794 (narrow-to-region (point) (org-end-of-subtree t t)))
795 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
796 (org-clock-sum))
797 (when (assoc "CLOCKSUM_T" org-columns-current-fmt-compiled)
798 (org-clock-sum-today))
799 (let ((cache
800 ;; Collect contents of columns ahead of time so as to
801 ;; compute their maximum width.
802 (org-map-entries
803 (lambda () (cons (point) (org-columns--collect-values)))
804 nil nil (and org-columns-skip-archived-trees 'archive))))
805 (when cache
806 (org-columns--set-widths cache)
807 (org-columns--display-here-title)
808 (when (setq-local org-columns-flyspell-was-active
809 (bound-and-true-p flyspell-mode))
810 (flyspell-mode 0))
811 (unless (local-variable-p 'org-colview-initial-truncate-line-value)
812 (setq-local org-colview-initial-truncate-line-value
813 truncate-lines))
814 (setq truncate-lines t)
815 (dolist (entry cache)
816 (goto-char (car entry))
817 (org-columns--display-here (cdr entry)))))))))
819 (defun org-columns-new (&optional spec &rest attributes)
820 "Insert a new column, to the left of the current column.
821 Interactively fill attributes for new column. When column format
822 specification SPEC is provided, edit it instead.
824 When optional argument attributes can be a list of columns
825 specifications attributes to create the new column
826 non-interactively. See `org-columns-compile-format' for
827 details."
828 (interactive)
829 (let ((new (or attributes
830 (let ((prop
831 (completing-read
832 "Property: "
833 (mapcar #'list (org-buffer-property-keys t nil t))
834 nil nil (nth 0 spec))))
835 (list prop
836 (read-string (format "Column title [%s]: " prop)
837 (nth 1 spec))
838 ;; Use `read-string' instead of `read-number'
839 ;; to allow empty width.
840 (let ((w (read-string
841 "Column width: "
842 (and (nth 2 spec)
843 (number-to-string (nth 2 spec))))))
844 (and (org-string-nw-p w) (string-to-number w)))
845 (org-string-nw-p
846 (completing-read
847 "Summary: "
848 (delete-dups
849 (cons '("") ;Allow empty operator.
850 (mapcar (lambda (x) (list (car x)))
851 (append
852 org-columns-summary-types
853 org-columns-summary-types-default))))
854 nil t (nth 3 spec)))
855 (org-string-nw-p
856 (read-string "Format: " (nth 4 spec))))))))
857 (if spec
858 (progn (setcar spec (car new))
859 (setcdr spec (cdr new)))
860 (push new (nthcdr (current-column) org-columns-current-fmt-compiled)))
861 (org-columns-store-format)
862 (org-columns-redo)))
864 (defun org-columns-delete ()
865 "Delete the column at point from columns view."
866 (interactive)
867 (let ((spec (nth (current-column) org-columns-current-fmt-compiled)))
868 (when (y-or-n-p (format "Are you sure you want to remove column %S? "
869 (nth 1 spec)))
870 (setq org-columns-current-fmt-compiled
871 (delq spec org-columns-current-fmt-compiled))
872 (org-columns-store-format)
873 ;; This may leave a now wrong value in a node property. However
874 ;; updating it may prove counter-intuitive. See comments in
875 ;; `org-columns-move-right' for details.
876 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
877 (when (>= (current-column) (length org-columns-current-fmt-compiled))
878 (backward-char)))))
880 (defun org-columns-edit-attributes ()
881 "Edit the attributes of the current column."
882 (interactive)
883 (org-columns-new (nth (current-column) org-columns-current-fmt-compiled)))
885 (defun org-columns-widen (arg)
886 "Make the column wider by ARG characters."
887 (interactive "p")
888 (let* ((n (current-column))
889 (entry (nth n org-columns-current-fmt-compiled))
890 (width (aref org-columns-current-maxwidths n)))
891 (setq width (max 1 (+ width arg)))
892 (setcar (nthcdr 2 entry) width)
893 (org-columns-store-format)
894 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))))
896 (defun org-columns-narrow (arg)
897 "Make the column narrower by ARG characters."
898 (interactive "p")
899 (org-columns-widen (- arg)))
901 (defun org-columns-move-right ()
902 "Swap this column with the one to the right."
903 (interactive)
904 (let* ((n (current-column))
905 (cell (nthcdr n org-columns-current-fmt-compiled))
907 (when (>= n (1- (length org-columns-current-fmt-compiled)))
908 (error "Cannot shift this column further to the right"))
909 (setq e (car cell))
910 (setcar cell (car (cdr cell)))
911 (setcdr cell (cons e (cdr (cdr cell))))
912 (org-columns-store-format)
913 ;; Do not compute again properties, since we're just moving
914 ;; columns around. It can put a property value a bit off when
915 ;; switching between an non-computed and a computed value for the
916 ;; same property, e.g. from "%A %A{+}" to "%A{+} %A".
918 ;; In this case, the value needs to be updated since the first
919 ;; column related to a property determines how its value is
920 ;; computed. However, (correctly) updating the value could be
921 ;; surprising, so we leave it as-is nonetheless.
922 (let ((org-columns-inhibit-recalculation t)) (org-columns-redo))
923 (forward-char 1)))
925 (defun org-columns-move-left ()
926 "Swap this column with the one to the left."
927 (interactive)
928 (let* ((n (current-column)))
929 (when (= n 0)
930 (error "Cannot shift this column further to the left"))
931 (backward-char 1)
932 (org-columns-move-right)
933 (backward-char 1)))
935 (defun org-columns-store-format ()
936 "Store the text version of the current columns format.
937 The format is stored either in the COLUMNS property of the node
938 starting the current column display, or in a #+COLUMNS line of
939 the current buffer."
940 (let ((fmt (org-columns-uncompile-format org-columns-current-fmt-compiled)))
941 (setq-local org-columns-current-fmt fmt)
942 (when (marker-position org-columns-top-level-marker)
943 (org-with-wide-buffer
944 (goto-char org-columns-top-level-marker)
945 (if (and (org-at-heading-p) (org-entry-get nil "COLUMNS"))
946 (org-entry-put nil "COLUMNS" fmt)
947 (goto-char (point-min))
948 (let ((case-fold-search t))
949 ;; Try to replace the first COLUMNS keyword available.
950 (catch :found
951 (while (re-search-forward "^[ \t]*#\\+COLUMNS:\\(.*\\)" nil t)
952 (let ((element (save-match-data (org-element-at-point))))
953 (when (and (eq (org-element-type element) 'keyword)
954 (equal (org-element-property :key element)
955 "COLUMNS"))
956 (replace-match (concat " " fmt) t t nil 1)
957 (throw :found nil))))
958 ;; No COLUMNS keyword in the buffer. Insert one at the
959 ;; beginning, right before the first heading, if any.
960 (goto-char (point-min))
961 (unless (org-at-heading-p t) (outline-next-heading))
962 (let ((inhibit-read-only t))
963 (insert-before-markers "#+COLUMNS: " fmt "\n"))))
964 (setq-local org-columns-default-format fmt))))))
966 (defun org-columns-update (property)
967 "Recompute PROPERTY, and update the columns display for it."
968 (org-columns-compute property)
969 (org-with-wide-buffer
970 (let ((p (upcase property)))
971 (dolist (ov org-columns-overlays)
972 (let ((key (overlay-get ov 'org-columns-key)))
973 (when (and key (equal key p) (overlay-start ov))
974 (goto-char (overlay-start ov))
975 (let* ((spec (nth (current-column) org-columns-current-fmt-compiled))
976 (value
977 (or (cdr (assoc spec
978 (get-text-property (line-beginning-position)
979 'org-summaries)))
980 (org-entry-get (point) key))))
981 (when value
982 (let ((displayed (org-columns--displayed-value spec value))
983 (format (overlay-get ov 'org-columns-format))
984 (width
985 (aref org-columns-current-maxwidths (current-column))))
986 (overlay-put ov 'org-columns-value value)
987 (overlay-put ov 'org-columns-value-modified displayed)
988 (overlay-put ov
989 'display
990 (org-columns--overlay-text
991 displayed format width property value)))))))))))
993 (defun org-columns-redo ()
994 "Construct the column display again."
995 (interactive)
996 (message "Recomputing columns...")
997 (org-with-wide-buffer
998 (when (marker-position org-columns-begin-marker)
999 (goto-char org-columns-begin-marker))
1000 (org-columns-remove-overlays)
1001 (if (derived-mode-p 'org-mode)
1002 ;; Since we already know the columns format, provide it instead
1003 ;; of computing again.
1004 (call-interactively #'org-columns org-columns-current-fmt)
1005 (org-agenda-redo)
1006 (call-interactively #'org-agenda-columns)))
1007 (message "Recomputing columns...done"))
1009 (defun org-columns-uncompile-format (compiled)
1010 "Turn the compiled columns format back into a string representation.
1011 COMPILED is an alist, as returned by
1012 `org-columns-compile-format', which see."
1013 (mapconcat
1014 (lambda (spec)
1015 (pcase spec
1016 (`(,prop ,title ,width ,op ,printf)
1017 (concat "%"
1018 (and width (number-to-string width))
1019 prop
1020 (and title (not (equal prop title)) (format "(%s)" title))
1021 (cond ((not op) nil)
1022 (printf (format "{%s;%s}" op printf))
1023 (t (format "{%s}" op)))))))
1024 compiled " "))
1026 (defun org-columns-compile-format (fmt)
1027 "Turn a column format string FMT into an alist of specifications.
1029 The alist has one entry for each column in the format. The elements of
1030 that list are:
1031 property the property name, as an upper-case string
1032 title the title field for the columns, as a string
1033 width the column width in characters, can be nil for automatic width
1034 operator the summary operator, as a string, or nil
1035 printf a printf format for computed values, as a string, or nil
1037 This function updates `org-columns-current-fmt-compiled'."
1038 (setq org-columns-current-fmt-compiled nil)
1039 (let ((start 0))
1040 (while (string-match
1041 "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\
1042 \\(?:{\\([^}]+\\)}\\)?\\s-*"
1043 fmt start)
1044 (setq start (match-end 0))
1045 (let* ((width (and (match-end 1) (string-to-number (match-string 1 fmt))))
1046 (prop (match-string-no-properties 2 fmt))
1047 (title (or (match-string-no-properties 3 fmt) prop))
1048 (operator (match-string-no-properties 4 fmt)))
1049 (push (if (not operator) (list (upcase prop) title width nil nil)
1050 (let (printf)
1051 (when (string-match ";" operator)
1052 (setq printf (substring operator (match-end 0)))
1053 (setq operator (substring operator 0 (match-beginning 0))))
1054 (list (upcase prop) title width operator printf)))
1055 org-columns-current-fmt-compiled)))
1056 (setq org-columns-current-fmt-compiled
1057 (nreverse org-columns-current-fmt-compiled))))
1060 ;;;; Column View Summary
1062 (defconst org-columns--duration-re
1063 (concat "[0-9.]+ *" (regexp-opt (mapcar #'car org-effort-durations)))
1064 "Regexp matching a duration.")
1066 (defun org-columns--time-to-seconds (s)
1067 "Turn time string S into a number of seconds.
1068 A time is expressed as HH:MM, HH:MM:SS, or with units defined in
1069 `org-effort-durations'. Plain numbers are considered as hours."
1070 (cond
1071 ((string-match "\\([0-9]+\\):\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?" s)
1072 (+ (* 3600 (string-to-number (match-string 1 s)))
1073 (* 60 (string-to-number (match-string 2 s)))
1074 (if (match-end 3) (string-to-number (match-string 3 s)) 0)))
1075 ((string-match-p org-columns--duration-re s)
1076 (* 60 (org-duration-string-to-minutes s)))
1077 (t (* 3600 (string-to-number s)))))
1079 (defun org-columns--age-to-seconds (s)
1080 "Turn age string S into a number of seconds.
1081 An age is either computed from a given time-stamp, or indicated
1082 as days/hours/minutes/seconds."
1083 (cond
1084 ((string-match-p org-ts-regexp s)
1085 (floor
1086 (- org-columns--time
1087 (float-time (apply #'encode-time (org-parse-time-string s))))))
1088 ;; Match own output for computations in upper levels.
1089 ((string-match "\\([0-9]+\\)d \\([0-9]+\\)h \\([0-9]+\\)m \\([0-9]+\\)s" s)
1090 (+ (* 86400 (string-to-number (match-string 1 s)))
1091 (* 3600 (string-to-number (match-string 2 s)))
1092 (* 60 (string-to-number (match-string 3 s)))
1093 (string-to-number (match-string 4 s))))
1094 (t (user-error "Invalid age: %S" s))))
1096 (defun org-columns--summary-apply-times (fun times)
1097 "Apply FUN to time values TIMES.
1098 If TIMES contains any time value expressed as a duration, return
1099 the result as a duration. If it contains any H:M:S, use that
1100 format instead. Otherwise, use H:M format."
1101 (let* ((hms-flag nil)
1102 (duration-flag nil)
1103 (seconds
1104 (apply fun
1105 (mapcar
1106 (lambda (time)
1107 (cond
1108 (duration-flag)
1109 ((string-match-p org-columns--duration-re time)
1110 (setq duration-flag t))
1111 (hms-flag)
1112 ((string-match-p "\\`[0-9]+:[0-9]+:[0-9]+\\'" time)
1113 (setq hms-flag t)))
1114 (org-columns--time-to-seconds time))
1115 times))))
1116 (cond (duration-flag (org-minutes-to-clocksum-string (/ seconds 60.0)))
1117 (hms-flag (format-seconds "%h:%.2m:%.2s" seconds))
1118 (t (format-seconds "%h:%.2m" seconds)))))
1120 (defun org-columns--compute-spec (spec &optional update)
1121 "Update tree according to SPEC.
1122 SPEC is a column format specification. When optional argument
1123 UPDATE is non-nil, summarized values can replace existing ones in
1124 properties drawers."
1125 (let* ((lmax (if (bound-and-true-p org-inlinetask-min-level)
1126 org-inlinetask-min-level
1127 29)) ;Hard-code deepest level.
1128 (lvals (make-vector (1+ lmax) nil))
1129 (level 0)
1130 (inminlevel lmax)
1131 (last-level lmax)
1132 (property (car spec))
1133 (printf (nth 4 spec))
1134 (summarize (org-columns--summarize (nth 3 spec))))
1135 (org-with-wide-buffer
1136 ;; Find the region to compute.
1137 (goto-char org-columns-top-level-marker)
1138 (goto-char (condition-case nil (org-end-of-subtree t) (error (point-max))))
1139 ;; Walk the tree from the back and do the computations.
1140 (while (re-search-backward
1141 org-outline-regexp-bol org-columns-top-level-marker t)
1142 (unless (or (= level 0) (eq level inminlevel))
1143 (setq last-level level))
1144 (setq level (org-reduced-level (org-outline-level)))
1145 (let* ((pos (match-beginning 0))
1146 (value (org-entry-get nil property))
1147 (value-set (org-string-nw-p value)))
1148 (cond
1149 ((< level last-level)
1150 ;; Collect values from lower levels and inline tasks here
1151 ;; and summarize them using SUMMARIZE. Store them in text
1152 ;; property `org-summaries', in alist whose key is SPEC.
1153 (let* ((summary
1154 (and summarize
1155 (let ((values (append (and (/= last-level inminlevel)
1156 (aref lvals last-level))
1157 (aref lvals inminlevel))))
1158 (and values (funcall summarize values printf))))))
1159 ;; Leaf values are not summaries: do not mark them.
1160 (when summary
1161 (let* ((summaries-alist (get-text-property pos 'org-summaries))
1162 (old (assoc spec summaries-alist)))
1163 (if old (setcdr old summary)
1164 (push (cons spec summary) summaries-alist)
1165 (org-with-silent-modifications
1166 (add-text-properties
1167 pos (1+ pos) (list 'org-summaries summaries-alist)))))
1168 ;; When PROPERTY exists in current node, even if empty,
1169 ;; but its value doesn't match the one computed, use
1170 ;; the latter instead.
1171 (when (and update value (not (equal value summary)))
1172 (org-entry-put (point) property summary)))
1173 ;; Add current to current level accumulator.
1174 (when (or summary value-set)
1175 (push (or summary value) (aref lvals level)))
1176 ;; Clear accumulators for deeper levels.
1177 (cl-loop for l from (1+ level) to lmax do (aset lvals l nil))))
1178 (value-set (push value (aref lvals level)))
1179 (t nil)))))))
1181 ;;;###autoload
1182 (defun org-columns-compute (property)
1183 "Summarize the values of PROPERTY hierarchically.
1184 Also update existing values for PROPERTY according to the first
1185 column specification."
1186 (interactive)
1187 (let ((main-flag t)
1188 (upcase-prop (upcase property)))
1189 (dolist (spec org-columns-current-fmt-compiled)
1190 (pcase spec
1191 (`(,(pred (equal upcase-prop)) . ,_)
1192 (org-columns--compute-spec spec main-flag)
1193 ;; Only the first summary can update the property value.
1194 (when main-flag (setq main-flag nil)))))))
1196 (defun org-columns-compute-all ()
1197 "Compute all columns that have operators defined."
1198 (org-with-silent-modifications
1199 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1200 (let ((org-columns--time (float-time (current-time)))
1201 seen)
1202 (dolist (spec org-columns-current-fmt-compiled)
1203 (let ((property (car spec)))
1204 ;; Property value is updated only the first time a given
1205 ;; property is encountered.
1206 (org-columns--compute-spec spec (not (member property seen)))
1207 (push property seen)))))
1209 (defun org-columns--summary-sum (values printf)
1210 "Compute the sum of VALUES.
1211 When PRINTF is non-nil, use it to format the result."
1212 (format (or printf "%s") (apply #'+ (mapcar #'string-to-number values))))
1214 (defun org-columns--summary-currencies (values _)
1215 "Compute the sum of VALUES, with two decimals."
1216 (format "%.2f" (apply #'+ (mapcar #'string-to-number values))))
1218 (defun org-columns--summary-checkbox (check-boxes _)
1219 "Summarize CHECK-BOXES with a check-box."
1220 (let ((done (cl-count "[X]" check-boxes :test #'equal))
1221 (all (length check-boxes)))
1222 (cond ((= done all) "[X]")
1223 ((> done 0) "[-]")
1224 (t "[ ]"))))
1226 (defun org-columns--summary-checkbox-count (check-boxes _)
1227 "Summarize CHECK-BOXES with a check-box cookie."
1228 (format "[%d/%d]"
1229 (cl-count "[X]" check-boxes :test #'equal)
1230 (length check-boxes)))
1232 (defun org-columns--summary-checkbox-percent (check-boxes _)
1233 "Summarize CHECK-BOXES with a check-box percent."
1234 (format "[%d%%]"
1235 (round (* 100.0 (cl-count "[X]" check-boxes :test #'equal))
1236 (float (length check-boxes)))))
1238 (defun org-columns--summary-min (values printf)
1239 "Compute the minimum of VALUES.
1240 When PRINTF is non-nil, use it to format the result."
1241 (format (or printf "%s")
1242 (apply #'min (mapcar #'string-to-number values))))
1244 (defun org-columns--summary-max (values printf)
1245 "Compute the maximum of VALUES.
1246 When PRINTF is non-nil, use it to format the result."
1247 (format (or printf "%s")
1248 (apply #'max (mapcar #'string-to-number values))))
1250 (defun org-columns--summary-mean (values printf)
1251 "Compute the mean of VALUES.
1252 When PRINTF is non-nil, use it to format the result."
1253 (format (or printf "%s")
1254 (/ (apply #'+ (mapcar #'string-to-number values))
1255 (float (length values)))))
1257 (defun org-columns--summary-sum-times (times _)
1258 "Sum TIMES."
1259 (org-columns--summary-apply-times #'+ times))
1261 (defun org-columns--summary-min-time (times _)
1262 "Compute the minimum time among TIMES."
1263 (org-columns--summary-apply-times #'min times))
1265 (defun org-columns--summary-max-time (times _)
1266 "Compute the maximum time among TIMES."
1267 (org-columns--summary-apply-times #'max times))
1269 (defun org-columns--summary-mean-time (times _)
1270 "Compute the mean time among TIMES."
1271 (org-columns--summary-apply-times
1272 (lambda (&rest values) (/ (apply #'+ values) (float (length values))))
1273 times))
1275 (defun org-columns--summary-min-age (ages _)
1276 "Compute the minimum time among AGES."
1277 (format-seconds
1278 "%dd %.2hh %mm %ss"
1279 (apply #'min (mapcar #'org-columns--age-to-seconds ages))))
1281 (defun org-columns--summary-max-age (ages _)
1282 "Compute the maximum time among AGES."
1283 (format-seconds
1284 "%dd %.2hh %mm %ss"
1285 (apply #'max (mapcar #'org-columns--age-to-seconds ages))))
1287 (defun org-columns--summary-mean-age (ages _)
1288 "Compute the minimum time among AGES."
1289 (format-seconds
1290 "%dd %.2hh %mm %ss"
1291 (/ (apply #'+ (mapcar #'org-columns--age-to-seconds ages))
1292 (float (length ages)))))
1294 (defun org-columns--summary-estimate (estimates printf)
1295 "Combine a list of estimates, using mean and variance.
1296 The mean and variance of the result will be the sum of the means
1297 and variances (respectively) of the individual estimates."
1298 (let ((mean 0)
1299 (var 0))
1300 (dolist (e estimates)
1301 (pcase (mapcar #'string-to-number (split-string e "-"))
1302 (`(,low ,high)
1303 (let ((m (/ (+ low high) 2.0)))
1304 (cl-incf mean m)
1305 (cl-incf var (- (/ (+ (* low low) (* high high)) 2.0) (* m m)))))
1306 (`(,value) (cl-incf mean value))))
1307 (let ((sd (sqrt var)))
1308 (format "%s-%s"
1309 (format (or printf "%.0f") (- mean sd))
1310 (format (or printf "%.0f") (+ mean sd))))))
1314 ;;; Dynamic block for Column view
1316 (defun org-columns--capture-view (maxlevel skip-empty format local)
1317 "Get the column view of the current buffer.
1319 MAXLEVEL sets the level limit. SKIP-EMPTY tells whether to skip
1320 empty rows, an empty row being one where all the column view
1321 specifiers but ITEM are empty. FORMAT is a format string for
1322 columns, or nil. When LOCAL is non-nil, only capture headings in
1323 current subtree.
1325 This function returns a list containing the title row and all
1326 other rows. Each row is a list of fields, as strings, or
1327 `hline'."
1328 (org-columns (not local) format)
1329 (goto-char org-columns-top-level-marker)
1330 (let ((columns (length org-columns-current-fmt-compiled))
1331 (has-item (assoc "ITEM" org-columns-current-fmt-compiled))
1332 table)
1333 (org-map-entries
1334 (lambda ()
1335 (when (get-char-property (point) 'org-columns-key)
1336 (let (row)
1337 (dotimes (i columns)
1338 (let* ((col (+ (line-beginning-position) i))
1339 (p (get-char-property col 'org-columns-key)))
1340 (push (org-quote-vert
1341 (get-char-property col
1342 (if (string= p "ITEM")
1343 'org-columns-value
1344 'org-columns-value-modified)))
1345 row)))
1346 (unless (and skip-empty
1347 (let ((r (delete-dups (remove "" row))))
1348 (or (null r) (and has-item (= (length r) 1)))))
1349 (push (cons (org-reduced-level (org-current-level)) (nreverse row))
1350 table)))))
1351 (and maxlevel (format "LEVEL<=%d" maxlevel))
1352 (and local 'tree)
1353 'archive 'comment)
1354 (org-columns-quit)
1355 ;; Add column titles and a horizontal rule in front of the table.
1356 (cons (mapcar #'cadr org-columns-current-fmt-compiled)
1357 (cons 'hline (nreverse table)))))
1359 (defun org-columns--clean-item (item)
1360 "Remove sensitive contents from string ITEM.
1361 This includes objects that may not be duplicated within
1362 a document, e.g., a target, or those forbidden in tables, e.g.,
1363 an inline src-block."
1364 (let ((data (org-element-parse-secondary-string
1365 item (org-element-restriction 'headline))))
1366 (org-element-map data
1367 '(footnote-reference inline-babel-call inline-src-block target
1368 radio-target statistics-cookie)
1369 #'org-element-extract-element)
1370 (org-no-properties (org-element-interpret-data data))))
1372 ;;;###autoload
1373 (defun org-dblock-write:columnview (params)
1374 "Write the column view table.
1375 PARAMS is a property list of parameters:
1377 :id the :ID: property of the entry where the columns view
1378 should be built. When the symbol `local', call locally.
1379 When `global' call column view with the cursor at the beginning
1380 of the buffer (usually this means that the whole buffer switches
1381 to column view). When \"file:path/to/file.org\", invoke column
1382 view at the start of that file. Otherwise, the ID is located
1383 using `org-id-find'.
1384 :hlines When t, insert a hline before each item. When a number, insert
1385 a hline before each level <= that number.
1386 :indent When non-nil, indent each ITEM field according to its level.
1387 :vlines When t, make each column a colgroup to enforce vertical lines.
1388 :maxlevel When set to a number, don't capture headlines below this level.
1389 :skip-empty-rows
1390 When t, skip rows where all specifiers other than ITEM are empty.
1391 :width apply widths specified in columns format using <N> specifiers.
1392 :format When non-nil, specify the column view format to use."
1393 (let ((table
1394 (let ((id (plist-get params :id))
1395 view-file view-pos)
1396 (pcase id
1397 (`global nil)
1398 ((or `local `nil) (setq view-pos (point)))
1399 ((and (let id-string (format "%s" id))
1400 (guard (string-match "^file:\\(.*\\)" id-string)))
1401 (setq view-file (match-string-no-properties 1 id-string))
1402 (unless (file-exists-p view-file)
1403 (user-error "No such file: %S" id-string)))
1404 ((and (let idpos (org-find-entry-with-id id)) (guard idpos))
1405 (setq view-pos idpos))
1406 ((let `(,filename . ,position) (org-id-find id))
1407 (setq view-file filename)
1408 (setq view-pos position))
1409 (_ (user-error "Cannot find entry with :ID: %s" id)))
1410 (with-current-buffer (if view-file (get-file-buffer view-file)
1411 (current-buffer))
1412 (org-with-wide-buffer
1413 (when view-pos (goto-char view-pos))
1414 (org-columns--capture-view (plist-get params :maxlevel)
1415 (plist-get params :skip-empty-rows)
1416 (plist-get params :format)
1417 view-pos))))))
1418 (when table
1419 ;; Prune level information from the table. Also normalize
1420 ;; headings: remove stars, add indentation entities, if
1421 ;; required, and possibly precede some of them with a horizontal
1422 ;; rule.
1423 (let ((item-index
1424 (let ((p (assoc "ITEM" org-columns-current-fmt-compiled)))
1425 (and p (cl-position p
1426 org-columns-current-fmt-compiled
1427 :test #'equal))))
1428 (hlines (plist-get params :hlines))
1429 (indent (plist-get params :indent))
1430 new-table)
1431 ;; Copy header and first rule.
1432 (push (pop table) new-table)
1433 (push (pop table) new-table)
1434 (dolist (row table (setq table (nreverse new-table)))
1435 (let ((level (car row)))
1436 (when (and (not (eq (car new-table) 'hline))
1437 (or (eq hlines t)
1438 (and (numberp hlines) (<= level hlines))))
1439 (push 'hline new-table))
1440 (when item-index
1441 (let ((item (org-columns--clean-item (nth item-index (cdr row)))))
1442 (setf (nth item-index (cdr row))
1443 (if (and indent (> level 1))
1444 (concat "\\_" (make-string (* 2 (1- level)) ?\s) item)
1445 item))))
1446 (push (cdr row) new-table))))
1447 (when (plist-get params :width)
1448 (setq table
1449 (append table
1450 (list
1451 (mapcar (lambda (spec)
1452 (let ((w (nth 2 spec)))
1453 (if w (format "<%d>" (max 3 w)) "")))
1454 org-columns-current-fmt-compiled)))))
1455 (when (plist-get params :vlines)
1456 (setq table
1457 (let ((size (length org-columns-current-fmt-compiled)))
1458 (append (mapcar (lambda (x) (if (eq 'hline x) x (cons "" x)))
1459 table)
1460 (list (cons "/" (make-list size "<>")))))))
1461 (let ((content-lines (org-split-string (plist-get params :content) "\n"))
1462 recalc)
1463 ;; Insert affiliated keywords before the table.
1464 (when content-lines
1465 (while (string-match-p "\\`[ \t]*#\\+" (car content-lines))
1466 (insert (pop content-lines) "\n")))
1467 (save-excursion
1468 ;; Insert table at point.
1469 (insert
1470 (mapconcat (lambda (row)
1471 (if (eq row 'hline) "|-|"
1472 (format "|%s|" (mapconcat #'identity row "|"))))
1473 table
1474 "\n"))
1475 ;; Insert TBLFM lines following table.
1476 (let ((case-fold-search t))
1477 (dolist (line content-lines)
1478 (when (string-match-p "\\`[ \t]*#\\+TBLFM:" line)
1479 (insert "\n" line)
1480 (unless recalc (setq recalc t))))))
1481 (when recalc (org-table-recalculate 'all t))
1482 (org-table-align)))))
1484 ;;;###autoload
1485 (defun org-columns-insert-dblock ()
1486 "Create a dynamic block capturing a column view table."
1487 (interactive)
1488 (let ((id (completing-read
1489 "Capture columns (local, global, entry with :ID: property) [local]: "
1490 (append '(("global") ("local"))
1491 (mapcar #'list (org-property-values "ID"))))))
1492 (org-create-dblock
1493 (list :name "columnview"
1494 :hlines 1
1495 :id (cond ((string= id "global") 'global)
1496 ((member id '("" "local")) 'local)
1497 (id)))))
1498 (org-update-dblock))
1502 ;;; Column view in the agenda
1504 ;;;###autoload
1505 (defun org-agenda-columns ()
1506 "Turn on or update column view in the agenda."
1507 (interactive)
1508 (org-columns-remove-overlays)
1509 (move-marker org-columns-begin-marker (point))
1510 (let ((org-columns--time (float-time (current-time)))
1511 (fmt
1512 (cond
1513 ((bound-and-true-p org-agenda-overriding-columns-format))
1514 ((let ((m (org-get-at-bol 'org-hd-marker)))
1515 (and m
1516 (or (org-entry-get m "COLUMNS" t)
1517 (with-current-buffer (marker-buffer m)
1518 org-columns-default-format)))))
1519 ((and (local-variable-p 'org-columns-current-fmt)
1520 org-columns-current-fmt))
1521 ((let ((m (next-single-property-change (point-min) 'org-hd-marker)))
1522 (and m
1523 (let ((m (get-text-property m 'org-hd-marker)))
1524 (or (org-entry-get m "COLUMNS" t)
1525 (with-current-buffer (marker-buffer m)
1526 org-columns-default-format))))))
1527 (t org-columns-default-format))))
1528 (setq-local org-columns-current-fmt fmt)
1529 (org-columns-compile-format fmt)
1530 (when org-agenda-columns-compute-summary-properties
1531 (org-agenda-colview-compute org-columns-current-fmt-compiled))
1532 (save-excursion
1533 ;; Collect properties for each headline in current view.
1534 (goto-char (point-min))
1535 (let (cache)
1536 (while (not (eobp))
1537 (let ((m (or (org-get-at-bol 'org-hd-marker)
1538 (org-get-at-bol 'org-marker))))
1539 (when m
1540 (push (cons (line-beginning-position)
1541 (org-with-point-at m
1542 (org-columns--collect-values 'agenda)))
1543 cache)))
1544 (forward-line))
1545 (when cache
1546 (org-columns--set-widths cache)
1547 (org-columns--display-here-title)
1548 (when (setq-local org-columns-flyspell-was-active
1549 (bound-and-true-p flyspell-mode))
1550 (flyspell-mode 0))
1551 (dolist (entry cache)
1552 (goto-char (car entry))
1553 (org-columns--display-here (cdr entry)))
1554 (when org-agenda-columns-show-summaries
1555 (org-agenda-colview-summarize cache)))))))
1557 (defun org-agenda-colview-summarize (cache)
1558 "Summarize the summarizable columns in column view in the agenda.
1559 This will add overlays to the date lines, to show the summary for each day."
1560 (let ((fmt (mapcar
1561 (lambda (spec)
1562 (pcase spec
1563 (`(,property ,title ,width . ,_)
1564 (if (member property '("CLOCKSUM" "CLOCKSUM_T"))
1565 (list property title width ":" nil)
1566 spec))))
1567 org-columns-current-fmt-compiled))
1568 entries)
1569 ;; Ensure there's at least one summation column.
1570 (when (cl-some (lambda (spec) (nth 3 spec)) fmt)
1571 (goto-char (point-max))
1572 (while (not (bobp))
1573 (when (or (get-text-property (point) 'org-date-line)
1574 (eq (get-text-property (point) 'face)
1575 'org-agenda-structure))
1576 ;; OK, this is a date line that should be used.
1577 (let (rest)
1578 (dolist (c cache (setq cache rest))
1579 (if (> (car c) (point))
1580 (push c entries)
1581 (push c rest))))
1582 ;; Now ENTRIES contains entries below the current one.
1583 ;; CACHE is the rest. Compute the summaries for the
1584 ;; properties we want, set nil properties for the rest.
1585 (when (setq entries (mapcar 'cdr entries))
1586 (org-columns--display-here
1587 (mapcar
1588 (lambda (spec)
1589 (pcase spec
1590 (`("ITEM" . ,_)
1591 ;; Replace ITEM with current date. Preserve
1592 ;; properties for fontification.
1593 (let ((date (buffer-substring
1594 (line-beginning-position)
1595 (line-end-position))))
1596 (list spec date date)))
1597 (`(,_ ,_ ,_ nil ,_) (list spec "" ""))
1598 (`(,_ ,_ ,_ ,operator ,printf)
1599 (let* ((summarize (org-columns--summarize operator))
1600 (values
1601 ;; Use real values for summary, not those
1602 ;; prepared for display.
1603 (delq nil
1604 (mapcar
1605 (lambda (e)
1606 (org-string-nw-p (nth 1 (assoc spec e))))
1607 entries)))
1608 (final (if values (funcall summarize values printf)
1609 "")))
1610 (unless (equal final "")
1611 (put-text-property 0 (length final) 'face 'bold final))
1612 (list spec final final)))))
1613 fmt)
1614 'dateline)
1615 (setq-local org-agenda-columns-active t)))
1616 (forward-line -1)))))
1618 (defun org-agenda-colview-compute (fmt)
1619 "Compute the relevant columns in the contributing source buffers."
1620 (let ((files org-agenda-contributing-files)
1621 (org-columns-begin-marker (make-marker))
1622 (org-columns-top-level-marker (make-marker)))
1623 (dolist (f files)
1624 (let ((b (find-buffer-visiting f)))
1625 (with-current-buffer (or (buffer-base-buffer b) b)
1626 (org-with-wide-buffer
1627 (org-with-silent-modifications
1628 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1629 (goto-char (point-min))
1630 (org-columns-get-format-and-top-level)
1631 (dolist (spec fmt)
1632 (let ((prop (car spec)))
1633 (cond
1634 ((equal prop "CLOCKSUM") (org-clock-sum))
1635 ((equal prop "CLOCKSUM_T") (org-clock-sum-today))
1636 ((and (nth 3 spec)
1637 (let ((a (assoc prop org-columns-current-fmt-compiled)))
1638 (equal (nth 3 a) (nth 3 spec))))
1639 (org-columns-compute prop)))))))))))
1642 (provide 'org-colview)
1644 ;;; org-colview.el ends here