org-colview: Silence byte-compiler
[org-mode.git] / lisp / org-colview.el
blob850ac006903b85eed885a9f8827877b7efe7f22e
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) 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 "26.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.
226 SPEC is a column format specification as stored in
227 `org-columns-current-fmt-compiled'. VALUE is the real value to
228 display, as a string."
229 (or (and (functionp org-columns-modify-value-for-display-function)
230 (funcall org-columns-modify-value-for-display-function
231 (nth 1 spec) ;column name
232 value))
233 (pcase spec
234 (`("ITEM" . ,_)
235 (concat (make-string (1- (org-current-level))
236 (if org-hide-leading-stars ?\s ?*))
237 "* "
238 (org-columns-compact-links value)))
239 (`(,_ ,_ ,_ ,_ nil) value)
240 ;; If PRINTF is set, assume we are displaying a number and
241 ;; obey to the format string.
242 (`(,_ ,_ ,_ ,_ ,printf) (format printf (string-to-number value)))
243 (_ (error "Invalid column specification format: %S" spec)))))
245 (defun org-columns--collect-values (&optional compiled-fmt)
246 "Collect values for columns on the current line.
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 is set in the current buffer. However, it is
253 possible to override it with optional argument COMPILED-FMT."
254 (let ((summaries (get-text-property (point) 'org-summaries)))
255 (mapcar
256 (lambda (spec)
257 (pcase spec
258 (`(,p . ,_)
259 (let* ((v (or (cdr (assoc spec summaries))
260 (org-entry-get (point) p 'selective t)
261 (and compiled-fmt ;assume `org-agenda-columns'
262 ;; Effort property is not defined. Try
263 ;; to use appointment duration.
264 org-agenda-columns-add-appointments-to-effort-sum
265 (string= p (upcase org-effort-property))
266 (get-text-property (point) 'duration)
267 (propertize (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 (or compiled-fmt 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-p org-columns--duration-re s)
1072 (* 60 (org-duration-string-to-minutes s)))
1073 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?\\'" s)
1074 (+ (* 3600 (string-to-number (match-string 1 s)))
1075 (* 60 (string-to-number (match-string 2 s)))
1076 (if (match-end 3) (string-to-number (match-string 3 s)) 0)))
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.
1172 ;; Ignore leading or trailing white spaces that might
1173 ;; have been introduced in summary, since those are not
1174 ;; significant in properties value.
1175 (let ((new-value (org-trim summary)))
1176 (when (and update value (not (equal value new-value)))
1177 (org-entry-put (point) property new-value))))
1178 ;; Add current to current level accumulator.
1179 (when (or summary value-set)
1180 (push (or summary value) (aref lvals level)))
1181 ;; Clear accumulators for deeper levels.
1182 (cl-loop for l from (1+ level) to lmax do (aset lvals l nil))))
1183 (value-set (push value (aref lvals level)))
1184 (t nil)))))))
1186 ;;;###autoload
1187 (defun org-columns-compute (property)
1188 "Summarize the values of PROPERTY hierarchically.
1189 Also update existing values for PROPERTY according to the first
1190 column specification."
1191 (interactive)
1192 (let ((main-flag t)
1193 (upcase-prop (upcase property)))
1194 (dolist (spec org-columns-current-fmt-compiled)
1195 (pcase spec
1196 (`(,(pred (equal upcase-prop)) . ,_)
1197 (org-columns--compute-spec spec main-flag)
1198 ;; Only the first summary can update the property value.
1199 (when main-flag (setq main-flag nil)))))))
1201 (defun org-columns-compute-all ()
1202 "Compute all columns that have operators defined."
1203 (org-with-silent-modifications
1204 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1205 (let ((org-columns--time (float-time (current-time)))
1206 seen)
1207 (dolist (spec org-columns-current-fmt-compiled)
1208 (let ((property (car spec)))
1209 ;; Property value is updated only the first time a given
1210 ;; property is encountered.
1211 (org-columns--compute-spec spec (not (member property seen)))
1212 (push property seen)))))
1214 (defun org-columns--summary-sum (values printf)
1215 "Compute the sum of VALUES.
1216 When PRINTF is non-nil, use it to format the result."
1217 (format (or printf "%s") (apply #'+ (mapcar #'string-to-number values))))
1219 (defun org-columns--summary-currencies (values _)
1220 "Compute the sum of VALUES, with two decimals."
1221 (format "%.2f" (apply #'+ (mapcar #'string-to-number values))))
1223 (defun org-columns--summary-checkbox (check-boxes _)
1224 "Summarize CHECK-BOXES with a check-box."
1225 (let ((done (cl-count "[X]" check-boxes :test #'equal))
1226 (all (length check-boxes)))
1227 (cond ((= done all) "[X]")
1228 ((> done 0) "[-]")
1229 (t "[ ]"))))
1231 (defun org-columns--summary-checkbox-count (check-boxes _)
1232 "Summarize CHECK-BOXES with a check-box cookie."
1233 (format "[%d/%d]"
1234 (cl-count-if (lambda (b) (or (equal b "[X]")
1235 (string-match-p "\\[\\([1-9]\\)/\\1\\]" b)))
1236 check-boxes)
1237 (length check-boxes)))
1239 (defun org-columns--summary-checkbox-percent (check-boxes _)
1240 "Summarize CHECK-BOXES with a check-box percent."
1241 (format "[%d%%]"
1242 (round (* 100.0 (cl-count-if (lambda (b) (member b '("[X]" "[100%]")))
1243 check-boxes))
1244 (length check-boxes))))
1246 (defun org-columns--summary-min (values printf)
1247 "Compute the minimum of VALUES.
1248 When PRINTF is non-nil, use it to format the result."
1249 (format (or printf "%s")
1250 (apply #'min (mapcar #'string-to-number values))))
1252 (defun org-columns--summary-max (values printf)
1253 "Compute the maximum of VALUES.
1254 When PRINTF is non-nil, use it to format the result."
1255 (format (or printf "%s")
1256 (apply #'max (mapcar #'string-to-number values))))
1258 (defun org-columns--summary-mean (values printf)
1259 "Compute the mean of VALUES.
1260 When PRINTF is non-nil, use it to format the result."
1261 (format (or printf "%s")
1262 (/ (apply #'+ (mapcar #'string-to-number values))
1263 (float (length values)))))
1265 (defun org-columns--summary-sum-times (times _)
1266 "Sum TIMES."
1267 (org-columns--summary-apply-times #'+ times))
1269 (defun org-columns--summary-min-time (times _)
1270 "Compute the minimum time among TIMES."
1271 (org-columns--summary-apply-times #'min times))
1273 (defun org-columns--summary-max-time (times _)
1274 "Compute the maximum time among TIMES."
1275 (org-columns--summary-apply-times #'max times))
1277 (defun org-columns--summary-mean-time (times _)
1278 "Compute the mean time among TIMES."
1279 (org-columns--summary-apply-times
1280 (lambda (&rest values) (/ (apply #'+ values) (float (length values))))
1281 times))
1283 (defun org-columns--summary-min-age (ages _)
1284 "Compute the minimum time among AGES."
1285 (format-seconds
1286 "%dd %.2hh %mm %ss"
1287 (apply #'min (mapcar #'org-columns--age-to-seconds ages))))
1289 (defun org-columns--summary-max-age (ages _)
1290 "Compute the maximum time among AGES."
1291 (format-seconds
1292 "%dd %.2hh %mm %ss"
1293 (apply #'max (mapcar #'org-columns--age-to-seconds ages))))
1295 (defun org-columns--summary-mean-age (ages _)
1296 "Compute the minimum time among AGES."
1297 (format-seconds
1298 "%dd %.2hh %mm %ss"
1299 (/ (apply #'+ (mapcar #'org-columns--age-to-seconds ages))
1300 (float (length ages)))))
1302 (defun org-columns--summary-estimate (estimates _)
1303 "Combine a list of estimates, using mean and variance.
1304 The mean and variance of the result will be the sum of the means
1305 and variances (respectively) of the individual estimates."
1306 (let ((mean 0)
1307 (var 0))
1308 (dolist (e estimates)
1309 (pcase (mapcar #'string-to-number (split-string e "-"))
1310 (`(,low ,high)
1311 (let ((m (/ (+ low high) 2.0)))
1312 (cl-incf mean m)
1313 (cl-incf var (- (/ (+ (* low low) (* high high)) 2.0) (* m m)))))
1314 (`(,value) (cl-incf mean value))))
1315 (let ((sd (sqrt var)))
1316 (format "%s-%s"
1317 (format "%.0f" (- mean sd))
1318 (format "%.0f" (+ mean sd))))))
1322 ;;; Dynamic block for Column view
1324 (defun org-columns--capture-view (maxlevel skip-empty format local)
1325 "Get the column view of the current buffer.
1327 MAXLEVEL sets the level limit. SKIP-EMPTY tells whether to skip
1328 empty rows, an empty row being one where all the column view
1329 specifiers but ITEM are empty. FORMAT is a format string for
1330 columns, or nil. When LOCAL is non-nil, only capture headings in
1331 current subtree.
1333 This function returns a list containing the title row and all
1334 other rows. Each row is a list of fields, as strings, or
1335 `hline'."
1336 (org-columns (not local) format)
1337 (goto-char org-columns-top-level-marker)
1338 (let ((columns (length org-columns-current-fmt-compiled))
1339 (has-item (assoc "ITEM" org-columns-current-fmt-compiled))
1340 table)
1341 (org-map-entries
1342 (lambda ()
1343 (when (get-char-property (point) 'org-columns-key)
1344 (let (row)
1345 (dotimes (i columns)
1346 (let* ((col (+ (line-beginning-position) i))
1347 (p (get-char-property col 'org-columns-key)))
1348 (push (org-quote-vert
1349 (get-char-property col
1350 (if (string= p "ITEM")
1351 'org-columns-value
1352 'org-columns-value-modified)))
1353 row)))
1354 (unless (and skip-empty
1355 (let ((r (delete-dups (remove "" row))))
1356 (or (null r) (and has-item (= (length r) 1)))))
1357 (push (cons (org-reduced-level (org-current-level)) (nreverse row))
1358 table)))))
1359 (and maxlevel (format "LEVEL<=%d" maxlevel))
1360 (and local 'tree)
1361 'archive 'comment)
1362 (org-columns-quit)
1363 ;; Add column titles and a horizontal rule in front of the table.
1364 (cons (mapcar #'cadr org-columns-current-fmt-compiled)
1365 (cons 'hline (nreverse table)))))
1367 (defun org-columns--clean-item (item)
1368 "Remove sensitive contents from string ITEM.
1369 This includes objects that may not be duplicated within
1370 a document, e.g., a target, or those forbidden in tables, e.g.,
1371 an inline src-block."
1372 (let ((data (org-element-parse-secondary-string
1373 item (org-element-restriction 'headline))))
1374 (org-element-map data
1375 '(footnote-reference inline-babel-call inline-src-block target
1376 radio-target statistics-cookie)
1377 #'org-element-extract-element)
1378 (org-no-properties (org-element-interpret-data data))))
1380 ;;;###autoload
1381 (defun org-dblock-write:columnview (params)
1382 "Write the column view table.
1383 PARAMS is a property list of parameters:
1385 :id the :ID: property of the entry where the columns view
1386 should be built. When the symbol `local', call locally.
1387 When `global' call column view with the cursor at the beginning
1388 of the buffer (usually this means that the whole buffer switches
1389 to column view). When \"file:path/to/file.org\", invoke column
1390 view at the start of that file. Otherwise, the ID is located
1391 using `org-id-find'.
1392 :hlines When t, insert a hline before each item. When a number, insert
1393 a hline before each level <= that number.
1394 :indent When non-nil, indent each ITEM field according to its level.
1395 :vlines When t, make each column a colgroup to enforce vertical lines.
1396 :maxlevel When set to a number, don't capture headlines below this level.
1397 :skip-empty-rows
1398 When t, skip rows where all specifiers other than ITEM are empty.
1399 :width apply widths specified in columns format using <N> specifiers.
1400 :format When non-nil, specify the column view format to use."
1401 (let ((table
1402 (let ((id (plist-get params :id))
1403 view-file view-pos)
1404 (pcase id
1405 (`global nil)
1406 ((or `local `nil) (setq view-pos (point)))
1407 ((and (let id-string (format "%s" id))
1408 (guard (string-match "^file:\\(.*\\)" id-string)))
1409 (setq view-file (match-string-no-properties 1 id-string))
1410 (unless (file-exists-p view-file)
1411 (user-error "No such file: %S" id-string)))
1412 ((and (let idpos (org-find-entry-with-id id)) (guard idpos))
1413 (setq view-pos idpos))
1414 ((let `(,filename . ,position) (org-id-find id))
1415 (setq view-file filename)
1416 (setq view-pos position))
1417 (_ (user-error "Cannot find entry with :ID: %s" id)))
1418 (with-current-buffer (if view-file (get-file-buffer view-file)
1419 (current-buffer))
1420 (org-with-wide-buffer
1421 (when view-pos (goto-char view-pos))
1422 (org-columns--capture-view (plist-get params :maxlevel)
1423 (plist-get params :skip-empty-rows)
1424 (plist-get params :format)
1425 view-pos))))))
1426 (when table
1427 ;; Prune level information from the table. Also normalize
1428 ;; headings: remove stars, add indentation entities, if
1429 ;; required, and possibly precede some of them with a horizontal
1430 ;; rule.
1431 (let ((item-index
1432 (let ((p (assoc "ITEM" org-columns-current-fmt-compiled)))
1433 (and p (cl-position p
1434 org-columns-current-fmt-compiled
1435 :test #'equal))))
1436 (hlines (plist-get params :hlines))
1437 (indent (plist-get params :indent))
1438 new-table)
1439 ;; Copy header and first rule.
1440 (push (pop table) new-table)
1441 (push (pop table) new-table)
1442 (dolist (row table (setq table (nreverse new-table)))
1443 (let ((level (car row)))
1444 (when (and (not (eq (car new-table) 'hline))
1445 (or (eq hlines t)
1446 (and (numberp hlines) (<= level hlines))))
1447 (push 'hline new-table))
1448 (when item-index
1449 (let ((item (org-columns--clean-item (nth item-index (cdr row)))))
1450 (setf (nth item-index (cdr row))
1451 (if (and indent (> level 1))
1452 (concat "\\_" (make-string (* 2 (1- level)) ?\s) item)
1453 item))))
1454 (push (cdr row) new-table))))
1455 (when (plist-get params :width)
1456 (setq table
1457 (append table
1458 (list
1459 (mapcar (lambda (spec)
1460 (let ((w (nth 2 spec)))
1461 (if w (format "<%d>" (max 3 w)) "")))
1462 org-columns-current-fmt-compiled)))))
1463 (when (plist-get params :vlines)
1464 (setq table
1465 (let ((size (length org-columns-current-fmt-compiled)))
1466 (append (mapcar (lambda (x) (if (eq 'hline x) x (cons "" x)))
1467 table)
1468 (list (cons "/" (make-list size "<>")))))))
1469 (let ((content-lines (org-split-string (plist-get params :content) "\n"))
1470 recalc)
1471 ;; Insert affiliated keywords before the table.
1472 (when content-lines
1473 (while (string-match-p "\\`[ \t]*#\\+" (car content-lines))
1474 (insert (pop content-lines) "\n")))
1475 (save-excursion
1476 ;; Insert table at point.
1477 (insert
1478 (mapconcat (lambda (row)
1479 (if (eq row 'hline) "|-|"
1480 (format "|%s|" (mapconcat #'identity row "|"))))
1481 table
1482 "\n"))
1483 ;; Insert TBLFM lines following table.
1484 (let ((case-fold-search t))
1485 (dolist (line content-lines)
1486 (when (string-match-p "\\`[ \t]*#\\+TBLFM:" line)
1487 (insert "\n" line)
1488 (unless recalc (setq recalc t))))))
1489 (when recalc (org-table-recalculate 'all t))
1490 (org-table-align)))))
1492 ;;;###autoload
1493 (defun org-columns-insert-dblock ()
1494 "Create a dynamic block capturing a column view table."
1495 (interactive)
1496 (let ((id (completing-read
1497 "Capture columns (local, global, entry with :ID: property) [local]: "
1498 (append '(("global") ("local"))
1499 (mapcar #'list (org-property-values "ID"))))))
1500 (org-create-dblock
1501 (list :name "columnview"
1502 :hlines 1
1503 :id (cond ((string= id "global") 'global)
1504 ((member id '("" "local")) 'local)
1505 (id)))))
1506 (org-update-dblock))
1510 ;;; Column view in the agenda
1512 ;;;###autoload
1513 (defun org-agenda-columns ()
1514 "Turn on or update column view in the agenda."
1515 (interactive)
1516 (org-columns-remove-overlays)
1517 (move-marker org-columns-begin-marker (point))
1518 (let* ((org-columns--time (float-time (current-time)))
1519 (fmt
1520 (cond
1521 ((bound-and-true-p org-agenda-overriding-columns-format))
1522 ((let ((m (org-get-at-bol 'org-hd-marker)))
1523 (and m
1524 (or (org-entry-get m "COLUMNS" t)
1525 (with-current-buffer (marker-buffer m)
1526 org-columns-default-format)))))
1527 ((and (local-variable-p 'org-columns-current-fmt)
1528 org-columns-current-fmt))
1529 ((let ((m (next-single-property-change (point-min) 'org-hd-marker)))
1530 (and m
1531 (let ((m (get-text-property m 'org-hd-marker)))
1532 (or (org-entry-get m "COLUMNS" t)
1533 (with-current-buffer (marker-buffer m)
1534 org-columns-default-format))))))
1535 (t org-columns-default-format)))
1536 (compiled-fmt (org-columns-compile-format fmt)))
1537 (setq org-columns-current-fmt fmt)
1538 (when org-agenda-columns-compute-summary-properties
1539 (org-agenda-colview-compute org-columns-current-fmt-compiled))
1540 (save-excursion
1541 ;; Collect properties for each headline in current view.
1542 (goto-char (point-min))
1543 (let (cache)
1544 (while (not (eobp))
1545 (let ((m (org-get-at-bol 'org-hd-marker)))
1546 (when m
1547 (push (cons (line-beginning-position)
1548 ;; `org-columns-current-fmt-compiled' is
1549 ;; initialized but only set locally to the
1550 ;; agenda buffer. Since current buffer is
1551 ;; changing, we need to force the original
1552 ;; compiled-fmt there.
1553 (org-with-point-at m
1554 (org-columns--collect-values compiled-fmt)))
1555 cache)))
1556 (forward-line))
1557 (when cache
1558 (org-columns--set-widths cache)
1559 (org-columns--display-here-title)
1560 (when (setq-local org-columns-flyspell-was-active
1561 (bound-and-true-p flyspell-mode))
1562 (flyspell-mode 0))
1563 (dolist (entry cache)
1564 (goto-char (car entry))
1565 (org-columns--display-here (cdr entry)))
1566 (when org-agenda-columns-show-summaries
1567 (org-agenda-colview-summarize cache)))))))
1569 (defun org-agenda-colview-summarize (cache)
1570 "Summarize the summarizable columns in column view in the agenda.
1571 This will add overlays to the date lines, to show the summary for each day."
1572 (let ((fmt (mapcar
1573 (lambda (spec)
1574 (pcase spec
1575 (`(,property ,title ,width . ,_)
1576 (if (member property '("CLOCKSUM" "CLOCKSUM_T"))
1577 (list property title width ":" nil)
1578 spec))))
1579 org-columns-current-fmt-compiled)))
1580 ;; Ensure there's at least one summation column.
1581 (when (cl-some (lambda (spec) (nth 3 spec)) fmt)
1582 (goto-char (point-max))
1583 (catch :complete
1584 (while t
1585 (when (or (get-text-property (point) 'org-date-line)
1586 (eq (get-text-property (point) 'face)
1587 'org-agenda-structure))
1588 ;; OK, this is a date line that should be used.
1589 (let (entries)
1590 (let (rest)
1591 (dolist (c cache)
1592 (if (> (car c) (point))
1593 (push c entries)
1594 (push c rest)))
1595 (setq cache rest))
1596 ;; ENTRIES contains entries below the current one.
1597 ;; CACHE is the rest. Compute the summaries for the
1598 ;; properties we want, set nil properties for the rest.
1599 (when (setq entries (mapcar #'cdr entries))
1600 (org-columns--display-here
1601 (mapcar
1602 (lambda (spec)
1603 (pcase spec
1604 (`("ITEM" . ,_)
1605 ;; Replace ITEM with current date. Preserve
1606 ;; properties for fontification.
1607 (let ((date (buffer-substring
1608 (line-beginning-position)
1609 (line-end-position))))
1610 (list spec date date)))
1611 (`(,_ ,_ ,_ nil ,_) (list spec "" ""))
1612 (`(,_ ,_ ,_ ,operator ,printf)
1613 (let* ((summarize (org-columns--summarize operator))
1614 (values
1615 ;; Use real values for summary, not
1616 ;; those prepared for display.
1617 (delq nil
1618 (mapcar
1619 (lambda (e) (org-string-nw-p
1620 (nth 1 (assoc spec e))))
1621 entries)))
1622 (final (if values
1623 (funcall summarize values printf)
1624 "")))
1625 (unless (equal final "")
1626 (put-text-property 0 (length final)
1627 'face 'bold final))
1628 (list spec final final)))))
1629 fmt)
1630 'dateline)
1631 (setq-local org-agenda-columns-active t))))
1632 (if (bobp) (throw :complete t) (forward-line -1)))))))
1634 (defun org-agenda-colview-compute (fmt)
1635 "Compute the relevant columns in the contributing source buffers."
1636 (let ((files org-agenda-contributing-files)
1637 (org-columns-begin-marker (make-marker))
1638 (org-columns-top-level-marker (make-marker)))
1639 (dolist (f files)
1640 (let ((b (find-buffer-visiting f)))
1641 (with-current-buffer (or (buffer-base-buffer b) b)
1642 (org-with-wide-buffer
1643 (org-with-silent-modifications
1644 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
1645 (goto-char (point-min))
1646 (org-columns-get-format-and-top-level)
1647 (dolist (spec fmt)
1648 (let ((prop (car spec)))
1649 (cond
1650 ((equal prop "CLOCKSUM") (org-clock-sum))
1651 ((equal prop "CLOCKSUM_T") (org-clock-sum-today))
1652 ((and (nth 3 spec)
1653 (let ((a (assoc prop org-columns-current-fmt-compiled)))
1654 (equal (nth 3 a) (nth 3 spec))))
1655 (org-columns-compute prop)))))))))))
1658 (provide 'org-colview)
1660 ;;; org-colview.el ends here