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