Keep headlines named like current one in refile targets
[org-mode.git] / lisp / org.el
blob7842b2f3090090d401c88e69000d71b518b7e5e3
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (&optional date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data &optional parent))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
139 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
140 (declare-function org-element-property "org-element" (property element))
141 (declare-function org-element-put-property "org-element" (element property value))
142 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
143 (declare-function org-element-type "org-element" (element))
144 (declare-function org-element-update-syntax "org-element" ())
145 (declare-function org-id-find-id-file "org-id" (id))
146 (declare-function org-id-get-create "org-id" (&optional force))
147 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
148 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
149 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
150 (declare-function org-plot/gnuplot "org-plot" (&optional params))
151 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-edit-field "org-table" (arg))
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
164 (declare-function org-table-next-row "org-table" ())
165 (declare-function org-table-paste-rectangle "org-table" ())
166 (declare-function org-table-wrap-region "org-table" (arg))
167 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
168 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
169 (declare-function orgtbl-mode "org-table" (&optional arg))
171 (defsubst org-uniquify (list)
172 "Non-destructively remove duplicate elements from LIST."
173 (let ((res (copy-sequence list))) (delete-dups res)))
175 (defsubst org-get-at-bol (property)
176 "Get text property PROPERTY at the beginning of line."
177 (get-text-property (point-at-bol) property))
179 (defsubst org-trim (s)
180 "Remove whitespace at the beginning and the end of string S."
181 (replace-regexp-in-string
182 "\\`[ \t\n\r]+" ""
183 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org-mode FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the org-mode file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org-mode buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Emacs Lisp" emacs-lisp)
258 (const :tag "Forth" forth)
259 (const :tag "Fortran" fortran)
260 (const :tag "Gnuplot" gnuplot)
261 (const :tag "Haskell" haskell)
262 (const :tag "IO" io)
263 (const :tag "J" J)
264 (const :tag "Java" java)
265 (const :tag "Javascript" js)
266 (const :tag "LaTeX" latex)
267 (const :tag "Ledger" ledger)
268 (const :tag "Lilypond" lilypond)
269 (const :tag "Lisp" lisp)
270 (const :tag "Makefile" makefile)
271 (const :tag "Maxima" maxima)
272 (const :tag "Matlab" matlab)
273 (const :tag "Mscgen" mscgen)
274 (const :tag "Ocaml" ocaml)
275 (const :tag "Octave" octave)
276 (const :tag "Org" org)
277 (const :tag "Perl" perl)
278 (const :tag "Pico Lisp" picolisp)
279 (const :tag "PlantUML" plantuml)
280 (const :tag "Python" python)
281 (const :tag "Ruby" ruby)
282 (const :tag "Sass" sass)
283 (const :tag "Scala" scala)
284 (const :tag "Scheme" scheme)
285 (const :tag "Screen" screen)
286 (const :tag "Shell Script" shell)
287 (const :tag "Shen" shen)
288 (const :tag "Sql" sql)
289 (const :tag "Sqlite" sqlite)
290 (const :tag "Stan" stan)
291 (const :tag "ebnf2ps" ebnf2ps))
292 :value-type (boolean :tag "Activate" :value t)))
294 ;;;; Customization variables
295 (defcustom org-clone-delete-id nil
296 "Remove ID property of clones of a subtree.
297 When non-nil, clones of a subtree don't inherit the ID property.
298 Otherwise they inherit the ID property with a new unique
299 identifier."
300 :type 'boolean
301 :version "24.1"
302 :group 'org-id)
304 ;;; Version
305 (org-check-version)
307 ;;;###autoload
308 (defun org-version (&optional here full message)
309 "Show the org-mode version.
310 Interactively, or when MESSAGE is non-nil, show it in echo area.
311 With prefix argument, or when HERE is non-nil, insert it at point.
312 In non-interactive uses, a reduced version string is output unless
313 FULL is given."
314 (interactive (list current-prefix-arg t (not current-prefix-arg)))
315 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
316 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
317 (load-suffixes (list ".el"))
318 (org-install-dir
319 (ignore-errors (org-find-library-dir "org-loaddefs"))))
320 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
321 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
322 (let* ((load-suffixes save-load-suffixes)
323 (release (org-release))
324 (git-version (org-git-version))
325 (version (format "Org-mode version %s (%s @ %s)"
326 release
327 git-version
328 (if org-install-dir
329 (if (string= org-dir org-install-dir)
330 org-install-dir
331 (concat "mixed installation! "
332 org-install-dir
333 " and "
334 org-dir))
335 "org-loaddefs.el can not be found!")))
336 (version1 (if full version release)))
337 (when here (insert version1))
338 (when message (message "%s" version1))
339 version1)))
341 (defconst org-version (org-version))
344 ;;; Syntax Constants
346 ;;;; Block
348 (defconst org-block-regexp
349 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
350 "Regular expression for hiding blocks.")
352 (defconst org-dblock-start-re
353 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
354 "Matches the start line of a dynamic block, with parameters.")
356 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
357 "Matches the end of a dynamic block.")
359 ;;;; Clock and Planning
361 (defconst org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item.")
364 (defvar org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry.")
367 (defvar org-deadline-string "DEADLINE:"
368 "String to mark deadline entries.
369 A deadline is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-deadline].")
373 (defvar org-scheduled-string "SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].")
379 (defconst org-ds-keyword-length
380 (+ 2
381 (apply #'max
382 (mapcar #'length
383 (list org-deadline-string org-scheduled-string
384 org-clock-string org-closed-string))))
385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
387 (defconst org-planning-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-closed-string org-deadline-string org-scheduled-string)
392 "Matches a line with planning info.
393 Matched keyword is in group 1.")
395 (defconst org-clock-line-re
396 (concat "^[ \t]*" org-clock-string)
397 "Matches a line with clock info.")
399 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
400 "Matches the DEADLINE keyword.")
402 (defconst org-deadline-time-regexp
403 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
404 "Matches the DEADLINE keyword together with a time stamp.")
406 (defconst org-deadline-time-hour-regexp
407 (concat "\\<" org-deadline-string
408 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
409 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
411 (defconst org-deadline-line-regexp
412 (concat "\\<\\(" org-deadline-string "\\).*")
413 "Matches the DEADLINE keyword and the rest of the line.")
415 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
416 "Matches the SCHEDULED keyword.")
418 (defconst org-scheduled-time-regexp
419 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
420 "Matches the SCHEDULED keyword together with a time stamp.")
422 (defconst org-scheduled-time-hour-regexp
423 (concat "\\<" org-scheduled-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
427 (defconst org-closed-time-regexp
428 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
429 "Matches the CLOSED keyword together with a time stamp.")
431 (defconst org-keyword-time-regexp
432 (concat "\\<"
433 (regexp-opt
434 (list org-scheduled-string org-deadline-string org-closed-string
435 org-clock-string)
437 " *[[<]\\([^]>]+\\)[]>]")
438 "Matches any of the 4 keywords, together with the time stamp.")
440 (defconst org-keyword-time-not-clock-regexp
441 (concat
442 "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string) t)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 3 keywords, together with the time stamp.")
448 (defconst org-maybe-keyword-time-regexp
449 (concat "\\(\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string
452 org-clock-string)
454 "\\)?"
455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
456 "\\|"
457 "<%%([^\r\n>]*>\\)")
458 "Matches a timestamp, possibly preceded by a keyword.")
460 (defconst org-all-time-keywords
461 (mapcar (lambda (w) (substring w 0 -1))
462 (list org-scheduled-string org-deadline-string
463 org-clock-string org-closed-string))
464 "List of time keywords.")
466 ;;;; Drawer
468 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
469 "Matches first or last line of a hidden block.
470 Group 1 contains drawer's name or \"END\".")
472 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
473 "Regular expression matching the first line of a property drawer.")
475 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
476 "Regular expression matching the last line of a property drawer.")
478 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
479 "Regular expression matching the first line of a clock drawer.")
481 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a clock drawer.")
484 (defconst org-property-drawer-re
485 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
486 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
487 "[ \t]*:END:[ \t]*$")
488 "Matches an entire property drawer.")
490 (defconst org-clock-drawer-re
491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
492 org-clock-drawer-end-re "\\)\n?")
493 "Matches an entire clock drawer.")
495 ;;;; Headline
497 (defconst org-heading-keyword-regexp-format
498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
499 "Printf format for a regexp matching a headline with some keyword.
500 This regexp will match the headline of any node which has the
501 exact keyword that is put into the format. The keyword isn't in
502 any group by default, but the stars and the body are.")
504 (defconst org-heading-keyword-maybe-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline, possibly with some keyword.
507 This regexp can match any headline with the specified keyword, or
508 without a keyword. The keyword isn't in any group by default,
509 but the stars and the body are.")
511 (defconst org-archive-tag "ARCHIVE"
512 "The tag that marks a subtree as archived.
513 An archived subtree does not open during visibility cycling, and does
514 not contribute to the agenda listings.")
516 (defconst org-comment-string "COMMENT"
517 "Entries starting with this keyword will never be exported.
518 An entry can be toggled between COMMENT and normal with
519 \\[org-toggle-comment].")
522 ;;;; LaTeX Environments and Fragments
524 (defconst org-latex-regexps
525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
533 "Regular expressions for matching embedded LaTeX.")
535 ;;;; Node Property
537 (defconst org-effort-property "Effort"
538 "The property that is being used to keep track of effort estimates.
539 Effort estimates given in this property need to have the format H:MM.")
541 ;;;; Table
543 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
544 "Detect an org-type or table-type table.")
546 (defconst org-table-line-regexp "^[ \t]*|"
547 "Detect an org-type table line.")
549 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
550 "Detect an org-type table line.")
552 (defconst org-table-hline-regexp "^[ \t]*|-"
553 "Detect an org-type table hline.")
555 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
556 "Detect a table-type table hline.")
558 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
559 "Detect the first line outside a table when searching from within it.
560 This works for both table types.")
562 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
563 "Detect a #+TBLFM line.")
565 ;;;; Timestamp
567 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
568 "Regular expression for fast time stamp matching.")
570 (defconst org-ts-regexp-inactive
571 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
572 "Regular expression for fast inactive time stamp matching.")
574 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp0
578 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
579 "Regular expression matching time strings for analysis.
580 This one does not require the space after the date, so it can be used
581 on a string that terminates immediately after the date.")
583 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
584 "Regular expression matching time strings for analysis.")
586 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
587 "Regular expression matching time stamps, with groups.")
589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
590 "Regular expression matching time stamps (also [..]), with groups.")
592 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tr-regexp-both
596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
600 org-ts-regexp "\\)?")
601 "Regular expression matching a time stamp or time stamp range.")
603 (defconst org-tsr-regexp-both
604 (concat org-ts-regexp-both "\\(--?-?"
605 org-ts-regexp-both "\\)?")
606 "Regular expression matching a time stamp or time stamp range.
607 The time stamps may be either active or inactive.")
609 (defconst org-repeat-re
610 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
611 "Regular expression for specifying repeated events.
612 After a match, group 1 contains the repeat expression.")
614 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
615 "Formats for `format-time-string' which are used for time stamps.")
618 ;;; The custom variables
620 (defgroup org nil
621 "Outline-based notes management and organizer."
622 :tag "Org"
623 :group 'outlines
624 :group 'calendar)
626 (defcustom org-mode-hook nil
627 "Mode hook for Org-mode, run after the mode was turned on."
628 :group 'org
629 :type 'hook)
631 (defcustom org-load-hook nil
632 "Hook that is run after org.el has been loaded."
633 :group 'org
634 :type 'hook)
636 (defcustom org-log-buffer-setup-hook nil
637 "Hook that is run after an Org log buffer is created."
638 :group 'org
639 :version "24.1"
640 :type 'hook)
642 (defvar org-modules) ; defined below
643 (defvar org-modules-loaded nil
644 "Have the modules been loaded already?")
646 (defun org-load-modules-maybe (&optional force)
647 "Load all extensions listed in `org-modules'."
648 (when (or force (not org-modules-loaded))
649 (dolist (ext org-modules)
650 (condition-case nil (require ext)
651 (error (message "Problems while trying to load feature `%s'" ext))))
652 (setq org-modules-loaded t)))
654 (defun org-set-modules (var value)
655 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
656 (set var value)
657 (when (featurep 'org)
658 (org-load-modules-maybe 'force)
659 (org-element-cache-reset 'all)))
661 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
662 "Modules that should always be loaded together with org.el.
664 If a description starts with <C>, the file is not part of Emacs
665 and loading it will require that you have downloaded and properly
666 installed the Org mode distribution.
668 You can also use this system to load external packages (i.e. neither Org
669 core modules, nor modules from the CONTRIB directory). Just add symbols
670 to the end of the list. If the package is called org-xyz.el, then you need
671 to add the symbol `xyz', and the package must have a call to:
673 (provide \\='org-xyz)
675 For export specific modules, see also `org-export-backends'."
676 :group 'org
677 :set 'org-set-modules
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type
681 '(set :greedy t
682 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
683 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
684 (const :tag " crypt: Encryption of subtrees" org-crypt)
685 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
686 (const :tag " docview: Links to doc-view buffers" org-docview)
687 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
688 (const :tag " habit: Track your consistency with habits" org-habit)
689 (const :tag " id: Global IDs for identifying entries" org-id)
690 (const :tag " info: Links to Info nodes" org-info)
691 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
692 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
693 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
694 (const :tag " mouse: Additional mouse support" org-mouse)
695 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
696 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
697 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
699 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
700 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
701 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
702 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
703 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
704 (const :tag "C collector: Collect properties into tables" org-collector)
705 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
706 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
707 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
708 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
709 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
710 (const :tag "C eval: Include command output as text" org-eval)
711 (const :tag "C eww: Store link to url of eww" org-eww)
712 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
713 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
714 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
715 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
716 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
717 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
718 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
719 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
720 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
721 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
722 (const :tag "C mew: Links to Mew folders/messages" org-mew)
723 (const :tag "C mtags: Support for muse-like tags" org-mtags)
724 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
725 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
726 (const :tag "C registry: A registry for Org-mode links" org-registry)
727 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
728 (const :tag "C secretary: Team management with org-mode" org-secretary)
729 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
730 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
731 (const :tag "C track: Keep up with Org-mode development" org-track)
732 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
733 (const :tag "C vm: Links to VM folders/messages" org-vm)
734 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
735 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
736 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
738 (defvar org-export-registered-backends) ; From ox.el.
739 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
740 (declare-function org-export-backend-name "ox" (backend))
741 (defcustom org-export-backends '(ascii html icalendar latex)
742 "List of export back-ends that should be always available.
744 If a description starts with <C>, the file is not part of Emacs
745 and loading it will require that you have downloaded and properly
746 installed the Org mode distribution.
748 Unlike to `org-modules', libraries in this list will not be
749 loaded along with Org, but only once the export framework is
750 needed.
752 This variable needs to be set before org.el is loaded. If you
753 need to make a change while Emacs is running, use the customize
754 interface or run the following code, where VAL stands for the new
755 value of the variable, after updating it:
757 (progn
758 (setq org-export-registered-backends
759 (cl-remove-if-not
760 (lambda (backend)
761 (let ((name (org-export-backend-name backend)))
762 (or (memq name val)
763 (catch \\='parentp
764 (dolist (b val)
765 (and (org-export-derived-backend-p b name)
766 (throw \\='parentp t)))))))
767 org-export-registered-backends))
768 (let ((new-list (mapcar #\\='org-export-backend-name
769 org-export-registered-backends)))
770 (dolist (backend val)
771 (cond
772 ((not (load (format \"ox-%s\" backend) t t))
773 (message \"Problems while trying to load export back-end \\=`%s\\='\"
774 backend))
775 ((not (memq backend new-list)) (push backend new-list))))
776 (set-default \\='org-export-backends new-list)))
778 Adding a back-end to this list will also pull the back-end it
779 depends on, if any."
780 :group 'org
781 :group 'org-export
782 :version "24.4"
783 :package-version '(Org . "8.0")
784 :initialize 'custom-initialize-set
785 :set (lambda (var val)
786 (if (not (featurep 'ox)) (set-default var val)
787 ;; Any back-end not required anymore (not present in VAL and not
788 ;; a parent of any back-end in the new value) is removed from the
789 ;; list of registered back-ends.
790 (setq org-export-registered-backends
791 (cl-remove-if-not
792 (lambda (backend)
793 (let ((name (org-export-backend-name backend)))
794 (or (memq name val)
795 (catch 'parentp
796 (dolist (b val)
797 (and (org-export-derived-backend-p b name)
798 (throw 'parentp t)))))))
799 org-export-registered-backends))
800 ;; Now build NEW-LIST of both new back-ends and required
801 ;; parents.
802 (let ((new-list (mapcar #'org-export-backend-name
803 org-export-registered-backends)))
804 (dolist (backend val)
805 (cond
806 ((not (load (format "ox-%s" backend) t t))
807 (message "Problems while trying to load export back-end `%s'"
808 backend))
809 ((not (memq backend new-list)) (push backend new-list))))
810 ;; Set VAR to that list with fixed dependencies.
811 (set-default var new-list))))
812 :type '(set :greedy t
813 (const :tag " ascii Export buffer to ASCII format" ascii)
814 (const :tag " beamer Export buffer to Beamer presentation" beamer)
815 (const :tag " html Export buffer to HTML format" html)
816 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
817 (const :tag " latex Export buffer to LaTeX format" latex)
818 (const :tag " man Export buffer to MAN format" man)
819 (const :tag " md Export buffer to Markdown format" md)
820 (const :tag " odt Export buffer to ODT format" odt)
821 (const :tag " org Export buffer to Org format" org)
822 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
823 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
824 (const :tag "C deck Export buffer to deck.js presentations" deck)
825 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
826 (const :tag "C groff Export buffer to Groff format" groff)
827 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
828 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
829 (const :tag "C s5 Export buffer to s5 presentations" s5)
830 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
832 (eval-after-load 'ox
833 '(dolist (backend org-export-backends)
834 (condition-case nil (require (intern (format "ox-%s" backend)))
835 (error (message "Problems while trying to load export back-end `%s'"
836 backend)))))
838 (defcustom org-support-shift-select nil
839 "Non-nil means make shift-cursor commands select text when possible.
840 \\<org-mode-map>\
842 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
843 start selecting a region, or enlarge regions started in this way.
844 In Org-mode, in special contexts, these same keys are used for
845 other purposes, important enough to compete with shift selection.
846 Org tries to balance these needs by supporting `shift-select-mode'
847 outside these special contexts, under control of this variable.
849 The default of this variable is nil, to avoid confusing behavior. Shifted
850 cursor keys will then execute Org commands in the following contexts:
851 - on a headline, changing TODO state (left/right) and priority (up/down)
852 - on a time stamp, changing the time
853 - in a plain list item, changing the bullet type
854 - in a property definition line, switching between allowed values
855 - in the BEGIN line of a clock table (changing the time block).
856 Outside these contexts, the commands will throw an error.
858 When this variable is t and the cursor is not in a special
859 context, Org-mode will support shift-selection for making and
860 enlarging regions. To make this more effective, the bullet
861 cycling will no longer happen anywhere in an item line, but only
862 if the cursor is exactly on the bullet.
864 If you set this variable to the symbol `always', then the keys
865 will not be special in headlines, property lines, and item lines,
866 to make shift selection work there as well. If this is what you
867 want, you can use the following alternative commands:
868 `\\[org-todo]' and `\\[org-priority]' \
869 to change TODO state and priority,
870 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
871 can be used to switch TODO sets,
872 `\\[org-ctrl-c-minus]' to cycle item bullet types,
873 and properties can be edited by hand or in column view.
875 However, when the cursor is on a timestamp, shift-cursor commands
876 will still edit the time stamp - this is just too good to give up.
878 XEmacs user should have this variable set to nil, because
879 `shift-select-mode' is in Emacs 23 or later only."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped."
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-indented nil
945 "Non-nil means turn on `org-indent-mode' on startup.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
949 #+STARTUP: indent
950 #+STARTUP: noindent"
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Not" nil)
954 (const :tag "Globally (slow on startup in large files)" t)))
956 (defcustom org-use-sub-superscripts t
957 "Non-nil means interpret \"_\" and \"^\" for display.
959 If you want to control how Org exports those characters, see
960 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
961 used to be an alias for `org-export-with-sub-superscripts' in
962 Org <8.0, it is not anymore.
964 When this option is turned on, you can use TeX-like syntax for
965 sub- and superscripts within the buffer. Several characters after
966 \"_\" or \"^\" will be considered as a single item - so grouping
967 with {} is normally not needed. For example, the following things
968 will be parsed as single sub- or superscripts:
970 10^24 or 10^tau several digits will be considered 1 item.
971 10^-12 or 10^-tau a leading sign with digits or a word
972 x^2-y^3 will be read as x^2 - y^3, because items are
973 terminated by almost any nonword/nondigit char.
974 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
976 Still, ambiguity is possible. So when in doubt, use {} to enclose
977 the sub/superscript. If you set this variable to the symbol `{}',
978 the braces are *required* in order to trigger interpretations as
979 sub/superscript. This can be helpful in documents that need \"_\"
980 frequently in plain text."
981 :group 'org-startup
982 :version "24.4"
983 :package-version '(Org . "8.0")
984 :type '(choice
985 (const :tag "Always interpret" t)
986 (const :tag "Only with braces" {})
987 (const :tag "Never interpret" nil)))
989 (defcustom org-startup-with-beamer-mode nil
990 "Non-nil means turn on `org-beamer-mode' on startup.
991 This can also be configured on a per-file basis by adding one of
992 the following lines anywhere in the buffer:
994 #+STARTUP: beamer"
995 :group 'org-startup
996 :version "24.1"
997 :type 'boolean)
999 (defcustom org-startup-align-all-tables nil
1000 "Non-nil means align all tables when visiting a file.
1001 This is useful when the column width in tables is forced with <N> cookies
1002 in table fields. Such tables will look correct only after the first re-align.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1005 #+STARTUP: align
1006 #+STARTUP: noalign"
1007 :group 'org-startup
1008 :type 'boolean)
1010 (defcustom org-startup-with-inline-images nil
1011 "Non-nil means show inline images when loading a new Org file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: inlineimages
1015 #+STARTUP: noinlineimages"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-with-latex-preview nil
1021 "Non-nil means preview LaTeX fragments when loading a new Org file.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: latexpreview
1026 #+STARTUP: nolatexpreview"
1027 :group 'org-startup
1028 :version "24.4"
1029 :package-version '(Org . "8.0")
1030 :type 'boolean)
1032 (defcustom org-insert-mode-line-in-empty-file nil
1033 "Non-nil means insert the first line setting Org-mode in empty files.
1034 When the function `org-mode' is called interactively in an empty file, this
1035 normally means that the file name does not automatically trigger Org-mode.
1036 To ensure that the file will always be in Org-mode in the future, a
1037 line enforcing Org-mode will be inserted into the buffer, if this option
1038 has been set."
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-replace-disputed-keys nil
1043 "Non-nil means use alternative key bindings for some keys.
1044 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1045 These keys are also used by other packages like shift-selection-mode'
1046 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1047 If you want to use Org-mode together with one of these other modes,
1048 or more generally if you would like to move some Org-mode commands to
1049 other keys, set this variable and configure the keys with the variable
1050 `org-disputed-keys'.
1052 This option is only relevant at load-time of Org-mode, and must be set
1053 *before* org.el is loaded. Changing it requires a restart of Emacs to
1054 become effective."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-use-extra-keys nil
1059 "Non-nil means use extra key sequence definitions for certain commands.
1060 This happens automatically if you run XEmacs or if `window-system'
1061 is nil. This variable lets you do the same manually. You must
1062 set it before loading org.
1064 Example: on Carbon Emacs 22 running graphically, with an external
1065 keyboard on a Powerbook, the default way of setting M-left might
1066 not work for either Alt or ESC. Setting this variable will make
1067 it work for ESC."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1073 (defcustom org-disputed-keys
1074 '(([(shift up)] . [(meta p)])
1075 ([(shift down)] . [(meta n)])
1076 ([(shift left)] . [(meta -)])
1077 ([(shift right)] . [(meta +)])
1078 ([(control shift right)] . [(meta shift +)])
1079 ([(control shift left)] . [(meta shift -)]))
1080 "Keys for which Org-mode and other modes compete.
1081 This is an alist, cars are the default keys, second element specifies
1082 the alternative to use when `org-replace-disputed-keys' is t.
1084 Keys can be specified in any syntax supported by `define-key'.
1085 The value of this option takes effect only at Org-mode's startup,
1086 therefore you'll have to restart Emacs to apply it after changing."
1087 :group 'org-startup
1088 :type 'alist)
1090 (defun org-key (key)
1091 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1092 Or return the original if not disputed.
1093 Also apply the translations defined in `org-xemacs-key-equivalents'."
1094 (when org-replace-disputed-keys
1095 (let* ((nkey (key-description key))
1096 (x (org-find-if (lambda (x)
1097 (equal (key-description (car x)) nkey))
1098 org-disputed-keys)))
1099 (setq key (if x (cdr x) key))))
1100 (when (featurep 'xemacs)
1101 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1102 key)
1104 (defun org-find-if (predicate seq)
1105 (catch 'exit
1106 (while seq
1107 (if (funcall predicate (car seq))
1108 (throw 'exit (car seq))
1109 (pop seq)))))
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org-mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1119 When a face, use the standard 3 dots, but with the specified face.
1120 The change affects only Org-mode (which will then use its own display table).
1121 Changing this requires executing \\[org-mode] in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (face :tag "Face" :value org-warning)
1126 (string :tag "String" :value "...#")))
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org-mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org-mode files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((isearch . lineage)
1155 (bookmark-jump . lineage)
1156 (default . ancestors))
1157 "Alist between context and visibility span when revealing a location.
1159 \\<org-mode-map>Some actions may move point into invisible
1160 locations. As a consequence, Org always expose a neighborhood
1161 around point. How much is shown depends on the initial action,
1162 or context. Valid contexts are
1164 agenda when exposing an entry from the agenda
1165 org-goto when using the command `org-goto' (\\[org-goto])
1166 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1167 tags-tree when constructing a sparse tree based on tags matches
1168 link-search when exposing search matches associated with a link
1169 mark-goto when exposing the jump goal of a mark
1170 bookmark-jump when exposing a bookmark location
1171 isearch when exiting from an incremental search
1172 default default for all contexts not set explicitly
1174 Allowed visibility spans are
1176 minimal show current headline; if point is not on headline,
1177 also show entry
1179 local show current headline, entry and next headline
1181 ancestors show current headline and its direct ancestors; if
1182 point is not on headline, also show entry
1184 lineage show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and first child
1188 tree show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and all children
1192 canonical show current headline, its direct ancestors along with
1193 their entries and children; if point is not located on
1194 the headline, also show current entry and all children
1196 As special cases, a nil or t value means show all contexts in
1197 `minimal' or `canonical' view, respectively.
1199 Some views can make displayed information very compact, but also
1200 make it harder to edit the location of the match. In such
1201 a case, use the command `org-reveal' (\\[org-reveal]) to show
1202 more context."
1203 :group 'org-reveal-location
1204 :version "25.1"
1205 :package-version '(Org . "8.3")
1206 :type '(choice
1207 (const :tag "Canonical" t)
1208 (const :tag "Minimal" nil)
1209 (repeat :greedy t :tag "Individual contexts"
1210 (cons
1211 (choice :tag "Context"
1212 (const agenda)
1213 (const org-goto)
1214 (const occur-tree)
1215 (const tags-tree)
1216 (const link-search)
1217 (const mark-goto)
1218 (const bookmark-jump)
1219 (const isearch)
1220 (const default))
1221 (choice :tag "Detail level"
1222 (const minimal)
1223 (const local)
1224 (const ancestors)
1225 (const lineage)
1226 (const tree)
1227 (const canonical))))))
1229 (defcustom org-indirect-buffer-display 'other-window
1230 "How should indirect tree buffers be displayed?
1231 This applies to indirect buffers created with the commands
1232 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1233 Valid values are:
1234 current-window Display in the current window
1235 other-window Just display in another window.
1236 dedicated-frame Create one new frame, and re-use it each time.
1237 new-frame Make a new frame each time. Note that in this case
1238 previously-made indirect buffers are kept, and you need to
1239 kill these buffers yourself."
1240 :group 'org-structure
1241 :group 'org-agenda-windows
1242 :type '(choice
1243 (const :tag "In current window" current-window)
1244 (const :tag "In current frame, other window" other-window)
1245 (const :tag "Each time a new frame" new-frame)
1246 (const :tag "One dedicated frame" dedicated-frame)))
1248 (defcustom org-use-speed-commands nil
1249 "Non-nil means activate single letter commands at beginning of a headline.
1250 This may also be a function to test for appropriate locations where speed
1251 commands should be active.
1253 For example, to activate speed commands when the point is on any
1254 star at the beginning of the headline, you can do this:
1256 (setq org-use-speed-commands
1257 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1258 :group 'org-structure
1259 :type '(choice
1260 (const :tag "Never" nil)
1261 (const :tag "At beginning of headline stars" t)
1262 (function)))
1264 (defcustom org-speed-commands-user nil
1265 "Alist of additional speed commands.
1266 This list will be checked before `org-speed-commands-default'
1267 when the variable `org-use-speed-commands' is non-nil
1268 and when the cursor is at the beginning of a headline.
1269 The car if each entry is a string with a single letter, which must
1270 be assigned to `self-insert-command' in the global map.
1271 The cdr is either a command to be called interactively, a function
1272 to be called, or a form to be evaluated.
1273 An entry that is just a list with a single string will be interpreted
1274 as a descriptive headline that will be added when listing the speed
1275 commands in the Help buffer using the `?' speed command."
1276 :group 'org-structure
1277 :type '(repeat :value ("k" . ignore)
1278 (choice :value ("k" . ignore)
1279 (list :tag "Descriptive Headline" (string :tag "Headline"))
1280 (cons :tag "Letter and Command"
1281 (string :tag "Command letter")
1282 (choice
1283 (function)
1284 (sexp))))))
1286 (defcustom org-bookmark-names-plist
1287 '(:last-capture "org-capture-last-stored"
1288 :last-refile "org-refile-last-stored"
1289 :last-capture-marker "org-capture-last-stored-marker")
1290 "Names for bookmarks automatically set by some Org commands.
1291 This can provide strings as names for a number of bookmarks Org sets
1292 automatically. The following keys are currently implemented:
1293 :last-capture
1294 :last-capture-marker
1295 :last-refile
1296 When a key does not show up in the property list, the corresponding bookmark
1297 is not set."
1298 :group 'org-structure
1299 :type 'plist)
1301 (defgroup org-cycle nil
1302 "Options concerning visibility cycling in Org-mode."
1303 :tag "Org Cycle"
1304 :group 'org-structure)
1306 (defcustom org-cycle-skip-children-state-if-no-children t
1307 "Non-nil means skip CHILDREN state in entries that don't have any."
1308 :group 'org-cycle
1309 :type 'boolean)
1311 (defcustom org-cycle-max-level nil
1312 "Maximum level which should still be subject to visibility cycling.
1313 Levels higher than this will, for cycling, be treated as text, not a headline.
1314 When `org-odd-levels-only' is set, a value of N in this variable actually
1315 means 2N-1 stars as the limiting headline.
1316 When nil, cycle all levels.
1317 Note that the limiting level of cycling is also influenced by
1318 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1319 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1320 than its value."
1321 :group 'org-cycle
1322 :type '(choice
1323 (const :tag "No limit" nil)
1324 (integer :tag "Maximum level")))
1326 (defcustom org-hide-block-startup nil
1327 "Non-nil means entering Org-mode will fold all blocks.
1328 This can also be set in on a per-file basis with
1330 #+STARTUP: hideblocks
1331 #+STARTUP: showblocks"
1332 :group 'org-startup
1333 :group 'org-cycle
1334 :type 'boolean)
1336 (defcustom org-cycle-global-at-bob nil
1337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1338 This makes it possible to do global cycling without having to use S-TAB or
1339 \\[universal-argument] TAB. For this special case to work, the first line
1340 of the buffer must not be a headline -- it may be empty or some other text.
1341 When used in this way, `org-cycle-hook' is disabled temporarily to make
1342 sure the cursor stays at the beginning of the buffer. When this option is
1343 nil, don't do anything special at the beginning of the buffer."
1344 :group 'org-cycle
1345 :type 'boolean)
1347 (defcustom org-cycle-level-after-item/entry-creation t
1348 "Non-nil means cycle entry level or item indentation in new empty entries.
1350 When the cursor is at the end of an empty headline, i.e., with only stars
1351 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1352 and then all possible ancestor states, before returning to the original state.
1353 This makes data entry extremely fast: M-RET to create a new headline,
1354 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1356 When the cursor is at the end of an empty plain list item, one TAB will
1357 make it a subitem, two or more tabs will back up to make this an item
1358 higher up in the item hierarchy."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-emulate-tab t
1363 "Where should `org-cycle' emulate TAB.
1364 nil Never
1365 white Only in completely white lines
1366 whitestart Only at the beginning of lines, before the first non-white char
1367 t Everywhere except in headlines
1368 exc-hl-bol Everywhere except at the start of a headline
1369 If TAB is used in a place where it does not emulate TAB, the current subtree
1370 visibility is cycled."
1371 :group 'org-cycle
1372 :type '(choice (const :tag "Never" nil)
1373 (const :tag "Only in completely white lines" white)
1374 (const :tag "Before first char in a line" whitestart)
1375 (const :tag "Everywhere except in headlines" t)
1376 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1378 (defcustom org-cycle-separator-lines 2
1379 "Number of empty lines needed to keep an empty line between collapsed trees.
1380 If you leave an empty line between the end of a subtree and the following
1381 headline, this empty line is hidden when the subtree is folded.
1382 Org-mode will leave (exactly) one empty line visible if the number of
1383 empty lines is equal or larger to the number given in this variable.
1384 So the default 2 means at least 2 empty lines after the end of a subtree
1385 are needed to produce free space between a collapsed subtree and the
1386 following headline.
1388 If the number is negative, and the number of empty lines is at least -N,
1389 all empty lines are shown.
1391 Special case: when 0, never leave empty lines in collapsed view."
1392 :group 'org-cycle
1393 :type 'integer)
1394 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1396 (defcustom org-pre-cycle-hook nil
1397 "Hook that is run before visibility cycling is happening.
1398 The function(s) in this hook must accept a single argument which indicates
1399 the new state that will be set right after running this hook. The
1400 argument is a symbol. Before a global state change, it can have the values
1401 `overview', `content', or `all'. Before a local state change, it can have
1402 the values `folded', `children', or `subtree'."
1403 :group 'org-cycle
1404 :type 'hook)
1406 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1407 org-cycle-hide-drawers
1408 org-cycle-show-empty-lines
1409 org-optimize-window-after-visibility-change)
1410 "Hook that is run after `org-cycle' has changed the buffer visibility.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that was set by the most recent `org-cycle' command. The
1413 argument is a symbol. After a global state change, it can have the values
1414 `overview', `contents', or `all'. After a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook
1418 :version "25.1"
1419 :package-version '(Org . "8.3"))
1421 (defgroup org-edit-structure nil
1422 "Options concerning structure editing in Org-mode."
1423 :tag "Org Edit Structure"
1424 :group 'org-structure)
1426 (defcustom org-odd-levels-only nil
1427 "Non-nil means skip even levels and only use odd levels for the outline.
1428 This has the effect that two stars are being added/taken away in
1429 promotion/demotion commands. It also influences how levels are
1430 handled by the exporters.
1431 Changing it requires restart of `font-lock-mode' to become effective
1432 for fontification also in regions already fontified.
1433 You may also set this on a per-file basis by adding one of the following
1434 lines to the buffer:
1436 #+STARTUP: odd
1437 #+STARTUP: oddeven"
1438 :group 'org-edit-structure
1439 :group 'org-appearance
1440 :type 'boolean)
1442 (defcustom org-adapt-indentation t
1443 "Non-nil means adapt indentation to outline node level.
1445 When this variable is set, Org assumes that you write outlines by
1446 indenting text in each node to align with the headline (after the
1447 stars). The following issues are influenced by this variable:
1449 - The indentation is increased by one space in a demotion
1450 command, and decreased by one in a promotion command. However,
1451 in the latter case, if shifting some line in the entry body
1452 would alter document structure (e.g., insert a new headline),
1453 indentation is not changed at all.
1455 - Property drawers and planning information is inserted indented
1456 when this variable is set. When nil, they will not be indented.
1458 - TAB indents a line relative to current level. The lines below
1459 a headline will be indented when this variable is set.
1461 Note that this is all about true indentation, by adding and
1462 removing space characters. See also `org-indent.el' which does
1463 level-dependent indentation in a virtual way, i.e. at display
1464 time in Emacs."
1465 :group 'org-edit-structure
1466 :type 'boolean)
1468 (defcustom org-special-ctrl-a/e nil
1469 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1471 When t, `C-a' will bring back the cursor to the beginning of the
1472 headline text, i.e. after the stars and after a possible TODO
1473 keyword. In an item, this will be the position after bullet and
1474 check-box, if any. When the cursor is already at that position,
1475 another `C-a' will bring it to the beginning of the line.
1477 `C-e' will jump to the end of the headline, ignoring the presence
1478 of tags in the headline. A second `C-e' will then jump to the
1479 true end of the line, after any tags. This also means that, when
1480 this variable is non-nil, `C-e' also will never jump beyond the
1481 end of the heading of a folded section, i.e. not after the
1482 ellipses.
1484 When set to the symbol `reversed', the first `C-a' or `C-e' works
1485 normally, going to the true line boundary first. Only a directly
1486 following, identical keypress will bring the cursor to the
1487 special positions.
1489 This may also be a cons cell where the behavior for `C-a' and
1490 `C-e' is set separately."
1491 :group 'org-edit-structure
1492 :type '(choice
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet and before tags first" t)
1495 (const :tag "reversed: true line boundary first" reversed)
1496 (cons :tag "Set C-a and C-e separately"
1497 (choice :tag "Special C-a"
1498 (const :tag "off" nil)
1499 (const :tag "on: after stars/bullet first" t)
1500 (const :tag "reversed: before stars/bullet first" reversed))
1501 (choice :tag "Special C-e"
1502 (const :tag "off" nil)
1503 (const :tag "on: before tags first" t)
1504 (const :tag "reversed: after tags first" reversed)))))
1505 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1507 (defcustom org-special-ctrl-k nil
1508 "Non-nil means `C-k' will behave specially in headlines.
1509 When nil, `C-k' will call the default `kill-line' command.
1510 When t, the following will happen while the cursor is in the headline:
1512 - When the cursor is at the beginning of a headline, kill the entire
1513 line and possible the folded subtree below the line.
1514 - When in the middle of the headline text, kill the headline up to the tags.
1515 - When after the headline text, kill the tags."
1516 :group 'org-edit-structure
1517 :type 'boolean)
1519 (defcustom org-ctrl-k-protect-subtree nil
1520 "Non-nil means, do not delete a hidden subtree with C-k.
1521 When set to the symbol `error', simply throw an error when C-k is
1522 used to kill (part-of) a headline that has hidden text behind it.
1523 Any other non-nil value will result in a query to the user, if it is
1524 OK to kill that hidden subtree. When nil, kill without remorse."
1525 :group 'org-edit-structure
1526 :version "24.1"
1527 :type '(choice
1528 (const :tag "Do not protect hidden subtrees" nil)
1529 (const :tag "Protect hidden subtrees with a security query" t)
1530 (const :tag "Never kill a hidden subtree with C-k" error)))
1532 (defcustom org-special-ctrl-o t
1533 "Non-nil means, make `C-o' insert a row in tables."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-catch-invisible-edits nil
1538 "Check if in invisible region before inserting or deleting a character.
1539 Valid values are:
1541 nil Do not check, so just do invisible edits.
1542 error Throw an error and do nothing.
1543 show Make point visible, and do the requested edit.
1544 show-and-error Make point visible, then throw an error and abort the edit.
1545 smart Make point visible, and do insertion/deletion if it is
1546 adjacent to visible text and the change feels predictable.
1547 Never delete a previously invisible character or add in the
1548 middle or right after an invisible region. Basically, this
1549 allows insertion and backward-delete right before ellipses.
1550 FIXME: maybe in this case we should not even show?"
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not check" nil)
1555 (const :tag "Throw error when trying to edit" error)
1556 (const :tag "Unhide, but do not do the edit" show-and-error)
1557 (const :tag "Show invisible part and do the edit" show)
1558 (const :tag "Be smart and do the right thing" smart)))
1560 (defcustom org-yank-folded-subtrees t
1561 "Non-nil means when yanking subtrees, fold them.
1562 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1563 it starts with a heading and all other headings in it are either children
1564 or siblings, then fold all the subtrees. However, do this only if no
1565 text after the yank would be swallowed into a folded tree by this action."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-yank-adjusted-subtrees nil
1570 "Non-nil means when yanking subtrees, adjust the level.
1571 With this setting, `org-paste-subtree' is used to insert the subtree, see
1572 this function for details."
1573 :group 'org-edit-structure
1574 :type 'boolean)
1576 (defcustom org-M-RET-may-split-line '((default . t))
1577 "Non-nil means M-RET will split the line at the cursor position.
1578 When nil, it will go to the end of the line before making a
1579 new line.
1580 You may also set this option in a different way for different
1581 contexts. Valid contexts are:
1583 headline when creating a new headline
1584 item when creating a new item
1585 table in a table field
1586 default the value to be used for all contexts not explicitly
1587 customized"
1588 :group 'org-structure
1589 :group 'org-table
1590 :type '(choice
1591 (const :tag "Always" t)
1592 (const :tag "Never" nil)
1593 (repeat :greedy t :tag "Individual contexts"
1594 (cons
1595 (choice :tag "Context"
1596 (const headline)
1597 (const item)
1598 (const table)
1599 (const default))
1600 (boolean)))))
1603 (defcustom org-insert-heading-respect-content nil
1604 "Non-nil means insert new headings after the current subtree.
1605 When nil, the new heading is created directly after the current line.
1606 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1607 this variable on for the duration of the command."
1608 :group 'org-structure
1609 :type 'boolean)
1611 (defcustom org-blank-before-new-entry '((heading . auto)
1612 (plain-list-item . auto))
1613 "Should `org-insert-heading' leave a blank line before new heading/item?
1614 The value is an alist, with `heading' and `plain-list-item' as CAR,
1615 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1616 which case Org will look at the surrounding headings/items and try to
1617 make an intelligent decision whether to insert a blank line or not."
1618 :group 'org-edit-structure
1619 :type '(list
1620 (cons (const heading)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))
1624 (cons (const plain-list-item)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))))
1629 (defcustom org-insert-heading-hook nil
1630 "Hook being run after inserting a new heading."
1631 :group 'org-edit-structure
1632 :type 'hook)
1634 (defcustom org-enable-fixed-width-editor t
1635 "Non-nil means lines starting with \":\" are treated as fixed-width.
1636 This currently only means they are never auto-wrapped.
1637 When nil, such lines will be treated like ordinary lines."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-goto-auto-isearch t
1642 "Non-nil means typing characters in `org-goto' starts incremental search.
1643 When nil, you can use these keybindings to navigate the buffer:
1645 q Quit the org-goto interface
1646 n Go to the next visible heading
1647 p Go to the previous visible heading
1648 f Go one heading forward on same level
1649 b Go one heading backward on same level
1650 u Go one heading up"
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org-mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1679 (defcustom org-occur-hook '(org-first-headline-recenter)
1680 "Hook that is run after `org-occur' has constructed a sparse tree.
1681 This can be used to recenter the window to show as much of the structure
1682 as possible."
1683 :group 'org-sparse-trees
1684 :type 'hook)
1686 (defgroup org-imenu-and-speedbar nil
1687 "Options concerning imenu and speedbar in Org-mode."
1688 :tag "Org Imenu and Speedbar"
1689 :group 'org-structure)
1691 (defcustom org-imenu-depth 2
1692 "The maximum level for Imenu access to Org-mode headlines.
1693 This also applied for speedbar access."
1694 :group 'org-imenu-and-speedbar
1695 :type 'integer)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org-mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-enable-table-editor 'optimized
1703 "Non-nil means lines starting with \"|\" are handled by the table editor.
1704 When nil, such lines will be treated like ordinary lines.
1706 When equal to the symbol `optimized', the table editor will be optimized to
1707 do the following:
1708 - Automatic overwrite mode in front of whitespace in table fields.
1709 This makes the structure of the table stay in tact as long as the edited
1710 field does not exceed the column width.
1711 - Minimize the number of realigns. Normally, the table is aligned each time
1712 TAB or RET are pressed to move to another field. With optimization this
1713 happens only if changes to a field might have changed the column width.
1714 Optimization requires replacing the functions `self-insert-command',
1715 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1716 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1717 very good at guessing when a re-align will be necessary, but you can always
1718 force one with \\[org-ctrl-c-ctrl-c].
1720 If you would like to use the optimized version in Org-mode, but the
1721 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1723 This variable can be used to turn on and off the table editor during a session,
1724 but in order to toggle optimization, a restart is required.
1726 See also the variable `org-table-auto-blank-field'."
1727 :group 'org-table
1728 :type '(choice
1729 (const :tag "off" nil)
1730 (const :tag "on" t)
1731 (const :tag "on, optimized" optimized)))
1733 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1734 (version<= emacs-version "24.1"))
1735 "Non-nil means cluster self-insert commands for undo when possible.
1736 If this is set, then, like in the Emacs command loop, 20 consecutive
1737 characters will be undone together.
1738 This is configurable, because there is some impact on typing performance."
1739 :group 'org-table
1740 :type 'boolean)
1742 (defcustom org-table-tab-recognizes-table.el t
1743 "Non-nil means TAB will automatically notice a table.el table.
1744 When it sees such a table, it moves point into it and - if necessary -
1745 calls `table-recognize-table'."
1746 :group 'org-table-editing
1747 :type 'boolean)
1749 (defgroup org-link nil
1750 "Options concerning links in Org-mode."
1751 :tag "Org Link"
1752 :group 'org)
1754 (defvar-local org-link-abbrev-alist-local nil
1755 "Buffer-local version of `org-link-abbrev-alist', which see.
1756 The value of this is taken from the #+LINK lines.")
1758 (defcustom org-link-abbrev-alist nil
1759 "Alist of link abbreviations.
1760 The car of each element is a string, to be replaced at the start of a link.
1761 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1762 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1764 [[linkkey:tag][description]]
1766 The `linkkey' must be a word word, starting with a letter, followed
1767 by letters, numbers, `-' or `_'.
1769 If REPLACE is a string, the tag will simply be appended to create the link.
1770 If the string contains \"%s\", the tag will be inserted there. If the string
1771 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1772 at that point (see the function `url-hexify-string'). If the string contains
1773 the specifier \"%(my-function)\", then the custom function `my-function' will
1774 be invoked: this function takes the tag as its only argument and must return
1775 a string.
1777 REPLACE may also be a function that will be called with the tag as the
1778 only argument to create the link, which should be returned as a string.
1780 See the manual for examples."
1781 :group 'org-link
1782 :type '(repeat
1783 (cons
1784 (string :tag "Protocol")
1785 (choice
1786 (string :tag "Format")
1787 (function)))))
1789 (defcustom org-descriptive-links t
1790 "Non-nil means Org will display descriptive links.
1791 E.g. [[http://orgmode.org][Org website]] will be displayed as
1792 \"Org Website\", hiding the link itself and just displaying its
1793 description. When set to nil, Org will display the full links
1794 literally.
1796 You can interactively set the value of this variable by calling
1797 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1798 :group 'org-link
1799 :type 'boolean)
1801 (defcustom org-link-file-path-type 'adaptive
1802 "How the path name in file links should be stored.
1803 Valid values are:
1805 relative Relative to the current directory, i.e. the directory of the file
1806 into which the link is being inserted.
1807 absolute Absolute path, if possible with ~ for home directory.
1808 noabbrev Absolute path, no abbreviation of home directory.
1809 adaptive Use relative path for files in the current directory and sub-
1810 directories of it. For other files, use an absolute path."
1811 :group 'org-link
1812 :type '(choice
1813 (const relative)
1814 (const absolute)
1815 (const noabbrev)
1816 (const adaptive)))
1818 (defvaralias 'org-activate-links 'org-highlight-links)
1819 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1820 "Types of links that should be highlighted in Org-mode files.
1822 This is a list of symbols, each one of them leading to the
1823 highlighting of a certain link type.
1825 You can still open links that are not highlighted.
1827 In principle, it does not hurt to turn on highlighting for all
1828 link types. There may be a small gain when turning off unused
1829 link types. The types are:
1831 bracket The recommended [[link][description]] or [[link]] links with hiding.
1832 angle Links in angular brackets that may contain whitespace like
1833 <bbdb:Carsten Dominik>.
1834 plain Plain links in normal text, no whitespace, like http://google.com.
1835 radio Text that is matched by a radio target, see manual for details.
1836 tag Tag settings in a headline (link to tag search).
1837 date Time stamps (link to calendar).
1838 footnote Footnote labels.
1840 If you set this variable during an Emacs session, use `org-mode-restart'
1841 in the Org buffer so that the change takes effect."
1842 :group 'org-link
1843 :group 'org-appearance
1844 :type '(set :greedy t
1845 (const :tag "Double bracket links" bracket)
1846 (const :tag "Angular bracket links" angle)
1847 (const :tag "Plain text links" plain)
1848 (const :tag "Radio target matches" radio)
1849 (const :tag "Tags" tag)
1850 (const :tag "Timestamps" date)
1851 (const :tag "Footnotes" footnote)))
1853 (defcustom org-make-link-description-function nil
1854 "Function to use for generating link descriptions from links.
1855 When nil, the link location will be used. This function must take
1856 two parameters: the first one is the link, the second one is the
1857 description generated by `org-insert-link'. The function should
1858 return the description to use."
1859 :group 'org-link
1860 :type '(choice (const nil) (function)))
1862 (defgroup org-link-store nil
1863 "Options concerning storing links in Org-mode."
1864 :tag "Org Store Link"
1865 :group 'org-link)
1867 (defcustom org-url-hexify-p t
1868 "When non-nil, hexify URL when creating a link."
1869 :type 'boolean
1870 :version "24.3"
1871 :group 'org-link-store)
1873 (defcustom org-email-link-description-format "Email %c: %.30s"
1874 "Format of the description part of a link to an email or usenet message.
1875 The following %-escapes will be replaced by corresponding information:
1877 %F full \"From\" field
1878 %f name, taken from \"From\" field, address if no name
1879 %T full \"To\" field
1880 %t first name in \"To\" field, address if no name
1881 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1882 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1883 %s subject
1884 %d date
1885 %m message-id.
1887 You may use normal field width specification between the % and the letter.
1888 This is for example useful to limit the length of the subject.
1890 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1891 :group 'org-link-store
1892 :type 'string)
1894 (defcustom org-from-is-user-regexp
1895 (let (r1 r2)
1896 (when (and user-mail-address (not (string= user-mail-address "")))
1897 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1898 (when (and user-full-name (not (string= user-full-name "")))
1899 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1900 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1901 "Regexp matched against the \"From:\" header of an email or usenet message.
1902 It should match if the message is from the user him/herself."
1903 :group 'org-link-store
1904 :type 'regexp)
1906 (defcustom org-context-in-file-links t
1907 "Non-nil means file links from `org-store-link' contain context.
1908 A search string will be added to the file name with :: as separator and
1909 used to find the context when the link is activated by the command
1910 `org-open-at-point'. When this option is t, the entire active region
1911 will be placed in the search string of the file link. If set to a
1912 positive integer, only the first n lines of context will be stored.
1914 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1915 negates this setting for the duration of the command."
1916 :group 'org-link-store
1917 :type '(choice boolean integer))
1919 (defcustom org-keep-stored-link-after-insertion nil
1920 "Non-nil means keep link in list for entire session.
1922 The command `org-store-link' adds a link pointing to the current
1923 location to an internal list. These links accumulate during a session.
1924 The command `org-insert-link' can be used to insert links into any
1925 Org-mode file (offering completion for all stored links). When this
1926 option is nil, every link which has been inserted once using \\[org-insert-link]
1927 will be removed from the list, to make completing the unused links
1928 more efficient."
1929 :group 'org-link-store
1930 :type 'boolean)
1932 (defgroup org-link-follow nil
1933 "Options concerning following links in Org-mode."
1934 :tag "Org Follow Link"
1935 :group 'org-link)
1937 (defcustom org-link-translation-function nil
1938 "Function to translate links with different syntax to Org syntax.
1939 This can be used to translate links created for example by the Planner
1940 or emacs-wiki packages to Org syntax.
1941 The function must accept two parameters, a TYPE containing the link
1942 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1943 which is everything after the link protocol. It should return a cons
1944 with possibly modified values of type and path.
1945 Org contains a function for this, so if you set this variable to
1946 `org-translate-link-from-planner', you should be able follow many
1947 links created by planner."
1948 :group 'org-link-follow
1949 :type '(choice (const nil) (function)))
1951 (defcustom org-follow-link-hook nil
1952 "Hook that is run after a link has been followed."
1953 :group 'org-link-follow
1954 :type 'hook)
1956 (defcustom org-tab-follows-link nil
1957 "Non-nil means on links TAB will follow the link.
1958 Needs to be set before org.el is loaded.
1959 This really should not be used, it does not make sense, and the
1960 implementation is bad."
1961 :group 'org-link-follow
1962 :type 'boolean)
1964 (defcustom org-return-follows-link nil
1965 "Non-nil means on links RET will follow the link.
1966 In tables, the special behavior of RET has precedence."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-mouse-1-follows-link
1971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1972 "Non-nil means mouse-1 on a link will follow the link.
1973 A longer mouse click will still set point. Does not work on XEmacs.
1974 Needs to be set before org.el is loaded."
1975 :group 'org-link-follow
1976 :version "24.4"
1977 :package-version '(Org . "8.3")
1978 :type '(choice
1979 (const :tag "A double click follows the link" double)
1980 (const :tag "Unconditionally follow the link with mouse-1" t)
1981 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1983 (defcustom org-mark-ring-length 4
1984 "Number of different positions to be recorded in the ring.
1985 Changing this requires a restart of Emacs to work correctly."
1986 :group 'org-link-follow
1987 :type 'integer)
1989 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1990 "Non-nil means internal links in Org files must exactly match a headline.
1991 When nil, the link search tries to match a phrase with all words
1992 in the search text."
1993 :group 'org-link-follow
1994 :version "24.1"
1995 :type '(choice
1996 (const :tag "Use fuzzy text search" nil)
1997 (const :tag "Match only exact headline" t)
1998 (const :tag "Match exact headline or query to create it"
1999 query-to-create)))
2001 (defcustom org-link-frame-setup
2002 '((vm . vm-visit-folder-other-frame)
2003 (vm-imap . vm-visit-imap-folder-other-frame)
2004 (gnus . org-gnus-no-new-news)
2005 (file . find-file-other-window)
2006 (wl . wl-other-frame))
2007 "Setup the frame configuration for following links.
2008 When following a link with Emacs, it may often be useful to display
2009 this link in another window or frame. This variable can be used to
2010 set this up for the different types of links.
2011 For VM, use any of
2012 `vm-visit-folder'
2013 `vm-visit-folder-other-window'
2014 `vm-visit-folder-other-frame'
2015 For Gnus, use any of
2016 `gnus'
2017 `gnus-other-frame'
2018 `org-gnus-no-new-news'
2019 For FILE, use any of
2020 `find-file'
2021 `find-file-other-window'
2022 `find-file-other-frame'
2023 For Wanderlust use any of
2024 `wl'
2025 `wl-other-frame'
2026 For the calendar, use the variable `calendar-setup'.
2027 For BBDB, it is currently only possible to display the matches in
2028 another window."
2029 :group 'org-link-follow
2030 :type '(list
2031 (cons (const vm)
2032 (choice
2033 (const vm-visit-folder)
2034 (const vm-visit-folder-other-window)
2035 (const vm-visit-folder-other-frame)))
2036 (cons (const vm-imap)
2037 (choice
2038 (const vm-visit-imap-folder)
2039 (const vm-visit-imap-folder-other-window)
2040 (const vm-visit-imap-folder-other-frame)))
2041 (cons (const gnus)
2042 (choice
2043 (const gnus)
2044 (const gnus-other-frame)
2045 (const org-gnus-no-new-news)))
2046 (cons (const file)
2047 (choice
2048 (const find-file)
2049 (const find-file-other-window)
2050 (const find-file-other-frame)))
2051 (cons (const wl)
2052 (choice
2053 (const wl)
2054 (const wl-other-frame)))))
2056 (defcustom org-display-internal-link-with-indirect-buffer nil
2057 "Non-nil means use indirect buffer to display infile links.
2058 Activating internal links (from one location in a file to another location
2059 in the same file) normally just jumps to the location. When the link is
2060 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2061 is displayed in
2062 another window. When this option is set, the other window actually displays
2063 an indirect buffer clone of the current buffer, to avoid any visibility
2064 changes to the current buffer."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-open-non-existing-files nil
2069 "Non-nil means `org-open-file' will open non-existing files.
2070 When nil, an error will be generated.
2071 This variable applies only to external applications because they
2072 might choke on non-existing files. If the link is to a file that
2073 will be opened in Emacs, the variable is ignored."
2074 :group 'org-link-follow
2075 :type 'boolean)
2077 (defcustom org-open-directory-means-index-dot-org nil
2078 "Non-nil means a link to a directory really means to index.org.
2079 When nil, following a directory link will run dired or open a finder/explorer
2080 window on that directory."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2085 "Non-nil means ask for confirmation before executing shell links.
2086 Shell links can be dangerous: just think about a link
2088 [[shell:rm -rf ~/*][Google Search]]
2090 This link would show up in your Org-mode document as \"Google Search\",
2091 but really it would remove your entire home directory.
2092 Therefore we advise against setting this variable to nil.
2093 Just change it to `y-or-n-p' if you want to confirm with a
2094 single keystroke rather than having to type \"yes\"."
2095 :group 'org-link-follow
2096 :type '(choice
2097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2098 (const :tag "with y-or-n (faster)" y-or-n-p)
2099 (const :tag "no confirmation (dangerous)" nil)))
2100 (put 'org-confirm-shell-link-function
2101 'safe-local-variable
2102 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2104 (defcustom org-confirm-shell-link-not-regexp ""
2105 "A regexp to skip confirmation for shell links."
2106 :group 'org-link-follow
2107 :version "24.1"
2108 :type 'regexp)
2110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2111 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2112 Elisp links can be dangerous: just think about a link
2114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2116 This link would show up in your Org-mode document as \"Google Search\",
2117 but really it would remove your entire home directory.
2118 Therefore we advise against setting this variable to nil.
2119 Just change it to `y-or-n-p' if you want to confirm with a
2120 single keystroke rather than having to type \"yes\"."
2121 :group 'org-link-follow
2122 :type '(choice
2123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2124 (const :tag "with y-or-n (faster)" y-or-n-p)
2125 (const :tag "no confirmation (dangerous)" nil)))
2126 (put 'org-confirm-shell-link-function
2127 'safe-local-variable
2128 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2130 (defcustom org-confirm-elisp-link-not-regexp ""
2131 "A regexp to skip confirmation for Elisp links."
2132 :group 'org-link-follow
2133 :version "24.1"
2134 :type 'regexp)
2136 (defconst org-file-apps-defaults-gnu
2137 '((remote . emacs)
2138 (system . mailcap)
2139 (t . mailcap))
2140 "Default file applications on a UNIX or GNU/Linux system.
2141 See `org-file-apps'.")
2143 (defconst org-file-apps-defaults-macosx
2144 '((remote . emacs)
2145 (system . "open %s")
2146 ("ps.gz" . "gv %s")
2147 ("eps.gz" . "gv %s")
2148 ("dvi" . "xdvi %s")
2149 ("fig" . "xfig %s")
2150 (t . "open %s"))
2151 "Default file applications on a MacOS X system.
2152 The system \"open\" is known as a default, but we use X11 applications
2153 for some files for which the OS does not have a good default.
2154 See `org-file-apps'.")
2156 (defconst org-file-apps-defaults-windowsnt
2157 (list '(remote . emacs)
2158 (cons 'system (lambda (file _path)
2159 (with-no-warnings (w32-shell-execute "open" file))))
2160 (cons t (lambda (file _path)
2161 (with-no-warnings (w32-shell-execute "open" file)))))
2162 "Default file applications on a Windows NT system.
2163 The system \"open\" is used for most files.
2164 See `org-file-apps'.")
2166 (defcustom org-file-apps
2167 '((auto-mode . emacs)
2168 ("\\.mm\\'" . default)
2169 ("\\.x?html?\\'" . default)
2170 ("\\.pdf\\'" . default))
2171 "External applications for opening `file:path' items in a document.
2172 \\<org-mode-map>\
2173 Org mode uses system defaults for different file types, but
2174 you can use this variable to set the application for a given file
2175 extension. The entries in this list are cons cells where the car identifies
2176 files and the cdr the corresponding command. Possible values for the
2177 file identifier are
2178 \"string\" A string as a file identifier can be interpreted in different
2179 ways, depending on its contents:
2181 - Alphanumeric characters only:
2182 Match links with this file extension.
2183 Example: (\"pdf\" . \"evince %s\")
2184 to open PDFs with evince.
2186 - Regular expression: Match links where the
2187 filename matches the regexp. If you want to
2188 use groups here, use shy groups.
2190 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2191 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2192 to open *.html and *.xhtml with firefox.
2194 - Regular expression which contains (non-shy) groups:
2195 Match links where the whole link, including \"::\", and
2196 anything after that, matches the regexp.
2197 In a custom command string, %1, %2, etc. are replaced with
2198 the parts of the link that were matched by the groups.
2199 For backwards compatibility, if a command string is given
2200 that does not use any of the group matches, this case is
2201 handled identically to the second one (i.e. match against
2202 file name only).
2203 In a custom function, you can access the group matches with
2204 \(match-string n link).
2206 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2207 to open [[file:document.pdf::5]] with evince at page 5.
2209 `directory' Matches a directory
2210 `remote' Matches a remote file, accessible through tramp or efs.
2211 Remote files most likely should be visited through Emacs
2212 because external applications cannot handle such paths.
2213 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2214 so all files Emacs knows how to handle. Using this with
2215 command `emacs' will open most files in Emacs. Beware that this
2216 will also open html files inside Emacs, unless you add
2217 \(\"html\" . default) to the list as well.
2218 `system' The system command to open files, like `open' on Windows
2219 and Mac OS X, and mailcap under GNU/Linux. This is the command
2220 that will be selected if you call \\[org-open-at-point] with a double
2221 \\[universal-argument] \\[universal-argument] prefix.
2222 t Default for files not matched by any of the other options.
2224 Possible values for the command are:
2225 `emacs' The file will be visited by the current Emacs process.
2226 `default' Use the default application for this file type, which is the
2227 association for t in the list, most likely in the system-specific
2228 part. This can be used to overrule an unwanted setting in the
2229 system-specific variable.
2230 `system' Use the system command for opening files, like \"open\".
2231 This command is specified by the entry whose car is `system'.
2232 Most likely, the system-specific version of this variable
2233 does define this command, but you can overrule/replace it
2234 here.
2235 `mailcap' Use command specified in the mailcaps.
2236 string A command to be executed by a shell; %s will be replaced
2237 by the path to the file.
2239 function A Lisp function, which will be called with two arguments:
2240 the file path and the original link string, without the
2241 \"file:\" prefix.
2243 For more examples, see the system specific constants
2244 `org-file-apps-defaults-macosx'
2245 `org-file-apps-defaults-windowsnt'
2246 `org-file-apps-defaults-gnu'."
2247 :group 'org-link-follow
2248 :type '(repeat
2249 (cons (choice :value ""
2250 (string :tag "Extension")
2251 (const :tag "System command to open files" system)
2252 (const :tag "Default for unrecognized files" t)
2253 (const :tag "Remote file" remote)
2254 (const :tag "Links to a directory" directory)
2255 (const :tag "Any files that have Emacs modes"
2256 auto-mode))
2257 (choice :value ""
2258 (const :tag "Visit with Emacs" emacs)
2259 (const :tag "Use default" default)
2260 (const :tag "Use the system command" system)
2261 (string :tag "Command")
2262 (function :tag "Function")))))
2264 (defcustom org-doi-server-url "http://dx.doi.org/"
2265 "The URL of the DOI server."
2266 :type 'string
2267 :version "24.3"
2268 :group 'org-link-follow)
2270 (defgroup org-refile nil
2271 "Options concerning refiling entries in Org-mode."
2272 :tag "Org Refile"
2273 :group 'org)
2275 (defcustom org-directory "~/org"
2276 "Directory with Org files.
2277 This is just a default location to look for Org files. There is no need
2278 at all to put your files into this directory. It is used in the
2279 following situations:
2281 1. When a capture template specifies a target file that is not an
2282 absolute path. The path will then be interpreted relative to
2283 `org-directory'
2284 2. When the value of variable `org-agenda-files' is a single file, any
2285 relative paths in this file will be taken as relative to
2286 `org-directory'."
2287 :group 'org-refile
2288 :group 'org-capture
2289 :type 'directory)
2291 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2292 "Default target for storing notes.
2293 Used as a fall back file for org-capture.el, for templates that
2294 do not specify a target file."
2295 :group 'org-refile
2296 :group 'org-capture
2297 :type 'file)
2299 (defcustom org-goto-interface 'outline
2300 "The default interface to be used for `org-goto'.
2301 Allowed values are:
2302 outline The interface shows an outline of the relevant file
2303 and the correct heading is found by moving through
2304 the outline or by searching with incremental search.
2305 outline-path-completion Headlines in the current buffer are offered via
2306 completion. This is the interface also used by
2307 the refile command."
2308 :group 'org-refile
2309 :type '(choice
2310 (const :tag "Outline" outline)
2311 (const :tag "Outline-path-completion" outline-path-completion)))
2313 (defcustom org-goto-max-level 5
2314 "Maximum target level when running `org-goto' with refile interface."
2315 :group 'org-refile
2316 :type 'integer)
2318 (defcustom org-reverse-note-order nil
2319 "Non-nil means store new notes at the beginning of a file or entry.
2320 When nil, new notes will be filed to the end of a file or entry.
2321 This can also be a list with cons cells of regular expressions that
2322 are matched against file names, and values."
2323 :group 'org-capture
2324 :group 'org-refile
2325 :type '(choice
2326 (const :tag "Reverse always" t)
2327 (const :tag "Reverse never" nil)
2328 (repeat :tag "By file name regexp"
2329 (cons regexp boolean))))
2331 (defcustom org-log-refile nil
2332 "Information to record when a task is refiled.
2334 Possible values are:
2336 nil Don't add anything
2337 time Add a time stamp to the task
2338 note Prompt for a note and add it with template `org-log-note-headings'
2340 This option can also be set with on a per-file-basis with
2342 #+STARTUP: nologrefile
2343 #+STARTUP: logrefile
2344 #+STARTUP: lognoterefile
2346 You can have local logging settings for a subtree by setting the LOGGING
2347 property to one or more of these keywords.
2349 When bulk-refiling from the agenda, the value `note' is forbidden and
2350 will temporarily be changed to `time'."
2351 :group 'org-refile
2352 :group 'org-progress
2353 :version "24.1"
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record timestamp" time)
2357 (const :tag "Record timestamp with note." note)))
2359 (defcustom org-refile-targets nil
2360 "Targets for refiling entries with \\[org-refile].
2361 This is a list of cons cells. Each cell contains:
2362 - a specification of the files to be considered, either a list of files,
2363 or a symbol whose function or variable value will be used to retrieve
2364 a file name or a list of file names. If you use `org-agenda-files' for
2365 that, all agenda files will be scanned for targets. Nil means consider
2366 headings in the current buffer.
2367 - A specification of how to find candidate refile targets. This may be
2368 any of:
2369 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2370 This tag has to be present in all target headlines, inheritance will
2371 not be considered.
2372 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2373 todo keyword.
2374 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2375 headlines that are refiling targets.
2376 - a cons cell (:level . N). Any headline of level N is considered a target.
2377 Note that, when `org-odd-levels-only' is set, level corresponds to
2378 order in hierarchy, not to the number of stars.
2379 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2383 Each element of this list generates a set of possible targets.
2384 The union of these sets is presented (with completion) to
2385 the user by `org-refile'.
2387 You can set the variable `org-refile-target-verify-function' to a function
2388 to verify each headline found by the simple criteria above.
2390 When this variable is nil, all top-level headlines in the current buffer
2391 are used, equivalent to the value `((nil . (:level . 1))'."
2392 :group 'org-refile
2393 :type '(repeat
2394 (cons
2395 (choice :value org-agenda-files
2396 (const :tag "All agenda files" org-agenda-files)
2397 (const :tag "Current buffer" nil)
2398 (function) (variable) (file))
2399 (choice :tag "Identify target headline by"
2400 (cons :tag "Specific tag" (const :value :tag) (string))
2401 (cons :tag "TODO keyword" (const :value :todo) (string))
2402 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2403 (cons :tag "Level number" (const :value :level) (integer))
2404 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2406 (defcustom org-refile-target-verify-function nil
2407 "Function to verify if the headline at point should be a refile target.
2408 The function will be called without arguments, with point at the
2409 beginning of the headline. It should return t and leave point
2410 where it is if the headline is a valid target for refiling.
2412 If the target should not be selected, the function must return nil.
2413 In addition to this, it may move point to a place from where the search
2414 should be continued. For example, the function may decide that the entire
2415 subtree of the current entry should be excluded and move point to the end
2416 of the subtree."
2417 :group 'org-refile
2418 :type '(choice
2419 (const nil)
2420 (function)))
2422 (defcustom org-refile-use-cache nil
2423 "Non-nil means cache refile targets to speed up the process.
2424 \\<org-mode-map>\
2425 The cache for a particular file will be updated automatically when
2426 the buffer has been killed, or when any of the marker used for flagging
2427 refile targets no longer points at a live buffer.
2428 If you have added new entries to a buffer that might themselves be targets,
2429 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2430 if you find that easier, \
2431 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2432 \\[org-refile]'."
2433 :group 'org-refile
2434 :version "24.1"
2435 :type 'boolean)
2437 (defcustom org-refile-use-outline-path nil
2438 "Non-nil means provide refile targets as paths.
2439 So a level 3 headline will be available as level1/level2/level3.
2441 When the value is `file', also include the file name (without directory)
2442 into the path. In this case, you can also stop the completion after
2443 the file name, to get entries inserted as top level in the file.
2445 When `full-file-path', include the full file path."
2446 :group 'org-refile
2447 :type '(choice
2448 (const :tag "Not" nil)
2449 (const :tag "Yes" t)
2450 (const :tag "Start with file name" file)
2451 (const :tag "Start with full file path" full-file-path)))
2453 (defcustom org-outline-path-complete-in-steps t
2454 "Non-nil means complete the outline path in hierarchical steps.
2455 When Org-mode uses the refile interface to select an outline path
2456 \(see variable `org-refile-use-outline-path'), the completion of
2457 the path can be done in a single go, or it can be done in steps down
2458 the headline hierarchy. Going in steps is probably the best if you
2459 do not use a special completion package like `ido' or `icicles'.
2460 However, when using these packages, going in one step can be very
2461 fast, while still showing the whole path to the entry."
2462 :group 'org-refile
2463 :type 'boolean)
2465 (defcustom org-refile-allow-creating-parent-nodes nil
2466 "Non-nil means allow the creation of new nodes as refile targets.
2467 New nodes are then created by adding \"/new node name\" to the completion
2468 of an existing node. When the value of this variable is `confirm',
2469 new node creation must be confirmed by the user (recommended).
2470 When nil, the completion must match an existing entry.
2472 Note that, if the new heading is not seen by the criteria
2473 listed in `org-refile-targets', multiple instances of the same
2474 heading would be created by trying again to file under the new
2475 heading."
2476 :group 'org-refile
2477 :type '(choice
2478 (const :tag "Never" nil)
2479 (const :tag "Always" t)
2480 (const :tag "Prompt for confirmation" confirm)))
2482 (defcustom org-refile-active-region-within-subtree nil
2483 "Non-nil means also refile active region within a subtree.
2485 By default `org-refile' doesn't allow refiling regions if they
2486 don't contain a set of subtrees, but it might be convenient to
2487 do so sometimes: in that case, the first line of the region is
2488 converted to a headline before refiling."
2489 :group 'org-refile
2490 :version "24.1"
2491 :type 'boolean)
2493 (defgroup org-todo nil
2494 "Options concerning TODO items in Org-mode."
2495 :tag "Org TODO"
2496 :group 'org)
2498 (defgroup org-progress nil
2499 "Options concerning Progress logging in Org-mode."
2500 :tag "Org Progress"
2501 :group 'org-time)
2503 (defvar org-todo-interpretation-widgets
2504 '((:tag "Sequence (cycling hits every state)" sequence)
2505 (:tag "Type (cycling directly to DONE)" type))
2506 "The available interpretation symbols for customizing `org-todo-keywords'.
2507 Interested libraries should add to this list.")
2509 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2510 "List of TODO entry keyword sequences and their interpretation.
2511 \\<org-mode-map>This is a list of sequences.
2513 Each sequence starts with a symbol, either `sequence' or `type',
2514 indicating if the keywords should be interpreted as a sequence of
2515 action steps, or as different types of TODO items. The first
2516 keywords are states requiring action - these states will select a headline
2517 for inclusion into the global TODO list Org-mode produces. If one of
2518 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2519 signify that no further action is necessary. If \"|\" is not found,
2520 the last keyword is treated as the only DONE state of the sequence.
2522 The command \\[org-todo] cycles an entry through these states, and one
2523 additional state where no keyword is present. For details about this
2524 cycling, see the manual.
2526 TODO keywords and interpretation can also be set on a per-file basis with
2527 the special #+SEQ_TODO and #+TYP_TODO lines.
2529 Each keyword can optionally specify a character for fast state selection
2530 \(in combination with the variable `org-use-fast-todo-selection')
2531 and specifiers for state change logging, using the same syntax that
2532 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2533 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2534 indicates to record a time stamp each time this state is selected.
2536 Each keyword may also specify if a timestamp or a note should be
2537 recorded when entering or leaving the state, by adding additional
2538 characters in the parenthesis after the keyword. This looks like this:
2539 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2540 record only the time of the state change. With X and Y being either
2541 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2542 Y when leaving the state if and only if the *target* state does not
2543 define X. You may omit any of the fast-selection key or X or /Y,
2544 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2546 For backward compatibility, this variable may also be just a list
2547 of keywords. In this case the interpretation (sequence or type) will be
2548 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice
2552 (repeat :tag "Old syntax, just keywords"
2553 (string :tag "Keyword"))
2554 (repeat :tag "New syntax"
2555 (cons
2556 (choice
2557 :tag "Interpretation"
2558 ;;Quick and dirty way to see
2559 ;;`org-todo-interpretations'. This takes the
2560 ;;place of item arguments
2561 :convert-widget
2562 (lambda (widget)
2563 (widget-put widget
2564 :args (mapcar
2565 (lambda (x)
2566 (widget-convert
2567 (cons 'const x)))
2568 org-todo-interpretation-widgets))
2569 widget))
2570 (repeat
2571 (string :tag "Keyword"))))))
2573 (defvar-local org-todo-keywords-1 nil
2574 "All TODO and DONE keywords active in a buffer.")
2575 (defvar org-todo-keywords-for-agenda nil)
2576 (defvar org-done-keywords-for-agenda nil)
2577 (defvar org-todo-keyword-alist-for-agenda nil)
2578 (defvar org-tag-alist-for-agenda nil
2579 "Alist of all tags from all agenda files.")
2580 (defvar org-tag-groups-alist-for-agenda nil
2581 "Alist of all groups tags from all current agenda files.")
2582 (defvar-local org-tag-groups-alist nil)
2583 (defvar org-agenda-contributing-files nil)
2584 (defvar-local org-not-done-keywords nil)
2585 (defvar-local org-done-keywords nil)
2586 (defvar-local org-todo-heads nil)
2587 (defvar-local org-todo-sets nil)
2588 (defvar-local org-todo-log-states nil)
2589 (defvar-local org-todo-kwd-alist nil)
2590 (defvar-local org-todo-key-alist nil)
2591 (defvar-local org-todo-key-trigger nil)
2593 (defcustom org-todo-interpretation 'sequence
2594 "Controls how TODO keywords are interpreted.
2595 This variable is in principle obsolete and is only used for
2596 backward compatibility, if the interpretation of todo keywords is
2597 not given already in `org-todo-keywords'. See that variable for
2598 more information."
2599 :group 'org-todo
2600 :group 'org-keywords
2601 :type '(choice (const sequence)
2602 (const type)))
2604 (defcustom org-use-fast-todo-selection t
2605 "\\<org-mode-map>\
2606 Non-nil means use the fast todo selection scheme with \\[org-todo].
2607 This variable describes if and under what circumstances the cycling
2608 mechanism for TODO keywords will be replaced by a single-key, direct
2609 selection scheme.
2611 When nil, fast selection is never used.
2613 When the symbol `prefix', it will be used when `org-todo' is called
2614 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2615 in an Org-mode buffer, and
2616 `\\[universal-argument] t' in an agenda buffer.
2618 When t, fast selection is used by default. In this case, the prefix
2619 argument forces cycling instead.
2621 In all cases, the special interface is only used if access keys have
2622 actually been assigned by the user, i.e. if keywords in the configuration
2623 are followed by a letter in parenthesis, like TODO(t)."
2624 :group 'org-todo
2625 :type '(choice
2626 (const :tag "Never" nil)
2627 (const :tag "By default" t)
2628 (const :tag "Only with C-u C-c C-t" prefix)))
2630 (defcustom org-provide-todo-statistics t
2631 "Non-nil means update todo statistics after insert and toggle.
2632 ALL-HEADLINES means update todo statistics by including headlines
2633 with no TODO keyword as well, counting them as not done.
2634 A list of TODO keywords means the same, but skip keywords that are
2635 not in this list.
2636 When set to a list of two lists, the first list contains keywords
2637 to consider as TODO keywords, the second list contains keywords
2638 to consider as DONE keywords.
2640 When this is set, todo statistics is updated in the parent of the
2641 current entry each time a todo state is changed."
2642 :group 'org-todo
2643 :type '(choice
2644 (const :tag "Yes, only for TODO entries" t)
2645 (const :tag "Yes, including all entries" all-headlines)
2646 (repeat :tag "Yes, for TODOs in this list"
2647 (string :tag "TODO keyword"))
2648 (list :tag "Yes, for TODOs and DONEs in these lists"
2649 (repeat (string :tag "TODO keyword"))
2650 (repeat (string :tag "DONE keyword")))
2651 (other :tag "No TODO statistics" nil)))
2653 (defcustom org-hierarchical-todo-statistics t
2654 "Non-nil means TODO statistics covers just direct children.
2655 When nil, all entries in the subtree are considered.
2656 This has only an effect if `org-provide-todo-statistics' is set.
2657 To set this to nil for only a single subtree, use a COOKIE_DATA
2658 property and include the word \"recursive\" into the value."
2659 :group 'org-todo
2660 :type 'boolean)
2662 (defcustom org-after-todo-state-change-hook nil
2663 "Hook which is run after the state of a TODO item was changed.
2664 The new state (a string with a TODO keyword, or nil) is available in the
2665 Lisp variable `org-state'."
2666 :group 'org-todo
2667 :type 'hook)
2669 (defvar org-blocker-hook nil
2670 "Hook for functions that are allowed to block a state change.
2672 Functions in this hook should not modify the buffer.
2673 Each function gets as its single argument a property list,
2674 see `org-trigger-hook' for more information about this list.
2676 If any of the functions in this hook returns nil, the state change
2677 is blocked.")
2679 (defvar org-trigger-hook nil
2680 "Hook for functions that are triggered by a state change.
2682 Each function gets as its single argument a property list with at
2683 least the following elements:
2685 (:type type-of-change :position pos-at-entry-start
2686 :from old-state :to new-state)
2688 Depending on the type, more properties may be present.
2690 This mechanism is currently implemented for:
2692 TODO state changes
2693 ------------------
2694 :type todo-state-change
2695 :from previous state (keyword as a string), or nil, or a symbol
2696 `todo' or `done', to indicate the general type of state.
2697 :to new state, like in :from")
2699 (defcustom org-enforce-todo-dependencies nil
2700 "Non-nil means undone TODO entries will block switching the parent to DONE.
2701 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2702 be blocked if any prior sibling is not yet done.
2703 Finally, if the parent is blocked because of ordered siblings of its own,
2704 the child will also be blocked."
2705 :set (lambda (var val)
2706 (set var val)
2707 (if val
2708 (add-hook 'org-blocker-hook
2709 'org-block-todo-from-children-or-siblings-or-parent)
2710 (remove-hook 'org-blocker-hook
2711 'org-block-todo-from-children-or-siblings-or-parent)))
2712 :group 'org-todo
2713 :type 'boolean)
2715 (defcustom org-enforce-todo-checkbox-dependencies nil
2716 "Non-nil means unchecked boxes will block switching the parent to DONE.
2717 When this is nil, checkboxes have no influence on switching TODO states.
2718 When non-nil, you first need to check off all check boxes before the TODO
2719 entry can be switched to DONE.
2720 This variable needs to be set before org.el is loaded, and you need to
2721 restart Emacs after a change to make the change effective. The only way
2722 to change is while Emacs is running is through the customize interface."
2723 :set (lambda (var val)
2724 (set var val)
2725 (if val
2726 (add-hook 'org-blocker-hook
2727 'org-block-todo-from-checkboxes)
2728 (remove-hook 'org-blocker-hook
2729 'org-block-todo-from-checkboxes)))
2730 :group 'org-todo
2731 :type 'boolean)
2733 (defcustom org-treat-insert-todo-heading-as-state-change nil
2734 "Non-nil means inserting a TODO heading is treated as state change.
2735 So when the command \\[org-insert-todo-heading] is used, state change
2736 logging will apply if appropriate. When nil, the new TODO item will
2737 be inserted directly, and no logging will take place."
2738 :group 'org-todo
2739 :type 'boolean)
2741 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2742 "Non-nil means switching TODO states with S-cursor counts as state change.
2743 This is the default behavior. However, setting this to nil allows a
2744 convenient way to select a TODO state and bypass any logging associated
2745 with that."
2746 :group 'org-todo
2747 :type 'boolean)
2749 (defcustom org-todo-state-tags-triggers nil
2750 "Tag changes that should be triggered by TODO state changes.
2751 This is a list. Each entry is
2753 (state-change (tag . flag) .......)
2755 State-change can be a string with a state, and empty string to indicate the
2756 state that has no TODO keyword, or it can be one of the symbols `todo'
2757 or `done', meaning any not-done or done state, respectively."
2758 :group 'org-todo
2759 :group 'org-tags
2760 :type '(repeat
2761 (cons (choice :tag "When changing to"
2762 (const :tag "Not-done state" todo)
2763 (const :tag "Done state" done)
2764 (string :tag "State"))
2765 (repeat
2766 (cons :tag "Tag action"
2767 (string :tag "Tag")
2768 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2770 (defcustom org-log-done nil
2771 "Information to record when a task moves to the DONE state.
2773 Possible values are:
2775 nil Don't add anything, just change the keyword
2776 time Add a time stamp to the task
2777 note Prompt for a note and add it with template `org-log-note-headings'
2779 This option can also be set with on a per-file-basis with
2781 #+STARTUP: nologdone
2782 #+STARTUP: logdone
2783 #+STARTUP: lognotedone
2785 You can have local logging settings for a subtree by setting the LOGGING
2786 property to one or more of these keywords."
2787 :group 'org-todo
2788 :group 'org-progress
2789 :type '(choice
2790 (const :tag "No logging" nil)
2791 (const :tag "Record CLOSED timestamp" time)
2792 (const :tag "Record CLOSED timestamp with note." note)))
2794 ;; Normalize old uses of org-log-done.
2795 (cond
2796 ((eq org-log-done t) (setq org-log-done 'time))
2797 ((and (listp org-log-done) (memq 'done org-log-done))
2798 (setq org-log-done 'note)))
2800 (defcustom org-log-reschedule nil
2801 "Information to record when the scheduling date of a tasks is modified.
2803 Possible values are:
2805 nil Don't add anything, just change the date
2806 time Add a time stamp to the task
2807 note Prompt for a note and add it with template `org-log-note-headings'
2809 This option can also be set with on a per-file-basis with
2811 #+STARTUP: nologreschedule
2812 #+STARTUP: logreschedule
2813 #+STARTUP: lognotereschedule"
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(choice
2817 (const :tag "No logging" nil)
2818 (const :tag "Record timestamp" time)
2819 (const :tag "Record timestamp with note." note)))
2821 (defcustom org-log-redeadline nil
2822 "Information to record when the deadline date of a tasks is modified.
2824 Possible values are:
2826 nil Don't add anything, just change the date
2827 time Add a time stamp to the task
2828 note Prompt for a note and add it with template `org-log-note-headings'
2830 This option can also be set with on a per-file-basis with
2832 #+STARTUP: nologredeadline
2833 #+STARTUP: logredeadline
2834 #+STARTUP: lognoteredeadline
2836 You can have local logging settings for a subtree by setting the LOGGING
2837 property to one or more of these keywords."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(choice
2841 (const :tag "No logging" nil)
2842 (const :tag "Record timestamp" time)
2843 (const :tag "Record timestamp with note." note)))
2845 (defcustom org-log-note-clock-out nil
2846 "Non-nil means record a note when clocking out of an item.
2847 This can also be configured on a per-file basis by adding one of
2848 the following lines anywhere in the buffer:
2850 #+STARTUP: lognoteclock-out
2851 #+STARTUP: nolognoteclock-out"
2852 :group 'org-todo
2853 :group 'org-progress
2854 :type 'boolean)
2856 (defcustom org-log-done-with-time t
2857 "Non-nil means the CLOSED time stamp will contain date and time.
2858 When nil, only the date will be recorded."
2859 :group 'org-progress
2860 :type 'boolean)
2862 (defcustom org-log-note-headings
2863 '((done . "CLOSING NOTE %t")
2864 (state . "State %-12s from %-12S %t")
2865 (note . "Note taken on %t")
2866 (reschedule . "Rescheduled from %S on %t")
2867 (delschedule . "Not scheduled, was %S on %t")
2868 (redeadline . "New deadline from %S on %t")
2869 (deldeadline . "Removed deadline, was %S on %t")
2870 (refile . "Refiled on %t")
2871 (clock-out . ""))
2872 "Headings for notes added to entries.
2874 The value is an alist, with the car being a symbol indicating the
2875 note context, and the cdr is the heading to be used. The heading
2876 may also be the empty string. The following placeholders can be
2877 used:
2879 %t a time stamp.
2880 %T an active time stamp instead the default inactive one
2881 %d a short-format time stamp.
2882 %D an active short-format time stamp.
2883 %s the new TODO state or time stamp (inactive), in double quotes.
2884 %S the old TODO state or time stamp (inactive), in double quotes.
2885 %u the user name.
2886 %U full user name.
2888 In fact, it is not a good idea to change the `state' entry,
2889 because Agenda Log mode depends on the format of these entries."
2890 :group 'org-todo
2891 :group 'org-progress
2892 :type '(list :greedy t
2893 (cons (const :tag "Heading when closing an item" done) string)
2894 (cons (const :tag
2895 "Heading when changing todo state (todo sequence only)"
2896 state) string)
2897 (cons (const :tag "Heading when just taking a note" note) string)
2898 (cons (const :tag "Heading when rescheduling" reschedule) string)
2899 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2900 (cons (const :tag "Heading when changing deadline" redeadline) string)
2901 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2902 (cons (const :tag "Heading when refiling" refile) string)
2903 (cons (const :tag "Heading when clocking out" clock-out) string)))
2905 (unless (assq 'note org-log-note-headings)
2906 (push '(note . "%t") org-log-note-headings))
2908 (defcustom org-log-into-drawer nil
2909 "Non-nil means insert state change notes and time stamps into a drawer.
2910 When nil, state changes notes will be inserted after the headline and
2911 any scheduling and clock lines, but not inside a drawer.
2913 The value of this variable should be the name of the drawer to use.
2914 LOGBOOK is proposed as the default drawer for this purpose, you can
2915 also set this to a string to define the drawer of your choice.
2917 A value of t is also allowed, representing \"LOGBOOK\".
2919 A value of t or nil can also be set with on a per-file-basis with
2921 #+STARTUP: logdrawer
2922 #+STARTUP: nologdrawer
2924 If this variable is set, `org-log-state-notes-insert-after-drawers'
2925 will be ignored.
2927 You can set the property LOG_INTO_DRAWER to overrule this setting for
2928 a subtree.
2930 Do not check directly this variable in a Lisp program. Call
2931 function `org-log-into-drawer' instead."
2932 :group 'org-todo
2933 :group 'org-progress
2934 :type '(choice
2935 (const :tag "Not into a drawer" nil)
2936 (const :tag "LOGBOOK" t)
2937 (string :tag "Other")))
2939 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2941 (defun org-log-into-drawer ()
2942 "Name of the log drawer, as a string, or nil.
2943 This is the value of `org-log-into-drawer'. However, if the
2944 current entry has or inherits a LOG_INTO_DRAWER property, it will
2945 be used instead of the default value."
2946 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2947 (cond ((equal p "nil") nil)
2948 ((equal p "t") "LOGBOOK")
2949 ((stringp p) p)
2950 (p "LOGBOOK")
2951 ((stringp org-log-into-drawer) org-log-into-drawer)
2952 (org-log-into-drawer "LOGBOOK"))))
2954 (defcustom org-log-state-notes-insert-after-drawers nil
2955 "Non-nil means insert state change notes after any drawers in entry.
2956 Only the drawers that *immediately* follow the headline and the
2957 deadline/scheduled line are skipped.
2958 When nil, insert notes right after the heading and perhaps the line
2959 with deadline/scheduling if present.
2961 This variable will have no effect if `org-log-into-drawer' is
2962 set."
2963 :group 'org-todo
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-states-order-reversed t
2968 "Non-nil means the latest state note will be directly after heading.
2969 When nil, the state change notes will be ordered according to time.
2971 This option can also be set with on a per-file-basis with
2973 #+STARTUP: logstatesreversed
2974 #+STARTUP: nologstatesreversed"
2975 :group 'org-todo
2976 :group 'org-progress
2977 :type 'boolean)
2979 (defcustom org-todo-repeat-to-state nil
2980 "The TODO state to which a repeater should return the repeating task.
2981 By default this is the first task in a TODO sequence, or the previous state
2982 in a TODO_TYP set. But you can specify another task here.
2983 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2984 :group 'org-todo
2985 :version "24.1"
2986 :type '(choice (const :tag "Head of sequence" nil)
2987 (string :tag "Specific state")))
2989 (defcustom org-log-repeat 'time
2990 "Non-nil means record moving through the DONE state when triggering repeat.
2991 An auto-repeating task is immediately switched back to TODO when
2992 marked DONE. If you are not logging state changes (by adding \"@\"
2993 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2994 record a closing note, there will be no record of the task moving
2995 through DONE. This variable forces taking a note anyway.
2997 nil Don't force a record
2998 time Record a time stamp
2999 note Prompt for a note and add it with template `org-log-note-headings'
3001 This option can also be set with on a per-file-basis with
3003 #+STARTUP: nologrepeat
3004 #+STARTUP: logrepeat
3005 #+STARTUP: lognoterepeat
3007 You can have local logging settings for a subtree by setting the LOGGING
3008 property to one or more of these keywords."
3009 :group 'org-todo
3010 :group 'org-progress
3011 :type '(choice
3012 (const :tag "Don't force a record" nil)
3013 (const :tag "Force recording the DONE state" time)
3014 (const :tag "Force recording a note with the DONE state" note)))
3017 (defgroup org-priorities nil
3018 "Priorities in Org-mode."
3019 :tag "Org Priorities"
3020 :group 'org-todo)
3022 (defcustom org-enable-priority-commands t
3023 "Non-nil means priority commands are active.
3024 When nil, these commands will be disabled, so that you never accidentally
3025 set a priority."
3026 :group 'org-priorities
3027 :type 'boolean)
3029 (defcustom org-highest-priority ?A
3030 "The highest priority of TODO items. A character like ?A, ?B etc.
3031 Must have a smaller ASCII number than `org-lowest-priority'."
3032 :group 'org-priorities
3033 :type 'character)
3035 (defcustom org-lowest-priority ?C
3036 "The lowest priority of TODO items. A character like ?A, ?B etc.
3037 Must have a larger ASCII number than `org-highest-priority'."
3038 :group 'org-priorities
3039 :type 'character)
3041 (defcustom org-default-priority ?B
3042 "The default priority of TODO items.
3043 This is the priority an item gets if no explicit priority is given.
3044 When starting to cycle on an empty priority the first step in the cycle
3045 depends on `org-priority-start-cycle-with-default'. The resulting first
3046 step priority must not exceed the range from `org-highest-priority' to
3047 `org-lowest-priority' which means that `org-default-priority' has to be
3048 in this range exclusive or inclusive the range boundaries. Else the
3049 first step refuses to set the default and the second will fall back
3050 to (depending on the command used) the highest or lowest priority."
3051 :group 'org-priorities
3052 :type 'character)
3054 (defcustom org-priority-start-cycle-with-default t
3055 "Non-nil means start with default priority when starting to cycle.
3056 When this is nil, the first step in the cycle will be (depending on the
3057 command used) one higher or lower than the default priority.
3058 See also `org-default-priority'."
3059 :group 'org-priorities
3060 :type 'boolean)
3062 (defcustom org-get-priority-function nil
3063 "Function to extract the priority from a string.
3064 The string is normally the headline. If this is nil Org computes the
3065 priority from the priority cookie like [#A] in the headline. It returns
3066 an integer, increasing by 1000 for each priority level.
3067 The user can set a different function here, which should take a string
3068 as an argument and return the numeric priority."
3069 :group 'org-priorities
3070 :version "24.1"
3071 :type '(choice
3072 (const nil)
3073 (function)))
3075 (defgroup org-time nil
3076 "Options concerning time stamps and deadlines in Org-mode."
3077 :tag "Org Time"
3078 :group 'org)
3080 (defcustom org-time-stamp-rounding-minutes '(0 5)
3081 "Number of minutes to round time stamps to.
3082 \\<org-mode-map>\
3083 These are two values, the first applies when first creating a time stamp.
3084 The second applies when changing it with the commands `S-up' and `S-down'.
3085 When changing the time stamp, this means that it will change in steps
3086 of N minutes, as given by the second value.
3088 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3089 numbers should be factors of 60, so for example 5, 10, 15.
3091 When this is larger than 1, you can still force an exact time stamp by using
3092 a double prefix argument to a time stamp command like \
3093 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3094 and by using a prefix arg to `S-up/down' to specify the exact number
3095 of minutes to shift."
3096 :group 'org-time
3097 :get (lambda (var) ; Make sure both elements are there
3098 (if (integerp (default-value var))
3099 (list (default-value var) 5)
3100 (default-value var)))
3101 :type '(list
3102 (integer :tag "when inserting times")
3103 (integer :tag "when modifying times")))
3105 ;; Normalize old customizations of this variable.
3106 (when (integerp org-time-stamp-rounding-minutes)
3107 (setq org-time-stamp-rounding-minutes
3108 (list org-time-stamp-rounding-minutes
3109 org-time-stamp-rounding-minutes)))
3111 (defcustom org-display-custom-times nil
3112 "Non-nil means overlay custom formats over all time stamps.
3113 The formats are defined through the variable `org-time-stamp-custom-formats'.
3114 To turn this on on a per-file basis, insert anywhere in the file:
3115 #+STARTUP: customtime"
3116 :group 'org-time
3117 :set 'set-default
3118 :type 'sexp)
3119 (make-variable-buffer-local 'org-display-custom-times)
3121 (defcustom org-time-stamp-custom-formats
3122 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3123 "Custom formats for time stamps. See `format-time-string' for the syntax.
3124 These are overlaid over the default ISO format if the variable
3125 `org-display-custom-times' is set. Time like %H:%M should be at the
3126 end of the second format. The custom formats are also honored by export
3127 commands, if custom time display is turned on at the time of export."
3128 :group 'org-time
3129 :type 'sexp)
3131 (defun org-time-stamp-format (&optional long inactive)
3132 "Get the right format for a time string."
3133 (let ((f (if long (cdr org-time-stamp-formats)
3134 (car org-time-stamp-formats))))
3135 (if inactive
3136 (concat "[" (substring f 1 -1) "]")
3137 f)))
3139 (defcustom org-time-clocksum-format
3140 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3141 "The format string used when creating CLOCKSUM lines.
3142 This is also used when Org mode generates a time duration.
3144 The value can be a single format string containing two
3145 %-sequences, which will be filled with the number of hours and
3146 minutes in that order.
3148 Alternatively, the value can be a plist associating any of the
3149 keys :years, :months, :weeks, :days, :hours or :minutes with
3150 format strings. The time duration is formatted using only the
3151 time components that are needed and concatenating the results.
3152 If a time unit in absent, it falls back to the next smallest
3153 unit.
3155 The keys :require-years, :require-months, :require-days,
3156 :require-weeks, :require-hours, :require-minutes are also
3157 meaningful. A non-nil value for these keys indicates that the
3158 corresponding time component should always be included, even if
3159 its value is 0.
3162 For example,
3164 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3165 :require-minutes t)
3167 means durations longer than a day will be expressed in days,
3168 hours and minutes, and durations less than a day will always be
3169 expressed in hours and minutes (even for durations less than an
3170 hour).
3172 The value
3174 (:days \"%dd\" :minutes \"%dm\")
3176 means durations longer than a day will be expressed in days and
3177 minutes, and durations less than a day will be expressed entirely
3178 in minutes (even for durations longer than an hour)."
3179 :group 'org-time
3180 :group 'org-clock
3181 :version "24.4"
3182 :package-version '(Org . "8.0")
3183 :type '(choice (string :tag "Format string")
3184 (set :tag "Plist"
3185 (group :inline t (const :tag "Years" :years)
3186 (string :tag "Format string"))
3187 (group :inline t
3188 (const :tag "Always show years" :require-years)
3189 (const t))
3190 (group :inline t (const :tag "Months" :months)
3191 (string :tag "Format string"))
3192 (group :inline t
3193 (const :tag "Always show months" :require-months)
3194 (const t))
3195 (group :inline t (const :tag "Weeks" :weeks)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show weeks" :require-weeks)
3199 (const t))
3200 (group :inline t (const :tag "Days" :days)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show days" :require-days)
3204 (const t))
3205 (group :inline t (const :tag "Hours" :hours)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show hours" :require-hours)
3209 (const t))
3210 (group :inline t (const :tag "Minutes" :minutes)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show minutes" :require-minutes)
3214 (const t)))))
3216 (defcustom org-time-clocksum-use-fractional nil
3217 "When non-nil, \\[org-clock-display] uses fractional times.
3218 See `org-time-clocksum-format' for more on time clock formats."
3219 :group 'org-time
3220 :group 'org-clock
3221 :version "24.3"
3222 :type 'boolean)
3224 (defcustom org-time-clocksum-use-effort-durations nil
3225 "When non-nil, \\[org-clock-display] uses effort durations.
3226 E.g. by default, one day is considered to be a 8 hours effort,
3227 so a task that has been clocked for 16 hours will be displayed
3228 as during 2 days in the clock display or in the clocktable.
3230 See `org-effort-durations' on how to set effort durations
3231 and `org-time-clocksum-format' for more on time clock formats."
3232 :group 'org-time
3233 :group 'org-clock
3234 :version "24.4"
3235 :package-version '(Org . "8.0")
3236 :type 'boolean)
3238 (defcustom org-time-clocksum-fractional-format "%.2f"
3239 "The format string used when creating CLOCKSUM lines,
3240 or when Org mode generates a time duration, if
3241 `org-time-clocksum-use-fractional' is enabled.
3243 The value can be a single format string containing one
3244 %-sequence, which will be filled with the number of hours as
3245 a float.
3247 Alternatively, the value can be a plist associating any of the
3248 keys :years, :months, :weeks, :days, :hours or :minutes with
3249 a format string. The time duration is formatted using the
3250 largest time unit which gives a non-zero integer part. If all
3251 specified formats have zero integer part, the smallest time unit
3252 is used."
3253 :group 'org-time
3254 :type '(choice (string :tag "Format string")
3255 (set (group :inline t (const :tag "Years" :years)
3256 (string :tag "Format string"))
3257 (group :inline t (const :tag "Months" :months)
3258 (string :tag "Format string"))
3259 (group :inline t (const :tag "Weeks" :weeks)
3260 (string :tag "Format string"))
3261 (group :inline t (const :tag "Days" :days)
3262 (string :tag "Format string"))
3263 (group :inline t (const :tag "Hours" :hours)
3264 (string :tag "Format string"))
3265 (group :inline t (const :tag "Minutes" :minutes)
3266 (string :tag "Format string")))))
3268 (defcustom org-deadline-warning-days 14
3269 "Number of days before expiration during which a deadline becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 When 0 or negative, it means use this number (the absolute value of it)
3272 even if a deadline has a different individual lead time specified.
3274 Custom commands can set this variable in the options section."
3275 :group 'org-time
3276 :group 'org-agenda-daily/weekly
3277 :type 'integer)
3279 (defcustom org-scheduled-delay-days 0
3280 "Number of days before a scheduled item becomes active.
3281 This variable governs the display in sparse trees and in the agenda.
3282 The default value (i.e. 0) means: don't delay scheduled item.
3283 When negative, it means use this number (the absolute value of it)
3284 even if a scheduled item has a different individual delay time
3285 specified.
3287 Custom commands can set this variable in the options section."
3288 :group 'org-time
3289 :group 'org-agenda-daily/weekly
3290 :version "24.4"
3291 :package-version '(Org . "8.0")
3292 :type 'integer)
3294 (defcustom org-read-date-prefer-future t
3295 "Non-nil means assume future for incomplete date input from user.
3296 This affects the following situations:
3297 1. The user gives a month but not a year.
3298 For example, if it is April and you enter \"feb 2\", this will be read
3299 as Feb 2, *next* year. \"May 5\", however, will be this year.
3300 2. The user gives a day, but no month.
3301 For example, if today is the 15th, and you enter \"3\", Org-mode will
3302 read this as the third of *next* month. However, if you enter \"17\",
3303 it will be considered as *this* month.
3305 If you set this variable to the symbol `time', then also the following
3306 will work:
3308 3. If the user gives a time.
3309 If the time is before now, it will be interpreted as tomorrow.
3311 Currently none of this works for ISO week specifications.
3313 When this option is nil, the current day, month and year will always be
3314 used as defaults.
3316 See also `org-agenda-jump-prefer-future'."
3317 :group 'org-time
3318 :type '(choice
3319 (const :tag "Never" nil)
3320 (const :tag "Check month and day" t)
3321 (const :tag "Check month, day, and time" time)))
3323 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3324 "Should the agenda jump command prefer the future for incomplete dates?
3325 The default is to do the same as configured in `org-read-date-prefer-future'.
3326 But you can also set a deviating value here.
3327 This may t or nil, or the symbol `org-read-date-prefer-future'."
3328 :group 'org-agenda
3329 :group 'org-time
3330 :version "24.1"
3331 :type '(choice
3332 (const :tag "Use org-read-date-prefer-future"
3333 org-read-date-prefer-future)
3334 (const :tag "Never" nil)
3335 (const :tag "Always" t)))
3337 (defcustom org-read-date-force-compatible-dates t
3338 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3340 Depending on the system Emacs is running on, certain dates cannot
3341 be represented with the type used internally to represent time.
3342 Dates between 1970-1-1 and 2038-1-1 can always be represented
3343 correctly. Some systems allow for earlier dates, some for later,
3344 some for both. One way to find out it to insert any date into an
3345 Org buffer, putting the cursor on the year and hitting S-up and
3346 S-down to test the range.
3348 When this variable is set to t, the date/time prompt will not let
3349 you specify dates outside the 1970-2037 range, so it is certain that
3350 these dates will work in whatever version of Emacs you are
3351 running, and also that you can move a file from one Emacs implementation
3352 to another. WHenever Org is forcing the year for you, it will display
3353 a message and beep.
3355 When this variable is nil, Org will check if the date is
3356 representable in the specific Emacs implementation you are using.
3357 If not, it will force a year, usually the current year, and beep
3358 to remind you. Currently this setting is not recommended because
3359 the likelihood that you will open your Org files in an Emacs that
3360 has limited date range is not negligible.
3362 A workaround for this problem is to use diary sexp dates for time
3363 stamps outside of this range."
3364 :group 'org-time
3365 :version "24.1"
3366 :type 'boolean)
3368 (defcustom org-read-date-display-live t
3369 "Non-nil means display current interpretation of date prompt live.
3370 This display will be in an overlay, in the minibuffer."
3371 :group 'org-time
3372 :type 'boolean)
3374 (defcustom org-read-date-popup-calendar t
3375 "Non-nil means pop up a calendar when prompting for a date.
3376 In the calendar, the date can be selected with mouse-1. However, the
3377 minibuffer will also be active, and you can simply enter the date as well.
3378 When nil, only the minibuffer will be available."
3379 :group 'org-time
3380 :type 'boolean)
3381 (org-defvaralias 'org-popup-calendar-for-date-prompt
3382 'org-read-date-popup-calendar)
3384 (make-obsolete-variable
3385 'org-read-date-minibuffer-setup-hook
3386 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3387 (defcustom org-read-date-minibuffer-setup-hook nil
3388 "Hook to be used to set up keys for the date/time interface.
3389 Add key definitions to `minibuffer-local-map', which will be a
3390 temporary copy.
3392 WARNING: This option is obsolete, you should use
3393 `org-read-date-minibuffer-local-map' to set up keys."
3394 :group 'org-time
3395 :type 'hook)
3397 (defcustom org-extend-today-until 0
3398 "The hour when your day really ends. Must be an integer.
3399 This has influence for the following applications:
3400 - When switching the agenda to \"today\". It it is still earlier than
3401 the time given here, the day recognized as TODAY is actually yesterday.
3402 - When a date is read from the user and it is still before the time given
3403 here, the current date and time will be assumed to be yesterday, 23:59.
3404 Also, timestamps inserted in capture templates follow this rule.
3406 IMPORTANT: This is a feature whose implementation is and likely will
3407 remain incomplete. Really, it is only here because past midnight seems to
3408 be the favorite working time of John Wiegley :-)"
3409 :group 'org-time
3410 :type 'integer)
3412 (defcustom org-use-effective-time nil
3413 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3414 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3415 \"effective time\" of any timestamps between midnight and 8am will be
3416 23:59 of the previous day."
3417 :group 'org-time
3418 :version "24.1"
3419 :type 'boolean)
3421 (defcustom org-use-last-clock-out-time-as-effective-time nil
3422 "When non-nil, use the last clock out time for `org-todo'.
3423 Note that this option has precedence over the combined use of
3424 `org-use-effective-time' and `org-extend-today-until'."
3425 :group 'org-time
3426 :version "24.4"
3427 :package-version '(Org . "8.0")
3428 :type 'boolean)
3430 (defcustom org-edit-timestamp-down-means-later nil
3431 "Non-nil means S-down will increase the time in a time stamp.
3432 When nil, S-up will increase."
3433 :group 'org-time
3434 :type 'boolean)
3436 (defcustom org-calendar-follow-timestamp-change t
3437 "Non-nil means make the calendar window follow timestamp changes.
3438 When a timestamp is modified and the calendar window is visible, it will be
3439 moved to the new date."
3440 :group 'org-time
3441 :type 'boolean)
3443 (defgroup org-tags nil
3444 "Options concerning tags in Org-mode."
3445 :tag "Org Tags"
3446 :group 'org)
3448 (defcustom org-tag-alist nil
3449 "List of tags allowed in Org-mode files.
3450 When this list is nil, Org-mode will base TAG input on what is already in the
3451 buffer.
3452 The value of this variable is an alist, the car of each entry must be a
3453 keyword as a string, the cdr may be a character that is used to select
3454 that tag through the fast-tag-selection interface.
3455 See the manual for details."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (list :tag "Start radio group"
3462 (const :startgroup)
3463 (option (string :tag "Group description")))
3464 (list :tag "Start tag group, non distinct"
3465 (const :startgrouptag)
3466 (option (string :tag "Group description")))
3467 (list :tag "Group tags delimiter"
3468 (const :grouptags))
3469 (list :tag "End radio group"
3470 (const :endgroup)
3471 (option (string :tag "Group description")))
3472 (list :tag "End tag group, non distinct"
3473 (const :endgrouptag)
3474 (option (string :tag "Group description")))
3475 (const :tag "New line" (:newline)))))
3477 (defcustom org-tag-persistent-alist nil
3478 "List of tags that will always appear in all Org-mode files.
3479 This is in addition to any in buffer settings or customizations
3480 of `org-tag-alist'.
3481 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3482 The value of this variable is an alist, the car of each entry must be a
3483 keyword as a string, the cdr may be a character that is used to select
3484 that tag through the fast-tag-selection interface.
3485 See the manual for details.
3486 To disable these tags on a per-file basis, insert anywhere in the file:
3487 #+STARTUP: noptag"
3488 :group 'org-tags
3489 :type '(repeat
3490 (choice
3491 (cons (string :tag "Tag name")
3492 (character :tag "Access char"))
3493 (const :tag "Start radio group" (:startgroup))
3494 (const :tag "Group tags delimiter" (:grouptags))
3495 (const :tag "End radio group" (:endgroup))
3496 (const :tag "New line" (:newline)))))
3498 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3499 "If non-nil, always offer completion for all tags of all agenda files.
3500 Instead of customizing this variable directly, you might want to
3501 set it locally for capture buffers, because there no list of
3502 tags in that file can be created dynamically (there are none).
3504 (add-hook \\='org-capture-mode-hook
3505 (lambda ()
3506 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3507 :group 'org-tags
3508 :version "24.1"
3509 :type 'boolean)
3511 (defvar org-file-tags nil
3512 "List of tags that can be inherited by all entries in the file.
3513 The tags will be inherited if the variable `org-use-tag-inheritance'
3514 says they should be.
3515 This variable is populated from #+FILETAGS lines.")
3517 (defcustom org-use-fast-tag-selection 'auto
3518 "Non-nil means use fast tag selection scheme.
3519 This is a special interface to select and deselect tags with single keys.
3520 When nil, fast selection is never used.
3521 When the symbol `auto', fast selection is used if and only if selection
3522 characters for tags have been configured, either through the variable
3523 `org-tag-alist' or through a #+TAGS line in the buffer.
3524 When t, fast selection is always used and selection keys are assigned
3525 automatically if necessary."
3526 :group 'org-tags
3527 :type '(choice
3528 (const :tag "Always" t)
3529 (const :tag "Never" nil)
3530 (const :tag "When selection characters are configured" auto)))
3532 (defcustom org-fast-tag-selection-single-key nil
3533 "Non-nil means fast tag selection exits after first change.
3534 When nil, you have to press RET to exit it.
3535 During fast tag selection, you can toggle this flag with `C-c'.
3536 This variable can also have the value `expert'. In this case, the window
3537 displaying the tags menu is not even shown, until you press C-c again."
3538 :group 'org-tags
3539 :type '(choice
3540 (const :tag "No" nil)
3541 (const :tag "Yes" t)
3542 (const :tag "Expert" expert)))
3544 (defvar org-fast-tag-selection-include-todo nil
3545 "Non-nil means fast tags selection interface will also offer TODO states.
3546 This is an undocumented feature, you should not rely on it.")
3548 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3549 "The column to which tags should be indented in a headline.
3550 If this number is positive, it specifies the column. If it is negative,
3551 it means that the tags should be flushright to that column. For example,
3552 -80 works well for a normal 80 character screen.
3553 When 0, place tags directly after headline text, with only one space in
3554 between."
3555 :group 'org-tags
3556 :type 'integer)
3558 (defcustom org-auto-align-tags t
3559 "Non-nil keeps tags aligned when modifying headlines.
3560 Some operations (i.e. demoting) change the length of a headline and
3561 therefore shift the tags around. With this option turned on, after
3562 each such operation the tags are again aligned to `org-tags-column'."
3563 :group 'org-tags
3564 :type 'boolean)
3566 (defcustom org-use-tag-inheritance t
3567 "Non-nil means tags in levels apply also for sublevels.
3568 When nil, only the tags directly given in a specific line apply there.
3569 This may also be a list of tags that should be inherited, or a regexp that
3570 matches tags that should be inherited. Additional control is possible
3571 with the variable `org-tags-exclude-from-inheritance' which gives an
3572 explicit list of tags to be excluded from inheritance, even if the value of
3573 `org-use-tag-inheritance' would select it for inheritance.
3575 If this option is t, a match early-on in a tree can lead to a large
3576 number of matches in the subtree when constructing the agenda or creating
3577 a sparse tree. If you only want to see the first match in a tree during
3578 a search, check out the variable `org-tags-match-list-sublevels'."
3579 :group 'org-tags
3580 :type '(choice
3581 (const :tag "Not" nil)
3582 (const :tag "Always" t)
3583 (repeat :tag "Specific tags" (string :tag "Tag"))
3584 (regexp :tag "Tags matched by regexp")))
3586 (defcustom org-tags-exclude-from-inheritance nil
3587 "List of tags that should never be inherited.
3588 This is a way to exclude a few tags from inheritance. For way to do
3589 the opposite, to actively allow inheritance for selected tags,
3590 see the variable `org-use-tag-inheritance'."
3591 :group 'org-tags
3592 :type '(repeat (string :tag "Tag")))
3594 (defun org-tag-inherit-p (tag)
3595 "Check if TAG is one that should be inherited."
3596 (cond
3597 ((member tag org-tags-exclude-from-inheritance) nil)
3598 ((eq org-use-tag-inheritance t) t)
3599 ((not org-use-tag-inheritance) nil)
3600 ((stringp org-use-tag-inheritance)
3601 (string-match org-use-tag-inheritance tag))
3602 ((listp org-use-tag-inheritance)
3603 (member tag org-use-tag-inheritance))
3604 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3606 (defcustom org-tags-match-list-sublevels t
3607 "Non-nil means list also sublevels of headlines matching a search.
3608 This variable applies to tags/property searches, and also to stuck
3609 projects because this search is based on a tags match as well.
3611 When set to the symbol `indented', sublevels are indented with
3612 leading dots.
3614 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3615 the sublevels of a headline matching a tag search often also match
3616 the same search. Listing all of them can create very long lists.
3617 Setting this variable to nil causes subtrees of a match to be skipped.
3619 This variable is semi-obsolete and probably should always be true. It
3620 is better to limit inheritance to certain tags using the variables
3621 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3622 :group 'org-tags
3623 :type '(choice
3624 (const :tag "No, don't list them" nil)
3625 (const :tag "Yes, do list them" t)
3626 (const :tag "List them, indented with leading dots" indented)))
3628 (defcustom org-tags-sort-function nil
3629 "When set, tags are sorted using this function as a comparator."
3630 :group 'org-tags
3631 :type '(choice
3632 (const :tag "No sorting" nil)
3633 (const :tag "Alphabetical" string<)
3634 (const :tag "Reverse alphabetical" string>)
3635 (function :tag "Custom function" nil)))
3637 (defvar org-tags-history nil
3638 "History of minibuffer reads for tags.")
3639 (defvar org-last-tags-completion-table nil
3640 "The last used completion table for tags.")
3641 (defvar org-after-tags-change-hook nil
3642 "Hook that is run after the tags in a line have changed.")
3644 (defgroup org-properties nil
3645 "Options concerning properties in Org-mode."
3646 :tag "Org Properties"
3647 :group 'org)
3649 (defcustom org-property-format "%-10s %s"
3650 "How property key/value pairs should be formatted by `indent-line'.
3651 When `indent-line' hits a property definition, it will format the line
3652 according to this format, mainly to make sure that the values are
3653 lined-up with respect to each other."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-properties-postprocess-alist nil
3658 "Alist of properties and functions to adjust inserted values.
3659 Elements of this alist must be of the form
3661 ([string] [function])
3663 where [string] must be a property name and [function] must be a
3664 lambda expression: this lambda expression must take one argument,
3665 the value to adjust, and return the new value as a string.
3667 For example, this element will allow the property \"Remaining\"
3668 to be updated wrt the relation between the \"Effort\" property
3669 and the clock summary:
3671 ((\"Remaining\" (lambda(value)
3672 (let ((clocksum (org-clock-sum-current-item))
3673 (effort (org-duration-string-to-minutes
3674 (org-entry-get (point) \"Effort\"))))
3675 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3676 :group 'org-properties
3677 :version "24.1"
3678 :type '(alist :key-type (string :tag "Property")
3679 :value-type (function :tag "Function")))
3681 (defcustom org-use-property-inheritance nil
3682 "Non-nil means properties apply also for sublevels.
3684 This setting is chiefly used during property searches. Turning it on can
3685 cause significant overhead when doing a search, which is why it is not
3686 on by default.
3688 When nil, only the properties directly given in the current entry count.
3689 When t, every property is inherited. The value may also be a list of
3690 properties that should have inheritance, or a regular expression matching
3691 properties that should be inherited.
3693 However, note that some special properties use inheritance under special
3694 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3695 and the properties ending in \"_ALL\" when they are used as descriptor
3696 for valid values of a property.
3698 Note for programmers:
3699 When querying an entry with `org-entry-get', you can control if inheritance
3700 should be used. By default, `org-entry-get' looks only at the local
3701 properties. You can request inheritance by setting the inherit argument
3702 to t (to force inheritance) or to `selective' (to respect the setting
3703 in this variable)."
3704 :group 'org-properties
3705 :type '(choice
3706 (const :tag "Not" nil)
3707 (const :tag "Always" t)
3708 (repeat :tag "Specific properties" (string :tag "Property"))
3709 (regexp :tag "Properties matched by regexp")))
3711 (defun org-property-inherit-p (property)
3712 "Check if PROPERTY is one that should be inherited."
3713 (cond
3714 ((eq org-use-property-inheritance t) t)
3715 ((not org-use-property-inheritance) nil)
3716 ((stringp org-use-property-inheritance)
3717 (string-match org-use-property-inheritance property))
3718 ((listp org-use-property-inheritance)
3719 (member property org-use-property-inheritance))
3720 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3722 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3723 "The default column format, if no other format has been defined.
3724 This variable can be set on the per-file basis by inserting a line
3726 #+COLUMNS: %25ITEM ....."
3727 :group 'org-properties
3728 :type 'string)
3730 (defcustom org-columns-ellipses ".."
3731 "The ellipses to be used when a field in column view is truncated.
3732 When this is the empty string, as many characters as possible are shown,
3733 but then there will be no visual indication that the field has been truncated.
3734 When this is a string of length N, the last N characters of a truncated
3735 field are replaced by this string. If the column is narrower than the
3736 ellipses string, only part of the ellipses string will be shown."
3737 :group 'org-properties
3738 :type 'string)
3740 (defconst org-global-properties-fixed
3741 '(("VISIBILITY_ALL" . "folded children content all")
3742 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3743 "List of property/value pairs that can be inherited by any entry.
3745 These are fixed values, for the preset properties. The user variable
3746 that can be used to add to this list is `org-global-properties'.
3748 The entries in this list are cons cells where the car is a property
3749 name and cdr is a string with the value. If the value represents
3750 multiple items like an \"_ALL\" property, separate the items by
3751 spaces.")
3753 (defcustom org-global-properties nil
3754 "List of property/value pairs that can be inherited by any entry.
3756 This list will be combined with the constant `org-global-properties-fixed'.
3758 The entries in this list are cons cells where the car is a property
3759 name and cdr is a string with the value.
3761 You can set buffer-local values for the same purpose in the variable
3762 `org-file-properties' this by adding lines like
3764 #+PROPERTY: NAME VALUE"
3765 :group 'org-properties
3766 :type '(repeat
3767 (cons (string :tag "Property")
3768 (string :tag "Value"))))
3770 (defvar-local org-file-properties nil
3771 "List of property/value pairs that can be inherited by any entry.
3772 Valid for the current buffer.
3773 This variable is populated from #+PROPERTY lines.")
3775 (defgroup org-agenda nil
3776 "Options concerning agenda views in Org-mode."
3777 :tag "Org Agenda"
3778 :group 'org)
3780 (defvar-local org-category nil
3781 "Variable used by org files to set a category for agenda display.
3782 Such files should use a file variable to set it, for example
3784 # -*- mode: org; org-category: \"ELisp\"
3786 or contain a special line
3788 #+CATEGORY: ELisp
3790 If the file does not specify a category, then file's base name
3791 is used instead.")
3792 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3794 (defcustom org-agenda-files nil
3795 "The files to be used for agenda display.
3796 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3797 \\[org-remove-file]. You can also use customize to edit the list.
3799 If an entry is a directory, all files in that directory that are matched by
3800 `org-agenda-file-regexp' will be part of the file list.
3802 If the value of the variable is not a list but a single file name, then
3803 the list of agenda files is actually stored and maintained in that file, one
3804 agenda file per line. In this file paths can be given relative to
3805 `org-directory'. Tilde expansion and environment variable substitution
3806 are also made."
3807 :group 'org-agenda
3808 :type '(choice
3809 (repeat :tag "List of files and directories" file)
3810 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3812 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3813 "Regular expression to match files for `org-agenda-files'.
3814 If any element in the list in that variable contains a directory instead
3815 of a normal file, all files in that directory that are matched by this
3816 regular expression will be included."
3817 :group 'org-agenda
3818 :type 'regexp)
3820 (defcustom org-agenda-text-search-extra-files nil
3821 "List of extra files to be searched by text search commands.
3822 These files will be searched in addition to the agenda files by the
3823 commands `org-search-view' (`\\[org-agenda] s') \
3824 and `org-occur-in-agenda-files'.
3825 Note that these files will only be searched for text search commands,
3826 not for the other agenda views like todo lists, tag searches or the weekly
3827 agenda. This variable is intended to list notes and possibly archive files
3828 that should also be searched by these two commands.
3829 In fact, if the first element in the list is the symbol `agenda-archives',
3830 then all archive files of all agenda files will be added to the search
3831 scope."
3832 :group 'org-agenda
3833 :type '(set :greedy t
3834 (const :tag "Agenda Archives" agenda-archives)
3835 (repeat :inline t (file))))
3837 (org-defvaralias 'org-agenda-multi-occur-extra-files
3838 'org-agenda-text-search-extra-files)
3840 (defcustom org-agenda-skip-unavailable-files nil
3841 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3842 A nil value means to remove them, after a query, from the list."
3843 :group 'org-agenda
3844 :type 'boolean)
3846 (defcustom org-calendar-to-agenda-key [?c]
3847 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3848 The command `org-calendar-goto-agenda' will be bound to this key. The
3849 default is the character `c' because then `c' can be used to switch back and
3850 forth between agenda and calendar."
3851 :group 'org-agenda
3852 :type 'sexp)
3854 (defcustom org-calendar-insert-diary-entry-key [?i]
3855 "The key to be installed in `calendar-mode-map' for adding diary entries.
3856 This option is irrelevant until `org-agenda-diary-file' has been configured
3857 to point to an Org-mode file. When that is the case, the command
3858 `org-agenda-diary-entry' will be bound to the key given here, by default
3859 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3860 if you want to continue doing this, you need to change this to a different
3861 key."
3862 :group 'org-agenda
3863 :type 'sexp)
3865 (defcustom org-agenda-diary-file 'diary-file
3866 "File to which to add new entries with the `i' key in agenda and calendar.
3867 When this is the symbol `diary-file', the functionality in the Emacs
3868 calendar will be used to add entries to the `diary-file'. But when this
3869 points to a file, `org-agenda-diary-entry' will be used instead."
3870 :group 'org-agenda
3871 :type '(choice
3872 (const :tag "The standard Emacs diary file" diary-file)
3873 (file :tag "Special Org file diary entries")))
3875 (eval-after-load "calendar"
3876 '(progn
3877 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3878 'org-calendar-goto-agenda)
3879 (add-hook 'calendar-mode-hook
3880 (lambda ()
3881 (unless (eq org-agenda-diary-file 'diary-file)
3882 (define-key calendar-mode-map
3883 org-calendar-insert-diary-entry-key
3884 'org-agenda-diary-entry))))))
3886 (defgroup org-latex nil
3887 "Options for embedding LaTeX code into Org-mode."
3888 :tag "Org LaTeX"
3889 :group 'org)
3891 (defcustom org-format-latex-options
3892 '(:foreground default :background default :scale 1.0
3893 :html-foreground "Black" :html-background "Transparent"
3894 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3895 "Options for creating images from LaTeX fragments.
3896 This is a property list with the following properties:
3897 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3898 `default' means use the foreground of the default face.
3899 `auto' means use the foreground from the text face.
3900 :background the background color, or \"Transparent\".
3901 `default' means use the background of the default face.
3902 `auto' means use the background from the text face.
3903 :scale a scaling factor for the size of the images, to get more pixels
3904 :html-foreground, :html-background, :html-scale
3905 the same numbers for HTML export.
3906 :matchers a list indicating which matchers should be used to
3907 find LaTeX fragments. Valid members of this list are:
3908 \"begin\" find environments
3909 \"$1\" find single characters surrounded by $.$
3910 \"$\" find math expressions surrounded by $...$
3911 \"$$\" find math expressions surrounded by $$....$$
3912 \"\\(\" find math expressions surrounded by \\(...\\)
3913 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3914 :group 'org-latex
3915 :type 'plist)
3917 (defcustom org-format-latex-signal-error t
3918 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3919 When nil, just push out a message."
3920 :group 'org-latex
3921 :version "24.1"
3922 :type 'boolean)
3924 (defcustom org-latex-to-mathml-jar-file nil
3925 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3926 Use this to specify additional executable file say a jar file.
3928 When using MathToWeb as the converter, specify the full-path to
3929 your mathtoweb.jar file."
3930 :group 'org-latex
3931 :version "24.1"
3932 :type '(choice
3933 (const :tag "None" nil)
3934 (file :tag "JAR file" :must-match t)))
3936 (defcustom org-latex-to-mathml-convert-command nil
3937 "Command to convert LaTeX fragments to MathML.
3938 Replace format-specifiers in the command as noted below and use
3939 `shell-command' to convert LaTeX to MathML.
3940 %j: Executable file in fully expanded form as specified by
3941 `org-latex-to-mathml-jar-file'.
3942 %I: Input LaTeX file in fully expanded form.
3943 %i: The latex fragment to be converted.
3944 %o: Output MathML file.
3946 This command is used by `org-create-math-formula'.
3948 When using MathToWeb as the converter, set this option to
3949 \"java -jar %j -unicode -force -df %o %I\".
3951 When using LaTeXML set this option to
3952 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3953 :group 'org-latex
3954 :version "24.1"
3955 :type '(choice
3956 (const :tag "None" nil)
3957 (string :tag "\nShell command")))
3959 (defcustom org-latex-create-formula-image-program 'dvipng
3960 "Program to convert LaTeX fragments with.
3962 dvipng Process the LaTeX fragments to dvi file, then convert
3963 dvi files to png files using dvipng.
3964 This will also include processing of non-math environments.
3965 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3966 to convert pdf files to png files"
3967 :group 'org-latex
3968 :version "24.1"
3969 :type '(choice
3970 (const :tag "dvipng" dvipng)
3971 (const :tag "imagemagick" imagemagick)))
3973 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3974 "Path to store latex preview images.
3975 A relative path here creates many directories relative to the
3976 processed org files paths. An absolute path puts all preview
3977 images at the same place."
3978 :group 'org-latex
3979 :version "24.3"
3980 :type 'string)
3982 (defun org-format-latex-mathml-available-p ()
3983 "Return t if `org-latex-to-mathml-convert-command' is usable."
3984 (save-match-data
3985 (when (and (boundp 'org-latex-to-mathml-convert-command)
3986 org-latex-to-mathml-convert-command)
3987 (let ((executable (car (split-string
3988 org-latex-to-mathml-convert-command))))
3989 (when (executable-find executable)
3990 (if (string-match
3991 "%j" org-latex-to-mathml-convert-command)
3992 (file-readable-p org-latex-to-mathml-jar-file)
3993 t))))))
3995 (defcustom org-format-latex-header "\\documentclass{article}
3996 \\usepackage[usenames]{color}
3997 \[PACKAGES]
3998 \[DEFAULT-PACKAGES]
3999 \\pagestyle{empty} % do not remove
4000 % The settings below are copied from fullpage.sty
4001 \\setlength{\\textwidth}{\\paperwidth}
4002 \\addtolength{\\textwidth}{-3cm}
4003 \\setlength{\\oddsidemargin}{1.5cm}
4004 \\addtolength{\\oddsidemargin}{-2.54cm}
4005 \\setlength{\\evensidemargin}{\\oddsidemargin}
4006 \\setlength{\\textheight}{\\paperheight}
4007 \\addtolength{\\textheight}{-\\headheight}
4008 \\addtolength{\\textheight}{-\\headsep}
4009 \\addtolength{\\textheight}{-\\footskip}
4010 \\addtolength{\\textheight}{-3cm}
4011 \\setlength{\\topmargin}{1.5cm}
4012 \\addtolength{\\topmargin}{-2.54cm}"
4013 "The document header used for processing LaTeX fragments.
4014 It is imperative that this header make sure that no page number
4015 appears on the page. The package defined in the variables
4016 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4017 will either replace the placeholder \"[PACKAGES]\" in this
4018 header, or they will be appended."
4019 :group 'org-latex
4020 :type 'string)
4022 (defun org-set-packages-alist (var val)
4023 "Set the packages alist and make sure it has 3 elements per entry."
4024 (set var (mapcar (lambda (x)
4025 (if (and (consp x) (= (length x) 2))
4026 (list (car x) (nth 1 x) t)
4028 val)))
4030 (defun org-get-packages-alist (var)
4031 "Get the packages alist and make sure it has 3 elements per entry."
4032 (mapcar (lambda (x)
4033 (if (and (consp x) (= (length x) 2))
4034 (list (car x) (nth 1 x) t)
4036 (default-value var)))
4038 (defcustom org-latex-default-packages-alist
4039 '(("AUTO" "inputenc" t ("pdflatex"))
4040 ("T1" "fontenc" t ("pdflatex"))
4041 ("" "graphicx" t)
4042 ("" "grffile" t)
4043 ("" "longtable" nil)
4044 ("" "wrapfig" nil)
4045 ("" "rotating" nil)
4046 ("normalem" "ulem" t)
4047 ("" "amsmath" t)
4048 ("" "textcomp" t)
4049 ("" "amssymb" t)
4050 ("" "capt-of" nil)
4051 ("" "hyperref" nil))
4052 "Alist of default packages to be inserted in the header.
4054 Change this only if one of the packages here causes an
4055 incompatibility with another package you are using.
4057 The packages in this list are needed by one part or another of
4058 Org mode to function properly:
4060 - inputenc, fontenc: for basic font and character selection
4061 - graphicx: for including images
4062 - grffile: allow periods and spaces in graphics file names
4063 - longtable: For multipage tables
4064 - wrapfig: for figure placement
4065 - rotating: for sideways figures and tables
4066 - ulem: for underline and strike-through
4067 - amsmath: for subscript and superscript and math environments
4068 - textcomp, amssymb: for various symbols used
4069 for interpreting the entities in `org-entities'. You can skip
4070 some of these packages if you don't use any of their symbols.
4071 - capt-of: for captions outside of floats
4072 - hyperref: for cross references
4074 Therefore you should not modify this variable unless you know
4075 what you are doing. The one reason to change it anyway is that
4076 you might be loading some other package that conflicts with one
4077 of the default packages. Each element is either a cell or
4078 a string.
4080 A cell is of the format
4082 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4084 If SNIPPET-FLAG is non-nil, the package also needs to be included
4085 when compiling LaTeX snippets into images for inclusion into
4086 non-LaTeX output. COMPILERS is a list of compilers that should
4087 include the package, see `org-latex-compiler'. If the document
4088 compiler is not in the list, and the list is non-nil, the package
4089 will not be inserted in the final document.
4091 A string will be inserted as-is in the header of the document."
4092 :group 'org-latex
4093 :group 'org-export-latex
4094 :set 'org-set-packages-alist
4095 :get 'org-get-packages-alist
4096 :version "25.1"
4097 :package-version '(Org . "8.3")
4098 :type '(repeat
4099 (choice
4100 (list :tag "options/package pair"
4101 (string :tag "options")
4102 (string :tag "package")
4103 (boolean :tag "Snippet"))
4104 (string :tag "A line of LaTeX"))))
4106 (defcustom org-latex-packages-alist nil
4107 "Alist of packages to be inserted in every LaTeX header.
4109 These will be inserted after `org-latex-default-packages-alist'.
4110 Each element is either a cell or a string.
4112 A cell is of the format:
4114 (\"options\" \"package\" SNIPPET-FLAG)
4116 SNIPPET-FLAG, when non-nil, indicates that this package is also
4117 needed when turning LaTeX snippets into images for inclusion into
4118 non-LaTeX output.
4120 A string will be inserted as-is in the header of the document.
4122 Make sure that you only list packages here which:
4124 - you want in every file;
4125 - do not conflict with the setup in `org-format-latex-header';
4126 - do not conflict with the default packages in
4127 `org-latex-default-packages-alist'."
4128 :group 'org-latex
4129 :group 'org-export-latex
4130 :set 'org-set-packages-alist
4131 :get 'org-get-packages-alist
4132 :type '(repeat
4133 (choice
4134 (list :tag "options/package pair"
4135 (string :tag "options")
4136 (string :tag "package")
4137 (boolean :tag "Snippet"))
4138 (string :tag "A line of LaTeX"))))
4140 (defgroup org-appearance nil
4141 "Settings for Org-mode appearance."
4142 :tag "Org Appearance"
4143 :group 'org)
4145 (defcustom org-level-color-stars-only nil
4146 "Non-nil means fontify only the stars in each headline.
4147 When nil, the entire headline is fontified.
4148 Changing it requires restart of `font-lock-mode' to become effective
4149 also in regions already fontified."
4150 :group 'org-appearance
4151 :type 'boolean)
4153 (defcustom org-hide-leading-stars nil
4154 "Non-nil means hide the first N-1 stars in a headline.
4155 This works by using the face `org-hide' for these stars. This
4156 face is white for a light background, and black for a dark
4157 background. You may have to customize the face `org-hide' to
4158 make this work.
4159 Changing it requires restart of `font-lock-mode' to become effective
4160 also in regions already fontified.
4161 You may also set this on a per-file basis by adding one of the following
4162 lines to the buffer:
4164 #+STARTUP: hidestars
4165 #+STARTUP: showstars"
4166 :group 'org-appearance
4167 :type 'boolean)
4169 (defcustom org-hidden-keywords nil
4170 "List of symbols corresponding to keywords to be hidden the org buffer.
4171 For example, a value \\='(title) for this list will make the document's title
4172 appear in the buffer without the initial #+TITLE: keyword."
4173 :group 'org-appearance
4174 :version "24.1"
4175 :type '(set (const :tag "#+AUTHOR" author)
4176 (const :tag "#+DATE" date)
4177 (const :tag "#+EMAIL" email)
4178 (const :tag "#+TITLE" title)))
4180 (defcustom org-custom-properties nil
4181 "List of properties (as strings) with a special meaning.
4182 The default use of these custom properties is to let the user
4183 hide them with `org-toggle-custom-properties-visibility'."
4184 :group 'org-properties
4185 :group 'org-appearance
4186 :version "24.3"
4187 :type '(repeat (string :tag "Property Name")))
4189 (defcustom org-fontify-done-headline nil
4190 "Non-nil means change the face of a headline if it is marked DONE.
4191 Normally, only the TODO/DONE keyword indicates the state of a headline.
4192 When this is non-nil, the headline after the keyword is set to the
4193 `org-headline-done' as an additional indication."
4194 :group 'org-appearance
4195 :type 'boolean)
4197 (defcustom org-fontify-emphasized-text t
4198 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4199 Changing this variable requires a restart of Emacs to take effect."
4200 :group 'org-appearance
4201 :type 'boolean)
4203 (defcustom org-fontify-whole-heading-line nil
4204 "Non-nil means fontify the whole line for headings.
4205 This is useful when setting a background color for the
4206 org-level-* faces."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-highlight-latex-and-related nil
4211 "Non-nil means highlight LaTeX related syntax in the buffer.
4212 When non nil, the value should be a list containing any of the
4213 following symbols:
4214 `latex' Highlight LaTeX snippets and environments.
4215 `script' Highlight subscript and superscript.
4216 `entities' Highlight entities."
4217 :group 'org-appearance
4218 :version "24.4"
4219 :package-version '(Org . "8.0")
4220 :type '(choice
4221 (const :tag "No highlighting" nil)
4222 (set :greedy t :tag "Highlight"
4223 (const :tag "LaTeX snippets and environments" latex)
4224 (const :tag "Subscript and superscript" script)
4225 (const :tag "Entities" entities))))
4227 (defcustom org-hide-emphasis-markers nil
4228 "Non-nil mean font-lock should hide the emphasis marker characters."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-hide-macro-markers nil
4233 "Non-nil mean font-lock should hide the brackets marking macro calls."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-pretty-entities nil
4238 "Non-nil means show entities as UTF8 characters.
4239 When nil, the \\name form remains in the buffer."
4240 :group 'org-appearance
4241 :version "24.1"
4242 :type 'boolean)
4244 (defcustom org-pretty-entities-include-sub-superscripts t
4245 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4246 :group 'org-appearance
4247 :version "24.1"
4248 :type 'boolean)
4250 (defvar org-emph-re nil
4251 "Regular expression for matching emphasis.
4252 After a match, the match groups contain these elements:
4253 0 The match of the full regular expression, including the characters
4254 before and after the proper match
4255 1 The character before the proper match, or empty at beginning of line
4256 2 The proper match, including the leading and trailing markers
4257 3 The leading marker like * or /, indicating the type of highlighting
4258 4 The text between the emphasis markers, not including the markers
4259 5 The character after the match, empty at the end of a line")
4260 (defvar org-verbatim-re nil
4261 "Regular expression for matching verbatim text.")
4262 (defvar org-emphasis-regexp-components) ; defined just below
4263 (defvar org-emphasis-alist) ; defined just below
4264 (defun org-set-emph-re (var val)
4265 "Set variable and compute the emphasis regular expression."
4266 (set var val)
4267 (when (and (boundp 'org-emphasis-alist)
4268 (boundp 'org-emphasis-regexp-components)
4269 org-emphasis-alist org-emphasis-regexp-components)
4270 (let* ((e org-emphasis-regexp-components)
4271 (pre (car e))
4272 (post (nth 1 e))
4273 (border (nth 2 e))
4274 (body (nth 3 e))
4275 (nl (nth 4 e))
4276 (body1 (concat body "*?"))
4277 (markers (mapconcat 'car org-emphasis-alist ""))
4278 (vmarkers (mapconcat
4279 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4280 org-emphasis-alist "")))
4281 ;; make sure special characters appear at the right position in the class
4282 (if (string-match "\\^" markers)
4283 (setq markers (concat (replace-match "" t t markers) "^")))
4284 (if (string-match "-" markers)
4285 (setq markers (concat (replace-match "" t t markers) "-")))
4286 (if (string-match "\\^" vmarkers)
4287 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4288 (if (string-match "-" vmarkers)
4289 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4290 (if (> nl 0)
4291 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4292 (int-to-string nl) "\\}")))
4293 ;; Make the regexp
4294 (setq org-emph-re
4295 (concat "\\([" pre "]\\|^\\)"
4296 "\\("
4297 "\\([" markers "]\\)"
4298 "\\("
4299 "[^" border "]\\|"
4300 "[^" border "]"
4301 body1
4302 "[^" border "]"
4303 "\\)"
4304 "\\3\\)"
4305 "\\([" post "]\\|$\\)"))
4306 (setq org-verbatim-re
4307 (concat "\\([" pre "]\\|^\\)"
4308 "\\("
4309 "\\([" vmarkers "]\\)"
4310 "\\("
4311 "[^" border "]\\|"
4312 "[^" border "]"
4313 body1
4314 "[^" border "]"
4315 "\\)"
4316 "\\3\\)"
4317 "\\([" post "]\\|$\\)")))))
4319 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4320 ;; set this option proved cumbersome. See this message/thread:
4321 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4322 (defvar org-emphasis-regexp-components
4323 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4324 "Components used to build the regular expression for emphasis.
4325 This is a list with five entries. Terminology: In an emphasis string
4326 like \" *strong word* \", we call the initial space PREMATCH, the final
4327 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4328 and \"trong wor\" is the body. The different components in this variable
4329 specify what is allowed/forbidden in each part:
4331 pre Chars allowed as prematch. Beginning of line will be allowed too.
4332 post Chars allowed as postmatch. End of line will be allowed too.
4333 border The chars *forbidden* as border characters.
4334 body-regexp A regexp like \".\" to match a body character. Don't use
4335 non-shy groups here, and don't allow newline here.
4336 newline The maximum number of newlines allowed in an emphasis exp.
4338 You need to reload Org or to restart Emacs after customizing this.")
4340 (defcustom org-emphasis-alist
4341 `(("*" bold)
4342 ("/" italic)
4343 ("_" underline)
4344 ("=" org-verbatim verbatim)
4345 ("~" org-code verbatim)
4346 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4347 "Alist of characters and faces to emphasize text.
4348 Text starting and ending with a special character will be emphasized,
4349 for example *bold*, _underlined_ and /italic/. This variable sets the
4350 marker characters and the face to be used by font-lock for highlighting
4351 in Org-mode Emacs buffers.
4353 You need to reload Org or to restart Emacs after customizing this."
4354 :group 'org-appearance
4355 :set 'org-set-emph-re
4356 :version "24.4"
4357 :package-version '(Org . "8.0")
4358 :type '(repeat
4359 (list
4360 (string :tag "Marker character")
4361 (choice
4362 (face :tag "Font-lock-face")
4363 (plist :tag "Face property list"))
4364 (option (const verbatim)))))
4366 (defvar org-protecting-blocks '("src" "example" "export")
4367 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4368 This is needed for font-lock setup.")
4370 ;;; Functions and variables from their packages
4371 ;; Declared here to avoid compiler warnings
4373 ;; XEmacs only
4374 (defvar outline-mode-menu-heading)
4375 (defvar outline-mode-menu-show)
4376 (defvar outline-mode-menu-hide)
4377 (defvar zmacs-regions) ; XEmacs regions
4379 ;; Emacs only
4380 (defvar mark-active)
4382 ;; Various packages
4383 (declare-function calc-eval "calc" (str &optional separator &rest args))
4384 (declare-function calendar-forward-day "cal-move" (arg))
4385 (declare-function calendar-goto-date "cal-move" (date))
4386 (declare-function calendar-goto-today "cal-move" ())
4387 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4388 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4389 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4390 (declare-function cdlatex-tab "ext:cdlatex" ())
4391 (declare-function dired-get-filename
4392 "dired"
4393 (&optional localp no-error-if-not-filep))
4394 (declare-function iswitchb-read-buffer
4395 "iswitchb"
4396 (prompt &optional default require-match start matches-set))
4397 (declare-function org-agenda-change-all-lines
4398 "org-agenda"
4399 (newhead hdmarker &optional fixface just-this))
4400 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4401 "org-agenda"
4402 (&optional end))
4403 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4404 (declare-function org-agenda-format-item
4405 "org-agenda"
4406 (extra txt &optional level category tags dotime noprefix
4407 remove-re habitp))
4408 (declare-function org-agenda-maybe-redo "org-agenda" ())
4409 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4410 (declare-function org-agenda-save-markers-for-cut-and-paste
4411 "org-agenda"
4412 (beg end))
4413 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4414 (declare-function org-agenda-skip "org-agenda" ())
4415 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4416 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4417 (declare-function org-indent-mode "org-indent" (&optional arg))
4418 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4419 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4420 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4421 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4422 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4423 (declare-function parse-time-string "parse-time" (string))
4424 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4425 (declare-function table--at-cell-p
4426 "table"
4427 (position &optional object at-column))
4429 (defvar align-mode-rules-list)
4430 (defvar calc-embedded-close-formula)
4431 (defvar calc-embedded-open-formula)
4432 (defvar calc-embedded-open-mode)
4433 (defvar font-lock-unfontify-region-function)
4434 (defvar iswitchb-temp-buflist)
4435 (defvar org-agenda-tags-todo-honor-ignore-options)
4436 (defvar remember-data-file)
4437 (defvar texmathp-why)
4439 ;;;###autoload
4440 (defun turn-on-orgtbl ()
4441 "Unconditionally turn on `orgtbl-mode'."
4442 (require 'org-table)
4443 (orgtbl-mode 1))
4445 (defun org-at-table-p (&optional table-type)
4446 "Non-nil if the cursor is inside an Org table.
4447 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4448 If `org-enable-table-editor' is nil, return nil unconditionally."
4449 (and
4450 org-enable-table-editor
4451 (save-excursion
4452 (beginning-of-line)
4453 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4454 (or (not (derived-mode-p 'org-mode))
4455 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4456 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4457 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4459 (defun org-at-table.el-p ()
4460 "Non-nil when point is at a table.el table."
4461 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4462 (let ((element (org-element-at-point)))
4463 (and (eq (org-element-type element) 'table)
4464 (eq (org-element-property :type element) 'table.el)))))
4466 (defun org-table-recognize-table.el ()
4467 "If there is a table.el table nearby, recognize it and move into it."
4468 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4469 (beginning-of-line)
4470 (unless (or (looking-at org-table-dataline-regexp)
4471 (not (looking-at org-table1-hline-regexp)))
4472 (forward-line)
4473 (when (looking-at org-table-any-border-regexp)
4474 (forward-line -2)))
4475 (if (re-search-forward "|" (org-table-end t) t)
4476 (progn
4477 (require 'table)
4478 (if (table--at-cell-p (point)) t
4479 (message "recognizing table.el table...")
4480 (table-recognize-table)
4481 (message "recognizing table.el table...done")))
4482 (error "This should not happen"))))
4483 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4484 (make-obsolete 'org-table-recognize-table.el
4485 "please notify the org mailing list if you use this function."
4486 "Org 9.0")
4488 (defun org-at-table-hline-p ()
4489 "Non-nil when point is inside a hline in a table.
4490 Assume point is already in a table. If `org-enable-table-editor'
4491 is nil, return nil unconditionally."
4492 (and org-enable-table-editor
4493 (save-excursion
4494 (beginning-of-line)
4495 (looking-at org-table-hline-regexp))))
4497 (defun org-table-map-tables (function &optional quietly)
4498 "Apply FUNCTION to the start of all tables in the buffer."
4499 (save-excursion
4500 (save-restriction
4501 (widen)
4502 (goto-char (point-min))
4503 (while (re-search-forward org-table-any-line-regexp nil t)
4504 (unless quietly
4505 (message "Mapping tables: %d%%"
4506 (floor (* 100.0 (point)) (buffer-size))))
4507 (beginning-of-line 1)
4508 (when (and (looking-at org-table-line-regexp)
4509 ;; Exclude tables in src/example/verbatim/clocktable blocks
4510 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4511 (save-excursion (funcall function))
4512 (or (looking-at org-table-line-regexp)
4513 (forward-char 1)))
4514 (re-search-forward org-table-any-border-regexp nil 1))))
4515 (unless quietly (message "Mapping tables: done")))
4517 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4518 (declare-function org-clock-update-mode-line "org-clock" ())
4519 (declare-function org-resolve-clocks "org-clock"
4520 (&optional also-non-dangling-p prompt last-valid))
4522 (defun org-at-TBLFM-p (&optional pos)
4523 "Non-nil when point (or POS) is in #+TBLFM line."
4524 (save-excursion
4525 (goto-char (or pos (point)))
4526 (beginning-of-line)
4527 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4528 (eq (org-element-type (org-element-at-point)) 'table))))
4530 (defvar org-clock-start-time)
4531 (defvar org-clock-marker (make-marker)
4532 "Marker recording the last clock-in.")
4533 (defvar org-clock-hd-marker (make-marker)
4534 "Marker recording the last clock-in, but the headline position.")
4535 (defvar org-clock-heading ""
4536 "The heading of the current clock entry.")
4537 (defun org-clock-is-active ()
4538 "Return the buffer where the clock is currently running.
4539 Return nil if no clock is running."
4540 (marker-buffer org-clock-marker))
4542 (defun org-check-running-clock ()
4543 "Check if the current buffer contains the running clock.
4544 If yes, offer to stop it and to save the buffer with the changes."
4545 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4546 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4547 (buffer-name))))
4548 (org-clock-out)
4549 (when (y-or-n-p "Save changed buffer?")
4550 (save-buffer))))
4552 (defun org-clocktable-try-shift (dir n)
4553 "Check if this line starts a clock table, if yes, shift the time block."
4554 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4555 (org-clocktable-shift dir n)))
4557 ;;;###autoload
4558 (defun org-clock-persistence-insinuate ()
4559 "Set up hooks for clock persistence."
4560 (require 'org-clock)
4561 (add-hook 'org-mode-hook 'org-clock-load)
4562 (add-hook 'kill-emacs-hook 'org-clock-save))
4564 (defgroup org-archive nil
4565 "Options concerning archiving in Org-mode."
4566 :tag "Org Archive"
4567 :group 'org-structure)
4569 (defcustom org-archive-location "%s_archive::"
4570 "The location where subtrees should be archived.
4572 The value of this variable is a string, consisting of two parts,
4573 separated by a double-colon. The first part is a filename and
4574 the second part is a headline.
4576 When the filename is omitted, archiving happens in the same file.
4577 %s in the filename will be replaced by the current file
4578 name (without the directory part). Archiving to a different file
4579 is useful to keep archived entries from contributing to the
4580 Org-mode Agenda.
4582 The archived entries will be filed as subtrees of the specified
4583 headline. When the headline is omitted, the subtrees are simply
4584 filed away at the end of the file, as top-level entries. Also in
4585 the heading you can use %s to represent the file name, this can be
4586 useful when using the same archive for a number of different files.
4588 Here are a few examples:
4589 \"%s_archive::\"
4590 If the current file is Projects.org, archive in file
4591 Projects.org_archive, as top-level trees. This is the default.
4593 \"::* Archived Tasks\"
4594 Archive in the current file, under the top-level headline
4595 \"* Archived Tasks\".
4597 \"~/org/archive.org::\"
4598 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4600 \"~/org/archive.org::* From %s\"
4601 Archive in file ~/org/archive.org (absolute path), under headlines
4602 \"From FILENAME\" where file name is the current file name.
4604 \"~/org/datetree.org::datetree/* Finished Tasks\"
4605 The \"datetree/\" string is special, signifying to archive
4606 items to the datetree. Items are placed in either the CLOSED
4607 date of the item, or the current date if there is no CLOSED date.
4608 The heading will be a subentry to the current date. There doesn't
4609 need to be a heading, but there always needs to be a slash after
4610 datetree. For example, to store archived items directly in the
4611 datetree, use \"~/org/datetree.org::datetree/\".
4613 \"basement::** Finished Tasks\"
4614 Archive in file ./basement (relative path), as level 3 trees
4615 below the level 2 heading \"** Finished Tasks\".
4617 You may set this option on a per-file basis by adding to the buffer a
4618 line like
4620 #+ARCHIVE: basement::** Finished Tasks
4622 You may also define it locally for a subtree by setting an ARCHIVE property
4623 in the entry. If such a property is found in an entry, or anywhere up
4624 the hierarchy, it will be used."
4625 :group 'org-archive
4626 :type 'string)
4628 (defcustom org-agenda-skip-archived-trees t
4629 "Non-nil means the agenda will skip any items located in archived trees.
4630 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4631 variable is no longer recommended, you should leave it at the value t.
4632 Instead, use the key `v' to cycle the archives-mode in the agenda."
4633 :group 'org-archive
4634 :group 'org-agenda-skip
4635 :type 'boolean)
4637 (defcustom org-columns-skip-archived-trees t
4638 "Non-nil means ignore archived trees when creating column view."
4639 :group 'org-archive
4640 :group 'org-properties
4641 :type 'boolean)
4643 (defcustom org-cycle-open-archived-trees nil
4644 "Non-nil means `org-cycle' will open archived trees.
4645 An archived tree is a tree marked with the tag ARCHIVE.
4646 When nil, archived trees will stay folded. You can still open them with
4647 normal outline commands like `show-all', but not with the cycling commands."
4648 :group 'org-archive
4649 :group 'org-cycle
4650 :type 'boolean)
4652 (defcustom org-sparse-tree-open-archived-trees nil
4653 "Non-nil means sparse tree construction shows matches in archived trees.
4654 When nil, matches in these trees are highlighted, but the trees are kept in
4655 collapsed state."
4656 :group 'org-archive
4657 :group 'org-sparse-trees
4658 :type 'boolean)
4660 (defcustom org-sparse-tree-default-date-type nil
4661 "The default date type when building a sparse tree.
4662 When this is nil, a date is a scheduled or a deadline timestamp.
4663 Otherwise, these types are allowed:
4665 all: all timestamps
4666 active: only active timestamps (<...>)
4667 inactive: only inactive timestamps ([...])
4668 scheduled: only scheduled timestamps
4669 deadline: only deadline timestamps"
4670 :type '(choice (const :tag "Scheduled or deadline" nil)
4671 (const :tag "All timestamps" all)
4672 (const :tag "Only active timestamps" active)
4673 (const :tag "Only inactive timestamps" inactive)
4674 (const :tag "Only scheduled timestamps" scheduled)
4675 (const :tag "Only deadline timestamps" deadline)
4676 (const :tag "Only closed timestamps" closed))
4677 :version "25.1"
4678 :package-version '(Org . "8.3")
4679 :group 'org-sparse-trees)
4681 (defun org-cycle-hide-archived-subtrees (state)
4682 "Re-hide all archived subtrees after a visibility state change."
4683 (when (and (not org-cycle-open-archived-trees)
4684 (not (memq state '(overview folded))))
4685 (save-excursion
4686 (let* ((globalp (memq state '(contents all)))
4687 (beg (if globalp (point-min) (point)))
4688 (end (if globalp (point-max) (org-end-of-subtree t))))
4689 (org-hide-archived-subtrees beg end)
4690 (goto-char beg)
4691 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4692 (message "%s" (substitute-command-keys
4693 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4695 (defun org-force-cycle-archived ()
4696 "Cycle subtree even if it is archived."
4697 (interactive)
4698 (setq this-command 'org-cycle)
4699 (let ((org-cycle-open-archived-trees t))
4700 (call-interactively 'org-cycle)))
4702 (defun org-hide-archived-subtrees (beg end)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (org-with-wide-buffer
4705 (let ((case-fold-search nil)
4706 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4707 (goto-char beg)
4708 ;; Include headline point is currently on.
4709 (beginning-of-line)
4710 (while (and (< (point) end) (re-search-forward re end t))
4711 (when (member org-archive-tag (org-get-tags))
4712 (org-flag-subtree t)
4713 (org-end-of-subtree t))))))
4715 (declare-function outline-end-of-heading "outline" ())
4716 (declare-function outline-flag-region "outline" (from to flag))
4717 (defun org-flag-subtree (flag)
4718 (save-excursion
4719 (org-back-to-heading t)
4720 (outline-end-of-heading)
4721 (outline-flag-region (point)
4722 (progn (org-end-of-subtree t) (point))
4723 flag)))
4725 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4727 ;; Declare Column View Code
4729 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4730 (declare-function org-columns-compute "org-colview" (property))
4732 ;; Declare ID code
4734 (declare-function org-id-store-link "org-id")
4735 (declare-function org-id-locations-load "org-id")
4736 (declare-function org-id-locations-save "org-id")
4737 (defvar org-id-track-globally)
4739 ;;; Variables for pre-computed regular expressions, all buffer local
4741 (defvar-local org-todo-regexp nil
4742 "Matches any of the TODO state keywords.")
4743 (defvar-local org-not-done-regexp nil
4744 "Matches any of the TODO state keywords except the last one.")
4745 (defvar-local org-not-done-heading-regexp nil
4746 "Matches a TODO headline that is not done.")
4747 (defvar-local org-todo-line-regexp nil
4748 "Matches a headline and puts TODO state into group 2 if present.")
4749 (defvar-local org-complex-heading-regexp nil
4750 "Matches a headline and puts everything into groups:
4751 group 1: the stars
4752 group 2: The todo keyword, maybe
4753 group 3: Priority cookie
4754 group 4: True headline
4755 group 5: Tags")
4756 (defvar-local org-complex-heading-regexp-format nil
4757 "Printf format to make regexp to match an exact headline.
4758 This regexp will match the headline of any node which has the
4759 exact headline text that is put into the format, but may have any
4760 TODO state, priority and tags.")
4761 (defvar-local org-todo-line-tags-regexp nil
4762 "Matches a headline and puts TODO state into group 2 if present.
4763 Also put tags into group 4 if tags are present.")
4765 (defconst org-plain-time-of-day-regexp
4766 (concat
4767 "\\(\\<[012]?[0-9]"
4768 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4769 "\\(--?"
4770 "\\(\\<[012]?[0-9]"
4771 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4772 "\\)?")
4773 "Regular expression to match a plain time or time range.
4774 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4775 groups carry important information:
4776 0 the full match
4777 1 the first time, range or not
4778 8 the second time, if it is a range.")
4780 (defconst org-plain-time-extension-regexp
4781 (concat
4782 "\\(\\<[012]?[0-9]"
4783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4785 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4786 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4787 groups carry important information:
4788 0 the full match
4789 7 hours of duration
4790 9 minutes of duration")
4792 (defconst org-stamp-time-of-day-regexp
4793 (concat
4794 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4795 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4796 "\\(--?"
4797 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4798 "Regular expression to match a timestamp time or time range.
4799 After a match, the following groups carry important information:
4800 0 the full match
4801 1 date plus weekday, for back referencing to make sure both times are on the same day
4802 2 the first time, range or not
4803 4 the second time, if it is a range.")
4805 (defconst org-startup-options
4806 '(("fold" org-startup-folded t)
4807 ("overview" org-startup-folded t)
4808 ("nofold" org-startup-folded nil)
4809 ("showall" org-startup-folded nil)
4810 ("showeverything" org-startup-folded showeverything)
4811 ("content" org-startup-folded content)
4812 ("indent" org-startup-indented t)
4813 ("noindent" org-startup-indented nil)
4814 ("hidestars" org-hide-leading-stars t)
4815 ("showstars" org-hide-leading-stars nil)
4816 ("odd" org-odd-levels-only t)
4817 ("oddeven" org-odd-levels-only nil)
4818 ("align" org-startup-align-all-tables t)
4819 ("noalign" org-startup-align-all-tables nil)
4820 ("inlineimages" org-startup-with-inline-images t)
4821 ("noinlineimages" org-startup-with-inline-images nil)
4822 ("latexpreview" org-startup-with-latex-preview t)
4823 ("nolatexpreview" org-startup-with-latex-preview nil)
4824 ("customtime" org-display-custom-times t)
4825 ("logdone" org-log-done time)
4826 ("lognotedone" org-log-done note)
4827 ("nologdone" org-log-done nil)
4828 ("lognoteclock-out" org-log-note-clock-out t)
4829 ("nolognoteclock-out" org-log-note-clock-out nil)
4830 ("logrepeat" org-log-repeat state)
4831 ("lognoterepeat" org-log-repeat note)
4832 ("logdrawer" org-log-into-drawer t)
4833 ("nologdrawer" org-log-into-drawer nil)
4834 ("logstatesreversed" org-log-states-order-reversed t)
4835 ("nologstatesreversed" org-log-states-order-reversed nil)
4836 ("nologrepeat" org-log-repeat nil)
4837 ("logreschedule" org-log-reschedule time)
4838 ("lognotereschedule" org-log-reschedule note)
4839 ("nologreschedule" org-log-reschedule nil)
4840 ("logredeadline" org-log-redeadline time)
4841 ("lognoteredeadline" org-log-redeadline note)
4842 ("nologredeadline" org-log-redeadline nil)
4843 ("logrefile" org-log-refile time)
4844 ("lognoterefile" org-log-refile note)
4845 ("nologrefile" org-log-refile nil)
4846 ("fninline" org-footnote-define-inline t)
4847 ("nofninline" org-footnote-define-inline nil)
4848 ("fnlocal" org-footnote-section nil)
4849 ("fnauto" org-footnote-auto-label t)
4850 ("fnprompt" org-footnote-auto-label nil)
4851 ("fnconfirm" org-footnote-auto-label confirm)
4852 ("fnplain" org-footnote-auto-label plain)
4853 ("fnadjust" org-footnote-auto-adjust t)
4854 ("nofnadjust" org-footnote-auto-adjust nil)
4855 ("constcgs" constants-unit-system cgs)
4856 ("constSI" constants-unit-system SI)
4857 ("noptag" org-tag-persistent-alist nil)
4858 ("hideblocks" org-hide-block-startup t)
4859 ("nohideblocks" org-hide-block-startup nil)
4860 ("beamer" org-startup-with-beamer-mode t)
4861 ("entitiespretty" org-pretty-entities t)
4862 ("entitiesplain" org-pretty-entities nil))
4863 "Variable associated with STARTUP options for org-mode.
4864 Each element is a list of three items: the startup options (as written
4865 in the #+STARTUP line), the corresponding variable, and the value to set
4866 this variable to if the option is found. An optional forth element PUSH
4867 means to push this value onto the list in the variable.")
4869 (defcustom org-group-tags t
4870 "When non-nil (the default), use group tags.
4871 This can be turned on/off through `org-toggle-tags-groups'."
4872 :group 'org-tags
4873 :group 'org-startup
4874 :type 'boolean)
4876 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4878 (defun org-toggle-tags-groups ()
4879 "Toggle support for group tags.
4880 Support for group tags is controlled by the option
4881 `org-group-tags', which is non-nil by default."
4882 (interactive)
4883 (setq org-group-tags (not org-group-tags))
4884 (cond ((and (derived-mode-p 'org-agenda-mode)
4885 org-group-tags)
4886 (org-agenda-redo))
4887 ((derived-mode-p 'org-mode)
4888 (let ((org-inhibit-startup t)) (org-mode))))
4889 (message "Groups tags support has been turned %s"
4890 (if org-group-tags "on" "off")))
4892 (defun org-set-regexps-and-options (&optional tags-only)
4893 "Precompute regular expressions used in the current buffer.
4894 When optional argument TAGS-ONLY is non-nil, only compute tags
4895 related expressions."
4896 (when (derived-mode-p 'org-mode)
4897 (let ((alist (org--setup-collect-keywords
4898 (org-make-options-regexp
4899 (append '("FILETAGS" "TAGS" "SETUPFILE")
4900 (and (not tags-only)
4901 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4902 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4903 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4904 (org--setup-process-tags
4905 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4906 (unless tags-only
4907 ;; File properties.
4908 (setq-local org-file-properties (cdr (assq 'property alist)))
4909 ;; Archive location.
4910 (let ((archive (cdr (assq 'archive alist))))
4911 (when archive (setq-local org-archive-location archive)))
4912 ;; Category.
4913 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4914 (when cat
4915 (setq-local org-category (intern cat))
4916 (setq-local org-file-properties
4917 (org--update-property-plist
4918 "CATEGORY" cat org-file-properties))))
4919 ;; Columns.
4920 (let ((column (cdr (assq 'columns alist))))
4921 (when column (setq-local org-columns-default-format column)))
4922 ;; Constants.
4923 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4924 ;; Link abbreviations.
4925 (let ((links (cdr (assq 'link alist))))
4926 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4927 ;; Priorities.
4928 (let ((priorities (cdr (assq 'priorities alist))))
4929 (when priorities
4930 (setq-local org-highest-priority (nth 0 priorities))
4931 (setq-local org-lowest-priority (nth 1 priorities))
4932 (setq-local org-default-priority (nth 2 priorities))))
4933 ;; Scripts.
4934 (let ((scripts (assq 'scripts alist)))
4935 (when scripts
4936 (setq-local org-use-sub-superscripts (cdr scripts))))
4937 ;; Startup options.
4938 (let ((startup (cdr (assq 'startup alist))))
4939 (dolist (option startup)
4940 (let ((entry (assoc-string option org-startup-options t)))
4941 (when entry
4942 (let ((var (nth 1 entry))
4943 (val (nth 2 entry)))
4944 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4945 (unless (listp (symbol-value var))
4946 (set (make-local-variable var) nil))
4947 (add-to-list var val)))))))
4948 ;; TODO keywords.
4949 (setq-local org-todo-kwd-alist nil)
4950 (setq-local org-todo-key-alist nil)
4951 (setq-local org-todo-key-trigger nil)
4952 (setq-local org-todo-keywords-1 nil)
4953 (setq-local org-done-keywords nil)
4954 (setq-local org-todo-heads nil)
4955 (setq-local org-todo-sets nil)
4956 (setq-local org-todo-log-states nil)
4957 (let ((todo-sequences
4958 (or (nreverse (cdr (assq 'todo alist)))
4959 (let ((d (default-value 'org-todo-keywords)))
4960 (if (not (stringp (car d))) d
4961 ;; XXX: Backward compatibility code.
4962 (list (cons org-todo-interpretation d)))))))
4963 (dolist (sequence todo-sequences)
4964 (let* ((sequence (or (run-hook-with-args-until-success
4965 'org-todo-setup-filter-hook sequence)
4966 sequence))
4967 (sequence-type (car sequence))
4968 (keywords (cdr sequence))
4969 (sep (member "|" keywords))
4970 names alist)
4971 (dolist (k (remove "|" keywords))
4972 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4974 (error "Invalid TODO keyword %s" k))
4975 (let ((name (match-string 1 k))
4976 (key (match-string 2 k))
4977 (log (org-extract-log-state-settings k)))
4978 (push name names)
4979 (push (cons name (and key (string-to-char key))) alist)
4980 (when log (push log org-todo-log-states))))
4981 (let* ((names (nreverse names))
4982 (done (if sep (org-remove-keyword-keys (cdr sep))
4983 (last names)))
4984 (head (car names))
4985 (tail (list sequence-type head (car done) (org-last done))))
4986 (add-to-list 'org-todo-heads head 'append)
4987 (push names org-todo-sets)
4988 (setq org-done-keywords (append org-done-keywords done nil))
4989 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4990 (setq org-todo-key-alist
4991 (append org-todo-key-alist
4992 (and alist
4993 (append '((:startgroup))
4994 (nreverse alist)
4995 '((:endgroup))))))
4996 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4997 (setq org-todo-sets (nreverse org-todo-sets)
4998 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4999 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5000 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5001 ;; Compute the regular expressions and other local variables.
5002 ;; Using `org-outline-regexp-bol' would complicate them much,
5003 ;; because of the fixed white space at the end of that string.
5004 (unless org-done-keywords
5005 (setq org-done-keywords
5006 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5007 (setq org-not-done-keywords
5008 (org-delete-all org-done-keywords
5009 (copy-sequence org-todo-keywords-1))
5010 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5011 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5012 org-not-done-heading-regexp
5013 (format org-heading-keyword-regexp-format org-not-done-regexp)
5014 org-todo-line-regexp
5015 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5016 org-complex-heading-regexp
5017 (concat "^\\(\\*+\\)"
5018 "\\(?: +" org-todo-regexp "\\)?"
5019 "\\(?: +\\(\\[#.\\]\\)\\)?"
5020 "\\(?: +\\(.*?\\)\\)??"
5021 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5022 "[ \t]*$")
5023 org-complex-heading-regexp-format
5024 (concat "^\\(\\*+\\)"
5025 "\\(?: +" org-todo-regexp "\\)?"
5026 "\\(?: +\\(\\[#.\\]\\)\\)?"
5027 "\\(?: +"
5028 ;; Stats cookies can be stuck to body.
5029 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5030 "\\(%s\\)"
5031 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5032 "\\)"
5033 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5034 "[ \t]*$")
5035 org-todo-line-tags-regexp
5036 (concat "^\\(\\*+\\)"
5037 "\\(?: +" org-todo-regexp "\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5040 "[ \t]*$"))
5041 (org-compute-latex-and-related-regexp)))))
5043 (defun org--setup-collect-keywords (regexp &optional files alist)
5044 "Return setup keywords values as an alist.
5046 REGEXP matches a subset of setup keywords. FILES is a list of
5047 file names already visited. It is used to avoid circular setup
5048 files. ALIST, when non-nil, is the alist computed so far.
5050 Return value contains the following keys: `archive', `category',
5051 `columns', `constants', `filetags', `link', `priorities',
5052 `property', `scripts', `startup', `tags' and `todo'."
5053 (org-with-wide-buffer
5054 (goto-char (point-min))
5055 (let ((case-fold-search t))
5056 (while (re-search-forward regexp nil t)
5057 (let ((element (org-element-at-point)))
5058 (when (eq (org-element-type element) 'keyword)
5059 (let ((key (org-element-property :key element))
5060 (value (org-element-property :value element)))
5061 (cond
5062 ((equal key "ARCHIVE")
5063 (when (org-string-nw-p value)
5064 (push (cons 'archive value) alist)))
5065 ((equal key "CATEGORY") (push (cons 'category value) alist))
5066 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5067 ((equal key "CONSTANTS")
5068 (let* ((constants (assq 'constants alist))
5069 (store (cdr constants)))
5070 (dolist (pair (org-split-string value))
5071 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5072 pair)
5073 (let* ((name (match-string 1 pair))
5074 (value (match-string 2 pair))
5075 (old (assoc name store)))
5076 (if old (setcdr old value)
5077 (push (cons name value) store)))))
5078 (if constants (setcdr constants store)
5079 (push (cons 'constants store) alist))))
5080 ((equal key "FILETAGS")
5081 (when (org-string-nw-p value)
5082 (let ((old (assq 'filetags alist))
5083 (new (apply #'nconc
5084 (mapcar (lambda (x) (org-split-string x ":"))
5085 (org-split-string value)))))
5086 (if old (setcdr old (append new (cdr old)))
5087 (push (cons 'filetags new) alist)))))
5088 ((equal key "LINK")
5089 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5090 (let ((links (assq 'link alist))
5091 (pair (cons (org-match-string-no-properties 1 value)
5092 (org-match-string-no-properties 2 value))))
5093 (if links (push pair (cdr links))
5094 (push (list 'link pair) alist)))))
5095 ((equal key "OPTIONS")
5096 (when (and (org-string-nw-p value)
5097 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5098 (push (cons 'scripts (read (match-string 1 value))) alist)))
5099 ((equal key "PRIORITIES")
5100 (push (cons 'priorities
5101 (let ((prio (org-split-string value)))
5102 (if (< (length prio) 3) '(?A ?C ?B)
5103 (mapcar #'string-to-char prio))))
5104 alist))
5105 ((equal key "PROPERTY")
5106 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5107 (let* ((property (assq 'property alist))
5108 (value (org--update-property-plist
5109 (org-match-string-no-properties 1 value)
5110 (org-match-string-no-properties 2 value)
5111 (cdr property))))
5112 (if property (setcdr property value)
5113 (push (cons 'property value) alist)))))
5114 ((equal key "STARTUP")
5115 (let ((startup (assq 'startup alist)))
5116 (if startup
5117 (setcdr startup
5118 (append (cdr startup) (org-split-string value)))
5119 (push (cons 'startup (org-split-string value)) alist))))
5120 ((equal key "TAGS")
5121 (let ((tag-cell (assq 'tags alist)))
5122 (if tag-cell
5123 (setcdr tag-cell
5124 (append (cdr tag-cell)
5125 '("\\n")
5126 (org-split-string value)))
5127 (push (cons 'tags (org-split-string value)) alist))))
5128 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5129 (let ((todo (assq 'todo alist))
5130 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5131 (org-split-string value))))
5132 (if todo (push value (cdr todo))
5133 (push (list 'todo value) alist))))
5134 ((equal key "SETUPFILE")
5135 (unless buffer-read-only ; Do not check in Gnus messages.
5136 (let ((f (and (org-string-nw-p value)
5137 (expand-file-name
5138 (org-remove-double-quotes value)))))
5139 (when (and f (file-readable-p f) (not (member f files)))
5140 (with-temp-buffer
5141 (setq default-directory (file-name-directory f))
5142 (insert-file-contents f)
5143 (setq alist
5144 ;; Fake Org mode to benefit from cache
5145 ;; without recurring needlessly.
5146 (let ((major-mode 'org-mode))
5147 (org--setup-collect-keywords
5148 regexp (cons f files) alist)))))))))))))))
5149 alist)
5151 (defun org--setup-process-tags (tags filetags)
5152 "Precompute variables used for tags.
5153 TAGS is a list of tags and tag group symbols, as strings.
5154 FILETAGS is a list of tags, as strings."
5155 ;; Process the file tags.
5156 (setq-local org-file-tags
5157 (mapcar #'org-add-prop-inherited filetags))
5158 ;; Provide default tags if no local tags are found.
5159 (when (and (not tags) org-tag-alist)
5160 (setq tags
5161 (mapcar (lambda (tag)
5162 (cl-case (car tag)
5163 (:startgroup "{")
5164 (:endgroup "}")
5165 (:startgrouptag "[")
5166 (:endgrouptag "]")
5167 (:grouptags ":")
5168 (:newline "\\n")
5169 (otherwise (concat (car tag)
5170 (and (characterp (cdr tag))
5171 (format "(%c)" (cdr tag)))))))
5172 org-tag-alist)))
5173 ;; Process the tags.
5174 (setq-local org-tag-groups-alist nil)
5175 (setq-local org-tag-alist nil)
5176 (let (group-flag)
5177 (while tags
5178 (let ((e (car tags)))
5179 (setq tags (cdr tags))
5180 (cond
5181 ((equal e "{")
5182 (push '(:startgroup) org-tag-alist)
5183 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5184 ((equal e "}")
5185 (push '(:endgroup) org-tag-alist)
5186 (setq group-flag nil))
5187 ((equal e "[")
5188 (push '(:startgrouptag) org-tag-alist)
5189 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5190 ((equal e "]")
5191 (push '(:endgrouptag) org-tag-alist)
5192 (setq group-flag nil))
5193 ((equal e ":")
5194 (push '(:grouptags) org-tag-alist)
5195 (setq group-flag 'append))
5196 ((equal e "\\n") (push '(:newline) org-tag-alist))
5197 ((string-match
5198 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5199 "\\|{.+?}\\)" ; regular expression
5200 "\\(?:(\\(.\\))\\)?\\'")) e)
5201 (let ((tag (match-string 1 e))
5202 (key (and (match-beginning 2)
5203 (string-to-char (match-string 2 e)))))
5204 (cond ((eq group-flag 'append)
5205 (setcar org-tag-groups-alist
5206 (append (car org-tag-groups-alist) (list tag))))
5207 (group-flag (push (list tag) org-tag-groups-alist)))
5208 ;; Push all tags in groups, no matter if they already exist.
5209 (unless (and (not group-flag) (assoc tag org-tag-alist))
5210 (push (cons tag key) org-tag-alist))))))))
5211 (setq org-tag-alist (nreverse org-tag-alist)))
5213 (defun org-file-contents (file &optional noerror)
5214 "Return the contents of FILE, as a string."
5215 (if (and file (file-readable-p file))
5216 (with-temp-buffer
5217 (insert-file-contents file)
5218 (buffer-string))
5219 (funcall (if noerror 'message 'error)
5220 "Cannot read file \"%s\"%s"
5221 file
5222 (let ((from (buffer-file-name (buffer-base-buffer))))
5223 (if from (concat " (referenced in file \"" from "\")") "")))))
5225 (defun org-extract-log-state-settings (x)
5226 "Extract the log state setting from a TODO keyword string.
5227 This will extract info from a string like \"WAIT(w@/!)\"."
5228 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5229 (let ((kw (match-string 1 x))
5230 (log1 (and (match-end 3) (match-string 3 x)))
5231 (log2 (and (match-end 4) (match-string 4 x))))
5232 (and (or log1 log2)
5233 (list kw
5234 (and log1 (if (equal log1 "!") 'time 'note))
5235 (and log2 (if (equal log2 "!") 'time 'note)))))))
5237 (defun org-remove-keyword-keys (list)
5238 "Remove a pair of parenthesis at the end of each string in LIST."
5239 (mapcar (lambda (x)
5240 (if (string-match "(.*)$" x)
5241 (substring x 0 (match-beginning 0))
5243 list))
5245 (defun org-assign-fast-keys (alist)
5246 "Assign fast keys to a keyword-key alist.
5247 Respect keys that are already there."
5248 (let (new e (alt ?0))
5249 (while (setq e (pop alist))
5250 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5251 (cdr e)) ;; Key already assigned.
5252 (push e new)
5253 (let ((clist (string-to-list (downcase (car e))))
5254 (used (append new alist)))
5255 (when (= (car clist) ?@)
5256 (pop clist))
5257 (while (and clist (rassoc (car clist) used))
5258 (pop clist))
5259 (unless clist
5260 (while (rassoc alt used)
5261 (cl-incf alt)))
5262 (push (cons (car e) (or (car clist) alt)) new))))
5263 (nreverse new)))
5265 ;;; Some variables used in various places
5267 (defvar org-window-configuration nil
5268 "Used in various places to store a window configuration.")
5269 (defvar org-selected-window nil
5270 "Used in various places to store a window configuration.")
5271 (defvar org-finish-function nil
5272 "Function to be called when `C-c C-c' is used.
5273 This is for getting out of special buffers like capture.")
5274 (defvar org-last-state)
5276 ;; Defined somewhere in this file, but used before definition.
5277 (defvar org-entities) ;; defined in org-entities.el
5278 (defvar org-struct-menu)
5279 (defvar org-org-menu)
5280 (defvar org-tbl-menu)
5282 ;;;; Define the Org-mode
5284 ;; We use a before-change function to check if a table might need
5285 ;; an update.
5286 (defvar org-table-may-need-update t
5287 "Indicates that a table might need an update.
5288 This variable is set by `org-before-change-function'.
5289 `org-table-align' sets it back to nil.")
5290 (defun org-before-change-function (_beg _end)
5291 "Every change indicates that a table might need an update."
5292 (setq org-table-may-need-update t))
5293 (defvar org-mode-map)
5294 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5295 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5296 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5297 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5298 (defvar org-table-buffer-is-an nil)
5300 (defvar bidi-paragraph-direction)
5301 (defvar buffer-face-mode-face)
5303 (require 'outline)
5304 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5305 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5306 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5308 ;; Other stuff we need.
5309 (require 'time-date)
5310 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5311 (require 'easymenu)
5312 (autoload 'easy-menu-add "easymenu")
5313 (require 'overlay)
5315 ;; (require 'org-macs) moved higher up in the file before it is first used
5316 (require 'org-entities)
5317 ;; (require 'org-compat) moved higher up in the file before it is first used
5318 (require 'org-faces)
5319 (require 'org-list)
5320 (require 'org-pcomplete)
5321 (require 'org-src)
5322 (require 'org-footnote)
5323 (require 'org-macro)
5325 ;; babel
5326 (require 'ob)
5328 ;;;###autoload
5329 (define-derived-mode org-mode outline-mode "Org"
5330 "Outline-based notes management and organizer, alias
5331 \"Carsten's outline-mode for keeping track of everything.\"
5333 Org-mode develops organizational tasks around a NOTES file which
5334 contains information about projects as plain text. Org-mode is
5335 implemented on top of outline-mode, which is ideal to keep the content
5336 of large files well structured. It supports ToDo items, deadlines and
5337 time stamps, which magically appear in the diary listing of the Emacs
5338 calendar. Tables are easily created with a built-in table editor.
5339 Plain text URL-like links connect to websites, emails (VM), Usenet
5340 messages (Gnus), BBDB entries, and any files related to the project.
5341 For printing and sharing of notes, an Org-mode file (or a part of it)
5342 can be exported as a structured ASCII or HTML file.
5344 The following commands are available:
5346 \\{org-mode-map}"
5348 ;; Get rid of Outline menus, they are not needed
5349 ;; Need to do this here because define-derived-mode sets up
5350 ;; the keymap so late. Still, it is a waste to call this each time
5351 ;; we switch another buffer into org-mode.
5352 (if (featurep 'xemacs)
5353 (when (boundp 'outline-mode-menu-heading)
5354 ;; Assume this is Greg's port, it uses easymenu
5355 (easy-menu-remove outline-mode-menu-heading)
5356 (easy-menu-remove outline-mode-menu-show)
5357 (easy-menu-remove outline-mode-menu-hide))
5358 (define-key org-mode-map [menu-bar headings] 'undefined)
5359 (define-key org-mode-map [menu-bar hide] 'undefined)
5360 (define-key org-mode-map [menu-bar show] 'undefined))
5362 (org-load-modules-maybe)
5363 (when (featurep 'xemacs)
5364 (easy-menu-add org-org-menu)
5365 (easy-menu-add org-tbl-menu))
5366 (org-install-agenda-files-menu)
5367 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5368 (add-to-invisibility-spec '(org-cwidth))
5369 (add-to-invisibility-spec '(org-hide-block . t))
5370 (when (featurep 'xemacs)
5371 (setq-local line-move-ignore-invisible t))
5372 (setq-local outline-regexp org-outline-regexp)
5373 (setq-local outline-level 'org-outline-level)
5374 (setq bidi-paragraph-direction 'left-to-right)
5375 (when (and org-ellipsis
5376 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5377 (fboundp 'make-glyph-code))
5378 (unless org-display-table
5379 (setq org-display-table (make-display-table)))
5380 (set-display-table-slot
5381 org-display-table 4
5382 (vconcat (mapcar
5383 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5384 org-ellipsis)))
5385 (if (stringp org-ellipsis) org-ellipsis "..."))))
5386 (setq buffer-display-table org-display-table))
5387 (org-set-regexps-and-options)
5388 (org-set-font-lock-defaults)
5389 (when (and org-tag-faces (not org-tags-special-faces-re))
5390 ;; tag faces set outside customize.... force initialization.
5391 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5392 ;; Calc embedded
5393 (setq-local calc-embedded-open-mode "# ")
5394 ;; Modify a few syntax entries
5395 (modify-syntax-entry ?@ "w")
5396 (modify-syntax-entry ?\" "\"")
5397 (modify-syntax-entry ?\\ "_")
5398 (modify-syntax-entry ?~ "_")
5399 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5400 ;; Activate before-change-function
5401 (setq-local org-table-may-need-update t)
5402 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5403 ;; Check for running clock before killing a buffer
5404 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5405 ;; Initialize macros templates.
5406 (org-macro-initialize-templates)
5407 ;; Initialize radio targets.
5408 (org-update-radio-target-regexp)
5409 ;; Indentation.
5410 (setq-local indent-line-function 'org-indent-line)
5411 (setq-local indent-region-function 'org-indent-region)
5412 ;; Filling and auto-filling.
5413 (org-setup-filling)
5414 ;; Comments.
5415 (org-setup-comments-handling)
5416 ;; Initialize cache.
5417 (org-element-cache-reset)
5418 ;; Beginning/end of defun
5419 (setq-local beginning-of-defun-function 'org-backward-element)
5420 (setq-local end-of-defun-function
5421 (lambda ()
5422 (if (not (org-at-heading-p))
5423 (org-forward-element)
5424 (org-forward-element)
5425 (forward-char -1))))
5426 ;; Next error for sparse trees
5427 (setq-local next-error-function 'org-occur-next-match)
5428 ;; Make sure dependence stuff works reliably, even for users who set it
5429 ;; too late :-(
5430 (if org-enforce-todo-dependencies
5431 (add-hook 'org-blocker-hook
5432 'org-block-todo-from-children-or-siblings-or-parent)
5433 (remove-hook 'org-blocker-hook
5434 'org-block-todo-from-children-or-siblings-or-parent))
5435 (if org-enforce-todo-checkbox-dependencies
5436 (add-hook 'org-blocker-hook
5437 'org-block-todo-from-checkboxes)
5438 (remove-hook 'org-blocker-hook
5439 'org-block-todo-from-checkboxes))
5441 ;; Align options lines
5442 (setq-local
5443 align-mode-rules-list
5444 '((org-in-buffer-settings
5445 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5446 (modes . '(org-mode)))))
5448 ;; Imenu
5449 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5451 ;; Make isearch reveal context
5452 (setq-local outline-isearch-open-invisible-function
5453 (lambda (&rest _) (org-show-context 'isearch)))
5455 ;; Setup the pcomplete hooks
5456 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5457 (setq-local pcomplete-command-name-function 'org-command-at-point)
5458 (setq-local pcomplete-default-completion-function 'ignore)
5459 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5460 (setq-local pcomplete-termination-string "")
5461 (setq-local buffer-face-mode-face 'org-default)
5463 ;; If empty file that did not turn on Org mode automatically, make
5464 ;; it to.
5465 (when (and org-insert-mode-line-in-empty-file
5466 (org-called-interactively-p 'any)
5467 (= (point-min) (point-max)))
5468 (insert "# -*- mode: org -*-\n\n"))
5469 (unless org-inhibit-startup
5470 (org-unmodified
5471 (when org-startup-with-beamer-mode (org-beamer-mode))
5472 (when org-startup-align-all-tables
5473 (org-table-map-tables #'org-table-align t))
5474 (when org-startup-with-inline-images (org-display-inline-images))
5475 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5476 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5477 (when org-startup-truncated (setq truncate-lines t))
5478 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5479 (org-refresh-effort-properties)))
5480 ;; Try to set `org-hide' face correctly.
5481 (let ((foreground (org-find-invisible-foreground)))
5482 (when foreground
5483 (set-face-foreground 'org-hide foreground))))
5485 ;; Update `customize-package-emacs-version-alist'
5486 (add-to-list 'customize-package-emacs-version-alist
5487 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5488 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5489 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5491 (defvar org-mode-transpose-word-syntax-table
5492 (let ((st (make-syntax-table text-mode-syntax-table)))
5493 (dolist (c org-emphasis-alist st)
5494 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5496 (when (fboundp 'abbrev-table-put)
5497 (abbrev-table-put org-mode-abbrev-table
5498 :parents (list text-mode-abbrev-table)))
5500 (defun org-find-invisible-foreground ()
5501 (let ((candidates (remove
5502 "unspecified-bg"
5503 (nconc
5504 (list (face-background 'default)
5505 (face-background 'org-default))
5506 (mapcar
5507 (lambda (alist)
5508 (when (boundp alist)
5509 (cdr (assoc 'background-color (symbol-value alist)))))
5510 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5511 (list (face-foreground 'org-hide))))))
5512 (car (remove nil candidates))))
5514 (defun org-current-time (&optional rounding-minutes past)
5515 "Current time, possibly rounded to ROUNDING-MINUTES.
5516 When ROUNDING-MINUTES is not an integer, fall back on the car of
5517 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5518 the rounding returns a past time."
5519 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5520 (car org-time-stamp-rounding-minutes)))
5521 (time (decode-time)) res)
5522 (if (< r 1)
5523 (current-time)
5524 (setq res
5525 (apply 'encode-time
5526 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5527 (nthcdr 2 time))))
5528 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5529 (seconds-to-time (- (org-float-time res) (* r 60)))
5530 res))))
5532 (defun org-today ()
5533 "Return today date, considering `org-extend-today-until'."
5534 (time-to-days
5535 (time-subtract (current-time)
5536 (list 0 (* 3600 org-extend-today-until) 0))))
5538 ;;;; Font-Lock stuff, including the activators
5540 (defvar org-mouse-map (make-sparse-keymap))
5541 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5542 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5543 (when org-mouse-1-follows-link
5544 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5545 (when org-tab-follows-link
5546 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5547 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5549 (require 'font-lock)
5551 (defconst org-non-link-chars "]\t\n\r<>")
5552 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5553 "file+sys" "news" "shell" "elisp" "doi" "message"
5554 "help"))
5555 (defvar org-link-types-re nil
5556 "Matches a link that has a url-like prefix like \"http:\"")
5557 (defvar org-link-re-with-space nil
5558 "Matches a link with spaces, optional angular brackets around it.")
5559 (defvar org-link-re-with-space2 nil
5560 "Matches a link with spaces, optional angular brackets around it.")
5561 (defvar org-link-re-with-space3 nil
5562 "Matches a link with spaces, only for internal part in bracket links.")
5563 (defvar org-angle-link-re nil
5564 "Matches link with angular brackets, spaces are allowed.")
5565 (defvar org-plain-link-re nil
5566 "Matches plain link, without spaces.")
5567 (defvar org-bracket-link-regexp nil
5568 "Matches a link in double brackets.")
5569 (defvar org-bracket-link-analytic-regexp nil
5570 "Regular expression used to analyze links.
5571 Here is what the match groups contain after a match:
5572 1: http:
5573 2: http
5574 3: path
5575 4: [desc]
5576 5: desc")
5577 (defvar org-bracket-link-analytic-regexp++ nil
5578 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5579 (defvar org-any-link-re nil
5580 "Regular expression matching any link.")
5582 (defconst org-match-sexp-depth 3
5583 "Number of stacked braces for sub/superscript matching.")
5585 (defun org-create-multibrace-regexp (left right n)
5586 "Create a regular expression which will match a balanced sexp.
5587 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5588 as single character strings.
5589 The regexp returned will match the entire expression including the
5590 delimiters. It will also define a single group which contains the
5591 match except for the outermost delimiters. The maximum depth of
5592 stacked delimiters is N. Escaping delimiters is not possible."
5593 (let* ((nothing (concat "[^" left right "]*?"))
5594 (or "\\|")
5595 (re nothing)
5596 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5597 (while (> n 1)
5598 (setq n (1- n)
5599 re (concat re or next)
5600 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5601 (concat left "\\(" re "\\)" right)))
5603 (defconst org-match-substring-regexp
5604 (concat
5605 "\\(\\S-\\)\\([_^]\\)\\("
5606 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5607 "\\|"
5608 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5609 "\\|"
5610 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5611 "The regular expression matching a sub- or superscript.")
5613 (defconst org-match-substring-with-braces-regexp
5614 (concat
5615 "\\(\\S-\\)\\([_^]\\)"
5616 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5617 "The regular expression matching a sub- or superscript, forcing braces.")
5619 (defun org-make-link-regexps ()
5620 "Update the link regular expressions.
5621 This should be called after the variable `org-link-types' has changed."
5622 (let ((types-re (regexp-opt org-link-types t)))
5623 (setq org-link-types-re
5624 (concat "\\`" types-re ":")
5625 org-link-re-with-space
5626 (concat "<?" types-re ":"
5627 "\\([^" org-non-link-chars " ]"
5628 "[^" org-non-link-chars "]*"
5629 "[^" org-non-link-chars " ]\\)>?")
5630 org-link-re-with-space2
5631 (concat "<?" types-re ":"
5632 "\\([^" org-non-link-chars " ]"
5633 "[^\t\n\r]*"
5634 "[^" org-non-link-chars " ]\\)>?")
5635 org-link-re-with-space3
5636 (concat "<?" types-re ":"
5637 "\\([^" org-non-link-chars " ]"
5638 "[^\t\n\r]*\\)")
5639 org-angle-link-re
5640 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5641 types-re)
5642 org-plain-link-re
5643 (concat
5644 "\\<" types-re ":"
5645 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5646 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5647 org-bracket-link-regexp
5648 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5649 org-bracket-link-analytic-regexp
5650 (concat
5651 "\\[\\["
5652 "\\(" types-re ":\\)?"
5653 "\\([^]]+\\)"
5654 "\\]"
5655 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5656 "\\]")
5657 org-bracket-link-analytic-regexp++
5658 (concat
5659 "\\[\\["
5660 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5661 "\\([^]]+\\)"
5662 "\\]"
5663 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5664 "\\]")
5665 org-any-link-re
5666 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5667 org-angle-link-re "\\)\\|\\("
5668 org-plain-link-re "\\)"))))
5670 (org-make-link-regexps)
5672 (defvar org-emph-face nil)
5674 (defun org-do-emphasis-faces (limit)
5675 "Run through the buffer and emphasize strings."
5676 (let (rtn a)
5677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5678 (let* ((border (char-after (match-beginning 3)))
5679 (bre (regexp-quote (char-to-string border))))
5680 (when (and (not (= border (char-after (match-beginning 4))))
5681 (not (string-match-p (concat bre ".*" bre)
5682 (replace-regexp-in-string
5683 "\n" " "
5684 (substring (match-string 2) 1 -1)))))
5685 (setq rtn t)
5686 (setq a (assoc (match-string 3) org-emphasis-alist))
5687 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5688 'face
5689 (nth 1 a))
5690 (and (nth 2 a)
5691 (org-remove-flyspell-overlays-in
5692 (match-beginning 0) (match-end 0)))
5693 (add-text-properties (match-beginning 2) (match-end 2)
5694 '(font-lock-multiline t org-emphasis t))
5695 (when org-hide-emphasis-markers
5696 (add-text-properties (match-end 4) (match-beginning 5)
5697 '(invisible org-link))
5698 (add-text-properties (match-beginning 3) (match-end 3)
5699 '(invisible org-link)))))
5700 (goto-char (1+ (match-beginning 0))))
5701 rtn))
5703 (defun org-emphasize (&optional char)
5704 "Insert or change an emphasis, i.e. a font like bold or italic.
5705 If there is an active region, change that region to a new emphasis.
5706 If there is no region, just insert the marker characters and position
5707 the cursor between them.
5708 CHAR should be the marker character. If it is a space, it means to
5709 remove the emphasis of the selected region.
5710 If CHAR is not given (for example in an interactive call) it will be
5711 prompted for."
5712 (interactive)
5713 (let ((erc org-emphasis-regexp-components)
5714 (string "") beg end move s)
5715 (if (org-region-active-p)
5716 (setq beg (region-beginning)
5717 end (region-end)
5718 string (buffer-substring beg end))
5719 (setq move t))
5721 (unless char
5722 (message "Emphasis marker or tag: [%s]"
5723 (mapconcat #'car org-emphasis-alist ""))
5724 (setq char (read-char-exclusive)))
5725 (if (equal char ?\s)
5726 (setq s ""
5727 move nil)
5728 (unless (assoc (char-to-string char) org-emphasis-alist)
5729 (user-error "No such emphasis marker: \"%c\"" char))
5730 (setq s (char-to-string char)))
5731 (while (and (> (length string) 1)
5732 (equal (substring string 0 1) (substring string -1))
5733 (assoc (substring string 0 1) org-emphasis-alist))
5734 (setq string (substring string 1 -1)))
5735 (setq string (concat s string s))
5736 (when beg (delete-region beg end))
5737 (unless (or (bolp)
5738 (string-match (concat "[" (nth 0 erc) "\n]")
5739 (char-to-string (char-before (point)))))
5740 (insert " "))
5741 (unless (or (eobp)
5742 (string-match (concat "[" (nth 1 erc) "\n]")
5743 (char-to-string (char-after (point)))))
5744 (insert " ") (backward-char 1))
5745 (insert string)
5746 (and move (backward-char 1))))
5748 (defconst org-nonsticky-props
5749 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5751 (defsubst org-rear-nonsticky-at (pos)
5752 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5754 (defun org-activate-plain-links (limit)
5755 "Add link properties for plain links."
5756 (when (and (re-search-forward org-plain-link-re limit t)
5757 (not (org-in-src-block-p)))
5758 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5759 'face))
5760 (link (org-match-string-no-properties 0)))
5761 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5762 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5763 (add-text-properties (match-beginning 0) (match-end 0)
5764 (list 'mouse-face 'highlight
5765 'face 'org-link
5766 'htmlize-link `(:uri ,link)
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 0))
5769 t))))
5771 (defun org-activate-code (limit)
5772 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (remove-text-properties (match-beginning 0) (match-end 0)
5775 '(display t invisible t intangible t))
5778 (defcustom org-src-fontify-natively t
5779 "When non-nil, fontify code in code blocks."
5780 :type 'boolean
5781 :version "24.4"
5782 :package-version '(Org . "8.3")
5783 :group 'org-appearance
5784 :group 'org-babel)
5786 (defcustom org-allow-promoting-top-level-subtree nil
5787 "When non-nil, allow promoting a top level subtree.
5788 The leading star of the top level headline will be replaced
5789 by a #."
5790 :type 'boolean
5791 :version "24.1"
5792 :group 'org-appearance)
5794 (defun org-fontify-meta-lines-and-blocks (limit)
5795 (condition-case nil
5796 (org-fontify-meta-lines-and-blocks-1 limit)
5797 (error (message "org-mode fontification error"))))
5799 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5800 "Fontify #+ lines and blocks."
5801 (let ((case-fold-search t))
5802 (when (re-search-forward
5803 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5804 limit t)
5805 (let ((beg (match-beginning 0))
5806 (block-start (match-end 0))
5807 (block-end nil)
5808 (lang (match-string 7))
5809 (beg1 (line-beginning-position 2))
5810 (dc1 (downcase (match-string 2)))
5811 (dc3 (downcase (match-string 3)))
5812 end end1 quoting block-type)
5813 (cond
5814 ((and (match-end 4) (equal dc3 "+begin"))
5815 ;; Truly a block
5816 (setq block-type (downcase (match-string 5))
5817 quoting (member block-type org-protecting-blocks))
5818 (when (re-search-forward
5819 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5820 nil t) ;; on purpose, we look further than LIMIT
5821 (setq end (min (point-max) (match-end 0))
5822 end1 (min (point-max) (1- (match-beginning 0))))
5823 (setq block-end (match-beginning 0))
5824 (when quoting
5825 (org-remove-flyspell-overlays-in beg1 end1)
5826 (remove-text-properties beg end
5827 '(display t invisible t intangible t)))
5828 (add-text-properties
5829 beg end '(font-lock-fontified t font-lock-multiline t))
5830 (add-text-properties beg beg1 '(face org-meta-line))
5831 (org-remove-flyspell-overlays-in beg beg1)
5832 (add-text-properties ; For end_src
5833 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5834 (org-remove-flyspell-overlays-in end1 end)
5835 (cond
5836 ((and lang (not (string= lang "")) org-src-fontify-natively)
5837 (org-src-font-lock-fontify-block lang block-start block-end)
5838 (add-text-properties beg1 block-end '(src-block t)))
5839 (quoting
5840 (add-text-properties beg1 (min (point-max) (1+ end1))
5841 '(face org-block))) ; end of source block
5842 ((not org-fontify-quote-and-verse-blocks))
5843 ((string= block-type "quote")
5844 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5845 ((string= block-type "verse")
5846 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5847 (add-text-properties beg beg1 '(face org-block-begin-line))
5848 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5849 '(face org-block-end-line))
5851 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5852 (org-remove-flyspell-overlays-in
5853 (match-beginning 0)
5854 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5855 (add-text-properties
5856 beg (match-end 3)
5857 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5858 '(font-lock-fontified t invisible t)
5859 '(font-lock-fontified t face org-document-info-keyword)))
5860 (add-text-properties
5861 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5862 (if (string-equal dc1 "+title:")
5863 '(font-lock-fontified t face org-document-title)
5864 '(font-lock-fontified t face org-document-info))))
5865 ((equal dc1 "+caption:")
5866 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5867 (remove-text-properties (match-beginning 0) (match-end 0)
5868 '(display t invisible t intangible t))
5869 (add-text-properties (match-beginning 1) (match-end 3)
5870 '(font-lock-fontified t face org-meta-line))
5871 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5872 '(font-lock-fontified t face org-block))
5874 ((member dc3 '(" " ""))
5875 (org-remove-flyspell-overlays-in beg (match-end 0))
5876 (add-text-properties
5877 beg (match-end 0)
5878 '(font-lock-fontified t face font-lock-comment-face)))
5879 (t ;; just any other in-buffer setting, but not indented
5880 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5881 (remove-text-properties (match-beginning 0) (match-end 0)
5882 '(display t invisible t intangible t))
5883 (add-text-properties beg (match-end 0)
5884 '(font-lock-fontified t face org-meta-line))
5885 t))))))
5887 (defun org-fontify-drawers (limit)
5888 "Fontify drawers."
5889 (when (re-search-forward org-drawer-regexp limit t)
5890 (add-text-properties
5891 (match-beginning 0) (match-end 0)
5892 '(font-lock-fontified t face org-special-keyword))
5893 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5896 (defun org-fontify-macros (limit)
5897 "Fontify macros."
5898 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5899 (add-text-properties
5900 (match-beginning 0) (match-end 0)
5901 '(font-lock-fontified t face org-macro))
5902 (when org-hide-macro-markers
5903 (add-text-properties (match-end 2) (match-beginning 2)
5904 '(invisible t))
5905 (add-text-properties (match-beginning 1) (match-end 1)
5906 '(invisible t)))
5907 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (defun org-activate-angle-links (limit)
5911 "Add text properties for angle links."
5912 (when (and (re-search-forward org-angle-link-re limit t)
5913 (not (org-in-src-block-p)))
5914 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5915 (add-text-properties (match-beginning 0) (match-end 0)
5916 (list 'mouse-face 'highlight
5917 'keymap org-mouse-map
5918 'font-lock-multiline t))
5919 (org-rear-nonsticky-at (match-end 0))
5922 (defun org-activate-footnote-links (limit)
5923 "Add text properties for footnotes."
5924 (let ((fn (org-footnote-next-reference-or-definition limit)))
5925 (when fn
5926 (let* ((beg (nth 1 fn))
5927 (end (nth 2 fn))
5928 (label (car fn))
5929 (referencep (/= (line-beginning-position) beg)))
5930 (when (and referencep (nth 3 fn))
5931 (save-excursion
5932 (goto-char beg)
5933 (search-forward (or label "fn:"))
5934 (org-remove-flyspell-overlays-in beg (match-end 0))))
5935 (add-text-properties beg end
5936 (list 'mouse-face 'highlight
5937 'keymap org-mouse-map
5938 'help-echo
5939 (if referencep "Footnote reference"
5940 "Footnote definition")
5941 'font-lock-fontified t
5942 'font-lock-multiline t
5943 'face 'org-footnote))))))
5945 (defun org-activate-bracket-links (limit)
5946 "Add text properties for bracketed links."
5947 (when (and (re-search-forward org-bracket-link-regexp limit t)
5948 (not (org-in-src-block-p)))
5949 (let* ((hl (org-match-string-no-properties 1))
5950 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5951 (ip (org-maybe-intangible
5952 (list 'invisible 'org-link
5953 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 ;; We need to remove the invisible property here. Table narrowing
5960 ;; may have made some of this invisible.
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(invisible nil))
5964 (if (match-end 3)
5965 (progn
5966 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5967 (org-rear-nonsticky-at (match-beginning 3))
5968 (add-text-properties (match-beginning 3) (match-end 3) vp)
5969 (org-rear-nonsticky-at (match-end 3))
5970 (add-text-properties (match-end 3) (match-end 0) ip)
5971 (org-rear-nonsticky-at (match-end 0)))
5972 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5973 (org-rear-nonsticky-at (match-beginning 1))
5974 (add-text-properties (match-beginning 1) (match-end 1) vp)
5975 (org-rear-nonsticky-at (match-end 1))
5976 (add-text-properties (match-end 1) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 t)))
5980 (defun org-activate-dates (limit)
5981 "Add text properties for dates."
5982 (when (and (re-search-forward org-tsr-regexp-both limit t)
5983 (not (equal (char-before (match-beginning 0)) 91)))
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when org-display-custom-times
5990 (if (match-end 3)
5991 (org-display-custom-time (match-beginning 3) (match-end 3))
5992 (org-display-custom-time (match-beginning 1) (match-end 1))))
5995 (defvar-local org-target-link-regexp nil
5996 "Regular expression matching radio targets in plain text.")
5998 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
5999 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6000 border border border))
6001 "Regular expression matching a link target.")
6003 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6004 "Regular expression matching a radio target.")
6006 (defconst org-any-target-regexp
6007 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6008 "Regular expression matching any target.")
6010 (defun org-activate-target-links (limit)
6011 "Add text properties for target matches."
6012 (when org-target-link-regexp
6013 (let ((case-fold-search t))
6014 (when (re-search-forward org-target-link-regexp limit t)
6015 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6016 (add-text-properties (match-beginning 1) (match-end 1)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 1))
6022 t))))
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression.
6026 Also refresh fontification if needed."
6027 (interactive)
6028 (let ((old-regexp org-target-link-regexp)
6029 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6030 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6031 (targets
6032 (org-with-wide-buffer
6033 (goto-char (point-min))
6034 (let (rtn)
6035 (while (re-search-forward org-radio-target-regexp nil t)
6036 ;; Make sure point is really within the object.
6037 (backward-char)
6038 (let ((obj (org-element-context)))
6039 (when (eq (org-element-type obj) 'radio-target)
6040 (cl-pushnew (org-element-property :value obj) rtn
6041 :test #'equal))))
6042 rtn))))
6043 (setq org-target-link-regexp
6044 (and targets
6045 (concat before-re
6046 (mapconcat
6047 (lambda (x)
6048 (replace-regexp-in-string
6049 " +" "\\s-+" (regexp-quote x) t t))
6050 targets
6051 "\\|")
6052 after-re)))
6053 (unless (equal old-regexp org-target-link-regexp)
6054 ;; Clean-up cache.
6055 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6056 ((not org-target-link-regexp) old-regexp)
6058 (concat before-re
6059 (mapconcat
6060 (lambda (re)
6061 (substring re (length before-re)
6062 (- (length after-re))))
6063 (list old-regexp org-target-link-regexp)
6064 "\\|")
6065 after-re)))))
6066 (org-with-wide-buffer
6067 (goto-char (point-min))
6068 (while (re-search-forward regexp nil t)
6069 (org-element-cache-refresh (match-beginning 1)))))
6070 ;; Re fontify buffer.
6071 (when (memq 'radio org-highlight-links)
6072 (org-restart-font-lock)))))
6074 (defun org-hide-wide-columns (limit)
6075 (let (s e)
6076 (setq s (text-property-any (point) (or limit (point-max))
6077 'org-cwidth t))
6078 (when s
6079 (setq e (next-single-property-change s 'org-cwidth))
6080 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6081 (goto-char e)
6082 t)))
6084 (defvar org-latex-and-related-regexp nil
6085 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6087 (defun org-compute-latex-and-related-regexp ()
6088 "Compute regular expression for LaTeX, entities and sub/superscript.
6089 Result depends on variable `org-highlight-latex-and-related'."
6090 (setq-local
6091 org-latex-and-related-regexp
6092 (let* ((re-sub
6093 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6094 ((eq org-use-sub-superscripts '{})
6095 (list org-match-substring-with-braces-regexp))
6096 (org-use-sub-superscripts (list org-match-substring-regexp))))
6097 (re-latex
6098 (when (memq 'latex org-highlight-latex-and-related)
6099 (let ((matchers (plist-get org-format-latex-options :matchers)))
6100 (delq nil
6101 (mapcar (lambda (x)
6102 (and (member (car x) matchers) (nth 1 x)))
6103 org-latex-regexps)))))
6104 (re-entities
6105 (when (memq 'entities org-highlight-latex-and-related)
6106 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6107 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6109 (defun org-do-latex-and-related (limit)
6110 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6111 LIMIT bounds the search for syntax to highlight. Stop at first
6112 highlighted object, if any. Return t if some highlighting was
6113 done, nil otherwise."
6114 (when (org-string-nw-p org-latex-and-related-regexp)
6115 (catch 'found
6116 (while (re-search-forward org-latex-and-related-regexp limit t)
6117 (unless
6118 (cl-some
6119 (lambda (f)
6120 (memq f '(org-code org-verbatim underline org-special-keyword)))
6121 (save-excursion
6122 (goto-char (1+ (match-beginning 0)))
6123 (face-at-point nil t)))
6124 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6125 '(?_ ?^))
6127 0)))
6128 (font-lock-prepend-text-property
6129 (+ offset (match-beginning 0)) (match-end 0)
6130 'face 'org-latex-and-related)
6131 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6132 '(font-lock-multiline t)))
6133 (throw 'found t)))
6134 nil)))
6136 (defun org-restart-font-lock ()
6137 "Restart `font-lock-mode', to force refontification."
6138 (when (and (boundp 'font-lock-mode) font-lock-mode)
6139 (font-lock-mode -1)
6140 (font-lock-mode 1)))
6142 (defun org-activate-tags (limit)
6143 (when (re-search-forward
6144 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6145 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6146 (add-text-properties (match-beginning 1) (match-end 1)
6147 (list 'mouse-face 'highlight
6148 'keymap org-mouse-map))
6149 (org-rear-nonsticky-at (match-end 1))
6152 (defun org-outline-level ()
6153 "Compute the outline level of the heading at point.
6155 If this is called at a normal headline, the level is the number
6156 of stars. Use `org-reduced-level' to remove the effect of
6157 `org-odd-levels'. Unlike to `org-current-level', this function
6158 takes into consideration inlinetasks."
6159 (org-with-wide-buffer
6160 (end-of-line)
6161 (if (re-search-backward org-outline-regexp-bol nil t)
6162 (1- (- (match-end 0) (match-beginning 0)))
6163 0)))
6165 (defvar org-font-lock-keywords nil)
6167 (defsubst org-re-property (property &optional literal allow-null value)
6168 "Return a regexp matching a PROPERTY line.
6170 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6171 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6172 non-nil, match properties even without a value.
6174 Match group 3 is set to the value when it exists. If there is no
6175 value and ALLOW-NULL is non-nil, it is set to the empty string.
6177 With optional argument VALUE, match only property lines with
6178 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6179 unless LITERAL is non-nil."
6180 (concat
6181 "^\\(?4:[ \t]*\\)"
6182 (format "\\(?1::\\(?2:%s\\):\\)"
6183 (if literal property (regexp-quote property)))
6184 (cond (value
6185 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6186 (if literal value (regexp-quote value))))
6187 (allow-null
6188 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6190 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6192 (defconst org-property-re
6193 (org-re-property "\\S-+" 'literal t)
6194 "Regular expression matching a property line.
6195 There are four matching groups:
6196 1: :PROPKEY: including the leading and trailing colon,
6197 2: PROPKEY without the leading and trailing colon,
6198 3: PROPVAL without leading or trailing spaces,
6199 4: the indentation of the current line,
6200 5: trailing whitespace.")
6202 (defvar org-font-lock-hook nil
6203 "Functions to be called for special font lock stuff.")
6205 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6207 (defvar org-font-lock-set-keywords-hook nil
6208 "Functions that can manipulate `org-font-lock-extra-keywords'.
6209 This is called after `org-font-lock-extra-keywords' is defined, but before
6210 it is installed to be used by font lock. This can be useful if something
6211 needs to be inserted at a specific position in the font-lock sequence.")
6213 (defun org-font-lock-hook (limit)
6214 "Run `org-font-lock-hook' within LIMIT."
6215 (run-hook-with-args 'org-font-lock-hook limit))
6217 (defun org-set-font-lock-defaults ()
6218 "Set font lock defaults for the current buffer."
6219 (let* ((em org-fontify-emphasized-text)
6220 (lk org-highlight-links)
6221 (org-font-lock-extra-keywords
6222 (list
6223 ;; Call the hook
6224 '(org-font-lock-hook)
6225 ;; Headlines
6226 `(,(if org-fontify-whole-heading-line
6227 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6228 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6229 (1 (org-get-level-face 1))
6230 (2 (org-get-level-face 2))
6231 (3 (org-get-level-face 3)))
6232 ;; Table lines
6233 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6234 (1 'org-table t))
6235 ;; Table internals
6236 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6237 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6238 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6239 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6240 ;; Drawers
6241 '(org-fontify-drawers)
6242 ;; Properties
6243 (list org-property-re
6244 '(1 'org-special-keyword t)
6245 '(3 'org-property-value t))
6246 ;; Links
6247 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6248 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6249 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6250 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6251 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6252 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6253 (when (memq 'footnote lk) '(org-activate-footnote-links))
6254 ;; Targets.
6255 (list org-any-target-regexp '(0 'org-target t))
6256 ;; Diary sexps.
6257 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6258 ;; Macro
6259 '(org-fontify-macros)
6260 '(org-hide-wide-columns (0 nil append))
6261 ;; TODO keyword
6262 (list (format org-heading-keyword-regexp-format
6263 org-todo-regexp)
6264 '(2 (org-get-todo-face 2) t))
6265 ;; DONE
6266 (if org-fontify-done-headline
6267 (list (format org-heading-keyword-regexp-format
6268 (concat
6269 "\\(?:"
6270 (mapconcat 'regexp-quote org-done-keywords "\\|")
6271 "\\)"))
6272 '(2 'org-headline-done t))
6273 nil)
6274 ;; Priorities
6275 '(org-font-lock-add-priority-faces)
6276 ;; Tags
6277 '(org-font-lock-add-tag-faces)
6278 ;; Tags groups
6279 (when (and org-group-tags org-tag-groups-alist)
6280 (list (concat org-outline-regexp-bol ".+\\(:"
6281 (regexp-opt (mapcar 'car org-tag-groups-alist))
6282 ":\\).*$")
6283 '(1 'org-tag-group prepend)))
6284 ;; Special keywords
6285 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6286 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6287 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6288 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6289 ;; Emphasis
6290 (when em
6291 (if (featurep 'xemacs)
6292 '(org-do-emphasis-faces (0 nil append))
6293 '(org-do-emphasis-faces)))
6294 ;; Checkboxes
6295 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6296 1 'org-checkbox prepend)
6297 (when (cdr (assq 'checkbox org-list-automatic-rules))
6298 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6299 (0 (org-get-checkbox-statistics-face) t)))
6300 ;; Description list items
6301 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6302 1 'org-list-dt prepend)
6303 ;; ARCHIVEd headings
6304 (list (concat
6305 org-outline-regexp-bol
6306 "\\(.*:" org-archive-tag ":.*\\)")
6307 '(1 'org-archived prepend))
6308 ;; Specials
6309 '(org-do-latex-and-related)
6310 '(org-fontify-entities)
6311 '(org-raise-scripts)
6312 ;; Code
6313 '(org-activate-code (1 'org-code t))
6314 ;; COMMENT
6315 (list (format
6316 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6317 org-todo-regexp
6318 org-comment-string)
6319 '(9 'org-special-keyword t))
6320 ;; Blocks and meta lines
6321 '(org-fontify-meta-lines-and-blocks))))
6322 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6323 (run-hooks 'org-font-lock-set-keywords-hook)
6324 ;; Now set the full font-lock-keywords
6325 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6326 (setq-local font-lock-defaults
6327 '(org-font-lock-keywords t nil nil backward-paragraph))
6328 (kill-local-variable 'font-lock-keywords) nil))
6330 (defun org-toggle-pretty-entities ()
6331 "Toggle the composition display of entities as UTF8 characters."
6332 (interactive)
6333 (setq-local org-pretty-entities (not org-pretty-entities))
6334 (org-restart-font-lock)
6335 (if org-pretty-entities
6336 (message "Entities are now displayed as UTF8 characters")
6337 (save-restriction
6338 (widen)
6339 (org-decompose-region (point-min) (point-max))
6340 (message "Entities are now displayed as plain text"))))
6342 (defvar-local org-custom-properties-overlays nil
6343 "List of overlays used for custom properties.")
6345 (defun org-toggle-custom-properties-visibility ()
6346 "Display or hide properties in `org-custom-properties'."
6347 (interactive)
6348 (if org-custom-properties-overlays
6349 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6350 (setq org-custom-properties-overlays nil))
6351 (when org-custom-properties
6352 (org-with-wide-buffer
6353 (goto-char (point-min))
6354 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6355 (while (re-search-forward regexp nil t)
6356 (let ((end (cdr (save-match-data (org-get-property-block)))))
6357 (when (and end (< (point) end))
6358 ;; Hide first custom property in current drawer.
6359 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6360 (overlay-put o 'invisible t)
6361 (overlay-put o 'org-custom-property t)
6362 (push o org-custom-properties-overlays))
6363 ;; Hide additional custom properties in the same drawer.
6364 (while (re-search-forward regexp end t)
6365 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6366 (overlay-put o 'invisible t)
6367 (overlay-put o 'org-custom-property t)
6368 (push o org-custom-properties-overlays)))))
6369 ;; Each entry is limited to a single property drawer.
6370 (outline-next-heading)))))))
6372 (defun org-fontify-entities (limit)
6373 "Find an entity to fontify."
6374 (let (ee)
6375 (when org-pretty-entities
6376 (catch 'match
6377 ;; "\_ "-family is left out on purpose. Only the first one,
6378 ;; i.e., "\_ ", could be fontified anyway, and it would be
6379 ;; confusing when adding a second white space character.
6380 (while (re-search-forward
6381 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6382 limit t)
6383 (when (and (not (org-at-comment-p))
6384 (setq ee (org-entity-get (match-string 1)))
6385 (= (length (nth 6 ee)) 1))
6386 (let* ((end (if (equal (match-string 2) "{}")
6387 (match-end 2)
6388 (match-end 1))))
6389 (add-text-properties
6390 (match-beginning 0) end
6391 (list 'font-lock-fontified t))
6392 (compose-region (match-beginning 0) end
6393 (nth 6 ee) nil)
6394 (backward-char 1)
6395 (throw 'match t))))
6396 nil))))
6398 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6399 "Fontify string S like in Org-mode."
6400 (with-temp-buffer
6401 (insert s)
6402 (let ((org-odd-levels-only odd-levels))
6403 (org-mode)
6404 (org-font-lock-ensure)
6405 (buffer-string))))
6407 (defvar org-m nil)
6408 (defvar org-l nil)
6409 (defvar org-f nil)
6410 (defun org-get-level-face (n)
6411 "Get the right face for match N in font-lock matching of headlines."
6412 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6413 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6414 (if org-cycle-level-faces
6415 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6416 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6417 (cond
6418 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6419 ((eq n 2) org-f)
6420 (t (unless org-level-color-stars-only org-f))))
6422 (defun org-face-from-face-or-color (context inherit face-or-color)
6423 "Create a face list that inherits INHERIT, but sets the foreground color.
6424 When FACE-OR-COLOR is not a string, just return it."
6425 (if (stringp face-or-color)
6426 (list :inherit inherit
6427 (cdr (assoc context org-faces-easy-properties))
6428 face-or-color)
6429 face-or-color))
6431 (defun org-get-todo-face (kwd)
6432 "Get the right face for a TODO keyword KWD.
6433 If KWD is a number, get the corresponding match group."
6434 (when (numberp kwd) (setq kwd (match-string kwd)))
6435 (or (org-face-from-face-or-color
6436 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6437 (and (member kwd org-done-keywords) 'org-done)
6438 'org-todo))
6440 (defun org-get-priority-face (priority)
6441 "Get the right face for PRIORITY.
6442 PRIORITY is a character."
6443 (or (org-face-from-face-or-color
6444 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6445 'org-priority))
6447 (defun org-get-tag-face (tag)
6448 "Get the right face for TAG.
6449 If TAG is a number, get the corresponding match group."
6450 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6451 (or (org-face-from-face-or-color
6452 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6453 'org-tag)))
6455 (defun org-font-lock-add-priority-faces (limit)
6456 "Add the special priority faces."
6457 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6458 (add-text-properties
6459 (match-beginning 1) (match-end 1)
6460 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6461 'font-lock-fontified t))))
6463 (defun org-font-lock-add-tag-faces (limit)
6464 "Add the special tag faces."
6465 (when (and org-tag-faces org-tags-special-faces-re)
6466 (while (re-search-forward org-tags-special-faces-re limit t)
6467 (add-text-properties (match-beginning 1) (match-end 1)
6468 (list 'face (org-get-tag-face 1)
6469 'font-lock-fontified t))
6470 (backward-char 1))))
6472 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6473 "Remove fontification and activation overlays from links."
6474 (font-lock-default-unfontify-region beg end)
6475 (let* ((buffer-undo-list t)
6476 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6477 (inhibit-modification-hooks t)
6478 deactivate-mark buffer-file-name buffer-file-truename)
6479 (org-decompose-region beg end)
6480 (remove-text-properties beg end
6481 '(mouse-face t keymap t org-linked-text t
6482 invisible t intangible t
6483 org-emphasis t))
6484 (org-remove-font-lock-display-properties beg end)))
6486 (defconst org-script-display '(((raise -0.3) (height 0.7))
6487 ((raise 0.3) (height 0.7))
6488 ((raise -0.5))
6489 ((raise 0.5)))
6490 "Display properties for showing superscripts and subscripts.")
6492 (defun org-remove-font-lock-display-properties (beg end)
6493 "Remove specific display properties that have been added by font lock.
6494 The will remove the raise properties that are used to show superscripts
6495 and subscripts."
6496 (let (next prop)
6497 (while (< beg end)
6498 (setq next (next-single-property-change beg 'display nil end)
6499 prop (get-text-property beg 'display))
6500 (when (member prop org-script-display)
6501 (put-text-property beg next 'display nil))
6502 (setq beg next))))
6504 (defun org-raise-scripts (limit)
6505 "Add raise properties to sub/superscripts."
6506 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6507 (re-search-forward
6508 (if (eq org-use-sub-superscripts t)
6509 org-match-substring-regexp
6510 org-match-substring-with-braces-regexp)
6511 limit t))
6512 (let* ((pos (point)) table-p comment-p
6513 (mpos (match-beginning 3))
6514 (emph-p (get-text-property mpos 'org-emphasis))
6515 (link-p (get-text-property mpos 'mouse-face))
6516 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6517 (goto-char (point-at-bol))
6518 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6519 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6520 (goto-char pos)
6521 ;; Handle a_b^c
6522 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6523 (unless (or comment-p emph-p link-p keyw-p)
6524 (put-text-property (match-beginning 3) (match-end 0)
6525 'display
6526 (if (equal (char-after (match-beginning 2)) ?^)
6527 (nth (if table-p 3 1) org-script-display)
6528 (nth (if table-p 2 0) org-script-display)))
6529 (add-text-properties (match-beginning 2) (match-end 2)
6530 (list 'invisible t
6531 'org-dwidth t 'org-dwidth-n 1))
6532 (if (and (eq (char-after (match-beginning 3)) ?{)
6533 (eq (char-before (match-end 3)) ?}))
6534 (progn
6535 (add-text-properties
6536 (match-beginning 3) (1+ (match-beginning 3))
6537 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6538 (add-text-properties
6539 (1- (match-end 3)) (match-end 3)
6540 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6541 t)))
6543 ;;;; Visibility cycling, including org-goto and indirect buffer
6545 ;;; Cycling
6547 (defvar-local org-cycle-global-status nil)
6548 (put 'org-cycle-global-status 'org-state t)
6549 (defvar-local org-cycle-subtree-status nil)
6550 (put 'org-cycle-subtree-status 'org-state t)
6552 (defvar org-inlinetask-min-level)
6554 (defun org-unlogged-message (&rest args)
6555 "Display a message, but avoid logging it in the *Messages* buffer."
6556 (let ((message-log-max nil))
6557 (apply 'message args)))
6559 ;;;###autoload
6560 (defun org-cycle (&optional arg)
6561 "TAB-action and visibility cycling for Org-mode.
6563 This is the command invoked in Org-mode by the TAB key. Its main purpose
6564 is outline visibility cycling, but it also invokes other actions
6565 in special contexts.
6567 - When this function is called with a prefix argument, rotate the entire
6568 buffer through 3 states (global cycling)
6569 1. OVERVIEW: Show only top-level headlines.
6570 2. CONTENTS: Show all headlines of all levels, but no body text.
6571 3. SHOW ALL: Show everything.
6572 With a double \\[universal-argument] prefix argument, \
6573 switch to the startup visibility,
6574 determined by the variable `org-startup-folded', and by any VISIBILITY
6575 properties in the buffer.
6576 With a triple \\[universal-argument] prefix argument, \
6577 show the entire buffer, including any drawers.
6579 - When inside a table, re-align the table and move to the next field.
6581 - When point is at the beginning of a headline, rotate the subtree started
6582 by this line through 3 different states (local cycling)
6583 1. FOLDED: Only the main headline is shown.
6584 2. CHILDREN: The main headline and the direct children are shown.
6585 From this state, you can move to one of the children
6586 and zoom in further.
6587 3. SUBTREE: Show the entire subtree, including body text.
6588 If there is no subtree, switch directly from CHILDREN to FOLDED.
6590 - When point is at the beginning of an empty headline and the variable
6591 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6592 of the headline by demoting and promoting it to likely levels. This
6593 speeds up creation document structure by pressing TAB once or several
6594 times right after creating a new headline.
6596 - When there is a numeric prefix, go up to a heading with level ARG, do
6597 a `show-subtree' and return to the previous cursor position. If ARG
6598 is negative, go up that many levels.
6600 - When point is not at the beginning of a headline, execute the global
6601 binding for TAB, which is re-indenting the line. See the option
6602 `org-cycle-emulate-tab' for details.
6604 - Special case: if point is at the beginning of the buffer and there is
6605 no headline in line 1, this function will act as if called with prefix arg
6606 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6607 But only if also the variable `org-cycle-global-at-bob' is t."
6608 (interactive "P")
6609 (org-load-modules-maybe)
6610 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6611 (and org-cycle-level-after-item/entry-creation
6612 (or (org-cycle-level)
6613 (org-cycle-item-indentation))))
6614 (let* ((limit-level
6615 (or org-cycle-max-level
6616 (and (boundp 'org-inlinetask-min-level)
6617 org-inlinetask-min-level
6618 (1- org-inlinetask-min-level))))
6619 (nstars (and limit-level
6620 (if org-odd-levels-only
6621 (and limit-level (1- (* limit-level 2)))
6622 limit-level)))
6623 (org-outline-regexp
6624 (if (not (derived-mode-p 'org-mode))
6625 outline-regexp
6626 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6627 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6628 (not (looking-at org-outline-regexp))))
6629 (org-cycle-hook
6630 (if bob-special
6631 (delq 'org-optimize-window-after-visibility-change
6632 (copy-sequence org-cycle-hook))
6633 org-cycle-hook))
6634 (pos (point)))
6636 (when (or bob-special (equal arg '(4)))
6637 ;; special case: use global cycling
6638 (setq arg t))
6640 (cond
6642 ((equal arg '(16))
6643 (setq last-command 'dummy)
6644 (org-set-startup-visibility)
6645 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6647 ((equal arg '(64))
6648 (outline-show-all)
6649 (org-unlogged-message "Entire buffer visible, including drawers"))
6651 ;; Try cdlatex TAB completion
6652 ((org-try-cdlatex-tab))
6654 ;; Table: enter it or move to the next field.
6655 ((org-at-table-p 'any)
6656 (if (org-at-table.el-p)
6657 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6658 Use \\[org-edit-special] to edit table.el tables"))
6659 (if arg (org-table-edit-field t)
6660 (org-table-justify-field-maybe)
6661 (call-interactively 'org-table-next-field))))
6663 ((run-hook-with-args-until-success
6664 'org-tab-after-check-for-table-hook))
6666 ;; Global cycling: delegate to `org-cycle-internal-global'.
6667 ((eq arg t) (org-cycle-internal-global))
6669 ;; Drawers: delegate to `org-flag-drawer'.
6670 ((save-excursion
6671 (beginning-of-line 1)
6672 (looking-at org-drawer-regexp))
6673 (org-flag-drawer ; toggle block visibility
6674 (not (get-char-property (match-end 0) 'invisible))))
6676 ;; Show-subtree, ARG levels up from here.
6677 ((integerp arg)
6678 (save-excursion
6679 (org-back-to-heading)
6680 (outline-up-heading (if (< arg 0) (- arg)
6681 (- (funcall outline-level) arg)))
6682 (org-show-subtree)))
6684 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6685 ((and (featurep 'org-inlinetask)
6686 (org-inlinetask-at-task-p)
6687 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6688 (org-inlinetask-toggle-visibility))
6690 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6691 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6692 (save-excursion (move-beginning-of-line 1)
6693 (looking-at org-outline-regexp)))
6694 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6695 (org-cycle-internal-local))
6697 ;; From there: TAB emulation and template completion.
6698 (buffer-read-only (org-back-to-heading))
6700 ((run-hook-with-args-until-success
6701 'org-tab-after-check-for-cycling-hook))
6703 ((org-try-structure-completion))
6705 ((run-hook-with-args-until-success
6706 'org-tab-before-tab-emulation-hook))
6708 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6709 (or (not (bolp))
6710 (not (looking-at org-outline-regexp))))
6711 (call-interactively (global-key-binding "\t")))
6713 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6714 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6715 (or (and (eq org-cycle-emulate-tab 'white)
6716 (= (match-end 0) (point-at-eol)))
6717 (and (eq org-cycle-emulate-tab 'whitestart)
6718 (>= (match-end 0) pos))))
6720 (eq org-cycle-emulate-tab t))
6721 (call-interactively (global-key-binding "\t")))
6723 (t (save-excursion
6724 (org-back-to-heading)
6725 (org-cycle)))))))
6727 (defun org-cycle-internal-global ()
6728 "Do the global cycling action."
6729 ;; Hack to avoid display of messages for .org attachments in Gnus
6730 (let ((ga (string-match "\\*fontification" (buffer-name))))
6731 (cond
6732 ((and (eq last-command this-command)
6733 (eq org-cycle-global-status 'overview))
6734 ;; We just created the overview - now do table of contents
6735 ;; This can be slow in very large buffers, so indicate action
6736 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6737 (unless ga (org-unlogged-message "CONTENTS..."))
6738 (org-content)
6739 (unless ga (org-unlogged-message "CONTENTS...done"))
6740 (setq org-cycle-global-status 'contents)
6741 (run-hook-with-args 'org-cycle-hook 'contents))
6743 ((and (eq last-command this-command)
6744 (eq org-cycle-global-status 'contents))
6745 ;; We just showed the table of contents - now show everything
6746 (run-hook-with-args 'org-pre-cycle-hook 'all)
6747 (outline-show-all)
6748 (unless ga (org-unlogged-message "SHOW ALL"))
6749 (setq org-cycle-global-status 'all)
6750 (run-hook-with-args 'org-cycle-hook 'all))
6753 ;; Default action: go to overview
6754 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6755 (org-overview)
6756 (unless ga (org-unlogged-message "OVERVIEW"))
6757 (setq org-cycle-global-status 'overview)
6758 (run-hook-with-args 'org-cycle-hook 'overview)))))
6760 (defvar org-called-with-limited-levels nil
6761 "Non-nil when `org-with-limited-levels' is currently active.")
6763 (defun org-cycle-internal-local ()
6764 "Do the local cycling action."
6765 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6766 ;; First, determine end of headline (EOH), end of subtree or item
6767 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6768 (save-excursion
6769 (if (org-at-item-p)
6770 (progn
6771 (beginning-of-line)
6772 (setq struct (org-list-struct))
6773 (setq eoh (point-at-eol))
6774 (setq eos (org-list-get-item-end-before-blank (point) struct))
6775 (setq has-children (org-list-has-child-p (point) struct)))
6776 (org-back-to-heading)
6777 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6778 (setq eos (save-excursion (org-end-of-subtree t t)
6779 (when (bolp) (backward-char)) (point)))
6780 (setq has-children
6781 (or (save-excursion
6782 (let ((level (funcall outline-level)))
6783 (outline-next-heading)
6784 (and (org-at-heading-p t)
6785 (> (funcall outline-level) level))))
6786 (save-excursion
6787 (org-list-search-forward (org-item-beginning-re) eos t)))))
6788 ;; Determine end invisible part of buffer (EOL)
6789 (beginning-of-line 2)
6790 ;; XEmacs doesn't have `next-single-char-property-change'
6791 (if (featurep 'xemacs)
6792 (while (and (not (eobp)) ;; this is like `next-line'
6793 (get-char-property (1- (point)) 'invisible))
6794 (beginning-of-line 2))
6795 (while (and (not (eobp)) ;; this is like `next-line'
6796 (get-char-property (1- (point)) 'invisible))
6797 (goto-char (next-single-char-property-change (point) 'invisible))
6798 (and (eolp) (beginning-of-line 2))))
6799 (setq eol (point)))
6800 ;; Find out what to do next and set `this-command'
6801 (cond
6802 ((= eos eoh)
6803 ;; Nothing is hidden behind this heading
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6806 (org-unlogged-message "EMPTY ENTRY")
6807 (setq org-cycle-subtree-status nil)
6808 (save-excursion
6809 (goto-char eos)
6810 (outline-next-heading)
6811 (when (outline-invisible-p) (org-flag-heading nil))))
6812 ((and (or (>= eol eos)
6813 (not (string-match "\\S-" (buffer-substring eol eos))))
6814 (or has-children
6815 (not (setq children-skipped
6816 org-cycle-skip-children-state-if-no-children))))
6817 ;; Entire subtree is hidden in one line: children view
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-pre-cycle-hook 'children))
6820 (if (org-at-item-p)
6821 (org-list-set-item-visibility (point-at-bol) struct 'children)
6822 (org-show-entry)
6823 (org-with-limited-levels (org-show-children))
6824 ;; FIXME: This slows down the func way too much.
6825 ;; How keep drawers hidden in subtree anyway?
6826 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6827 ;; (org-cycle-hide-drawers 'subtree))
6829 ;; Fold every list in subtree to top-level items.
6830 (when (eq org-cycle-include-plain-lists 'integrate)
6831 (save-excursion
6832 (org-back-to-heading)
6833 (while (org-list-search-forward (org-item-beginning-re) eos t)
6834 (beginning-of-line 1)
6835 (let* ((struct (org-list-struct))
6836 (prevs (org-list-prevs-alist struct))
6837 (end (org-list-get-bottom-point struct)))
6838 (dolist (e (org-list-get-all-items (point) struct prevs))
6839 (org-list-set-item-visibility e struct 'folded))
6840 (goto-char (if (< end eos) end eos)))))))
6841 (org-unlogged-message "CHILDREN")
6842 (save-excursion
6843 (goto-char eos)
6844 (outline-next-heading)
6845 (when (outline-invisible-p) (org-flag-heading nil)))
6846 (setq org-cycle-subtree-status 'children)
6847 (unless (org-before-first-heading-p)
6848 (run-hook-with-args 'org-cycle-hook 'children)))
6849 ((or children-skipped
6850 (and (eq last-command this-command)
6851 (eq org-cycle-subtree-status 'children)))
6852 ;; We just showed the children, or no children are there,
6853 ;; now show everything.
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6856 (outline-flag-region eoh eos nil)
6857 (org-unlogged-message
6858 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6859 (setq org-cycle-subtree-status 'subtree)
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-cycle-hook 'subtree)))
6863 ;; Default action: hide the subtree.
6864 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6865 (outline-flag-region eoh eos t)
6866 (org-unlogged-message "FOLDED")
6867 (setq org-cycle-subtree-status 'folded)
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-cycle-hook 'folded))))))
6871 ;;;###autoload
6872 (defun org-global-cycle (&optional arg)
6873 "Cycle the global visibility. For details see `org-cycle'.
6874 With \\[universal-argument] prefix arg, switch to startup visibility.
6875 With a numeric prefix, show all headlines up to that level."
6876 (interactive "P")
6877 (let ((org-cycle-include-plain-lists
6878 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6879 (cond
6880 ((integerp arg)
6881 (outline-show-all)
6882 (outline-hide-sublevels arg)
6883 (setq org-cycle-global-status 'contents))
6884 ((equal arg '(4))
6885 (org-set-startup-visibility)
6886 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6888 (org-cycle '(4))))))
6890 (defun org-set-startup-visibility ()
6891 "Set the visibility required by startup options and properties."
6892 (cond
6893 ((eq org-startup-folded t)
6894 (org-overview))
6895 ((eq org-startup-folded 'content)
6896 (org-content))
6897 ((or (eq org-startup-folded 'showeverything)
6898 (eq org-startup-folded nil))
6899 (outline-show-all)))
6900 (unless (eq org-startup-folded 'showeverything)
6901 (when org-hide-block-startup (org-hide-block-all))
6902 (org-set-visibility-according-to-property 'no-cleanup)
6903 (org-cycle-hide-archived-subtrees 'all)
6904 (org-cycle-hide-drawers 'all)
6905 (org-cycle-show-empty-lines t)))
6907 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6908 "Switch subtree visibilities according to :VISIBILITY: property."
6909 (interactive)
6910 (org-with-wide-buffer
6911 (goto-char (point-min))
6912 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6913 (if (not (org-at-property-p)) (outline-next-heading)
6914 (let ((state (match-string 3)))
6915 (save-excursion
6916 (org-back-to-heading t)
6917 (outline-hide-subtree)
6918 (org-reveal)
6919 (cond
6920 ((equal state "folded")
6921 (outline-hide-subtree))
6922 ((equal state "children")
6923 (org-show-hidden-entry)
6924 (org-show-children))
6925 ((equal state "content")
6926 (save-excursion
6927 (save-restriction
6928 (org-narrow-to-subtree)
6929 (org-content))))
6930 ((member state '("all" "showall"))
6931 (outline-show-subtree)))))))
6932 (unless no-cleanup
6933 (org-cycle-hide-archived-subtrees 'all)
6934 (org-cycle-hide-drawers 'all)
6935 (org-cycle-show-empty-lines 'all))))
6937 ;; This function uses outline-regexp instead of the more fundamental
6938 ;; org-outline-regexp so that org-cycle-global works outside of Org
6939 ;; buffers, where outline-regexp is needed.
6940 (defun org-overview ()
6941 "Switch to overview mode, showing only top-level headlines.
6942 This shows all headlines with a level equal or greater than the level
6943 of the first headline in the buffer. This is important, because if the
6944 first headline is not level one, then (hide-sublevels 1) gives confusing
6945 results."
6946 (interactive)
6947 (save-excursion
6948 (let ((level
6949 (save-excursion
6950 (goto-char (point-min))
6951 (when (re-search-forward (concat "^" outline-regexp) nil t)
6952 (goto-char (match-beginning 0))
6953 (funcall outline-level)))))
6954 (and level (outline-hide-sublevels level)))))
6956 (defun org-content (&optional arg)
6957 "Show all headlines in the buffer, like a table of contents.
6958 With numerical argument N, show content up to level N."
6959 (interactive "P")
6960 (org-overview)
6961 (save-excursion
6962 ;; Visit all headings and show their offspring
6963 (and (integerp arg) (org-overview))
6964 (goto-char (point-max))
6965 (catch 'exit
6966 (while (and (progn (condition-case nil
6967 (outline-previous-visible-heading 1)
6968 (error (goto-char (point-min))))
6970 (looking-at org-outline-regexp))
6971 (if (integerp arg)
6972 (org-show-children (1- arg))
6973 (outline-show-branches))
6974 (when (bobp) (throw 'exit nil))))))
6976 (defun org-optimize-window-after-visibility-change (state)
6977 "Adjust the window after a change in outline visibility.
6978 This function is the default value of the hook `org-cycle-hook'."
6979 (when (get-buffer-window (current-buffer))
6980 (cond
6981 ((eq state 'content) nil)
6982 ((eq state 'all) nil)
6983 ((eq state 'folded) nil)
6984 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6985 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6987 (defun org-remove-empty-overlays-at (pos)
6988 "Remove outline overlays that do not contain non-white stuff."
6989 (dolist (o (overlays-at pos))
6990 (and (eq 'outline (overlay-get o 'invisible))
6991 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6992 (overlay-end o))))
6993 (delete-overlay o))))
6995 (defun org-clean-visibility-after-subtree-move ()
6996 "Fix visibility issues after moving a subtree."
6997 ;; First, find a reasonable region to look at:
6998 ;; Start two siblings above, end three below
6999 (let* ((beg (save-excursion
7000 (and (org-get-last-sibling)
7001 (org-get-last-sibling))
7002 (point)))
7003 (end (save-excursion
7004 (and (org-get-next-sibling)
7005 (org-get-next-sibling)
7006 (org-get-next-sibling))
7007 (if (org-at-heading-p)
7008 (point-at-eol)
7009 (point))))
7010 (level (looking-at "\\*+"))
7011 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7012 (save-excursion
7013 (save-restriction
7014 (narrow-to-region beg end)
7015 (when re
7016 ;; Properly fold already folded siblings
7017 (goto-char (point-min))
7018 (while (re-search-forward re nil t)
7019 (when (and (not (outline-invisible-p))
7020 (save-excursion
7021 (goto-char (point-at-eol)) (outline-invisible-p)))
7022 (outline-hide-entry))))
7023 (org-cycle-show-empty-lines 'overview)
7024 (org-cycle-hide-drawers 'overview)))))
7026 (defun org-cycle-show-empty-lines (state)
7027 "Show empty lines above all visible headlines.
7028 The region to be covered depends on STATE when called through
7029 `org-cycle-hook'. Lisp program can use t for STATE to get the
7030 entire buffer covered. Note that an empty line is only shown if there
7031 are at least `org-cycle-separator-lines' empty lines before the headline."
7032 (when (/= org-cycle-separator-lines 0)
7033 (save-excursion
7034 (let* ((n (abs org-cycle-separator-lines))
7035 (re (cond
7036 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7037 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7038 (t (let ((ns (number-to-string (- n 2))))
7039 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7040 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7041 beg end)
7042 (cond
7043 ((memq state '(overview contents t))
7044 (setq beg (point-min) end (point-max)))
7045 ((memq state '(children folded))
7046 (setq beg (point)
7047 end (progn (org-end-of-subtree t t)
7048 (line-beginning-position 2)))))
7049 (when beg
7050 (goto-char beg)
7051 (while (re-search-forward re end t)
7052 (unless (get-char-property (match-end 1) 'invisible)
7053 (let ((e (match-end 1))
7054 (b (if (>= org-cycle-separator-lines 0)
7055 (match-beginning 1)
7056 (save-excursion
7057 (goto-char (match-beginning 0))
7058 (skip-chars-backward " \t\n")
7059 (line-end-position)))))
7060 (outline-flag-region b e nil))))))))
7061 ;; Never hide empty lines at the end of the file.
7062 (save-excursion
7063 (goto-char (point-max))
7064 (outline-previous-heading)
7065 (outline-end-of-heading)
7066 (when (and (looking-at "[ \t\n]+")
7067 (= (match-end 0) (point-max)))
7068 (outline-flag-region (point) (match-end 0) nil))))
7070 (defun org-show-empty-lines-in-parent ()
7071 "Move to the parent and re-show empty lines before visible headlines."
7072 (save-excursion
7073 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7074 (org-cycle-show-empty-lines context))))
7076 (defun org-files-list ()
7077 "Return `org-agenda-files' list, plus all open org-mode files.
7078 This is useful for operations that need to scan all of a user's
7079 open and agenda-wise Org files."
7080 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7081 (dolist (buf (buffer-list))
7082 (with-current-buffer buf
7083 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7084 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7085 files))
7087 (defsubst org-entry-beginning-position ()
7088 "Return the beginning position of the current entry."
7089 (save-excursion (org-back-to-heading t) (point)))
7091 (defsubst org-entry-end-position ()
7092 "Return the end position of the current entry."
7093 (save-excursion (outline-next-heading) (point)))
7095 (defun org-cycle-hide-drawers (state &optional exceptions)
7096 "Re-hide all drawers after a visibility state change.
7097 When non-nil, optional argument EXCEPTIONS is a list of strings
7098 specifying which drawers should not be hidden."
7099 (when (and (derived-mode-p 'org-mode)
7100 (not (memq state '(overview folded contents))))
7101 (save-excursion
7102 (let* ((globalp (memq state '(contents all)))
7103 (beg (if globalp (point-min) (point)))
7104 (end (if globalp (point-max)
7105 (if (eq state 'children)
7106 (save-excursion (outline-next-heading) (point))
7107 (org-end-of-subtree t)))))
7108 (goto-char beg)
7109 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7110 (unless (member-ignore-case (match-string 1) exceptions)
7111 (let ((drawer (org-element-at-point)))
7112 (when (memq (org-element-type drawer) '(drawer property-drawer))
7113 (org-flag-drawer t drawer)
7114 ;; Make sure to skip drawer entirely or we might flag
7115 ;; it another time when matching its ending line with
7116 ;; `org-drawer-regexp'.
7117 (goto-char (org-element-property :end drawer))))))))))
7119 (defun org-flag-drawer (flag &optional element)
7120 "When FLAG is non-nil, hide the drawer we are at.
7121 Otherwise make it visible. When optional argument ELEMENT is
7122 a parsed drawer, as returned by `org-element-at-point', hide or
7123 show that drawer instead."
7124 (when (save-excursion
7125 (beginning-of-line)
7126 (org-looking-at-p org-drawer-regexp))
7127 (let ((drawer (or element (org-element-at-point))))
7128 (when (memq (org-element-type drawer) '(drawer property-drawer))
7129 (let ((post (org-element-property :post-affiliated drawer)))
7130 (save-excursion
7131 (outline-flag-region
7132 (progn (goto-char post) (line-end-position))
7133 (progn (goto-char (org-element-property :end drawer))
7134 (skip-chars-backward " \r\t\n")
7135 (line-end-position))
7136 flag))
7137 ;; When the drawer is hidden away, make sure point lies in
7138 ;; a visible part of the buffer.
7139 (when (and flag (> (line-beginning-position) post))
7140 (goto-char post)))))))
7142 (defun org-subtree-end-visible-p ()
7143 "Is the end of the current subtree visible?"
7144 (pos-visible-in-window-p
7145 (save-excursion (org-end-of-subtree t) (point))))
7147 (defun org-first-headline-recenter ()
7148 "Move cursor to the first headline and recenter the headline."
7149 (goto-char (point-min))
7150 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7151 (set-window-start (selected-window) (point-at-bol))))
7153 ;;; Saving and restoring visibility
7155 (defun org-outline-overlay-data (&optional use-markers)
7156 "Return a list of the locations of all outline overlays.
7157 These are overlays with the `invisible' property value `outline'.
7158 The return value is a list of cons cells, with start and stop
7159 positions for each overlay.
7160 If USE-MARKERS is set, return the positions as markers."
7161 (let (beg end)
7162 (save-excursion
7163 (save-restriction
7164 (widen)
7165 (delq nil
7166 (mapcar (lambda (o)
7167 (when (eq (overlay-get o 'invisible) 'outline)
7168 (setq beg (overlay-start o)
7169 end (overlay-end o))
7170 (and beg end (> end beg)
7171 (if use-markers
7172 (cons (copy-marker beg)
7173 (copy-marker end t))
7174 (cons beg end)))))
7175 (overlays-in (point-min) (point-max))))))))
7177 (defun org-set-outline-overlay-data (data)
7178 "Create visibility overlays for all positions in DATA.
7179 DATA should have been made by `org-outline-overlay-data'."
7180 (org-with-wide-buffer
7181 (outline-show-all)
7182 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7184 ;;; Folding of blocks
7186 (defvar-local org-hide-block-overlays nil
7187 "Overlays hiding blocks.")
7189 (defun org-block-map (function &optional start end)
7190 "Call FUNCTION at the head of all source blocks in the current buffer.
7191 Optional arguments START and END can be used to limit the range."
7192 (let ((start (or start (point-min)))
7193 (end (or end (point-max))))
7194 (save-excursion
7195 (goto-char start)
7196 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7197 (save-excursion
7198 (save-match-data
7199 (goto-char (match-beginning 0))
7200 (funcall function)))))))
7202 (defun org-hide-block-toggle-all ()
7203 "Toggle the visibility of all blocks in the current buffer."
7204 (org-block-map 'org-hide-block-toggle))
7206 (defun org-hide-block-all ()
7207 "Fold all blocks in the current buffer."
7208 (interactive)
7209 (org-show-block-all)
7210 (org-block-map 'org-hide-block-toggle-maybe))
7212 (defun org-show-block-all ()
7213 "Unfold all blocks in the current buffer."
7214 (interactive)
7215 (mapc #'delete-overlay org-hide-block-overlays)
7216 (setq org-hide-block-overlays nil))
7218 (defun org-hide-block-toggle-maybe ()
7219 "Toggle visibility of block at point.
7220 Unlike to `org-hide-block-toggle', this function does not throw
7221 an error. Return a non-nil value when toggling is successful."
7222 (interactive)
7223 (ignore-errors (org-hide-block-toggle)))
7225 (defun org-hide-block-toggle (&optional force)
7226 "Toggle the visibility of the current block.
7227 When optional argument FORCE is `off', make block visible. If it
7228 is non-nil, hide it unconditionally. Throw an error when not at
7229 a block. Return a non-nil value when toggling is successful."
7230 (interactive)
7231 (let ((element (org-element-at-point)))
7232 (unless (memq (org-element-type element)
7233 '(center-block comment-block dynamic-block example-block
7234 export-block quote-block special-block
7235 src-block verse-block))
7236 (user-error "Not at a block"))
7237 (let* ((start (save-excursion
7238 (goto-char (org-element-property :post-affiliated element))
7239 (line-end-position)))
7240 (end (save-excursion
7241 (goto-char (org-element-property :end element))
7242 (skip-chars-backward " \r\t\n")
7243 (line-end-position)))
7244 (overlays (overlays-at start)))
7245 (cond
7246 ;; Do nothing when not before or at the block opening line or
7247 ;; at the block closing line.
7248 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7249 ((and (not (eq force 'off))
7250 (not (memq t (mapcar
7251 (lambda (o)
7252 (eq (overlay-get o 'invisible) 'org-hide-block))
7253 overlays))))
7254 (let ((ov (make-overlay start end)))
7255 (overlay-put ov 'invisible 'org-hide-block)
7256 ;; Make the block accessible to `isearch'.
7257 (overlay-put
7258 ov 'isearch-open-invisible
7259 (lambda (ov)
7260 (when (memq ov org-hide-block-overlays)
7261 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7262 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7263 (delete-overlay ov))))
7264 (push ov org-hide-block-overlays)
7265 ;; When the block is hidden away, make sure point is left in
7266 ;; a visible part of the buffer.
7267 (when (> (line-beginning-position) start)
7268 (goto-char start)
7269 (beginning-of-line))
7270 ;; Signal successful toggling.
7272 ((or (not force) (eq force 'off))
7273 (dolist (ov overlays t)
7274 (when (memq ov org-hide-block-overlays)
7275 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7276 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7277 (delete-overlay ov))))))))
7279 ;; org-tab-after-check-for-cycling-hook
7280 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7281 ;; Remove overlays when changing major mode
7282 (add-hook 'org-mode-hook
7283 (lambda () (org-add-hook 'change-major-mode-hook
7284 'org-show-block-all 'append 'local)))
7286 ;;; Org-goto
7288 (defvar org-goto-window-configuration nil)
7289 (defvar org-goto-marker nil)
7290 (defvar org-goto-map)
7291 (defun org-goto-map ()
7292 "Set the keymap `org-goto'."
7293 (setq org-goto-map
7294 (let ((map (make-sparse-keymap)))
7295 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7296 mouse-drag-region universal-argument org-occur)))
7297 (dolist (cmd cmds)
7298 (substitute-key-definition cmd cmd map global-map)))
7299 (suppress-keymap map)
7300 (org-defkey map "\C-m" 'org-goto-ret)
7301 (org-defkey map [(return)] 'org-goto-ret)
7302 (org-defkey map [(left)] 'org-goto-left)
7303 (org-defkey map [(right)] 'org-goto-right)
7304 (org-defkey map [(control ?g)] 'org-goto-quit)
7305 (org-defkey map "\C-i" 'org-cycle)
7306 (org-defkey map [(tab)] 'org-cycle)
7307 (org-defkey map [(down)] 'outline-next-visible-heading)
7308 (org-defkey map [(up)] 'outline-previous-visible-heading)
7309 (if org-goto-auto-isearch
7310 (if (fboundp 'define-key-after)
7311 (define-key-after map [t] 'org-goto-local-auto-isearch)
7312 nil)
7313 (org-defkey map "q" 'org-goto-quit)
7314 (org-defkey map "n" 'outline-next-visible-heading)
7315 (org-defkey map "p" 'outline-previous-visible-heading)
7316 (org-defkey map "f" 'outline-forward-same-level)
7317 (org-defkey map "b" 'outline-backward-same-level)
7318 (org-defkey map "u" 'outline-up-heading))
7319 (org-defkey map "/" 'org-occur)
7320 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7321 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7322 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7323 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7324 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7325 map)))
7327 (defconst org-goto-help
7328 "Browse buffer copy, to find location or copy text.%s
7329 RET=jump to location C-g=quit and return to previous location
7330 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7332 (defvar org-goto-start-pos) ; dynamically scoped parameter
7334 (defun org-goto (&optional alternative-interface)
7335 "Look up a different location in the current file, keeping current visibility.
7337 When you want look-up or go to a different location in a
7338 document, the fastest way is often to fold the entire buffer and
7339 then dive into the tree. This method has the disadvantage, that
7340 the previous location will be folded, which may not be what you
7341 want.
7343 This command works around this by showing a copy of the current
7344 buffer in an indirect buffer, in overview mode. You can dive
7345 into the tree in that copy, use org-occur and incremental search
7346 to find a location. When pressing RET or `Q', the command
7347 returns to the original buffer in which the visibility is still
7348 unchanged. After RET it will also jump to the location selected
7349 in the indirect buffer and expose the headline hierarchy above.
7351 With a prefix argument, use the alternative interface: e.g., if
7352 `org-goto-interface' is `outline' use `outline-path-completion'."
7353 (interactive "P")
7354 (org-goto-map)
7355 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7356 (org-refile-use-outline-path t)
7357 (org-refile-target-verify-function nil)
7358 (interface
7359 (if (not alternative-interface)
7360 org-goto-interface
7361 (if (eq org-goto-interface 'outline)
7362 'outline-path-completion
7363 'outline)))
7364 (org-goto-start-pos (point))
7365 (selected-point
7366 (if (eq interface 'outline)
7367 (car (org-get-location (current-buffer) org-goto-help))
7368 (let ((pa (org-refile-get-location "Goto")))
7369 (org-refile-check-position pa)
7370 (nth 3 pa)))))
7371 (if selected-point
7372 (progn
7373 (org-mark-ring-push org-goto-start-pos)
7374 (goto-char selected-point)
7375 (when (or (outline-invisible-p) (org-invisible-p2))
7376 (org-show-context 'org-goto)))
7377 (message "Quit"))))
7379 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7380 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7381 (defvar org-goto-local-auto-isearch-map) ; defined below
7383 (defun org-get-location (_buf help)
7384 "Let the user select a location in current buffer.
7385 This function uses a recursive edit. It returns the selected position
7386 or nil."
7387 (org-no-popups
7388 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7389 (isearch-hide-immediately nil)
7390 (isearch-search-fun-function
7391 (lambda () 'org-goto-local-search-headings))
7392 (org-goto-selected-point org-goto-exit-command))
7393 (save-excursion
7394 (save-window-excursion
7395 (delete-other-windows)
7396 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7397 (org-pop-to-buffer-same-window
7398 (condition-case nil
7399 (make-indirect-buffer (current-buffer) "*org-goto*")
7400 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7401 (with-output-to-temp-buffer "*Org Help*"
7402 (princ (format help (if org-goto-auto-isearch
7403 " Just type for auto-isearch."
7404 " n/p/f/b/u to navigate, q to quit."))))
7405 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7406 (setq buffer-read-only nil)
7407 (let ((org-startup-truncated t)
7408 (org-startup-folded nil)
7409 (org-startup-align-all-tables nil))
7410 (org-mode)
7411 (org-overview))
7412 (setq buffer-read-only t)
7413 (if (and (boundp 'org-goto-start-pos)
7414 (integer-or-marker-p org-goto-start-pos))
7415 (progn (goto-char org-goto-start-pos)
7416 (when (outline-invisible-p)
7417 (org-show-set-visibility 'lineage)))
7418 (goto-char (point-min)))
7419 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7420 (message "Select location and press RET")
7421 (use-local-map org-goto-map)
7422 (recursive-edit)))
7423 (kill-buffer "*org-goto*")
7424 (cons org-goto-selected-point org-goto-exit-command))))
7426 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7427 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7428 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7429 (if (fboundp 'isearch-other-control-char)
7430 (progn
7431 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7432 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7433 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7434 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7435 (define-key org-goto-local-auto-isearch-map [return] nil))
7437 (defun org-goto-local-search-headings (string bound noerror)
7438 "Search and make sure that any matches are in headlines."
7439 (catch 'return
7440 (while (if isearch-forward
7441 (search-forward string bound noerror)
7442 (search-backward string bound noerror))
7443 (when (save-match-data
7444 (and (save-excursion
7445 (beginning-of-line)
7446 (looking-at org-complex-heading-regexp))
7447 (or (not (match-beginning 5))
7448 (< (point) (match-beginning 5)))))
7449 (throw 'return (point))))))
7451 (defun org-goto-local-auto-isearch ()
7452 "Start isearch."
7453 (interactive)
7454 (goto-char (point-min))
7455 (let ((keys (this-command-keys)))
7456 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7457 (isearch-mode t)
7458 (isearch-process-search-char (string-to-char keys)))))
7460 (defun org-goto-ret (&optional _arg)
7461 "Finish `org-goto' by going to the new location."
7462 (interactive "P")
7463 (setq org-goto-selected-point (point))
7464 (setq org-goto-exit-command 'return)
7465 (throw 'exit nil))
7467 (defun org-goto-left ()
7468 "Finish `org-goto' by going to the new location."
7469 (interactive)
7470 (if (org-at-heading-p)
7471 (progn
7472 (beginning-of-line 1)
7473 (setq org-goto-selected-point (point)
7474 org-goto-exit-command 'left)
7475 (throw 'exit nil))
7476 (user-error "Not on a heading")))
7478 (defun org-goto-right ()
7479 "Finish `org-goto' by going to the new location."
7480 (interactive)
7481 (if (org-at-heading-p)
7482 (progn
7483 (setq org-goto-selected-point (point)
7484 org-goto-exit-command 'right)
7485 (throw 'exit nil))
7486 (user-error "Not on a heading")))
7488 (defun org-goto-quit ()
7489 "Finish `org-goto' without cursor motion."
7490 (interactive)
7491 (setq org-goto-selected-point nil)
7492 (setq org-goto-exit-command 'quit)
7493 (throw 'exit nil))
7495 ;;; Indirect buffer display of subtrees
7497 (defvar org-indirect-dedicated-frame nil
7498 "This is the frame being used for indirect tree display.")
7499 (defvar org-last-indirect-buffer nil)
7501 (defun org-tree-to-indirect-buffer (&optional arg)
7502 "Create indirect buffer and narrow it to current subtree.
7503 With a numerical prefix ARG, go up to this level and then take that tree.
7504 If ARG is negative, go up that many levels.
7506 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7507 indirect buffer previously made with this command, to avoid proliferation of
7508 indirect buffers. However, when you call the command with a \
7509 \\[universal-argument] prefix, or
7510 when `org-indirect-buffer-display' is `new-frame', the last buffer
7511 is kept so that you can work with several indirect buffers at the same time.
7512 If `org-indirect-buffer-display' is `dedicated-frame', the \
7513 \\[universal-argument] prefix also
7514 requests that a new frame be made for the new buffer, so that the dedicated
7515 frame is not changed."
7516 (interactive "P")
7517 (let ((cbuf (current-buffer))
7518 (cwin (selected-window))
7519 (pos (point))
7520 beg end level heading ibuf)
7521 (save-excursion
7522 (org-back-to-heading t)
7523 (when (numberp arg)
7524 (setq level (org-outline-level))
7525 (when (< arg 0) (setq arg (+ level arg)))
7526 (while (> (setq level (org-outline-level)) arg)
7527 (org-up-heading-safe)))
7528 (setq beg (point)
7529 heading (org-get-heading 'no-tags))
7530 (org-end-of-subtree t t)
7531 (when (org-at-heading-p) (backward-char 1))
7532 (setq end (point)))
7533 (when (and (buffer-live-p org-last-indirect-buffer)
7534 (not (eq org-indirect-buffer-display 'new-frame))
7535 (not arg))
7536 (kill-buffer org-last-indirect-buffer))
7537 (setq ibuf (org-get-indirect-buffer cbuf heading)
7538 org-last-indirect-buffer ibuf)
7539 (cond
7540 ((or (eq org-indirect-buffer-display 'new-frame)
7541 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7542 (select-frame (make-frame))
7543 (delete-other-windows)
7544 (org-pop-to-buffer-same-window ibuf)
7545 (org-set-frame-title heading))
7546 ((eq org-indirect-buffer-display 'dedicated-frame)
7547 (raise-frame
7548 (select-frame (or (and org-indirect-dedicated-frame
7549 (frame-live-p org-indirect-dedicated-frame)
7550 org-indirect-dedicated-frame)
7551 (setq org-indirect-dedicated-frame (make-frame)))))
7552 (delete-other-windows)
7553 (org-pop-to-buffer-same-window ibuf)
7554 (org-set-frame-title (concat "Indirect: " heading)))
7555 ((eq org-indirect-buffer-display 'current-window)
7556 (org-pop-to-buffer-same-window ibuf))
7557 ((eq org-indirect-buffer-display 'other-window)
7558 (pop-to-buffer ibuf))
7559 (t (error "Invalid value")))
7560 (when (featurep 'xemacs)
7561 (save-excursion (org-mode) (turn-on-font-lock)))
7562 (narrow-to-region beg end)
7563 (outline-show-all)
7564 (goto-char pos)
7565 (run-hook-with-args 'org-cycle-hook 'all)
7566 (and (window-live-p cwin) (select-window cwin))))
7568 (defun org-get-indirect-buffer (&optional buffer heading)
7569 (setq buffer (or buffer (current-buffer)))
7570 (let ((n 1) (base (buffer-name buffer)) bname)
7571 (while (buffer-live-p
7572 (get-buffer
7573 (setq bname
7574 (concat base "-"
7575 (if heading (concat heading "-" (number-to-string n))
7576 (number-to-string n))))))
7577 (setq n (1+ n)))
7578 (condition-case nil
7579 (make-indirect-buffer buffer bname 'clone)
7580 (error (make-indirect-buffer buffer bname)))))
7582 (defun org-set-frame-title (title)
7583 "Set the title of the current frame to the string TITLE."
7584 ;; FIXME: how to name a single frame in XEmacs???
7585 (unless (featurep 'xemacs)
7586 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7588 ;;;; Structure editing
7590 ;;; Inserting headlines
7592 (defun org--line-empty-p (n)
7593 "Is the Nth next line empty?
7595 Counts the current line as N = 1 and the previous line as N = 0;
7596 see `beginning-of-line'."
7597 (save-excursion
7598 (and (not (bobp))
7599 (or (beginning-of-line n) t)
7600 (save-match-data
7601 (looking-at "[ \t]*$")))))
7603 (defun org-previous-line-empty-p ()
7604 "Is the previous line a blank line?
7605 When NEXT is non-nil, check the next line instead."
7606 (org--line-empty-p 0))
7608 (defun org-next-line-empty-p ()
7609 "Is the previous line a blank line?
7610 When NEXT is non-nil, check the next line instead."
7611 (org--line-empty-p 2))
7613 (defun org-insert-heading (&optional arg invisible-ok top)
7614 "Insert a new heading or an item with the same depth at point.
7616 If point is at the beginning of a heading or a list item, insert
7617 a new heading or a new item above the current one. If point is
7618 at the beginning of a normal line, turn the line into a heading.
7620 If point is in the middle of a headline or a list item, split the
7621 headline or the item and create a new headline/item with the text
7622 in the current line after point \(see `org-M-RET-may-split-line'
7623 on how to modify this behavior).
7625 With one universal prefix argument, set the user option
7626 `org-insert-heading-respect-content' to t for the duration of
7627 the command. This modifies the behavior described above in this
7628 ways: on list items and at the beginning of normal lines, force
7629 the insertion of a heading after the current subtree.
7631 With two universal prefix arguments, insert the heading at the
7632 end of the grandparent subtree. For example, if point is within
7633 a 2nd-level heading, then it will insert a 2nd-level heading at
7634 the end of the 1st-level parent heading.
7636 If point is at the beginning of a headline, insert a sibling
7637 before the current headline. If point is not at the beginning,
7638 split the line and create a new headline with the text in the
7639 current line after point \(see `org-M-RET-may-split-line' on how
7640 to modify this behavior).
7642 If point is at the beginning of a normal line, turn this line
7643 into a heading.
7645 When INVISIBLE-OK is set, stop at invisible headlines when going
7646 back. This is important for non-interactive uses of the
7647 command.
7649 When optional argument TOP is non-nil, insert a level 1 heading,
7650 unconditionally."
7651 (interactive "P")
7652 (when (org-called-interactively-p 'any) (org-reveal))
7653 (let ((itemp (and (not top) (org-in-item-p)))
7654 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7655 (respect-content (or org-insert-heading-respect-content
7656 (equal arg '(4))))
7657 (initial-content ""))
7659 (cond
7661 ((or (= (buffer-size) 0)
7662 (and (not (save-excursion
7663 (and (ignore-errors (org-back-to-heading invisible-ok))
7664 (org-at-heading-p))))
7665 (or arg (not itemp))))
7666 ;; At beginning of buffer or so high up that only a heading
7667 ;; makes sense.
7668 (cond ((and (bolp) (not respect-content)) (insert "* "))
7669 ((not respect-content)
7670 (unless may-split (end-of-line))
7671 (insert "\n* "))
7672 ((re-search-forward org-outline-regexp-bol nil t)
7673 (beginning-of-line)
7674 (insert "* \n")
7675 (backward-char))
7676 (t (goto-char (point-max))
7677 (insert "\n* ")))
7678 (run-hooks 'org-insert-heading-hook))
7680 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7683 ;; Maybe move at the end of the subtree
7684 (when (equal arg '(16))
7685 (org-up-heading-safe)
7686 (org-end-of-subtree t))
7687 ;; Insert a heading
7688 (save-restriction
7689 (widen)
7690 (let* ((level nil)
7691 (on-heading (org-at-heading-p))
7692 (empty-line-p (if on-heading
7693 (org-previous-line-empty-p)
7694 ;; We will decide later
7695 nil))
7696 ;; Get a level string to fall back on.
7697 (fix-level
7698 (if (org-before-first-heading-p) "*"
7699 (save-excursion
7700 (org-back-to-heading t)
7701 (when (org-previous-line-empty-p) (setq empty-line-p t))
7702 (looking-at org-outline-regexp)
7703 (make-string (1- (length (match-string 0))) ?*))))
7704 (stars
7705 (save-excursion
7706 (condition-case nil
7707 (if top "* "
7708 (org-back-to-heading invisible-ok)
7709 (when (and (not on-heading)
7710 (featurep 'org-inlinetask)
7711 (integerp org-inlinetask-min-level)
7712 (>= (length (match-string 0))
7713 org-inlinetask-min-level))
7714 ;; Find a heading level before the inline
7715 ;; task.
7716 (while (and (setq level (org-up-heading-safe))
7717 (>= level org-inlinetask-min-level)))
7718 (if (org-at-heading-p)
7719 (org-back-to-heading invisible-ok)
7720 (error "This should not happen")))
7721 (unless (and (save-excursion
7722 (save-match-data
7723 (org-backward-heading-same-level
7724 1 invisible-ok))
7725 (= (point) (match-beginning 0)))
7726 (not (org-next-line-empty-p)))
7727 (setq empty-line-p (or empty-line-p
7728 (org-previous-line-empty-p))))
7729 (match-string 0))
7730 (error (or fix-level "* ")))))
7731 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7732 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7734 ;; If we insert after content, move there and clean up
7735 ;; whitespace.
7736 (when (and respect-content
7737 (not (org-looking-at-p org-outline-regexp-bol)))
7738 (if (not (org-before-first-heading-p))
7739 (org-end-of-subtree nil t)
7740 (re-search-forward org-outline-regexp-bol)
7741 (beginning-of-line 0))
7742 (skip-chars-backward " \r\t\n")
7743 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7744 (looking-at "[ \t]+") (replace-match ""))
7745 (unless (eobp) (forward-char 1))
7746 (when (looking-at "^\\*")
7747 (unless (bobp) (backward-char 1))
7748 (insert "\n")))
7750 ;; If we are splitting, grab the text that should be moved
7751 ;; to the new headline.
7752 (when may-split
7753 (if (org-at-heading-p)
7754 ;; This is a heading: split intelligently (keeping
7755 ;; tags).
7756 (let ((pos (point)))
7757 (beginning-of-line)
7758 (unless (looking-at org-complex-heading-regexp)
7759 (error "This should not happen"))
7760 (when (and (match-beginning 4)
7761 (> pos (match-beginning 4))
7762 (< pos (match-end 4)))
7763 (setq initial-content (buffer-substring pos (match-end 4)))
7764 (goto-char pos)
7765 (delete-region (point) (match-end 4))
7766 (if (looking-at "[ \t]*$")
7767 (replace-match "")
7768 (insert (make-string (length initial-content) ?\s)))
7769 (setq initial-content (org-trim initial-content)))
7770 (goto-char pos))
7771 ;; A normal line.
7772 (setq initial-content
7773 (org-trim
7774 (delete-and-extract-region (point) (line-end-position))))))
7776 ;; If we are at the beginning of the line, insert before it.
7777 ;; Otherwise, after it.
7778 (cond
7779 ((and (bolp) (looking-at "[ \t]*$")))
7780 ((bolp) (save-excursion (insert "\n")))
7781 (t (end-of-line)
7782 (insert "\n")))
7784 ;; Insert the new heading
7785 (insert stars)
7786 (just-one-space)
7787 (insert initial-content)
7788 (unless (and blank (org-previous-line-empty-p))
7789 (org-N-empty-lines-before-current (if blank 1 0)))
7790 ;; Adjust visibility, which may be messed up if we removed
7791 ;; blank lines while previous entry was hidden.
7792 (let ((bol (line-beginning-position)))
7793 (dolist (o (overlays-at (1- bol)))
7794 (when (and (eq (overlay-get o 'invisible) 'outline)
7795 (eq (overlay-end o) bol))
7796 (move-overlay o (overlay-start o) (1- bol)))))
7797 (run-hooks 'org-insert-heading-hook)))))))
7799 (defun org-N-empty-lines-before-current (N)
7800 "Make the number of empty lines before current exactly N.
7801 So this will delete or add empty lines."
7802 (save-excursion
7803 (beginning-of-line)
7804 (let ((p (point)))
7805 (skip-chars-backward " \r\t\n")
7806 (unless (bolp) (forward-line))
7807 (delete-region (point) p))
7808 (when (> N 0) (insert (make-string N ?\n)))))
7810 (defun org-get-heading (&optional no-tags no-todo)
7811 "Return the heading of the current entry, without the stars.
7812 When NO-TAGS is non-nil, don't include tags.
7813 When NO-TODO is non-nil, don't include TODO keywords."
7814 (save-excursion
7815 (org-back-to-heading t)
7816 (cond
7817 ((and no-tags no-todo)
7818 (looking-at org-complex-heading-regexp)
7819 (match-string 4))
7820 (no-tags
7821 (looking-at (concat org-outline-regexp
7822 "\\(.*?\\)"
7823 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7824 (match-string 1))
7825 (no-todo
7826 (looking-at org-todo-line-regexp)
7827 (match-string 3))
7828 (t (looking-at org-heading-regexp)
7829 (match-string 2)))))
7831 (defvar orgstruct-mode) ; defined below
7833 (defun org-heading-components ()
7834 "Return the components of the current heading.
7835 This is a list with the following elements:
7836 - the level as an integer
7837 - the reduced level, different if `org-odd-levels-only' is set.
7838 - the TODO keyword, or nil
7839 - the priority character, like ?A, or nil if no priority is given
7840 - the headline text itself, or the tags string if no headline text
7841 - the tags string, or nil."
7842 (save-excursion
7843 (org-back-to-heading t)
7844 (when (let (case-fold-search)
7845 (looking-at
7846 (if orgstruct-mode
7847 org-heading-regexp
7848 org-complex-heading-regexp)))
7849 (if orgstruct-mode
7850 (list (length (match-string 1))
7851 (org-reduced-level (length (match-string 1)))
7854 (match-string 2)
7855 nil)
7856 (list (length (match-string 1))
7857 (org-reduced-level (length (match-string 1)))
7858 (org-match-string-no-properties 2)
7859 (and (match-end 3) (aref (match-string 3) 2))
7860 (org-match-string-no-properties 4)
7861 (org-match-string-no-properties 5))))))
7863 (defun org-get-entry ()
7864 "Get the entry text, after heading, entire subtree."
7865 (save-excursion
7866 (org-back-to-heading t)
7867 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7869 (defun org-edit-headline (&optional heading)
7870 "Edit the current headline.
7871 Set it to HEADING when provided."
7872 (interactive)
7873 (org-with-wide-buffer
7874 (org-back-to-heading t)
7875 (when (looking-at org-complex-heading-regexp)
7876 (let* ((old (match-string-no-properties 4))
7877 (new (org-trim (or heading (read-string "Edit: " old)))))
7878 (unless (equal old new)
7879 (if old (replace-match new t t nil 4)
7880 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7881 (insert " " new))
7882 (org-set-tags nil t)
7883 (when (looking-at "[ \t]*$") (replace-match "")))))))
7885 (defun org-insert-heading-after-current ()
7886 "Insert a new heading with same level as current, after current subtree."
7887 (interactive)
7888 (org-back-to-heading)
7889 (org-insert-heading)
7890 (org-move-subtree-down)
7891 (end-of-line 1))
7893 (defun org-insert-heading-respect-content (&optional invisible-ok)
7894 "Insert heading with `org-insert-heading-respect-content' set to t."
7895 (interactive)
7896 (org-insert-heading '(4) invisible-ok))
7898 (defun org-insert-todo-heading-respect-content (&optional force-state)
7899 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7900 (interactive)
7901 (org-insert-todo-heading force-state '(4)))
7903 (defun org-insert-todo-heading (arg &optional force-heading)
7904 "Insert a new heading with the same level and TODO state as current heading.
7905 If the heading has no TODO state, or if the state is DONE, use the first
7906 state (TODO by default). Also with one prefix arg, force first state. With
7907 two prefix args, force inserting at the end of the parent subtree."
7908 (interactive "P")
7909 (when (or force-heading (not (org-insert-item 'checkbox)))
7910 (org-insert-heading (or (and (equal arg '(16)) '(16))
7911 force-heading))
7912 (save-excursion
7913 (org-back-to-heading)
7914 (outline-previous-heading)
7915 (looking-at org-todo-line-regexp))
7916 (let*
7917 ((new-mark-x
7918 (if (or (equal arg '(4))
7919 (not (match-beginning 2))
7920 (member (match-string 2) org-done-keywords))
7921 (car org-todo-keywords-1)
7922 (match-string 2)))
7923 (new-mark
7925 (run-hook-with-args-until-success
7926 'org-todo-get-default-hook new-mark-x nil)
7927 new-mark-x)))
7928 (beginning-of-line 1)
7929 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7930 (if org-treat-insert-todo-heading-as-state-change
7931 (org-todo new-mark)
7932 (insert new-mark " "))))
7933 (when org-provide-todo-statistics
7934 (org-update-parent-todo-statistics))))
7936 (defun org-insert-subheading (arg)
7937 "Insert a new subheading and demote it.
7938 Works for outline headings and for plain lists alike."
7939 (interactive "P")
7940 (org-insert-heading arg)
7941 (cond
7942 ((org-at-heading-p) (org-do-demote))
7943 ((org-at-item-p) (org-indent-item))))
7945 (defun org-insert-todo-subheading (arg)
7946 "Insert a new subheading with TODO keyword or checkbox and demote it.
7947 Works for outline headings and for plain lists alike."
7948 (interactive "P")
7949 (org-insert-todo-heading arg)
7950 (cond
7951 ((org-at-heading-p) (org-do-demote))
7952 ((org-at-item-p) (org-indent-item))))
7954 ;;; Promotion and Demotion
7956 (defvar org-after-demote-entry-hook nil
7957 "Hook run after an entry has been demoted.
7958 The cursor will be at the beginning of the entry.
7959 When a subtree is being demoted, the hook will be called for each node.")
7961 (defvar org-after-promote-entry-hook nil
7962 "Hook run after an entry has been promoted.
7963 The cursor will be at the beginning of the entry.
7964 When a subtree is being promoted, the hook will be called for each node.")
7966 (defun org-promote-subtree ()
7967 "Promote the entire subtree.
7968 See also `org-promote'."
7969 (interactive)
7970 (save-excursion
7971 (org-with-limited-levels (org-map-tree 'org-promote)))
7972 (org-fix-position-after-promote))
7974 (defun org-demote-subtree ()
7975 "Demote the entire subtree.
7976 See `org-demote' and `org-promote'."
7977 (interactive)
7978 (save-excursion
7979 (org-with-limited-levels (org-map-tree 'org-demote)))
7980 (org-fix-position-after-promote))
7982 (defun org-do-promote ()
7983 "Promote the current heading higher up the tree.
7984 If the region is active in `transient-mark-mode', promote all
7985 headings in the region."
7986 (interactive)
7987 (save-excursion
7988 (if (org-region-active-p)
7989 (org-map-region 'org-promote (region-beginning) (region-end))
7990 (org-promote)))
7991 (org-fix-position-after-promote))
7993 (defun org-do-demote ()
7994 "Demote the current heading lower down the tree.
7995 If the region is active in `transient-mark-mode', demote all
7996 headings in the region."
7997 (interactive)
7998 (save-excursion
7999 (if (org-region-active-p)
8000 (org-map-region 'org-demote (region-beginning) (region-end))
8001 (org-demote)))
8002 (org-fix-position-after-promote))
8004 (defun org-fix-position-after-promote ()
8005 "Fix cursor position and indentation after demoting/promoting."
8006 (let ((pos (point)))
8007 (when (save-excursion
8008 (beginning-of-line 1)
8009 (looking-at org-todo-line-regexp)
8010 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8011 (cond ((eobp) (insert " "))
8012 ((eolp) (insert " "))
8013 ((equal (char-after) ?\ ) (forward-char 1))))))
8015 (defun org-current-level ()
8016 "Return the level of the current entry, or nil if before the first headline.
8017 The level is the number of stars at the beginning of the
8018 headline. Use `org-reduced-level' to remove the effect of
8019 `org-odd-levels'. Unlike to `org-outline-level', this function
8020 ignores inlinetasks."
8021 (let ((level (org-with-limited-levels (org-outline-level))))
8022 (and (> level 0) level)))
8024 (defun org-get-previous-line-level ()
8025 "Return the outline depth of the last headline before the current line.
8026 Returns 0 for the first headline in the buffer, and nil if before the
8027 first headline."
8028 (and (org-current-level)
8029 (or (and (/= (line-beginning-position) (point-min))
8030 (save-excursion (beginning-of-line 0) (org-current-level)))
8031 0)))
8033 (defun org-reduced-level (l)
8034 "Compute the effective level of a heading.
8035 This takes into account the setting of `org-odd-levels-only'."
8036 (cond
8037 ((zerop l) 0)
8038 (org-odd-levels-only (1+ (floor (/ l 2))))
8039 (t l)))
8041 (defun org-level-increment ()
8042 "Return the number of stars that will be added or removed at a
8043 time to headlines when structure editing, based on the value of
8044 `org-odd-levels-only'."
8045 (if org-odd-levels-only 2 1))
8047 (defun org-get-valid-level (level &optional change)
8048 "Rectify a level change under the influence of `org-odd-levels-only'
8049 LEVEL is a current level, CHANGE is by how much the level should be
8050 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8051 even level numbers will become the next higher odd number."
8052 (if org-odd-levels-only
8053 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8054 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8055 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8056 (max 1 (+ level (or change 0)))))
8057 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8059 (defun org-promote ()
8060 "Promote the current heading higher up the tree."
8061 (org-with-wide-buffer
8062 (org-back-to-heading t)
8063 (let* ((after-change-functions (remq 'flyspell-after-change-function
8064 after-change-functions))
8065 (level (save-match-data (funcall outline-level)))
8066 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8067 (diff (abs (- level (length up-head) -1))))
8068 (cond
8069 ((and (= level 1) org-allow-promoting-top-level-subtree)
8070 (replace-match "# " nil t))
8071 ((= level 1)
8072 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8073 (t (replace-match up-head nil t)))
8074 (unless (= level 1)
8075 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8076 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8077 (run-hooks 'org-after-promote-entry-hook))))
8079 (defun org-demote ()
8080 "Demote the current heading lower down the tree."
8081 (org-with-wide-buffer
8082 (org-back-to-heading t)
8083 (let* ((after-change-functions (remq 'flyspell-after-change-function
8084 after-change-functions))
8085 (level (save-match-data (funcall outline-level)))
8086 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8087 (diff (abs (- level (length down-head) -1))))
8088 (replace-match down-head nil t)
8089 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8090 (when org-adapt-indentation (org-fixup-indentation diff))
8091 (run-hooks 'org-after-demote-entry-hook))))
8093 (defun org-cycle-level ()
8094 "Cycle the level of an empty headline through possible states.
8095 This goes first to child, then to parent, level, then up the hierarchy.
8096 After top level, it switches back to sibling level."
8097 (interactive)
8098 (let ((org-adapt-indentation nil))
8099 (when (org-point-at-end-of-empty-headline)
8100 (setq this-command 'org-cycle-level) ; Only needed for caching
8101 (let ((cur-level (org-current-level))
8102 (prev-level (org-get-previous-line-level)))
8103 (cond
8104 ;; If first headline in file, promote to top-level.
8105 ((= prev-level 0)
8106 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8107 do (org-do-promote)))
8108 ;; If same level as prev, demote one.
8109 ((= prev-level cur-level)
8110 (org-do-demote))
8111 ;; If parent is top-level, promote to top level if not already.
8112 ((= prev-level 1)
8113 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8114 do (org-do-promote)))
8115 ;; If top-level, return to prev-level.
8116 ((= cur-level 1)
8117 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8118 do (org-do-demote)))
8119 ;; If less than prev-level, promote one.
8120 ((< cur-level prev-level)
8121 (org-do-promote))
8122 ;; If deeper than prev-level, promote until higher than
8123 ;; prev-level.
8124 ((> cur-level prev-level)
8125 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8126 do (org-do-promote))))
8127 t))))
8129 (defun org-map-tree (fun)
8130 "Call FUN for every heading underneath the current one."
8131 (org-back-to-heading)
8132 (let ((level (funcall outline-level)))
8133 (save-excursion
8134 (funcall fun)
8135 (while (and (progn
8136 (outline-next-heading)
8137 (> (funcall outline-level) level))
8138 (not (eobp)))
8139 (funcall fun)))))
8141 (defun org-map-region (fun beg end)
8142 "Call FUN for every heading between BEG and END."
8143 (let ((org-ignore-region t))
8144 (save-excursion
8145 (setq end (copy-marker end))
8146 (goto-char beg)
8147 (when (and (re-search-forward org-outline-regexp-bol nil t)
8148 (< (point) end))
8149 (funcall fun))
8150 (while (and (progn
8151 (outline-next-heading)
8152 (< (point) end))
8153 (not (eobp)))
8154 (funcall fun)))))
8156 (defun org-fixup-indentation (diff)
8157 "Change the indentation in the current entry by DIFF.
8159 DIFF is an integer. Indentation is done according to the
8160 following rules:
8162 - Planning information and property drawers are always indented
8163 according to the new level of the headline;
8165 - Footnote definitions and their contents are ignored;
8167 - Inlinetasks' boundaries are not shifted;
8169 - Empty lines are ignored;
8171 - Other lines' indentation are shifted by DIFF columns, unless
8172 it would introduce a structural change in the document, in
8173 which case no shifting is done at all.
8175 Assume point is at a heading or an inlinetask beginning."
8176 (org-with-wide-buffer
8177 (narrow-to-region (line-beginning-position)
8178 (save-excursion
8179 (if (org-with-limited-levels (org-at-heading-p))
8180 (org-with-limited-levels (outline-next-heading))
8181 (org-inlinetask-goto-end))
8182 (point)))
8183 (forward-line)
8184 ;; Indent properly planning info and property drawer.
8185 (when (org-looking-at-p org-planning-line-re)
8186 (org-indent-line)
8187 (forward-line))
8188 (when (looking-at org-property-drawer-re)
8189 (goto-char (match-end 0))
8190 (forward-line)
8191 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8192 (catch 'no-shift
8193 (when (zerop diff) (throw 'no-shift nil))
8194 ;; If DIFF is negative, first check if a shift is possible at all
8195 ;; (e.g., it doesn't break structure). This can only happen if
8196 ;; some contents are not properly indented.
8197 (let ((case-fold-search t))
8198 (when (< diff 0)
8199 (let ((diff (- diff))
8200 (forbidden-re (concat org-outline-regexp
8201 "\\|"
8202 (substring org-footnote-definition-re 1))))
8203 (save-excursion
8204 (while (not (eobp))
8205 (cond
8206 ((org-looking-at-p "[ \t]*$") (forward-line))
8207 ((and (org-looking-at-p org-footnote-definition-re)
8208 (let ((e (org-element-at-point)))
8209 (and (eq (org-element-type e) 'footnote-definition)
8210 (goto-char (org-element-property :end e))))))
8211 ((org-looking-at-p org-outline-regexp) (forward-line))
8212 ;; Give up if shifting would move before column 0 or
8213 ;; if it would introduce a headline or a footnote
8214 ;; definition.
8216 (skip-chars-forward " \t")
8217 (let ((ind (current-column)))
8218 (when (or (< ind diff)
8219 (and (= ind diff) (org-looking-at-p forbidden-re)))
8220 (throw 'no-shift nil)))
8221 ;; Ignore contents of example blocks and source
8222 ;; blocks if their indentation is meant to be
8223 ;; preserved. Jump to block's closing line.
8224 (beginning-of-line)
8225 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8226 (let ((e (org-element-at-point)))
8227 (and (memq (org-element-type e)
8228 '(example-block src-block))
8229 (or org-src-preserve-indentation
8230 (org-element-property :preserve-indent e))
8231 (goto-char (org-element-property :end e))
8232 (progn (skip-chars-backward " \r\t\n")
8233 (beginning-of-line)
8234 t))))
8235 (forward-line))))))))
8236 ;; Shift lines but footnote definitions, inlinetasks boundaries
8237 ;; by DIFF. Also skip contents of source or example blocks
8238 ;; when indentation is meant to be preserved.
8239 (while (not (eobp))
8240 (cond
8241 ((and (org-looking-at-p org-footnote-definition-re)
8242 (let ((e (org-element-at-point)))
8243 (and (eq (org-element-type e) 'footnote-definition)
8244 (goto-char (org-element-property :end e))))))
8245 ((org-looking-at-p org-outline-regexp) (forward-line))
8246 ((org-looking-at-p "[ \t]*$") (forward-line))
8248 (org-indent-line-to (+ (org-get-indentation) diff))
8249 (beginning-of-line)
8250 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8251 (let ((e (org-element-at-point)))
8252 (and (memq (org-element-type e)
8253 '(example-block src-block))
8254 (or org-src-preserve-indentation
8255 (org-element-property :preserve-indent e))
8256 (goto-char (org-element-property :end e))
8257 (progn (skip-chars-backward " \r\t\n")
8258 (beginning-of-line)
8259 t))))
8260 (forward-line)))))))))
8262 (defun org-convert-to-odd-levels ()
8263 "Convert an org-mode file with all levels allowed to one with odd levels.
8264 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8265 level 5 etc."
8266 (interactive)
8267 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8268 (let ((outline-level 'org-outline-level)
8269 (org-odd-levels-only nil) n)
8270 (save-excursion
8271 (goto-char (point-min))
8272 (while (re-search-forward "^\\*\\*+ " nil t)
8273 (setq n (- (length (match-string 0)) 2))
8274 (while (>= (setq n (1- n)) 0)
8275 (org-demote))
8276 (end-of-line 1))))))
8278 (defun org-convert-to-oddeven-levels ()
8279 "Convert an org-mode file with only odd levels to one with odd/even levels.
8280 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8281 file contains a section with an even level, conversion would
8282 destroy the structure of the file. An error is signaled in this
8283 case."
8284 (interactive)
8285 (goto-char (point-min))
8286 ;; First check if there are no even levels
8287 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8288 (org-show-set-visibility 'canonical)
8289 (error "Not all levels are odd in this file. Conversion not possible"))
8290 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8291 (let ((outline-regexp org-outline-regexp)
8292 (outline-level 'org-outline-level)
8293 (org-odd-levels-only nil) n)
8294 (save-excursion
8295 (goto-char (point-min))
8296 (while (re-search-forward "^\\*\\*+ " nil t)
8297 (setq n (/ (1- (length (match-string 0))) 2))
8298 (while (>= (setq n (1- n)) 0)
8299 (org-promote))
8300 (end-of-line 1))))))
8302 (defun org-tr-level (n)
8303 "Make N odd if required."
8304 (if org-odd-levels-only (1+ (/ n 2)) n))
8306 ;;; Vertical tree motion, cutting and pasting of subtrees
8308 (defun org-move-subtree-up (&optional arg)
8309 "Move the current subtree up past ARG headlines of the same level."
8310 (interactive "p")
8311 (org-move-subtree-down (- (prefix-numeric-value arg))))
8313 (defun org-move-subtree-down (&optional arg)
8314 "Move the current subtree down past ARG headlines of the same level."
8315 (interactive "p")
8316 (setq arg (prefix-numeric-value arg))
8317 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8318 'org-get-last-sibling))
8319 (ins-point (make-marker))
8320 (cnt (abs arg))
8321 (col (current-column))
8322 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8323 ;; Select the tree
8324 (org-back-to-heading)
8325 (setq beg0 (point))
8326 (save-excursion
8327 (setq ne-beg (org-back-over-empty-lines))
8328 (setq beg (point)))
8329 (save-match-data
8330 (save-excursion (outline-end-of-heading)
8331 (setq folded (outline-invisible-p)))
8332 (progn (org-end-of-subtree nil t)
8333 (unless (eobp) (backward-char))))
8334 (outline-next-heading)
8335 (setq ne-end (org-back-over-empty-lines))
8336 (setq end (point))
8337 (goto-char beg0)
8338 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8339 ;; include less whitespace
8340 (save-excursion
8341 (goto-char beg)
8342 (forward-line (- ne-beg ne-end))
8343 (setq beg (point))))
8344 ;; Find insertion point, with error handling
8345 (while (> cnt 0)
8346 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8347 (progn (goto-char beg0)
8348 (user-error "Cannot move past superior level or buffer limit")))
8349 (setq cnt (1- cnt)))
8350 (when (> arg 0)
8351 ;; Moving forward - still need to move over subtree
8352 (org-end-of-subtree t t)
8353 (save-excursion
8354 (org-back-over-empty-lines)
8355 (or (bolp) (newline))))
8356 (setq ne-ins (org-back-over-empty-lines))
8357 (move-marker ins-point (point))
8358 (setq txt (buffer-substring beg end))
8359 (org-save-markers-in-region beg end)
8360 (delete-region beg end)
8361 (org-remove-empty-overlays-at beg)
8362 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8363 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8364 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8365 (let ((bbb (point)))
8366 (insert-before-markers txt)
8367 (org-reinstall-markers-in-region bbb)
8368 (move-marker ins-point bbb))
8369 (or (bolp) (insert "\n"))
8370 (setq ins-end (point))
8371 (goto-char ins-point)
8372 (org-skip-whitespace)
8373 (when (and (< arg 0)
8374 (org-first-sibling-p)
8375 (> ne-ins ne-beg))
8376 ;; Move whitespace back to beginning
8377 (save-excursion
8378 (goto-char ins-end)
8379 (let ((kill-whole-line t))
8380 (kill-line (- ne-ins ne-beg)) (point)))
8381 (insert (make-string (- ne-ins ne-beg) ?\n)))
8382 (move-marker ins-point nil)
8383 (if folded
8384 (outline-hide-subtree)
8385 (org-show-entry)
8386 (org-show-children)
8387 (org-cycle-hide-drawers 'children))
8388 (org-clean-visibility-after-subtree-move)
8389 ;; move back to the initial column we were at
8390 (move-to-column col)))
8392 (defvar org-subtree-clip ""
8393 "Clipboard for cut and paste of subtrees.
8394 This is actually only a copy of the kill, because we use the normal kill
8395 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8397 (defvar org-subtree-clip-folded nil
8398 "Was the last copied subtree folded?
8399 This is used to fold the tree back after pasting.")
8401 (defun org-cut-subtree (&optional n)
8402 "Cut the current subtree into the clipboard.
8403 With prefix arg N, cut this many sequential subtrees.
8404 This is a short-hand for marking the subtree and then cutting it."
8405 (interactive "p")
8406 (org-copy-subtree n 'cut))
8408 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8409 "Copy the current subtree it in the clipboard.
8410 With prefix arg N, copy this many sequential subtrees.
8411 This is a short-hand for marking the subtree and then copying it.
8412 If CUT is non-nil, actually cut the subtree.
8413 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8414 of some markers in the region, even if CUT is non-nil. This is
8415 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8416 (interactive "p")
8417 (let (beg end folded (beg0 (point)))
8418 (if (org-called-interactively-p 'any)
8419 (org-back-to-heading nil) ; take what looks like a subtree
8420 (org-back-to-heading t)) ; take what is really there
8421 (setq beg (point))
8422 (skip-chars-forward " \t\r\n")
8423 (save-match-data
8424 (if nosubtrees
8425 (outline-next-heading)
8426 (save-excursion (outline-end-of-heading)
8427 (setq folded (outline-invisible-p)))
8428 (ignore-errors (org-forward-heading-same-level (1- n) t))
8429 (org-end-of-subtree t t)))
8430 ;; Include the end of an inlinetask
8431 (when (and (featurep 'org-inlinetask)
8432 (looking-at-p (concat (org-inlinetask-outline-regexp)
8433 "END[ \t]*$")))
8434 (end-of-line))
8435 (setq end (point))
8436 (goto-char beg0)
8437 (when (> end beg)
8438 (setq org-subtree-clip-folded folded)
8439 (when (or cut force-store-markers)
8440 (org-save-markers-in-region beg end))
8441 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8442 (setq org-subtree-clip (current-kill 0))
8443 (message "%s: Subtree(s) with %d characters"
8444 (if cut "Cut" "Copied")
8445 (length org-subtree-clip)))))
8447 (defun org-paste-subtree (&optional level tree for-yank remove)
8448 "Paste the clipboard as a subtree, with modification of headline level.
8449 The entire subtree is promoted or demoted in order to match a new headline
8450 level.
8452 If the cursor is at the beginning of a headline, the same level as
8453 that headline is used to paste the tree.
8455 If not, the new level is derived from the *visible* headings
8456 before and after the insertion point, and taken to be the inferior headline
8457 level of the two. So if the previous visible heading is level 3 and the
8458 next is level 4 (or vice versa), level 4 will be used for insertion.
8459 This makes sure that the subtree remains an independent subtree and does
8460 not swallow low level entries.
8462 You can also force a different level, either by using a numeric prefix
8463 argument, or by inserting the heading marker by hand. For example, if the
8464 cursor is after \"*****\", then the tree will be shifted to level 5.
8466 If optional TREE is given, use this text instead of the kill ring.
8468 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8469 move back over whitespace before inserting, and move point to the end of
8470 the inserted text when done.
8472 When REMOVE is non-nil, remove the subtree from the clipboard."
8473 (interactive "P")
8474 (setq tree (or tree (and kill-ring (current-kill 0))))
8475 (unless (org-kill-is-subtree-p tree)
8476 (user-error "%s"
8477 (substitute-command-keys
8478 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8479 (org-with-limited-levels
8480 (let* ((visp (not (outline-invisible-p)))
8481 (txt tree)
8482 (^re_ "\\(\\*+\\)[ \t]*")
8483 (old-level (if (string-match org-outline-regexp-bol txt)
8484 (- (match-end 0) (match-beginning 0) 1)
8485 -1))
8486 (force-level (cond (level (prefix-numeric-value level))
8487 ((and (looking-at "[ \t]*$")
8488 (string-match
8489 "^\\*+$" (buffer-substring
8490 (point-at-bol) (point))))
8491 (- (match-end 0) (match-beginning 0)))
8492 ((and (bolp)
8493 (looking-at org-outline-regexp))
8494 (- (match-end 0) (point) 1))))
8495 (previous-level (save-excursion
8496 (condition-case nil
8497 (progn
8498 (outline-previous-visible-heading 1)
8499 (if (looking-at ^re_)
8500 (- (match-end 0) (match-beginning 0) 1)
8502 (error 1))))
8503 (next-level (save-excursion
8504 (condition-case nil
8505 (progn
8506 (or (looking-at org-outline-regexp)
8507 (outline-next-visible-heading 1))
8508 (if (looking-at ^re_)
8509 (- (match-end 0) (match-beginning 0) 1)
8511 (error 1))))
8512 (new-level (or force-level (max previous-level next-level)))
8513 (shift (if (or (= old-level -1)
8514 (= new-level -1)
8515 (= old-level new-level))
8517 (- new-level old-level)))
8518 (delta (if (> shift 0) -1 1))
8519 (func (if (> shift 0) 'org-demote 'org-promote))
8520 (org-odd-levels-only nil)
8521 beg end newend)
8522 ;; Remove the forced level indicator
8523 (when force-level
8524 (delete-region (point-at-bol) (point)))
8525 ;; Paste
8526 (beginning-of-line (if (bolp) 1 2))
8527 (setq beg (point))
8528 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8529 (insert-before-markers txt)
8530 (unless (string-match "\n\\'" txt) (insert "\n"))
8531 (setq newend (point))
8532 (org-reinstall-markers-in-region beg)
8533 (setq end (point))
8534 (goto-char beg)
8535 (skip-chars-forward " \t\n\r")
8536 (setq beg (point))
8537 (when (and (outline-invisible-p) visp)
8538 (save-excursion (outline-show-heading)))
8539 ;; Shift if necessary
8540 (unless (= shift 0)
8541 (save-restriction
8542 (narrow-to-region beg end)
8543 (while (not (= shift 0))
8544 (org-map-region func (point-min) (point-max))
8545 (setq shift (+ delta shift)))
8546 (goto-char (point-min))
8547 (setq newend (point-max))))
8548 (when (or (org-called-interactively-p 'interactive) for-yank)
8549 (message "Clipboard pasted as level %d subtree" new-level))
8550 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8551 kill-ring
8552 (eq org-subtree-clip (current-kill 0))
8553 org-subtree-clip-folded)
8554 ;; The tree was folded before it was killed/copied
8555 (outline-hide-subtree))
8556 (and for-yank (goto-char newend))
8557 (and remove (setq kill-ring (cdr kill-ring))))))
8559 (defun org-kill-is-subtree-p (&optional txt)
8560 "Check if the current kill is an outline subtree, or a set of trees.
8561 Returns nil if kill does not start with a headline, or if the first
8562 headline level is not the largest headline level in the tree.
8563 So this will actually accept several entries of equal levels as well,
8564 which is OK for `org-paste-subtree'.
8565 If optional TXT is given, check this string instead of the current kill."
8566 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8567 (re (org-get-limited-outline-regexp))
8568 (^re (concat "^" re))
8569 (start-level (and kill
8570 (string-match
8571 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8572 kill)
8573 (- (match-end 2) (match-beginning 2) 1)))
8574 (start (1+ (or (match-beginning 2) -1))))
8575 (if (not start-level)
8576 (progn
8577 nil) ;; does not even start with a heading
8578 (catch 'exit
8579 (while (setq start (string-match ^re kill (1+ start)))
8580 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8581 (throw 'exit nil)))
8582 t))))
8584 (defvar org-markers-to-move nil
8585 "Markers that should be moved with a cut-and-paste operation.
8586 Those markers are stored together with their positions relative to
8587 the start of the region.")
8589 (defun org-save-markers-in-region (beg end)
8590 "Check markers in region.
8591 If these markers are between BEG and END, record their position relative
8592 to BEG, so that after moving the block of text, we can put the markers back
8593 into place.
8594 This function gets called just before an entry or tree gets cut from the
8595 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8596 called immediately, to move the markers with the entries."
8597 (setq org-markers-to-move nil)
8598 (when (featurep 'org-clock)
8599 (org-clock-save-markers-for-cut-and-paste beg end))
8600 (when (featurep 'org-agenda)
8601 (org-agenda-save-markers-for-cut-and-paste beg end)))
8603 (defun org-check-and-save-marker (marker beg end)
8604 "Check if MARKER is between BEG and END.
8605 If yes, remember the marker and the distance to BEG."
8606 (when (and (marker-buffer marker)
8607 (equal (marker-buffer marker) (current-buffer))
8608 (>= marker beg) (< marker end))
8609 (push (cons marker (- marker beg)) org-markers-to-move)))
8611 (defun org-reinstall-markers-in-region (beg)
8612 "Move all remembered markers to their position relative to BEG."
8613 (dolist (x org-markers-to-move)
8614 (move-marker (car x) (+ beg (cdr x))))
8615 (setq org-markers-to-move nil))
8617 (defun org-narrow-to-subtree ()
8618 "Narrow buffer to the current subtree."
8619 (interactive)
8620 (save-excursion
8621 (save-match-data
8622 (org-with-limited-levels
8623 (narrow-to-region
8624 (progn (org-back-to-heading t) (point))
8625 (progn (org-end-of-subtree t t)
8626 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8627 (point)))))))
8629 (defun org-narrow-to-block ()
8630 "Narrow buffer to the current block."
8631 (interactive)
8632 (let* ((case-fold-search t)
8633 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8634 "^[ \t]*#\\+end_.*")))
8635 (if blockp
8636 (narrow-to-region (car blockp) (cdr blockp))
8637 (user-error "Not in a block"))))
8639 (defun org-clone-subtree-with-time-shift (n &optional shift)
8640 "Clone the task (subtree) at point N times.
8641 The clones will be inserted as siblings.
8643 In interactive use, the user will be prompted for the number of
8644 clones to be produced. If the entry has a timestamp, the user
8645 will also be prompted for a time shift, which may be a repeater
8646 as used in time stamps, for example `+3d'. To disable this,
8647 you can call the function with a universal prefix argument.
8649 When a valid repeater is given and the entry contains any time
8650 stamps, the clones will become a sequence in time, with time
8651 stamps in the subtree shifted for each clone produced. If SHIFT
8652 is nil or the empty string, time stamps will be left alone. The
8653 ID property of the original subtree is removed.
8655 If the original subtree did contain time stamps with a repeater,
8656 the following will happen:
8657 - the repeater will be removed in each clone
8658 - an additional clone will be produced, with the current, unshifted
8659 date(s) in the entry.
8660 - the original entry will be placed *after* all the clones, with
8661 repeater intact.
8662 - the start days in the repeater in the original entry will be shifted
8663 to past the last clone.
8664 In this way you can spell out a number of instances of a repeating task,
8665 and still retain the repeater to cover future instances of the task.
8667 As described above, N+1 clones are produced when the original
8668 subtree has a repeater. Setting N to 0, then, can be used to
8669 remove the repeater from a subtree and create a shifted clone
8670 with the original repeater."
8671 (interactive "nNumber of clones to produce: ")
8672 (let ((shift
8673 (or shift
8674 (if (and (not (equal current-prefix-arg '(4)))
8675 (save-excursion
8676 (re-search-forward org-ts-regexp-both
8677 (save-excursion
8678 (org-end-of-subtree t)
8679 (point)) t)))
8680 (read-from-minibuffer
8681 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8682 ""))) ;; No time shift
8683 (n-no-remove -1)
8684 (drawer-re org-drawer-regexp)
8685 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8686 beg end template task idprop
8687 shift-n shift-what doshift nmin nmax)
8688 (unless (wholenump n)
8689 (user-error "Invalid number of replications %s" n))
8690 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8691 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8692 shift)))
8693 (user-error "Invalid shift specification %s" shift))
8694 (when doshift
8695 (setq shift-n (string-to-number (match-string 1 shift))
8696 shift-what (cdr (assoc (match-string 2 shift)
8697 '(("d" . day) ("w" . week)
8698 ("m" . month) ("y" . year))))))
8699 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8700 (setq nmin 1 nmax n)
8701 (org-back-to-heading t)
8702 (setq beg (point))
8703 (setq idprop (org-entry-get nil "ID"))
8704 (org-end-of-subtree t t)
8705 (or (bolp) (insert "\n"))
8706 (setq end (point))
8707 (setq template (buffer-substring beg end))
8708 (when (and doshift
8709 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8710 (delete-region beg end)
8711 (setq end beg)
8712 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8713 (goto-char end)
8714 (cl-loop for n from nmin to nmax do
8715 ;; prepare clone
8716 (with-temp-buffer
8717 (insert template)
8718 (org-mode)
8719 (goto-char (point-min))
8720 (org-show-subtree)
8721 (and idprop (if org-clone-delete-id
8722 (org-entry-delete nil "ID")
8723 (org-id-get-create t)))
8724 (unless (= n 0)
8725 (while (re-search-forward org-clock-re nil t)
8726 (kill-whole-line))
8727 (goto-char (point-min))
8728 (while (re-search-forward drawer-re nil t)
8729 (org-remove-empty-drawer-at (point))))
8730 (goto-char (point-min))
8731 (when doshift
8732 (while (re-search-forward org-ts-regexp-both nil t)
8733 (org-timestamp-change (* n shift-n) shift-what))
8734 (unless (= n n-no-remove)
8735 (goto-char (point-min))
8736 (while (re-search-forward org-ts-regexp nil t)
8737 (save-excursion
8738 (goto-char (match-beginning 0))
8739 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8740 (delete-region (match-beginning 1) (match-end 1)))))))
8741 (setq task (buffer-string)))
8742 (insert task))
8743 (goto-char beg)))
8745 ;;; Outline Sorting
8747 (defun org-sort (with-case)
8748 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8749 Optional argument WITH-CASE means sort case-sensitively."
8750 (interactive "P")
8751 (cond
8752 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8753 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8755 (org-call-with-arg 'org-sort-entries with-case))))
8757 (defun org-sort-remove-invisible (s)
8758 "Remove invisible links from string S."
8759 (remove-text-properties 0 (length s) org-rm-props s)
8760 (while (string-match org-bracket-link-regexp s)
8761 (setq s (replace-match (if (match-end 2)
8762 (match-string 3 s)
8763 (match-string 1 s))
8764 t t s)))
8765 (let ((st (format " %s " s)))
8766 (while (string-match org-emph-re st)
8767 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8768 (setq s (substring st 1 -1)))
8771 (defvar org-priority-regexp) ; defined later in the file
8773 (defvar org-after-sorting-entries-or-items-hook nil
8774 "Hook that is run after a bunch of entries or items have been sorted.
8775 When children are sorted, the cursor is in the parent line when this
8776 hook gets called. When a region or a plain list is sorted, the cursor
8777 will be in the first entry of the sorted region/list.")
8779 (defun org-sort-entries
8780 (&optional with-case sorting-type getkey-func compare-func property)
8781 "Sort entries on a certain level of an outline tree.
8782 If there is an active region, the entries in the region are sorted.
8783 Else, if the cursor is before the first entry, sort the top-level items.
8784 Else, the children of the entry at point are sorted.
8786 Sorting can be alphabetically, numerically, by date/time as given by
8787 a time stamp, by a property, by priority order, or by a custom function.
8789 The command prompts for the sorting type unless it has been given to the
8790 function through the SORTING-TYPE argument, which needs to be a character,
8791 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8792 the precise meaning of each character:
8794 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8795 c By creation time, which is assumed to be the first inactive time stamp
8796 at the beginning of a line.
8797 d By deadline date/time.
8798 k By clocking time.
8799 n Numerically, by converting the beginning of the entry/item to a number.
8800 o By order of TODO keywords.
8801 p By priority according to the cookie.
8802 r By the value of a property.
8803 s By scheduled date/time.
8804 t By date/time, either the first active time stamp in the entry, or, if
8805 none exist, by the first inactive one.
8807 Capital letters will reverse the sort order.
8809 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8810 called with point at the beginning of the record. It must return either
8811 a string or a number that should serve as the sorting key for that record.
8813 Comparing entries ignores case by default. However, with an optional argument
8814 WITH-CASE, the sorting considers case as well.
8816 Sorting is done against the visible part of the headlines, it ignores hidden
8817 links.
8819 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8820 (interactive "P")
8821 (let ((case-func (if with-case 'identity 'downcase))
8822 (cmstr
8823 ;; The clock marker is lost when using `sort-subr', let's
8824 ;; store the clocking string.
8825 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8826 (save-excursion
8827 (goto-char org-clock-marker)
8828 (buffer-substring-no-properties (line-beginning-position)
8829 (point)))))
8830 start beg end stars re re2
8831 txt what tmp)
8832 ;; Find beginning and end of region to sort
8833 (cond
8834 ((org-region-active-p)
8835 ;; we will sort the region
8836 (setq end (region-end)
8837 what "region")
8838 (goto-char (region-beginning))
8839 (unless (org-at-heading-p) (outline-next-heading))
8840 (setq start (point)))
8841 ((or (org-at-heading-p)
8842 (ignore-errors (progn (org-back-to-heading) t)))
8843 ;; we will sort the children of the current headline
8844 (org-back-to-heading)
8845 (setq start (point)
8846 end (progn (org-end-of-subtree t t)
8847 (or (bolp) (insert "\n"))
8848 (when (>= (org-back-over-empty-lines) 1)
8849 (forward-line 1))
8850 (point))
8851 what "children")
8852 (goto-char start)
8853 (outline-show-subtree)
8854 (outline-next-heading))
8856 ;; we will sort the top-level entries in this file
8857 (goto-char (point-min))
8858 (or (org-at-heading-p) (outline-next-heading))
8859 (setq start (point))
8860 (goto-char (point-max))
8861 (beginning-of-line 1)
8862 (when (looking-at ".*?\\S-")
8863 ;; File ends in a non-white line
8864 (end-of-line 1)
8865 (insert "\n"))
8866 (setq end (point-max))
8867 (setq what "top-level")
8868 (goto-char start)
8869 (outline-show-all)))
8871 (setq beg (point))
8872 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8874 (looking-at "\\(\\*+\\)")
8875 (setq stars (match-string 1)
8876 re (concat "^" (regexp-quote stars) " +")
8877 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8878 txt (buffer-substring beg end))
8879 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8880 (when (and (not (equal stars "*")) (string-match re2 txt))
8881 (user-error "Region to sort contains a level above the first entry"))
8883 (unless sorting-type
8884 (message
8885 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8886 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8887 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8888 what)
8889 (setq sorting-type (read-char-exclusive))
8891 (unless getkey-func
8892 (and (= (downcase sorting-type) ?f)
8893 (setq getkey-func
8894 (completing-read "Sort using function: "
8895 obarray 'fboundp t nil nil))
8896 (setq getkey-func (intern getkey-func))))
8898 (and (= (downcase sorting-type) ?r)
8899 (not property)
8900 (setq property
8901 (completing-read "Property: "
8902 (mapcar #'list (org-buffer-property-keys t))
8903 nil t))))
8905 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8906 (message "Sorting entries...")
8908 (save-restriction
8909 (narrow-to-region start end)
8910 (let ((dcst (downcase sorting-type))
8911 (case-fold-search nil)
8912 (now (current-time)))
8913 (sort-subr
8914 (/= dcst sorting-type)
8915 ;; This function moves to the beginning character of the "record" to
8916 ;; be sorted.
8917 (lambda nil
8918 (if (re-search-forward re nil t)
8919 (goto-char (match-beginning 0))
8920 (goto-char (point-max))))
8921 ;; This function moves to the last character of the "record" being
8922 ;; sorted.
8923 (lambda nil
8924 (save-match-data
8925 (condition-case nil
8926 (outline-forward-same-level 1)
8927 (error
8928 (goto-char (point-max))))))
8929 ;; This function returns the value that gets sorted against.
8930 (lambda nil
8931 (cond
8932 ((= dcst ?n)
8933 (if (looking-at org-complex-heading-regexp)
8934 (string-to-number (org-sort-remove-invisible (match-string 4)))
8935 nil))
8936 ((= dcst ?a)
8937 (if (looking-at org-complex-heading-regexp)
8938 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8939 nil))
8940 ((= dcst ?k)
8941 (or (get-text-property (point) :org-clock-minutes) 0))
8942 ((= dcst ?t)
8943 (let ((end (save-excursion (outline-next-heading) (point))))
8944 (if (or (re-search-forward org-ts-regexp end t)
8945 (re-search-forward org-ts-regexp-both end t))
8946 (org-time-string-to-seconds (match-string 0))
8947 (org-float-time now))))
8948 ((= dcst ?c)
8949 (let ((end (save-excursion (outline-next-heading) (point))))
8950 (if (re-search-forward
8951 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8952 end t)
8953 (org-time-string-to-seconds (match-string 0))
8954 (org-float-time now))))
8955 ((= dcst ?s)
8956 (let ((end (save-excursion (outline-next-heading) (point))))
8957 (if (re-search-forward org-scheduled-time-regexp end t)
8958 (org-time-string-to-seconds (match-string 1))
8959 (org-float-time now))))
8960 ((= dcst ?d)
8961 (let ((end (save-excursion (outline-next-heading) (point))))
8962 (if (re-search-forward org-deadline-time-regexp end t)
8963 (org-time-string-to-seconds (match-string 1))
8964 (org-float-time now))))
8965 ((= dcst ?p)
8966 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8967 (string-to-char (match-string 2))
8968 org-default-priority))
8969 ((= dcst ?r)
8970 (or (org-entry-get nil property) ""))
8971 ((= dcst ?o)
8972 (when (looking-at org-complex-heading-regexp)
8973 (let* ((m (match-string 2))
8974 (s (if (member m org-done-keywords) '- '+)))
8975 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8976 ((= dcst ?f)
8977 (if getkey-func
8978 (progn
8979 (setq tmp (funcall getkey-func))
8980 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8981 tmp)
8982 (error "Invalid key function `%s'" getkey-func)))
8983 (t (error "Invalid sorting type `%c'" sorting-type))))
8985 (cond
8986 ((= dcst ?a) 'string<)
8987 ((= dcst ?f) compare-func)
8988 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8989 (run-hooks 'org-after-sorting-entries-or-items-hook)
8990 ;; Reset the clock marker if needed
8991 (when cmstr
8992 (save-excursion
8993 (goto-char start)
8994 (search-forward cmstr nil t)
8995 (move-marker org-clock-marker (point))))
8996 (message "Sorting entries...done")))
8998 ;;; The orgstruct minor mode
9000 ;; Define a minor mode which can be used in other modes in order to
9001 ;; integrate the org-mode structure editing commands.
9003 ;; This is really a hack, because the org-mode structure commands use
9004 ;; keys which normally belong to the major mode. Here is how it
9005 ;; works: The minor mode defines all the keys necessary to operate the
9006 ;; structure commands, but wraps the commands into a function which
9007 ;; tests if the cursor is currently at a headline or a plain list
9008 ;; item. If that is the case, the structure command is used,
9009 ;; temporarily setting many Org-mode variables like regular
9010 ;; expressions for filling etc. However, when any of those keys is
9011 ;; used at a different location, function uses `key-binding' to look
9012 ;; up if the key has an associated command in another currently active
9013 ;; keymap (minor modes, major mode, global), and executes that
9014 ;; command. There might be problems if any of the keys is otherwise
9015 ;; used as a prefix key.
9017 (defcustom orgstruct-heading-prefix-regexp ""
9018 "Regexp that matches the custom prefix of Org headlines in
9019 orgstruct(++)-mode."
9020 :group 'org
9021 :version "24.4"
9022 :package-version '(Org . "8.3")
9023 :type 'regexp)
9024 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9026 (defcustom orgstruct-setup-hook nil
9027 "Hook run after orgstruct-mode-map is filled."
9028 :group 'org
9029 :version "24.4"
9030 :package-version '(Org . "8.0")
9031 :type 'hook)
9033 (defvar orgstruct-initialized nil)
9035 (defvar org-local-vars nil
9036 "List of local variables, for use by `orgstruct-mode'.")
9038 ;;;###autoload
9039 (define-minor-mode orgstruct-mode
9040 "Toggle the minor mode `orgstruct-mode'.
9041 This mode is for using Org-mode structure commands in other
9042 modes. The following keys behave as if Org-mode were active, if
9043 the cursor is on a headline, or on a plain list item (both as
9044 defined by Org-mode)."
9045 nil " OrgStruct" (make-sparse-keymap)
9046 (funcall (if orgstruct-mode
9047 'add-to-invisibility-spec
9048 'remove-from-invisibility-spec)
9049 '(outline . t))
9050 (when orgstruct-mode
9051 (org-load-modules-maybe)
9052 (unless orgstruct-initialized
9053 (orgstruct-setup)
9054 (setq orgstruct-initialized t))))
9056 ;;;###autoload
9057 (defun turn-on-orgstruct ()
9058 "Unconditionally turn on `orgstruct-mode'."
9059 (orgstruct-mode 1))
9061 (defvar-local orgstruct-is-++ nil
9062 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9063 (defvar-local org-fb-vars nil)
9064 (defun orgstruct++-mode (&optional arg)
9065 "Toggle `orgstruct-mode', the enhanced version of it.
9066 In addition to setting orgstruct-mode, this also exports all
9067 indentation and autofilling variables from org-mode into the
9068 buffer. It will also recognize item context in multiline items."
9069 (interactive "P")
9070 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9071 (if (< arg 1)
9072 (progn (orgstruct-mode -1)
9073 (dolist (v org-fb-vars)
9074 (set (make-local-variable (car v))
9075 (if (eq (car-safe (cadr v)) 'quote)
9076 (cl-cadadr v)
9077 (nth 1 v)))))
9078 (orgstruct-mode 1)
9079 (setq org-fb-vars nil)
9080 (unless org-local-vars
9081 (setq org-local-vars (org-get-local-variables)))
9082 (let (var val)
9083 (dolist (x org-local-vars)
9084 (when (string-match
9085 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9086 \\|fill-prefix\\|indent-\\)"
9087 (symbol-name (car x)))
9088 (setq var (car x) val (nth 1 x))
9089 (push (list var `(quote ,(eval var))) org-fb-vars)
9090 (set (make-local-variable var)
9091 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9092 (setq-local orgstruct-is-++ t))))
9094 ;;;###autoload
9095 (defun turn-on-orgstruct++ ()
9096 "Unconditionally turn on `orgstruct++-mode'."
9097 (orgstruct++-mode 1))
9099 (defun orgstruct-error ()
9100 "Error when there is no default binding for a structure key."
9101 (interactive)
9102 (funcall (if (fboundp 'user-error)
9103 'user-error
9104 'error)
9105 "This key has no function outside structure elements"))
9107 (defun orgstruct-setup ()
9108 "Setup orgstruct keymap."
9109 (dolist (cell '((org-demote . t)
9110 (org-metaleft . t)
9111 (org-metaright . t)
9112 (org-promote . t)
9113 (org-shiftmetaleft . t)
9114 (org-shiftmetaright . t)
9115 org-backward-element
9116 org-backward-heading-same-level
9117 org-ctrl-c-ret
9118 org-ctrl-c-minus
9119 org-ctrl-c-star
9120 org-cycle
9121 org-force-cycle-archived
9122 org-forward-heading-same-level
9123 org-insert-heading
9124 org-insert-heading-respect-content
9125 org-kill-note-or-show-branches
9126 org-mark-subtree
9127 org-meta-return
9128 org-metadown
9129 org-metaup
9130 org-narrow-to-subtree
9131 org-promote-subtree
9132 org-reveal
9133 org-shiftdown
9134 org-shiftleft
9135 org-shiftmetadown
9136 org-shiftmetaup
9137 org-shiftright
9138 org-shifttab
9139 org-shifttab
9140 org-shiftup
9141 org-show-children
9142 org-show-subtree
9143 org-sort
9144 org-up-element
9145 outline-demote
9146 outline-next-visible-heading
9147 outline-previous-visible-heading
9148 outline-promote
9149 outline-up-heading))
9150 (let ((f (or (car-safe cell) cell))
9151 (disable-when-heading-prefix (cdr-safe cell)))
9152 (when (fboundp f)
9153 (let ((new-bindings))
9154 (dolist (binding (nconc (where-is-internal f org-mode-map)
9155 (where-is-internal f outline-mode-map)))
9156 (push binding new-bindings)
9157 ;; TODO use local-function-key-map
9158 (dolist (rep '(("<tab>" . "TAB")
9159 ("<return>" . "RET")
9160 ("<escape>" . "ESC")
9161 ("<delete>" . "DEL")))
9162 (setq binding (read-kbd-macro
9163 (let ((case-fold-search))
9164 (replace-regexp-in-string
9165 (regexp-quote (cdr rep))
9166 (car rep)
9167 (key-description binding)))))
9168 (cl-pushnew binding new-bindings :test 'equal)))
9169 (dolist (binding new-bindings)
9170 (let ((key (lookup-key orgstruct-mode-map binding)))
9171 (when (or (not key) (numberp key))
9172 (ignore-errors
9173 (org-defkey orgstruct-mode-map
9174 binding
9175 (orgstruct-make-binding
9176 f binding disable-when-heading-prefix))))))))))
9177 (run-hooks 'orgstruct-setup-hook))
9179 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9180 "Create a function for binding in the structure minor mode.
9181 FUN is the command to call inside a table. KEY is the key that
9182 should be checked in for a command to execute outside of tables.
9183 Non-nil `disable-when-heading-prefix' means to disable the command
9184 if `orgstruct-heading-prefix-regexp' is not empty."
9185 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9186 (let ((nname name)
9187 (i 0))
9188 (while (fboundp (intern nname))
9189 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9190 (setq name (intern nname)))
9191 (eval
9192 (let ((bindings '((org-heading-regexp
9193 (concat "^"
9194 orgstruct-heading-prefix-regexp
9195 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9196 (org-outline-regexp
9197 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9198 (org-outline-regexp-bol
9199 (concat "^" org-outline-regexp))
9200 (outline-regexp org-outline-regexp)
9201 (outline-heading-end-regexp "\n")
9202 (outline-level 'org-outline-level)
9203 (outline-heading-alist))))
9204 `(defun ,name (arg)
9205 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9206 "Outside of structure, run the binding of `"
9207 (key-description key) "'."
9208 (when disable-when-heading-prefix
9209 (concat
9210 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9211 "back to the default binding due to limitations of Org's implementation of\n"
9212 "`" (symbol-name fun) "'.")))
9213 (interactive "p")
9214 (let* ((disable
9215 ,(and disable-when-heading-prefix
9216 '(not (string= orgstruct-heading-prefix-regexp ""))))
9217 (fallback
9218 (or disable
9219 (not
9220 (let* ,bindings
9221 (org-context-p 'headline 'item
9222 ,(when (memq fun
9223 '(org-insert-heading
9224 org-insert-heading-respect-content
9225 org-meta-return))
9226 '(when orgstruct-is-++
9227 'item-body))))))))
9228 (if fallback
9229 (let* ((orgstruct-mode)
9230 (binding
9231 (let ((key ,key))
9232 (catch 'exit
9233 (dolist
9234 (rep
9235 '(nil
9236 ("<\\([^>]*\\)tab>" . "\\1TAB")
9237 ("<\\([^>]*\\)return>" . "\\1RET")
9238 ("<\\([^>]*\\)escape>" . "\\1ESC")
9239 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9240 nil)
9241 (when rep
9242 (setq key (read-kbd-macro
9243 (let ((case-fold-search))
9244 (replace-regexp-in-string
9245 (car rep)
9246 (cdr rep)
9247 (key-description key))))))
9248 (when (key-binding key)
9249 (throw 'exit (key-binding key))))))))
9250 (if (keymapp binding)
9251 (org-set-transient-map binding)
9252 (let ((func (or binding
9253 (unless disable
9254 'orgstruct-error))))
9255 (when func
9256 (call-interactively func)))))
9257 (org-run-like-in-org-mode
9258 (lambda ()
9259 (interactive)
9260 (let* ,bindings
9261 (call-interactively ',fun)))))))))
9262 name))
9264 (defun org-contextualize-keys (alist contexts)
9265 "Return valid elements in ALIST depending on CONTEXTS.
9267 `org-agenda-custom-commands' or `org-capture-templates' are the
9268 values used for ALIST, and `org-agenda-custom-commands-contexts'
9269 or `org-capture-templates-contexts' are the associated contexts
9270 definitions."
9271 (let ((contexts
9272 ;; normalize contexts
9273 (mapcar
9274 (lambda(c) (cond ((listp (cadr c))
9275 (list (car c) (car c) (nth 1 c)))
9276 ((string= "" (cadr c))
9277 (list (car c) (car c) (nth 2 c)))
9278 (t c)))
9279 contexts))
9280 (a alist) r s)
9281 ;; loop over all commands or templates
9282 (dolist (c a)
9283 (let (vrules repl)
9284 (cond
9285 ((not (assoc (car c) contexts))
9286 (push c r))
9287 ((and (assoc (car c) contexts)
9288 (setq vrules (org-contextualize-validate-key
9289 (car c) contexts)))
9290 (mapc (lambda (vr)
9291 (unless (equal (car vr) (cadr vr))
9292 (setq repl vr)))
9293 vrules)
9294 (if (not repl) (push c r)
9295 (push (cadr repl) s)
9296 (push
9297 (cons (car c)
9298 (cdr (or (assoc (cadr repl) alist)
9299 (error "Undefined key `%s' as contextual replacement for `%s'"
9300 (cadr repl) (car c)))))
9301 r))))))
9302 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9303 (delq
9305 (delete-dups
9306 (mapcar (lambda (x)
9307 (let ((tpl (car x)))
9308 (unless (delq
9310 (mapcar (lambda (y)
9311 (equal y tpl))
9313 x)))
9314 (reverse r))))))
9316 (defun org-contextualize-validate-key (key contexts)
9317 "Check CONTEXTS for agenda or capture KEY."
9318 (let (res)
9319 (dolist (r contexts)
9320 (dolist (rr (car (last r)))
9321 (when
9322 (and (equal key (car r))
9323 (if (functionp rr) (funcall rr)
9324 (or (and (eq (car rr) 'in-file)
9325 (buffer-file-name)
9326 (string-match (cdr rr) (buffer-file-name)))
9327 (and (eq (car rr) 'in-mode)
9328 (string-match (cdr rr) (symbol-name major-mode)))
9329 (and (eq (car rr) 'in-buffer)
9330 (string-match (cdr rr) (buffer-name)))
9331 (when (and (eq (car rr) 'not-in-file)
9332 (buffer-file-name))
9333 (not (string-match (cdr rr) (buffer-file-name))))
9334 (when (eq (car rr) 'not-in-mode)
9335 (not (string-match (cdr rr) (symbol-name major-mode))))
9336 (when (eq (car rr) 'not-in-buffer)
9337 (not (string-match (cdr rr) (buffer-name)))))))
9338 (push r res))))
9339 (delete-dups (delq nil res))))
9341 (defun org-context-p (&rest contexts)
9342 "Check if local context is any of CONTEXTS.
9343 Possible values in the list of contexts are `table', `headline', and `item'."
9344 (let ((pos (point)))
9345 (goto-char (point-at-bol))
9346 (prog1 (or (and (memq 'table contexts)
9347 (looking-at "[ \t]*|"))
9348 (and (memq 'headline contexts)
9349 (looking-at org-outline-regexp))
9350 (and (memq 'item contexts)
9351 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9352 (and (memq 'item-body contexts)
9353 (org-in-item-p)))
9354 (goto-char pos))))
9356 (defconst org-unique-local-variables
9357 '(org-element--cache
9358 org-element--cache-objects
9359 org-element--cache-sync-keys
9360 org-element--cache-sync-requests
9361 org-element--cache-sync-timer)
9362 "List of local variables that cannot be transferred to another buffer.")
9364 (defun org-get-local-variables ()
9365 "Return a list of all local variables in an Org mode buffer."
9366 (delq nil
9367 (mapcar
9368 (lambda (x)
9369 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9370 (name (car binding)))
9371 (and (not (get name 'org-state))
9372 (not (memq name org-unique-local-variables))
9373 (string-match-p
9374 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9375 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9376 (symbol-name name))
9377 binding)))
9378 (with-temp-buffer
9379 (org-mode)
9380 (buffer-local-variables)))))
9382 (defun org-clone-local-variables (from-buffer &optional regexp)
9383 "Clone local variables from FROM-BUFFER.
9384 Optional argument REGEXP selects variables to clone."
9385 (dolist (pair (buffer-local-variables from-buffer))
9386 (let ((name (car pair)))
9387 (when (and (symbolp name)
9388 (not (memq name org-unique-local-variables))
9389 (or (null regexp) (string-match regexp (symbol-name name))))
9390 (set (make-local-variable name) (cdr pair))))))
9392 ;;;###autoload
9393 (defun org-run-like-in-org-mode (cmd)
9394 "Run a command, pretending that the current buffer is in Org-mode.
9395 This will temporarily bind local variables that are typically bound in
9396 Org-mode to the values they have in Org-mode, and then interactively
9397 call CMD."
9398 (org-load-modules-maybe)
9399 (unless org-local-vars
9400 (setq org-local-vars (org-get-local-variables)))
9401 (let (binds)
9402 (dolist (var org-local-vars)
9403 (when (or (not (boundp (car var)))
9404 (eq (symbol-value (car var))
9405 (default-value (car var))))
9406 (push (list (car var) `(quote ,(cadr var))) binds)))
9407 (eval `(let ,binds
9408 (call-interactively (quote ,cmd))))))
9410 (defun org-get-category (&optional pos force-refresh)
9411 "Get the category applying to position POS."
9412 (save-match-data
9413 (when force-refresh (org-refresh-category-properties))
9414 (let ((pos (or pos (point))))
9415 (or (get-text-property pos 'org-category)
9416 (progn (org-refresh-category-properties)
9417 (get-text-property pos 'org-category))))))
9419 ;;; Refresh properties
9421 (defun org-refresh-properties (dprop tprop)
9422 "Refresh buffer text properties.
9423 DPROP is the drawer property and TPROP is either the
9424 corresponding text property to set, or an alist with each element
9425 being a text property (as a symbol) and a function to apply to
9426 the value of the drawer property."
9427 (let ((case-fold-search t)
9428 (inhibit-read-only t))
9429 (org-with-silent-modifications
9430 (save-excursion
9431 (save-restriction
9432 (widen)
9433 (goto-char (point-min))
9434 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9435 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9437 (defun org-refresh-property (tprop p)
9438 "Refresh the buffer text property TPROP from the drawer property P.
9439 The refresh happens only for the current tree (not subtree)."
9440 (unless (org-before-first-heading-p)
9441 (save-excursion
9442 (org-back-to-heading t)
9443 (if (symbolp tprop)
9444 ;; TPROP is a text property symbol
9445 (put-text-property
9446 (point) (or (outline-next-heading) (point-max)) tprop p)
9447 ;; TPROP is an alist with (properties . function) elements
9448 (dolist (al tprop)
9449 (save-excursion
9450 (put-text-property
9451 (line-beginning-position) (or (outline-next-heading) (point-max))
9452 (car al)
9453 (funcall (cdr al) p))))))))
9455 (defun org-refresh-category-properties ()
9456 "Refresh category text properties in the buffer."
9457 (let ((case-fold-search t)
9458 (inhibit-read-only t)
9459 (default-category
9460 (cond ((null org-category)
9461 (if buffer-file-name
9462 (file-name-sans-extension
9463 (file-name-nondirectory buffer-file-name))
9464 "???"))
9465 ((symbolp org-category) (symbol-name org-category))
9466 (t org-category))))
9467 (org-with-silent-modifications
9468 (org-with-wide-buffer
9469 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9470 ;; This is the default category for the buffer. If none is
9471 ;; found, fall-back to `org-category' or buffer file name.
9472 (put-text-property
9473 (point-min) (point-max)
9474 'org-category
9475 (catch 'buffer-category
9476 (goto-char (point-max))
9477 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9478 (let ((element (org-element-at-point)))
9479 (when (eq (org-element-type element) 'keyword)
9480 (throw 'buffer-category
9481 (org-element-property :value element)))))
9482 default-category))
9483 ;; Set sub-tree specific categories.
9484 (goto-char (point-min))
9485 (let ((regexp (org-re-property "CATEGORY")))
9486 (while (re-search-forward regexp nil t)
9487 (let ((value (org-match-string-no-properties 3)))
9488 (when (org-at-property-p)
9489 (put-text-property
9490 (save-excursion (org-back-to-heading t) (point))
9491 (save-excursion (org-end-of-subtree t t) (point))
9492 'org-category
9493 value)))))))))
9495 (defun org-refresh-stats-properties ()
9496 "Refresh stats text properties in the buffer."
9497 (let (stats)
9498 (org-with-silent-modifications
9499 (save-excursion
9500 (save-restriction
9501 (widen)
9502 (goto-char (point-min))
9503 (while (re-search-forward
9504 (concat org-outline-regexp-bol ".*"
9505 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9506 nil t)
9507 (setq stats (cond ((equal (match-string 3) "0") 0)
9508 ((match-string 2)
9509 (/ (* (string-to-number (match-string 2)) 100)
9510 (string-to-number (match-string 3))))
9511 (t (string-to-number (match-string 1)))))
9512 (org-back-to-heading t)
9513 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9514 'org-stats stats)))))))
9516 (defun org-refresh-effort-properties ()
9517 "Refresh effort properties"
9518 (org-refresh-properties
9519 org-effort-property
9520 '((effort . identity)
9521 (effort-minutes . org-duration-string-to-minutes))))
9523 ;;;; Link Stuff
9525 ;;; Link abbreviations
9527 (defun org-link-expand-abbrev (link)
9528 "Apply replacements as defined in `org-link-abbrev-alist'."
9529 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9530 (let* ((key (match-string 1 link))
9531 (as (or (assoc key org-link-abbrev-alist-local)
9532 (assoc key org-link-abbrev-alist)))
9533 (tag (and (match-end 2) (match-string 3 link)))
9534 rpl)
9535 (if (not as)
9536 link
9537 (setq rpl (cdr as))
9538 (cond
9539 ((symbolp rpl) (funcall rpl tag))
9540 ((string-match "%(\\([^)]+\\))" rpl)
9541 (replace-match
9542 (save-match-data
9543 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9544 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9545 ((string-match "%h" rpl)
9546 (replace-match (url-hexify-string (or tag "")) t t rpl))
9547 (t (concat rpl tag)))))
9548 link))
9550 ;;; Storing and inserting links
9552 (defvar org-insert-link-history nil
9553 "Minibuffer history for links inserted with `org-insert-link'.")
9555 (defvar org-stored-links nil
9556 "Contains the links stored with `org-store-link'.")
9558 (defvar org-store-link-plist nil
9559 "Plist with info about the most recently link created with `org-store-link'.")
9561 (defvar org-link-protocols nil
9562 "Link protocols added to Org-mode using `org-add-link-type'.")
9564 (defvar org-store-link-functions nil
9565 "List of functions that are called to create and store a link.
9566 Each function will be called in turn until one returns a non-nil
9567 value. Each function should check if it is responsible for creating
9568 this link (for example by looking at the major mode).
9569 If not, it must exit and return nil.
9570 If yes, it should return a non-nil value after a calling
9571 `org-store-link-props' with a list of properties and values.
9572 Special properties are:
9574 :type The link prefix, like \"http\". This must be given.
9575 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9576 This is obligatory as well.
9577 :description Optional default description for the second pair
9578 of brackets in an Org-mode link. The user can still change
9579 this when inserting this link into an Org-mode buffer.
9581 In addition to these, any additional properties can be specified
9582 and then used in capture templates.")
9584 (defun org-add-link-type (type &optional follow export)
9585 "Add TYPE to the list of `org-link-types'.
9586 Re-compute all regular expressions depending on `org-link-types'
9588 FOLLOW and EXPORT are two functions.
9590 FOLLOW should take the link path as the single argument and do whatever
9591 is necessary to follow the link, for example find a file or display
9592 a mail message.
9594 EXPORT should format the link path for export to one of the export formats.
9595 It should be a function accepting three arguments:
9597 path the path of the link, the text after the prefix (like \"http:\")
9598 desc the description of the link, if any
9599 format the export format, a symbol like `html' or `latex' or `ascii'.
9601 The function may use the FORMAT information to return different values
9602 depending on the format. The return value will be put literally into
9603 the exported file. If the return value is nil, this means Org should
9604 do what it normally does with links which do not have EXPORT defined.
9606 Org mode has a built-in default for exporting links. If you are happy with
9607 this default, there is no need to define an export function for the link
9608 type. For a simple example of an export function, see `org-bbdb.el'."
9609 (add-to-list 'org-link-types type t)
9610 (org-make-link-regexps)
9611 (org-element-update-syntax)
9612 (if (assoc type org-link-protocols)
9613 (setcdr (assoc type org-link-protocols) (list follow export))
9614 (push (list type follow export) org-link-protocols)))
9616 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9617 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9619 ;;;###autoload
9620 (defun org-store-link (arg)
9621 "\\<org-mode-map>Store an org-link to the current location.
9622 This link is added to `org-stored-links' and can later be inserted
9623 into an Org buffer with \\[org-insert-link].
9625 For some link types, a prefix ARG is interpreted.
9626 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9627 For file links, ARG negates `org-context-in-file-links'.
9629 A double prefix ARG force skipping storing functions that are not
9630 part of Org's core.
9632 A triple prefix ARG force storing a link for each line in the
9633 active region."
9634 (interactive "P")
9635 (org-load-modules-maybe)
9636 (if (and (equal arg '(64)) (org-region-active-p))
9637 (save-excursion
9638 (let ((end (region-end)))
9639 (goto-char (region-beginning))
9640 (set-mark (point))
9641 (while (< (point-at-eol) end)
9642 (move-end-of-line 1) (activate-mark)
9643 (let (current-prefix-arg)
9644 (call-interactively 'org-store-link))
9645 (move-beginning-of-line 2)
9646 (set-mark (point)))))
9647 (org-with-limited-levels
9648 (setq org-store-link-plist nil)
9649 (let (link cpltxt desc description search
9650 txt custom-id agenda-link sfuns sfunsn)
9651 (cond
9653 ;; Store a link using an external link type
9654 ((and (not (equal arg '(16)))
9655 (setq sfuns
9656 (delq
9657 nil (mapcar (lambda (f)
9658 (let (fs) (if (funcall f) (push f fs))))
9659 org-store-link-functions))
9660 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9661 (or (and (cdr sfuns)
9662 (funcall (intern
9663 (completing-read
9664 "Which function for creating the link? "
9665 sfunsn nil t (car sfunsn)))))
9666 (funcall (caar sfuns)))
9667 (setq link (plist-get org-store-link-plist :link)
9668 desc (or (plist-get org-store-link-plist
9669 :description)
9670 link))))
9672 ;; Store a link from a source code buffer.
9673 ((org-src-edit-buffer-p)
9674 (cond
9675 ((save-excursion
9676 (beginning-of-line)
9677 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9678 "[ \t]*$")))
9679 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9680 ((org-called-interactively-p 'any)
9681 (let (label)
9682 (while (or (not label)
9683 (org-with-wide-buffer
9684 (goto-char (point-min))
9685 (re-search-forward
9686 (regexp-quote (format org-coderef-label-format label))
9687 nil t)))
9688 (when label (message "Label exists already") (sit-for 2))
9689 (setq label (read-string "Code line label: " label)))
9690 (end-of-line)
9691 (setq link (format org-coderef-label-format label))
9692 (let ((gc (- 79 (length link))))
9693 (if (< (current-column) gc) (org-move-to-column gc t)
9694 (insert " ")))
9695 (insert link)
9696 (setq link (concat "(" label ")") desc nil)))
9697 (t (setq link nil))))
9699 ;; We are in the agenda, link to referenced location
9700 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9701 (let ((m (or (get-text-property (point) 'org-hd-marker)
9702 (get-text-property (point) 'org-marker))))
9703 (when m
9704 (org-with-point-at m
9705 (setq agenda-link
9706 (if (org-called-interactively-p 'any)
9707 (call-interactively 'org-store-link)
9708 (org-store-link nil)))))))
9710 ((eq major-mode 'calendar-mode)
9711 (let ((cd (calendar-cursor-to-date)))
9712 (setq link
9713 (format-time-string
9714 (car org-time-stamp-formats)
9715 (apply 'encode-time
9716 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9717 nil nil nil))))
9718 (org-store-link-props :type "calendar" :date cd)))
9720 ((eq major-mode 'help-mode)
9721 (setq link (concat "help:" (save-excursion
9722 (goto-char (point-min))
9723 (looking-at "^[^ ]+")
9724 (match-string 0))))
9725 (org-store-link-props :type "help"))
9727 ((eq major-mode 'w3-mode)
9728 (setq cpltxt (if (and (buffer-name)
9729 (not (string-match "Untitled" (buffer-name))))
9730 (buffer-name)
9731 (url-view-url t))
9732 link (url-view-url t))
9733 (org-store-link-props :type "w3" :url (url-view-url t)))
9735 ((eq major-mode 'image-mode)
9736 (setq cpltxt (concat "file:"
9737 (abbreviate-file-name buffer-file-name))
9738 link cpltxt)
9739 (org-store-link-props :type "image" :file buffer-file-name))
9741 ;; In dired, store a link to the file of the current line
9742 ((derived-mode-p 'dired-mode)
9743 (let ((file (dired-get-filename nil t)))
9744 (setq file (if file
9745 (abbreviate-file-name
9746 (expand-file-name (dired-get-filename nil t)))
9747 ;; otherwise, no file so use current directory.
9748 default-directory))
9749 (setq cpltxt (concat "file:" file)
9750 link cpltxt)))
9752 ((setq search (run-hook-with-args-until-success
9753 'org-create-file-search-functions))
9754 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9755 "::" search))
9756 (setq cpltxt (or description link)))
9758 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9759 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9760 (cond
9761 ;; Store a link using the target at point
9762 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9763 (setq cpltxt
9764 (concat "file:"
9765 (abbreviate-file-name
9766 (buffer-file-name (buffer-base-buffer)))
9767 "::" (match-string 1))
9768 link cpltxt))
9769 ((and (featurep 'org-id)
9770 (or (eq org-id-link-to-org-use-id t)
9771 (and (org-called-interactively-p 'any)
9772 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9773 (and (eq org-id-link-to-org-use-id
9774 'create-if-interactive-and-no-custom-id)
9775 (not custom-id))))
9776 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9777 ;; Store a link using the ID at point
9778 (setq link (condition-case nil
9779 (prog1 (org-id-store-link)
9780 (setq desc (or (plist-get org-store-link-plist
9781 :description)
9782 "")))
9783 (error
9784 ;; Probably before first headline, link only to file
9785 (concat "file:"
9786 (abbreviate-file-name
9787 (buffer-file-name (buffer-base-buffer))))))))
9789 ;; Just link to current headline
9790 (setq cpltxt (concat "file:"
9791 (abbreviate-file-name
9792 (buffer-file-name (buffer-base-buffer)))))
9793 ;; Add a context search string
9794 (when (org-xor org-context-in-file-links arg)
9795 (let* ((ee (org-element-at-point))
9796 (et (org-element-type ee))
9797 (ev (plist-get (cadr ee) :value))
9798 (ek (plist-get (cadr ee) :key))
9799 (eok (and (stringp ek) (string-match "name" ek))))
9800 (setq txt (cond
9801 ((org-at-heading-p) nil)
9802 ((and (eq et 'keyword) eok) ev)
9803 ((org-region-active-p)
9804 (buffer-substring (region-beginning) (region-end)))))
9805 (when (or (null txt) (string-match "\\S-" txt))
9806 (setq cpltxt
9807 (concat cpltxt "::"
9808 (condition-case nil
9809 (org-make-org-heading-search-string txt)
9810 (error "")))
9811 desc (or (and (eq et 'keyword) eok ev)
9812 (nth 4 (ignore-errors (org-heading-components)))
9813 "NONE")))))
9814 (when (string-match "::\\'" cpltxt)
9815 (setq cpltxt (substring cpltxt 0 -2)))
9816 (setq link cpltxt))))
9818 ((buffer-file-name (buffer-base-buffer))
9819 ;; Just link to this file here.
9820 (setq cpltxt (concat "file:"
9821 (abbreviate-file-name
9822 (buffer-file-name (buffer-base-buffer)))))
9823 ;; Add a context string.
9824 (when (org-xor org-context-in-file-links arg)
9825 (setq txt (if (org-region-active-p)
9826 (buffer-substring (region-beginning) (region-end))
9827 (buffer-substring (point-at-bol) (point-at-eol))))
9828 ;; Only use search option if there is some text.
9829 (when (string-match "\\S-" txt)
9830 (setq cpltxt
9831 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9832 desc "NONE")))
9833 (setq link cpltxt))
9835 ((org-called-interactively-p 'interactive)
9836 (user-error "No method for storing a link from this buffer"))
9838 (t (setq link nil)))
9840 ;; We're done setting link and desc, clean up
9841 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9842 (setq link (or link cpltxt)
9843 desc (or desc cpltxt))
9844 (cond ((equal desc "NONE") (setq desc nil))
9845 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9846 (let ((d0 (match-string 3 desc))
9847 (p0 (match-string 5 desc)))
9848 (setq desc
9849 (replace-regexp-in-string
9850 org-bracket-link-regexp
9851 (concat (or p0 d0)
9852 (if (equal (length (match-string 0 desc))
9853 (length desc)) "*" "")) desc)))))
9855 ;; Return the link
9856 (if (not (and (or (org-called-interactively-p 'any)
9857 executing-kbd-macro)
9858 link))
9859 (or agenda-link (and link (org-make-link-string link desc)))
9860 (push (list link desc) org-stored-links)
9861 (message "Stored: %s" (or desc link))
9862 (when custom-id
9863 (setq link (concat "file:" (abbreviate-file-name
9864 (buffer-file-name)) "::#" custom-id))
9865 (push (list link desc) org-stored-links))
9866 (car org-stored-links))))))
9868 (defun org-store-link-props (&rest plist)
9869 "Store link properties, extract names, addresses and dates."
9870 (let ((x (plist-get plist :from)))
9871 (when x
9872 (let ((adr (mail-extract-address-components x)))
9873 (setq plist (plist-put plist :fromname (car adr)))
9874 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9875 (let ((x (plist-get plist :to)))
9876 (when x
9877 (let ((adr (mail-extract-address-components x)))
9878 (setq plist (plist-put plist :toname (car adr)))
9879 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9880 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9881 (when x
9882 (setq plist (plist-put plist :date-timestamp
9883 (format-time-string
9884 (org-time-stamp-format t) x)))
9885 (setq plist (plist-put plist :date-timestamp-inactive
9886 (format-time-string
9887 (org-time-stamp-format t t) x)))))
9888 (let ((from (plist-get plist :from))
9889 (to (plist-get plist :to)))
9890 (when (and from to org-from-is-user-regexp)
9891 (setq plist
9892 (plist-put plist :fromto
9893 (if (string-match org-from-is-user-regexp from)
9894 (concat "to %t")
9895 (concat "from %f"))))))
9896 (setq org-store-link-plist plist))
9898 (defun org-add-link-props (&rest plist)
9899 "Add these properties to the link property list."
9900 (let (key value)
9901 (while plist
9902 (setq key (pop plist) value (pop plist))
9903 (setq org-store-link-plist
9904 (plist-put org-store-link-plist key value)))))
9906 (defun org-email-link-description (&optional fmt)
9907 "Return the description part of an email link.
9908 This takes information from `org-store-link-plist' and formats it
9909 according to FMT (default from `org-email-link-description-format')."
9910 (setq fmt (or fmt org-email-link-description-format))
9911 (let* ((p org-store-link-plist)
9912 (to (plist-get p :toaddress))
9913 (from (plist-get p :fromaddress))
9914 (table
9915 (list
9916 (cons "%c" (plist-get p :fromto))
9917 (cons "%F" (plist-get p :from))
9918 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9919 (cons "%T" (plist-get p :to))
9920 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9921 (cons "%s" (plist-get p :subject))
9922 (cons "%d" (plist-get p :date))
9923 (cons "%m" (plist-get p :message-id)))))
9924 (when (string-match "%c" fmt)
9925 ;; Check if the user wrote this message
9926 (if (and org-from-is-user-regexp from to
9927 (save-match-data (string-match org-from-is-user-regexp from)))
9928 (setq fmt (replace-match "to %t" t t fmt))
9929 (setq fmt (replace-match "from %f" t t fmt))))
9930 (org-replace-escapes fmt table)))
9932 (defun org-make-org-heading-search-string (&optional string)
9933 "Make search string for the current headline or STRING."
9934 (let ((s (or string
9935 (and (derived-mode-p 'org-mode)
9936 (save-excursion
9937 (org-back-to-heading t)
9938 (org-element-property :raw-value (org-element-at-point))))))
9939 (lines org-context-in-file-links))
9940 (or string (setq s (concat "*" s))) ; Add * for headlines
9941 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9942 (when (and string (integerp lines) (> lines 0))
9943 (let ((slines (org-split-string s "\n")))
9944 (when (< lines (length slines))
9945 (setq s (mapconcat
9946 'identity
9947 (reverse (nthcdr (- (length slines) lines)
9948 (reverse slines))) "\n")))))
9949 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9951 (defun org-make-link-string (link &optional description)
9952 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9953 (unless (org-string-nw-p link) (error "Empty link"))
9954 (let ((uri (cond ((string-match org-link-types-re link)
9955 (concat (match-string 1 link)
9956 (org-link-escape (substring link (match-end 1)))))
9957 ;; For readability, url-encode internal links only
9958 ;; when absolutely needed (i.e, when they contain
9959 ;; square brackets). File links however, are
9960 ;; encoded since, e.g., spaces are significant.
9961 ((or (file-name-absolute-p link)
9962 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
9963 (org-link-escape link))
9964 (t link)))
9965 (description
9966 (and (org-string-nw-p description)
9967 ;; Remove brackets from description, as they are fatal.
9968 (replace-regexp-in-string
9969 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9970 (org-trim description)))))
9971 (format "[[%s]%s]"
9973 (if description (format "[%s]" description) ""))))
9975 (defconst org-link-escape-chars
9976 ;;%20 %5B %5D %25
9977 '(?\s ?\[ ?\] ?%)
9978 "List of characters that should be escaped in a link when stored to Org.
9979 This is the list that is used for internal purposes.")
9981 (defconst org-link-escape-chars-browser
9982 ;;%20 %22
9983 '(?\s ?\")
9984 "List of characters to be escaped before handing over to the browser.
9985 If you consider using this constant then you probably want to use
9986 the function `org-link-escape-browser' instead. See there why
9987 this constant is a candidate to be removed once Org drops support
9988 for Emacs 24.1 and 24.2.")
9990 (defun org-link-escape (text &optional table merge)
9991 "Return percent escaped representation of TEXT.
9992 TEXT is a string with the text to escape.
9993 Optional argument TABLE is a list with characters that should be
9994 escaped. When nil, `org-link-escape-chars' is used.
9995 If optional argument MERGE is set, merge TABLE into
9996 `org-link-escape-chars'."
9997 (let ((characters-to-encode
9998 (cond ((null table) org-link-escape-chars)
9999 (merge (append org-link-escape-chars table))
10000 (t table))))
10001 (mapconcat
10002 (lambda (c)
10003 (if (or (memq c characters-to-encode)
10004 (and org-url-hexify-p (or (< c 32) (> c 126))))
10005 (mapconcat (lambda (e) (format "%%%.2X" e))
10006 (or (encode-coding-char c 'utf-8)
10007 (error "Unable to percent escape character: %c" c))
10009 (char-to-string c)))
10010 text "")))
10012 (defun org-link-escape-browser (text)
10013 "Escape some characters before handing over to the browser.
10014 This function is a candidate to be removed together with the
10015 constant `org-link-escape-chars-browser' once Org drops support
10016 for Emacs 24.1 and 24.2. All calls to this function will have to
10017 be replaced with `url-encode-url' which is available since Emacs
10018 24.3.1."
10019 ;; Example with the Org link
10020 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10021 ;; to open the browser with +subject:"Release 8.2" filled into the
10022 ;; query field: In this case the variable TEXT contains the
10023 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10024 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10025 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10026 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10027 (if (fboundp 'url-encode-url)
10028 (url-encode-url text)
10029 (if (org-string-match-p
10030 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10031 text)
10032 (org-link-escape text org-link-escape-chars-browser)
10033 text)))
10035 (defun org-link-unescape (str)
10036 "Unhex hexified Unicode parts in string STR.
10037 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10038 reciprocal of `org-link-escape', which see."
10039 (if (org-string-nw-p str)
10040 (replace-regexp-in-string
10041 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10042 str))
10044 (defun org-link-unescape-compound (hex)
10045 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10046 Note: this function also decodes single byte encodings like
10047 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10048 (save-match-data
10049 (let* ((bytes (cdr (split-string hex "%")))
10050 (ret "")
10051 (eat 0)
10052 (sum 0))
10053 (while bytes
10054 (let* ((val (string-to-number (pop bytes) 16))
10055 (shift-xor
10056 (if (= 0 eat)
10057 (cond
10058 ((>= val 252) (cons 6 252))
10059 ((>= val 248) (cons 5 248))
10060 ((>= val 240) (cons 4 240))
10061 ((>= val 224) (cons 3 224))
10062 ((>= val 192) (cons 2 192))
10063 (t (cons 0 0)))
10064 (cons 6 128))))
10065 (when (>= val 192) (setq eat (car shift-xor)))
10066 (setq val (logxor val (cdr shift-xor)))
10067 (setq sum (+ (lsh sum (car shift-xor)) val))
10068 (when (> eat 0) (setq eat (- eat 1)))
10069 (cond
10070 ((= 0 eat) ;multi byte
10071 (setq ret (concat ret (org-char-to-string sum)))
10072 (setq sum 0))
10073 ((not bytes) ; single byte(s)
10074 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10075 ret)))
10077 (defun org-link-unescape-single-byte-sequence (hex)
10078 "Unhexify hex-encoded single byte character sequences."
10079 (mapconcat (lambda (byte)
10080 (char-to-string (string-to-number byte 16)))
10081 (cdr (split-string hex "%")) ""))
10083 (defun org-xor (a b)
10084 "Exclusive or."
10085 (if a (not b) b))
10087 (defun org-fixup-message-id-for-http (s)
10088 "Replace special characters in a message id, so it can be used in an http query."
10089 (when (string-match "%" s)
10090 (setq s (mapconcat (lambda (c)
10091 (if (eq c ?%)
10092 "%25"
10093 (char-to-string c)))
10094 s "")))
10095 (while (string-match "<" s)
10096 (setq s (replace-match "%3C" t t s)))
10097 (while (string-match ">" s)
10098 (setq s (replace-match "%3E" t t s)))
10099 (while (string-match "@" s)
10100 (setq s (replace-match "%40" t t s)))
10103 (defun org-link-prettify (link)
10104 "Return a human-readable representation of LINK.
10105 The car of LINK must be a raw link.
10106 The cdr of LINK must be either a link description or nil."
10107 (let ((desc (or (cadr link) "<no description>")))
10108 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10109 "<" (car link) ">")))
10111 ;;;###autoload
10112 (defun org-insert-link-global ()
10113 "Insert a link like Org-mode does.
10114 This command can be called in any mode to insert a link in Org-mode syntax."
10115 (interactive)
10116 (org-load-modules-maybe)
10117 (org-run-like-in-org-mode 'org-insert-link))
10119 (defun org-insert-all-links (arg &optional pre post)
10120 "Insert all links in `org-stored-links'.
10121 When a universal prefix, do not delete the links from `org-stored-links'.
10122 When `ARG' is a number, insert the last N link(s).
10123 `PRE' and `POST' are optional arguments to define a string to
10124 prepend or to append."
10125 (interactive "P")
10126 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10127 (links (copy-sequence org-stored-links))
10128 (pr (or pre "- "))
10129 (po (or post "\n"))
10130 (cnt 1) l)
10131 (if (null org-stored-links)
10132 (message "No link to insert")
10133 (while (and (or (listp arg) (>= arg cnt))
10134 (setq l (if (listp arg)
10135 (pop links)
10136 (pop org-stored-links))))
10137 (setq cnt (1+ cnt))
10138 (insert pr)
10139 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10140 (insert po)))))
10142 (defun org-insert-last-stored-link (arg)
10143 "Insert the last link stored in `org-stored-links'."
10144 (interactive "p")
10145 (org-insert-all-links arg "" "\n"))
10147 (defun org-link-fontify-links-to-this-file ()
10148 "Fontify links to the current file in `org-stored-links'."
10149 (let ((f (buffer-file-name)) a b)
10150 (setq a (mapcar (lambda(l)
10151 (let ((ll (car l)))
10152 (when (and (string-match "^file:\\(.+\\)::" ll)
10153 (equal f (expand-file-name (match-string 1 ll))))
10154 ll)))
10155 org-stored-links))
10156 (when (featurep 'org-id)
10157 (setq b (mapcar (lambda(l)
10158 (let ((ll (car l)))
10159 (when (and (string-match "^id:\\(.+\\)$" ll)
10160 (equal f (expand-file-name
10161 (or (org-id-find-id-file
10162 (match-string 1 ll)) ""))))
10163 ll)))
10164 org-stored-links)))
10165 (mapcar (lambda(l)
10166 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10167 (delq nil (append a b)))))
10169 (defvar org--links-history nil)
10170 (defun org-insert-link (&optional complete-file link-location default-description)
10171 "Insert a link. At the prompt, enter the link.
10173 Completion can be used to insert any of the link protocol prefixes like
10174 http or ftp in use.
10176 The history can be used to select a link previously stored with
10177 `org-store-link'. When the empty string is entered (i.e. if you just
10178 press RET at the prompt), the link defaults to the most recently
10179 stored link. As SPC triggers completion in the minibuffer, you need to
10180 use M-SPC or C-q SPC to force the insertion of a space character.
10182 You will also be prompted for a description, and if one is given, it will
10183 be displayed in the buffer instead of the link.
10185 If there is already a link at point, this command will allow you to edit link
10186 and description parts.
10188 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10189 be selected using completion. The path to the file will be relative to the
10190 current directory if the file is in the current directory or a subdirectory.
10191 Otherwise, the link will be the absolute path as completed in the minibuffer
10192 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10193 option `org-link-file-path-type'.
10195 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10196 the current directory or below.
10198 With three \\[universal-argument] prefixes, negate the meaning of
10199 `org-keep-stored-link-after-insertion'.
10201 If `org-make-link-description-function' is non-nil, this function will be
10202 called with the link target, and the result will be the default
10203 link description.
10205 If the LINK-LOCATION parameter is non-nil, this value will be
10206 used as the link location instead of reading one interactively.
10208 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10209 be used as the default description."
10210 (interactive "P")
10211 (let* ((wcf (current-window-configuration))
10212 (origbuf (current-buffer))
10213 (region (when (org-region-active-p)
10214 (buffer-substring (region-beginning) (region-end))))
10215 (remove (and region (list (region-beginning) (region-end))))
10216 (desc region)
10217 (link link-location)
10218 (abbrevs org-link-abbrev-alist-local)
10219 entry all-prefixes auto-desc)
10220 (cond
10221 (link-location) ; specified by arg, just use it.
10222 ((org-in-regexp org-bracket-link-regexp 1)
10223 ;; We do have a link at point, and we are going to edit it.
10224 (setq remove (list (match-beginning 0) (match-end 0)))
10225 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10226 (setq link (read-string "Link: "
10227 (org-link-unescape
10228 (org-match-string-no-properties 1)))))
10229 ((or (org-in-regexp org-angle-link-re)
10230 (org-in-regexp org-plain-link-re))
10231 ;; Convert to bracket link
10232 (setq remove (list (match-beginning 0) (match-end 0))
10233 link (read-string "Link: "
10234 (org-remove-angle-brackets (match-string 0)))))
10235 ((member complete-file '((4) (16)))
10236 ;; Completing read for file names.
10237 (setq link (org-file-complete-link complete-file)))
10239 ;; Read link, with completion for stored links.
10240 (org-link-fontify-links-to-this-file)
10241 (org-switch-to-buffer-other-window "*Org Links*")
10242 (with-current-buffer "*Org Links*"
10243 (erase-buffer)
10244 (insert "Insert a link.
10245 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10246 (when org-stored-links
10247 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10248 (insert (mapconcat 'org-link-prettify
10249 (reverse org-stored-links) "\n")))
10250 (goto-char (point-min)))
10251 (let ((cw (selected-window)))
10252 (select-window (get-buffer-window "*Org Links*" 'visible))
10253 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10254 (unless (pos-visible-in-window-p (point-max))
10255 (org-fit-window-to-buffer))
10256 (and (window-live-p cw) (select-window cw)))
10257 (setq all-prefixes (append (mapcar 'car abbrevs)
10258 (mapcar 'car org-link-abbrev-alist)
10259 org-link-types))
10260 (unwind-protect
10261 ;; Fake a link history, containing the stored links.
10262 (let ((org--links-history
10263 (append (mapcar #'car org-stored-links)
10264 org-insert-link-history)))
10265 (setq link
10266 (org-completing-read
10267 "Link: "
10268 (append
10269 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10270 (mapcar #'car org-stored-links))
10271 nil nil nil
10272 'org--links-history
10273 (caar org-stored-links)))
10274 (unless (org-string-nw-p link) (user-error "No link selected"))
10275 (dolist (l org-stored-links)
10276 (when (equal link (cadr l))
10277 (setq link (car l))
10278 (setq auto-desc t)))
10279 (when (or (member link all-prefixes)
10280 (and (equal ":" (substring link -1))
10281 (member (substring link 0 -1) all-prefixes)
10282 (setq link (substring link 0 -1))))
10283 (setq link (with-current-buffer origbuf
10284 (org-link-try-special-completion link)))))
10285 (set-window-configuration wcf)
10286 (kill-buffer "*Org Links*"))
10287 (setq entry (assoc link org-stored-links))
10288 (or entry (push link org-insert-link-history))
10289 (setq desc (or desc (nth 1 entry)))))
10291 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10292 (not org-keep-stored-link-after-insertion))
10293 (setq org-stored-links (delq (assoc link org-stored-links)
10294 org-stored-links)))
10296 (when (and (string-match org-plain-link-re link)
10297 (not (string-match org-ts-regexp link)))
10298 ;; URL-like link, normalize the use of angular brackets.
10299 (setq link (org-remove-angle-brackets link)))
10301 ;; Check if we are linking to the current file with a search
10302 ;; option If yes, simplify the link by using only the search
10303 ;; option.
10304 (when (and buffer-file-name
10305 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10306 (let* ((path (match-string 1 link))
10307 (case-fold-search nil)
10308 (search (match-string 2 link)))
10309 (save-match-data
10310 (when (equal (file-truename buffer-file-name) (file-truename path))
10311 ;; We are linking to this same file, with a search option
10312 (setq link search)))))
10314 ;; Check if we can/should use a relative path. If yes, simplify the link
10315 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10316 (let* ((type (match-string 1 link))
10317 (path (match-string 2 link))
10318 (origpath path)
10319 (case-fold-search nil))
10320 (cond
10321 ((or (eq org-link-file-path-type 'absolute)
10322 (equal complete-file '(16)))
10323 (setq path (abbreviate-file-name (expand-file-name path))))
10324 ((eq org-link-file-path-type 'noabbrev)
10325 (setq path (expand-file-name path)))
10326 ((eq org-link-file-path-type 'relative)
10327 (setq path (file-relative-name path)))
10329 (save-match-data
10330 (if (string-match (concat "^" (regexp-quote
10331 (expand-file-name
10332 (file-name-as-directory
10333 default-directory))))
10334 (expand-file-name path))
10335 ;; We are linking a file with relative path name.
10336 (setq path (substring (expand-file-name path)
10337 (match-end 0)))
10338 (setq path (abbreviate-file-name (expand-file-name path)))))))
10339 (setq link (concat type path))
10340 (when (equal desc origpath)
10341 (setq desc path))))
10343 (if org-make-link-description-function
10344 (setq desc
10345 (or (condition-case nil
10346 (funcall org-make-link-description-function link desc)
10347 (error (progn (message "Can't get link description from `%s'"
10348 (symbol-name org-make-link-description-function))
10349 (sit-for 2) nil)))
10350 (read-string "Description: " default-description)))
10351 (if default-description (setq desc default-description)
10352 (setq desc (or (and auto-desc desc)
10353 (read-string "Description: " desc)))))
10355 (unless (string-match "\\S-" desc) (setq desc nil))
10356 (when remove (apply 'delete-region remove))
10357 (insert (org-make-link-string link desc))
10358 ;; Redisplay so as the new link has proper invisible characters.
10359 (sit-for 0)))
10361 (defun org-link-try-special-completion (type)
10362 "If there is completion support for link type TYPE, offer it."
10363 (let ((fun (intern (concat "org-" type "-complete-link"))))
10364 (if (functionp fun)
10365 (funcall fun)
10366 (read-string "Link (no completion support): " (concat type ":")))))
10368 (defun org-file-complete-link (&optional arg)
10369 "Create a file link using completion."
10370 (let ((file (read-file-name "File: "))
10371 (pwd (file-name-as-directory (expand-file-name ".")))
10372 (pwd1 (file-name-as-directory (abbreviate-file-name
10373 (expand-file-name ".")))))
10374 (cond ((equal arg '(16))
10375 (concat "file:"
10376 (abbreviate-file-name (expand-file-name file))))
10377 ((string-match
10378 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10379 (concat "file:" (match-string 1 file)))
10380 ((string-match
10381 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10382 (expand-file-name file))
10383 (concat "file:"
10384 (match-string 1 (expand-file-name file))))
10385 (t (concat "file:" file)))))
10387 (defun org-completing-read (&rest args)
10388 "Completing-read with SPACE being a normal character."
10389 (let ((enable-recursive-minibuffers t)
10390 (minibuffer-local-completion-map
10391 (copy-keymap minibuffer-local-completion-map)))
10392 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10393 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10394 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10395 'org-time-stamp-inactive)
10396 (apply #'completing-read args)))
10398 (define-obsolete-function-alias
10399 'org-completing-read-no-i 'completing-read "Org 9.0")
10400 (define-obsolete-function-alias
10401 'org-icompleting-read 'completing-read "Org 9.0")
10402 (define-obsolete-function-alias
10403 'org-iread-file-name 'read-file-name "Org 9.0")
10405 ;;; Opening/following a link
10407 (defvar org-link-search-failed nil)
10409 (defvar org-open-link-functions nil
10410 "Hook for functions finding a plain text link.
10411 These functions must take a single argument, the link content.
10412 They will be called for links that look like [[link text][description]]
10413 when LINK TEXT does not have a protocol like \"http:\" and does not look
10414 like a filename (e.g. \"./blue.png\").
10416 These functions will be called *before* Org attempts to resolve the
10417 link by doing text searches in the current buffer - so if you want a
10418 link \"[[target]]\" to still find \"<<target>>\", your function should
10419 handle this as a special case.
10421 When the function does handle the link, it must return a non-nil value.
10422 If it decides that it is not responsible for this link, it must return
10423 nil to indicate that that Org-mode can continue with other options
10424 like exact and fuzzy text search.")
10426 (defun org-next-link (&optional search-backward)
10427 "Move forward to the next link.
10428 If the link is in hidden text, expose it."
10429 (interactive "P")
10430 (when (and org-link-search-failed (eq this-command last-command))
10431 (goto-char (point-min))
10432 (message "Link search wrapped back to beginning of buffer"))
10433 (setq org-link-search-failed nil)
10434 (let* ((pos (point))
10435 (ct (org-context))
10436 (a (assoc :link ct))
10437 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10438 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10439 ((looking-at org-any-link-re)
10440 ;; Don't stay stuck at link without an org-link face
10441 (forward-char (if search-backward -1 1))))
10442 (if (funcall srch-fun org-any-link-re nil t)
10443 (progn
10444 (goto-char (match-beginning 0))
10445 (when (outline-invisible-p) (org-show-context)))
10446 (goto-char pos)
10447 (setq org-link-search-failed t)
10448 (message "No further link found"))))
10450 (defun org-previous-link ()
10451 "Move backward to the previous link.
10452 If the link is in hidden text, expose it."
10453 (interactive)
10454 (funcall 'org-next-link t))
10456 (defun org-translate-link (s)
10457 "Translate a link string if a translation function has been defined."
10458 (with-temp-buffer
10459 (insert (org-trim s))
10460 (org-trim (org-element-interpret-data (org-element-context)))))
10462 (defun org-translate-link-from-planner (type path)
10463 "Translate a link from Emacs Planner syntax so that Org can follow it.
10464 This is still an experimental function, your mileage may vary."
10465 (cond
10466 ((member type '("http" "https" "news" "ftp"))
10467 ;; standard Internet links are the same.
10468 nil)
10469 ((and (equal type "irc") (string-match "^//" path))
10470 ;; Planner has two / at the beginning of an irc link, we have 1.
10471 ;; We should have zero, actually....
10472 (setq path (substring path 1)))
10473 ((and (equal type "lisp") (string-match "^/" path))
10474 ;; Planner has a slash, we do not.
10475 (setq type "elisp" path (substring path 1)))
10476 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10477 ;; A typical message link. Planner has the id after the final slash,
10478 ;; we separate it with a hash mark
10479 (setq path (concat (match-string 1 path) "#"
10480 (org-remove-angle-brackets (match-string 2 path))))))
10481 (cons type path))
10483 (defun org-find-file-at-mouse (ev)
10484 "Open file link or URL at mouse."
10485 (interactive "e")
10486 (mouse-set-point ev)
10487 (org-open-at-point 'in-emacs))
10489 (defun org-open-at-mouse (ev)
10490 "Open file link or URL at mouse.
10491 See the docstring of `org-open-file' for details."
10492 (interactive "e")
10493 (mouse-set-point ev)
10494 (when (eq major-mode 'org-agenda-mode)
10495 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10496 (org-open-at-point))
10498 (defvar org-window-config-before-follow-link nil
10499 "The window configuration before following a link.
10500 This is saved in case the need arises to restore it.")
10502 ;;;###autoload
10503 (defun org-open-at-point-global ()
10504 "Follow a link like Org-mode does.
10505 This command can be called in any mode to follow a link that has
10506 Org-mode syntax."
10507 (interactive)
10508 (org-run-like-in-org-mode 'org-open-at-point))
10510 ;;;###autoload
10511 (defun org-open-link-from-string (s &optional arg reference-buffer)
10512 "Open a link in the string S, as if it was in Org-mode."
10513 (interactive "sLink: \nP")
10514 (let ((reference-buffer (or reference-buffer (current-buffer))))
10515 (with-temp-buffer
10516 (let ((org-inhibit-startup (not reference-buffer)))
10517 (org-mode)
10518 (insert s)
10519 (goto-char (point-min))
10520 (when reference-buffer
10521 (setq org-link-abbrev-alist-local
10522 (with-current-buffer reference-buffer
10523 org-link-abbrev-alist-local)))
10524 (org-open-at-point arg reference-buffer)))))
10526 (defvar org-open-at-point-functions nil
10527 "Hook that is run when following a link at point.
10529 Functions in this hook must return t if they identify and follow
10530 a link at point. If they don't find anything interesting at point,
10531 they must return nil.")
10533 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10534 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10535 (defun org-open-at-point (&optional arg reference-buffer)
10536 "Open link, timestamp, footnote or tags at point.
10538 When point is on a link, follow it. Normally, files will be
10539 opened by an appropriate application. If the optional prefix
10540 argument ARG is non-nil, Emacs will visit the file. With
10541 a double prefix argument, try to open outside of Emacs, in the
10542 application the system uses for this file type.
10544 When point is on a timestamp, open the agenda at the day
10545 specified.
10547 When point is a footnote definition, move to the first reference
10548 found. If it is on a reference, move to the associated
10549 definition.
10551 When point is on a headline, display a list of every link in the
10552 entry, so it is possible to pick one, or all, of them. If point
10553 is on a tag, call `org-tags-view' instead.
10555 When optional argument REFERENCE-BUFFER is non-nil, it should
10556 specify a buffer from where the link search should happen. This
10557 is used internally by `org-open-link-from-string'.
10559 On top of syntactically correct links, this function will open
10560 the link at point in comments or comment blocks and the first
10561 link in a property drawer line."
10562 (interactive "P")
10563 ;; On a code block, open block's results.
10564 (unless (call-interactively 'org-babel-open-src-block-result)
10565 (org-load-modules-maybe)
10566 (setq org-window-config-before-follow-link (current-window-configuration))
10567 (org-remove-occur-highlights nil nil t)
10568 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10569 (let* ((context
10570 ;; Only consider supported types, even if they are not
10571 ;; the closest one.
10572 (org-element-lineage
10573 (org-element-context)
10574 '(clock comment comment-block footnote-definition
10575 footnote-reference headline inlinetask keyword link
10576 node-property timestamp)
10578 (type (org-element-type context))
10579 (value (org-element-property :value context)))
10580 (cond
10581 ((not context) (user-error "No link found"))
10582 ;; Exception: open timestamps and links in properties
10583 ;; drawers, keywords and comments.
10584 ((memq type '(comment comment-block keyword node-property))
10585 (cond ((org-in-regexp org-any-link-re)
10586 (org-open-link-from-string (match-string-no-properties 0)))
10587 ((or (org-in-regexp org-ts-regexp-both nil t)
10588 (org-in-regexp org-tsr-regexp-both nil t))
10589 (org-follow-timestamp-link))
10590 (t (user-error "No link found"))))
10591 ;; On a headline or an inlinetask, but not on a timestamp,
10592 ;; a link, a footnote reference or on tags.
10593 ((and (memq type '(headline inlinetask))
10594 ;; Not on tags.
10595 (progn (save-excursion (beginning-of-line)
10596 (looking-at org-complex-heading-regexp))
10597 (or (not (match-beginning 5))
10598 (< (point) (match-beginning 5)))))
10599 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10600 (links (car data))
10601 (links-end (cdr data)))
10602 (if links
10603 (dolist (link (if (stringp links) (list links) links))
10604 (search-forward link nil links-end)
10605 (goto-char (match-beginning 0))
10606 (org-open-at-point))
10607 (require 'org-attach)
10608 (org-attach-reveal 'if-exists))))
10609 ;; On a clock line, make sure point is on the timestamp
10610 ;; before opening it.
10611 ((and (eq type 'clock)
10612 value
10613 (>= (point) (org-element-property :begin value))
10614 (<= (point) (org-element-property :end value)))
10615 (org-follow-timestamp-link))
10616 ;; Do nothing on white spaces after an object.
10617 ((>= (point)
10618 (save-excursion
10619 (goto-char (org-element-property :end context))
10620 (skip-chars-backward " \t")
10621 (point)))
10622 (user-error "No link found"))
10623 ((eq type 'timestamp) (org-follow-timestamp-link))
10624 ;; On tags within a headline or an inlinetask.
10625 ((and (memq type '(headline inlinetask))
10626 (progn (save-excursion (beginning-of-line)
10627 (looking-at org-complex-heading-regexp))
10628 (and (match-beginning 5)
10629 (>= (point) (match-beginning 5)))))
10630 (org-tags-view arg (substring (match-string 5) 0 -1)))
10631 ((eq type 'link)
10632 ;; When link is located within the description of another
10633 ;; link (e.g., an inline image), always open the parent
10634 ;; link.
10635 (let*((link (let ((up (org-element-property :parent context)))
10636 (if (eq (org-element-type up) 'link) up context)))
10637 (type (org-element-property :type link))
10638 (path (org-link-unescape (org-element-property :path link))))
10639 ;; Switch back to REFERENCE-BUFFER needed when called in
10640 ;; a temporary buffer through `org-open-link-from-string'.
10641 (with-current-buffer (or reference-buffer (current-buffer))
10642 (cond
10643 ((equal type "file")
10644 (if (string-match "[*?{]" (file-name-nondirectory path))
10645 (dired path)
10646 ;; Look into `org-link-protocols' in order to find
10647 ;; a DEDICATED-FUNCTION to open file. The function
10648 ;; will be applied on raw link instead of parsed
10649 ;; link due to the limitation in `org-add-link-type'
10650 ;; ("open" function called with a single argument).
10651 ;; If no such function is found, fallback to
10652 ;; `org-open-file'.
10654 ;; Note : "file+emacs" and "file+sys" types are
10655 ;; hard-coded in order to escape the previous
10656 ;; limitation.
10657 (let* ((option (org-element-property :search-option link))
10658 (app (org-element-property :application link))
10659 (dedicated-function
10660 (nth 1 (assoc app org-link-protocols))))
10661 (if dedicated-function
10662 (funcall dedicated-function
10663 (concat path
10664 (and option (concat "::" option))))
10665 (apply #'org-open-file
10666 path
10667 (cond (arg)
10668 ((equal app "emacs") 'emacs)
10669 ((equal app "sys") 'system))
10670 (cond ((not option) nil)
10671 ((org-string-match-p "\\`[0-9]+\\'" option)
10672 (list (string-to-number option)))
10673 (t (list nil
10674 (org-link-unescape option)))))))))
10675 ((assoc type org-link-protocols)
10676 (funcall (nth 1 (assoc type org-link-protocols)) path))
10677 ((equal type "help")
10678 (let ((f-or-v (intern path)))
10679 (cond ((fboundp f-or-v) (describe-function f-or-v))
10680 ((boundp f-or-v) (describe-variable f-or-v))
10681 (t (error "Not a known function or variable")))))
10682 ((member type '("http" "https" "ftp" "mailto" "news"))
10683 (browse-url (org-link-escape-browser (concat type ":" path))))
10684 ((equal type "doi")
10685 (browse-url
10686 (org-link-escape-browser (concat org-doi-server-url path))))
10687 ((equal type "message") (browse-url (concat type ":" path)))
10688 ((equal type "shell")
10689 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10690 (cmd path))
10691 (if (or (and (org-string-nw-p
10692 org-confirm-shell-link-not-regexp)
10693 (string-match
10694 org-confirm-shell-link-not-regexp cmd))
10695 (not org-confirm-shell-link-function)
10696 (funcall org-confirm-shell-link-function
10697 (format "Execute \"%s\" in shell? "
10698 (org-add-props cmd nil
10699 'face 'org-warning))))
10700 (progn
10701 (message "Executing %s" cmd)
10702 (shell-command cmd buf)
10703 (when (featurep 'midnight)
10704 (setq clean-buffer-list-kill-buffer-names
10705 (cons (buffer-name buf)
10706 clean-buffer-list-kill-buffer-names))))
10707 (user-error "Abort"))))
10708 ((equal type "elisp")
10709 (let ((cmd path))
10710 (if (or (and (org-string-nw-p
10711 org-confirm-elisp-link-not-regexp)
10712 (org-string-match-p
10713 org-confirm-elisp-link-not-regexp cmd))
10714 (not org-confirm-elisp-link-function)
10715 (funcall org-confirm-elisp-link-function
10716 (format "Execute \"%s\" as elisp? "
10717 (org-add-props cmd nil
10718 'face 'org-warning))))
10719 (message "%s => %s" cmd
10720 (if (eq (string-to-char cmd) ?\()
10721 (eval (read cmd))
10722 (call-interactively (read cmd))))
10723 (user-error "Abort"))))
10724 ((equal type "id")
10725 (require 'org-id)
10726 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10727 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10728 (unless (run-hook-with-args-until-success
10729 'org-open-link-functions path)
10730 (if (not arg) (org-mark-ring-push)
10731 (switch-to-buffer-other-window
10732 (org-get-buffer-for-internal-link (current-buffer))))
10733 (let ((destination
10734 (org-with-wide-buffer
10735 (if (equal type "radio")
10736 (org-search-radio-target
10737 (org-element-property :path link))
10738 (org-link-search
10739 (if (member type '("custom-id" "coderef"))
10740 (org-element-property :raw-link link)
10741 path)
10742 ;; Prevent fuzzy links from matching
10743 ;; themselves.
10744 (and (equal type "fuzzy")
10745 (+ 2 (org-element-property :begin link)))))
10746 (point))))
10747 (unless (and (<= (point-min) destination)
10748 (>= (point-max) destination))
10749 (widen))
10750 (goto-char destination))))
10751 (t (browse-url-at-point))))))
10752 ;; On a footnote reference or at a footnote definition's label.
10753 ((or (eq type 'footnote-reference)
10754 (and (eq type 'footnote-definition)
10755 (save-excursion
10756 ;; Do not validate action when point is on the
10757 ;; spaces right after the footnote label, in
10758 ;; order to be on par with behaviour on links.
10759 (skip-chars-forward " \t")
10760 (let ((begin
10761 (org-element-property :contents-begin context)))
10762 (if begin (< (point) begin)
10763 (= (org-element-property :post-affiliated context)
10764 (line-beginning-position)))))))
10765 (org-footnote-action))
10766 (t (user-error "No link found")))))
10767 (run-hook-with-args 'org-follow-link-hook)))
10769 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10770 "Offer links in the current entry and return the selected link.
10771 If there is only one link, return it.
10772 If NTH is an integer, return the NTH link found.
10773 If ZERO is a string, check also this string for a link, and if
10774 there is one, return it."
10775 (with-current-buffer buffer
10776 (save-excursion
10777 (save-restriction
10778 (widen)
10779 (goto-char marker)
10780 (let ((cnt ?0)
10781 have-zero end links link c)
10782 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10783 (push (match-string 0 zero) links)
10784 (setq cnt (1- cnt) have-zero t))
10785 (save-excursion
10786 (org-back-to-heading t)
10787 (setq end (save-excursion (outline-next-heading) (point)))
10788 (while (re-search-forward org-any-link-re end t)
10789 (push (match-string 0) links))
10790 (setq links (org-uniquify (reverse links))))
10791 (cond
10792 ((null links)
10793 (message "No links"))
10794 ((equal (length links) 1)
10795 (setq link (car links)))
10796 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10797 (setq link (nth (if have-zero nth (1- nth)) links)))
10798 (t ; we have to select a link
10799 (save-excursion
10800 (save-window-excursion
10801 (delete-other-windows)
10802 (with-output-to-temp-buffer "*Select Link*"
10803 (dolist (l links)
10804 (cond
10805 ((not (string-match org-bracket-link-regexp l))
10806 (princ (format "[%c] %s\n" (cl-incf cnt)
10807 (org-remove-angle-brackets l))))
10808 ((match-end 3)
10809 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10810 (match-string 3 l) (match-string 1 l))))
10811 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10812 (match-string 1 l)))))))
10813 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10814 (message "Select link to open, RET to open all:")
10815 (setq c (read-char-exclusive))
10816 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10817 (when (equal c ?q) (user-error "Abort"))
10818 (if (equal c ?\C-m)
10819 (setq link links)
10820 (setq nth (- c ?0))
10821 (when have-zero (setq nth (1+ nth)))
10822 (unless (and (integerp nth) (>= (length links) nth))
10823 (user-error "Invalid link selection"))
10824 (setq link (nth (1- nth) links)))))
10825 (cons link end))))))
10827 ;; TODO: These functions are deprecated since `org-open-at-point'
10828 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10829 (defun org-open-file-with-system (path)
10830 "Open file at PATH using the system way of opening it."
10831 (org-open-file path 'system))
10832 (defun org-open-file-with-emacs (path)
10833 "Open file at PATH in Emacs."
10834 (org-open-file path 'emacs))
10837 ;;; File search
10839 (defvar org-create-file-search-functions nil
10840 "List of functions to construct the right search string for a file link.
10841 These functions are called in turn with point at the location to
10842 which the link should point.
10844 A function in the hook should first test if it would like to
10845 handle this file type, for example by checking the `major-mode'
10846 or the file extension. If it decides not to handle this file, it
10847 should just return nil to give other functions a chance. If it
10848 does handle the file, it must return the search string to be used
10849 when following the link. The search string will be part of the
10850 file link, given after a double colon, and `org-open-at-point'
10851 will automatically search for it. If special measures must be
10852 taken to make the search successful, another function should be
10853 added to the companion hook `org-execute-file-search-functions',
10854 which see.
10856 A function in this hook may also use `setq' to set the variable
10857 `description' to provide a suggestion for the descriptive text to
10858 be used for this link when it gets inserted into an Org-mode
10859 buffer with \\[org-insert-link].")
10861 (defvar org-execute-file-search-functions nil
10862 "List of functions to execute a file search triggered by a link.
10864 Functions added to this hook must accept a single argument, the
10865 search string that was part of the file link, the part after the
10866 double colon. The function must first check if it would like to
10867 handle this search, for example by checking the `major-mode' or
10868 the file extension. If it decides not to handle this search, it
10869 should just return nil to give other functions a chance. If it
10870 does handle the search, it must return a non-nil value to keep
10871 other functions from trying.
10873 Each function can access the current prefix argument through the
10874 variable `current-prefix-arg'. Note that a single prefix is used
10875 to force opening a link in Emacs, so it may be good to only use a
10876 numeric or double prefix to guide the search function.
10878 In case this is needed, a function in this hook can also restore
10879 the window configuration before `org-open-at-point' was called using:
10881 \(set-window-configuration org-window-config-before-follow-link)")
10883 (defun org-search-radio-target (target)
10884 "Search a radio target matching TARGET in current buffer.
10885 White spaces are not significant."
10886 (let ((re (format "<<<%s>>>"
10887 (mapconcat #'regexp-quote
10888 (org-split-string target "[ \t\n]+")
10889 "[ \t]+\\(?:\n[ \t]*\\)?")))
10890 (origin (point)))
10891 (goto-char (point-min))
10892 (catch :radio-match
10893 (while (re-search-forward re nil t)
10894 (backward-char)
10895 (let ((object (org-element-context)))
10896 (when (eq (org-element-type object) 'radio-target)
10897 (goto-char (org-element-property :begin object))
10898 (org-show-context 'link-search)
10899 (throw :radio-match nil))))
10900 (goto-char origin)
10901 (user-error "No match for radio target: %s" target))))
10903 (defun org-link-search (s &optional avoid-pos stealth)
10904 "Search for a search string S.
10906 If S starts with \"#\", it triggers a custom ID search.
10908 If S is enclosed within parenthesis, it initiates a coderef
10909 search.
10911 If S is surrounded by forward slashes, it is interpreted as
10912 a regular expression. In Org mode files, this will create an
10913 `org-occur' sparse tree. In ordinary files, `occur' will be used
10914 to list matches. If the current buffer is in `dired-mode', grep
10915 will be used to search in all files.
10917 When AVOID-POS is given, ignore matches near that position.
10919 When optional argument STEALTH is non-nil, do not modify
10920 visibility around point, thus ignoring `org-show-context-detail'
10921 variable.
10923 Search is case-insensitive and ignores white spaces. Return type
10924 of matched result, with is either `dedicated' or `fuzzy'."
10925 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10926 (let* ((case-fold-search t)
10927 (origin (point))
10928 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10929 (words (org-split-string s "[ \t\n]+"))
10930 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10931 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10932 type)
10933 (cond
10934 ;; Check if there are any special search functions.
10935 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10936 ((eq (string-to-char s) ?#)
10937 ;; Look for a custom ID S if S starts with "#".
10938 (let* ((id (substring normalized 1))
10939 (match (org-find-property "CUSTOM_ID" id)))
10940 (if match (progn (goto-char match) (setf type 'dedicated))
10941 (error "No match for custom ID: %s" id))))
10942 ((string-match "\\`(\\(.*\\))\\'" normalized)
10943 ;; Look for coderef targets if S is enclosed within parenthesis.
10944 (let ((coderef (match-string-no-properties 1 normalized))
10945 (re (substring s-single-re 1 -1)))
10946 (goto-char (point-min))
10947 (catch :coderef-match
10948 (while (re-search-forward re nil t)
10949 (let ((element (org-element-at-point)))
10950 (when (and (memq (org-element-type element)
10951 '(example-block src-block))
10952 ;; Build proper regexp according to current
10953 ;; block's label format.
10954 (let ((label-fmt
10955 (regexp-quote
10956 (or (org-element-property :label-fmt element)
10957 org-coderef-label-format))))
10958 (save-excursion
10959 (beginning-of-line)
10960 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10961 (format label-fmt coderef))))))
10962 (setq type 'dedicated)
10963 (goto-char (match-beginning 1))
10964 (throw :coderef-match nil))))
10965 (goto-char origin)
10966 (error "No match for coderef: %s" coderef))))
10967 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10968 ;; Look for a regular expression.
10969 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10970 (match-string 1 s)))
10971 ;; Fuzzy links.
10973 (let ((starred (eq (string-to-char normalized) ?*)))
10974 (cond
10975 ;; Look for targets, only if not in a headline search.
10976 ((and (not starred)
10977 (let ((target (format "<<%s>>" s-multi-re)))
10978 (catch :target-match
10979 (goto-char (point-min))
10980 (while (re-search-forward target nil t)
10981 (backward-char)
10982 (let ((context (org-element-context)))
10983 (when (eq (org-element-type context) 'target)
10984 (setq type 'dedicated)
10985 (goto-char (org-element-property :begin context))
10986 (throw :target-match t))))
10987 nil))))
10988 ;; Look for elements named after S, only if not in a headline
10989 ;; search.
10990 ((and (not starred)
10991 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10992 (catch :name-match
10993 (goto-char (point-min))
10994 (while (re-search-forward name nil t)
10995 (let ((element (org-element-at-point)))
10996 (when (equal (org-split-string
10997 (org-element-property :name element)
10998 "[ \t]+")
10999 words)
11000 (setq type 'dedicated)
11001 (beginning-of-line)
11002 (throw :name-match t))))
11003 nil))))
11004 ;; Regular text search. Prefer headlines in Org mode
11005 ;; buffers.
11006 ((and (derived-mode-p 'org-mode)
11007 (let* ((wspace "[ \t]")
11008 (wspaceopt (concat wspace "*"))
11009 (cookie (concat "\\(?:"
11010 wspaceopt
11011 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11012 wspaceopt
11013 "\\)"))
11014 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11015 (re (concat
11016 org-outline-regexp-bol
11017 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11018 "\\(?:\\[#.\\][ \t]+\\)?"
11019 "\\(?:" org-comment-string "[ \t]+\\)?"
11020 sep "?"
11021 (let ((title (mapconcat #'regexp-quote
11022 words
11023 sep)))
11024 (if starred (substring title 1) title))
11025 sep "?"
11026 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11027 "[ \t]*$")))
11028 (goto-char (point-min))
11029 (re-search-forward re nil t)))
11030 (goto-char (match-beginning 0))
11031 (setq type 'dedicated))
11032 ;; Offer to create non-existent headline depending on
11033 ;; `org-link-search-must-match-exact-headline'.
11034 ((and (derived-mode-p 'org-mode)
11035 (not org-link-search-inhibit-query)
11036 (eq org-link-search-must-match-exact-headline 'query-to-create)
11037 (yes-or-no-p "No match - create this as a new heading? "))
11038 (goto-char (point-max))
11039 (unless (bolp) (newline))
11040 (org-insert-heading nil t t)
11041 (insert s "\n")
11042 (beginning-of-line 0))
11043 ;; Only headlines are looked after. No need to process
11044 ;; further: throw an error.
11045 ((and (derived-mode-p 'org-mode)
11046 (or starred org-link-search-must-match-exact-headline))
11047 (goto-char origin)
11048 (error "No match for fuzzy expression: %s" normalized))
11049 ;; Regular text search.
11050 ((catch :fuzzy-match
11051 (goto-char (point-min))
11052 (while (re-search-forward s-multi-re nil t)
11053 ;; Skip match if it contains AVOID-POS or it is included
11054 ;; in a link with a description but outside the
11055 ;; description.
11056 (unless (or (and avoid-pos
11057 (<= (match-beginning 0) avoid-pos)
11058 (> (match-end 0) avoid-pos))
11059 (and (save-match-data
11060 (org-in-regexp org-bracket-link-regexp))
11061 (match-beginning 3)
11062 (or (> (match-beginning 3) (point))
11063 (<= (match-end 3) (point)))
11064 (org-element-lineage
11065 (save-match-data (org-element-context))
11066 '(link) t)))
11067 (goto-char (match-beginning 0))
11068 (setq type 'fuzzy)
11069 (throw :fuzzy-match t)))
11070 nil))
11071 ;; All failed. Throw an error.
11072 (t (goto-char origin)
11073 (error "No match for fuzzy expression: %s" normalized))))))
11074 ;; Disclose surroundings of match, if appropriate.
11075 (when (and (derived-mode-p 'org-mode) (not stealth))
11076 (org-show-context 'link-search))
11077 type))
11079 (defun org-get-buffer-for-internal-link (buffer)
11080 "Return a buffer to be used for displaying the link target of internal links."
11081 (cond
11082 ((not org-display-internal-link-with-indirect-buffer)
11083 buffer)
11084 ((string-match "(Clone)$" (buffer-name buffer))
11085 (message "Buffer is already a clone, not making another one")
11086 ;; we also do not modify visibility in this case
11087 buffer)
11088 (t ; make a new indirect buffer for displaying the link
11089 (let* ((bn (buffer-name buffer))
11090 (ibn (concat bn "(Clone)"))
11091 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11092 (with-current-buffer ib (org-overview))
11093 ib))))
11095 (defun org-do-occur (regexp &optional cleanup)
11096 "Call the Emacs command `occur'.
11097 If CLEANUP is non-nil, remove the printout of the regular expression
11098 in the *Occur* buffer. This is useful if the regex is long and not useful
11099 to read."
11100 (occur regexp)
11101 (when cleanup
11102 (let ((cwin (selected-window)) win beg end)
11103 (when (setq win (get-buffer-window "*Occur*"))
11104 (select-window win))
11105 (goto-char (point-min))
11106 (when (re-search-forward "match[a-z]+" nil t)
11107 (setq beg (match-end 0))
11108 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11109 (setq end (1- (match-beginning 0)))))
11110 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11111 (goto-char (point-min))
11112 (select-window cwin))))
11114 ;;; The mark ring for links jumps
11116 (defvar org-mark-ring nil
11117 "Mark ring for positions before jumps in Org-mode.")
11118 (defvar org-mark-ring-last-goto nil
11119 "Last position in the mark ring used to go back.")
11120 ;; Fill and close the ring
11121 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11122 (dotimes (_ org-mark-ring-length)
11123 (push (make-marker) org-mark-ring))
11124 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11125 org-mark-ring)
11127 (defun org-mark-ring-push (&optional pos buffer)
11128 "Put the current position or POS into the mark ring and rotate it."
11129 (interactive)
11130 (setq pos (or pos (point)))
11131 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11132 (move-marker (car org-mark-ring)
11133 (or pos (point))
11134 (or buffer (current-buffer)))
11135 (message "%s"
11136 (substitute-command-keys
11137 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11139 (defun org-mark-ring-goto (&optional n)
11140 "Jump to the previous position in the mark ring.
11141 With prefix arg N, jump back that many stored positions. When
11142 called several times in succession, walk through the entire ring.
11143 Org-mode commands jumping to a different position in the current file,
11144 or to another Org-mode file, automatically push the old position
11145 onto the ring."
11146 (interactive "p")
11147 (let (p m)
11148 (if (eq last-command this-command)
11149 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11150 (setq p org-mark-ring))
11151 (setq org-mark-ring-last-goto p)
11152 (setq m (car p))
11153 (org-pop-to-buffer-same-window (marker-buffer m))
11154 (goto-char m)
11155 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11157 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11158 ;;; Emacs 24.4+
11159 (defun org-remove-angle-brackets (s)
11160 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11161 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11163 (defun org-add-angle-brackets (s)
11164 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11165 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11167 (defun org-remove-double-quotes (s)
11168 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11169 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11172 ;;; Following specific links
11174 (defvar org-agenda-buffer-tmp-name)
11175 (defvar org-agenda-start-on-weekday)
11176 (defun org-follow-timestamp-link ()
11177 "Open an agenda view for the time-stamp date/range at point."
11178 (cond
11179 ((org-at-date-range-p t)
11180 (let ((org-agenda-start-on-weekday)
11181 (t1 (match-string 1))
11182 (t2 (match-string 2)) tt1 tt2)
11183 (setq tt1 (time-to-days (org-time-string-to-time t1))
11184 tt2 (time-to-days (org-time-string-to-time t2)))
11185 (let ((org-agenda-buffer-tmp-name
11186 (format "*Org Agenda(a:%s)"
11187 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11188 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11189 ((org-at-timestamp-p t)
11190 (let ((org-agenda-buffer-tmp-name
11191 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11192 (org-agenda-list nil (time-to-days (org-time-string-to-time
11193 (substring (match-string 1) 0 10)))
11194 1)))
11195 (t (error "This should not happen"))))
11198 ;;; Following file links
11199 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11200 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11201 (declare-function mailcap-mime-info
11202 "mailcap" (string &optional request no-decode))
11203 (defvar org-wait nil)
11204 (defun org-open-file (path &optional in-emacs line search)
11205 "Open the file at PATH.
11206 First, this expands any special file name abbreviations. Then the
11207 configuration variable `org-file-apps' is checked if it contains an
11208 entry for this file type, and if yes, the corresponding command is launched.
11210 If no application is found, Emacs simply visits the file.
11212 With optional prefix argument IN-EMACS, Emacs will visit the file.
11213 With a double \\[universal-argument] \\[universal-argument] \
11214 prefix arg, Org tries to avoid opening in Emacs
11215 and to use an external application to visit the file.
11217 Optional LINE specifies a line to go to, optional SEARCH a string
11218 to search for. If LINE or SEARCH is given, the file will be
11219 opened in Emacs, unless an entry from org-file-apps that makes
11220 use of groups in a regexp matches.
11222 If you want to change the way frames are used when following a
11223 link, please customize `org-link-frame-setup'.
11225 If the file does not exist, an error is thrown."
11226 (let* ((file (if (equal path "")
11227 buffer-file-name
11228 (substitute-in-file-name (expand-file-name path))))
11229 (file-apps (append org-file-apps (org-default-apps)))
11230 (apps (cl-remove-if
11231 'org-file-apps-entry-match-against-dlink-p file-apps))
11232 (apps-dlink (cl-remove-if-not
11233 'org-file-apps-entry-match-against-dlink-p file-apps))
11234 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11235 (dirp (unless remp (file-directory-p file)))
11236 (file (if (and dirp org-open-directory-means-index-dot-org)
11237 (concat (file-name-as-directory file) "index.org")
11238 file))
11239 (a-m-a-p (assq 'auto-mode apps))
11240 (dfile (downcase file))
11241 ;; Reconstruct the original link from the PATH, LINE and
11242 ;; SEARCH args.
11243 (link (cond (line (concat file "::" (number-to-string line)))
11244 (search (concat file "::" search))
11245 (t file)))
11246 (dlink (downcase link))
11247 (old-buffer (current-buffer))
11248 (old-pos (point))
11249 (old-mode major-mode)
11250 (ext
11251 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11252 (match-string 1 dfile)))
11253 cmd link-match-data)
11254 (cond
11255 ((member in-emacs '((16) system))
11256 (setq cmd (cdr (assq 'system apps))))
11257 (in-emacs (setq cmd 'emacs))
11259 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11260 (and dirp (cdr (assq 'directory apps)))
11261 ;; First, try matching against apps-dlink if we
11262 ;; get a match here, store the match data for
11263 ;; later.
11264 (let ((match (assoc-default dlink apps-dlink
11265 'string-match)))
11266 (if match
11267 (progn (setq link-match-data (match-data))
11268 match)
11269 (progn (setq in-emacs (or in-emacs line search))
11270 nil))) ; if we have no match in apps-dlink,
11271 ; always open the file in emacs if line or search
11272 ; is given (for backwards compatibility)
11273 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11274 'string-match)
11275 (cdr (assoc ext apps))
11276 (cdr (assq t apps))))))
11277 (when (eq cmd 'system)
11278 (setq cmd (cdr (assoc 'system apps))))
11279 (when (eq cmd 'default)
11280 (setq cmd (cdr (assoc t apps))))
11281 (when (eq cmd 'mailcap)
11282 (require 'mailcap)
11283 (mailcap-parse-mailcaps)
11284 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11285 (command (mailcap-mime-info mime-type)))
11286 (if (stringp command)
11287 (setq cmd command)
11288 (setq cmd 'emacs))))
11289 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11290 (not (file-exists-p file))
11291 (not org-open-non-existing-files))
11292 (user-error "No such file: %s" file))
11293 (cond
11294 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11295 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11296 (while (string-match "['\"]%s['\"]" cmd)
11297 (setq cmd (replace-match "%s" t t cmd)))
11298 (while (string-match "%s" cmd)
11299 (setq cmd (replace-match
11300 (save-match-data
11301 (shell-quote-argument
11302 (convert-standard-filename file)))
11303 t t cmd)))
11305 ;; Replace "%1", "%2" etc. in command with group matches from regex
11306 (save-match-data
11307 (let ((match-index 1)
11308 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11309 (set-match-data link-match-data)
11310 (while (<= match-index number-of-groups)
11311 (let ((regex (concat "%" (number-to-string match-index)))
11312 (replace-with (match-string match-index dlink)))
11313 (while (string-match regex cmd)
11314 (setq cmd (replace-match replace-with t t cmd))))
11315 (setq match-index (+ match-index 1)))))
11317 (save-window-excursion
11318 (message "Running %s...done" cmd)
11319 (start-process-shell-command cmd nil cmd)
11320 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11321 ((or (stringp cmd)
11322 (eq cmd 'emacs))
11323 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11324 (widen)
11325 (cond (line (org-goto-line line)
11326 (when (derived-mode-p 'org-mode) (org-reveal)))
11327 (search (org-link-search search))))
11328 ((functionp cmd)
11329 (save-match-data
11330 (set-match-data link-match-data)
11331 (condition-case nil
11332 (funcall cmd file link)
11333 ;; FIXME: Remove this check when most default installations
11334 ;; of Emacs have at least Org 9.0.
11335 ((debug wrong-number-of-arguments wrong-type-argument
11336 invalid-function)
11337 (user-error "Please see Org News for version 9.0 about \
11338 `org-file-apps'--Lisp error: %S" cmd)))))
11339 ((consp cmd)
11340 ;; FIXME: Remove this check when most default installations of
11341 ;; Emacs have at least Org 9.0.
11342 ;; Heads-up instead of silently fall back to
11343 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11344 ;; with sexp instead of a function for `cmd'.
11345 (user-error "Please see Org News for version 9.0 about \
11346 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11347 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11348 (and (derived-mode-p 'org-mode)
11349 (eq old-mode 'org-mode)
11350 (or (not (eq old-buffer (current-buffer)))
11351 (not (eq old-pos (point))))
11352 (org-mark-ring-push old-pos old-buffer))))
11354 (defun org-file-apps-entry-match-against-dlink-p (entry)
11355 "This function returns non-nil if `entry' uses a regular
11356 expression which should be matched against the whole link by
11357 org-open-file.
11359 It assumes that is the case when the entry uses a regular
11360 expression which has at least one grouping construct and the
11361 action is either a lisp form or a command string containing
11362 `%1', i.e. using at least one subexpression match as a
11363 parameter."
11364 (let ((selector (car entry))
11365 (action (cdr entry)))
11366 (if (stringp selector)
11367 (and (> (regexp-opt-depth selector) 0)
11368 (or (and (stringp action)
11369 (string-match "%[0-9]" action))
11370 (consp action)))
11371 nil)))
11373 (defun org-default-apps ()
11374 "Return the default applications for this operating system."
11375 (cond
11376 ((eq system-type 'darwin)
11377 org-file-apps-defaults-macosx)
11378 ((eq system-type 'windows-nt)
11379 org-file-apps-defaults-windowsnt)
11380 (t org-file-apps-defaults-gnu)))
11382 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11383 "Convert extensions to regular expressions in the cars of LIST.
11384 Also, weed out any non-string entries, because the return value is used
11385 only for regexp matching.
11386 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11387 point to the symbol `emacs', indicating that the file should
11388 be opened in Emacs."
11389 (append
11390 (delq nil
11391 (mapcar (lambda (x)
11392 (unless (not (stringp (car x)))
11393 (if (string-match "\\W" (car x))
11395 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11396 list))
11397 (when add-auto-mode
11398 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11400 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11401 (defun org-file-remote-p (file)
11402 "Test whether FILE specifies a location on a remote system.
11403 Return non-nil if the location is indeed remote.
11405 For example, the filename \"/user@host:/foo\" specifies a location
11406 on the system \"/user@host:\"."
11407 (cond ((fboundp 'file-remote-p)
11408 (file-remote-p file))
11409 ((fboundp 'tramp-handle-file-remote-p)
11410 (tramp-handle-file-remote-p file))
11411 ((and (boundp 'ange-ftp-name-format)
11412 (string-match (car ange-ftp-name-format) file))
11413 t)))
11416 ;;;; Refiling
11418 (defun org-get-org-file ()
11419 "Read a filename, with default directory `org-directory'."
11420 (let ((default (or org-default-notes-file remember-data-file)))
11421 (read-file-name (format "File name [%s]: " default)
11422 (file-name-as-directory org-directory)
11423 default)))
11425 (defun org-notes-order-reversed-p ()
11426 "Check if the current file should receive notes in reversed order."
11427 (cond
11428 ((not org-reverse-note-order) nil)
11429 ((eq t org-reverse-note-order) t)
11430 ((not (listp org-reverse-note-order)) nil)
11431 (t (catch 'exit
11432 (dolist (entry org-reverse-note-order)
11433 (when (string-match (car entry) buffer-file-name)
11434 (throw 'exit (cdr entry))))))))
11436 (defvar org-refile-target-table nil
11437 "The list of refile targets, created by `org-refile'.")
11439 (defvar org-agenda-new-buffers nil
11440 "Buffers created to visit agenda files.")
11442 (defvar org-refile-cache nil
11443 "Cache for refile targets.")
11445 (defvar org-refile-markers nil
11446 "All the markers used for caching refile locations.")
11448 (defun org-refile-marker (pos)
11449 "Get a new refile marker, but only if caching is in use."
11450 (if (not org-refile-use-cache)
11452 (let ((m (make-marker)))
11453 (move-marker m pos)
11454 (push m org-refile-markers)
11455 m)))
11457 (defun org-refile-cache-clear ()
11458 "Clear the refile cache and disable all the markers."
11459 (dolist (m org-refile-markers) (move-marker m nil))
11460 (setq org-refile-markers nil)
11461 (setq org-refile-cache nil)
11462 (message "Refile cache has been cleared"))
11464 (defun org-refile-cache-check-set (set)
11465 "Check if all the markers in the cache still have live buffers."
11466 (let (marker)
11467 (catch 'exit
11468 (while (and set (setq marker (nth 3 (pop set))))
11469 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11470 (when (and marker (null (marker-buffer marker)))
11471 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11472 (sit-for 3)
11473 (throw 'exit nil)))
11474 t)))
11476 (defun org-refile-cache-put (set &rest identifiers)
11477 "Push the refile targets SET into the cache, under IDENTIFIERS."
11478 (let* ((key (sha1 (prin1-to-string identifiers)))
11479 (entry (assoc key org-refile-cache)))
11480 (if entry
11481 (setcdr entry set)
11482 (push (cons key set) org-refile-cache))))
11484 (defun org-refile-cache-get (&rest identifiers)
11485 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11486 (cond
11487 ((not org-refile-cache) nil)
11488 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11490 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11491 org-refile-cache))))
11492 (and set (org-refile-cache-check-set set) set)))))
11494 (defvar org-outline-path-cache nil
11495 "Alist between buffer positions and outline paths.
11496 It value is an alist (POSITION . PATH) where POSITION is the
11497 buffer position at the beginning of an entry and PATH is a list
11498 of strings describing the outline path for that entry, in reverse
11499 order.")
11501 (defun org-refile-get-targets (&optional default-buffer)
11502 "Produce a table with refile targets."
11503 (let ((case-fold-search nil)
11504 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11505 (entries (or org-refile-targets '((nil . (:level . 1)))))
11506 targets tgs files desc descre)
11507 (message "Getting targets...")
11508 (with-current-buffer (or default-buffer (current-buffer))
11509 (dolist (entry entries)
11510 (setq files (car entry) desc (cdr entry))
11511 (cond
11512 ((null files) (setq files (list (current-buffer))))
11513 ((eq files 'org-agenda-files)
11514 (setq files (org-agenda-files 'unrestricted)))
11515 ((and (symbolp files) (fboundp files))
11516 (setq files (funcall files)))
11517 ((and (symbolp files) (boundp files))
11518 (setq files (symbol-value files))))
11519 (when (stringp files) (setq files (list files)))
11520 (cond
11521 ((eq (car desc) :tag)
11522 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11523 ((eq (car desc) :todo)
11524 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11525 ((eq (car desc) :regexp)
11526 (setq descre (cdr desc)))
11527 ((eq (car desc) :level)
11528 (setq descre (concat "^\\*\\{" (number-to-string
11529 (if org-odd-levels-only
11530 (1- (* 2 (cdr desc)))
11531 (cdr desc)))
11532 "\\}[ \t]")))
11533 ((eq (car desc) :maxlevel)
11534 (setq descre (concat "^\\*\\{1," (number-to-string
11535 (if org-odd-levels-only
11536 (1- (* 2 (cdr desc)))
11537 (cdr desc)))
11538 "\\}[ \t]")))
11539 (t (error "Bad refiling target description %s" desc)))
11540 (dolist (f files)
11541 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11543 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11544 (progn
11545 (when (bufferp f)
11546 (setq f (buffer-file-name (buffer-base-buffer f))))
11547 (setq f (and f (expand-file-name f)))
11548 (when (eq org-refile-use-outline-path 'file)
11549 (push (list (file-name-nondirectory f) f nil nil) tgs))
11550 (org-with-wide-buffer
11551 (goto-char (point-min))
11552 (setq org-outline-path-cache nil)
11553 (while (re-search-forward descre nil t)
11554 (beginning-of-line)
11555 (looking-at org-complex-heading-regexp)
11556 (let ((begin (point))
11557 (heading (org-match-string-no-properties 4)))
11558 (unless (or (and
11559 org-refile-target-verify-function
11560 (not
11561 (funcall org-refile-target-verify-function)))
11562 (not heading))
11563 (let ((re (format org-complex-heading-regexp-format
11564 (regexp-quote heading)))
11565 (target
11566 (if (not org-refile-use-outline-path) heading
11567 (mapconcat
11568 #'org-protect-slash
11569 (append
11570 (pcase org-refile-use-outline-path
11571 (`file (list (file-name-nondirectory
11572 (buffer-file-name
11573 (buffer-base-buffer)))))
11574 (`full-file-path
11575 (list (buffer-file-name
11576 (buffer-base-buffer))))
11577 (_ nil))
11578 (org-get-outline-path t t))
11579 "/"))))
11580 (push (list target f re (org-refile-marker (point)))
11581 tgs)))
11582 (when (= (point) begin)
11583 ;; Verification function has not moved point.
11584 (end-of-line)))))))
11585 (when org-refile-use-cache
11586 (org-refile-cache-put tgs (buffer-file-name) descre))
11587 (setq targets (append tgs targets))))))
11588 (message "Getting targets...done")
11589 (nreverse targets)))
11591 (defun org-protect-slash (s)
11592 (while (string-match "/" s)
11593 (setq s (replace-match "\\" t t s)))
11596 (defun org--get-outline-path-1 (&optional use-cache)
11597 "Return outline path to current headline.
11599 Outline path is a list of strings, in reverse order. When
11600 optional argument USE-CACHE is non-nil, make use of a cache. See
11601 `org-get-outline-path' for details.
11603 Assume buffer is widened and point is on a headline."
11604 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11605 (let ((p (point))
11606 (heading (progn
11607 (looking-at org-complex-heading-regexp)
11608 (if (not (match-end 4)) ""
11609 ;; Remove statistics cookies.
11610 (org-trim
11611 (org-link-display-format
11612 (replace-regexp-in-string
11613 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11614 (org-match-string-no-properties 4))))))))
11615 (if (org-up-heading-safe)
11616 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11617 (when use-cache
11618 (push (cons p path) org-outline-path-cache))
11619 path)
11620 ;; This is a new root node. Since we assume we are moving
11621 ;; forward, we can drop previous cache so as to limit number
11622 ;; of associations there.
11623 (let ((path (list heading)))
11624 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11625 path)))))
11627 (defun org-get-outline-path (&optional with-self use-cache)
11628 "Return the outline path to the current entry.
11630 An outline path is a list of ancestors for current headline, as
11631 a list of strings. Statistics cookies are removed and links are
11632 replaced with their description, if any, or their path otherwise.
11634 When optional argument WITH-SELF is non-nil, the path also
11635 includes the current headline.
11637 When optional argument USE-CACHE is non-nil, cache outline paths
11638 between calls to this function so as to avoid backtracking. This
11639 argument is useful when planning to find more than one outline
11640 path in the same document. In that case, there are two
11641 conditions to satisfy:
11642 - `org-outline-path-cache' is set to nil before starting the
11643 process;
11644 - outline paths are computed by increasing buffer positions."
11645 (org-with-wide-buffer
11646 (and (or (and with-self (org-back-to-heading t))
11647 (org-up-heading-safe))
11648 (reverse (org--get-outline-path-1 use-cache)))))
11650 (defun org-format-outline-path (path &optional width prefix separator)
11651 "Format the outline path PATH for display.
11652 WIDTH is the maximum number of characters that is available.
11653 PREFIX is a prefix to be included in the returned string,
11654 such as the file name.
11655 SEPARATOR is inserted between the different parts of the path,
11656 the default is \"/\"."
11657 (setq width (or width 79))
11658 (setq path (delq nil path))
11659 (unless (> width 0)
11660 (user-error "Argument `width' must be positive"))
11661 (setq separator (or separator "/"))
11662 (let* ((org-odd-levels-only nil)
11663 (fpath (concat
11664 prefix (and prefix path separator)
11665 (mapconcat
11666 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11667 (cl-loop for head in path
11668 for n from 0
11669 collect (org-add-props
11670 head nil 'face
11671 (nth (% n org-n-level-faces) org-level-faces)))
11672 separator))))
11673 (when (> (length fpath) width)
11674 (if (< width 7)
11675 ;; It's unlikely that `width' will be this small, but don't
11676 ;; waste characters by adding ".." if it is.
11677 (setq fpath (substring fpath 0 width))
11678 (setf (substring fpath (- width 2)) "..")))
11679 fpath))
11681 (defun org-display-outline-path (&optional file current separator just-return-string)
11682 "Display the current outline path in the echo area.
11684 If FILE is non-nil, prepend the output with the file name.
11685 If CURRENT is non-nil, append the current heading to the output.
11686 SEPARATOR is passed through to `org-format-outline-path'. It separates
11687 the different parts of the path and defaults to \"/\".
11688 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11689 (interactive "P")
11690 (let* (case-fold-search
11691 (bfn (buffer-file-name (buffer-base-buffer)))
11692 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11693 res)
11694 (when current (setq path (append path
11695 (save-excursion
11696 (org-back-to-heading t)
11697 (when (looking-at org-complex-heading-regexp)
11698 (list (match-string 4)))))))
11699 (setq res
11700 (org-format-outline-path
11701 path
11702 (1- (frame-width))
11703 (and file bfn (concat (file-name-nondirectory bfn) separator))
11704 separator))
11705 (if just-return-string
11706 (org-no-properties res)
11707 (org-unlogged-message "%s" res))))
11709 (defvar org-refile-history nil
11710 "History for refiling operations.")
11712 (defvar org-after-refile-insert-hook nil
11713 "Hook run after `org-refile' has inserted its stuff at the new location.
11714 Note that this is still *before* the stuff will be removed from
11715 the *old* location.")
11717 (defvar org-capture-last-stored-marker)
11718 (defvar org-refile-keep nil
11719 "Non-nil means `org-refile' will copy instead of refile.")
11721 (defun org-copy ()
11722 "Like `org-refile', but copy."
11723 (interactive)
11724 (let ((org-refile-keep t))
11725 (funcall 'org-refile nil nil nil "Copy")))
11727 (defun org-refile (&optional arg default-buffer rfloc msg)
11728 "Move the entry or entries at point to another heading.
11729 The list of target headings is compiled using the information in
11730 `org-refile-targets', which see.
11732 At the target location, the entry is filed as a subitem of the
11733 target heading. Depending on `org-reverse-note-order', the new
11734 subitem will either be the first or the last subitem.
11736 If there is an active region, all entries in that region will be
11737 refiled. However, the region must fulfill the requirement that
11738 the first heading sets the top-level of the moved text.
11740 With prefix arg ARG, the command will only visit the target
11741 location and not actually move anything.
11743 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11744 refiling operation has put the subtree.
11746 With a numeric prefix argument of `2', refile to the running clock.
11748 With a numeric prefix argument of `3', emulate `org-refile-keep'
11749 being set to t and copy to the target location, don't move it.
11750 Beware that keeping refiled entries may result in duplicated ID
11751 properties.
11753 RFLOC can be a refile location obtained in a different way.
11755 MSG is a string to replace \"Refile\" in the default prompt with
11756 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11758 See also `org-refile-use-outline-path'.
11760 If you are using target caching (see `org-refile-use-cache'), you
11761 have to clear the target cache in order to find new targets.
11762 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11763 prefix argument (`C-u C-u C-u C-c C-w')."
11764 (interactive "P")
11765 (if (member arg '(0 (64)))
11766 (org-refile-cache-clear)
11767 (let* ((actionmsg (cond (msg msg)
11768 ((equal arg 3) "Refile (and keep)")
11769 (t "Refile")))
11770 (regionp (org-region-active-p))
11771 (region-start (and regionp (region-beginning)))
11772 (region-end (and regionp (region-end)))
11773 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11774 pos it nbuf file level reversed)
11775 (setq last-command nil)
11776 (when regionp
11777 (goto-char region-start)
11778 (or (bolp) (goto-char (point-at-bol)))
11779 (setq region-start (point))
11780 (unless (or (org-kill-is-subtree-p
11781 (buffer-substring region-start region-end))
11782 (prog1 org-refile-active-region-within-subtree
11783 (let ((s (point-at-eol)))
11784 (org-toggle-heading)
11785 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11786 (user-error "The region is not a (sequence of) subtree(s)")))
11787 (if (equal arg '(16))
11788 (org-refile-goto-last-stored)
11789 (when (or
11790 (and (equal arg 2)
11791 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11792 (prog1
11793 (setq it (list (or org-clock-heading "running clock")
11794 (buffer-file-name
11795 (marker-buffer org-clock-hd-marker))
11797 (marker-position org-clock-hd-marker)))
11798 (setq arg nil)))
11799 (setq it
11800 (or rfloc
11801 (let (heading-text)
11802 (save-excursion
11803 (unless (and arg (listp arg))
11804 (org-back-to-heading t)
11805 (setq heading-text
11806 (replace-regexp-in-string
11807 org-bracket-link-regexp
11808 "\\3"
11809 (nth 4 (org-heading-components)))))
11810 (org-refile-get-location
11811 (cond ((and arg (listp arg)) "Goto")
11812 (regionp (concat actionmsg " region to"))
11813 (t (concat actionmsg " subtree \""
11814 heading-text "\" to")))
11815 default-buffer
11816 (and (not (equal '(4) arg))
11817 org-refile-allow-creating-parent-nodes)))))))
11818 (setq file (nth 1 it)
11819 pos (nth 3 it))
11820 (when (and (not arg)
11822 (equal (buffer-file-name) file)
11823 (if regionp
11824 (and (>= pos region-start)
11825 (<= pos region-end))
11826 (and (>= pos (point))
11827 (< pos (save-excursion
11828 (org-end-of-subtree t t))))))
11829 (error "Cannot refile to position inside the tree or region"))
11830 (setq nbuf (or (find-buffer-visiting file)
11831 (find-file-noselect file)))
11832 (if (and arg (not (equal arg 3)))
11833 (progn
11834 (org-pop-to-buffer-same-window nbuf)
11835 (goto-char pos)
11836 (org-show-context 'org-goto))
11837 (if regionp
11838 (progn
11839 (org-kill-new (buffer-substring region-start region-end))
11840 (org-save-markers-in-region region-start region-end))
11841 (org-copy-subtree 1 nil t))
11842 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11843 (find-file-noselect file)))
11844 (setq reversed (org-notes-order-reversed-p))
11845 (save-excursion
11846 (save-restriction
11847 (widen)
11848 (if pos
11849 (progn
11850 (goto-char pos)
11851 (looking-at org-outline-regexp)
11852 (setq level (org-get-valid-level (funcall outline-level) 1))
11853 (goto-char
11854 (if reversed
11855 (or (outline-next-heading) (point-max))
11856 (or (save-excursion (org-get-next-sibling))
11857 (org-end-of-subtree t t)
11858 (point-max)))))
11859 (setq level 1)
11860 (if (not reversed)
11861 (goto-char (point-max))
11862 (goto-char (point-min))
11863 (or (outline-next-heading) (goto-char (point-max)))))
11864 (unless (bolp) (newline))
11865 (org-paste-subtree level nil nil t)
11866 (when org-log-refile
11867 (org-add-log-setup 'refile nil nil org-log-refile)
11868 (unless (eq org-log-refile 'note)
11869 (save-excursion (org-add-log-note))))
11870 (and org-auto-align-tags
11871 (let ((org-loop-over-headlines-in-active-region nil))
11872 (org-set-tags nil t)))
11873 (let ((bookmark-name (plist-get org-bookmark-names-plist
11874 :last-refile)))
11875 (when bookmark-name
11876 (with-demoted-errors
11877 (bookmark-set bookmark-name))))
11878 ;; If we are refiling for capture, make sure that the
11879 ;; last-capture pointers point here
11880 (when (org-bound-and-true-p org-capture-is-refiling)
11881 (let ((bookmark-name (plist-get org-bookmark-names-plist
11882 :last-capture-marker)))
11883 (when bookmark-name
11884 (with-demoted-errors
11885 (bookmark-set bookmark-name))))
11886 (move-marker org-capture-last-stored-marker (point)))
11887 (when (fboundp 'deactivate-mark) (deactivate-mark))
11888 (run-hooks 'org-after-refile-insert-hook))))
11889 (unless org-refile-keep
11890 (if regionp
11891 (delete-region (point) (+ (point) (- region-end region-start)))
11892 (delete-region
11893 (and (org-back-to-heading t) (point))
11894 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11895 (when (featurep 'org-inlinetask)
11896 (org-inlinetask-remove-END-maybe))
11897 (setq org-markers-to-move nil)
11898 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11900 (defun org-refile-goto-last-stored ()
11901 "Go to the location where the last refile was stored."
11902 (interactive)
11903 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11904 (message "This is the location of the last refile"))
11906 (defun org-refile--get-location (refloc tbl)
11907 "When user refile to REFLOC, find the associated target in TBL.
11908 Also check `org-refile-target-table'."
11909 (car (delq
11911 (mapcar
11912 (lambda (r) (or (assoc r tbl)
11913 (assoc r org-refile-target-table)))
11914 (list (replace-regexp-in-string "/$" "" refloc)
11915 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11917 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11918 "Prompt the user for a refile location, using PROMPT.
11919 PROMPT should not be suffixed with a colon and a space, because
11920 this function appends the default value from
11921 `org-refile-history' automatically, if that is not empty."
11922 (let ((org-refile-targets org-refile-targets)
11923 (org-refile-use-outline-path org-refile-use-outline-path))
11924 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11925 (unless org-refile-target-table
11926 (user-error "No refile targets"))
11927 (let* ((cbuf (current-buffer))
11928 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11929 (cfunc (if (and org-refile-use-outline-path
11930 org-outline-path-complete-in-steps)
11931 #'org-olpath-completing-read
11932 #'completing-read))
11933 (extra (if org-refile-use-outline-path "/" ""))
11934 (cbnex (concat (buffer-name) extra))
11935 (filename (and cfn (expand-file-name cfn)))
11936 (tbl (mapcar
11937 (lambda (x)
11938 (if (and (not (member org-refile-use-outline-path
11939 '(file full-file-path)))
11940 (not (equal filename (nth 1 x))))
11941 (cons (concat (car x) extra " ("
11942 (file-name-nondirectory (nth 1 x)) ")")
11943 (cdr x))
11944 (cons (concat (car x) extra) (cdr x))))
11945 org-refile-target-table))
11946 (completion-ignore-case t)
11947 cdef
11948 (prompt (concat prompt
11949 (or (and (car org-refile-history)
11950 (concat " (default " (car org-refile-history) ")"))
11951 (and (assoc cbnex tbl) (setq cdef cbnex)
11952 (concat " (default " cbnex ")"))) ": "))
11953 pa answ parent-target child parent old-hist)
11954 (setq old-hist org-refile-history)
11955 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11956 nil 'org-refile-history (or cdef (car org-refile-history))))
11957 (if (setq pa (org-refile--get-location answ tbl))
11958 (progn
11959 (org-refile-check-position pa)
11960 (when (or (not org-refile-history)
11961 (not (eq old-hist org-refile-history))
11962 (not (equal (car pa) (car org-refile-history))))
11963 (setq org-refile-history
11964 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11965 org-refile-history
11966 (cdr org-refile-history))))
11967 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11968 (pop org-refile-history)))
11970 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11971 (progn
11972 (setq parent (match-string 1 answ)
11973 child (match-string 2 answ))
11974 (setq parent-target (org-refile--get-location parent tbl))
11975 (when (and parent-target
11976 (or (eq new-nodes t)
11977 (and (eq new-nodes 'confirm)
11978 (y-or-n-p (format "Create new node \"%s\"? "
11979 child)))))
11980 (org-refile-new-child parent-target child)))
11981 (user-error "Invalid target location")))))
11983 (declare-function org-string-nw-p "org-macs" (s))
11984 (defun org-refile-check-position (refile-pointer)
11985 "Check if the refile pointer matches the headline to which it points."
11986 (let* ((file (nth 1 refile-pointer))
11987 (re (nth 2 refile-pointer))
11988 (pos (nth 3 refile-pointer))
11989 buffer)
11990 (if (and (not (markerp pos)) (not file))
11991 (user-error "Please indicate a target file in the refile path")
11992 (when (org-string-nw-p re)
11993 (setq buffer (if (markerp pos)
11994 (marker-buffer pos)
11995 (or (find-buffer-visiting file)
11996 (find-file-noselect file))))
11997 (with-current-buffer buffer
11998 (save-excursion
11999 (save-restriction
12000 (widen)
12001 (goto-char pos)
12002 (beginning-of-line 1)
12003 (unless (org-looking-at-p re)
12004 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12006 (defun org-refile-new-child (parent-target child)
12007 "Use refile target PARENT-TARGET to add new CHILD below it."
12008 (unless parent-target
12009 (error "Cannot find parent for new node"))
12010 (let ((file (nth 1 parent-target))
12011 (pos (nth 3 parent-target))
12012 level)
12013 (with-current-buffer (or (find-buffer-visiting file)
12014 (find-file-noselect file))
12015 (save-excursion
12016 (save-restriction
12017 (widen)
12018 (if pos
12019 (goto-char pos)
12020 (goto-char (point-max))
12021 (unless (bolp) (newline)))
12022 (when (looking-at org-outline-regexp)
12023 (setq level (funcall outline-level))
12024 (org-end-of-subtree t t))
12025 (org-back-over-empty-lines)
12026 (insert "\n" (make-string
12027 (if pos (org-get-valid-level level 1) 1) ?*)
12028 " " child "\n")
12029 (beginning-of-line 0)
12030 (list (concat (car parent-target) "/" child) file "" (point)))))))
12032 (defun org-olpath-completing-read (prompt collection &rest args)
12033 "Read an outline path like a file name."
12034 (let ((thetable collection))
12035 (apply #'completing-read
12036 prompt
12037 (lambda (string predicate &optional flag)
12038 (cond
12039 ((eq flag nil) (try-completion string thetable))
12040 ((eq flag t)
12041 (let ((l (length string)))
12042 (mapcar (lambda (x)
12043 (let ((r (substring x l))
12044 (f (if (string-match " ([^)]*)$" x)
12045 (match-string 0 x)
12046 "")))
12047 (if (string-match "/" r)
12048 (concat string (substring r 0 (match-end 0)) f)
12049 x)))
12050 (all-completions string thetable predicate))))
12051 ;; Exact match?
12052 ((eq flag 'lambda) (assoc string thetable))))
12053 args)))
12055 ;;;; Dynamic blocks
12057 (defun org-find-dblock (name)
12058 "Find the first dynamic block with name NAME in the buffer.
12059 If not found, stay at current position and return nil."
12060 (let ((case-fold-search t) pos)
12061 (save-excursion
12062 (goto-char (point-min))
12063 (setq pos (and (re-search-forward
12064 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12065 (match-beginning 0))))
12066 (when pos (goto-char pos))
12067 pos))
12069 (defun org-create-dblock (plist)
12070 "Create a dynamic block section, with parameters taken from PLIST.
12071 PLIST must contain a :name entry which is used as the name of the block."
12072 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12073 (end-of-line 1)
12074 (newline))
12075 (let ((col (current-column))
12076 (name (plist-get plist :name)))
12077 (insert "#+BEGIN: " name)
12078 (while plist
12079 (if (eq (car plist) :name)
12080 (setq plist (cddr plist))
12081 (insert " " (prin1-to-string (pop plist)))))
12082 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12083 (beginning-of-line -2)))
12085 (defun org-prepare-dblock ()
12086 "Prepare dynamic block for refresh.
12087 This empties the block, puts the cursor at the insert position and returns
12088 the property list including an extra property :name with the block name."
12089 (unless (looking-at org-dblock-start-re)
12090 (user-error "Not at a dynamic block"))
12091 (let* ((begdel (1+ (match-end 0)))
12092 (name (org-no-properties (match-string 1)))
12093 (params (append (list :name name)
12094 (read (concat "(" (match-string 3) ")")))))
12095 (save-excursion
12096 (beginning-of-line 1)
12097 (skip-chars-forward " \t")
12098 (setq params (plist-put params :indentation-column (current-column))))
12099 (unless (re-search-forward org-dblock-end-re nil t)
12100 (error "Dynamic block not terminated"))
12101 (setq params
12102 (append params
12103 (list :content (buffer-substring
12104 begdel (match-beginning 0)))))
12105 (delete-region begdel (match-beginning 0))
12106 (goto-char begdel)
12107 (open-line 1)
12108 params))
12110 (defun org-map-dblocks (&optional command)
12111 "Apply COMMAND to all dynamic blocks in the current buffer.
12112 If COMMAND is not given, use `org-update-dblock'."
12113 (let ((cmd (or command 'org-update-dblock)))
12114 (save-excursion
12115 (goto-char (point-min))
12116 (while (re-search-forward org-dblock-start-re nil t)
12117 (goto-char (match-beginning 0))
12118 (save-excursion
12119 (condition-case nil
12120 (funcall cmd)
12121 (error (message "Error during update of dynamic block"))))
12122 (unless (re-search-forward org-dblock-end-re nil t)
12123 (error "Dynamic block not terminated"))))))
12125 (defun org-dblock-update (&optional arg)
12126 "User command for updating dynamic blocks.
12127 Update the dynamic block at point. With prefix ARG, update all dynamic
12128 blocks in the buffer."
12129 (interactive "P")
12130 (if arg
12131 (org-update-all-dblocks)
12132 (or (looking-at org-dblock-start-re)
12133 (org-beginning-of-dblock))
12134 (org-update-dblock)))
12136 (defun org-update-dblock ()
12137 "Update the dynamic block at point.
12138 This means to empty the block, parse for parameters and then call
12139 the correct writing function."
12140 (interactive)
12141 (save-excursion
12142 (let* ((win (selected-window))
12143 (pos (point))
12144 (line (org-current-line))
12145 (params (org-prepare-dblock))
12146 (name (plist-get params :name))
12147 (indent (plist-get params :indentation-column))
12148 (cmd (intern (concat "org-dblock-write:" name))))
12149 (message "Updating dynamic block `%s' at line %d..." name line)
12150 (funcall cmd params)
12151 (message "Updating dynamic block `%s' at line %d...done" name line)
12152 (goto-char pos)
12153 (when (and indent (> indent 0))
12154 (setq indent (make-string indent ?\ ))
12155 (save-excursion
12156 (select-window win)
12157 (org-beginning-of-dblock)
12158 (forward-line 1)
12159 (while (not (looking-at org-dblock-end-re))
12160 (insert indent)
12161 (beginning-of-line 2))
12162 (when (looking-at org-dblock-end-re)
12163 (and (looking-at "[ \t]+")
12164 (replace-match ""))
12165 (insert indent)))))))
12167 (defun org-beginning-of-dblock ()
12168 "Find the beginning of the dynamic block at point.
12169 Error if there is no such block at point."
12170 (let ((pos (point))
12171 beg)
12172 (end-of-line 1)
12173 (if (and (re-search-backward org-dblock-start-re nil t)
12174 (setq beg (match-beginning 0))
12175 (re-search-forward org-dblock-end-re nil t)
12176 (> (match-end 0) pos))
12177 (goto-char beg)
12178 (goto-char pos)
12179 (error "Not in a dynamic block"))))
12181 (defun org-update-all-dblocks ()
12182 "Update all dynamic blocks in the buffer.
12183 This function can be used in a hook."
12184 (interactive)
12185 (when (derived-mode-p 'org-mode)
12186 (org-map-dblocks 'org-update-dblock)))
12189 ;;;; Completion
12191 (declare-function org-export-backend-name "org-export" (cl-x))
12192 (declare-function org-export-backend-options "org-export" (cl-x))
12193 (defun org-get-export-keywords ()
12194 "Return a list of all currently understood export keywords.
12195 Export keywords include options, block names, attributes and
12196 keywords relative to each registered export back-end."
12197 (let (keywords)
12198 (dolist (backend
12199 (org-bound-and-true-p org-export-registered-backends)
12200 (delq nil keywords))
12201 ;; Back-end name (for keywords, like #+LATEX:)
12202 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12203 (dolist (option-entry (org-export-backend-options backend))
12204 ;; Back-end options.
12205 (push (nth 1 option-entry) keywords)))))
12207 (defconst org-options-keywords
12208 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12209 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12210 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12211 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12212 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12214 (defcustom org-structure-template-alist
12215 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12216 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12217 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12218 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12219 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12220 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12221 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12222 ("L" "#+LaTeX: ")
12223 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12224 ("H" "#+HTML: ")
12225 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12226 ("A" "#+ASCII: ")
12227 ("i" "#+INDEX: ?")
12228 ("I" "#+INCLUDE: %file ?"))
12229 "Structure completion elements.
12230 This is a list of abbreviation keys and values. The value gets inserted
12231 if you type `<' followed by the key and then press the completion key,
12232 usually `TAB'. %file will be replaced by a file name after prompting
12233 for the file using completion. The cursor will be placed at the position
12234 of the `?' in the template.
12235 There are two templates for each key, the first uses the original Org syntax,
12236 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12237 the default when the /org-mtags.el/ module has been loaded. See also the
12238 variable `org-mtags-prefer-muse-templates'."
12239 :group 'org-completion
12240 :type '(repeat
12241 (list
12242 (string :tag "Key")
12243 (string :tag "Template")))
12244 :version "25.1"
12245 :package-version '(Org . "8.3"))
12247 (defun org-try-structure-completion ()
12248 "Try to complete a structure template before point.
12249 This looks for strings like \"<e\" on an otherwise empty line and
12250 expands them."
12251 (let ((l (buffer-substring (point-at-bol) (point)))
12253 (when (and (looking-at "[ \t]*$")
12254 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12255 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12256 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12257 (match-beginning 1)) a)
12258 t)))
12260 (defun org-complete-expand-structure-template (start cell)
12261 "Expand a structure template."
12262 (let ((rpl (nth 1 cell))
12263 (ind ""))
12264 (delete-region start (point))
12265 (when (string-match "\\`[ \t]*#\\+" rpl)
12266 (cond
12267 ((bolp))
12268 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12269 (setq ind (buffer-substring (point-at-bol) (point))))
12270 (t (newline))))
12271 (setq start (point))
12272 (when (string-match "%file" rpl)
12273 (setq rpl (replace-match
12274 (concat
12275 "\""
12276 (save-match-data
12277 (abbreviate-file-name (read-file-name "Include file: ")))
12278 "\"")
12279 t t rpl)))
12280 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12281 (concat "\n" ind)))
12282 (insert rpl)
12283 (when (re-search-backward "\\?" start t) (delete-char 1))))
12285 ;;;; TODO, DEADLINE, Comments
12287 (defun org-toggle-comment ()
12288 "Change the COMMENT state of an entry."
12289 (interactive)
12290 (save-excursion
12291 (org-back-to-heading)
12292 (looking-at org-complex-heading-regexp)
12293 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12294 (skip-chars-forward " \t")
12295 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12296 (if (org-in-commented-heading-p t)
12297 (delete-region (point)
12298 (progn (search-forward " " (line-end-position) 'move)
12299 (skip-chars-forward " \t")
12300 (point)))
12301 (insert org-comment-string)
12302 (unless (eolp) (insert " ")))))
12304 (defvar org-last-todo-state-is-todo nil
12305 "This is non-nil when the last TODO state change led to a TODO state.
12306 If the last change removed the TODO tag or switched to DONE, then
12307 this is nil.")
12309 (defvar org-setting-tags nil) ; dynamically skipped
12311 (defvar org-todo-setup-filter-hook nil
12312 "Hook for functions that pre-filter todo specs.
12313 Each function takes a todo spec and returns either nil or the spec
12314 transformed into canonical form." )
12316 (defvar org-todo-get-default-hook nil
12317 "Hook for functions that get a default item for todo.
12318 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12319 nil or a string to be used for the todo mark." )
12321 (defvar org-agenda-headline-snapshot-before-repeat)
12323 (defun org-current-effective-time ()
12324 "Return current time adjusted for `org-extend-today-until' variable."
12325 (let* ((ct (org-current-time))
12326 (dct (decode-time ct))
12327 (ct1
12328 (cond
12329 (org-use-last-clock-out-time-as-effective-time
12330 (or (org-clock-get-last-clock-out-time) ct))
12331 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12332 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12333 (t ct))))
12334 ct1))
12336 (defun org-todo-yesterday (&optional arg)
12337 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12338 (interactive "P")
12339 (if (eq major-mode 'org-agenda-mode)
12340 (apply 'org-agenda-todo-yesterday arg)
12341 (let* ((org-use-effective-time t)
12342 (hour (nth 2 (decode-time (org-current-time))))
12343 (org-extend-today-until (1+ hour)))
12344 (org-todo arg))))
12346 (defvar org-block-entry-blocking ""
12347 "First entry preventing the TODO state change.")
12349 (defun org-cancel-repeater ()
12350 "Cancel a repeater by setting its numeric value to zero."
12351 (interactive)
12352 (save-excursion
12353 (org-back-to-heading t)
12354 (let ((bound1 (point))
12355 (bound0 (save-excursion (outline-next-heading) (point))))
12356 (when (and (re-search-forward
12357 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12358 org-deadline-time-regexp "\\)\\|\\("
12359 org-ts-regexp "\\)")
12360 bound0 t)
12361 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12362 bound1 t))
12363 (replace-match "0" t nil nil 1)))))
12365 (defvar org-state) ;; dynamically scoped into this function
12366 (defun org-todo (&optional arg)
12367 "Change the TODO state of an item.
12368 The state of an item is given by a keyword at the start of the heading,
12369 like
12370 *** TODO Write paper
12371 *** DONE Call mom
12373 The different keywords are specified in the variable `org-todo-keywords'.
12374 By default the available states are \"TODO\" and \"DONE\".
12375 So for this example: when the item starts with TODO, it is changed to DONE.
12376 When it starts with DONE, the DONE is removed. And when neither TODO nor
12377 DONE are present, add TODO at the beginning of the heading.
12379 With \\[universal-argument] prefix arg, use completion to determine the new \
12380 state.
12381 With numeric prefix arg, switch to that state.
12382 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12383 keywords (nextset).
12384 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12385 With a numeric prefix arg of 0, inhibit note taking for the change.
12386 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12388 When called through ELisp, arg is also interpreted in the following way:
12389 `none' -> empty state
12390 \"\"(empty string) -> switch to empty state
12391 `done' -> switch to DONE
12392 `nextset' -> switch to the next set of keywords
12393 `previousset' -> switch to the previous set of keywords
12394 \"WAITING\" -> switch to the specified keyword, but only if it
12395 really is a member of `org-todo-keywords'."
12396 (interactive "P")
12397 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12398 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12399 'region-start-level 'region))
12400 org-loop-over-headlines-in-active-region)
12401 (org-map-entries
12402 `(org-todo ,arg)
12403 org-loop-over-headlines-in-active-region
12404 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12405 (when (equal arg '(16)) (setq arg 'nextset))
12406 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12407 (let ((org-blocker-hook org-blocker-hook)
12408 commentp
12409 case-fold-search)
12410 (when (equal arg '(64))
12411 (setq arg nil org-blocker-hook nil))
12412 (when (and org-blocker-hook
12413 (or org-inhibit-blocking
12414 (org-entry-get nil "NOBLOCKING")))
12415 (setq org-blocker-hook nil))
12416 (save-excursion
12417 (catch 'exit
12418 (org-back-to-heading t)
12419 (when (org-in-commented-heading-p t)
12420 (org-toggle-comment)
12421 (setq commentp t))
12422 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12423 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12424 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12425 (let* ((match-data (match-data))
12426 (startpos (point-at-bol))
12427 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12428 (org-log-done org-log-done)
12429 (org-log-repeat org-log-repeat)
12430 (org-todo-log-states org-todo-log-states)
12431 (org-inhibit-logging
12432 (if (equal arg 0)
12433 (progn (setq arg nil) 'note) org-inhibit-logging))
12434 (this (match-string 1))
12435 (hl-pos (match-beginning 0))
12436 (head (org-get-todo-sequence-head this))
12437 (ass (assoc head org-todo-kwd-alist))
12438 (interpret (nth 1 ass))
12439 (done-word (nth 3 ass))
12440 (final-done-word (nth 4 ass))
12441 (org-last-state (or this ""))
12442 (completion-ignore-case t)
12443 (member (member this org-todo-keywords-1))
12444 (tail (cdr member))
12445 (org-state (cond
12446 ((and org-todo-key-trigger
12447 (or (and (equal arg '(4))
12448 (eq org-use-fast-todo-selection 'prefix))
12449 (and (not arg) org-use-fast-todo-selection
12450 (not (eq org-use-fast-todo-selection
12451 'prefix)))))
12452 ;; Use fast selection
12453 (org-fast-todo-selection))
12454 ((and (equal arg '(4))
12455 (or (not org-use-fast-todo-selection)
12456 (not org-todo-key-trigger)))
12457 ;; Read a state with completion
12458 (completing-read
12459 "State: " (mapcar #'list org-todo-keywords-1)
12460 nil t))
12461 ((eq arg 'right)
12462 (if this
12463 (if tail (car tail) nil)
12464 (car org-todo-keywords-1)))
12465 ((eq arg 'left)
12466 (unless (equal member org-todo-keywords-1)
12467 (if this
12468 (nth (- (length org-todo-keywords-1)
12469 (length tail) 2)
12470 org-todo-keywords-1)
12471 (org-last org-todo-keywords-1))))
12472 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12473 (setq arg nil))) ; hack to fall back to cycling
12474 (arg
12475 ;; user or caller requests a specific state
12476 (cond
12477 ((equal arg "") nil)
12478 ((eq arg 'none) nil)
12479 ((eq arg 'done) (or done-word (car org-done-keywords)))
12480 ((eq arg 'nextset)
12481 (or (car (cdr (member head org-todo-heads)))
12482 (car org-todo-heads)))
12483 ((eq arg 'previousset)
12484 (let ((org-todo-heads (reverse org-todo-heads)))
12485 (or (car (cdr (member head org-todo-heads)))
12486 (car org-todo-heads))))
12487 ((car (member arg org-todo-keywords-1)))
12488 ((stringp arg)
12489 (user-error "State `%s' not valid in this file" arg))
12490 ((nth (1- (prefix-numeric-value arg))
12491 org-todo-keywords-1))))
12492 ((null member) (or head (car org-todo-keywords-1)))
12493 ((equal this final-done-word) nil) ;; -> make empty
12494 ((null tail) nil) ;; -> first entry
12495 ((memq interpret '(type priority))
12496 (if (eq this-command last-command)
12497 (car tail)
12498 (if (> (length tail) 0)
12499 (or done-word (car org-done-keywords))
12500 nil)))
12502 (car tail))))
12503 (org-state (or
12504 (run-hook-with-args-until-success
12505 'org-todo-get-default-hook org-state org-last-state)
12506 org-state))
12507 (next (if org-state (concat " " org-state " ") " "))
12508 (change-plist (list :type 'todo-state-change :from this :to org-state
12509 :position startpos))
12510 dolog now-done-p)
12511 (when org-blocker-hook
12512 (setq org-last-todo-state-is-todo
12513 (not (member this org-done-keywords)))
12514 (unless (save-excursion
12515 (save-match-data
12516 (org-with-wide-buffer
12517 (run-hook-with-args-until-failure
12518 'org-blocker-hook change-plist))))
12519 (if (org-called-interactively-p 'interactive)
12520 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12521 this org-state org-block-entry-blocking)
12522 ;; fail silently
12523 (message "TODO state change from %s to %s blocked (by \"%s\")"
12524 this org-state org-block-entry-blocking)
12525 (throw 'exit nil))))
12526 (store-match-data match-data)
12527 (replace-match next t t)
12528 (cond ((equal this org-state)
12529 (message "TODO state was already %s" (org-trim next)))
12530 ((pos-visible-in-window-p hl-pos)
12531 (message "TODO state changed to %s" (org-trim next))))
12532 (unless head
12533 (setq head (org-get-todo-sequence-head org-state)
12534 ass (assoc head org-todo-kwd-alist)
12535 interpret (nth 1 ass)
12536 done-word (nth 3 ass)
12537 final-done-word (nth 4 ass)))
12538 (when (memq arg '(nextset previousset))
12539 (message "Keyword-Set %d/%d: %s"
12540 (- (length org-todo-sets) -1
12541 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12542 (length org-todo-sets)
12543 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12544 (setq org-last-todo-state-is-todo
12545 (not (member org-state org-done-keywords)))
12546 (setq now-done-p (and (member org-state org-done-keywords)
12547 (not (member this org-done-keywords))))
12548 (and logging (org-local-logging logging))
12549 (when (and (or org-todo-log-states org-log-done)
12550 (not (eq org-inhibit-logging t))
12551 (not (memq arg '(nextset previousset))))
12552 ;; we need to look at recording a time and note
12553 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12554 (nth 2 (assoc this org-todo-log-states))))
12555 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12556 (setq dolog 'time))
12557 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12558 (and org-state
12559 (member org-state org-not-done-keywords)
12560 (not (member this org-not-done-keywords))))
12561 ;; This is now a todo state and was not one before
12562 ;; If there was a CLOSED time stamp, get rid of it.
12563 (org-add-planning-info nil nil 'closed))
12564 (when (and now-done-p org-log-done)
12565 ;; It is now done, and it was not done before
12566 (org-add-planning-info 'closed (org-current-effective-time))
12567 (when (and (not dolog) (eq 'note org-log-done))
12568 (org-add-log-setup 'done org-state this 'note)))
12569 (when (and org-state dolog)
12570 ;; This is a non-nil state, and we need to log it
12571 (org-add-log-setup 'state org-state this dolog)))
12572 ;; Fixup tag positioning
12573 (org-todo-trigger-tag-changes org-state)
12574 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12575 (when org-provide-todo-statistics
12576 (org-update-parent-todo-statistics))
12577 (run-hooks 'org-after-todo-state-change-hook)
12578 (when (and arg (not (member org-state org-done-keywords)))
12579 (setq head (org-get-todo-sequence-head org-state)))
12580 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12581 ;; Do we need to trigger a repeat?
12582 (when now-done-p
12583 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12584 ;; This is for the agenda, take a snapshot of the headline.
12585 (save-match-data
12586 (setq org-agenda-headline-snapshot-before-repeat
12587 (org-get-heading))))
12588 (org-auto-repeat-maybe org-state))
12589 ;; Fixup cursor location if close to the keyword
12590 (when (and (outline-on-heading-p)
12591 (not (bolp))
12592 (save-excursion (beginning-of-line 1)
12593 (looking-at org-todo-line-regexp))
12594 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12595 (goto-char (or (match-end 2) (match-end 1)))
12596 (and (looking-at " ") (just-one-space)))
12597 (when org-trigger-hook
12598 (save-excursion
12599 (run-hook-with-args 'org-trigger-hook change-plist)))
12600 (when commentp (org-toggle-comment))))))))
12602 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12603 "Block turning an entry into a TODO, using the hierarchy.
12604 This checks whether the current task should be blocked from state
12605 changes. Such blocking occurs when:
12607 1. The task has children which are not all in a completed state.
12609 2. A task has a parent with the property :ORDERED:, and there
12610 are siblings prior to the current task with incomplete
12611 status.
12613 3. The parent of the task is blocked because it has siblings that should
12614 be done first, or is child of a block grandparent TODO entry."
12616 (if (not org-enforce-todo-dependencies)
12617 t ; if locally turned off don't block
12618 (catch 'dont-block
12619 ;; If this is not a todo state change, or if this entry is already DONE,
12620 ;; do not block
12621 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12622 (member (plist-get change-plist :from)
12623 (cons 'done org-done-keywords))
12624 (member (plist-get change-plist :to)
12625 (cons 'todo org-not-done-keywords))
12626 (not (plist-get change-plist :to)))
12627 (throw 'dont-block t))
12628 ;; If this task has children, and any are undone, it's blocked
12629 (save-excursion
12630 (org-back-to-heading t)
12631 (let ((this-level (funcall outline-level)))
12632 (outline-next-heading)
12633 (let ((child-level (funcall outline-level)))
12634 (while (and (not (eobp))
12635 (> child-level this-level))
12636 ;; this todo has children, check whether they are all
12637 ;; completed
12638 (when (and (not (org-entry-is-done-p))
12639 (org-entry-is-todo-p))
12640 (setq org-block-entry-blocking (org-get-heading))
12641 (throw 'dont-block nil))
12642 (outline-next-heading)
12643 (setq child-level (funcall outline-level))))))
12644 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12645 ;; any previous siblings are undone, it's blocked
12646 (save-excursion
12647 (org-back-to-heading t)
12648 (let* ((pos (point))
12649 (parent-pos (and (org-up-heading-safe) (point))))
12650 (unless parent-pos (throw 'dont-block t)) ; no parent
12651 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12652 (forward-line 1)
12653 (re-search-forward org-not-done-heading-regexp pos t))
12654 (setq org-block-entry-blocking (match-string 0))
12655 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12656 ;; Search further up the hierarchy, to see if an ancestor is blocked
12657 (while t
12658 (goto-char parent-pos)
12659 (unless (looking-at org-not-done-heading-regexp)
12660 (throw 'dont-block t)) ; do not block, parent is not a TODO
12661 (setq pos (point))
12662 (setq parent-pos (and (org-up-heading-safe) (point)))
12663 (unless parent-pos (throw 'dont-block t)) ; no parent
12664 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12665 (forward-line 1)
12666 (re-search-forward org-not-done-heading-regexp pos t)
12667 (setq org-block-entry-blocking (org-get-heading)))
12668 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12670 (defcustom org-track-ordered-property-with-tag nil
12671 "Should the ORDERED property also be shown as a tag?
12672 The ORDERED property decides if an entry should require subtasks to be
12673 completed in sequence. Since a property is not very visible, setting
12674 this option means that toggling the ORDERED property with the command
12675 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12676 not relevant for the behavior, but it makes things more visible.
12678 Note that toggling the tag with tags commands will not change the property
12679 and therefore not influence behavior!
12681 This can be t, meaning the tag ORDERED should be used, It can also be a
12682 string to select a different tag for this task."
12683 :group 'org-todo
12684 :type '(choice
12685 (const :tag "No tracking" nil)
12686 (const :tag "Track with ORDERED tag" t)
12687 (string :tag "Use other tag")))
12689 (defun org-toggle-ordered-property ()
12690 "Toggle the ORDERED property of the current entry.
12691 For better visibility, you can track the value of this property with a tag.
12692 See variable `org-track-ordered-property-with-tag'."
12693 (interactive)
12694 (let* ((t1 org-track-ordered-property-with-tag)
12695 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12696 (save-excursion
12697 (org-back-to-heading)
12698 (if (org-entry-get nil "ORDERED")
12699 (progn
12700 (org-delete-property "ORDERED")
12701 (and tag (org-toggle-tag tag 'off))
12702 (message "Subtasks can be completed in arbitrary order"))
12703 (org-entry-put nil "ORDERED" "t")
12704 (and tag (org-toggle-tag tag 'on))
12705 (message "Subtasks must be completed in sequence")))))
12707 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12708 (defun org-block-todo-from-checkboxes (change-plist)
12709 "Block turning an entry into a TODO, using checkboxes.
12710 This checks whether the current task should be blocked from state
12711 changes because there are unchecked boxes in this entry."
12712 (if (not org-enforce-todo-checkbox-dependencies)
12713 t ; if locally turned off don't block
12714 (catch 'dont-block
12715 ;; If this is not a todo state change, or if this entry is already DONE,
12716 ;; do not block
12717 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12718 (member (plist-get change-plist :from)
12719 (cons 'done org-done-keywords))
12720 (member (plist-get change-plist :to)
12721 (cons 'todo org-not-done-keywords))
12722 (not (plist-get change-plist :to)))
12723 (throw 'dont-block t))
12724 ;; If this task has checkboxes that are not checked, it's blocked
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (let ((beg (point)) end)
12728 (outline-next-heading)
12729 (setq end (point))
12730 (goto-char beg)
12731 (when (org-list-search-forward
12732 (concat (org-item-beginning-re)
12733 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12734 "\\[[- ]\\]")
12735 end t)
12736 (when (boundp 'org-blocked-by-checkboxes)
12737 (setq org-blocked-by-checkboxes t))
12738 (throw 'dont-block nil))))
12739 t))) ; do not block
12741 (defun org-entry-blocked-p ()
12742 "Non-nil if entry at point is blocked."
12743 (and (not (org-entry-get nil "NOBLOCKING"))
12744 (member (org-entry-get nil "TODO") org-not-done-keywords)
12745 (not (run-hook-with-args-until-failure
12746 'org-blocker-hook
12747 (list :type 'todo-state-change
12748 :position (point)
12749 :from 'todo
12750 :to 'done)))))
12752 (defun org-update-statistics-cookies (all)
12753 "Update the statistics cookie, either from TODO or from checkboxes.
12754 This should be called with the cursor in a line with a statistics cookie."
12755 (interactive "P")
12756 (if all
12757 (progn
12758 (org-update-checkbox-count 'all)
12759 (org-map-entries 'org-update-parent-todo-statistics))
12760 (if (not (org-at-heading-p))
12761 (org-update-checkbox-count)
12762 (let ((pos (point-marker))
12763 end l1 l2)
12764 (ignore-errors (org-back-to-heading t))
12765 (if (not (org-at-heading-p))
12766 (org-update-checkbox-count)
12767 (setq l1 (org-outline-level))
12768 (setq end (save-excursion
12769 (outline-next-heading)
12770 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12771 (point)))
12772 (if (and (save-excursion
12773 (re-search-forward
12774 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12775 (not (save-excursion (re-search-forward
12776 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12777 (org-update-checkbox-count)
12778 (if (and l2 (> l2 l1))
12779 (progn
12780 (goto-char end)
12781 (org-update-parent-todo-statistics))
12782 (goto-char pos)
12783 (beginning-of-line 1)
12784 (while (re-search-forward
12785 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12786 (point-at-eol) t)
12787 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12788 (goto-char pos)
12789 (move-marker pos nil)))))
12791 (defvar org-entry-property-inherited-from) ;; defined below
12792 (defun org-update-parent-todo-statistics ()
12793 "Update any statistics cookie in the parent of the current headline.
12794 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12795 the entire subtree and this will travel up the hierarchy and update
12796 statistics everywhere."
12797 (let* ((prop (save-excursion (org-up-heading-safe)
12798 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12799 (recursive (or (not org-hierarchical-todo-statistics)
12800 (and prop (string-match "\\<recursive\\>" prop))))
12801 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12803 (first t)
12804 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12805 level ltoggle l1 new ndel
12806 (cnt-all 0) (cnt-done 0) is-percent kwd
12807 checkbox-beg ov ovs ove cookie-present)
12808 (catch 'exit
12809 (save-excursion
12810 (beginning-of-line 1)
12811 (setq ltoggle (funcall outline-level))
12812 ;; Three situations are to consider:
12814 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12815 ;; to the top-level ancestor on the headline;
12817 ;; 2. If parent has "recursive" property, repeat up to the
12818 ;; headline setting that property, taking inheritance into
12819 ;; account;
12821 ;; 3. Else, move up to direct parent and proceed only once.
12822 (while (and (setq level (org-up-heading-safe))
12823 (or recursive first)
12824 (>= (point) lim))
12825 (setq first nil cookie-present nil)
12826 (unless (and level
12827 (not (string-match
12828 "\\<checkbox\\>"
12829 (downcase (or (org-entry-get nil "COOKIE_DATA")
12830 "")))))
12831 (throw 'exit nil))
12832 (while (re-search-forward box-re (point-at-eol) t)
12833 (setq cnt-all 0 cnt-done 0 cookie-present t)
12834 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12835 (save-match-data
12836 (unless (outline-next-heading) (throw 'exit nil))
12837 (while (and (looking-at org-complex-heading-regexp)
12838 (> (setq l1 (length (match-string 1))) level))
12839 (setq kwd (and (or recursive (= l1 ltoggle))
12840 (match-string 2)))
12841 (if (or (eq org-provide-todo-statistics 'all-headlines)
12842 (and (eq org-provide-todo-statistics t)
12843 (or (member kwd org-done-keywords)))
12844 (and (listp org-provide-todo-statistics)
12845 (stringp (car org-provide-todo-statistics))
12846 (or (member kwd org-provide-todo-statistics)
12847 (member kwd org-done-keywords)))
12848 (and (listp org-provide-todo-statistics)
12849 (listp (car org-provide-todo-statistics))
12850 (or (member kwd (car org-provide-todo-statistics))
12851 (and (member kwd org-done-keywords)
12852 (member kwd (cadr org-provide-todo-statistics))))))
12853 (setq cnt-all (1+ cnt-all))
12854 (and (eq org-provide-todo-statistics t)
12856 (setq cnt-all (1+ cnt-all))))
12857 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12858 (member kwd org-done-keywords))
12859 (and (listp org-provide-todo-statistics)
12860 (listp (car org-provide-todo-statistics))
12861 (member kwd org-done-keywords)
12862 (member kwd (cadr org-provide-todo-statistics)))
12863 (and (listp org-provide-todo-statistics)
12864 (stringp (car org-provide-todo-statistics))
12865 (member kwd org-done-keywords)))
12866 (setq cnt-done (1+ cnt-done)))
12867 (outline-next-heading)))
12868 (setq new
12869 (if is-percent
12870 (format "[%d%%]" (floor (* 100.0 cnt-done)
12871 (max 1 cnt-all)))
12872 (format "[%d/%d]" cnt-done cnt-all))
12873 ndel (- (match-end 0) checkbox-beg))
12874 ;; handle overlays when updating cookie from column view
12875 (when (setq ov (car (overlays-at checkbox-beg)))
12876 (setq ovs (overlay-start ov) ove (overlay-end ov))
12877 (delete-overlay ov))
12878 (goto-char checkbox-beg)
12879 (insert new)
12880 (delete-region (point) (+ (point) ndel))
12881 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12882 (when ov (move-overlay ov ovs ove)))
12883 (when cookie-present
12884 (run-hook-with-args 'org-after-todo-statistics-hook
12885 cnt-done (- cnt-all cnt-done))))))
12886 (run-hooks 'org-todo-statistics-hook)))
12888 (defvar org-after-todo-statistics-hook nil
12889 "Hook that is called after a TODO statistics cookie has been updated.
12890 Each function is called with two arguments: the number of not-done entries
12891 and the number of done entries.
12893 For example, the following function, when added to this hook, will switch
12894 an entry to DONE when all children are done, and back to TODO when new
12895 entries are set to a TODO status. Note that this hook is only called
12896 when there is a statistics cookie in the headline!
12898 \(defun org-summary-todo (n-done n-not-done)
12899 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12900 \(let (org-log-done org-log-states) ; turn off logging
12901 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12904 (defvar org-todo-statistics-hook nil
12905 "Hook that is run whenever Org thinks TODO statistics should be updated.
12906 This hook runs even if there is no statistics cookie present, in which case
12907 `org-after-todo-statistics-hook' would not run.")
12909 (defun org-todo-trigger-tag-changes (state)
12910 "Apply the changes defined in `org-todo-state-tags-triggers'."
12911 (let ((l org-todo-state-tags-triggers)
12912 changes)
12913 (when (or (not state) (equal state ""))
12914 (setq changes (append changes (cdr (assoc "" l)))))
12915 (when (and (stringp state) (> (length state) 0))
12916 (setq changes (append changes (cdr (assoc state l)))))
12917 (when (member state org-not-done-keywords)
12918 (setq changes (append changes (cdr (assoc 'todo l)))))
12919 (when (member state org-done-keywords)
12920 (setq changes (append changes (cdr (assoc 'done l)))))
12921 (dolist (c changes)
12922 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12924 (defun org-local-logging (value)
12925 "Get logging settings from a property VALUE."
12926 ;; Directly set the variables, they are already local.
12927 (setq org-log-done nil
12928 org-log-repeat nil
12929 org-todo-log-states nil)
12930 (dolist (w (org-split-string value))
12931 (let (a)
12932 (cond
12933 ((setq a (assoc w org-startup-options))
12934 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12935 (set (nth 1 a) (nth 2 a))))
12936 ((setq a (org-extract-log-state-settings w))
12937 (and (member (car a) org-todo-keywords-1)
12938 (push a org-todo-log-states)))))))
12940 (defun org-get-todo-sequence-head (kwd)
12941 "Return the head of the TODO sequence to which KWD belongs.
12942 If KWD is not set, check if there is a text property remembering the
12943 right sequence."
12944 (let (p)
12945 (cond
12946 ((not kwd)
12947 (or (get-text-property (point-at-bol) 'org-todo-head)
12948 (progn
12949 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12950 nil (point-at-eol)))
12951 (get-text-property p 'org-todo-head))))
12952 ((not (member kwd org-todo-keywords-1))
12953 (car org-todo-keywords-1))
12954 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12956 (defun org-fast-todo-selection ()
12957 "Fast TODO keyword selection with single keys.
12958 Returns the new TODO keyword, or nil if no state change should occur."
12959 (let* ((fulltable org-todo-key-alist)
12960 (done-keywords org-done-keywords) ;; needed for the faces.
12961 (maxlen (apply 'max (mapcar
12962 (lambda (x)
12963 (if (stringp (car x)) (string-width (car x)) 0))
12964 fulltable)))
12965 (expert nil)
12966 (fwidth (+ maxlen 3 1 3))
12967 (ncol (/ (- (window-width) 4) fwidth))
12968 tg cnt e c tbl
12969 groups ingroup)
12970 (save-excursion
12971 (save-window-excursion
12972 (if expert
12973 (set-buffer (get-buffer-create " *Org todo*"))
12974 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12975 (erase-buffer)
12976 (setq-local org-done-keywords done-keywords)
12977 (setq tbl fulltable cnt 0)
12978 (while (setq e (pop tbl))
12979 (cond
12980 ((equal e '(:startgroup))
12981 (push '() groups) (setq ingroup t)
12982 (unless (= cnt 0)
12983 (setq cnt 0)
12984 (insert "\n"))
12985 (insert "{ "))
12986 ((equal e '(:endgroup))
12987 (setq ingroup nil cnt 0)
12988 (insert "}\n"))
12989 ((equal e '(:newline))
12990 (unless (= cnt 0)
12991 (setq cnt 0)
12992 (insert "\n")
12993 (setq e (car tbl))
12994 (while (equal (car tbl) '(:newline))
12995 (insert "\n")
12996 (setq tbl (cdr tbl)))))
12998 (setq tg (car e) c (cdr e))
12999 (when ingroup (push tg (car groups)))
13000 (setq tg (org-add-props tg nil 'face
13001 (org-get-todo-face tg)))
13002 (when (and (= cnt 0) (not ingroup)) (insert " "))
13003 (insert "[" c "] " tg (make-string
13004 (- fwidth 4 (length tg)) ?\ ))
13005 (when (= (setq cnt (1+ cnt)) ncol)
13006 (insert "\n")
13007 (when ingroup (insert " "))
13008 (setq cnt 0)))))
13009 (insert "\n")
13010 (goto-char (point-min))
13011 (unless expert (org-fit-window-to-buffer))
13012 (message "[a-z..]:Set [SPC]:clear")
13013 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13014 (cond
13015 ((or (= c ?\C-g)
13016 (and (= c ?q) (not (rassoc c fulltable))))
13017 (setq quit-flag t))
13018 ((= c ?\ ) nil)
13019 ((setq e (rassoc c fulltable) tg (car e))
13021 (t (setq quit-flag t)))))))
13023 (defun org-entry-is-todo-p ()
13024 (member (org-get-todo-state) org-not-done-keywords))
13026 (defun org-entry-is-done-p ()
13027 (member (org-get-todo-state) org-done-keywords))
13029 (defun org-get-todo-state ()
13030 "Return the TODO keyword of the current subtree."
13031 (save-excursion
13032 (org-back-to-heading t)
13033 (and (looking-at org-todo-line-regexp)
13034 (match-end 2)
13035 (match-string 2))))
13037 (defun org-at-date-range-p (&optional inactive-ok)
13038 "Non-nil if point is inside a date range.
13040 When optional argument INACTIVE-OK is non-nil, also consider
13041 inactive time ranges.
13043 When this function returns a non-nil value, match data is set
13044 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13045 on INACTIVE-OK."
13046 (interactive)
13047 (save-excursion
13048 (catch 'exit
13049 (let ((pos (point)))
13050 (skip-chars-backward "^[<\r\n")
13051 (skip-chars-backward "<[")
13052 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13053 (>= (match-end 0) pos)
13054 (throw 'exit t))
13055 (skip-chars-backward "^<[\r\n")
13056 (skip-chars-backward "<[")
13057 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13058 (>= (match-end 0) pos)
13059 (throw 'exit t)))
13060 nil)))
13062 (defun org-get-repeat (&optional tagline)
13063 "Check if there is a deadline/schedule with repeater in this entry."
13064 (save-match-data
13065 (save-excursion
13066 (org-back-to-heading t)
13067 (and (re-search-forward (if tagline
13068 (concat tagline "\\s-*" org-repeat-re)
13069 org-repeat-re)
13070 (org-entry-end-position) t)
13071 (match-string-no-properties 1)))))
13073 (defvar org-last-changed-timestamp)
13074 (defvar org-last-inserted-timestamp)
13075 (defvar org-log-post-message)
13076 (defvar org-log-note-purpose)
13077 (defvar org-log-note-how nil)
13078 (defvar org-log-note-extra)
13079 (defun org-auto-repeat-maybe (done-word)
13080 "Check if the current headline contains a repeated time-stamp.
13082 If yes, set TODO state back to what it was and change the base date
13083 of repeating deadline/scheduled time stamps to new date.
13085 This function is run automatically after each state change to a DONE state."
13086 (let* ((repeat (org-get-repeat))
13087 (aa (assoc org-last-state org-todo-kwd-alist))
13088 (interpret (nth 1 aa))
13089 (head (nth 2 aa))
13090 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13091 (msg "Entry repeats: ")
13092 (org-log-done nil)
13093 (org-todo-log-states nil))
13094 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13095 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13096 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13097 org-todo-repeat-to-state)))
13098 (unless (and to-state (member to-state org-todo-keywords-1))
13099 (setq to-state (if (eq interpret 'type) org-last-state head)))
13100 (org-todo to-state))
13101 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13102 (org-entry-put nil "LAST_REPEAT" (format-time-string
13103 (org-time-stamp-format t t))))
13104 (when org-log-repeat
13105 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13106 (memq 'org-add-log-note post-command-hook))
13107 ;; We are already setup for some record.
13108 (when (eq org-log-repeat 'note)
13109 ;; Make sure we take a note, not only a time stamp.
13110 (setq org-log-note-how 'note))
13111 ;; Set up for taking a record.
13112 (org-add-log-setup 'state
13113 (or done-word (car org-done-keywords))
13114 org-last-state
13115 org-log-repeat)))
13116 (org-back-to-heading t)
13117 (org-add-planning-info nil nil 'closed)
13118 (let ((end (save-excursion (outline-next-heading) (point))))
13119 (while (re-search-forward org-ts-regexp end t)
13120 (when (save-match-data
13121 (or (org-at-planning-p)
13122 (org-at-property-p)
13123 (eq (org-element-type (save-excursion
13124 (backward-char)
13125 (org-element-context)))
13126 'timestamp)))
13127 (let ((type (cond ((match-end 1) org-scheduled-string)
13128 ((match-end 3) org-deadline-string)
13129 (t "Plain:")))
13130 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13131 (cond
13132 ((not
13133 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13134 ;; Time-stamps without a repeater are usually skipped.
13135 ;; However, a SCHEDULED time-stamp without one is
13136 ;; removed, as it is considered as no longer relevant.
13137 (when (equal type org-scheduled-string)
13138 (org-remove-timestamp-with-keyword type)))
13140 (let ((n (string-to-number (match-string 2 ts)))
13141 (what (match-string 3 ts)))
13142 (when (equal what "w") (setq n (* n 7) what "d"))
13143 (when (and (equal what "h")
13144 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13145 ts)))
13146 (user-error
13147 "Cannot repeat in Repeat in %d hour(s) because no hour \
13148 has been set"
13150 ;; Preparation, see if we need to modify the start
13151 ;; date for the change.
13152 (when (match-end 1)
13153 (let ((time (save-match-data (org-time-string-to-time ts))))
13154 (cond
13155 ((equal (match-string 1 ts) ".")
13156 ;; Shift starting date to today
13157 (org-timestamp-change
13158 (- (org-today) (time-to-days time))
13159 'day))
13160 ((equal (match-string 1 ts) "+")
13161 (let ((nshiftmax 10)
13162 (nshift 0))
13163 (while (or (= nshift 0)
13164 (<= (time-to-days time)
13165 (time-to-days (current-time))))
13166 (when (= (cl-incf nshift) nshiftmax)
13167 (or (y-or-n-p
13168 (format "%d repeater intervals were not \
13169 enough to shift date past today. Continue? "
13170 nshift))
13171 (user-error "Abort")))
13172 (org-timestamp-change n (cdr (assoc what whata)))
13173 (org-at-timestamp-p t)
13174 (setq ts (match-string 1))
13175 (setq time
13176 (save-match-data
13177 (org-time-string-to-time ts)))))
13178 (org-timestamp-change (- n) (cdr (assoc what whata)))
13179 ;; Rematch, so that we have everything in
13180 ;; place for the real shift.
13181 (org-at-timestamp-p t)
13182 (setq ts (match-string 1))
13183 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13184 ts)))))
13185 (save-excursion
13186 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13187 (setq msg
13188 (concat
13189 msg type " " org-last-changed-timestamp " ")))))))))
13190 (setq org-log-post-message msg)
13191 (message "%s" msg))))
13193 (defun org-show-todo-tree (arg)
13194 "Make a compact tree which shows all headlines marked with TODO.
13195 The tree will show the lines where the regexp matches, and all higher
13196 headlines above the match.
13197 With a \\[universal-argument] prefix, prompt for a regexp to match.
13198 With a numeric prefix N, construct a sparse tree for the Nth element
13199 of `org-todo-keywords-1'."
13200 (interactive "P")
13201 (let ((case-fold-search nil)
13202 (kwd-re
13203 (cond ((null arg) org-not-done-regexp)
13204 ((equal arg '(4))
13205 (let ((kwd
13206 (completing-read "Keyword (or KWD1|KWD2|...): "
13207 (mapcar #'list org-todo-keywords-1))))
13208 (concat "\\("
13209 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13210 "\\)\\>")))
13211 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13212 (regexp-quote (nth (1- (prefix-numeric-value arg))
13213 org-todo-keywords-1)))
13214 (t (user-error "Invalid prefix argument: %s" arg)))))
13215 (message "%d TODO entries found"
13216 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13218 (defun org-deadline (arg &optional time)
13219 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13220 With one universal prefix argument, remove any deadline from the item.
13221 With two universal prefix arguments, prompt for a warning delay.
13222 With argument TIME, set the deadline at the corresponding date. TIME
13223 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13224 (interactive "P")
13225 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13226 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13227 'region-start-level 'region))
13228 org-loop-over-headlines-in-active-region)
13229 (org-map-entries
13230 `(org-deadline ',arg ,time)
13231 org-loop-over-headlines-in-active-region
13232 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13233 (let* ((old-date (org-entry-get nil "DEADLINE"))
13234 (old-date-time (when old-date (org-time-string-to-time old-date)))
13235 (repeater (and old-date
13236 (string-match
13237 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13238 old-date)
13239 (match-string 1 old-date))))
13240 (cond
13241 ((equal arg '(4))
13242 (when (and old-date org-log-redeadline)
13243 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13244 (org-remove-timestamp-with-keyword org-deadline-string)
13245 (message "Item no longer has a deadline."))
13246 ((equal arg '(16))
13247 (save-excursion
13248 (org-back-to-heading t)
13249 (if (re-search-forward
13250 org-deadline-time-regexp
13251 (save-excursion (outline-next-heading) (point)) t)
13252 (let* ((rpl0 (match-string 1))
13253 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13254 (replace-match
13255 (concat org-deadline-string
13256 " <" rpl
13257 (format " -%dd"
13258 (abs
13259 (- (time-to-days
13260 (save-match-data
13261 (org-read-date nil t nil "Warn starting from" old-date-time)))
13262 (time-to-days old-date-time))))
13263 ">") t t))
13264 (user-error "No deadline information to update"))))
13266 (org-add-planning-info 'deadline time 'closed)
13267 (when (and old-date
13268 org-log-redeadline
13269 (not (equal old-date org-last-inserted-timestamp)))
13270 (org-add-log-setup
13271 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13272 (when repeater
13273 (save-excursion
13274 (org-back-to-heading t)
13275 (when (re-search-forward (concat org-deadline-string " "
13276 org-last-inserted-timestamp)
13277 (save-excursion
13278 (outline-next-heading) (point)) t)
13279 (goto-char (1- (match-end 0)))
13280 (insert " " repeater)
13281 (setq org-last-inserted-timestamp
13282 (concat (substring org-last-inserted-timestamp 0 -1)
13283 " " repeater
13284 (substring org-last-inserted-timestamp -1))))))
13285 (message "Deadline on %s" org-last-inserted-timestamp))))))
13287 (defun org-schedule (arg &optional time)
13288 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13289 With one universal prefix argument, remove any scheduling date from the item.
13290 With two universal prefix arguments, prompt for a delay cookie.
13291 With argument TIME, scheduled at the corresponding date. TIME can
13292 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13293 (interactive "P")
13294 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13295 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13296 'region-start-level 'region))
13297 org-loop-over-headlines-in-active-region)
13298 (org-map-entries
13299 `(org-schedule ',arg ,time)
13300 org-loop-over-headlines-in-active-region
13301 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13302 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13303 (old-date-time (when old-date (org-time-string-to-time old-date)))
13304 (repeater (and old-date
13305 (string-match
13306 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13307 old-date)
13308 (match-string 1 old-date))))
13309 (cond
13310 ((equal arg '(4))
13311 (progn
13312 (when (and old-date org-log-reschedule)
13313 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13314 (org-remove-timestamp-with-keyword org-scheduled-string)
13315 (message "Item is no longer scheduled.")))
13316 ((equal arg '(16))
13317 (save-excursion
13318 (org-back-to-heading t)
13319 (if (re-search-forward
13320 org-scheduled-time-regexp
13321 (save-excursion (outline-next-heading) (point)) t)
13322 (let* ((rpl0 (match-string 1))
13323 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13324 (replace-match
13325 (concat org-scheduled-string
13326 " <" rpl
13327 (format " -%dd"
13328 (abs
13329 (- (time-to-days
13330 (save-match-data
13331 (org-read-date nil t nil "Delay until" old-date-time)))
13332 (time-to-days old-date-time))))
13333 ">") t t))
13334 (user-error "No scheduled information to update"))))
13336 (org-add-planning-info 'scheduled time 'closed)
13337 (when (and old-date
13338 org-log-reschedule
13339 (not (equal old-date org-last-inserted-timestamp)))
13340 (org-add-log-setup
13341 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13342 (when repeater
13343 (save-excursion
13344 (org-back-to-heading t)
13345 (when (re-search-forward (concat org-scheduled-string " "
13346 org-last-inserted-timestamp)
13347 (save-excursion
13348 (outline-next-heading) (point)) t)
13349 (goto-char (1- (match-end 0)))
13350 (insert " " repeater)
13351 (setq org-last-inserted-timestamp
13352 (concat (substring org-last-inserted-timestamp 0 -1)
13353 " " repeater
13354 (substring org-last-inserted-timestamp -1))))))
13355 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13357 (defun org-get-scheduled-time (pom &optional inherit)
13358 "Get the scheduled time as a time tuple, of a format suitable
13359 for calling org-schedule with, or if there is no scheduling,
13360 returns nil."
13361 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13362 (when time
13363 (apply 'encode-time (org-parse-time-string time)))))
13365 (defun org-get-deadline-time (pom &optional inherit)
13366 "Get the deadline as a time tuple, of a format suitable for
13367 calling org-deadline with, or if there is no scheduling, returns
13368 nil."
13369 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13370 (when time
13371 (apply 'encode-time (org-parse-time-string time)))))
13373 (defun org-remove-timestamp-with-keyword (keyword)
13374 "Remove all time stamps with KEYWORD in the current entry."
13375 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13376 beg)
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (setq beg (point))
13380 (outline-next-heading)
13381 (while (re-search-backward re beg t)
13382 (replace-match "")
13383 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13384 (equal (char-before) ?\ ))
13385 (backward-delete-char 1)
13386 (when (string-match "^[ \t]*$" (buffer-substring
13387 (point-at-bol) (point-at-eol)))
13388 (delete-region (point-at-bol)
13389 (min (point-max) (1+ (point-at-eol))))))))))
13391 (defvar org-time-was-given) ; dynamically scoped parameter
13392 (defvar org-end-time-was-given) ; dynamically scoped parameter
13394 (defun org-at-planning-p ()
13395 "Non-nil when point is on a planning info line."
13396 ;; This is as accurate and faster than `org-element-at-point' since
13397 ;; planning info location is fixed in the section.
13398 (org-with-wide-buffer
13399 (beginning-of-line)
13400 (and (org-looking-at-p org-planning-line-re)
13401 (eq (point)
13402 (ignore-errors
13403 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13404 (org-back-to-heading t)
13405 (org-with-limited-levels (org-back-to-heading t)))
13406 (line-beginning-position 2))))))
13408 (defun org-add-planning-info (what &optional time &rest remove)
13409 "Insert new timestamp with keyword in the planning line.
13410 WHAT indicates what kind of time stamp to add. It is a symbol
13411 among `closed', `deadline', `scheduled' and nil. TIME indicates
13412 the time to use. If none is given, the user is prompted for
13413 a date. REMOVE indicates what kind of entries to remove. An old
13414 WHAT entry will also be removed."
13415 (let (org-time-was-given org-end-time-was-given default-time default-input)
13416 (catch 'exit
13417 (when (and (memq what '(scheduled deadline))
13418 (or (not time)
13419 (and (stringp time)
13420 (string-match "^[-+]+[0-9]" time))))
13421 ;; Try to get a default date/time from existing timestamp
13422 (save-excursion
13423 (org-back-to-heading t)
13424 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13425 (when (re-search-forward (if (eq what 'scheduled)
13426 org-scheduled-time-regexp
13427 org-deadline-time-regexp)
13428 end t)
13429 (setq ts (match-string 1)
13430 default-time (apply 'encode-time (org-parse-time-string ts))
13431 default-input (and ts (org-get-compact-tod ts)))))))
13432 (when what
13433 (setq time
13434 (if (stringp time)
13435 ;; This is a string (relative or absolute), set
13436 ;; proper date.
13437 (apply #'encode-time
13438 (org-read-date-analyze
13439 time default-time (decode-time default-time)))
13440 ;; If necessary, get the time from the user
13441 (or time (org-read-date nil 'to-time nil nil
13442 default-time default-input)))))
13444 (org-with-wide-buffer
13445 (org-back-to-heading t)
13446 (forward-line)
13447 (unless (bolp) (insert "\n"))
13448 (cond ((org-looking-at-p org-planning-line-re)
13449 ;; Move to current indentation.
13450 (skip-chars-forward " \t")
13451 ;; Check if we have to remove something.
13452 (dolist (type (if what (cons what remove) remove))
13453 (save-excursion
13454 (when (re-search-forward
13455 (cl-case type
13456 (closed org-closed-time-regexp)
13457 (deadline org-deadline-time-regexp)
13458 (scheduled org-scheduled-time-regexp)
13459 (otherwise
13460 (error "Invalid planning type: %s" type)))
13461 (line-end-position) t)
13462 ;; Delete until next keyword or end of line.
13463 (delete-region
13464 (match-beginning 0)
13465 (if (re-search-forward org-keyword-time-not-clock-regexp
13466 (line-end-position)
13468 (match-beginning 0)
13469 (line-end-position))))))
13470 ;; If there is nothing more to add and no more keyword
13471 ;; is left, remove the line completely.
13472 (if (and (org-looking-at-p "[ \t]*$") (not what))
13473 (delete-region (line-beginning-position)
13474 (line-beginning-position 2))
13475 ;; If we removed last keyword, do not leave trailing
13476 ;; white space at the end of line.
13477 (let ((p (point)))
13478 (save-excursion
13479 (end-of-line)
13480 (unless (= (skip-chars-backward " \t" p) 0)
13481 (delete-region (point) (line-end-position)))))))
13482 ((not what) (throw 'exit nil)) ; Nothing to do.
13483 (t (insert-before-markers "\n")
13484 (backward-char 1)
13485 (when org-adapt-indentation
13486 (org-indent-to-column (1+ (org-outline-level))))))
13487 (when what
13488 ;; Insert planning keyword.
13489 (insert (cl-case what
13490 (closed org-closed-string)
13491 (deadline org-deadline-string)
13492 (scheduled org-scheduled-string)
13493 (otherwise (error "Invalid planning type: %s" what)))
13494 " ")
13495 ;; Insert associated timestamp.
13496 (let ((ts (org-insert-time-stamp
13497 time
13498 (or org-time-was-given
13499 (and (eq what 'closed) org-log-done-with-time))
13500 (eq what 'closed)
13501 nil nil (list org-end-time-was-given))))
13502 (unless (eolp) (insert " "))
13503 ts))))))
13505 (defvar org-log-note-marker (make-marker)
13506 "Marker pointing at the entry where the note is to be inserted.")
13507 (defvar org-log-note-purpose nil)
13508 (defvar org-log-note-state nil)
13509 (defvar org-log-note-previous-state nil)
13510 (defvar org-log-note-extra nil)
13511 (defvar org-log-note-window-configuration nil)
13512 (defvar org-log-note-return-to (make-marker))
13513 (defvar org-log-note-effective-time nil
13514 "Remembered current time so that dynamically scoped
13515 `org-extend-today-until' affects timestamps in state change log")
13517 (defvar org-log-post-message nil
13518 "Message to be displayed after a log note has been stored.
13519 The auto-repeater uses this.")
13521 (defun org-add-note ()
13522 "Add a note to the current entry.
13523 This is done in the same way as adding a state change note."
13524 (interactive)
13525 (org-add-log-setup 'note))
13527 (defun org-log-beginning (&optional create)
13528 "Return expected start of log notes in current entry.
13529 When optional argument CREATE is non-nil, the function creates
13530 a drawer to store notes, if necessary. Returned position ignores
13531 narrowing."
13532 (org-with-wide-buffer
13533 (let ((drawer (org-log-into-drawer)))
13534 (cond
13535 (drawer
13536 (org-end-of-meta-data)
13537 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13538 (end (if (org-at-heading-p) (point)
13539 (save-excursion (outline-next-heading) (point))))
13540 (case-fold-search t))
13541 (catch 'exit
13542 ;; Try to find existing drawer.
13543 (while (re-search-forward regexp end t)
13544 (let ((element (org-element-at-point)))
13545 (when (eq (org-element-type element) 'drawer)
13546 (let ((cend (org-element-property :contents-end element)))
13547 (when (and (not org-log-states-order-reversed) cend)
13548 (goto-char cend)))
13549 (throw 'exit nil))))
13550 ;; No drawer found. Create one, if permitted.
13551 (when create
13552 (unless (bolp) (insert "\n"))
13553 (let ((beg (point)))
13554 (insert ":" drawer ":\n:END:\n")
13555 (org-indent-region beg (point)))
13556 (end-of-line -1)))))
13558 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13559 (skip-chars-forward " \t\n")
13560 (beginning-of-line)
13561 (unless org-log-states-order-reversed
13562 (org-skip-over-state-notes)
13563 (skip-chars-backward " \t\n")
13564 (forward-line)))))
13565 (if (bolp) (point) (line-beginning-position 2))))
13567 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13568 "Set up the post command hook to take a note.
13569 If this is about to TODO state change, the new state is expected in STATE.
13570 HOW is an indicator what kind of note should be created.
13571 EXTRA is additional text that will be inserted into the notes buffer."
13572 (move-marker org-log-note-marker (point))
13573 (setq org-log-note-purpose purpose
13574 org-log-note-state state
13575 org-log-note-previous-state prev-state
13576 org-log-note-how how
13577 org-log-note-extra extra
13578 org-log-note-effective-time (org-current-effective-time))
13579 (add-hook 'post-command-hook 'org-add-log-note 'append))
13581 (defun org-skip-over-state-notes ()
13582 "Skip past the list of State notes in an entry."
13583 (when (ignore-errors (goto-char (org-in-item-p)))
13584 (let* ((struct (org-list-struct))
13585 (prevs (org-list-prevs-alist struct))
13586 (regexp
13587 (concat "[ \t]*- +"
13588 (replace-regexp-in-string
13589 " +" " +"
13590 (org-replace-escapes
13591 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13592 `(("%d" . ,org-ts-regexp-inactive)
13593 ("%D" . ,org-ts-regexp)
13594 ("%s" . "\"\\S-+\"")
13595 ("%S" . "\"\\S-+\"")
13596 ("%t" . ,org-ts-regexp-inactive)
13597 ("%T" . ,org-ts-regexp)
13598 ("%u" . ".*?")
13599 ("%U" . ".*?")))))))
13600 (while (org-looking-at-p regexp)
13601 (goto-char (or (org-list-get-next-item (point) struct prevs)
13602 (org-list-get-item-end (point) struct)))))))
13604 (defun org-add-log-note (&optional _purpose)
13605 "Pop up a window for taking a note, and add this note later."
13606 (remove-hook 'post-command-hook 'org-add-log-note)
13607 (setq org-log-note-window-configuration (current-window-configuration))
13608 (delete-other-windows)
13609 (move-marker org-log-note-return-to (point))
13610 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13611 (goto-char org-log-note-marker)
13612 (org-switch-to-buffer-other-window "*Org Note*")
13613 (erase-buffer)
13614 (if (memq org-log-note-how '(time state))
13615 (let (current-prefix-arg) (org-store-log-note))
13616 (let ((org-inhibit-startup t)) (org-mode))
13617 (insert (format "# Insert note for %s.
13618 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13619 (cond
13620 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13621 ((eq org-log-note-purpose 'done) "closed todo item")
13622 ((eq org-log-note-purpose 'state)
13623 (format "state change from \"%s\" to \"%s\""
13624 (or org-log-note-previous-state "")
13625 (or org-log-note-state "")))
13626 ((eq org-log-note-purpose 'reschedule)
13627 "rescheduling")
13628 ((eq org-log-note-purpose 'delschedule)
13629 "no longer scheduled")
13630 ((eq org-log-note-purpose 'redeadline)
13631 "changing deadline")
13632 ((eq org-log-note-purpose 'deldeadline)
13633 "removing deadline")
13634 ((eq org-log-note-purpose 'refile)
13635 "refiling")
13636 ((eq org-log-note-purpose 'note)
13637 "this entry")
13638 (t (error "This should not happen")))))
13639 (when org-log-note-extra (insert org-log-note-extra))
13640 (setq-local org-finish-function 'org-store-log-note)
13641 (run-hooks 'org-log-buffer-setup-hook)))
13643 (defvar org-note-abort nil) ; dynamically scoped
13644 (defun org-store-log-note ()
13645 "Finish taking a log note, and insert it to where it belongs."
13646 (let ((txt (prog1 (buffer-string)
13647 (kill-buffer)))
13648 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13649 lines)
13650 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13651 (setq txt (replace-match "" t t txt)))
13652 (when (string-match "\\s-+\\'" txt)
13653 (setq txt (replace-match "" t t txt)))
13654 (setq lines (org-split-string txt "\n"))
13655 (when (org-string-nw-p note)
13656 (setq note
13657 (org-replace-escapes
13658 note
13659 (list (cons "%u" (user-login-name))
13660 (cons "%U" user-full-name)
13661 (cons "%t" (format-time-string
13662 (org-time-stamp-format 'long 'inactive)
13663 org-log-note-effective-time))
13664 (cons "%T" (format-time-string
13665 (org-time-stamp-format 'long nil)
13666 org-log-note-effective-time))
13667 (cons "%d" (format-time-string
13668 (org-time-stamp-format nil 'inactive)
13669 org-log-note-effective-time))
13670 (cons "%D" (format-time-string
13671 (org-time-stamp-format nil nil)
13672 org-log-note-effective-time))
13673 (cons "%s" (cond
13674 ((not org-log-note-state) "")
13675 ((org-string-match-p org-ts-regexp
13676 org-log-note-state)
13677 (format "\"[%s]\""
13678 (substring org-log-note-state 1 -1)))
13679 (t (format "\"%s\"" org-log-note-state))))
13680 (cons "%S"
13681 (cond
13682 ((not org-log-note-previous-state) "")
13683 ((org-string-match-p org-ts-regexp
13684 org-log-note-previous-state)
13685 (format "\"[%s]\""
13686 (substring
13687 org-log-note-previous-state 1 -1)))
13688 (t (format "\"%s\""
13689 org-log-note-previous-state)))))))
13690 (when lines (setq note (concat note " \\\\")))
13691 (push note lines))
13692 (when (and lines (not (or current-prefix-arg org-note-abort)))
13693 (with-current-buffer (marker-buffer org-log-note-marker)
13694 (org-with-wide-buffer
13695 ;; Find location for the new note.
13696 (goto-char org-log-note-marker)
13697 (set-marker org-log-note-marker nil)
13698 (goto-char (org-log-beginning t))
13699 ;; Make sure point is at the beginning of an empty line.
13700 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13701 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13702 ;; In an existing list, add a new item at the top level.
13703 ;; Otherwise, indent line like a regular one.
13704 (let ((itemp (org-in-item-p)))
13705 (if itemp
13706 (org-indent-line-to
13707 (let ((struct (save-excursion
13708 (goto-char itemp) (org-list-struct))))
13709 (org-list-get-ind (org-list-get-top-point struct) struct)))
13710 (org-indent-line)))
13711 (insert (org-list-bullet-string "-") (pop lines))
13712 (let ((ind (org-list-item-body-column (line-beginning-position))))
13713 (dolist (line lines)
13714 (insert "\n")
13715 (org-indent-line-to ind)
13716 (insert line)))
13717 (message "Note stored")
13718 (org-back-to-heading t)
13719 (org-cycle-hide-drawers 'children))
13720 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13721 ;; from within `org-add-log-note' because `buffer-undo-list'
13722 ;; is then modified outside of `org-with-remote-undo'.
13723 (when (eq this-command 'org-agenda-todo)
13724 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13725 ;; Don't add undo information when called from `org-agenda-todo'.
13726 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13727 (set-window-configuration org-log-note-window-configuration)
13728 (with-current-buffer (marker-buffer org-log-note-return-to)
13729 (goto-char org-log-note-return-to))
13730 (move-marker org-log-note-return-to nil)
13731 (when org-log-post-message (message "%s" org-log-post-message))))
13733 (defun org-remove-empty-drawer-at (pos)
13734 "Remove an empty drawer at position POS.
13735 POS may also be a marker."
13736 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13737 (org-with-wide-buffer
13738 (goto-char pos)
13739 (let ((drawer (org-element-at-point)))
13740 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13741 (not (org-element-property :contents-begin drawer)))
13742 (delete-region (org-element-property :begin drawer)
13743 (progn (goto-char (org-element-property :end drawer))
13744 (skip-chars-backward " \r\t\n")
13745 (forward-line)
13746 (point))))))))
13748 (defvar org-ts-type nil)
13749 (defun org-sparse-tree (&optional arg type)
13750 "Create a sparse tree, prompt for the details.
13751 This command can create sparse trees. You first need to select the type
13752 of match used to create the tree:
13754 t Show all TODO entries.
13755 T Show entries with a specific TODO keyword.
13756 m Show entries selected by a tags/property match.
13757 p Enter a property name and its value (both with completion on existing
13758 names/values) and show entries with that property.
13759 r Show entries matching a regular expression (`/' can be used as well).
13760 b Show deadlines and scheduled items before a date.
13761 a Show deadlines and scheduled items after a date.
13762 d Show deadlines due within `org-deadline-warning-days'.
13763 D Show deadlines and scheduled items between a date range."
13764 (interactive "P")
13765 (setq type (or type org-sparse-tree-default-date-type))
13766 (setq org-ts-type type)
13767 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13768 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13769 \[c]ycle through date types: %s"
13770 (cl-case type
13771 (all "all timestamps")
13772 (scheduled "only scheduled")
13773 (deadline "only deadline")
13774 (active "only active timestamps")
13775 (inactive "only inactive timestamps")
13776 (closed "with a closed time-stamp")
13777 (otherwise "scheduled/deadline")))
13778 (let ((answer (read-char-exclusive)))
13779 (cl-case answer
13781 (org-sparse-tree
13783 (cadr
13784 (memq type '(nil all scheduled deadline active inactive closed)))))
13785 (?d (call-interactively 'org-check-deadlines))
13786 (?b (call-interactively 'org-check-before-date))
13787 (?a (call-interactively 'org-check-after-date))
13788 (?D (call-interactively 'org-check-dates-range))
13789 (?t (call-interactively 'org-show-todo-tree))
13790 (?T (org-show-todo-tree '(4)))
13791 (?m (call-interactively 'org-match-sparse-tree))
13792 ((?p ?P)
13793 (let* ((kwd (completing-read
13794 "Property: " (mapcar #'list (org-buffer-property-keys))))
13795 (value (completing-read
13796 "Value: " (mapcar #'list (org-property-values kwd)))))
13797 (unless (string-match "\\`{.*}\\'" value)
13798 (setq value (concat "\"" value "\"")))
13799 (org-match-sparse-tree arg (concat kwd "=" value))))
13800 ((?r ?R ?/) (call-interactively 'org-occur))
13801 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13803 (defvar-local org-occur-highlights nil
13804 "List of overlays used for occur matches.")
13805 (defvar-local org-occur-parameters nil
13806 "Parameters of the active org-occur calls.
13807 This is a list, each call to org-occur pushes as cons cell,
13808 containing the regular expression and the callback, onto the list.
13809 The list can contain several entries if `org-occur' has been called
13810 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13811 will only contain one set of parameters. When the highlights are
13812 removed (for example with `C-c C-c', or with the next edit (depending
13813 on `org-remove-highlights-with-change'), this variable is emptied
13814 as well.")
13816 (defun org-occur (regexp &optional keep-previous callback)
13817 "Make a compact tree which shows all matches of REGEXP.
13818 The tree will show the lines where the regexp matches, and all higher
13819 headlines above the match. It will also show the heading after the match,
13820 to make sure editing the matching entry is easy.
13821 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13822 call to `org-occur' will be kept, to allow stacking of calls to this
13823 command.
13824 If CALLBACK is non-nil, it is a function which is called to confirm
13825 that the match should indeed be shown."
13826 (interactive "sRegexp: \nP")
13827 (when (equal regexp "")
13828 (user-error "Regexp cannot be empty"))
13829 (unless keep-previous
13830 (org-remove-occur-highlights nil nil t))
13831 (push (cons regexp callback) org-occur-parameters)
13832 (let ((cnt 0))
13833 (save-excursion
13834 (goto-char (point-min))
13835 (when (or (not keep-previous) ; do not want to keep
13836 (not org-occur-highlights)) ; no previous matches
13837 ;; hide everything
13838 (org-overview))
13839 (while (re-search-forward regexp nil t)
13840 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13841 (when (or (not callback)
13842 (save-match-data (funcall callback)))
13843 (setq cnt (1+ cnt))
13844 (when org-highlight-sparse-tree-matches
13845 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13846 (org-show-context 'occur-tree))))
13847 (when org-remove-highlights-with-change
13848 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13849 nil 'local))
13850 (unless org-sparse-tree-open-archived-trees
13851 (org-hide-archived-subtrees (point-min) (point-max)))
13852 (run-hooks 'org-occur-hook)
13853 (when (org-called-interactively-p 'interactive)
13854 (message "%d match(es) for regexp %s" cnt regexp))
13855 cnt))
13857 (defun org-occur-next-match (&optional n _reset)
13858 "Function for `next-error-function' to find sparse tree matches.
13859 N is the number of matches to move, when negative move backwards.
13860 This function always goes back to the starting point when no
13861 match is found."
13862 (let* ((limit (if (< n 0) (point-min) (point-max)))
13863 (search-func (if (< n 0)
13864 'previous-single-char-property-change
13865 'next-single-char-property-change))
13866 (n (abs n))
13867 (pos (point))
13869 (catch 'exit
13870 (while (setq p1 (funcall search-func (point) 'org-type))
13871 (when (equal p1 limit)
13872 (goto-char pos)
13873 (user-error "No more matches"))
13874 (when (equal (get-char-property p1 'org-type) 'org-occur)
13875 (setq n (1- n))
13876 (when (= n 0)
13877 (goto-char p1)
13878 (throw 'exit (point))))
13879 (goto-char p1))
13880 (goto-char p1)
13881 (user-error "No more matches"))))
13883 (defun org-show-context (&optional key)
13884 "Make sure point and context are visible.
13885 Optional argument KEY, when non-nil, is a symbol. See
13886 `org-show-context-detail' for allowed values and how much is to
13887 be shown."
13888 (org-show-set-visibility
13889 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13890 ((cdr (assq key org-show-context-detail)))
13891 (t (cdr (assq 'default org-show-context-detail))))))
13893 (defun org-show-set-visibility (detail)
13894 "Set visibility around point according to DETAIL.
13895 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13896 `tree', `canonical' or t. See `org-show-context-detail' for more
13897 information."
13898 (unless (org-before-first-heading-p)
13899 ;; Show current heading and possibly its entry, following headline
13900 ;; or all children.
13901 (if (and (org-at-heading-p) (not (eq detail 'local)))
13902 (org-flag-heading nil)
13903 (org-show-entry)
13904 (org-with-limited-levels
13905 (cl-case detail
13906 ((tree canonical t) (org-show-children))
13907 ((nil minimal ancestors))
13908 (t (save-excursion
13909 (outline-next-heading)
13910 (org-flag-heading nil))))))
13911 ;; Show all siblings.
13912 (when (eq detail 'lineage) (org-show-siblings))
13913 ;; Show ancestors, possibly with their children.
13914 (when (memq detail '(ancestors lineage tree canonical t))
13915 (save-excursion
13916 (while (org-up-heading-safe)
13917 (org-flag-heading nil)
13918 (when (memq detail '(canonical t)) (org-show-entry))
13919 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13921 (defvar org-reveal-start-hook nil
13922 "Hook run before revealing a location.")
13924 (defun org-reveal (&optional siblings)
13925 "Show current entry, hierarchy above it, and the following headline.
13927 This can be used to show a consistent set of context around
13928 locations exposed with `org-show-context'.
13930 With optional argument SIBLINGS, on each level of the hierarchy all
13931 siblings are shown. This repairs the tree structure to what it would
13932 look like when opened with hierarchical calls to `org-cycle'.
13934 With double optional argument \\[universal-argument] \\[universal-argument], \
13935 go to the parent and show the
13936 entire tree."
13937 (interactive "P")
13938 (run-hooks 'org-reveal-start-hook)
13939 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13940 ((equal siblings '(16))
13941 (save-excursion
13942 (when (org-up-heading-safe)
13943 (org-show-subtree)
13944 (run-hook-with-args 'org-cycle-hook 'subtree))))
13945 (t (org-show-set-visibility 'lineage))))
13947 (defun org-highlight-new-match (beg end)
13948 "Highlight from BEG to END and mark the highlight is an occur headline."
13949 (let ((ov (make-overlay beg end)))
13950 (overlay-put ov 'face 'secondary-selection)
13951 (overlay-put ov 'org-type 'org-occur)
13952 (push ov org-occur-highlights)))
13954 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13955 "Remove the occur highlights from the buffer.
13956 BEG and END are ignored. If NOREMOVE is nil, remove this function
13957 from the `before-change-functions' in the current buffer."
13958 (interactive)
13959 (unless org-inhibit-highlight-removal
13960 (mapc #'delete-overlay org-occur-highlights)
13961 (setq org-occur-highlights nil)
13962 (setq org-occur-parameters nil)
13963 (unless noremove
13964 (remove-hook 'before-change-functions
13965 'org-remove-occur-highlights 'local))))
13967 ;;;; Priorities
13969 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13970 "Regular expression matching the priority indicator.")
13972 (defvar org-remove-priority-next-time nil)
13974 (defun org-priority-up ()
13975 "Increase the priority of the current item."
13976 (interactive)
13977 (org-priority 'up))
13979 (defun org-priority-down ()
13980 "Decrease the priority of the current item."
13981 (interactive)
13982 (org-priority 'down))
13984 (defun org-priority (&optional action _show)
13985 "Change the priority of an item.
13986 ACTION can be `set', `up', `down', or a character."
13987 (interactive "P")
13988 (if (equal action '(4))
13989 (org-show-priority)
13990 (unless org-enable-priority-commands
13991 (user-error "Priority commands are disabled"))
13992 (setq action (or action 'set))
13993 (let (current new news have remove)
13994 (save-excursion
13995 (org-back-to-heading t)
13996 (when (looking-at org-priority-regexp)
13997 (setq current (string-to-char (match-string 2))
13998 have t))
13999 (cond
14000 ((eq action 'remove)
14001 (setq remove t new ?\ ))
14002 ((or (eq action 'set)
14003 (if (featurep 'xemacs) (characterp action) (integerp action)))
14004 (if (not (eq action 'set))
14005 (setq new action)
14006 (message "Priority %c-%c, SPC to remove: "
14007 org-highest-priority org-lowest-priority)
14008 (save-match-data
14009 (setq new (read-char-exclusive))))
14010 (when (and (= (upcase org-highest-priority) org-highest-priority)
14011 (= (upcase org-lowest-priority) org-lowest-priority))
14012 (setq new (upcase new)))
14013 (cond ((equal new ?\ ) (setq remove t))
14014 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14015 (user-error "Priority must be between `%c' and `%c'"
14016 org-highest-priority org-lowest-priority))))
14017 ((eq action 'up)
14018 (setq new (if have
14019 (1- current) ; normal cycling
14020 ;; last priority was empty
14021 (if (eq last-command this-command)
14022 org-lowest-priority ; wrap around empty to lowest
14023 ;; default
14024 (if org-priority-start-cycle-with-default
14025 org-default-priority
14026 (1- org-default-priority))))))
14027 ((eq action 'down)
14028 (setq new (if have
14029 (1+ current) ; normal cycling
14030 ;; last priority was empty
14031 (if (eq last-command this-command)
14032 org-highest-priority ; wrap around empty to highest
14033 ;; default
14034 (if org-priority-start-cycle-with-default
14035 org-default-priority
14036 (1+ org-default-priority))))))
14037 (t (user-error "Invalid action")))
14038 (when (or (< (upcase new) org-highest-priority)
14039 (> (upcase new) org-lowest-priority))
14040 (if (and (memq action '(up down))
14041 (not have) (not (eq last-command this-command)))
14042 ;; `new' is from default priority
14043 (error
14044 "The default can not be set, see `org-default-priority' why")
14045 ;; normal cycling: `new' is beyond highest/lowest priority
14046 ;; and is wrapped around to the empty priority
14047 (setq remove t)))
14048 (setq news (format "%c" new))
14049 (if have
14050 (if remove
14051 (replace-match "" t t nil 1)
14052 (replace-match news t t nil 2))
14053 (if remove
14054 (user-error "No priority cookie found in line")
14055 (let ((case-fold-search nil))
14056 (looking-at org-todo-line-regexp))
14057 (if (match-end 2)
14058 (progn
14059 (goto-char (match-end 2))
14060 (insert " [#" news "]"))
14061 (goto-char (match-beginning 3))
14062 (insert "[#" news "] "))))
14063 (org-set-tags nil 'align))
14064 (if remove
14065 (message "Priority removed")
14066 (message "Priority of current item set to %s" news)))))
14068 (defun org-show-priority ()
14069 "Show the priority of the current item.
14070 This priority is composed of the main priority given with the [#A] cookies,
14071 and by additional input from the age of a schedules or deadline entry."
14072 (interactive)
14073 (let ((pri (if (eq major-mode 'org-agenda-mode)
14074 (org-get-at-bol 'priority)
14075 (save-excursion
14076 (save-match-data
14077 (beginning-of-line)
14078 (and (looking-at org-heading-regexp)
14079 (org-get-priority (match-string 0))))))))
14080 (message "Priority is %d" (if pri pri -1000))))
14082 (defun org-get-priority (s)
14083 "Find priority cookie and return priority."
14084 (save-match-data
14085 (if (functionp org-get-priority-function)
14086 (funcall org-get-priority-function)
14087 (if (not (string-match org-priority-regexp s))
14088 (* 1000 (- org-lowest-priority org-default-priority))
14089 (* 1000 (- org-lowest-priority
14090 (string-to-char (match-string 2 s))))))))
14092 ;;;; Tags
14094 (defvar org-agenda-archives-mode)
14095 (defvar org-map-continue-from nil
14096 "Position from where mapping should continue.
14097 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14099 (defvar org-scanner-tags nil
14100 "The current tag list while the tags scanner is running.")
14102 (defvar org-trust-scanner-tags nil
14103 "Should `org-get-tags-at' use the tags for the scanner.
14104 This is for internal dynamical scoping only.
14105 When this is non-nil, the function `org-get-tags-at' will return the value
14106 of `org-scanner-tags' instead of building the list by itself. This
14107 can lead to large speed-ups when the tags scanner is used in a file with
14108 many entries, and when the list of tags is retrieved, for example to
14109 obtain a list of properties. Building the tags list for each entry in such
14110 a file becomes an N^2 operation - but with this variable set, it scales
14111 as N.")
14113 (defvar org--matcher-tags-todo-only nil)
14115 (defun org-scan-tags (action matcher todo-only &optional start-level)
14116 "Scan headline tags with inheritance and produce output ACTION.
14118 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14119 or `agenda' to produce an entry list for an agenda view. It can also be
14120 a Lisp form or a function that should be called at each matched headline, in
14121 this case the return value is a list of all return values from these calls.
14123 MATCHER is a function accepting three arguments, returning
14124 a non-nil value whenever a given set of tags qualifies a headline
14125 for inclusion. See `org-make-tags-matcher' for more information.
14126 As a special case, it can also be set to t (respectively nil) in
14127 order to match all (respectively none) headline.
14129 When TODO-ONLY is non-nil, only lines with a not-done TODO
14130 keyword are included in the output.
14132 START-LEVEL can be a string with asterisks, reducing the scope to
14133 headlines matching this string."
14134 (require 'org-agenda)
14135 (let* ((re (concat "^"
14136 (if start-level
14137 ;; Get the correct level to match
14138 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14139 org-outline-regexp)
14140 " *\\(\\<\\("
14141 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14142 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14143 (props (list 'face 'default
14144 'done-face 'org-agenda-done
14145 'undone-face 'default
14146 'mouse-face 'highlight
14147 'org-not-done-regexp org-not-done-regexp
14148 'org-todo-regexp org-todo-regexp
14149 'org-complex-heading-regexp org-complex-heading-regexp
14150 'help-echo
14151 (format "mouse-2 or RET jump to org file %s"
14152 (abbreviate-file-name
14153 (or (buffer-file-name (buffer-base-buffer))
14154 (buffer-name (buffer-base-buffer)))))))
14155 (org-map-continue-from nil)
14156 lspos tags tags-list
14157 (tags-alist (list (cons 0 org-file-tags)))
14158 (llast 0) rtn rtn1 level category i txt
14159 todo marker entry priority
14160 ts-date ts-date-type ts-date-pair)
14161 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14162 (setq action (list 'lambda nil action)))
14163 (save-excursion
14164 (goto-char (point-min))
14165 (when (eq action 'sparse-tree)
14166 (org-overview)
14167 (org-remove-occur-highlights))
14168 (while (let (case-fold-search)
14169 (re-search-forward re nil t))
14170 (setq org-map-continue-from nil)
14171 (catch :skip
14172 (setq todo
14173 ;; TODO: is the 1-2 difference a bug?
14174 (when (match-end 1) (org-match-string-no-properties 2))
14175 tags (when (match-end 4) (org-match-string-no-properties 4)))
14176 (goto-char (setq lspos (match-beginning 0)))
14177 (setq level (org-reduced-level (org-outline-level))
14178 category (org-get-category))
14179 (when (eq action 'agenda)
14180 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14181 ts-date (car ts-date-pair)
14182 ts-date-type (cdr ts-date-pair)))
14183 (setq i llast llast level)
14184 ;; remove tag lists from same and sublevels
14185 (while (>= i level)
14186 (when (setq entry (assoc i tags-alist))
14187 (setq tags-alist (delete entry tags-alist)))
14188 (setq i (1- i)))
14189 ;; add the next tags
14190 (when tags
14191 (setq tags (org-split-string tags ":")
14192 tags-alist
14193 (cons (cons level tags) tags-alist)))
14194 ;; compile tags for current headline
14195 (setq tags-list
14196 (if org-use-tag-inheritance
14197 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14198 tags)
14199 org-scanner-tags tags-list)
14200 (when org-use-tag-inheritance
14201 (setcdr (car tags-alist)
14202 (mapcar (lambda (x)
14203 (setq x (copy-sequence x))
14204 (org-add-prop-inherited x))
14205 (cdar tags-alist))))
14206 (when (and tags org-use-tag-inheritance
14207 (or (not (eq t org-use-tag-inheritance))
14208 org-tags-exclude-from-inheritance))
14209 ;; Selective inheritance, remove uninherited ones.
14210 (setcdr (car tags-alist)
14211 (org-remove-uninherited-tags (cdar tags-alist))))
14212 (when (and
14214 ;; eval matcher only when the todo condition is OK
14215 (and (or (not todo-only) (member todo org-not-done-keywords))
14216 (if (functionp matcher)
14217 (let ((case-fold-search t) (org-trust-scanner-tags t))
14218 (funcall matcher todo tags-list level))
14219 matcher))
14221 ;; Call the skipper, but return t if it does not
14222 ;; skip, so that the `and' form continues evaluating.
14223 (progn
14224 (unless (eq action 'sparse-tree) (org-agenda-skip))
14227 ;; Check if timestamps are deselecting this entry
14228 (or (not todo-only)
14229 (and (member todo org-not-done-keywords)
14230 (or (not org-agenda-tags-todo-honor-ignore-options)
14231 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14233 ;; select this headline
14234 (cond
14235 ((eq action 'sparse-tree)
14236 (and org-highlight-sparse-tree-matches
14237 (org-get-heading) (match-end 0)
14238 (org-highlight-new-match
14239 (match-beginning 1) (match-end 1)))
14240 (org-show-context 'tags-tree))
14241 ((eq action 'agenda)
14242 (setq txt (org-agenda-format-item
14244 (concat
14245 (if (eq org-tags-match-list-sublevels 'indented)
14246 (make-string (1- level) ?.) "")
14247 (org-get-heading))
14248 (make-string level ?\s)
14249 category
14250 tags-list)
14251 priority (org-get-priority txt))
14252 (goto-char lspos)
14253 (setq marker (org-agenda-new-marker))
14254 (org-add-props txt props
14255 'org-marker marker 'org-hd-marker marker 'org-category category
14256 'todo-state todo
14257 'ts-date ts-date
14258 'priority priority
14259 'type (concat "tagsmatch" ts-date-type))
14260 (push txt rtn))
14261 ((functionp action)
14262 (setq org-map-continue-from nil)
14263 (save-excursion
14264 (setq rtn1 (funcall action))
14265 (push rtn1 rtn)))
14266 (t (user-error "Invalid action")))
14268 ;; if we are to skip sublevels, jump to end of subtree
14269 (unless org-tags-match-list-sublevels
14270 (org-end-of-subtree t)
14271 (backward-char 1))))
14272 ;; Get the correct position from where to continue
14273 (if org-map-continue-from
14274 (goto-char org-map-continue-from)
14275 (and (= (point) lspos) (end-of-line 1)))))
14276 (when (and (eq action 'sparse-tree)
14277 (not org-sparse-tree-open-archived-trees))
14278 (org-hide-archived-subtrees (point-min) (point-max)))
14279 (nreverse rtn)))
14281 (defun org-remove-uninherited-tags (tags)
14282 "Remove all tags that are not inherited from the list TAGS."
14283 (cond
14284 ((eq org-use-tag-inheritance t)
14285 (if org-tags-exclude-from-inheritance
14286 (org-delete-all org-tags-exclude-from-inheritance tags)
14287 tags))
14288 ((not org-use-tag-inheritance) nil)
14289 ((stringp org-use-tag-inheritance)
14290 (delq nil (mapcar
14291 (lambda (x)
14292 (if (and (string-match org-use-tag-inheritance x)
14293 (not (member x org-tags-exclude-from-inheritance)))
14294 x nil))
14295 tags)))
14296 ((listp org-use-tag-inheritance)
14297 (delq nil (mapcar
14298 (lambda (x)
14299 (if (member x org-use-tag-inheritance) x nil))
14300 tags)))))
14302 (defun org-match-sparse-tree (&optional todo-only match)
14303 "Create a sparse tree according to tags string MATCH.
14304 MATCH can contain positive and negative selection of tags, like
14305 \"+WORK+URGENT-WITHBOSS\".
14306 If optional argument TODO-ONLY is non-nil, only select lines that are
14307 also TODO lines."
14308 (interactive "P")
14309 (org-agenda-prepare-buffers (list (current-buffer)))
14310 (let ((org--matcher-tags-todo-only todo-only))
14311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14312 org--matcher-tags-todo-only)))
14314 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14316 (defvar org-cached-props nil)
14317 (defun org-cached-entry-get (pom property)
14318 (if (or (eq t org-use-property-inheritance)
14319 (and (stringp org-use-property-inheritance)
14320 (let ((case-fold-search t))
14321 (org-string-match-p org-use-property-inheritance property)))
14322 (and (listp org-use-property-inheritance)
14323 (member-ignore-case property org-use-property-inheritance)))
14324 ;; Caching is not possible, check it directly.
14325 (org-entry-get pom property 'inherit)
14326 ;; Get all properties, so we can do complicated checks easily.
14327 (cdr (assoc-string property
14328 (or org-cached-props
14329 (setq org-cached-props (org-entry-properties pom)))
14330 t))))
14332 (defun org-global-tags-completion-table (&optional files)
14333 "Return the list of all tags in all agenda buffer/files.
14334 Optional FILES argument is a list of files which can be used
14335 instead of the agenda files."
14336 (save-excursion
14337 (org-uniquify
14338 (delq nil
14339 (apply 'append
14340 (mapcar
14341 (lambda (file)
14342 (set-buffer (find-file-noselect file))
14343 (append (org-get-buffer-tags)
14344 (mapcar (lambda (x) (if (stringp (car-safe x))
14345 (list (car-safe x)) nil))
14346 org-tag-alist)))
14347 (if (and files (car files))
14348 files
14349 (org-agenda-files))))))))
14351 (defun org-make-tags-matcher (match)
14352 "Create the TAGS/TODO matcher form for the selection string MATCH.
14354 Returns a cons of the selection string MATCH and a function
14355 implementing the matcher.
14357 The matcher is to be called at an Org entry, with point on the
14358 headline, and returns non-nil if the entry matches the selection
14359 string MATCH. It must be called with three arguments: the TODO
14360 keyword at the entry (or nil if none), the list of all tags at
14361 the entry including inherited ones and the reduced level of the
14362 headline. Additionally, the category of the entry, if any, must
14363 be specified as the text property `org-category' on the headline.
14365 This function sets the variable `org--matcher-tags-todo-only' to
14366 a non-nil value if the matcher restricts matching to TODO
14367 entries, otherwise it is not touched.
14369 See also `org-scan-tags'."
14370 (unless match
14371 ;; Get a new match request, with completion against the global
14372 ;; tags table and the local tags in current buffer.
14373 (let ((org-last-tags-completion-table
14374 (org-uniquify
14375 (delq nil (append (org-get-buffer-tags)
14376 (org-global-tags-completion-table))))))
14377 (setq match
14378 (completing-read
14379 "Match: "
14380 'org-tags-completion-function nil nil nil 'org-tags-history))))
14382 (let ((match0 match)
14383 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14384 (start 0)
14385 tagsmatch todomatch tagsmatcher todomatcher)
14387 ;; Expand group tags.
14388 (setq match (org-tags-expand match))
14390 ;; Check if there is a TODO part of this match, which would be the
14391 ;; part after a "/". To make sure that this slash is not part of
14392 ;; a property value to be matched against, we also check that
14393 ;; there is no / after that slash. First, find the last slash.
14394 (let ((s 0))
14395 (while (string-match "/+" match s)
14396 (setq start (match-beginning 0))
14397 (setq s (match-end 0))))
14398 (if (and (string-match "/+" match start)
14399 (not (string-match-p "\"" match start)))
14400 ;; Match contains also a TODO-matching request.
14401 (progn
14402 (setq tagsmatch (substring match 0 (match-beginning 0)))
14403 (setq todomatch (substring match (match-end 0)))
14404 (when (string-match "\\`!" todomatch)
14405 (setq org--matcher-tags-todo-only t)
14406 (setq todomatch (substring todomatch 1)))
14407 (when (string-match "\\`\\s-*\\'" todomatch)
14408 (setq todomatch nil)))
14409 ;; Only matching tags.
14410 (setq tagsmatch match)
14411 (setq todomatch nil))
14413 ;; Make the tags matcher.
14414 (when (org-string-nw-p tagsmatch)
14415 (let ((orlist nil)
14416 (orterms (org-split-string tagsmatch "|"))
14417 term)
14418 (while (setq term (pop orterms))
14419 (while (and (equal (substring term -1) "\\") orterms)
14420 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14421 (while (string-match re term)
14422 (let* ((rest (substring term (match-end 0)))
14423 (minus (and (match-end 1)
14424 (equal (match-string 1 term) "-")))
14425 (tag (save-match-data
14426 (replace-regexp-in-string
14427 "\\\\-" "-" (match-string 2 term))))
14428 (regexp (eq (string-to-char tag) ?{))
14429 (levelp (match-end 4))
14430 (propp (match-end 5))
14432 (cond
14433 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14434 (levelp
14435 `(,(org-op-to-function (match-string 3 term))
14436 level
14437 ,(string-to-number (match-string 4 term))))
14438 (propp
14439 (let* ((gv (pcase (upcase (match-string 5 term))
14440 ("CATEGORY"
14441 '(get-text-property (point) 'org-category))
14442 ("TODO" 'todo)
14443 (p `(org-cached-entry-get nil ,p))))
14444 (pv (match-string 7 term))
14445 (regexp (eq (string-to-char pv) ?{))
14446 (strp (eq (string-to-char pv) ?\"))
14447 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14448 (po (org-op-to-function (match-string 6 term)
14449 (if timep 'time strp))))
14450 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14451 (when timep (setq pv (org-matcher-time pv)))
14452 (cond ((and regexp (eq po 'org<>))
14453 `(not (string-match ,pv (or ,gv ""))))
14454 (regexp `(string-match ,pv (or ,gv "")))
14455 (strp `(,po (or ,gv "") ,pv))
14457 `(,po
14458 (string-to-number (or ,gv ""))
14459 ,(string-to-number pv))))))
14460 (t `(member ,tag tags-list)))))
14461 (push (if minus `(not ,mm) mm) tagsmatcher)
14462 (setq term rest)))
14463 (push `(and ,@tagsmatcher) orlist)
14464 (setq tagsmatcher nil))
14465 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14467 ;; Make the TODO matcher.
14468 (when (org-string-nw-p todomatch)
14469 (let ((orlist nil))
14470 (dolist (term (org-split-string todomatch "|"))
14471 (while (string-match re term)
14472 (let* ((minus (and (match-end 1)
14473 (equal (match-string 1 term) "-")))
14474 (kwd (match-string 2 term))
14475 (regexp (eq (string-to-char kwd) ?{))
14476 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14477 `(equal todo ,kwd))))
14478 (push (if minus `(not ,mm) mm) todomatcher))
14479 (setq term (substring term (match-end 0))))
14480 (push (if (> (length todomatcher) 1)
14481 (cons 'and todomatcher)
14482 (car todomatcher))
14483 orlist)
14484 (setq todomatcher nil))
14485 (setq todomatcher (cons 'or orlist))))
14487 ;; Return the string and function of the matcher. If no
14488 ;; tags-specific or todo-specific matcher exists, match
14489 ;; everything.
14490 (let ((matcher (if (and tagsmatcher todomatcher)
14491 `(and ,tagsmatcher ,todomatcher)
14492 (or tagsmatcher todomatcher t))))
14493 (when org--matcher-tags-todo-only
14494 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14495 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14497 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14498 "Expand group tags in MATCH.
14500 This replaces every group tag in MATCH with a regexp tag search.
14501 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14502 will be replaced like this:
14504 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14505 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14506 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14508 Replacing by a regexp preserves the structure of the match.
14509 E.g., this expansion
14511 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14513 will match anything tagged with \"Lab\" and \"Home\", or tagged
14514 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14516 A group tag in MATCH can contain regular expressions of its own.
14517 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14518 will be replaced like this:
14520 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14522 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14523 assumed to be a single group tag, and the function will return
14524 the list of tags in this group.
14526 When DOWNCASE is non-nil, expand downcased TAGS."
14527 (if org-group-tags
14528 (let* ((case-fold-search t)
14529 (stable org-mode-syntax-table)
14530 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14531 (taggroups (if downcased
14532 (mapcar (lambda (tg) (mapcar #'downcase tg))
14533 taggroups)
14534 taggroups))
14535 (taggroups-keys (mapcar #'car taggroups))
14536 (return-match (if downcased (downcase match) match))
14537 (count 0)
14538 (work-already-expanded tags-already-expanded)
14539 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14540 ;; @ and _ are allowed as word-components in tags.
14541 (modify-syntax-entry ?@ "w" stable)
14542 (modify-syntax-entry ?_ "w" stable)
14543 ;; Temporarily replace regexp-expressions in the match-expression.
14544 (while (string-match "{.+?}" return-match)
14545 (cl-incf count)
14546 (push (match-string 0 return-match) regexps-in-match)
14547 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14548 (while (and taggroups-keys
14549 (with-syntax-table stable
14550 (string-match
14551 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14552 (regexp-opt taggroups-keys) "\\>\\)")
14553 return-match)))
14554 (let* ((dir (match-string 1 return-match))
14555 (tag (match-string 2 return-match))
14556 (tag (if downcased (downcase tag) tag)))
14557 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14558 (member tag work-already-expanded))
14559 (setq tags-in-group (assoc tag taggroups))
14560 (push tag work-already-expanded)
14561 ;; Recursively expand each tag in the group, if the tag hasn't
14562 ;; already been expanded. Restore the match-data after all recursive calls.
14563 (save-match-data
14564 (let (tags-expanded)
14565 (dolist (x (cdr tags-in-group))
14566 (if (and (member x taggroups-keys)
14567 (not (member x work-already-expanded)))
14568 (setq tags-expanded
14569 (delete-dups
14570 (append
14571 (org-tags-expand x t downcased
14572 work-already-expanded)
14573 tags-expanded)))
14574 (setq tags-expanded
14575 (append (list x) tags-expanded)))
14576 (setq work-already-expanded
14577 (delete-dups
14578 (append tags-expanded
14579 work-already-expanded))))
14580 (setq tags-in-group
14581 (delete-dups (cons (car tags-in-group)
14582 tags-expanded)))))
14583 ;; Filter tag-regexps from tags.
14584 (setq regexp-in-group-escaped
14585 (delq nil (mapcar (lambda (x)
14586 (if (stringp x)
14587 (and (equal "{" (substring x 0 1))
14588 (equal "}" (substring x -1))
14591 tags-in-group))
14592 regexp-in-group
14593 (mapcar (lambda (x)
14594 (substring x 1 -1))
14595 regexp-in-group-escaped)
14596 tags-in-group
14597 (delq nil (mapcar (lambda (x)
14598 (if (stringp x)
14599 (and (not (equal "{" (substring x 0 1)))
14600 (not (equal "}" (substring x -1)))
14603 tags-in-group)))
14604 ;; If single-as-list, do no more in the while-loop.
14605 (if (not single-as-list)
14606 (progn
14607 (when regexp-in-group
14608 (setq regexp-in-group
14609 (concat "\\|"
14610 (mapconcat 'identity regexp-in-group
14611 "\\|"))))
14612 (setq tags-in-group
14613 (concat dir
14614 "{\\<"
14615 (regexp-opt tags-in-group)
14616 "\\>"
14617 regexp-in-group
14618 "}"))
14619 (when (stringp tags-in-group)
14620 (org-add-props tags-in-group '(grouptag t)))
14621 (setq return-match
14622 (replace-match tags-in-group t t return-match)))
14623 (setq tags-in-group
14624 (append regexp-in-group-escaped tags-in-group))))
14625 (setq taggroups-keys (delete tag taggroups-keys))))
14626 ;; Add the regular expressions back into the match-expression again.
14627 (while regexps-in-match
14628 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14629 (pop regexps-in-match)
14630 return-match t t))
14631 (cl-decf count))
14632 (if single-as-list
14633 (if tags-in-group tags-in-group (list return-match))
14634 return-match))
14635 (if single-as-list
14636 (list (if downcased (downcase match) match))
14637 match)))
14639 (defun org-op-to-function (op &optional stringp)
14640 "Turn an operator into the appropriate function."
14641 (setq op
14642 (cond
14643 ((equal op "<" ) '(< string< org-time<))
14644 ((equal op ">" ) '(> org-string> org-time>))
14645 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14646 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14647 ((member op '("=" "==")) '(= string= org-time=))
14648 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14649 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14651 (defun org<> (a b) (not (= a b)))
14652 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14653 (defun org-string>= (a b) (not (string< a b)))
14654 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14655 (defun org-string<> (a b) (not (string= a b)))
14656 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14657 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14658 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14659 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14660 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14661 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14662 (defun org-2ft (s)
14663 "Convert S to a floating point time.
14664 If S is already a number, just return it. If it is a string, parse
14665 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14666 (cond
14667 ((numberp s) s)
14668 ((stringp s)
14669 (condition-case nil
14670 (float-time (apply 'encode-time (org-parse-time-string s)))
14671 (error 0.)))
14672 (t 0.)))
14674 (defun org-time-today ()
14675 "Time in seconds today at 0:00.
14676 Returns the float number of seconds since the beginning of the
14677 epoch to the beginning of today (00:00)."
14678 (float-time (apply 'encode-time
14679 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14681 (defun org-matcher-time (s)
14682 "Interpret a time comparison value."
14683 (save-match-data
14684 (cond
14685 ((string= s "<now>") (float-time))
14686 ((string= s "<today>") (org-time-today))
14687 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14688 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14689 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14690 (+ (org-time-today)
14691 (* (string-to-number (match-string 1 s))
14692 (cdr (assoc (match-string 2 s)
14693 '(("d" . 86400.0) ("w" . 604800.0)
14694 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14695 (t (org-2ft s)))))
14697 (defun org-match-any-p (re list)
14698 "Does re match any element of list?"
14699 (setq list (mapcar (lambda (x) (string-match re x)) list))
14700 (delq nil list))
14702 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14703 (defvar org-tags-overlay (make-overlay 1 1))
14704 (org-detach-overlay org-tags-overlay)
14706 (defun org-get-local-tags-at (&optional pos)
14707 "Get a list of tags defined in the current headline."
14708 (org-get-tags-at pos 'local))
14710 (defun org-get-local-tags ()
14711 "Get a list of tags defined in the current headline."
14712 (org-get-tags-at nil 'local))
14714 (defun org-get-tags-at (&optional pos local)
14715 "Get a list of all headline tags applicable at POS.
14716 POS defaults to point. If tags are inherited, the list contains
14717 the targets in the same sequence as the headlines appear, i.e.
14718 the tags of the current headline come last.
14719 When LOCAL is non-nil, only return tags from the current headline,
14720 ignore inherited ones."
14721 (interactive)
14722 (if (and org-trust-scanner-tags
14723 (or (not pos) (equal pos (point)))
14724 (not local))
14725 org-scanner-tags
14726 (let (tags ltags lastpos parent)
14727 (save-excursion
14728 (save-restriction
14729 (widen)
14730 (goto-char (or pos (point)))
14731 (save-match-data
14732 (catch 'done
14733 (condition-case nil
14734 (progn
14735 (org-back-to-heading t)
14736 (while (not (equal lastpos (point)))
14737 (setq lastpos (point))
14738 (when (looking-at
14739 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14740 (setq ltags (org-split-string
14741 (org-match-string-no-properties 1) ":"))
14742 (when parent
14743 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14744 (setq tags (append
14745 (if parent
14746 (org-remove-uninherited-tags ltags)
14747 ltags)
14748 tags)))
14749 (or org-use-tag-inheritance (throw 'done t))
14750 (when local (throw 'done t))
14751 (or (org-up-heading-safe) (error nil))
14752 (setq parent t)))
14753 (error nil)))))
14754 (if local
14755 tags
14756 (reverse (delete-dups
14757 (reverse (append
14758 (org-remove-uninherited-tags
14759 org-file-tags)
14760 tags)))))))))
14762 (defun org-add-prop-inherited (s)
14763 (add-text-properties 0 (length s) '(inherited t) s)
14766 (defun org-toggle-tag (tag &optional onoff)
14767 "Toggle the tag TAG for the current line.
14768 If ONOFF is `on' or `off', don't toggle but set to this state."
14769 (let (res current)
14770 (save-excursion
14771 (org-back-to-heading t)
14772 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14773 (point-at-eol) t)
14774 (progn
14775 (setq current (match-string 1))
14776 (replace-match ""))
14777 (setq current ""))
14778 (setq current (nreverse (org-split-string current ":")))
14779 (cond
14780 ((eq onoff 'on)
14781 (setq res t)
14782 (or (member tag current) (push tag current)))
14783 ((eq onoff 'off)
14784 (or (not (member tag current)) (setq current (delete tag current))))
14785 (t (if (member tag current)
14786 (setq current (delete tag current))
14787 (setq res t)
14788 (push tag current))))
14789 (end-of-line 1)
14790 (if current
14791 (progn
14792 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14793 (org-set-tags nil t))
14794 (delete-horizontal-space))
14795 (run-hooks 'org-after-tags-change-hook))
14796 res))
14798 (defun org-align-tags-here (to-col)
14799 ;; Assumes that this is a headline
14800 "Align tags on the current headline to TO-COL."
14801 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14802 (beginning-of-line 1)
14803 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14804 (< pos (match-beginning 2)))
14805 (progn
14806 (setq tags-l (- (match-end 2) (match-beginning 2)))
14807 (goto-char (match-beginning 1))
14808 (insert " ")
14809 (delete-region (point) (1+ (match-beginning 2)))
14810 (setq ncol (max (current-column)
14811 (1+ col)
14812 (if (> to-col 0)
14813 to-col
14814 (- (abs to-col) tags-l))))
14815 (setq p (point))
14816 (insert (make-string (- ncol (current-column)) ?\ ))
14817 (setq ncol (current-column))
14818 (when indent-tabs-mode (tabify p (point-at-eol)))
14819 (org-move-to-column (min ncol col)))
14820 (goto-char pos))))
14822 (defun org-set-tags-command (&optional arg just-align)
14823 "Call the set-tags command for the current entry."
14824 (interactive "P")
14825 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14826 (org-set-tags arg just-align)
14827 (save-excursion
14828 (unless (and (org-region-active-p)
14829 org-loop-over-headlines-in-active-region)
14830 (org-back-to-heading t))
14831 (org-set-tags arg just-align))))
14833 (defun org-set-tags-to (data)
14834 "Set the tags of the current entry to DATA, replacing the current tags.
14835 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14836 If DATA is nil or the empty string, any tags will be removed."
14837 (interactive "sTags: ")
14838 (setq data
14839 (cond
14840 ((eq data nil) "")
14841 ((equal data "") "")
14842 ((stringp data)
14843 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14844 ":"))
14845 ((listp data)
14846 (concat ":" (mapconcat 'identity data ":") ":"))))
14847 (when data
14848 (save-excursion
14849 (org-back-to-heading t)
14850 (when (looking-at org-complex-heading-regexp)
14851 (if (match-end 5)
14852 (progn
14853 (goto-char (match-beginning 5))
14854 (insert data)
14855 (delete-region (point) (point-at-eol))
14856 (org-set-tags nil 'align))
14857 (goto-char (point-at-eol))
14858 (insert " " data)
14859 (org-set-tags nil 'align)))
14860 (beginning-of-line 1)
14861 (when (looking-at ".*?\\([ \t]+\\)$")
14862 (delete-region (match-beginning 1) (match-end 1))))))
14864 (defun org-align-all-tags ()
14865 "Align the tags in all headings."
14866 (interactive)
14867 (save-excursion
14868 (or (ignore-errors (org-back-to-heading t))
14869 (outline-next-heading))
14870 (if (org-at-heading-p)
14871 (org-set-tags t)
14872 (message "No headings"))))
14874 (defvar org-indent-indentation-per-level)
14875 (defun org-set-tags (&optional arg just-align)
14876 "Set the tags for the current headline.
14877 With prefix ARG, realign all tags in headings in the current buffer.
14878 When JUST-ALIGN is non-nil, only align tags."
14879 (interactive "P")
14880 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14881 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14882 'region-start-level
14883 'region))
14884 org-loop-over-headlines-in-active-region)
14885 (org-map-entries
14886 ;; We don't use ARG and JUST-ALIGN here because these args
14887 ;; are not useful when looping over headlines.
14888 #'org-set-tags
14889 org-loop-over-headlines-in-active-region
14891 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14892 (let ((org-setting-tags t))
14893 (if arg
14894 (save-excursion
14895 (goto-char (point-min))
14896 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14897 (while (re-search-forward org-outline-regexp-bol nil t)
14898 (org-set-tags nil t)
14899 (end-of-line)))
14900 (message "All tags realigned to column %d" org-tags-column))
14901 (let* ((current (org-get-tags-string))
14902 (col (current-column))
14903 (tags
14904 (if just-align current
14905 ;; Get a new set of tags from the user.
14906 (save-excursion
14907 (let* ((table
14908 (setq
14909 org-last-tags-completion-table
14910 (append
14911 org-tag-persistent-alist
14912 (or org-tag-alist (org-get-buffer-tags))
14913 (and
14914 org-complete-tags-always-offer-all-agenda-tags
14915 (org-global-tags-completion-table
14916 (org-agenda-files))))))
14917 (current-tags (org-split-string current ":"))
14918 (inherited-tags
14919 (nreverse (nthcdr (length current-tags)
14920 (nreverse (org-get-tags-at))))))
14921 (replace-regexp-in-string
14922 "\\([-+&]+\\|,\\)"
14924 (if (or (eq t org-use-fast-tag-selection)
14925 (and org-use-fast-tag-selection
14926 (delq nil (mapcar #'cdr table))))
14927 (org-fast-tag-selection
14928 current-tags inherited-tags table
14929 (and org-fast-tag-selection-include-todo
14930 org-todo-key-alist))
14931 (let ((org-add-colon-after-tag-completion
14932 (< 1 (length table))))
14933 (org-trim
14934 (completing-read
14935 "Tags: "
14936 #'org-tags-completion-function
14937 nil nil current 'org-tags-history))))))))))
14939 (when org-tags-sort-function
14940 (setq tags
14941 (mapconcat
14942 #'identity
14943 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14944 org-tags-sort-function)
14945 ":")))
14947 (if (not (org-string-nw-p tags)) (setq tags "")
14948 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14949 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14951 ;; Insert new tags at the correct column
14952 (beginning-of-line)
14953 (let ((level (if (looking-at org-outline-regexp)
14954 (- (match-end 0) (point) 1)
14955 1)))
14956 (cond
14957 ((and (equal current "") (equal tags "")))
14958 ((re-search-forward
14959 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14960 (line-end-position)
14962 (if (equal tags "") (replace-match "" t t)
14963 (goto-char (match-beginning 0))
14964 (let* ((c0 (current-column))
14965 ;; Compute offset for the case of org-indent-mode
14966 ;; active.
14967 (di (if (org-bound-and-true-p org-indent-mode)
14968 (* (1- org-indent-indentation-per-level)
14969 (1- level))
14971 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14972 (tc (+ org-tags-column
14973 (if (> org-tags-column 0) (- di) di)))
14974 (c1 (max (1+ c0)
14975 (if (> tc 0) tc
14976 (- (- tc) (string-width tags)))))
14977 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14978 (replace-match rpl t t)
14979 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14980 (tabify p0 (point))))))
14981 (t (error "Tags alignment failed"))))
14982 (org-move-to-column col))
14983 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14985 (defun org-change-tag-in-region (beg end tag off)
14986 "Add or remove TAG for each entry in the region.
14987 This works in the agenda, and also in an org-mode buffer."
14988 (interactive
14989 (list (region-beginning) (region-end)
14990 (let ((org-last-tags-completion-table
14991 (if (derived-mode-p 'org-mode)
14992 (org-uniquify
14993 (delq nil (append (org-get-buffer-tags)
14994 (org-global-tags-completion-table))))
14995 (org-global-tags-completion-table))))
14996 (completing-read
14997 "Tag: " 'org-tags-completion-function nil nil nil
14998 'org-tags-history))
14999 (progn
15000 (message "[s]et or [r]emove? ")
15001 (equal (read-char-exclusive) ?r))))
15002 (when (fboundp 'deactivate-mark) (deactivate-mark))
15003 (let ((agendap (equal major-mode 'org-agenda-mode))
15004 l1 l2 m buf pos newhead (cnt 0))
15005 (goto-char end)
15006 (setq l2 (1- (org-current-line)))
15007 (goto-char beg)
15008 (setq l1 (org-current-line))
15009 (cl-loop for l from l1 to l2 do
15010 (org-goto-line l)
15011 (setq m (get-text-property (point) 'org-hd-marker))
15012 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15013 (and agendap m))
15014 (setq buf (if agendap (marker-buffer m) (current-buffer))
15015 pos (if agendap m (point)))
15016 (with-current-buffer buf
15017 (save-excursion
15018 (save-restriction
15019 (goto-char pos)
15020 (setq cnt (1+ cnt))
15021 (org-toggle-tag tag (if off 'off 'on))
15022 (setq newhead (org-get-heading)))))
15023 (and agendap (org-agenda-change-all-lines newhead m))))
15024 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15026 (defun org-tags-completion-function (string _predicate &optional flag)
15027 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15028 (confirm (lambda (x) (stringp (car x)))))
15029 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15030 (setq s1 (match-string 1 string)
15031 s2 (match-string 2 string))
15032 (setq s1 "" s2 string))
15033 (cond
15034 ((eq flag nil)
15035 ;; try completion
15036 (setq rtn (try-completion s2 ctable confirm))
15037 (when (stringp rtn)
15038 (setq rtn
15039 (concat s1 s2 (substring rtn (length s2))
15040 (if (and org-add-colon-after-tag-completion
15041 (assoc rtn ctable))
15042 ":" ""))))
15043 rtn)
15044 ((eq flag t)
15045 ;; all-completions
15046 (all-completions s2 ctable confirm))
15047 ((eq flag 'lambda)
15048 ;; exact match?
15049 (assoc s2 ctable)))))
15051 (defun org-fast-tag-insert (kwd tags face &optional end)
15052 "Insert KDW, and the TAGS, the latter with face FACE.
15053 Also insert END."
15054 (insert (format "%-12s" (concat kwd ":"))
15055 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15056 (or end "")))
15058 (defun org-fast-tag-show-exit (flag)
15059 (save-excursion
15060 (org-goto-line 3)
15061 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15062 (replace-match ""))
15063 (when flag
15064 (end-of-line 1)
15065 (org-move-to-column (- (window-width) 19) t)
15066 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15068 (defun org-set-current-tags-overlay (current prefix)
15069 "Add an overlay to CURRENT tag with PREFIX."
15070 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15071 (if (featurep 'xemacs)
15072 (org-overlay-display org-tags-overlay (concat prefix s)
15073 'secondary-selection)
15074 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15075 (org-overlay-display org-tags-overlay (concat prefix s)))))
15077 (defvar org-last-tag-selection-key nil)
15078 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15079 "Fast tag selection with single keys.
15080 CURRENT is the current list of tags in the headline, INHERITED is the
15081 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15082 possibly with grouping information. TODO-TABLE is a similar table with
15083 TODO keywords, should these have keys assigned to them.
15084 If the keys are nil, a-z are automatically assigned.
15085 Returns the new tags string, or nil to not change the current settings."
15086 (let* ((fulltable (append table todo-table))
15087 (maxlen (apply 'max (mapcar
15088 (lambda (x)
15089 (if (stringp (car x)) (string-width (car x)) 0))
15090 fulltable)))
15091 (buf (current-buffer))
15092 (expert (eq org-fast-tag-selection-single-key 'expert))
15093 (buffer-tags nil)
15094 (fwidth (+ maxlen 3 1 3))
15095 (ncol (/ (- (window-width) 4) fwidth))
15096 (i-face 'org-done)
15097 (c-face 'org-todo)
15098 tg cnt e c char c1 c2 ntable tbl rtn
15099 ov-start ov-end ov-prefix
15100 (exit-after-next org-fast-tag-selection-single-key)
15101 (done-keywords org-done-keywords)
15102 groups ingroup intaggroup)
15103 (save-excursion
15104 (beginning-of-line 1)
15105 (if (looking-at
15106 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15107 (setq ov-start (match-beginning 1)
15108 ov-end (match-end 1)
15109 ov-prefix "")
15110 (setq ov-start (1- (point-at-eol))
15111 ov-end (1+ ov-start))
15112 (skip-chars-forward "^\n\r")
15113 (setq ov-prefix
15114 (concat
15115 (buffer-substring (1- (point)) (point))
15116 (if (> (current-column) org-tags-column)
15118 (make-string (- org-tags-column (current-column)) ?\ ))))))
15119 (move-overlay org-tags-overlay ov-start ov-end)
15120 (save-window-excursion
15121 (if expert
15122 (set-buffer (get-buffer-create " *Org tags*"))
15123 (delete-other-windows)
15124 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15125 (org-switch-to-buffer-other-window " *Org tags*"))
15126 (erase-buffer)
15127 (setq-local org-done-keywords done-keywords)
15128 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15129 (org-fast-tag-insert "Current" current c-face "\n\n")
15130 (org-fast-tag-show-exit exit-after-next)
15131 (org-set-current-tags-overlay current ov-prefix)
15132 (setq tbl fulltable char ?a cnt 0)
15133 (while (setq e (pop tbl))
15134 (cond
15135 ((eq (car e) :startgroup)
15136 (push '() groups) (setq ingroup t)
15137 (unless (zerop cnt)
15138 (setq cnt 0)
15139 (insert "\n"))
15140 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15141 ((eq (car e) :endgroup)
15142 (setq ingroup nil cnt 0)
15143 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15144 ((eq (car e) :startgrouptag)
15145 (setq intaggroup t)
15146 (unless (zerop cnt)
15147 (setq cnt 0)
15148 (insert "\n"))
15149 (insert "[ "))
15150 ((eq (car e) :endgrouptag)
15151 (setq intaggroup nil cnt 0)
15152 (insert "]\n"))
15153 ((equal e '(:newline))
15154 (unless (zerop cnt)
15155 (setq cnt 0)
15156 (insert "\n")
15157 (setq e (car tbl))
15158 (while (equal (car tbl) '(:newline))
15159 (insert "\n")
15160 (setq tbl (cdr tbl)))))
15161 ((equal e '(:grouptags)) (insert " : "))
15163 (setq tg (copy-sequence (car e)) c2 nil)
15164 (if (cdr e)
15165 (setq c (cdr e))
15166 ;; automatically assign a character.
15167 (setq c1 (string-to-char
15168 (downcase (substring
15169 tg (if (= (string-to-char tg) ?@) 1 0)))))
15170 (if (or (rassoc c1 ntable) (rassoc c1 table))
15171 (while (or (rassoc char ntable) (rassoc char table))
15172 (setq char (1+ char)))
15173 (setq c2 c1))
15174 (setq c (or c2 char)))
15175 (when ingroup (push tg (car groups)))
15176 (setq tg (org-add-props tg nil 'face
15177 (cond
15178 ((not (assoc tg table))
15179 (org-get-todo-face tg))
15180 ((member tg current) c-face)
15181 ((member tg inherited) i-face))))
15182 (when (equal (caar tbl) :grouptags)
15183 (org-add-props tg nil 'face 'org-tag-group))
15184 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15185 (insert "[" c "] " tg (make-string
15186 (- fwidth 4 (length tg)) ?\ ))
15187 (push (cons tg c) ntable)
15188 (when (= (cl-incf cnt) ncol)
15189 (insert "\n")
15190 (when (or ingroup intaggroup) (insert " "))
15191 (setq cnt 0)))))
15192 (setq ntable (nreverse ntable))
15193 (insert "\n")
15194 (goto-char (point-min))
15195 (unless expert (org-fit-window-to-buffer))
15196 (setq rtn
15197 (catch 'exit
15198 (while t
15199 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15200 (if (not groups) "no " "")
15201 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15202 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15203 (setq org-last-tag-selection-key c)
15204 (cond
15205 ((= c ?\r) (throw 'exit t))
15206 ((= c ?!)
15207 (setq groups (not groups))
15208 (goto-char (point-min))
15209 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15210 ((= c ?\C-c)
15211 (if (not expert)
15212 (org-fast-tag-show-exit
15213 (setq exit-after-next (not exit-after-next)))
15214 (setq expert nil)
15215 (delete-other-windows)
15216 (set-window-buffer (split-window-vertically) " *Org tags*")
15217 (org-switch-to-buffer-other-window " *Org tags*")
15218 (org-fit-window-to-buffer)))
15219 ((or (= c ?\C-g)
15220 (and (= c ?q) (not (rassoc c ntable))))
15221 (org-detach-overlay org-tags-overlay)
15222 (setq quit-flag t))
15223 ((= c ?\ )
15224 (setq current nil)
15225 (when exit-after-next (setq exit-after-next 'now)))
15226 ((= c ?\t)
15227 (condition-case nil
15228 (setq tg (completing-read
15229 "Tag: "
15230 (or buffer-tags
15231 (with-current-buffer buf
15232 (setq buffer-tags
15233 (org-get-buffer-tags))))))
15234 (quit (setq tg "")))
15235 (when (string-match "\\S-" tg)
15236 (cl-pushnew (list tg) buffer-tags :test #'equal)
15237 (if (member tg current)
15238 (setq current (delete tg current))
15239 (push tg current)))
15240 (when exit-after-next (setq exit-after-next 'now)))
15241 ((setq e (rassoc c todo-table) tg (car e))
15242 (with-current-buffer buf
15243 (save-excursion (org-todo tg)))
15244 (when exit-after-next (setq exit-after-next 'now)))
15245 ((setq e (rassoc c ntable) tg (car e))
15246 (if (member tg current)
15247 (setq current (delete tg current))
15248 (cl-loop for g in groups do
15249 (when (member tg g)
15250 (dolist (x g) (setq current (delete x current)))))
15251 (push tg current))
15252 (when exit-after-next (setq exit-after-next 'now))))
15254 ;; Create a sorted list
15255 (setq current
15256 (sort current
15257 (lambda (a b)
15258 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15259 (when (eq exit-after-next 'now) (throw 'exit t))
15260 (goto-char (point-min))
15261 (beginning-of-line 2)
15262 (delete-region (point) (point-at-eol))
15263 (org-fast-tag-insert "Current" current c-face)
15264 (org-set-current-tags-overlay current ov-prefix)
15265 (while (re-search-forward
15266 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15267 (setq tg (match-string 1))
15268 (add-text-properties
15269 (match-beginning 1) (match-end 1)
15270 (list 'face
15271 (cond
15272 ((member tg current) c-face)
15273 ((member tg inherited) i-face)
15274 (t (get-text-property (match-beginning 1) 'face))))))
15275 (goto-char (point-min)))))
15276 (org-detach-overlay org-tags-overlay)
15277 (if rtn
15278 (mapconcat 'identity current ":")
15279 nil))))
15281 (defun org-get-tags-string ()
15282 "Get the TAGS string in the current headline."
15283 (unless (org-at-heading-p t)
15284 (user-error "Not on a heading"))
15285 (save-excursion
15286 (beginning-of-line 1)
15287 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15288 (org-match-string-no-properties 1)
15289 "")))
15291 (defun org-get-tags ()
15292 "Get the list of tags specified in the current headline."
15293 (org-split-string (org-get-tags-string) ":"))
15295 (defun org-get-buffer-tags ()
15296 "Get a table of all tags used in the buffer, for completion."
15297 (org-with-wide-buffer
15298 (goto-char (point-min))
15299 (let ((tag-re (concat org-outline-regexp-bol
15300 "\\(?:.*?[ \t]\\)?"
15301 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15302 tags)
15303 (while (re-search-forward tag-re nil t)
15304 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15305 (push tag tags)))
15306 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15308 ;;;; The mapping API
15310 (defvar org-agenda-skip-comment-trees)
15311 (defvar org-agenda-skip-function)
15312 (defun org-map-entries (func &optional match scope &rest skip)
15313 "Call FUNC at each headline selected by MATCH in SCOPE.
15315 FUNC is a function or a lisp form. The function will be called without
15316 arguments, with the cursor positioned at the beginning of the headline.
15317 The return values of all calls to the function will be collected and
15318 returned as a list.
15320 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15321 does not need to preserve point. After evaluation, the cursor will be
15322 moved to the end of the line (presumably of the headline of the
15323 processed entry) and search continues from there. Under some
15324 circumstances, this may not produce the wanted results. For example,
15325 if you have removed (e.g. archived) the current (sub)tree it could
15326 mean that the next entry will be skipped entirely. In such cases, you
15327 can specify the position from where search should continue by making
15328 FUNC set the variable `org-map-continue-from' to the desired buffer
15329 position.
15331 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15332 Only headlines that are matched by this query will be considered during
15333 the iteration. When MATCH is nil or t, all headlines will be
15334 visited by the iteration.
15336 SCOPE determines the scope of this command. It can be any of:
15338 nil The current buffer, respecting the restriction if any
15339 tree The subtree started with the entry at point
15340 region The entries within the active region, if any
15341 region-start-level
15342 The entries within the active region, but only those at
15343 the same level than the first one.
15344 file The current buffer, without restriction
15345 file-with-archives
15346 The current buffer, and any archives associated with it
15347 agenda All agenda files
15348 agenda-with-archives
15349 All agenda files with any archive files associated with them
15350 \(file1 file2 ...)
15351 If this is a list, all files in the list will be scanned
15353 The remaining args are treated as settings for the skipping facilities of
15354 the scanner. The following items can be given here:
15356 archive skip trees with the archive tag
15357 comment skip trees with the COMMENT keyword
15358 function or Emacs Lisp form:
15359 will be used as value for `org-agenda-skip-function', so
15360 whenever the function returns a position, FUNC will not be
15361 called for that entry and search will continue from the
15362 position returned
15364 If your function needs to retrieve the tags including inherited tags
15365 at the *current* entry, you can use the value of the variable
15366 `org-scanner-tags' which will be much faster than getting the value
15367 with `org-get-tags-at'. If your function gets properties with
15368 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15369 to t around the call to `org-entry-properties' to get the same speedup.
15370 Note that if your function moves around to retrieve tags and properties at
15371 a *different* entry, you cannot use these techniques."
15372 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15373 (not (org-region-active-p)))
15374 (let* ((org-agenda-archives-mode nil) ; just to make sure
15375 (org-agenda-skip-archived-trees (memq 'archive skip))
15376 (org-agenda-skip-comment-trees (memq 'comment skip))
15377 (org-agenda-skip-function
15378 (car (org-delete-all '(comment archive) skip)))
15379 (org-tags-match-list-sublevels t)
15380 (start-level (eq scope 'region-start-level))
15381 matcher res
15382 org-todo-keywords-for-agenda
15383 org-done-keywords-for-agenda
15384 org-todo-keyword-alist-for-agenda
15385 org-tag-alist-for-agenda
15386 org--matcher-tags-todo-only)
15388 (cond
15389 ((eq match t) (setq matcher t))
15390 ((eq match nil) (setq matcher t))
15391 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15393 (save-excursion
15394 (save-restriction
15395 (cond ((eq scope 'tree)
15396 (org-back-to-heading t)
15397 (org-narrow-to-subtree)
15398 (setq scope nil))
15399 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15400 (org-region-active-p))
15401 ;; If needed, set start-level to a string like "2"
15402 (when start-level
15403 (save-excursion
15404 (goto-char (region-beginning))
15405 (unless (org-at-heading-p) (outline-next-heading))
15406 (setq start-level (org-current-level))))
15407 (narrow-to-region (region-beginning)
15408 (save-excursion
15409 (goto-char (region-end))
15410 (unless (and (bolp) (org-at-heading-p))
15411 (outline-next-heading))
15412 (point)))
15413 (setq scope nil)))
15415 (if (not scope)
15416 (progn
15417 (org-agenda-prepare-buffers
15418 (and buffer-file-name (list buffer-file-name)))
15419 (setq res
15420 (org-scan-tags
15421 func matcher org--matcher-tags-todo-only start-level)))
15422 ;; Get the right scope
15423 (cond
15424 ((and scope (listp scope) (symbolp (car scope)))
15425 (setq scope (eval scope)))
15426 ((eq scope 'agenda)
15427 (setq scope (org-agenda-files t)))
15428 ((eq scope 'agenda-with-archives)
15429 (setq scope (org-agenda-files t))
15430 (setq scope (org-add-archive-files scope)))
15431 ((eq scope 'file)
15432 (setq scope (and buffer-file-name (list buffer-file-name))))
15433 ((eq scope 'file-with-archives)
15434 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15435 (org-agenda-prepare-buffers scope)
15436 (dolist (file scope)
15437 (with-current-buffer (org-find-base-buffer-visiting file)
15438 (save-excursion
15439 (save-restriction
15440 (widen)
15441 (goto-char (point-min))
15442 (setq res
15443 (append
15445 (org-scan-tags
15446 func matcher org--matcher-tags-todo-only))))))))))
15447 res)))
15449 ;;; Properties API
15451 (defconst org-special-properties
15452 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15453 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15454 "The special properties valid in Org mode.
15455 These are properties that are not defined in the property drawer,
15456 but in some other way.")
15458 (defconst org-default-properties
15459 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15460 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15461 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15462 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15463 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15464 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15465 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15466 "Some properties that are used by Org mode for various purposes.
15467 Being in this list makes sure that they are offered for completion.")
15469 (defun org--valid-property-p (property)
15470 "Non nil when string PROPERTY is a valid property name."
15471 (not
15472 (or (equal property "")
15473 (org-string-match-p "\\s-" property))))
15475 (defun org--update-property-plist (key val props)
15476 "Associate KEY to VAL in alist PROPS.
15477 Modifications are made by side-effect. Return new alist."
15478 (let* ((appending (string= (substring key -1) "+"))
15479 (key (if appending (substring key 0 -1) key))
15480 (old (assoc-string key props t)))
15481 (if (not old) (cons (cons key val) props)
15482 (setcdr old (if appending (concat (cdr old) " " val) val))
15483 props)))
15485 (defun org-get-property-block (&optional beg force)
15486 "Return the (beg . end) range of the body of the property drawer.
15487 BEG is the beginning of the current subtree, or of the part
15488 before the first headline. If it is not given, it will be found.
15489 If the drawer does not exist, create it if FORCE is non-nil, or
15490 return nil."
15491 (org-with-wide-buffer
15492 (when beg (goto-char beg))
15493 (unless (org-before-first-heading-p)
15494 (let ((beg (cond (beg)
15495 ((or (not (featurep 'org-inlinetask))
15496 (org-inlinetask-in-task-p))
15497 (org-back-to-heading t))
15498 (t (org-with-limited-levels (org-back-to-heading t))))))
15499 (forward-line)
15500 (when (org-looking-at-p org-planning-line-re) (forward-line))
15501 (cond ((looking-at org-property-drawer-re)
15502 (forward-line)
15503 (cons (point) (progn (goto-char (match-end 0))
15504 (line-beginning-position))))
15505 (force
15506 (goto-char beg)
15507 (org-insert-property-drawer)
15508 (let ((pos (save-excursion (search-forward ":END:")
15509 (line-beginning-position))))
15510 (cons pos pos))))))))
15512 (defun org-at-property-p ()
15513 "Non-nil when point is inside a property drawer.
15514 See `org-property-re' for match data, if applicable."
15515 (save-excursion
15516 (beginning-of-line)
15517 (and (looking-at org-property-re)
15518 (let ((property-drawer (save-match-data (org-get-property-block))))
15519 (and property-drawer
15520 (>= (point) (car property-drawer))
15521 (< (point) (cdr property-drawer)))))))
15523 (defun org-property-action ()
15524 "Do an action on properties."
15525 (interactive)
15526 (unless (org-at-property-p) (user-error "Not at a property"))
15527 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15528 (let ((c (read-char-exclusive)))
15529 (cl-case c
15530 (?s (call-interactively #'org-set-property))
15531 (?d (call-interactively #'org-delete-property))
15532 (?D (call-interactively #'org-delete-property-globally))
15533 (?c (call-interactively #'org-compute-property-at-point))
15534 (otherwise (user-error "No such property action %c" c)))))
15536 (defun org-inc-effort ()
15537 "Increment the value of the effort property in the current entry."
15538 (interactive)
15539 (org-set-effort nil t))
15541 (defvar org-clock-effort) ; Defined in org-clock.el.
15542 (defvar org-clock-current-task) ; Defined in org-clock.el.
15543 (defun org-set-effort (&optional value increment)
15544 "Set the effort property of the current entry.
15545 With numerical prefix arg, use the nth allowed value, 0 stands for the
15546 10th allowed value.
15548 When INCREMENT is non-nil, set the property to the next allowed value."
15549 (interactive "P")
15550 (when (equal value 0) (setq value 10))
15551 (let* ((completion-ignore-case t)
15552 (prop org-effort-property)
15553 (cur (org-entry-get nil prop))
15554 (allowed (org-property-get-allowed-values nil prop 'table))
15555 (existing (mapcar 'list (org-property-values prop)))
15556 (heading (nth 4 (org-heading-components)))
15558 (val (cond
15559 ((stringp value) value)
15560 ((and allowed (integerp value))
15561 (or (car (nth (1- value) allowed))
15562 (car (org-last allowed))))
15563 ((and allowed increment)
15564 (or (cl-caadr (member (list cur) allowed))
15565 (user-error "Allowed effort values are not set")))
15566 (allowed
15567 (message "Select 1-9,0, [RET%s]: %s"
15568 (if cur (concat "=" cur) "")
15569 (mapconcat 'car allowed " "))
15570 (setq rpl (read-char-exclusive))
15571 (if (equal rpl ?\r)
15573 (setq rpl (- rpl ?0))
15574 (when (equal rpl 0) (setq rpl 10))
15575 (if (and (> rpl 0) (<= rpl (length allowed)))
15576 (car (nth (1- rpl) allowed))
15577 (org-completing-read "Effort: " allowed nil))))
15579 (org-completing-read
15580 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15581 (concat "[" cur "]") "")
15582 ": ")
15583 existing nil nil "" nil cur)))))
15584 (unless (equal (org-entry-get nil prop) val)
15585 (org-entry-put nil prop val))
15586 (org-refresh-property
15587 '((effort . identity)
15588 (effort-minutes . org-duration-string-to-minutes))
15589 val)
15590 (when (string= heading org-clock-current-task)
15591 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15592 (org-clock-update-mode-line))
15593 (message "%s is now %s" prop val)))
15595 (defun org-entry-properties (&optional pom which)
15596 "Get all properties of the current entry.
15598 When POM is a buffer position, get all properties from the entry
15599 there instead.
15601 This includes the TODO keyword, the tags, time strings for
15602 deadline, scheduled, and clocking, and any additional properties
15603 defined in the entry.
15605 If WHICH is nil or `all', get all properties. If WHICH is
15606 `special' or `standard', only get that subclass. If WHICH is
15607 a string, only get that property.
15609 Return value is an alist. Keys are properties, as upcased
15610 strings."
15611 (org-with-point-at pom
15612 (when (and (derived-mode-p 'org-mode)
15613 (ignore-errors (org-back-to-heading t)))
15614 (catch 'exit
15615 (let* ((beg (point))
15616 (specific (and (stringp which) (upcase which)))
15617 (which (cond ((not specific) which)
15618 ((member specific org-special-properties) 'special)
15619 (t 'standard)))
15620 props)
15621 ;; Get the special properties, like TODO and TAGS.
15622 (when (memq which '(nil all special))
15623 (when (or (not specific) (string= specific "CLOCKSUM"))
15624 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15625 (when clocksum
15626 (push (cons "CLOCKSUM"
15627 (org-minutes-to-clocksum-string clocksum))
15628 props)))
15629 (when specific (throw 'exit props)))
15630 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15631 (let ((clocksumt (get-text-property (point)
15632 :org-clock-minutes-today)))
15633 (when clocksumt
15634 (push (cons "CLOCKSUM_T"
15635 (org-minutes-to-clocksum-string clocksumt))
15636 props)))
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific) (string= specific "ITEM"))
15639 (when (looking-at org-complex-heading-regexp)
15640 (push (cons "ITEM"
15641 (let ((title (match-string-no-properties 4)))
15642 (if (org-string-nw-p title)
15643 (org-remove-tabs title)
15644 "")))
15645 props))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "TODO"))
15648 (let ((case-fold-search nil))
15649 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15650 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15651 (when specific (throw 'exit props)))
15652 (when (or (not specific) (string= specific "PRIORITY"))
15653 (push (cons "PRIORITY"
15654 (if (looking-at org-priority-regexp)
15655 (org-match-string-no-properties 2)
15656 (char-to-string org-default-priority)))
15657 props)
15658 (when specific (throw 'exit props)))
15659 (when (or (not specific) (string= specific "FILE"))
15660 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15661 props)
15662 (when specific (throw 'exit props)))
15663 (when (or (not specific) (string= specific "TAGS"))
15664 (let ((value (org-string-nw-p (org-get-tags-string))))
15665 (when value (push (cons "TAGS" value) props)))
15666 (when specific (throw 'exit props)))
15667 (when (or (not specific) (string= specific "ALLTAGS"))
15668 (let ((value (org-get-tags-at)))
15669 (when value
15670 (push (cons "ALLTAGS"
15671 (format ":%s:" (mapconcat #'identity value ":")))
15672 props)))
15673 (when specific (throw 'exit props)))
15674 (when (or (not specific) (string= specific "BLOCKED"))
15675 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15676 (when specific (throw 'exit props)))
15677 (when (or (not specific)
15678 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15679 (forward-line)
15680 (when (org-looking-at-p org-planning-line-re)
15681 (end-of-line)
15682 (let ((bol (line-beginning-position))
15683 ;; Backward compatibility: time keywords used to
15684 ;; be configurable (before 8.3). Make sure we
15685 ;; get the correct keyword.
15686 (key-assoc `(("CLOSED" . ,org-closed-string)
15687 ("DEADLINE" . ,org-deadline-string)
15688 ("SCHEDULED" . ,org-scheduled-string))))
15689 (dolist (pair (if specific (list (assoc specific key-assoc))
15690 key-assoc))
15691 (save-excursion
15692 (when (search-backward (cdr pair) bol t)
15693 (goto-char (match-end 0))
15694 (skip-chars-forward " \t")
15695 (and (looking-at org-ts-regexp-both)
15696 (push (cons (car pair)
15697 (org-match-string-no-properties 0))
15698 props)))))))
15699 (when specific (throw 'exit props)))
15700 (when (or (not specific)
15701 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15702 (let ((find-ts
15703 (lambda (end ts)
15704 ;; Fix next time-stamp before END. TS is the
15705 ;; list of time-stamps found so far.
15706 (let ((ts ts)
15707 (regexp (cond
15708 ((string= specific "TIMESTAMP")
15709 org-ts-regexp)
15710 ((string= specific "TIMESTAMP_IA")
15711 org-ts-regexp-inactive)
15712 ((assoc "TIMESTAMP_IA" ts)
15713 org-ts-regexp)
15714 ((assoc "TIMESTAMP" ts)
15715 org-ts-regexp-inactive)
15716 (t org-ts-regexp-both))))
15717 (catch 'next
15718 (while (re-search-forward regexp end t)
15719 (backward-char)
15720 (let ((object (org-element-context)))
15721 ;; Accept to match timestamps in node
15722 ;; properties, too.
15723 (when (memq (org-element-type object)
15724 '(node-property timestamp))
15725 (let ((type
15726 (org-element-property :type object)))
15727 (cond
15728 ((and (memq type '(active active-range))
15729 (not (equal specific "TIMESTAMP_IA")))
15730 (unless (assoc "TIMESTAMP" ts)
15731 (push (cons "TIMESTAMP"
15732 (org-element-property
15733 :raw-value object))
15735 (when specific (throw 'exit ts))))
15736 ((and (memq type '(inactive inactive-range))
15737 (not (string= specific "TIMESTAMP")))
15738 (unless (assoc "TIMESTAMP_IA" ts)
15739 (push (cons "TIMESTAMP_IA"
15740 (org-element-property
15741 :raw-value object))
15743 (when specific (throw 'exit ts))))))
15744 ;; Both timestamp types are found,
15745 ;; move to next part.
15746 (when (= (length ts) 2) (throw 'next ts)))))
15747 ts)))))
15748 (goto-char beg)
15749 ;; First look for timestamps within headline.
15750 (let ((ts (funcall find-ts (line-end-position) nil)))
15751 (if (= (length ts) 2) (setq props (nconc ts props))
15752 (forward-line)
15753 ;; Then find timestamps in the section, skipping
15754 ;; planning line.
15755 (when (org-looking-at-p org-planning-line-re)
15756 (forward-line))
15757 (let ((end (save-excursion (outline-next-heading))))
15758 (setq props (nconc (funcall find-ts end ts) props))))))))
15759 ;; Get the standard properties, like :PROP:.
15760 (when (memq which '(nil all standard))
15761 ;; If we are looking after a specific property, delegate
15762 ;; to `org-entry-get', which is faster. However, make an
15763 ;; exception for "CATEGORY", since it can be also set
15764 ;; through keywords (i.e. #+CATEGORY).
15765 (if (and specific (not (equal specific "CATEGORY")))
15766 (let ((value (org-entry-get beg specific nil t)))
15767 (throw 'exit (and value (list (cons specific value)))))
15768 (let ((range (org-get-property-block beg)))
15769 (when range
15770 (let ((end (cdr range)) seen-base)
15771 (goto-char (car range))
15772 ;; Unlike to `org--update-property-plist', we
15773 ;; handle the case where base values is found
15774 ;; after its extension. We also forbid standard
15775 ;; properties to be named as special properties.
15776 (while (re-search-forward org-property-re end t)
15777 (let* ((key (upcase (org-match-string-no-properties 2)))
15778 (extendp (org-string-match-p "\\+\\'" key))
15779 (key-base (if extendp (substring key 0 -1) key))
15780 (value (org-match-string-no-properties 3)))
15781 (cond
15782 ((member-ignore-case key-base org-special-properties))
15783 (extendp
15784 (setq props
15785 (org--update-property-plist key value props)))
15786 ((member key seen-base))
15787 (t (push key seen-base)
15788 (let ((p (assoc-string key props t)))
15789 (if p (setcdr p (concat value " " (cdr p)))
15790 (push (cons key value) props))))))))))))
15791 (unless (assoc "CATEGORY" props)
15792 (push (cons "CATEGORY" (org-get-category beg)) props)
15793 (when (string= specific "CATEGORY") (throw 'exit props)))
15794 ;; Return value.
15795 props)))))
15797 (defun org-property--local-values (property literal-nil)
15798 "Return value for PROPERTY in current entry.
15799 Value is a list whose care is the base value for PROPERTY and cdr
15800 a list of accumulated values. Return nil if neither is found in
15801 the entry. Also return nil when PROPERTY is set to \"nil\",
15802 unless LITERAL-NIL is non-nil."
15803 (let ((range (org-get-property-block)))
15804 (when range
15805 (goto-char (car range))
15806 (let* ((case-fold-search t)
15807 (end (cdr range))
15808 (value
15809 ;; Base value.
15810 (save-excursion
15811 (let ((v (and (re-search-forward
15812 (org-re-property property nil t) end t)
15813 (org-match-string-no-properties 3))))
15814 (list (if literal-nil v (org-not-nil v)))))))
15815 ;; Find additional values.
15816 (let* ((property+ (org-re-property (concat property "+") nil t)))
15817 (while (re-search-forward property+ end t)
15818 (push (org-match-string-no-properties 3) value)))
15819 ;; Return final values.
15820 (and (not (equal value '(nil))) (nreverse value))))))
15822 (defun org-entry-get (pom property &optional inherit literal-nil)
15823 "Get value of PROPERTY for entry or content at point-or-marker POM.
15825 If INHERIT is non-nil and the entry does not have the property,
15826 then also check higher levels of the hierarchy. If INHERIT is
15827 the symbol `selective', use inheritance only if the setting in
15828 `org-use-property-inheritance' selects PROPERTY for inheritance.
15830 If the property is present but empty, the return value is the
15831 empty string. If the property is not present at all, nil is
15832 returned. In any other case, return the value as a string.
15833 Search is case-insensitive.
15835 If LITERAL-NIL is set, return the string value \"nil\" as
15836 a string, do not interpret it as the list atom nil. This is used
15837 for inheritance when a \"nil\" value can supersede a non-nil
15838 value higher up the hierarchy."
15839 (org-with-point-at pom
15840 (cond
15841 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15842 ;; We need a special property. Use `org-entry-properties' to
15843 ;; retrieve it, but specify the wanted property.
15844 (cdr (assoc-string property (org-entry-properties nil property))))
15845 ((and inherit
15846 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15847 (org-entry-get-with-inheritance property literal-nil))
15849 (let* ((local (org-property--local-values property literal-nil))
15850 (value (and local (mapconcat #'identity (delq nil local) " "))))
15851 (if literal-nil value (org-not-nil value)))))))
15853 (defun org-property-or-variable-value (var &optional inherit)
15854 "Check if there is a property fixing the value of VAR.
15855 If yes, return this value. If not, return the current value of the variable."
15856 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15857 (if (and prop (stringp prop) (string-match "\\S-" prop))
15858 (read prop)
15859 (symbol-value var))))
15861 (defun org-entry-delete (pom property)
15862 "Delete PROPERTY from entry at point-or-marker POM.
15863 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15864 non-nil when a property was removed."
15865 (unless (member property org-special-properties)
15866 (org-with-point-at pom
15867 (let ((range (org-get-property-block)))
15868 (when range
15869 (let* ((begin (car range))
15870 (origin (cdr range))
15871 (end (copy-marker origin))
15872 (re (org-re-property
15873 (concat (regexp-quote property) "\\+?") t t)))
15874 (goto-char begin)
15875 (while (re-search-forward re end t)
15876 (delete-region (match-beginning 0) (line-beginning-position 2)))
15877 ;; If drawer is empty, remove it altogether.
15878 (when (= begin end)
15879 (delete-region (line-beginning-position 0)
15880 (line-beginning-position 2)))
15881 ;; Return non-nil if some property was removed.
15882 (prog1 (/= end origin) (set-marker end nil))))))))
15884 ;; Multi-values properties are properties that contain multiple values
15885 ;; These values are assumed to be single words, separated by whitespace.
15886 (defun org-entry-add-to-multivalued-property (pom property value)
15887 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15888 (let* ((old (org-entry-get pom property))
15889 (values (and old (org-split-string old "[ \t]"))))
15890 (setq value (org-entry-protect-space value))
15891 (unless (member value values)
15892 (setq values (append values (list value)))
15893 (org-entry-put pom property
15894 (mapconcat 'identity values " ")))))
15896 (defun org-entry-remove-from-multivalued-property (pom property value)
15897 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15898 (let* ((old (org-entry-get pom property))
15899 (values (and old (org-split-string old "[ \t]"))))
15900 (setq value (org-entry-protect-space value))
15901 (when (member value values)
15902 (setq values (delete value values))
15903 (org-entry-put pom property
15904 (mapconcat 'identity values " ")))))
15906 (defun org-entry-member-in-multivalued-property (pom property value)
15907 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15908 (let* ((old (org-entry-get pom property))
15909 (values (and old (org-split-string old "[ \t]"))))
15910 (setq value (org-entry-protect-space value))
15911 (member value values)))
15913 (defun org-entry-get-multivalued-property (pom property)
15914 "Return a list of values in a multivalued property."
15915 (let* ((value (org-entry-get pom property))
15916 (values (and value (org-split-string value "[ \t]"))))
15917 (mapcar 'org-entry-restore-space values)))
15919 (defun org-entry-put-multivalued-property (pom property &rest values)
15920 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15921 VALUES should be a list of strings. Spaces will be protected."
15922 (org-entry-put pom property
15923 (mapconcat 'org-entry-protect-space values " "))
15924 (let* ((value (org-entry-get pom property))
15925 (values (and value (org-split-string value "[ \t]"))))
15926 (mapcar 'org-entry-restore-space values)))
15928 (defun org-entry-protect-space (s)
15929 "Protect spaces and newline in string S."
15930 (while (string-match " " s)
15931 (setq s (replace-match "%20" t t s)))
15932 (while (string-match "\n" s)
15933 (setq s (replace-match "%0A" t t s)))
15936 (defun org-entry-restore-space (s)
15937 "Restore spaces and newline in string S."
15938 (while (string-match "%20" s)
15939 (setq s (replace-match " " t t s)))
15940 (while (string-match "%0A" s)
15941 (setq s (replace-match "\n" t t s)))
15944 (defvar org-entry-property-inherited-from (make-marker)
15945 "Marker pointing to the entry from where a property was inherited.
15946 Each call to `org-entry-get-with-inheritance' will set this marker to the
15947 location of the entry where the inheritance search matched. If there was
15948 no match, the marker will point nowhere.
15949 Note that also `org-entry-get' calls this function, if the INHERIT flag
15950 is set.")
15952 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15953 "Get PROPERTY of entry or content at point, search higher levels if needed.
15954 The search will stop at the first ancestor which has the property defined.
15955 If the value found is \"nil\", return nil to show that the property
15956 should be considered as undefined (this is the meaning of nil here).
15957 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15958 (move-marker org-entry-property-inherited-from nil)
15959 (org-with-wide-buffer
15960 (let (value)
15961 (catch 'exit
15962 (while t
15963 (let ((v (org-property--local-values property literal-nil)))
15964 (when v
15965 (setq value
15966 (concat (mapconcat #'identity (delq nil v) " ")
15967 (and value " ")
15968 value)))
15969 (cond
15970 ((car v)
15971 (org-back-to-heading t)
15972 (move-marker org-entry-property-inherited-from (point))
15973 (throw 'exit nil))
15974 ((org-up-heading-safe))
15976 (let ((global
15977 (cdr (or (assoc-string property org-file-properties t)
15978 (assoc-string property org-global-properties t)
15979 (assoc-string property org-global-properties-fixed t)))))
15980 (cond ((not global))
15981 (value (setq value (concat global " " value)))
15982 (t (setq value global))))
15983 (throw 'exit nil))))))
15984 (if literal-nil value (org-not-nil value)))))
15986 (defvar org-property-changed-functions nil
15987 "Hook called when the value of a property has changed.
15988 Each hook function should accept two arguments, the name of the property
15989 and the new value.")
15991 (defun org-entry-put (pom property value)
15992 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15994 If the value is nil, it is converted to the empty string. If it
15995 is not a string, an error is raised. Also raise an error on
15996 invalid property names.
15998 PROPERTY can be any regular property (see
15999 `org-special-properties'). It can also be \"TODO\",
16000 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16002 For the last two properties, VALUE may have any of the special
16003 values \"earlier\" and \"later\". The function then increases or
16004 decreases scheduled or deadline date by one day."
16005 (cond ((null value) (setq value ""))
16006 ((not (stringp value)) (error "Properties values should be strings"))
16007 ((not (org--valid-property-p property))
16008 (user-error "Invalid property name: \"%s\"" property)))
16009 (org-with-point-at pom
16010 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16011 (org-back-to-heading t)
16012 (org-with-limited-levels (org-back-to-heading t)))
16013 (let ((beg (point)))
16014 (cond
16015 ((equal property "TODO")
16016 (cond ((not (org-string-nw-p value)) (setq value 'none))
16017 ((not (member value org-todo-keywords-1))
16018 (user-error "\"%s\" is not a valid TODO state" value)))
16019 (org-todo value)
16020 (org-set-tags nil 'align))
16021 ((equal property "PRIORITY")
16022 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16023 (org-set-tags nil 'align))
16024 ((equal property "SCHEDULED")
16025 (forward-line)
16026 (if (and (org-looking-at-p org-planning-line-re)
16027 (re-search-forward
16028 org-scheduled-time-regexp (line-end-position) t))
16029 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16030 ((string= value "later") (org-timestamp-change 1 'day))
16031 ((string= value "") (org-schedule '(4)))
16032 (t (org-schedule nil value)))
16033 (if (member value '("earlier" "later" ""))
16034 (call-interactively #'org-schedule)
16035 (org-schedule nil value))))
16036 ((equal property "DEADLINE")
16037 (forward-line)
16038 (if (and (org-looking-at-p org-planning-line-re)
16039 (re-search-forward
16040 org-deadline-time-regexp (line-end-position) t))
16041 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16042 ((string= value "later") (org-timestamp-change 1 'day))
16043 ((string= value "") (org-deadline '(4)))
16044 (t (org-deadline nil value)))
16045 (if (member value '("earlier" "later" ""))
16046 (call-interactively #'org-deadline)
16047 (org-deadline nil value))))
16048 ((member property org-special-properties)
16049 (error "The %s property cannot be set with `org-entry-put'" property))
16051 (let* ((range (org-get-property-block beg 'force))
16052 (end (cdr range))
16053 (case-fold-search t))
16054 (goto-char (car range))
16055 (if (re-search-forward (org-re-property property nil t) end t)
16056 (progn (delete-region (match-beginning 0) (match-end 0))
16057 (goto-char (match-beginning 0)))
16058 (goto-char end)
16059 (insert "\n")
16060 (backward-char))
16061 (insert ":" property ":")
16062 (when value (insert " " value))
16063 (org-indent-line)))))
16064 (run-hook-with-args 'org-property-changed-functions property value)))
16066 (defun org-buffer-property-keys
16067 (&optional specials defaults columns ignore-malformed)
16068 "Get all property keys in the current buffer.
16070 When SPECIALS is non-nil, also list the special properties that
16071 reflect things like tags and TODO state.
16073 When DEFAULTS is non-nil, also include properties that has
16074 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16075 DESCRIPTION, LOCATION, and LOGGING and others.
16077 When COLUMNS in non-nil, also include property names given in
16078 COLUMN formats in the current buffer.
16080 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16081 automatically performed, such drawers will be silently ignored."
16082 (let ((case-fold-search t)
16083 (props (append
16084 (and specials org-special-properties)
16085 (and defaults (cons org-effort-property org-default-properties))
16086 nil)))
16087 (org-with-wide-buffer
16088 (goto-char (point-min))
16089 (while (re-search-forward org-property-start-re nil t)
16090 (let ((range (org-get-property-block)))
16091 (catch 'skip
16092 (unless range
16093 (when (and (not ignore-malformed)
16094 (not (org-before-first-heading-p))
16095 (y-or-n-p (format "Malformed drawer at %d, repair?"
16096 (line-beginning-position))))
16097 (org-get-property-block nil t))
16098 (throw 'skip nil))
16099 (goto-char (car range))
16100 (let ((begin (car range))
16101 (end (cdr range)))
16102 ;; Make sure that found property block is not located
16103 ;; before current point, as it would generate an infloop.
16104 ;; It can happen, for example, in the following
16105 ;; situation:
16107 ;; * Headline
16108 ;; :PROPERTIES:
16109 ;; ...
16110 ;; :END:
16111 ;; *************** Inlinetask
16112 ;; #+BEGIN_EXAMPLE
16113 ;; :PROPERTIES:
16114 ;; #+END_EXAMPLE
16116 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16117 (while (< (point) end)
16118 (let ((p (progn (looking-at org-property-re)
16119 (org-match-string-no-properties 2))))
16120 ;; Only add true property name, not extension symbol.
16121 (push (if (not (org-string-match-p "\\+\\'" p)) p
16122 (substring p 0 -1))
16123 props))
16124 (forward-line))))
16125 (outline-next-heading)))
16126 (when columns
16127 (goto-char (point-min))
16128 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16129 (let ((element (org-element-at-point)))
16130 (when (memq (org-element-type element) '(keyword node-property))
16131 (let ((value (org-element-property :value element))
16132 (start 0))
16133 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16134 (setq start (match-end 0))
16135 (let ((p (org-match-string-no-properties 1 value)))
16136 (unless (member-ignore-case p org-special-properties)
16137 (push p props))))))))))
16138 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16140 (defun org-property-values (key)
16141 "List all non-nil values of property KEY in current buffer."
16142 (org-with-wide-buffer
16143 (goto-char (point-min))
16144 (let ((case-fold-search t)
16145 (re (org-re-property key))
16146 values)
16147 (while (re-search-forward re nil t)
16148 (push (org-entry-get (point) key) values))
16149 (delete-dups values))))
16151 (defun org-insert-property-drawer ()
16152 "Insert a property drawer into the current entry."
16153 (org-with-wide-buffer
16154 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16155 (org-back-to-heading t)
16156 (org-with-limited-levels (org-back-to-heading t)))
16157 (forward-line)
16158 (when (org-looking-at-p org-planning-line-re) (forward-line))
16159 (unless (org-looking-at-p org-property-drawer-re)
16160 ;; Make sure we start editing a line from current entry, not from
16161 ;; next one. It prevents extending text properties or overlays
16162 ;; belonging to the latter.
16163 (when (bolp) (backward-char))
16164 (let ((begin (1+ (point)))
16165 (inhibit-read-only t))
16166 (insert "\n:PROPERTIES:\n:END:")
16167 (when (eobp) (insert "\n"))
16168 (org-indent-region begin (point))))))
16170 (defun org-insert-drawer (&optional arg drawer)
16171 "Insert a drawer at point.
16173 When optional argument ARG is non-nil, insert a property drawer.
16175 Optional argument DRAWER, when non-nil, is a string representing
16176 drawer's name. Otherwise, the user is prompted for a name.
16178 If a region is active, insert the drawer around that region
16179 instead.
16181 Point is left between drawer's boundaries."
16182 (interactive "P")
16183 (let* ((drawer (if arg "PROPERTIES"
16184 (or drawer (read-from-minibuffer "Drawer: ")))))
16185 (cond
16186 ;; With C-u, fall back on `org-insert-property-drawer'
16187 (arg (org-insert-property-drawer))
16188 ;; Check validity of suggested drawer's name.
16189 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16190 (user-error "Invalid drawer name"))
16191 ;; With an active region, insert a drawer at point.
16192 ((not (org-region-active-p))
16193 (progn
16194 (unless (bolp) (insert "\n"))
16195 (insert (format ":%s:\n\n:END:\n" drawer))
16196 (forward-line -2)))
16197 ;; Otherwise, insert the drawer at point
16199 (let ((rbeg (region-beginning))
16200 (rend (copy-marker (region-end))))
16201 (unwind-protect
16202 (progn
16203 (goto-char rbeg)
16204 (beginning-of-line)
16205 (when (save-excursion
16206 (re-search-forward org-outline-regexp-bol rend t))
16207 (user-error "Drawers cannot contain headlines"))
16208 ;; Position point at the beginning of the first
16209 ;; non-blank line in region. Insert drawer's opening
16210 ;; there, then indent it.
16211 (org-skip-whitespace)
16212 (beginning-of-line)
16213 (insert ":" drawer ":\n")
16214 (forward-line -1)
16215 (indent-for-tab-command)
16216 ;; Move point to the beginning of the first blank line
16217 ;; after the last non-blank line in region. Insert
16218 ;; drawer's closing, then indent it.
16219 (goto-char rend)
16220 (skip-chars-backward " \r\t\n")
16221 (insert "\n:END:")
16222 (deactivate-mark t)
16223 (indent-for-tab-command)
16224 (unless (eolp) (insert "\n")))
16225 ;; Clear marker, whatever the outcome of insertion is.
16226 (set-marker rend nil)))))))
16228 (defvar org-property-set-functions-alist nil
16229 "Property set function alist.
16230 Each entry should have the following format:
16232 (PROPERTY . READ-FUNCTION)
16234 The read function will be called with the same argument as
16235 `org-completing-read'.")
16237 (defun org-set-property-function (property)
16238 "Get the function that should be used to set PROPERTY.
16239 This is computed according to `org-property-set-functions-alist'."
16240 (or (cdr (assoc property org-property-set-functions-alist))
16241 'org-completing-read))
16243 (defun org-read-property-value (property)
16244 "Read PROPERTY value from user."
16245 (let* ((completion-ignore-case t)
16246 (allowed (org-property-get-allowed-values nil property 'table))
16247 (cur (org-entry-get nil property))
16248 (prompt (concat property " value"
16249 (if (and cur (string-match "\\S-" cur))
16250 (concat " [" cur "]") "") ": "))
16251 (set-function (org-set-property-function property))
16252 (val (if allowed
16253 (funcall set-function prompt allowed nil
16254 (not (get-text-property 0 'org-unrestricted
16255 (caar allowed))))
16256 (funcall set-function prompt
16257 (mapcar 'list (org-property-values property))
16258 nil nil "" nil cur))))
16259 (org-trim val)))
16261 (defvar org-last-set-property nil)
16262 (defvar org-last-set-property-value nil)
16263 (defun org-read-property-name ()
16264 "Read a property name."
16265 (let ((completion-ignore-case t)
16266 (default-prop (or (and (org-at-property-p)
16267 (org-match-string-no-properties 2))
16268 org-last-set-property)))
16269 (org-completing-read
16270 (concat "Property"
16271 (if default-prop (concat " [" default-prop "]") "")
16272 ": ")
16273 (mapcar #'list (org-buffer-property-keys nil t t))
16274 nil nil nil nil default-prop)))
16276 (defun org-set-property-and-value (use-last)
16277 "Allow to set [PROPERTY]: [value] direction from prompt.
16278 When use-default, don't even ask, just use the last
16279 \"[PROPERTY]: [value]\" string from the history."
16280 (interactive "P")
16281 (let* ((completion-ignore-case t)
16282 (pv (or (and use-last org-last-set-property-value)
16283 (org-completing-read
16284 "Enter a \"[Property]: [value]\" pair: "
16285 nil nil nil nil nil
16286 org-last-set-property-value)))
16287 prop val)
16288 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16289 (setq prop (match-string 1 pv)
16290 val (match-string 2 pv))
16291 (org-set-property prop val))))
16293 (defun org-set-property (property value)
16294 "In the current entry, set PROPERTY to VALUE.
16296 When called interactively, this will prompt for a property name, offering
16297 completion on existing and default properties. And then it will prompt
16298 for a value, offering completion either on allowed values (via an inherited
16299 xxx_ALL property) or on existing values in other instances of this property
16300 in the current file.
16302 Throw an error when trying to set a property with an invalid name."
16303 (interactive (list nil nil))
16304 (let ((property (or property (org-read-property-name))))
16305 ;; `org-entry-put' also makes the following check, but this one
16306 ;; avoids polluting `org-last-set-property' and
16307 ;; `org-last-set-property-value' needlessly.
16308 (unless (org--valid-property-p property)
16309 (user-error "Invalid property name: \"%s\"" property))
16310 (let ((value (or value (org-read-property-value property)))
16311 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16312 (setq org-last-set-property property)
16313 (setq org-last-set-property-value (concat property ": " value))
16314 ;; Possibly postprocess the inserted value:
16315 (when fn (setq value (funcall fn value)))
16316 (unless (equal (org-entry-get nil property) value)
16317 (org-entry-put nil property value)))))
16319 (defun org-find-property (property &optional value)
16320 "Find first entry in buffer that sets PROPERTY.
16322 When optional argument VALUE is non-nil, only consider an entry
16323 if it contains PROPERTY set to this value. If PROPERTY should be
16324 explicitly set to nil, use string \"nil\" for VALUE.
16326 Return position where the entry begins, or nil if there is no
16327 such entry. If narrowing is in effect, only search the visible
16328 part of the buffer."
16329 (save-excursion
16330 (goto-char (point-min))
16331 (let ((case-fold-search t)
16332 (re (org-re-property property nil (not value) value)))
16333 (catch 'exit
16334 (while (re-search-forward re nil t)
16335 (when (if value (org-at-property-p)
16336 (org-entry-get (point) property nil t))
16337 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16339 (defun org-delete-property (property)
16340 "In the current entry, delete PROPERTY."
16341 (interactive
16342 (let* ((completion-ignore-case t)
16343 (cat (org-entry-get (point) "CATEGORY"))
16344 (props0 (org-entry-properties nil 'standard))
16345 (props (if cat props0
16346 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16347 (prop (if (< 1 (length props))
16348 (completing-read "Property: " props nil t)
16349 (caar props))))
16350 (list prop)))
16351 (if (not property)
16352 (message "No property to delete in this entry")
16353 (org-entry-delete nil property)
16354 (message "Property \"%s\" deleted" property)))
16356 (defun org-delete-property-globally (property)
16357 "Remove PROPERTY globally, from all entries.
16358 This function ignores narrowing, if any."
16359 (interactive
16360 (let* ((completion-ignore-case t)
16361 (prop (completing-read
16362 "Globally remove property: "
16363 (mapcar #'list (org-buffer-property-keys)))))
16364 (list prop)))
16365 (org-with-wide-buffer
16366 (goto-char (point-min))
16367 (let ((count 0)
16368 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16369 (while (re-search-forward re nil t)
16370 (when (org-entry-delete (point) property) (cl-incf count)))
16371 (message "Property \"%s\" removed from %d entries" property count))))
16373 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16375 (defun org-compute-property-at-point ()
16376 "Compute the property at point.
16377 This looks for an enclosing column format, extracts the operator and
16378 then applies it to the property in the column format's scope."
16379 (interactive)
16380 (unless (org-at-property-p)
16381 (user-error "Not at a property"))
16382 (let ((prop (org-match-string-no-properties 2)))
16383 (org-columns-get-format-and-top-level)
16384 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16385 (user-error "No operator defined for property %s" prop))
16386 (org-columns-compute prop)))
16388 (defvar org-property-allowed-value-functions nil
16389 "Hook for functions supplying allowed values for a specific property.
16390 The functions must take a single argument, the name of the property, and
16391 return a flat list of allowed values. If \":ETC\" is one of
16392 the values, this means that these values are intended as defaults for
16393 completion, but that other values should be allowed too.
16394 The functions must return nil if they are not responsible for this
16395 property.")
16397 (defun org-property-get-allowed-values (pom property &optional table)
16398 "Get allowed values for the property PROPERTY.
16399 When TABLE is non-nil, return an alist that can directly be used for
16400 completion."
16401 (let (vals)
16402 (cond
16403 ((equal property "TODO")
16404 (setq vals (org-with-point-at pom
16405 (append org-todo-keywords-1 '("")))))
16406 ((equal property "PRIORITY")
16407 (let ((n org-lowest-priority))
16408 (while (>= n org-highest-priority)
16409 (push (char-to-string n) vals)
16410 (setq n (1- n)))))
16411 ((equal property "CATEGORY"))
16412 ((member property org-special-properties))
16413 ((setq vals (run-hook-with-args-until-success
16414 'org-property-allowed-value-functions property)))
16416 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16417 (when (and vals (string-match "\\S-" vals))
16418 (setq vals (car (read-from-string (concat "(" vals ")"))))
16419 (setq vals (mapcar (lambda (x)
16420 (cond ((stringp x) x)
16421 ((numberp x) (number-to-string x))
16422 ((symbolp x) (symbol-name x))
16423 (t "???")))
16424 vals)))))
16425 (when (member ":ETC" vals)
16426 (setq vals (remove ":ETC" vals))
16427 (org-add-props (car vals) '(org-unrestricted t)))
16428 (if table (mapcar 'list vals) vals)))
16430 (defun org-property-previous-allowed-value (&optional _previous)
16431 "Switch to the next allowed value for this property."
16432 (interactive)
16433 (org-property-next-allowed-value t))
16435 (defun org-property-next-allowed-value (&optional previous)
16436 "Switch to the next allowed value for this property."
16437 (interactive)
16438 (unless (org-at-property-p)
16439 (user-error "Not at a property"))
16440 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16441 (key (match-string 2))
16442 (value (match-string 3))
16443 (allowed (or (org-property-get-allowed-values (point) key)
16444 (and (member value '("[ ]" "[-]" "[X]"))
16445 '("[ ]" "[X]"))))
16446 (heading (save-match-data (nth 4 (org-heading-components))))
16447 nval)
16448 (unless allowed
16449 (user-error "Allowed values for this property have not been defined"))
16450 (when previous (setq allowed (reverse allowed)))
16451 (when (member value allowed)
16452 (setq nval (car (cdr (member value allowed)))))
16453 (setq nval (or nval (car allowed)))
16454 (when (equal nval value)
16455 (user-error "Only one allowed value for this property"))
16456 (org-at-property-p)
16457 (replace-match (concat " :" key ": " nval) t t)
16458 (org-indent-line)
16459 (beginning-of-line 1)
16460 (skip-chars-forward " \t")
16461 (when (equal prop org-effort-property)
16462 (org-refresh-property
16463 '((effort . identity)
16464 (effort-minutes . org-duration-string-to-minutes))
16465 nval)
16466 (when (string= org-clock-current-task heading)
16467 (setq org-clock-effort nval)
16468 (org-clock-update-mode-line)))
16469 (run-hook-with-args 'org-property-changed-functions key nval)))
16471 (defun org-find-olp (path &optional this-buffer)
16472 "Return a marker pointing to the entry at outline path OLP.
16473 If anything goes wrong, throw an error.
16474 You can wrap this call to catch the error like this:
16476 \(condition-case msg
16477 \(org-mobile-locate-entry (match-string 4))
16478 \(error (nth 1 msg)))
16480 The return value will then be either a string with the error message,
16481 or a marker if everything is OK.
16483 If THIS-BUFFER is set, the outline path does not contain a file,
16484 only headings."
16485 (let* ((file (if this-buffer buffer-file-name (pop path)))
16486 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16487 (level 1)
16488 (lmin 1)
16489 (lmax 1)
16490 end found flevel)
16491 (unless buffer (error "File not found :%s" file))
16492 (with-current-buffer buffer
16493 (org-with-wide-buffer
16494 (goto-char (point-min))
16495 (dolist (heading path)
16496 (let ((re (format org-complex-heading-regexp-format
16497 (regexp-quote heading)))
16498 (cnt 0))
16499 (while (re-search-forward re end t)
16500 (setq level (- (match-end 1) (match-beginning 1)))
16501 (when (and (>= level lmin) (<= level lmax))
16502 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16503 (when (= cnt 0)
16504 (error "Heading not found on level %d: %s" lmax heading))
16505 (when (> cnt 1)
16506 (error "Heading not unique on level %d: %s" lmax heading))
16507 (goto-char found)
16508 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16509 (setq end (save-excursion (org-end-of-subtree t t)))))
16510 (when (org-at-heading-p)
16511 (point-marker))))))
16513 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16514 "Find node HEADING in BUFFER.
16515 Return a marker to the heading if it was found, or nil if not.
16516 If POS-ONLY is set, return just the position instead of a marker.
16518 The heading text must match exact, but it may have a TODO keyword,
16519 a priority cookie and tags in the standard locations."
16520 (with-current-buffer (or buffer (current-buffer))
16521 (save-excursion
16522 (save-restriction
16523 (widen)
16524 (goto-char (point-min))
16525 (let (case-fold-search)
16526 (when (re-search-forward
16527 (format org-complex-heading-regexp-format
16528 (regexp-quote heading)) nil t)
16529 (if pos-only
16530 (match-beginning 0)
16531 (move-marker (make-marker) (match-beginning 0)))))))))
16533 (defun org-find-exact-heading-in-directory (heading &optional dir)
16534 "Find Org node headline HEADING in all .org files in directory DIR.
16535 When the target headline is found, return a marker to this location."
16536 (let ((files (directory-files (or dir default-directory)
16537 t "\\`[^.#].*\\.org\\'"))
16538 visiting m buffer)
16539 (catch 'found
16540 (dolist (file files)
16541 (message "trying %s" file)
16542 (setq visiting (org-find-base-buffer-visiting file))
16543 (setq buffer (or visiting (find-file-noselect file)))
16544 (setq m (org-find-exact-headline-in-buffer
16545 heading buffer))
16546 (when (and (not m) (not visiting)) (kill-buffer buffer))
16547 (and m (throw 'found m))))))
16549 (defun org-find-entry-with-id (ident)
16550 "Locate the entry that contains the ID property with exact value IDENT.
16551 IDENT can be a string, a symbol or a number, this function will search for
16552 the string representation of it.
16553 Return the position where this entry starts, or nil if there is no such entry."
16554 (interactive "sID: ")
16555 (let ((id (cond
16556 ((stringp ident) ident)
16557 ((symbolp ident) (symbol-name ident))
16558 ((numberp ident) (number-to-string ident))
16559 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16560 (org-with-wide-buffer (org-find-property "ID" id))))
16562 ;;;; Timestamps
16564 (defvar org-last-changed-timestamp nil)
16565 (defvar org-last-inserted-timestamp nil
16566 "The last time stamp inserted with `org-insert-time-stamp'.")
16567 (defvar org-ts-what) ; dynamically scoped parameter
16569 (defun org-time-stamp (arg &optional inactive)
16570 "Prompt for a date/time and insert a time stamp.
16572 If the user specifies a time like HH:MM or if this command is
16573 called with at least one prefix argument, the time stamp contains
16574 the date and the time. Otherwise, only the date is included.
16576 All parts of a date not specified by the user are filled in from
16577 the timestamp at point, if any, or the current date/time
16578 otherwise.
16580 If there is already a timestamp at the cursor, it is replaced.
16582 With two universal prefix arguments, insert an active timestamp
16583 with the current time without prompting the user.
16585 When called from lisp, the timestamp is inactive if INACTIVE is
16586 non-nil."
16587 (interactive "P")
16588 (let* ((ts (cond
16589 ((org-at-date-range-p t)
16590 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16591 ((org-at-timestamp-p t) (match-string 0))))
16592 ;; Default time is either the timestamp at point or today.
16593 ;; When entering a range, only the range start is considered.
16594 (default-time (if (not ts) (current-time)
16595 (apply #'encode-time (org-parse-time-string ts))))
16596 (default-input (and ts (org-get-compact-tod ts)))
16597 (repeater (and ts
16598 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16599 (match-string 0 ts)))
16600 org-time-was-given
16601 org-end-time-was-given
16602 (time
16603 (and (if (equal arg '(16)) (current-time)
16604 ;; Preserve `this-command' and `last-command'.
16605 (let ((this-command this-command)
16606 (last-command last-command))
16607 (org-read-date
16608 arg 'totime nil nil default-time default-input
16609 inactive))))))
16610 (cond
16611 ((and ts
16612 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16613 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16614 (insert "--")
16615 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16617 ;; Make sure we're on a timestamp. When in the middle of a date
16618 ;; range, move arbitrarily to range end.
16619 (unless (org-at-timestamp-p t)
16620 (skip-chars-forward "-")
16621 (org-at-timestamp-p t))
16622 (replace-match "")
16623 (setq org-last-changed-timestamp
16624 (org-insert-time-stamp
16625 time (or org-time-was-given arg)
16626 inactive nil nil (list org-end-time-was-given)))
16627 (when repeater
16628 (backward-char)
16629 (insert " " repeater)
16630 (setq org-last-changed-timestamp
16631 (concat (substring org-last-inserted-timestamp 0 -1)
16632 " " repeater ">")))
16633 (message "Timestamp updated"))
16634 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16635 (t (org-insert-time-stamp
16636 time (or org-time-was-given arg) inactive nil nil
16637 (list org-end-time-was-given))))))
16639 ;; FIXME: can we use this for something else, like computing time differences?
16640 (defun org-get-compact-tod (s)
16641 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16642 (let* ((t1 (match-string 1 s))
16643 (h1 (string-to-number (match-string 2 s)))
16644 (m1 (string-to-number (match-string 3 s)))
16645 (t2 (and (match-end 4) (match-string 5 s)))
16646 (h2 (and t2 (string-to-number (match-string 6 s))))
16647 (m2 (and t2 (string-to-number (match-string 7 s))))
16648 dh dm)
16649 (if (not t2)
16651 (setq dh (- h2 h1) dm (- m2 m1))
16652 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16653 (concat t1 "+" (number-to-string dh)
16654 (and (/= 0 dm) (format ":%02d" dm)))))))
16656 (defun org-time-stamp-inactive (&optional arg)
16657 "Insert an inactive time stamp.
16658 An inactive time stamp is enclosed in square brackets instead of angle
16659 brackets. It is inactive in the sense that it does not trigger agenda entries,
16660 does not link to the calendar and cannot be changed with the S-cursor keys.
16661 So these are more for recording a certain time/date."
16662 (interactive "P")
16663 (org-time-stamp arg 'inactive))
16665 (defvar org-date-ovl (make-overlay 1 1))
16666 (overlay-put org-date-ovl 'face 'org-date-selected)
16667 (org-detach-overlay org-date-ovl)
16669 (defvar org-ans1) ; dynamically scoped parameter
16670 (defvar org-ans2) ; dynamically scoped parameter
16672 (defvar org-plain-time-of-day-regexp) ; defined below
16674 (defvar org-overriding-default-time nil) ; dynamically scoped
16675 (defvar org-read-date-overlay nil)
16676 (defvar org-dcst nil) ; dynamically scoped
16677 (defvar org-read-date-history nil)
16678 (defvar org-read-date-final-answer nil)
16679 (defvar org-read-date-analyze-futurep nil)
16680 (defvar org-read-date-analyze-forced-year nil)
16681 (defvar org-read-date-inactive)
16683 (defvar org-read-date-minibuffer-local-map
16684 (let* ((map (make-sparse-keymap)))
16685 (set-keymap-parent map minibuffer-local-map)
16686 (org-defkey map (kbd ".")
16687 (lambda () (interactive)
16688 ;; Are we at the beginning of the prompt?
16689 (if (org-looking-back "^[^:]+: "
16690 (let ((inhibit-field-text-motion t))
16691 (line-beginning-position)))
16692 (org-eval-in-calendar '(calendar-goto-today))
16693 (insert "."))))
16694 (org-defkey map (kbd "C-.")
16695 (lambda () (interactive)
16696 (org-eval-in-calendar '(calendar-goto-today))))
16697 (org-defkey map [(meta shift left)]
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(calendar-backward-month 1))))
16700 (org-defkey map [(meta shift right)]
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-forward-month 1))))
16703 (org-defkey map [(meta shift up)]
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(calendar-backward-year 1))))
16706 (org-defkey map [(meta shift down)]
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-forward-year 1))))
16709 (org-defkey map [?\e (shift left)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-month 1))))
16712 (org-defkey map [?\e (shift right)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-month 1))))
16715 (org-defkey map [?\e (shift up)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-year 1))))
16718 (org-defkey map [?\e (shift down)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-year 1))))
16721 (org-defkey map [(shift up)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-week 1))))
16724 (org-defkey map [(shift down)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-week 1))))
16727 (org-defkey map [(shift left)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-day 1))))
16730 (org-defkey map [(shift right)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-day 1))))
16733 (org-defkey map "!"
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(diary-view-entries))
16736 (message "")))
16737 (org-defkey map ">"
16738 (lambda () (interactive)
16739 (org-eval-in-calendar '(calendar-scroll-left 1))))
16740 (org-defkey map "<"
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-scroll-right 1))))
16743 (org-defkey map "\C-v"
16744 (lambda () (interactive)
16745 (org-eval-in-calendar
16746 '(calendar-scroll-left-three-months 1))))
16747 (org-defkey map "\M-v"
16748 (lambda () (interactive)
16749 (org-eval-in-calendar
16750 '(calendar-scroll-right-three-months 1))))
16751 map)
16752 "Keymap for minibuffer commands when using `org-read-date'.")
16754 (defvar org-def)
16755 (defvar org-defdecode)
16756 (defvar org-with-time)
16758 (defvar calendar-setup) ; Dynamically scoped.
16759 (defun org-read-date (&optional with-time to-time from-string prompt
16760 default-time default-input inactive)
16761 "Read a date, possibly a time, and make things smooth for the user.
16762 The prompt will suggest to enter an ISO date, but you can also enter anything
16763 which will at least partially be understood by `parse-time-string'.
16764 Unrecognized parts of the date will default to the current day, month, year,
16765 hour and minute. If this command is called to replace a timestamp at point,
16766 or to enter the second timestamp of a range, the default time is taken
16767 from the existing stamp. Furthermore, the command prefers the future,
16768 so if you are giving a date where the year is not given, and the day-month
16769 combination is already past in the current year, it will assume you
16770 mean next year. For details, see the manual. A few examples:
16772 3-2-5 --> 2003-02-05
16773 feb 15 --> currentyear-02-15
16774 2/15 --> currentyear-02-15
16775 sep 12 9 --> 2009-09-12
16776 12:45 --> today 12:45
16777 22 sept 0:34 --> currentyear-09-22 0:34
16778 12 --> currentyear-currentmonth-12
16779 Fri --> nearest Friday after today
16780 -Tue --> last Tuesday
16781 etc.
16783 Furthermore you can specify a relative date by giving, as the *first* thing
16784 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16785 change in days weeks, months, years.
16786 With a single plus or minus, the date is relative to today. With a double
16787 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16788 +4d --> four days from today
16789 +4 --> same as above
16790 +2w --> two weeks from today
16791 ++5 --> five days from default date
16793 The function understands only English month and weekday abbreviations.
16795 While prompting, a calendar is popped up - you can also select the
16796 date with the mouse (button 1). The calendar shows a period of three
16797 months. To scroll it to other months, use the keys `>' and `<'.
16798 If you don't like the calendar, turn it off with
16799 (setq org-read-date-popup-calendar nil)
16801 With optional argument TO-TIME, the date will immediately be converted
16802 to an internal time.
16803 With an optional argument WITH-TIME, the prompt will suggest to
16804 also insert a time. Note that when WITH-TIME is not set, you can
16805 still enter a time, and this function will inform the calling routine
16806 about this change. The calling routine may then choose to change the
16807 format used to insert the time stamp into the buffer to include the time.
16808 With optional argument FROM-STRING, read from this string instead from
16809 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16810 the time/date that is used for everything that is not specified by the
16811 user."
16812 (require 'parse-time)
16813 (let* ((org-with-time with-time)
16814 (org-time-stamp-rounding-minutes
16815 (if (equal org-with-time '(16))
16816 '(0 0)
16817 org-time-stamp-rounding-minutes))
16818 (org-dcst org-display-custom-times)
16819 (ct (org-current-time))
16820 (org-def (or org-overriding-default-time default-time ct))
16821 (org-defdecode (decode-time org-def))
16822 (cur-frame (selected-frame))
16823 (mouse-autoselect-window nil) ; Don't let the mouse jump
16824 (calendar-setup
16825 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16826 (calendar-move-hook nil)
16827 (calendar-view-diary-initially-flag nil)
16828 (calendar-view-holidays-initially-flag nil)
16829 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16830 ;; Rationalize `org-def' and `org-defdecode', if required.
16831 (when (< (nth 2 org-defdecode) org-extend-today-until)
16832 (setf (nth 2 org-defdecode) -1)
16833 (setf (nth 1 org-defdecode) 59)
16834 (setq org-def (apply #'encode-time org-defdecode))
16835 (setq org-defdecode (decode-time org-def)))
16836 (let* ((timestr (format-time-string
16837 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16838 org-def))
16839 (prompt (concat (if prompt (concat prompt " ") "")
16840 (format "Date+time [%s]: " timestr))))
16841 (cond
16842 (from-string (setq ans from-string))
16843 (org-read-date-popup-calendar
16844 (save-excursion
16845 (save-window-excursion
16846 (calendar)
16847 (when (eq calendar-setup 'calendar-only)
16848 (setq cal-frame
16849 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16850 (select-frame cal-frame))
16851 (org-eval-in-calendar '(setq cursor-type nil) t)
16852 (unwind-protect
16853 (progn
16854 (calendar-forward-day (- (time-to-days org-def)
16855 (calendar-absolute-from-gregorian
16856 (calendar-current-date))))
16857 (org-eval-in-calendar nil t)
16858 (let* ((old-map (current-local-map))
16859 (map (copy-keymap calendar-mode-map))
16860 (minibuffer-local-map
16861 (copy-keymap org-read-date-minibuffer-local-map)))
16862 (org-defkey map (kbd "RET") 'org-calendar-select)
16863 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16864 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16865 (unwind-protect
16866 (progn
16867 (use-local-map map)
16868 (setq org-read-date-inactive inactive)
16869 (add-hook 'post-command-hook 'org-read-date-display)
16870 (setq org-ans0
16871 (read-string prompt
16872 default-input
16873 'org-read-date-history
16874 nil))
16875 ;; org-ans0: from prompt
16876 ;; org-ans1: from mouse click
16877 ;; org-ans2: from calendar motion
16878 (setq ans
16879 (concat org-ans0 " " (or org-ans1 org-ans2))))
16880 (remove-hook 'post-command-hook 'org-read-date-display)
16881 (use-local-map old-map)
16882 (when org-read-date-overlay
16883 (delete-overlay org-read-date-overlay)
16884 (setq org-read-date-overlay nil)))))
16885 (bury-buffer "*Calendar*")
16886 (when cal-frame
16887 (delete-frame cal-frame)
16888 (select-frame-set-input-focus cur-frame))))))
16890 (t ; Naked prompt only
16891 (unwind-protect
16892 (setq ans (read-string prompt default-input
16893 'org-read-date-history timestr))
16894 (when org-read-date-overlay
16895 (delete-overlay org-read-date-overlay)
16896 (setq org-read-date-overlay nil))))))
16898 (setq final (org-read-date-analyze ans org-def org-defdecode))
16900 (when org-read-date-analyze-forced-year
16901 (message "Year was forced into %s"
16902 (if org-read-date-force-compatible-dates
16903 "compatible range (1970-2037)"
16904 "range representable on this machine"))
16905 (ding))
16907 ;; One round trip to get rid of 34th of August and stuff like that....
16908 (setq final (decode-time (apply 'encode-time final)))
16910 (setq org-read-date-final-answer ans)
16912 (if to-time
16913 (apply 'encode-time final)
16914 (if (and (boundp 'org-time-was-given) org-time-was-given)
16915 (format "%04d-%02d-%02d %02d:%02d"
16916 (nth 5 final) (nth 4 final) (nth 3 final)
16917 (nth 2 final) (nth 1 final))
16918 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16920 (defun org-read-date-display ()
16921 "Display the current date prompt interpretation in the minibuffer."
16922 (when org-read-date-display-live
16923 (when org-read-date-overlay
16924 (delete-overlay org-read-date-overlay))
16925 (when (minibufferp (current-buffer))
16926 (save-excursion
16927 (end-of-line 1)
16928 (while (not (equal (buffer-substring
16929 (max (point-min) (- (point) 4)) (point))
16930 " "))
16931 (insert " ")))
16932 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16933 " " (or org-ans1 org-ans2)))
16934 (org-end-time-was-given nil)
16935 (f (org-read-date-analyze ans org-def org-defdecode))
16936 (fmts (if org-dcst
16937 org-time-stamp-custom-formats
16938 org-time-stamp-formats))
16939 (fmt (if (or org-with-time
16940 (and (boundp 'org-time-was-given) org-time-was-given))
16941 (cdr fmts)
16942 (car fmts)))
16943 (txt (format-time-string fmt (apply 'encode-time f)))
16944 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16945 (txt (concat "=> " txt)))
16946 (when (and org-end-time-was-given
16947 (string-match org-plain-time-of-day-regexp txt))
16948 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16949 org-end-time-was-given
16950 (substring txt (match-end 0)))))
16951 (when org-read-date-analyze-futurep
16952 (setq txt (concat txt " (=>F)")))
16953 (setq org-read-date-overlay
16954 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16955 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16957 (defun org-read-date-analyze (ans def defdecode)
16958 "Analyze the combined answer of the date prompt."
16959 ;; FIXME: cleanup and comment
16960 ;; Pass `current-time' result to `decode-time' (instead of calling
16961 ;; without arguments) so that only `current-time' has to be
16962 ;; overriden in tests.
16963 (let ((org-def def)
16964 (org-defdecode defdecode)
16965 (nowdecode (decode-time (current-time)))
16966 delta deltan deltaw deltadef year month day
16967 hour minute second wday pm h2 m2 tl wday1
16968 iso-year iso-weekday iso-week iso-date futurep kill-year)
16969 (setq org-read-date-analyze-futurep nil
16970 org-read-date-analyze-forced-year nil)
16971 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16972 (setq ans "+0"))
16974 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16975 (setq ans (replace-match "" t t ans)
16976 deltan (car delta)
16977 deltaw (nth 1 delta)
16978 deltadef (nth 2 delta)))
16980 ;; Check if there is an iso week date in there. If yes, store the
16981 ;; info and postpone interpreting it until the rest of the parsing
16982 ;; is done.
16983 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16984 (setq iso-year (when (match-end 1)
16985 (org-small-year-to-year
16986 (string-to-number (match-string 1 ans))))
16987 iso-weekday (when (match-end 3)
16988 (string-to-number (match-string 3 ans)))
16989 iso-week (string-to-number (match-string 2 ans)))
16990 (setq ans (replace-match "" t t ans)))
16992 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16993 (when (string-match
16994 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16995 (setq year (if (match-end 2)
16996 (string-to-number (match-string 2 ans))
16997 (progn (setq kill-year t)
16998 (string-to-number (format-time-string "%Y"))))
16999 month (string-to-number (match-string 3 ans))
17000 day (string-to-number (match-string 4 ans)))
17001 (setq year (org-small-year-to-year year))
17002 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17003 t nil ans)))
17005 ;; Help matching dotted european dates
17006 (when (string-match
17007 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17008 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17009 (setq kill-year t)
17010 (string-to-number (format-time-string "%Y")))
17011 day (string-to-number (match-string 1 ans))
17012 month (string-to-number (match-string 2 ans))
17013 ans (replace-match (format "%04d-%02d-%02d" year month day)
17014 t nil ans)))
17016 ;; Help matching american dates, like 5/30 or 5/30/7
17017 (when (string-match
17018 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17019 (setq year (if (match-end 4)
17020 (string-to-number (match-string 4 ans))
17021 (progn (setq kill-year t)
17022 (string-to-number (format-time-string "%Y"))))
17023 month (string-to-number (match-string 1 ans))
17024 day (string-to-number (match-string 2 ans)))
17025 (setq year (org-small-year-to-year year))
17026 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17027 t nil ans)))
17028 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17029 ;; If there is a time with am/pm, and *no* time without it, we convert
17030 ;; so that matching will be successful.
17031 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17032 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17033 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17034 (setq hour (string-to-number (match-string 1 ans))
17035 minute (if (match-end 3)
17036 (string-to-number (match-string 3 ans))
17038 pm (equal ?p
17039 (string-to-char (downcase (match-string 4 ans)))))
17040 (if (and (= hour 12) (not pm))
17041 (setq hour 0)
17042 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17043 (setq ans (replace-match (format "%02d:%02d" hour minute)
17044 t t ans))))
17046 ;; Check if a time range is given as a duration
17047 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17048 (setq hour (string-to-number (match-string 1 ans))
17049 h2 (+ hour (string-to-number (match-string 3 ans)))
17050 minute (string-to-number (match-string 2 ans))
17051 m2 (+ minute (if (match-end 5) (string-to-number
17052 (match-string 5 ans))0)))
17053 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17054 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17055 t t ans)))
17057 ;; Check if there is a time range
17058 (when (boundp 'org-end-time-was-given)
17059 (setq org-time-was-given nil)
17060 (when (and (string-match org-plain-time-of-day-regexp ans)
17061 (match-end 8))
17062 (setq org-end-time-was-given (match-string 8 ans))
17063 (setq ans (concat (substring ans 0 (match-beginning 7))
17064 (substring ans (match-end 7))))))
17066 (setq tl (parse-time-string ans)
17067 day (or (nth 3 tl) (nth 3 org-defdecode))
17068 month
17069 (cond ((nth 4 tl))
17070 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17071 ;; Day was specified. Make sure DAY+MONTH
17072 ;; combination happens in the future.
17073 ((nth 3 tl)
17074 (setq futurep t)
17075 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17076 (nth 4 nowdecode)))
17077 (t (nth 4 org-defdecode)))
17078 year
17079 (cond ((and (not kill-year) (nth 5 tl)))
17080 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17081 ;; Month was guessed in the future and is at least
17082 ;; equal to NOWDECODE's. Fix year accordingly.
17083 (futurep
17084 (if (or (> month (nth 4 nowdecode))
17085 (>= day (nth 3 nowdecode)))
17086 (nth 5 nowdecode)
17087 (1+ (nth 5 nowdecode))))
17088 ;; Month was specified. Make sure MONTH+YEAR
17089 ;; combination happens in the future.
17090 ((nth 4 tl)
17091 (setq futurep t)
17092 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17093 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17094 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17095 (t (nth 5 nowdecode))))
17096 (t (nth 5 org-defdecode)))
17097 hour (or (nth 2 tl) (nth 2 org-defdecode))
17098 minute (or (nth 1 tl) (nth 1 org-defdecode))
17099 second (or (nth 0 tl) 0)
17100 wday (nth 6 tl))
17102 (when (and (eq org-read-date-prefer-future 'time)
17103 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17104 (equal day (nth 3 nowdecode))
17105 (equal month (nth 4 nowdecode))
17106 (equal year (nth 5 nowdecode))
17107 (nth 2 tl)
17108 (or (< (nth 2 tl) (nth 2 nowdecode))
17109 (and (= (nth 2 tl) (nth 2 nowdecode))
17110 (nth 1 tl)
17111 (< (nth 1 tl) (nth 1 nowdecode)))))
17112 (setq day (1+ day)
17113 futurep t))
17115 ;; Special date definitions below
17116 (cond
17117 (iso-week
17118 ;; There was an iso week
17119 (require 'cal-iso)
17120 (setq futurep nil)
17121 (setq year (or iso-year year)
17122 day (or iso-weekday wday 1)
17123 wday nil ; to make sure that the trigger below does not match
17124 iso-date (calendar-gregorian-from-absolute
17125 (calendar-iso-to-absolute
17126 (list iso-week day year))))
17127 ; FIXME: Should we also push ISO weeks into the future?
17128 ; (when (and org-read-date-prefer-future
17129 ; (not iso-year)
17130 ; (< (calendar-absolute-from-gregorian iso-date)
17131 ; (time-to-days (current-time))))
17132 ; (setq year (1+ year)
17133 ; iso-date (calendar-gregorian-from-absolute
17134 ; (calendar-iso-to-absolute
17135 ; (list iso-week day year)))))
17136 (setq month (car iso-date)
17137 year (nth 2 iso-date)
17138 day (nth 1 iso-date)))
17139 (deltan
17140 (setq futurep nil)
17141 (unless deltadef
17142 ;; Pass `current-time' result to `decode-time' (instead of
17143 ;; calling without arguments) so that only `current-time' has
17144 ;; to be overriden in tests.
17145 (let ((now (decode-time (current-time))))
17146 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17147 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17148 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17149 ((equal deltaw "m") (setq month (+ month deltan)))
17150 ((equal deltaw "y") (setq year (+ year deltan)))))
17151 ((and wday (not (nth 3 tl)))
17152 ;; Weekday was given, but no day, so pick that day in the week
17153 ;; on or after the derived date.
17154 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17155 (unless (equal wday wday1)
17156 (setq day (+ day (% (- wday wday1 -7) 7))))))
17157 (when (and (boundp 'org-time-was-given)
17158 (nth 2 tl))
17159 (setq org-time-was-given t))
17160 (when (< year 100) (setq year (+ 2000 year)))
17161 ;; Check of the date is representable
17162 (if org-read-date-force-compatible-dates
17163 (progn
17164 (when (< year 1970)
17165 (setq year 1970 org-read-date-analyze-forced-year t))
17166 (when (> year 2037)
17167 (setq year 2037 org-read-date-analyze-forced-year t)))
17168 (condition-case nil
17169 (ignore (encode-time second minute hour day month year))
17170 (error
17171 (setq year (nth 5 org-defdecode))
17172 (setq org-read-date-analyze-forced-year t))))
17173 (setq org-read-date-analyze-futurep futurep)
17174 (list second minute hour day month year)))
17176 (defvar parse-time-weekdays)
17177 (defun org-read-date-get-relative (s today default)
17178 "Check string S for special relative date string.
17179 TODAY and DEFAULT are internal times, for today and for a default.
17180 Return shift list (N what def-flag)
17181 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17182 N is the number of WHATs to shift.
17183 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17184 the DEFAULT date rather than TODAY."
17185 (require 'parse-time)
17186 (when (and
17187 (string-match
17188 (concat
17189 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17190 "\\([0-9]+\\)?"
17191 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17192 "\\([ \t]\\|$\\)") s)
17193 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17194 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17195 (string-to-char (substring (match-string 1 s) -1))
17196 ?+))
17197 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17198 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17199 (what (if (match-end 3) (match-string 3 s) "d"))
17200 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17201 (date (if rel default today))
17202 (wday (nth 6 (decode-time date)))
17203 delta)
17204 (if wday1
17205 (progn
17206 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17207 (when (= delta 0) (setq delta 7))
17208 (when (= dir ?-)
17209 (setq delta (- delta 7))
17210 (when (= delta 0) (setq delta -7)))
17211 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17212 (list delta "d" rel))
17213 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17215 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17216 "Turn a user-specified date into the internal representation.
17217 The internal representation needed by the calendar is (month day year).
17218 This is a wrapper to handle the brain-dead convention in calendar that
17219 user function argument order change dependent on argument order."
17220 (if (boundp 'calendar-date-style)
17221 (cond
17222 ((eq calendar-date-style 'american)
17223 (list arg1 arg2 arg3))
17224 ((eq calendar-date-style 'european)
17225 (list arg2 arg1 arg3))
17226 ((eq calendar-date-style 'iso)
17227 (list arg2 arg3 arg1)))
17228 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17229 (if (org-bound-and-true-p european-calendar-style)
17230 (list arg2 arg1 arg3)
17231 (list arg1 arg2 arg3)))))
17233 (defun org-eval-in-calendar (form &optional keepdate)
17234 "Eval FORM in the calendar window and return to current window.
17235 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17236 (let ((sf (selected-frame))
17237 (sw (selected-window)))
17238 (select-window (get-buffer-window "*Calendar*" t))
17239 (eval form)
17240 (when (and (not keepdate) (calendar-cursor-to-date))
17241 (let* ((date (calendar-cursor-to-date))
17242 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17243 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17244 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17245 (select-window sw)
17246 (org-select-frame-set-input-focus sf)))
17248 (defun org-calendar-select ()
17249 "Return to `org-read-date' with the date currently selected.
17250 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17251 (interactive)
17252 (when (calendar-cursor-to-date)
17253 (let* ((date (calendar-cursor-to-date))
17254 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17255 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17256 (when (active-minibuffer-window) (exit-minibuffer))))
17258 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17259 "Insert a date stamp for the date given by the internal TIME.
17260 See `format-time-string' for the format of TIME.
17261 WITH-HM means use the stamp format that includes the time of the day.
17262 INACTIVE means use square brackets instead of angular ones, so that the
17263 stamp will not contribute to the agenda.
17264 PRE and POST are optional strings to be inserted before and after the
17265 stamp.
17266 The command returns the inserted time stamp."
17267 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17268 stamp)
17269 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17270 (insert-before-markers (or pre ""))
17271 (when (listp extra)
17272 (setq extra (car extra))
17273 (if (and (stringp extra)
17274 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17275 (setq extra (format "-%02d:%02d"
17276 (string-to-number (match-string 1 extra))
17277 (string-to-number (match-string 2 extra))))
17278 (setq extra nil)))
17279 (when extra
17280 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17281 (insert-before-markers (setq stamp (format-time-string fmt time)))
17282 (insert-before-markers (or post ""))
17283 (setq org-last-inserted-timestamp stamp)))
17285 (defun org-toggle-time-stamp-overlays ()
17286 "Toggle the use of custom time stamp formats."
17287 (interactive)
17288 (setq org-display-custom-times (not org-display-custom-times))
17289 (unless org-display-custom-times
17290 (let ((p (point-min)) (bmp (buffer-modified-p)))
17291 (while (setq p (next-single-property-change p 'display))
17292 (when (and (get-text-property p 'display)
17293 (eq (get-text-property p 'face) 'org-date))
17294 (remove-text-properties
17295 p (setq p (next-single-property-change p 'display))
17296 '(display t))))
17297 (set-buffer-modified-p bmp)))
17298 (when (featurep 'xemacs)
17299 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17300 (org-restart-font-lock)
17301 (setq org-table-may-need-update t)
17302 (if org-display-custom-times
17303 (message "Time stamps are overlaid with custom format")
17304 (message "Time stamp overlays removed")))
17306 (defun org-display-custom-time (beg end)
17307 "Overlay modified time stamp format over timestamp between BEG and END."
17308 (let* ((ts (buffer-substring beg end))
17309 t1 w1 with-hm tf time str w2 (off 0))
17310 (save-match-data
17311 (setq t1 (org-parse-time-string ts t))
17312 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17313 (setq off (- (match-end 0) (match-beginning 0)))))
17314 (setq end (- end off))
17315 (setq w1 (- end beg)
17316 with-hm (and (nth 1 t1) (nth 2 t1))
17317 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17318 time (org-fix-decoded-time t1)
17319 str (org-add-props
17320 (format-time-string
17321 (substring tf 1 -1) (apply 'encode-time time))
17322 nil 'mouse-face 'highlight)
17323 w2 (length str))
17324 (unless (= w2 w1)
17325 (add-text-properties (1+ beg) (+ 2 beg)
17326 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17327 (if (featurep 'xemacs)
17328 (progn
17329 (put-text-property beg end 'invisible t)
17330 (put-text-property beg end 'end-glyph (make-glyph str)))
17331 (put-text-property beg end 'display str))))
17333 (defun org-fix-decoded-time (time)
17334 "Set 0 instead of nil for the first 6 elements of time.
17335 Don't touch the rest."
17336 (let ((n 0))
17337 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17339 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17341 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17342 "Difference between TIMESTAMP-STRING and now in days.
17343 If SECONDS is non-nil, return the difference in seconds."
17344 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17345 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17346 (funcall fdiff (current-time)))))
17348 (defun org-deadline-close (timestamp-string &optional ndays)
17349 "Is the time in TIMESTAMP-STRING close to the current date?"
17350 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17351 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17352 (not (org-entry-is-done-p))))
17354 (defun org-get-wdays (ts &optional delay zero-delay)
17355 "Get the deadline lead time appropriate for timestring TS.
17356 When DELAY is non-nil, get the delay time for scheduled items
17357 instead of the deadline lead time. When ZERO-DELAY is non-nil
17358 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17359 don't try to find the delay cookie in the scheduled timestamp."
17360 (let ((tv (if delay org-scheduled-delay-days
17361 org-deadline-warning-days)))
17362 (cond
17363 ((or (and delay (< tv 0))
17364 (and delay zero-delay (<= tv 0))
17365 (and (not delay) (<= tv 0)))
17366 ;; Enforce this value no matter what
17367 (- tv))
17368 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17369 ;; lead time is specified.
17370 (floor (* (string-to-number (match-string 1 ts))
17371 (cdr (assoc (match-string 2 ts)
17372 '(("d" . 1) ("w" . 7)
17373 ("m" . 30.4) ("y" . 365.25)
17374 ("h" . 0.041667)))))))
17375 ;; go for the default.
17376 (t tv))))
17378 (defun org-calendar-select-mouse (ev)
17379 "Return to `org-read-date' with the date currently selected.
17380 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17381 (interactive "e")
17382 (mouse-set-point ev)
17383 (when (calendar-cursor-to-date)
17384 (let* ((date (calendar-cursor-to-date))
17385 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17386 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17387 (when (active-minibuffer-window) (exit-minibuffer))))
17389 (defun org-check-deadlines (ndays)
17390 "Check if there are any deadlines due or past due.
17391 A deadline is considered due if it happens within `org-deadline-warning-days'
17392 days from today's date. If the deadline appears in an entry marked DONE,
17393 it is not shown. The prefix arg NDAYS can be used to test that many
17394 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17395 (interactive "P")
17396 (let* ((org-warn-days
17397 (cond
17398 ((equal ndays '(4)) 100000)
17399 (ndays (prefix-numeric-value ndays))
17400 (t (abs org-deadline-warning-days))))
17401 (case-fold-search nil)
17402 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17403 (callback
17404 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17405 (message "%d deadlines past-due or due within %d days"
17406 (org-occur regexp nil callback)
17407 org-warn-days)))
17409 (defsubst org-re-timestamp (type)
17410 "Return a regexp for timestamp TYPE.
17411 Allowed values for TYPE are:
17413 all: all timestamps
17414 active: only active timestamps (<...>)
17415 inactive: only inactive timestamps ([...])
17416 scheduled: only scheduled timestamps
17417 deadline: only deadline timestamps
17418 closed: only closed time-stamps
17420 When TYPE is nil, fall back on returning a regexp that matches
17421 both scheduled and deadline timestamps."
17422 (cl-case type
17423 (all org-ts-regexp-both)
17424 (active org-ts-regexp)
17425 (inactive org-ts-regexp-inactive)
17426 (scheduled org-scheduled-time-regexp)
17427 (deadline org-deadline-time-regexp)
17428 (closed org-closed-time-regexp)
17429 (otherwise
17430 (concat "\\<"
17431 (regexp-opt (list org-deadline-string org-scheduled-string))
17432 " *<\\([^>]+\\)>"))))
17434 (defun org-check-before-date (d)
17435 "Check if there are deadlines or scheduled entries before date D."
17436 (interactive (list (org-read-date)))
17437 (let* ((case-fold-search nil)
17438 (regexp (org-re-timestamp org-ts-type))
17439 (ts-type org-ts-type)
17440 (callback
17441 (lambda ()
17442 (let ((match (match-string 1)))
17443 (and (if (memq ts-type '(active inactive all))
17444 (eq (org-element-type (org-element-context)) 'timestamp)
17445 (org-at-planning-p))
17446 (time-less-p
17447 (org-time-string-to-time match)
17448 (org-time-string-to-time d)))))))
17449 (message "%d entries before %s"
17450 (org-occur regexp nil callback)
17451 d)))
17453 (defun org-check-after-date (d)
17454 "Check if there are deadlines or scheduled entries after date D."
17455 (interactive (list (org-read-date)))
17456 (let* ((case-fold-search nil)
17457 (regexp (org-re-timestamp org-ts-type))
17458 (ts-type org-ts-type)
17459 (callback
17460 (lambda ()
17461 (let ((match (match-string 1)))
17462 (and (if (memq ts-type '(active inactive all))
17463 (eq (org-element-type (org-element-context)) 'timestamp)
17464 (org-at-planning-p))
17465 (not (time-less-p
17466 (org-time-string-to-time match)
17467 (org-time-string-to-time d))))))))
17468 (message "%d entries after %s"
17469 (org-occur regexp nil callback)
17470 d)))
17472 (defun org-check-dates-range (start-date end-date)
17473 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17474 (interactive (list (org-read-date nil nil nil "Range starts")
17475 (org-read-date nil nil nil "Range end")))
17476 (let ((case-fold-search nil)
17477 (regexp (org-re-timestamp org-ts-type))
17478 (callback
17479 `(lambda ()
17480 (let ((match (match-string 1)))
17481 (and
17482 ,(if (memq org-ts-type '(active inactive all))
17483 '(eq (org-element-type (org-element-context)) 'timestamp)
17484 '(org-at-planning-p))
17485 (not (time-less-p
17486 (org-time-string-to-time match)
17487 (org-time-string-to-time start-date)))
17488 (time-less-p
17489 (org-time-string-to-time match)
17490 (org-time-string-to-time end-date)))))))
17491 (message "%d entries between %s and %s"
17492 (org-occur regexp nil callback) start-date end-date)))
17494 (defun org-evaluate-time-range (&optional to-buffer)
17495 "Evaluate a time range by computing the difference between start and end.
17496 Normally the result is just printed in the echo area, but with prefix arg
17497 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17498 If the time range is actually in a table, the result is inserted into the
17499 next column.
17500 For time difference computation, a year is assumed to be exactly 365
17501 days in order to avoid rounding problems."
17502 (interactive "P")
17504 (org-clock-update-time-maybe)
17505 (save-excursion
17506 (unless (org-at-date-range-p t)
17507 (goto-char (point-at-bol))
17508 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17509 (unless (org-at-date-range-p t)
17510 (user-error "Not at a time-stamp range, and none found in current line")))
17511 (let* ((ts1 (match-string 1))
17512 (ts2 (match-string 2))
17513 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17514 (match-end (match-end 0))
17515 (time1 (org-time-string-to-time ts1))
17516 (time2 (org-time-string-to-time ts2))
17517 (t1 (org-float-time time1))
17518 (t2 (org-float-time time2))
17519 (diff (abs (- t2 t1)))
17520 (negative (< (- t2 t1) 0))
17521 ;; (ys (floor (* 365 24 60 60)))
17522 (ds (* 24 60 60))
17523 (hs (* 60 60))
17524 (fy "%dy %dd %02d:%02d")
17525 (fy1 "%dy %dd")
17526 (fd "%dd %02d:%02d")
17527 (fd1 "%dd")
17528 (fh "%02d:%02d")
17529 y d h m align)
17530 (if havetime
17531 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17533 d (floor (/ diff ds)) diff (mod diff ds)
17534 h (floor (/ diff hs)) diff (mod diff hs)
17535 m (floor (/ diff 60)))
17536 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17538 d (floor (+ (/ diff ds) 0.5))
17539 h 0 m 0))
17540 (if (not to-buffer)
17541 (message "%s" (org-make-tdiff-string y d h m))
17542 (if (org-at-table-p)
17543 (progn
17544 (goto-char match-end)
17545 (setq align t)
17546 (and (looking-at " *|") (goto-char (match-end 0))))
17547 (goto-char match-end))
17548 (when (looking-at
17549 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17550 (replace-match ""))
17551 (when negative (insert " -"))
17552 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17553 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17554 (insert " " (format fh h m))))
17555 (when align (org-table-align))
17556 (message "Time difference inserted")))))
17558 (defun org-make-tdiff-string (y d h m)
17559 (let ((fmt "")
17560 (l nil))
17561 (when (> y 0)
17562 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17563 (push y l))
17564 (when (> d 0)
17565 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17566 (push d l))
17567 (when (> h 0)
17568 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17569 (push h l))
17570 (when (> m 0)
17571 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17572 (push m l))
17573 (apply 'format fmt (nreverse l))))
17575 (defun org-time-string-to-time (s &optional buffer pos)
17576 "Convert a timestamp string into internal time."
17577 (condition-case errdata
17578 (apply 'encode-time (org-parse-time-string s))
17579 (error (error "Bad timestamp `%s'%s\nError was: %s"
17580 s (if (not (and buffer pos))
17582 (format-message " at %d in buffer `%s'" pos buffer))
17583 (cdr errdata)))))
17585 (defun org-time-string-to-seconds (s)
17586 "Convert a timestamp string to a number of seconds."
17587 (org-float-time (org-time-string-to-time s)))
17589 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17591 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17592 "Convert time stamp S to an absolute day number.
17594 If DAYNR in non-nil, and there is a specifier for a cyclic time
17595 stamp, get the closest date to DAYNR. If PREFER is
17596 `past' (respectively `future') return a date past (respectively
17597 after) or equal to DAYNR.
17599 POS is the location of time stamp S, as a buffer position in
17600 BUFFER.
17602 Diary sexp timestamps are matched against DAYNR, when non-nil.
17603 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17604 signalled."
17605 (cond
17606 ((string-match "\\`%%\\((.*)\\)" s)
17607 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17608 ;; only able to match individual dates. If it fails, raise an
17609 ;; error.
17610 (if (and daynr
17611 (org-diary-sexp-entry
17612 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17613 daynr
17614 (signal 'org-diary-sexp-no-match (list s))))
17615 ((and daynr show-all) (org-closest-date s daynr prefer))
17616 (t (time-to-days
17617 (condition-case errdata
17618 (apply #'encode-time (org-parse-time-string s))
17619 (error (error "Bad timestamp `%s'%s\nError was: %s"
17621 (if (not (and buffer pos)) ""
17622 (format-message " at %d in buffer `%s'" pos buffer))
17623 (cdr errdata))))))))
17625 (defun org-days-to-iso-week (days)
17626 "Return the iso week number."
17627 (require 'cal-iso)
17628 (car (calendar-iso-from-absolute days)))
17630 (defun org-small-year-to-year (year)
17631 "Convert 2-digit years into 4-digit years.
17632 YEAR is expanded into one of the 30 next years, if possible, or
17633 into a past one. Any year larger than 99 is returned unchanged."
17634 (if (>= year 100) year
17635 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17636 (century (/ current 100))
17637 (offset (- year (% current 100))))
17638 (cond ((> offset 30) (+ (* (1- century) 100) year))
17639 ((> offset -70) (+ (* century 100) year))
17640 (t (+ (* (1+ century) 100) year))))))
17642 (defun org-time-from-absolute (d)
17643 "Return the time corresponding to date D.
17644 D may be an absolute day number, or a calendar-type list (month day year)."
17645 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17646 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17648 (defvar org-agenda-current-date)
17649 (defun org-calendar-holiday ()
17650 "List of holidays, for Diary display in Org mode."
17651 (require 'holidays)
17652 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17653 (and hl (mapconcat #'identity hl "; "))))
17655 (defun org-diary-sexp-entry (sexp entry d)
17656 "Process a SEXP diary ENTRY for date D."
17657 (require 'diary-lib)
17658 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17659 ;; dynamically.
17660 (let* ((sexp `(let ((entry ,entry)
17661 (date ',d))
17662 ,(car (read-from-string sexp))))
17663 (result (if calendar-debug-sexp (eval sexp)
17664 (condition-case nil
17665 (eval sexp)
17666 (error
17667 (beep)
17668 (message "Bad sexp at line %d in %s: %s"
17669 (org-current-line)
17670 (buffer-file-name) sexp)
17671 (sleep-for 2))))))
17672 (cond ((stringp result) (split-string result "; "))
17673 ((and (consp result)
17674 (not (consp (cdr result)))
17675 (stringp (cdr result))) (cdr result))
17676 ((and (consp result)
17677 (stringp (car result))) result)
17678 (result entry))))
17680 (defun org-diary-to-ical-string (frombuf)
17681 "Get iCalendar entries from diary entries in buffer FROMBUF.
17682 This uses the icalendar.el library."
17683 (let* ((tmpdir (if (featurep 'xemacs)
17684 (temp-directory)
17685 temporary-file-directory))
17686 (tmpfile (make-temp-name
17687 (expand-file-name "orgics" tmpdir)))
17688 buf rtn b e)
17689 (with-current-buffer frombuf
17690 (icalendar-export-region (point-min) (point-max) tmpfile)
17691 (setq buf (find-buffer-visiting tmpfile))
17692 (set-buffer buf)
17693 (goto-char (point-min))
17694 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17695 (setq b (match-beginning 0)))
17696 (goto-char (point-max))
17697 (when (re-search-backward "^END:VEVENT" nil t)
17698 (setq e (match-end 0)))
17699 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17700 (kill-buffer buf)
17701 (delete-file tmpfile)
17702 rtn))
17704 (defun org-closest-date (start current prefer)
17705 "Return closest date to CURRENT starting from START.
17707 CURRENT and START are both time stamps.
17709 When PREFER is `past', return a date that is either CURRENT or
17710 past. When PREFER is `future', return a date that is either
17711 CURRENT or future.
17713 Only time stamps with a repeater are modified. Any other time
17714 stamp stay unchanged. In any case, return value is an absolute
17715 day number."
17716 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17717 ;; No repeater. Do not shift time stamp.
17718 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17719 (let ((value (string-to-number (match-string 1 start)))
17720 (type (match-string 2 start)))
17721 (if (= 0 value)
17722 ;; Repeater with a 0-value is considered as void.
17723 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17724 (let* ((base (org-date-to-gregorian start))
17725 (target (org-date-to-gregorian current))
17726 (sday (calendar-absolute-from-gregorian base))
17727 (cday (calendar-absolute-from-gregorian target))
17728 n1 n2)
17729 ;; If START is already past CURRENT, just return START.
17730 (if (<= cday sday) sday
17731 ;; Compute closest date before (N1) and closest date past
17732 ;; (N2) CURRENT.
17733 (pcase type
17734 ("h"
17735 (let ((missing-hours
17736 (mod (+ (- (* 24 (- cday sday))
17737 (nth 2 (org-parse-time-string start)))
17738 org-extend-today-until)
17739 value)))
17740 (setf n1 (if (= missing-hours 0) cday
17741 (- cday (1+ (/ missing-hours 24)))))
17742 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17743 ((or "d" "w")
17744 (let ((value (if (equal type "w") (* 7 value) value)))
17745 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17746 (setf n2 (+ n1 value))))
17747 ("m"
17748 (let* ((add-months
17749 (lambda (d n)
17750 ;; Add N months to gregorian date D, i.e.,
17751 ;; a list (MONTH DAY YEAR). Return a valid
17752 ;; gregorian date.
17753 (let ((m (+ (nth 0 d) n)))
17754 (list (mod m 12)
17755 (nth 1 d)
17756 (+ (/ m 12) (nth 2 d))))))
17757 (months ; Complete months to TARGET.
17758 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17759 (- (nth 0 target) (nth 0 base))
17760 ;; If START's day is greater than
17761 ;; TARGET's, remove incomplete month.
17762 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17763 value)
17764 value))
17765 (before (funcall add-months base months)))
17766 (setf n1 (calendar-absolute-from-gregorian before))
17767 (setf n2
17768 (calendar-absolute-from-gregorian
17769 (funcall add-months before value)))))
17771 (let* ((d (nth 1 base))
17772 (m (nth 0 base))
17773 (y (nth 2 base))
17774 (years ; Complete years to TARGET.
17775 (* (/ (- (nth 2 target)
17777 ;; If START's month and day are
17778 ;; greater than TARGET's, remove
17779 ;; incomplete year.
17780 (if (or (> (nth 0 target) m)
17781 (and (= (nth 0 target) m)
17782 (> (nth 1 target) d)))
17785 value)
17786 value))
17787 (before (list m d (+ y years))))
17788 (setf n1 (calendar-absolute-from-gregorian before))
17789 (setf n2 (calendar-absolute-from-gregorian
17790 (list m d (+ (nth 2 before) value)))))))
17791 ;; Handle PREFER parameter, if any.
17792 (cond
17793 ((eq prefer 'past) (if (= cday n2) n2 n1))
17794 ((eq prefer 'future) (if (= cday n1) n1 n2))
17795 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17797 (defun org-date-to-gregorian (d)
17798 "Turn any specification of date D into a Gregorian date for the calendar."
17799 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17800 ((and (listp d) (= (length d) 3)) d)
17801 ((stringp d)
17802 (let ((d (org-parse-time-string d)))
17803 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17804 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17806 (defun org-parse-time-string (s &optional nodefault)
17807 "Parse the standard Org-mode time string.
17808 This should be a lot faster than the normal `parse-time-string'.
17809 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17810 hour and minute fields will be nil if not given."
17811 (cond ((string-match org-ts-regexp0 s)
17812 (list 0
17813 (when (or (match-beginning 8) (not nodefault))
17814 (string-to-number (or (match-string 8 s) "0")))
17815 (when (or (match-beginning 7) (not nodefault))
17816 (string-to-number (or (match-string 7 s) "0")))
17817 (string-to-number (match-string 4 s))
17818 (string-to-number (match-string 3 s))
17819 (string-to-number (match-string 2 s))
17820 nil nil nil))
17821 ((string-match "^<[^>]+>$" s)
17822 (decode-time (seconds-to-time (org-matcher-time s))))
17823 (t (error "Not a standard Org-mode time string: %s" s))))
17825 (defun org-timestamp-up (&optional arg)
17826 "Increase the date item at the cursor by one.
17827 If the cursor is on the year, change the year. If it is on the month,
17828 the day or the time, change that.
17829 With prefix ARG, change by that many units."
17830 (interactive "p")
17831 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17833 (defun org-timestamp-down (&optional arg)
17834 "Decrease the date item at the cursor by one.
17835 If the cursor is on the year, change the year. If it is on the month,
17836 the day or the time, change that.
17837 With prefix ARG, change by that many units."
17838 (interactive "p")
17839 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17841 (defun org-timestamp-up-day (&optional arg)
17842 "Increase the date in the time stamp by one day.
17843 With prefix ARG, change that many days."
17844 (interactive "p")
17845 (if (and (not (org-at-timestamp-p t))
17846 (org-at-heading-p))
17847 (org-todo 'up)
17848 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17850 (defun org-timestamp-down-day (&optional arg)
17851 "Decrease the date in the time stamp by one day.
17852 With prefix ARG, change that many days."
17853 (interactive "p")
17854 (if (and (not (org-at-timestamp-p t))
17855 (org-at-heading-p))
17856 (org-todo 'down)
17857 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17859 (defun org-at-timestamp-p (&optional inactive-ok)
17860 "Non-nil if point is inside a timestamp.
17862 When optional argument INACTIVE-OK is non-nil, also consider
17863 inactive timestamps.
17865 When this function returns a non-nil value, match data is set
17866 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17867 INACTIVE-OK."
17868 (interactive)
17869 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17870 (pos (point))
17871 (ans (or (looking-at tsr)
17872 (save-excursion
17873 (skip-chars-backward "^[<\n\r\t")
17874 (when (> (point) (point-min)) (backward-char 1))
17875 (and (looking-at tsr)
17876 (> (- (match-end 0) pos) -1))))))
17877 (and ans
17878 (boundp 'org-ts-what)
17879 (setq org-ts-what
17880 (cond
17881 ((= pos (match-beginning 0)) 'bracket)
17882 ;; Point is considered to be "on the bracket" whether
17883 ;; it's really on it or right after it.
17884 ((= pos (1- (match-end 0))) 'bracket)
17885 ((= pos (match-end 0)) 'after)
17886 ((org-pos-in-match-range pos 2) 'year)
17887 ((org-pos-in-match-range pos 3) 'month)
17888 ((org-pos-in-match-range pos 7) 'hour)
17889 ((org-pos-in-match-range pos 8) 'minute)
17890 ((or (org-pos-in-match-range pos 4)
17891 (org-pos-in-match-range pos 5)) 'day)
17892 ((and (> pos (or (match-end 8) (match-end 5)))
17893 (< pos (match-end 0)))
17894 (- pos (or (match-end 8) (match-end 5))))
17895 (t 'day))))
17896 ans))
17898 (defun org-toggle-timestamp-type ()
17899 "Toggle the type (<active> or [inactive]) of a time stamp."
17900 (interactive)
17901 (when (org-at-timestamp-p t)
17902 (let ((beg (match-beginning 0)) (end (match-end 0))
17903 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17904 (save-excursion
17905 (goto-char beg)
17906 (while (re-search-forward "[][<>]" end t)
17907 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17908 t t)))
17909 (message "Timestamp is now %sactive"
17910 (if (equal (char-after beg) ?<) "" "in")))))
17912 (defun org-at-clock-log-p nil
17913 "Is the cursor on the clock log line?"
17914 (save-excursion
17915 (move-beginning-of-line 1)
17916 (looking-at org-clock-line-re)))
17918 (defvar org-clock-history) ; defined in org-clock.el
17919 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17920 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17921 "Change the date in the time stamp at point.
17922 The date will be changed by N times WHAT. WHAT can be `day', `month',
17923 `year', `minute', `second'. If WHAT is not given, the cursor position
17924 in the timestamp determines what will be changed.
17925 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17926 (let ((origin (point)) origin-cat
17927 with-hm inactive
17928 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17929 org-ts-what
17930 extra rem
17931 ts time time0 fixnext clrgx)
17932 (unless (org-at-timestamp-p t)
17933 (user-error "Not at a timestamp"))
17934 (if (and (not what) (eq org-ts-what 'bracket))
17935 (org-toggle-timestamp-type)
17936 ;; Point isn't on brackets. Remember the part of the time-stamp
17937 ;; the point was in. Indeed, size of time-stamps may change,
17938 ;; but point must be kept in the same category nonetheless.
17939 (setq origin-cat org-ts-what)
17940 (when (and (not what) (not (eq org-ts-what 'day))
17941 org-display-custom-times
17942 (get-text-property (point) 'display)
17943 (not (get-text-property (1- (point)) 'display)))
17944 (setq org-ts-what 'day))
17945 (setq org-ts-what (or what org-ts-what)
17946 inactive (= (char-after (match-beginning 0)) ?\[)
17947 ts (match-string 0))
17948 (replace-match "")
17949 (when (string-match
17950 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17952 (setq extra (match-string 1 ts))
17953 (when suppress-tmp-delay
17954 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17955 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17956 (setq with-hm t))
17957 (setq time0 (org-parse-time-string ts))
17958 (when (and updown
17959 (eq org-ts-what 'minute)
17960 (not current-prefix-arg))
17961 ;; This looks like s-up and s-down. Change by one rounding step.
17962 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17963 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17964 (setcar (cdr time0) (+ (nth 1 time0)
17965 (if (> n 0) (- rem) (- dm rem))))))
17966 (setq time
17967 (encode-time (or (car time0) 0)
17968 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17969 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17970 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17971 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17972 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17973 (nthcdr 6 time0)))
17974 (when (and (member org-ts-what '(hour minute))
17975 extra
17976 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17977 (setq extra (org-modify-ts-extra
17978 extra
17979 (if (eq org-ts-what 'hour) 2 5)
17980 n dm)))
17981 (when (integerp org-ts-what)
17982 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17983 (when (eq what 'calendar)
17984 (let ((cal-date (org-get-date-from-calendar)))
17985 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17986 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17987 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17988 (setcar time0 (or (car time0) 0))
17989 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17990 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17991 (setq time (apply 'encode-time time0))))
17992 ;; Insert the new time-stamp, and ensure point stays in the same
17993 ;; category as before (i.e. not after the last position in that
17994 ;; category).
17995 (let ((pos (point)))
17996 ;; Stay before inserted string. `save-excursion' is of no use.
17997 (setq org-last-changed-timestamp
17998 (org-insert-time-stamp time with-hm inactive nil nil extra))
17999 (goto-char pos))
18000 (save-match-data
18001 (looking-at org-ts-regexp3)
18002 (goto-char (cond
18003 ;; `day' category ends before `hour' if any, or at
18004 ;; the end of the day name.
18005 ((eq origin-cat 'day)
18006 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18007 ((eq origin-cat 'hour) (min (match-end 7) origin))
18008 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18009 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18010 ;; `year' and `month' have both fixed size: point
18011 ;; couldn't have moved into another part.
18012 (t origin))))
18013 ;; Update clock if on a CLOCK line.
18014 (org-clock-update-time-maybe)
18015 ;; Maybe adjust the closest clock in `org-clock-history'
18016 (when org-clock-adjust-closest
18017 (if (not (and (org-at-clock-log-p)
18018 (< 1 (length (delq nil (mapcar 'marker-position
18019 org-clock-history))))))
18020 (message "No clock to adjust")
18021 (cond ((save-excursion ; fix previous clock?
18022 (re-search-backward org-ts-regexp0 nil t)
18023 (org-looking-back (concat org-clock-string " \\[")
18024 (line-beginning-position)))
18025 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18026 ((save-excursion ; fix next clock?
18027 (re-search-backward org-ts-regexp0 nil t)
18028 (looking-at (concat org-ts-regexp0 "\\] =>")))
18029 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18030 (save-window-excursion
18031 ;; Find closest clock to point, adjust the previous/next one in history
18032 (let* ((p (save-excursion (org-back-to-heading t)))
18033 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18034 (clfixnth
18035 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18036 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18037 (if (not clfixpos)
18038 (message "No clock to adjust")
18039 (save-excursion
18040 (org-goto-marker-or-bmk clfixpos)
18041 (org-show-subtree)
18042 (when (re-search-forward clrgx nil t)
18043 (goto-char (match-beginning 1))
18044 (let (org-clock-adjust-closest)
18045 (org-timestamp-change n org-ts-what updown))
18046 (message "Clock adjusted in %s for heading: %s"
18047 (file-name-nondirectory (buffer-file-name))
18048 (org-get-heading t t)))))))))
18049 ;; Try to recenter the calendar window, if any.
18050 (when (and org-calendar-follow-timestamp-change
18051 (get-buffer-window "*Calendar*" t)
18052 (memq org-ts-what '(day month year)))
18053 (org-recenter-calendar (time-to-days time))))))
18055 (defun org-modify-ts-extra (s pos n dm)
18056 "Change the different parts of the lead-time and repeat fields in timestamp."
18057 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18058 ng h m new rem)
18059 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18060 (cond
18061 ((or (org-pos-in-match-range pos 2)
18062 (org-pos-in-match-range pos 3))
18063 (setq m (string-to-number (match-string 3 s))
18064 h (string-to-number (match-string 2 s)))
18065 (if (org-pos-in-match-range pos 2)
18066 (setq h (+ h n))
18067 (setq n (* dm (org-no-warnings (signum n))))
18068 (unless (= 0 (setq rem (% m dm)))
18069 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18070 (setq m (+ m n)))
18071 (when (< m 0) (setq m (+ m 60) h (1- h)))
18072 (when (> m 59) (setq m (- m 60) h (1+ h)))
18073 (setq h (mod h 24))
18074 (setq ng 1 new (format "-%02d:%02d" h m)))
18075 ((org-pos-in-match-range pos 6)
18076 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18077 ((org-pos-in-match-range pos 5)
18078 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18080 ((org-pos-in-match-range pos 9)
18081 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18082 ((org-pos-in-match-range pos 8)
18083 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18085 (when ng
18086 (setq s (concat
18087 (substring s 0 (match-beginning ng))
18089 (substring s (match-end ng))))))
18092 (defun org-recenter-calendar (d)
18093 "If the calendar is visible, recenter it to date D."
18094 (let ((cwin (get-buffer-window "*Calendar*" t)))
18095 (when cwin
18096 (let ((calendar-move-hook nil))
18097 (with-selected-window cwin
18098 (calendar-goto-date
18099 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18101 (defun org-goto-calendar (&optional arg)
18102 "Go to the Emacs calendar at the current date.
18103 If there is a time stamp in the current line, go to that date.
18104 A prefix ARG can be used to force the current date."
18105 (interactive "P")
18106 (let ((tsr org-ts-regexp) diff
18107 (calendar-move-hook nil)
18108 (calendar-view-holidays-initially-flag nil)
18109 (calendar-view-diary-initially-flag nil))
18110 (when (or (org-at-timestamp-p)
18111 (save-excursion
18112 (beginning-of-line 1)
18113 (looking-at (concat ".*" tsr))))
18114 (let ((d1 (time-to-days (current-time)))
18115 (d2 (time-to-days
18116 (org-time-string-to-time (match-string 1)))))
18117 (setq diff (- d2 d1))))
18118 (calendar)
18119 (calendar-goto-today)
18120 (when (and diff (not arg)) (calendar-forward-day diff))))
18122 (defun org-get-date-from-calendar ()
18123 "Return a list (month day year) of date at point in calendar."
18124 (with-current-buffer "*Calendar*"
18125 (save-match-data
18126 (calendar-cursor-to-date))))
18128 (defun org-date-from-calendar ()
18129 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18130 If there is already a time stamp at the cursor position, update it."
18131 (interactive)
18132 (if (org-at-timestamp-p t)
18133 (org-timestamp-change 0 'calendar)
18134 (let ((cal-date (org-get-date-from-calendar)))
18135 (org-insert-time-stamp
18136 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18138 (defcustom org-effort-durations
18139 `(("min" . 1)
18140 ("h" . 60)
18141 ("d" . ,(* 60 8))
18142 ("w" . ,(* 60 8 5))
18143 ("m" . ,(* 60 8 5 4))
18144 ("y" . ,(* 60 8 5 40)))
18145 "Conversion factor to minutes for an effort modifier.
18147 Each entry has the form (MODIFIER . MINUTES).
18149 In an effort string, a number followed by MODIFIER is multiplied
18150 by the specified number of MINUTES to obtain an effort in
18151 minutes.
18153 For example, if the value of this variable is ((\"hours\" . 60)), then an
18154 effort string \"2hours\" is equivalent to 120 minutes."
18155 :group 'org-agenda
18156 :version "25.1"
18157 :package-version '(Org . "8.3")
18158 :type '(alist :key-type (string :tag "Modifier")
18159 :value-type (number :tag "Minutes")))
18161 (defun org-minutes-to-clocksum-string (m)
18162 "Format number of minutes as a clocksum string.
18163 The format is determined by `org-time-clocksum-format',
18164 `org-time-clocksum-use-fractional' and
18165 `org-time-clocksum-fractional-format' and
18166 `org-time-clocksum-use-effort-durations'."
18167 (let ((clocksum "")
18168 (m (round m)) ; Don't allow fractions of minutes
18169 h d w mo y fmt n)
18170 (setq h (if org-time-clocksum-use-effort-durations
18171 (cdr (assoc "h" org-effort-durations)) 60)
18172 d (if org-time-clocksum-use-effort-durations
18173 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18174 w (if org-time-clocksum-use-effort-durations
18175 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18176 mo (if org-time-clocksum-use-effort-durations
18177 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18178 y (if org-time-clocksum-use-effort-durations
18179 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18180 ;; fractional format
18181 (if org-time-clocksum-use-fractional
18182 (cond
18183 ;; single format string
18184 ((stringp org-time-clocksum-fractional-format)
18185 (format org-time-clocksum-fractional-format (/ m (float h))))
18186 ;; choice of fractional formats for different time units
18187 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18188 (> (/ (truncate m) (* y d h)) 0))
18189 (format fmt (/ m (* y d (float h)))))
18190 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18191 (> (/ (truncate m) (* mo d h)) 0))
18192 (format fmt (/ m (* mo d (float h)))))
18193 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18194 (> (/ (truncate m) (* w d h)) 0))
18195 (format fmt (/ m (* w d (float h)))))
18196 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18197 (> (/ (truncate m) (* d h)) 0))
18198 (format fmt (/ m (* d (float h)))))
18199 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18200 (> (/ (truncate m) h) 0))
18201 (format fmt (/ m (float h))))
18202 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18203 (format fmt m))
18204 ;; fall back to smallest time unit with a format
18205 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18206 (format fmt (/ m (float h))))
18207 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18208 (format fmt (/ m (* d (float h)))))
18209 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18210 (format fmt (/ m (* w d (float h)))))
18211 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18212 (format fmt (/ m (* mo d (float h)))))
18213 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18214 (format fmt (/ m (* y d (float h))))))
18215 ;; standard (non-fractional) format, with single format string
18216 (if (stringp org-time-clocksum-format)
18217 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18218 ;; separate formats components
18219 (and (setq fmt (plist-get org-time-clocksum-format :years))
18220 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18221 (plist-get org-time-clocksum-format :require-years))
18222 (setq clocksum (concat clocksum (format fmt n))
18223 m (- m (* n y d h))))
18224 (and (setq fmt (plist-get org-time-clocksum-format :months))
18225 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18226 (plist-get org-time-clocksum-format :require-months))
18227 (setq clocksum (concat clocksum (format fmt n))
18228 m (- m (* n mo d h))))
18229 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18230 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18231 (plist-get org-time-clocksum-format :require-weeks))
18232 (setq clocksum (concat clocksum (format fmt n))
18233 m (- m (* n w d h))))
18234 (and (setq fmt (plist-get org-time-clocksum-format :days))
18235 (or (> (setq n (/ (truncate m) (* d h))) 0)
18236 (plist-get org-time-clocksum-format :require-days))
18237 (setq clocksum (concat clocksum (format fmt n))
18238 m (- m (* n d h))))
18239 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18240 (or (> (setq n (/ (truncate m) h)) 0)
18241 (plist-get org-time-clocksum-format :require-hours))
18242 (setq clocksum (concat clocksum (format fmt n))
18243 m (- m (* n h))))
18244 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18245 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18246 (setq clocksum (concat clocksum (format fmt m))))
18247 ;; return formatted time duration
18248 clocksum))))
18250 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18251 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18252 "Org mode version 8.0")
18254 (defun org-hours-to-clocksum-string (n)
18255 (org-minutes-to-clocksum-string (* n 60)))
18257 (defun org-hh:mm-string-to-minutes (s)
18258 "Convert a string H:MM to a number of minutes.
18259 If the string is just a number, interpret it as minutes.
18260 In fact, the first hh:mm or number in the string will be taken,
18261 there can be extra stuff in the string.
18262 If no number is found, the return value is 0."
18263 (cond
18264 ((integerp s) s)
18265 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18266 (+ (* (string-to-number (match-string 1 s)) 60)
18267 (string-to-number (match-string 2 s))))
18268 ((string-match "\\([0-9]+\\)" s)
18269 (string-to-number (match-string 1 s)))
18270 (t 0)))
18272 (defcustom org-image-actual-width t
18273 "Should we use the actual width of images when inlining them?
18275 When set to t, always use the image width.
18277 When set to a number, use imagemagick (when available) to set
18278 the image's width to this value.
18280 When set to a number in a list, try to get the width from any
18281 #+ATTR.* keyword if it matches a width specification like
18283 #+ATTR_HTML: :width 300px
18285 and fall back on that number if none is found.
18287 When set to nil, try to get the width from an #+ATTR.* keyword
18288 and fall back on the original width if none is found.
18290 This requires Emacs >= 24.1, build with imagemagick support."
18291 :group 'org-appearance
18292 :version "24.4"
18293 :package-version '(Org . "8.0")
18294 :type '(choice
18295 (const :tag "Use the image width" t)
18296 (integer :tag "Use a number of pixels")
18297 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18298 (const :tag "Use #+ATTR* or don't resize" nil)))
18300 (defcustom org-agenda-inhibit-startup nil
18301 "Inhibit startup when preparing agenda buffers.
18302 When this variable is t, the initialization of the Org agenda
18303 buffers is inhibited: e.g. the visibility state is not set, the
18304 tables are not re-aligned, etc."
18305 :type 'boolean
18306 :version "24.3"
18307 :group 'org-agenda)
18309 (define-obsolete-variable-alias
18310 'org-agenda-ignore-drawer-properties
18311 'org-agenda-ignore-properties "25.1")
18313 (defcustom org-agenda-ignore-properties nil
18314 "Avoid updating text properties when building the agenda.
18315 Properties are used to prepare buffers for effort estimates,
18316 appointments, statistics and subtree-local categories.
18317 If you don't use these in the agenda, you can add them to this
18318 list and agenda building will be a bit faster.
18319 The value is a list, with zero or more of the symbols `effort', `appt',
18320 `stats' or `category'."
18321 :type '(set :greedy t
18322 (const effort)
18323 (const appt)
18324 (const stats)
18325 (const category))
18326 :version "25.1"
18327 :package-version '(Org . "8.3")
18328 :group 'org-agenda)
18330 (defun org-duration-string-to-minutes (s &optional output-to-string)
18331 "Convert a duration string S to minutes.
18333 A bare number is interpreted as minutes, modifiers can be set by
18334 customizing `org-effort-durations' (which see).
18336 Entries containing a colon are interpreted as H:MM by
18337 `org-hh:mm-string-to-minutes'."
18338 (let ((result 0)
18339 (re (concat "\\([0-9.]+\\) *\\("
18340 (regexp-opt (mapcar 'car org-effort-durations))
18341 "\\)")))
18342 (while (string-match re s)
18343 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18344 (string-to-number (match-string 1 s))))
18345 (setq s (replace-match "" nil t s)))
18346 (setq result (floor result))
18347 (cl-incf result (org-hh:mm-string-to-minutes s))
18348 (if output-to-string (number-to-string result) result)))
18350 ;;;; Files
18352 (defun org-save-all-org-buffers ()
18353 "Save all Org-mode buffers without user confirmation."
18354 (interactive)
18355 (message "Saving all Org-mode buffers...")
18356 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18357 (when (featurep 'org-id) (org-id-locations-save))
18358 (message "Saving all Org-mode buffers... done"))
18360 (defun org-revert-all-org-buffers ()
18361 "Revert all Org-mode buffers.
18362 Prompt for confirmation when there are unsaved changes.
18363 Be sure you know what you are doing before letting this function
18364 overwrite your changes.
18366 This function is useful in a setup where one tracks org files
18367 with a version control system, to revert on one machine after pulling
18368 changes from another. I believe the procedure must be like this:
18370 1. M-x org-save-all-org-buffers
18371 2. Pull changes from the other machine, resolve conflicts
18372 3. M-x org-revert-all-org-buffers"
18373 (interactive)
18374 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18375 (user-error "Abort"))
18376 (save-excursion
18377 (save-window-excursion
18378 (dolist (b (buffer-list))
18379 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18380 (with-current-buffer b buffer-file-name))
18381 (org-pop-to-buffer-same-window b)
18382 (revert-buffer t 'no-confirm)))
18383 (when (and (featurep 'org-id) org-id-track-globally)
18384 (org-id-locations-load)))))
18386 ;;;; Agenda files
18388 ;;;###autoload
18389 (defun org-switchb (&optional arg)
18390 "Switch between Org buffers.
18392 With \\[universal-argument] prefix, restrict available buffers to files.
18394 With \\[universal-argument] \\[universal-argument] \
18395 prefix, restrict available buffers to agenda files."
18396 (interactive "P")
18397 (let ((blist (org-buffer-list
18398 (cond ((equal arg '(4)) 'files)
18399 ((equal arg '(16)) 'agenda)))))
18400 (org-pop-to-buffer-same-window
18401 (completing-read "Org buffer: "
18402 (mapcar #'list (mapcar #'buffer-name blist))
18403 nil t))))
18405 (defun org-buffer-list (&optional predicate exclude-tmp)
18406 "Return a list of Org buffers.
18407 PREDICATE can be `export', `files' or `agenda'.
18409 export restrict the list to Export buffers.
18410 files restrict the list to buffers visiting Org files.
18411 agenda restrict the list to buffers visiting agenda files.
18413 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18414 (let* ((bfn nil)
18415 (agenda-files (and (eq predicate 'agenda)
18416 (mapcar 'file-truename (org-agenda-files t))))
18417 (filter
18418 (cond
18419 ((eq predicate 'files)
18420 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18421 ((eq predicate 'export)
18422 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18423 ((eq predicate 'agenda)
18424 (lambda (b)
18425 (with-current-buffer b
18426 (and (derived-mode-p 'org-mode)
18427 (setq bfn (buffer-file-name b))
18428 (member (file-truename bfn) agenda-files)))))
18429 (t (lambda (b) (with-current-buffer b
18430 (or (derived-mode-p 'org-mode)
18431 (string-match "\\*Org .*Export"
18432 (buffer-name b)))))))))
18433 (delq nil
18434 (mapcar
18435 (lambda(b)
18436 (if (and (funcall filter b)
18437 (or (not exclude-tmp)
18438 (not (string-match "tmp" (buffer-name b)))))
18440 nil))
18441 (buffer-list)))))
18443 (defun org-agenda-files (&optional unrestricted archives)
18444 "Get the list of agenda files.
18445 Optional UNRESTRICTED means return the full list even if a restriction
18446 is currently in place.
18447 When ARCHIVES is t, include all archive files that are really being
18448 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18449 `org-agenda-archives-mode' is t."
18450 (let ((files
18451 (cond
18452 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18453 ((stringp org-agenda-files) (org-read-agenda-file-list))
18454 ((listp org-agenda-files) org-agenda-files)
18455 (t (error "Invalid value of `org-agenda-files'")))))
18456 (setq files (apply 'append
18457 (mapcar (lambda (f)
18458 (if (file-directory-p f)
18459 (directory-files
18460 f t org-agenda-file-regexp)
18461 (list f)))
18462 files)))
18463 (when org-agenda-skip-unavailable-files
18464 (setq files (delq nil
18465 (mapcar (function
18466 (lambda (file)
18467 (and (file-readable-p file) file)))
18468 files))))
18469 (when (or (eq archives t)
18470 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18471 (setq files (org-add-archive-files files)))
18472 files))
18474 (defun org-agenda-file-p (&optional file)
18475 "Return non-nil, if FILE is an agenda file.
18476 If FILE is omitted, use the file associated with the current
18477 buffer."
18478 (let ((fname (or file (buffer-file-name))))
18479 (and fname
18480 (member (file-truename fname)
18481 (mapcar #'file-truename (org-agenda-files t))))))
18483 (defun org-edit-agenda-file-list ()
18484 "Edit the list of agenda files.
18485 Depending on setup, this either uses customize to edit the variable
18486 `org-agenda-files', or it visits the file that is holding the list. In the
18487 latter case, the buffer is set up in a way that saving it automatically kills
18488 the buffer and restores the previous window configuration."
18489 (interactive)
18490 (if (stringp org-agenda-files)
18491 (let ((cw (current-window-configuration)))
18492 (find-file org-agenda-files)
18493 (setq-local org-window-configuration cw)
18494 (org-add-hook 'after-save-hook
18495 (lambda ()
18496 (set-window-configuration
18497 (prog1 org-window-configuration
18498 (kill-buffer (current-buffer))))
18499 (org-install-agenda-files-menu)
18500 (message "New agenda file list installed"))
18501 nil 'local)
18502 (message "%s" (substitute-command-keys
18503 "Edit list and finish with \\[save-buffer]")))
18504 (customize-variable 'org-agenda-files)))
18506 (defun org-store-new-agenda-file-list (list)
18507 "Set new value for the agenda file list and save it correctly."
18508 (if (stringp org-agenda-files)
18509 (let ((fe (org-read-agenda-file-list t)) b u)
18510 (while (setq b (find-buffer-visiting org-agenda-files))
18511 (kill-buffer b))
18512 (with-temp-file org-agenda-files
18513 (insert
18514 (mapconcat
18515 (lambda (f) ;; Keep un-expanded entries.
18516 (if (setq u (assoc f fe))
18517 (cdr u)
18519 list "\n")
18520 "\n")))
18521 (let ((org-mode-hook nil) (org-inhibit-startup t)
18522 (org-insert-mode-line-in-empty-file nil))
18523 (setq org-agenda-files list)
18524 (customize-save-variable 'org-agenda-files org-agenda-files))))
18526 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18527 "Read the list of agenda files from a file.
18528 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18529 filenames, used by `org-store-new-agenda-file-list' to write back
18530 un-expanded file names."
18531 (when (file-directory-p org-agenda-files)
18532 (error "`org-agenda-files' cannot be a single directory"))
18533 (when (stringp org-agenda-files)
18534 (with-temp-buffer
18535 (insert-file-contents org-agenda-files)
18536 (mapcar
18537 (lambda (f)
18538 (let ((e (expand-file-name (substitute-in-file-name f)
18539 org-directory)))
18540 (if pair-with-expansion
18541 (cons e f)
18542 e)))
18543 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18545 ;;;###autoload
18546 (defun org-cycle-agenda-files ()
18547 "Cycle through the files in `org-agenda-files'.
18548 If the current buffer visits an agenda file, find the next one in the list.
18549 If the current buffer does not, find the first agenda file."
18550 (interactive)
18551 (let* ((fs (or (org-agenda-files t)
18552 (user-error "No agenda files")))
18553 (files (copy-sequence fs))
18554 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18555 file)
18556 (when tcf
18557 (while (and (setq file (pop files))
18558 (not (equal (file-truename file) tcf)))))
18559 (find-file (car (or files fs)))
18560 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18562 (defun org-agenda-file-to-front (&optional to-end)
18563 "Move/add the current file to the top of the agenda file list.
18564 If the file is not present in the list, it is added to the front. If it is
18565 present, it is moved there. With optional argument TO-END, add/move to the
18566 end of the list."
18567 (interactive "P")
18568 (let ((org-agenda-skip-unavailable-files nil)
18569 (file-alist (mapcar (lambda (x)
18570 (cons (file-truename x) x))
18571 (org-agenda-files t)))
18572 (ctf (file-truename
18573 (or buffer-file-name
18574 (user-error "Please save the current buffer to a file"))))
18575 x had)
18576 (setq x (assoc ctf file-alist) had x)
18578 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18579 (if to-end
18580 (setq file-alist (append (delq x file-alist) (list x)))
18581 (setq file-alist (cons x (delq x file-alist))))
18582 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18583 (org-install-agenda-files-menu)
18584 (message "File %s to %s of agenda file list"
18585 (if had "moved" "added") (if to-end "end" "front"))))
18587 (defun org-remove-file (&optional file)
18588 "Remove current file from the list of files in variable `org-agenda-files'.
18589 These are the files which are being checked for agenda entries.
18590 Optional argument FILE means use this file instead of the current."
18591 (interactive)
18592 (let* ((org-agenda-skip-unavailable-files nil)
18593 (file (or file buffer-file-name
18594 (user-error "Current buffer does not visit a file")))
18595 (true-file (file-truename file))
18596 (afile (abbreviate-file-name file))
18597 (files (delq nil (mapcar
18598 (lambda (x)
18599 (unless (equal true-file
18600 (file-truename x))
18602 (org-agenda-files t)))))
18603 (if (not (= (length files) (length (org-agenda-files t))))
18604 (progn
18605 (org-store-new-agenda-file-list files)
18606 (org-install-agenda-files-menu)
18607 (message "Removed from Org Agenda list: %s" afile))
18608 (message "File was not in list: %s (not removed)" afile))))
18610 (defun org-file-menu-entry (file)
18611 (vector file (list 'find-file file) t))
18613 (defun org-check-agenda-file (file)
18614 "Make sure FILE exists. If not, ask user what to do."
18615 (unless (file-exists-p file)
18616 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18617 (abbreviate-file-name file))
18618 (let ((r (downcase (read-char-exclusive))))
18619 (cond
18620 ((equal r ?r)
18621 (org-remove-file file)
18622 (throw 'nextfile t))
18623 (t (user-error "Abort"))))))
18625 (defun org-get-agenda-file-buffer (file)
18626 "Get an agenda buffer visiting FILE.
18627 If the buffer needs to be created, add it to the list of buffers
18628 which might be released later."
18629 (let ((buf (org-find-base-buffer-visiting file)))
18630 (if buf
18631 buf ; just return it
18632 ;; Make a new buffer and remember it
18633 (setq buf (find-file-noselect file))
18634 (when buf (push buf org-agenda-new-buffers))
18635 buf)))
18637 (defun org-release-buffers (blist)
18638 "Release all buffers in list, asking the user for confirmation when needed.
18639 When a buffer is unmodified, it is just killed. When modified, it is saved
18640 \(if the user agrees) and then killed."
18641 (let (file)
18642 (dolist (buf blist)
18643 (setq file (buffer-file-name buf))
18644 (when (and (buffer-modified-p buf)
18645 file
18646 (y-or-n-p (format "Save file %s? " file)))
18647 (with-current-buffer buf (save-buffer)))
18648 (kill-buffer buf))))
18650 (defun org-agenda-prepare-buffers (files)
18651 "Create buffers for all agenda files, protect archived trees and comments."
18652 (interactive)
18653 (let ((pa '(:org-archived t))
18654 (pc '(:org-comment t))
18655 (pall '(:org-archived t :org-comment t))
18656 (inhibit-read-only t)
18657 (org-inhibit-startup org-agenda-inhibit-startup)
18658 (rea (concat ":" org-archive-tag ":"))
18659 re pos)
18660 (setq org-tag-alist-for-agenda nil
18661 org-tag-groups-alist-for-agenda nil)
18662 (save-excursion
18663 (save-restriction
18664 (dolist (file files)
18665 (catch 'nextfile
18666 (if (bufferp file)
18667 (set-buffer file)
18668 (org-check-agenda-file file)
18669 (set-buffer (org-get-agenda-file-buffer file)))
18670 (widen)
18671 (org-set-regexps-and-options 'tags-only)
18672 (setq pos (point))
18673 (or (memq 'category org-agenda-ignore-properties)
18674 (org-refresh-category-properties))
18675 (or (memq 'stats org-agenda-ignore-properties)
18676 (org-refresh-stats-properties))
18677 (or (memq 'effort org-agenda-ignore-properties)
18678 (org-refresh-effort-properties))
18679 (or (memq 'appt org-agenda-ignore-properties)
18680 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18681 (setq org-todo-keywords-for-agenda
18682 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18683 (setq org-done-keywords-for-agenda
18684 (append org-done-keywords-for-agenda org-done-keywords))
18685 (setq org-todo-keyword-alist-for-agenda
18686 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18687 (setq org-tag-alist-for-agenda
18688 (org-uniquify
18689 (append org-tag-alist-for-agenda
18690 org-tag-alist
18691 org-tag-persistent-alist)))
18692 ;; Merge current file's tag groups into global
18693 ;; `org-tag-groups-alist-for-agenda'.
18694 (when org-group-tags
18695 (dolist (alist org-tag-groups-alist)
18696 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18697 (if old
18698 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18699 (push alist org-tag-groups-alist-for-agenda)))))
18700 (org-with-silent-modifications
18701 (save-excursion
18702 (remove-text-properties (point-min) (point-max) pall)
18703 (when org-agenda-skip-archived-trees
18704 (goto-char (point-min))
18705 (while (re-search-forward rea nil t)
18706 (when (org-at-heading-p t)
18707 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18708 (goto-char (point-min))
18709 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18710 (while (re-search-forward re nil t)
18711 (when (save-match-data (org-in-commented-heading-p t))
18712 (add-text-properties
18713 (match-beginning 0) (org-end-of-subtree t) pc)))))
18714 (goto-char pos)))))
18715 (setq org-todo-keywords-for-agenda
18716 (org-uniquify org-todo-keywords-for-agenda))
18717 (setq org-todo-keyword-alist-for-agenda
18718 (org-uniquify org-todo-keyword-alist-for-agenda))))
18721 ;;;; CDLaTeX minor mode
18723 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18724 "Keymap for the minor `org-cdlatex-mode'.")
18726 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18727 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18728 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18729 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18730 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18732 (defvar org-cdlatex-texmathp-advice-is-done nil
18733 "Flag remembering if we have applied the advice to texmathp already.")
18735 (define-minor-mode org-cdlatex-mode
18736 "Toggle the minor `org-cdlatex-mode'.
18737 This mode supports entering LaTeX environment and math in LaTeX fragments
18738 in Org-mode.
18739 \\{org-cdlatex-mode-map}"
18740 nil " OCDL" nil
18741 (when org-cdlatex-mode
18742 (require 'cdlatex)
18743 (run-hooks 'cdlatex-mode-hook)
18744 (cdlatex-compute-tables))
18745 (unless org-cdlatex-texmathp-advice-is-done
18746 (setq org-cdlatex-texmathp-advice-is-done t)
18747 (defadvice texmathp (around org-math-always-on activate)
18748 "Always return t in org-mode buffers.
18749 This is because we want to insert math symbols without dollars even outside
18750 the LaTeX math segments. If Orgmode thinks that point is actually inside
18751 an embedded LaTeX fragment, let texmathp do its job.
18752 \\[org-cdlatex-mode-map]"
18753 (interactive)
18754 (let (p)
18755 (cond
18756 ((not (derived-mode-p 'org-mode)) ad-do-it)
18757 ((eq this-command 'cdlatex-math-symbol)
18758 (setq ad-return-value t
18759 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18761 (let ((p (org-inside-LaTeX-fragment-p)))
18762 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18763 (setq ad-return-value t
18764 texmathp-why '("Org-mode embedded math" . 0))
18765 (when p ad-do-it)))))))))
18767 (defun turn-on-org-cdlatex ()
18768 "Unconditionally turn on `org-cdlatex-mode'."
18769 (org-cdlatex-mode 1))
18771 (defun org-try-cdlatex-tab ()
18772 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18773 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18774 - inside a LaTeX fragment, or
18775 - after the first word in a line, where an abbreviation expansion could
18776 insert a LaTeX environment."
18777 (when org-cdlatex-mode
18778 (cond
18779 ;; Before any word on the line: No expansion possible.
18780 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18781 ;; Just after first word on the line: Expand it. Make sure it
18782 ;; cannot happen on headlines, though.
18783 ((save-excursion
18784 (skip-chars-backward "a-zA-Z0-9*")
18785 (skip-chars-backward " \t")
18786 (and (bolp) (not (org-at-heading-p))))
18787 (cdlatex-tab) t)
18788 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18790 (defun org-cdlatex-underscore-caret (&optional _arg)
18791 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18792 Revert to the normal definition outside of these fragments."
18793 (interactive "P")
18794 (if (org-inside-LaTeX-fragment-p)
18795 (call-interactively 'cdlatex-sub-superscript)
18796 (let (org-cdlatex-mode)
18797 (call-interactively (key-binding (vector last-input-event))))))
18799 (defun org-cdlatex-math-modify (&optional _arg)
18800 "Execute `cdlatex-math-modify' in LaTeX fragments.
18801 Revert to the normal definition outside of these fragments."
18802 (interactive "P")
18803 (if (org-inside-LaTeX-fragment-p)
18804 (call-interactively 'cdlatex-math-modify)
18805 (let (org-cdlatex-mode)
18806 (call-interactively (key-binding (vector last-input-event))))))
18808 (defun org-cdlatex-environment-indent (&optional environment item)
18809 "Execute `cdlatex-environment' and indent the inserted environment.
18811 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18813 The inserted environment is indented to current indentation
18814 unless point is at the beginning of the line, in which the
18815 environment remains unintended."
18816 (interactive)
18817 ;; cdlatex-environment always return nil. Therefore, capture output
18818 ;; first and determine if an environment was selected.
18819 (let* ((beg (point-marker))
18820 (end (copy-marker (point) t))
18821 (inserted (progn
18822 (ignore-errors (cdlatex-environment environment item))
18823 (< beg end)))
18824 ;; Figure out how many lines to move forward after the
18825 ;; environment has been inserted.
18826 (lines (when inserted
18827 (save-excursion
18828 (- (cl-loop while (< beg (point))
18829 with x = 0
18830 do (forward-line -1)
18831 (cl-incf x)
18832 finally return x)
18833 (if (progn (goto-char beg)
18834 (and (progn (skip-chars-forward " \t") (eolp))
18835 (progn (skip-chars-backward " \t") (bolp))))
18836 1 0)))))
18837 (env (org-trim (delete-and-extract-region beg end))))
18838 (when inserted
18839 ;; Get indentation of next line unless at column 0.
18840 (let ((ind (if (bolp) 0
18841 (save-excursion
18842 (org-return-indent)
18843 (prog1 (org-get-indentation)
18844 (when (progn (skip-chars-forward " \t") (eolp))
18845 (delete-region beg (point)))))))
18846 (bol (progn (skip-chars-backward " \t") (bolp))))
18847 ;; Insert a newline before environment unless at column zero
18848 ;; to "escape" the current line. Insert a newline if
18849 ;; something is one the same line as \end{ENVIRONMENT}.
18850 (insert
18851 (concat (unless bol "\n") env
18852 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18853 (unless (zerop ind)
18854 (save-excursion
18855 (goto-char beg)
18856 (while (< (point) end)
18857 (unless (eolp) (org-indent-line-to ind))
18858 (forward-line))))
18859 (goto-char beg)
18860 (forward-line lines)
18861 (org-indent-line-to ind)))
18862 (set-marker beg nil)
18863 (set-marker end nil)))
18866 ;;;; LaTeX fragments
18868 (defun org-inside-LaTeX-fragment-p ()
18869 "Test if point is inside a LaTeX fragment.
18870 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18871 sequence appearing also before point.
18872 Even though the matchers for math are configurable, this function assumes
18873 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18874 delimiters are skipped when they have been removed by customization.
18875 The return value is nil, or a cons cell with the delimiter and the
18876 position of this delimiter.
18878 This function does a reasonably good job, but can locally be fooled by
18879 for example currency specifications. For example it will assume being in
18880 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18881 fragments that are properly closed, but during editing, we have to live
18882 with the uncertainty caused by missing closing delimiters. This function
18883 looks only before point, not after."
18884 (catch 'exit
18885 (let ((pos (point))
18886 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18887 (lim (progn
18888 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18889 (point)))
18890 dd-on str (start 0) m re)
18891 (goto-char pos)
18892 (when dodollar
18893 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18894 re (nth 1 (assoc "$" org-latex-regexps)))
18895 (while (string-match re str start)
18896 (cond
18897 ((= (match-end 0) (length str))
18898 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18899 ((= (match-end 0) (- (length str) 5))
18900 (throw 'exit nil))
18901 (t (setq start (match-end 0))))))
18902 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18903 (goto-char pos)
18904 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18905 (and (match-beginning 2) (throw 'exit nil))
18906 ;; count $$
18907 (while (re-search-backward "\\$\\$" lim t)
18908 (setq dd-on (not dd-on)))
18909 (goto-char pos)
18910 (when dd-on (cons "$$" m))))))
18912 (defun org-inside-latex-macro-p ()
18913 "Is point inside a LaTeX macro or its arguments?"
18914 (save-match-data
18915 (org-in-regexp
18916 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18918 (defun org--format-latex-make-overlay (beg end image)
18919 "Build an overlay between BEG and END using IMAGE file."
18920 (let ((ov (make-overlay beg end)))
18921 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18922 (overlay-put ov 'evaporate t)
18923 (overlay-put ov
18924 'modification-hooks
18925 (list (lambda (o _flag _beg _end &optional _l)
18926 (delete-overlay o))))
18927 (if (featurep 'xemacs)
18928 (progn
18929 (overlay-put ov 'invisible t)
18930 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18931 (overlay-put ov
18932 'display
18933 (list 'image :type 'png :file image :ascent 'center)))))
18935 (defun org--list-latex-overlays (&optional beg end)
18936 "List all Org LaTeX overlays in current buffer.
18937 Limit to overlays between BEG and END when those are provided."
18938 (cl-remove-if-not
18939 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18940 (overlays-in (or beg (point-min)) (or end (point-max)))))
18942 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18943 "Remove all overlays with LaTeX fragment images in current buffer.
18944 When optional arguments BEG and END are non-nil, remove all
18945 overlays between them instead. Return a non-nil value when some
18946 overlays were removed, nil otherwise."
18947 (let ((overlays (org--list-latex-overlays beg end)))
18948 (mapc #'delete-overlay overlays)
18949 overlays))
18951 (define-obsolete-function-alias
18952 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18953 (defun org-toggle-latex-fragment (&optional arg)
18954 "Preview the LaTeX fragment at point, or all locally or globally.
18956 If the cursor is on a LaTeX fragment, create the image and overlay
18957 it over the source code, if there is none. Remove it otherwise.
18958 If there is no fragment at point, display all fragments in the
18959 current section.
18961 With prefix ARG, preview or clear image for all fragments in the
18962 current subtree or in the whole buffer when used before the first
18963 headline. With a double prefix ARG \\[universal-argument] \
18964 \\[universal-argument] preview or clear images
18965 for all fragments in the buffer."
18966 (interactive "P")
18967 (when (display-graphic-p)
18968 (catch 'exit
18969 (save-excursion
18970 (let ((window-start (window-start)) msg)
18971 (save-restriction
18972 (cond
18973 ((or (equal arg '(16))
18974 (and (equal arg '(4))
18975 (org-with-limited-levels (org-before-first-heading-p))))
18976 (if (org-remove-latex-fragment-image-overlays)
18977 (progn (message "LaTeX fragments images removed from buffer")
18978 (throw 'exit nil))
18979 (setq msg "Creating images for buffer...")))
18980 ((equal arg '(4))
18981 (org-with-limited-levels (org-back-to-heading t))
18982 (let ((beg (point))
18983 (end (progn (org-end-of-subtree t) (point))))
18984 (if (org-remove-latex-fragment-image-overlays beg end)
18985 (progn
18986 (message "LaTeX fragment images removed from subtree")
18987 (throw 'exit nil))
18988 (setq msg "Creating images for subtree...")
18989 (narrow-to-region beg end))))
18990 ((let ((datum (org-element-context)))
18991 (when (memq (org-element-type datum)
18992 '(latex-environment latex-fragment))
18993 (let* ((beg (org-element-property :begin datum))
18994 (end (org-element-property :end datum)))
18995 (if (org-remove-latex-fragment-image-overlays beg end)
18996 (progn (message "LaTeX fragment image removed")
18997 (throw 'exit nil))
18998 (narrow-to-region beg end)
18999 (setq msg "Creating image..."))))))
19001 (org-with-limited-levels
19002 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19003 (outline-previous-heading)
19004 (point)))
19005 (end (progn (outline-next-heading) (point))))
19006 (if (org-remove-latex-fragment-image-overlays beg end)
19007 (progn
19008 (message "LaTeX fragment images removed from section")
19009 (throw 'exit nil))
19010 (setq msg "Creating images for section...")
19011 (narrow-to-region beg end))))))
19012 (let ((file (buffer-file-name (buffer-base-buffer))))
19013 (org-format-latex
19014 (concat org-latex-preview-ltxpng-directory "org-ltxpng")
19015 ;; Emacs cannot overlay images from remote hosts.
19016 ;; Create it in `temporary-file-directory' instead.
19017 (if (or (not file) (file-remote-p file))
19018 temporary-file-directory
19019 default-directory)
19020 'overlays msg 'forbuffer
19021 org-latex-create-formula-image-program)))
19022 ;; Work around a bug that doesn't restore window's start
19023 ;; when widening back the buffer.
19024 (set-window-start nil window-start)
19025 (message (concat msg "done")))))))
19027 (defun org-format-latex
19028 (prefix &optional dir overlays msg forbuffer processing-type)
19029 "Replace LaTeX fragments with links to an image, and produce images.
19031 When optional argument OVERLAYS is non-nil, display the image on
19032 top of the fragment instead of replacing it.
19034 PROCESSING-TYPE is the conversion method to use, as a symbol.
19036 Some of the options can be changed using the variable
19037 `org-format-latex-options', which see."
19038 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19039 (unless (eq processing-type 'verbatim)
19040 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19041 (cnt 0)
19042 checkdir-flag)
19043 (goto-char (point-min))
19044 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19045 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19046 (overlay-recenter (point-max)))
19047 (while (re-search-forward math-regexp nil t)
19048 (unless (and overlays
19049 (eq (get-char-property (point) 'org-overlay-type)
19050 'org-latex-overlay))
19051 (let* ((context (org-element-context))
19052 (type (org-element-type context)))
19053 (when (memq type '(latex-environment latex-fragment))
19054 (let ((block-type (eq type 'latex-environment))
19055 (value (org-element-property :value context))
19056 (beg (org-element-property :begin context))
19057 (end (save-excursion
19058 (goto-char (org-element-property :end context))
19059 (skip-chars-backward " \r\t\n")
19060 (point))))
19061 (cl-case processing-type
19062 (mathjax
19063 ;; Prepare for MathJax processing.
19064 (if (not (string-match "\\`\\$\\$?" value))
19065 (goto-char end)
19066 (delete-region beg end)
19067 (if (string= (match-string 0 value) "$$")
19068 (insert "\\[" (substring value 2 -2) "\\]")
19069 (insert "\\(" (substring value 1 -1) "\\)"))))
19070 ((dvipng imagemagick)
19071 ;; Process to an image.
19072 (cl-incf cnt)
19073 (goto-char beg)
19074 (let* ((face (face-at-point))
19075 ;; Get the colors from the face at point.
19077 (let ((color (plist-get org-format-latex-options
19078 :foreground)))
19079 (if (and forbuffer (eq color 'auto))
19080 (face-attribute face :foreground nil 'default)
19081 color)))
19083 (let ((color (plist-get org-format-latex-options
19084 :background)))
19085 (if (and forbuffer (eq color 'auto))
19086 (face-attribute face :background nil 'default)
19087 color)))
19088 (hash (sha1 (prin1-to-string
19089 (list org-format-latex-header
19090 org-latex-default-packages-alist
19091 org-latex-packages-alist
19092 org-format-latex-options
19093 forbuffer value fg bg))))
19094 (absprefix (expand-file-name prefix dir))
19095 (linkfile (format "%s_%s.png" prefix hash))
19096 (movefile (format "%s_%s.png" absprefix hash))
19097 (sep (and block-type "\n\n"))
19098 (link (concat sep "[[file:" linkfile "]]" sep))
19099 (options
19100 (org-combine-plists
19101 org-format-latex-options
19102 `(:foreground ,fg :background ,bg))))
19103 (when msg (message msg cnt))
19104 (unless checkdir-flag ; Ensure the directory exists.
19105 (setq checkdir-flag t)
19106 (let ((todir (file-name-directory absprefix)))
19107 (unless (file-directory-p todir)
19108 (make-directory todir t))))
19109 (unless (file-exists-p movefile)
19110 (org-create-formula-image
19111 value movefile options forbuffer processing-type))
19112 (if overlays
19113 (progn
19114 (dolist (o (overlays-in beg end))
19115 (when (eq (overlay-get o 'org-overlay-type)
19116 'org-latex-overlay)
19117 (delete-overlay o)))
19118 (org--format-latex-make-overlay beg end movefile)
19119 (goto-char end))
19120 (delete-region beg end)
19121 (insert
19122 (org-add-props link
19123 (list 'org-latex-src
19124 (replace-regexp-in-string "\"" "" value)
19125 'org-latex-src-embed-type
19126 (if block-type 'paragraph 'character)))))))
19127 (mathml
19128 ;; Process to MathML.
19129 (unless (org-format-latex-mathml-available-p)
19130 (user-error "LaTeX to MathML converter not configured"))
19131 (cl-incf cnt)
19132 (when msg (message msg cnt))
19133 (goto-char beg)
19134 (delete-region beg end)
19135 (insert (org-format-latex-as-mathml
19136 value block-type prefix dir)))
19137 (otherwise
19138 (error "Unknown conversion type %s for LaTeX fragments"
19139 processing-type)))))))))))
19141 (defun org-create-math-formula (latex-frag &optional mathml-file)
19142 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19143 Use `org-latex-to-mathml-convert-command'. If the conversion is
19144 sucessful, return the portion between \"<math...> </math>\"
19145 elements otherwise return nil. When MATHML-FILE is specified,
19146 write the results in to that file. When invoked as an
19147 interactive command, prompt for LATEX-FRAG, with initial value
19148 set to the current active region and echo the results for user
19149 inspection."
19150 (interactive (list (let ((frag (when (org-region-active-p)
19151 (buffer-substring-no-properties
19152 (region-beginning) (region-end)))))
19153 (read-string "LaTeX Fragment: " frag nil frag))))
19154 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19155 (let* ((tmp-in-file
19156 (let ((file (file-relative-name
19157 (make-temp-name (expand-file-name "ltxmathml-in")))))
19158 (write-region latex-frag nil file)
19159 file))
19160 (tmp-out-file (file-relative-name
19161 (make-temp-name (expand-file-name "ltxmathml-out"))))
19162 (cmd (format-spec
19163 org-latex-to-mathml-convert-command
19164 `((?j . ,(and org-latex-to-mathml-jar-file
19165 (shell-quote-argument
19166 (expand-file-name
19167 org-latex-to-mathml-jar-file))))
19168 (?I . ,(shell-quote-argument tmp-in-file))
19169 (?i . ,latex-frag)
19170 (?o . ,(shell-quote-argument tmp-out-file)))))
19171 mathml shell-command-output)
19172 (when (org-called-interactively-p 'any)
19173 (unless (org-format-latex-mathml-available-p)
19174 (user-error "LaTeX to MathML converter not configured")))
19175 (message "Running %s" cmd)
19176 (setq shell-command-output (shell-command-to-string cmd))
19177 (setq mathml
19178 (when (file-readable-p tmp-out-file)
19179 (with-current-buffer (find-file-noselect tmp-out-file t)
19180 (goto-char (point-min))
19181 (when (re-search-forward
19182 (concat
19183 (regexp-quote
19184 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19185 "[^>]*?>"
19186 "\\(.\\|\n\\)*"
19187 "</math>")
19188 nil t)
19189 (prog1 (match-string 0) (kill-buffer))))))
19190 (cond
19191 (mathml
19192 (setq mathml
19193 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19194 (when mathml-file
19195 (write-region mathml nil mathml-file))
19196 (when (org-called-interactively-p 'any)
19197 (message mathml)))
19198 ((message "LaTeX to MathML conversion failed")
19199 (message shell-command-output)))
19200 (delete-file tmp-in-file)
19201 (when (file-exists-p tmp-out-file)
19202 (delete-file tmp-out-file))
19203 mathml))
19205 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19206 prefix &optional dir)
19207 "Use `org-create-math-formula' but check local cache first."
19208 (let* ((absprefix (expand-file-name prefix dir))
19209 (print-length nil) (print-level nil)
19210 (formula-id (concat
19211 "formula-"
19212 (sha1
19213 (prin1-to-string
19214 (list latex-frag
19215 org-latex-to-mathml-convert-command)))))
19216 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19217 (formula-cache-dir (file-name-directory formula-cache)))
19219 (unless (file-directory-p formula-cache-dir)
19220 (make-directory formula-cache-dir t))
19222 (unless (file-exists-p formula-cache)
19223 (org-create-math-formula latex-frag formula-cache))
19225 (if (file-exists-p formula-cache)
19226 ;; Successful conversion. Return the link to MathML file.
19227 (org-add-props
19228 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19229 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19230 'org-latex-src-embed-type (if latex-frag-type
19231 'paragraph 'character)))
19232 ;; Failed conversion. Return the LaTeX fragment verbatim
19233 latex-frag)))
19235 (defun org-create-formula-image (string tofile options buffer &optional type)
19236 "Create an image from LaTeX source using dvipng or convert.
19237 This function calls either `org-create-formula-image-with-dvipng'
19238 or `org-create-formula-image-with-imagemagick' depending on the
19239 value of `org-latex-create-formula-image-program' or on the value
19240 of the optional TYPE variable.
19242 Note: ultimately these two function should be combined as they
19243 share a good deal of logic."
19244 (org-check-external-command
19245 "latex" "needed to convert LaTeX fragments to images")
19246 (funcall
19247 (cl-case (or type org-latex-create-formula-image-program)
19248 (dvipng
19249 (org-check-external-command
19250 "dvipng" "needed to convert LaTeX fragments to images")
19251 #'org-create-formula-image-with-dvipng)
19252 (imagemagick
19253 (org-check-external-command
19254 "convert" "you need to install imagemagick")
19255 #'org-create-formula-image-with-imagemagick)
19256 (t (error
19257 "Invalid value of `org-latex-create-formula-image-program'")))
19258 string tofile options buffer))
19260 (declare-function org-export-get-backend "ox" (name))
19261 (declare-function org-export--get-global-options "ox" (&optional backend))
19262 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19263 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19264 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19265 (defun org-create-formula--latex-header ()
19266 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19267 (let ((info (org-combine-plists (org-export--get-global-options
19268 (org-export-get-backend 'latex))
19269 (org-export--get-inbuffer-options
19270 (org-export-get-backend 'latex)))))
19271 (org-latex-guess-babel-language
19272 (org-latex-guess-inputenc
19273 (org-splice-latex-header
19274 org-format-latex-header
19275 org-latex-default-packages-alist
19276 org-latex-packages-alist t
19277 (plist-get info :latex-header)))
19278 info)))
19280 (defun org--get-display-dpi ()
19281 "Get the DPI of the display.
19283 Assumes that the display has the same pixel width in the
19284 horizontal and vertical directions."
19285 (if (display-graphic-p)
19286 (round (/ (display-pixel-height)
19287 (/ (display-mm-height) 25.4)))
19288 (error "Attempt to calculate the dpi of a non-graphic display")))
19290 ;; This function borrows from Ganesh Swami's latex2png.el
19291 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19292 "This calls dvipng."
19293 (require 'ox-latex)
19294 (let* ((tmpdir (if (featurep 'xemacs)
19295 (temp-directory)
19296 temporary-file-directory))
19297 (texfilebase (make-temp-name
19298 (expand-file-name "orgtex" tmpdir)))
19299 (texfile (concat texfilebase ".tex"))
19300 (dvifile (concat texfilebase ".dvi"))
19301 (pngfile (concat texfilebase ".png"))
19302 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19303 ;; This assumes that the display has the same pixel width in
19304 ;; the horizontal and vertical directions
19305 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19306 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19307 "Black"))
19308 (bg (or (plist-get options (if buffer :background :html-background))
19309 "Transparent")))
19310 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19311 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19312 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19313 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19314 (let ((latex-header (org-create-formula--latex-header)))
19315 (with-temp-file texfile
19316 (insert latex-header)
19317 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19318 (let ((dir default-directory))
19319 (ignore-errors
19320 (cd tmpdir)
19321 (call-process "latex" nil nil nil texfile))
19322 (cd dir))
19323 (if (not (file-exists-p dvifile))
19324 (progn (message "Failed to create dvi file from %s" texfile) nil)
19325 (ignore-errors
19326 (if (featurep 'xemacs)
19327 (call-process "dvipng" nil nil nil
19328 "-fg" fg "-bg" bg
19329 "-T" "tight"
19330 "-o" pngfile
19331 dvifile)
19332 (call-process "dvipng" nil nil nil
19333 "-fg" fg "-bg" bg
19334 "-D" dpi
19335 ;;"-x" scale "-y" scale
19336 "-T" "tight"
19337 "-o" pngfile
19338 dvifile)))
19339 (if (not (file-exists-p pngfile))
19340 (if org-format-latex-signal-error
19341 (error "Failed to create png file from %s" texfile)
19342 (message "Failed to create png file from %s" texfile)
19343 nil)
19344 ;; Use the requested file name and clean up
19345 (copy-file pngfile tofile 'replace)
19346 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19347 (when (file-exists-p (concat texfilebase e))
19348 (delete-file (concat texfilebase e))))
19349 pngfile))))
19351 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19352 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19353 "This calls convert, which is included into imagemagick."
19354 (require 'ox-latex)
19355 (let* ((tmpdir (if (featurep 'xemacs)
19356 (temp-directory)
19357 temporary-file-directory))
19358 (texfilebase (make-temp-name
19359 (expand-file-name "orgtex" tmpdir)))
19360 (texfile (concat texfilebase ".tex"))
19361 (pdffile (concat texfilebase ".pdf"))
19362 (pngfile (concat texfilebase ".png"))
19363 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19364 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19365 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19366 "black"))
19367 (bg (or (plist-get options (if buffer :background :html-background))
19368 "white")))
19369 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19370 (setq fg (org-latex-color-format fg)))
19371 (if (eq bg 'default) (setq bg (org-latex-color :background))
19372 (setq bg (org-latex-color-format
19373 (if (string= bg "Transparent") "white" bg))))
19374 (let ((latex-header (org-create-formula--latex-header)))
19375 (with-temp-file texfile
19376 (insert latex-header)
19377 (insert "\n\\begin{document}\n"
19378 "\\definecolor{fg}{rgb}{" fg "}\n"
19379 "\\definecolor{bg}{rgb}{" bg "}\n"
19380 "\n\\pagecolor{bg}\n"
19381 "\n{\\color{fg}\n"
19382 string
19383 "\n}\n"
19384 "\n\\end{document}\n")))
19385 (org-latex-compile texfile t)
19386 (if (not (file-exists-p pdffile))
19387 (progn (message "Failed to create pdf file from %s" texfile) nil)
19388 (ignore-errors
19389 (if (featurep 'xemacs)
19390 (call-process "convert" nil nil nil
19391 "-density" "96"
19392 "-trim"
19393 "-antialias"
19394 pdffile
19395 "-quality" "100"
19396 ;; "-sharpen" "0x1.0"
19397 pngfile)
19398 (call-process "convert" nil nil nil
19399 "-density" dpi
19400 "-trim"
19401 "-antialias"
19402 pdffile
19403 "-quality" "100"
19404 ;; "-sharpen" "0x1.0"
19405 pngfile)))
19406 (if (not (file-exists-p pngfile))
19407 (if org-format-latex-signal-error
19408 (error "Failed to create png file from %s" texfile)
19409 (message "Failed to create png file from %s" texfile)
19410 nil)
19411 ;; Use the requested file name and clean up
19412 (copy-file pngfile tofile 'replace)
19413 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19414 (when (file-exists-p (concat texfilebase e))
19415 (delete-file (concat texfilebase e))))
19416 pngfile))))
19418 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19419 "Fill a LaTeX header template TPL.
19420 In the template, the following place holders will be recognized:
19422 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19423 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19424 [PACKAGES] \\usepackage statements for PKG
19425 [NO-PACKAGES] do not include PKG
19426 [EXTRA] the string EXTRA
19427 [NO-EXTRA] do not include EXTRA
19429 For backward compatibility, if both the positive and the negative place
19430 holder is missing, the positive one (without the \"NO-\") will be
19431 assumed to be present at the end of the template.
19432 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19433 EXTRA is a string.
19434 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19435 (let (rpl (end ""))
19436 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19437 (setq rpl (if (or (match-end 1) (not def-pkg))
19438 "" (org-latex-packages-to-string def-pkg snippets-p t))
19439 tpl (replace-match rpl t t tpl))
19440 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19442 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19443 (setq rpl (if (or (match-end 1) (not pkg))
19444 "" (org-latex-packages-to-string pkg snippets-p t))
19445 tpl (replace-match rpl t t tpl))
19446 (when pkg (setq end
19447 (concat end "\n"
19448 (org-latex-packages-to-string pkg snippets-p)))))
19450 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19451 (setq rpl (if (or (match-end 1) (not extra))
19452 "" (concat extra "\n"))
19453 tpl (replace-match rpl t t tpl))
19454 (when (and extra (string-match "\\S-" extra))
19455 (setq end (concat end "\n" extra))))
19457 (if (string-match "\\S-" end)
19458 (concat tpl "\n" end)
19459 tpl)))
19461 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19462 "Turn an alist of packages into a string with the \\usepackage macros."
19463 (setq pkg (mapconcat (lambda(p)
19464 (cond
19465 ((stringp p) p)
19466 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19467 (format "%% Package %s omitted" (cadr p)))
19468 ((equal "" (car p))
19469 (format "\\usepackage{%s}" (cadr p)))
19471 (format "\\usepackage[%s]{%s}"
19472 (car p) (cadr p)))))
19474 "\n"))
19475 (if newline (concat pkg "\n") pkg))
19477 (defun org-dvipng-color (attr)
19478 "Return a RGB color specification for dvipng."
19479 (apply 'format "rgb %s %s %s"
19480 (mapcar 'org-normalize-color
19481 (if (featurep 'xemacs)
19482 (color-rgb-components
19483 (face-property 'default
19484 (cond ((eq attr :foreground) 'foreground)
19485 ((eq attr :background) 'background))))
19486 (color-values (face-attribute 'default attr nil))))))
19488 (defun org-dvipng-color-format (color-name)
19489 "Convert COLOR-NAME to a RGB color value for dvipng."
19490 (apply 'format "rgb %s %s %s"
19491 (mapcar 'org-normalize-color
19492 (color-values color-name))))
19494 (defun org-latex-color (attr)
19495 "Return a RGB color for the LaTeX color package."
19496 (apply 'format "%s,%s,%s"
19497 (mapcar 'org-normalize-color
19498 (if (featurep 'xemacs)
19499 (color-rgb-components
19500 (face-property 'default
19501 (cond ((eq attr :foreground) 'foreground)
19502 ((eq attr :background) 'background))))
19503 (color-values (face-attribute 'default attr nil))))))
19505 (defun org-latex-color-format (color-name)
19506 "Convert COLOR-NAME to a RGB color value."
19507 (apply 'format "%s,%s,%s"
19508 (mapcar 'org-normalize-color
19509 (color-values color-name))))
19511 (defun org-normalize-color (value)
19512 "Return string to be used as color value for an RGB component."
19513 (format "%g" (/ value 65535.0)))
19517 ;; Image display
19519 (defvar-local org-inline-image-overlays nil)
19521 (defun org-toggle-inline-images (&optional include-linked)
19522 "Toggle the display of inline images.
19523 INCLUDE-LINKED is passed to `org-display-inline-images'."
19524 (interactive "P")
19525 (if org-inline-image-overlays
19526 (progn
19527 (org-remove-inline-images)
19528 (when (org-called-interactively-p 'interactive)
19529 (message "Inline image display turned off")))
19530 (org-display-inline-images include-linked)
19531 (when (org-called-interactively-p 'interactive)
19532 (message (if org-inline-image-overlays
19533 (format "%d images displayed inline"
19534 (length org-inline-image-overlays))
19535 "No images to display inline")))))
19537 (defun org-redisplay-inline-images ()
19538 "Refresh the display of inline images."
19539 (interactive)
19540 (if (not org-inline-image-overlays)
19541 (org-toggle-inline-images)
19542 (org-toggle-inline-images)
19543 (org-toggle-inline-images)))
19545 (defun org-display-inline-images (&optional include-linked refresh beg end)
19546 "Display inline images.
19548 An inline image is a link which follows either of these
19549 conventions:
19551 1. Its path is a file with an extension matching return value
19552 from `image-file-name-regexp' and it has no contents.
19554 2. Its description consists in a single link of the previous
19555 type.
19557 When optional argument INCLUDE-LINKED is non-nil, also links with
19558 a text description part will be inlined. This can be nice for
19559 a quick look at those images, but it does not reflect what
19560 exported files will look like.
19562 When optional argument REFRESH is non-nil, refresh existing
19563 images between BEG and END. This will create new image displays
19564 only if necessary. BEG and END default to the buffer
19565 boundaries."
19566 (interactive "P")
19567 (when (display-graphic-p)
19568 (unless refresh
19569 (org-remove-inline-images)
19570 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19571 (org-with-wide-buffer
19572 (goto-char (or beg (point-min)))
19573 (let ((case-fold-search t)
19574 (file-extension-re (image-file-name-regexp)))
19575 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19576 (let ((link (save-match-data (org-element-context))))
19577 ;; Check if we're at an inline image.
19578 (when (and (equal (org-element-property :type link) "file")
19579 (or include-linked
19580 (not (org-element-property :contents-begin link)))
19581 (let ((parent (org-element-property :parent link)))
19582 (or (not (eq (org-element-type parent) 'link))
19583 (not (cdr (org-element-contents parent)))))
19584 (org-string-match-p file-extension-re
19585 (org-element-property :path link)))
19586 (let ((file (expand-file-name
19587 (org-link-unescape
19588 (org-element-property :path link)))))
19589 (when (file-exists-p file)
19590 (let ((width
19591 ;; Apply `org-image-actual-width' specifications.
19592 (cond
19593 ((not (image-type-available-p 'imagemagick)) nil)
19594 ((eq org-image-actual-width t) nil)
19595 ((listp org-image-actual-width)
19597 ;; First try to find a width among
19598 ;; attributes associated to the paragraph
19599 ;; containing link.
19600 (let ((paragraph
19601 (let ((e link))
19602 (while (and (setq e (org-element-property
19603 :parent e))
19604 (not (eq (org-element-type e)
19605 'paragraph))))
19606 e)))
19607 (when paragraph
19608 (save-excursion
19609 (goto-char (org-element-property :begin paragraph))
19610 (when
19611 (re-search-forward
19612 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19613 (org-element-property
19614 :post-affiliated paragraph)
19616 (string-to-number (match-string 1))))))
19617 ;; Otherwise, fall-back to provided number.
19618 (car org-image-actual-width)))
19619 ((numberp org-image-actual-width)
19620 org-image-actual-width)))
19621 (old (get-char-property-and-overlay
19622 (org-element-property :begin link)
19623 'org-image-overlay)))
19624 (if (and (car-safe old) refresh)
19625 (image-refresh (overlay-get (cdr old) 'display))
19626 (let ((image (create-image file
19627 (and width 'imagemagick)
19629 :width width)))
19630 (when image
19631 (let* ((link
19632 ;; If inline image is the description
19633 ;; of another link, be sure to
19634 ;; consider the latter as the one to
19635 ;; apply the overlay on.
19636 (let ((parent
19637 (org-element-property :parent link)))
19638 (if (eq (org-element-type parent) 'link)
19639 parent
19640 link)))
19641 (ov (make-overlay
19642 (org-element-property :begin link)
19643 (progn
19644 (goto-char
19645 (org-element-property :end link))
19646 (skip-chars-backward " \t")
19647 (point)))))
19648 (overlay-put ov 'display image)
19649 (overlay-put ov 'face 'default)
19650 (overlay-put ov 'org-image-overlay t)
19651 (overlay-put
19652 ov 'modification-hooks
19653 (list 'org-display-inline-remove-overlay))
19654 (push ov org-inline-image-overlays)))))))))))))))
19656 (define-obsolete-function-alias
19657 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19659 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19660 "Remove inline-display overlay if a corresponding region is modified."
19661 (let ((inhibit-modification-hooks t))
19662 (when (and ov after)
19663 (delete ov org-inline-image-overlays)
19664 (delete-overlay ov))))
19666 (defun org-remove-inline-images ()
19667 "Remove inline display of images."
19668 (interactive)
19669 (mapc #'delete-overlay org-inline-image-overlays)
19670 (setq org-inline-image-overlays nil))
19672 ;;;; Key bindings
19674 ;; Outline functions from `outline-mode-prefix-map'
19675 ;; that can be remapped in Org:
19676 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19677 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19678 (define-key org-mode-map [remap outline-forward-same-level]
19679 'org-forward-heading-same-level)
19680 (define-key org-mode-map [remap outline-backward-same-level]
19681 'org-backward-heading-same-level)
19682 (define-key org-mode-map [remap outline-show-branches]
19683 'org-kill-note-or-show-branches)
19684 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19685 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19686 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19687 (define-key org-mode-map [remap outline-next-visible-heading]
19688 'org-next-visible-heading)
19689 (define-key org-mode-map [remap outline-previous-visible-heading]
19690 'org-previous-visible-heading)
19691 (define-key org-mode-map [remap show-children] 'org-show-children)
19693 ;; Outline functions from `outline-mode-prefix-map' that can not
19694 ;; be remapped in Org:
19696 ;; - the column "key binding" shows whether the Outline function is still
19697 ;; available in Org mode on the same key that it has been bound to in
19698 ;; Outline mode:
19699 ;; - "overridden": key used for a different functionality in Org mode
19700 ;; - else: key still bound to the same Outline function in Org mode
19702 ;; | Outline function | key binding | Org replacement |
19703 ;; |------------------------------------+-------------+--------------------------|
19704 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19705 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19706 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19707 ;; | `show-entry' | overridden | no replacement |
19708 ;; | `show-branches' | `C-c C-k' | still same function |
19709 ;; | `show-subtree' | overridden | visibility cycling |
19710 ;; | `show-all' | overridden | no replacement |
19711 ;; | `hide-subtree' | overridden | visibility cycling |
19712 ;; | `hide-body' | overridden | no replacement |
19713 ;; | `hide-entry' | overridden | visibility cycling |
19714 ;; | `hide-leaves' | overridden | no replacement |
19715 ;; | `hide-sublevels' | overridden | no replacement |
19716 ;; | `hide-other' | overridden | no replacement |
19718 ;; Make `C-c C-x' a prefix key
19719 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19721 ;; TAB key with modifiers
19722 (org-defkey org-mode-map "\C-i" 'org-cycle)
19723 (org-defkey org-mode-map [(tab)] 'org-cycle)
19724 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19725 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19726 ;; The following line is necessary under Suse GNU/Linux
19727 (unless (featurep 'xemacs)
19728 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19729 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19730 (define-key org-mode-map [backtab] 'org-shifttab)
19732 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19733 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19734 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19736 ;; Cursor keys with modifiers
19737 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19738 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19739 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19740 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19742 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19743 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19744 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19745 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19746 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19747 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19749 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19750 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19751 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19752 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19754 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19755 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19756 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19757 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19759 ;; Babel keys
19760 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19761 (dolist (pair org-babel-key-bindings)
19762 (define-key org-babel-map (car pair) (cdr pair)))
19764 ;;; Extra keys for tty access.
19765 ;; We only set them when really needed because otherwise the
19766 ;; menus don't show the simple keys
19768 (when (or org-use-extra-keys
19769 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19770 (not window-system))
19771 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19772 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19773 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19774 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19775 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19776 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19777 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19778 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19779 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19780 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19781 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19782 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19783 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19784 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19785 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19786 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19787 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19788 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19789 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19790 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19791 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19792 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19793 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19794 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19795 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19796 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19797 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19798 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19800 ;; All the other keys
19802 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19803 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19804 (if (boundp 'narrow-map)
19805 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19806 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19807 (if (boundp 'narrow-map)
19808 (org-defkey narrow-map "b" 'org-narrow-to-block)
19809 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19810 (if (boundp 'narrow-map)
19811 (org-defkey narrow-map "e" 'org-narrow-to-element)
19812 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19813 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19814 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19815 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19816 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19817 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19818 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19819 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19820 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19821 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19822 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19823 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19824 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19825 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19826 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19827 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19828 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19829 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19830 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19831 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19832 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19833 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19834 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19835 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19836 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19837 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19838 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19839 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19840 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19841 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19842 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19843 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19844 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19845 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19846 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19847 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19848 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19849 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19850 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19851 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19852 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19853 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19854 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19855 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19856 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19857 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19858 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19859 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19860 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19861 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19862 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19863 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19864 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19865 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19866 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19867 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19868 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19869 (org-defkey org-mode-map "\C-c^" 'org-sort)
19870 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19871 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19872 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19873 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19874 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19875 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19876 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19877 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19878 (org-defkey org-mode-map "\C-m" 'org-return)
19879 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19880 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19881 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19882 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19883 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19884 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19885 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19886 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19887 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19888 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19889 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19890 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19891 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19892 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19893 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19894 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19895 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19896 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19897 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19898 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19899 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19900 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19901 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19902 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19903 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19905 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19906 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19907 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19909 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19910 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19911 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19912 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19913 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19914 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19915 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19916 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19917 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19918 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19919 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19920 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19921 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19922 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19923 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19924 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19925 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19926 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19927 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19928 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19929 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19930 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19932 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19933 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19934 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19935 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19936 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19938 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19940 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19942 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19943 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19945 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19948 (when (featurep 'xemacs)
19949 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19952 (defconst org-speed-commands-default
19954 ("Outline Navigation")
19955 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19956 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19957 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19958 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19959 ("F" . org-next-block)
19960 ("B" . org-previous-block)
19961 ("u" . (org-speed-move-safe 'outline-up-heading))
19962 ("j" . org-goto)
19963 ("g" . (org-refile t))
19964 ("Outline Visibility")
19965 ("c" . org-cycle)
19966 ("C" . org-shifttab)
19967 (" " . org-display-outline-path)
19968 ("s" . org-narrow-to-subtree)
19969 ("=" . org-columns)
19970 ("Outline Structure Editing")
19971 ("U" . org-metaup)
19972 ("D" . org-metadown)
19973 ("r" . org-metaright)
19974 ("l" . org-metaleft)
19975 ("R" . org-shiftmetaright)
19976 ("L" . org-shiftmetaleft)
19977 ("i" . (progn (forward-char 1) (call-interactively
19978 'org-insert-heading-respect-content)))
19979 ("^" . org-sort)
19980 ("w" . org-refile)
19981 ("a" . org-archive-subtree-default-with-confirmation)
19982 ("@" . org-mark-subtree)
19983 ("#" . org-toggle-comment)
19984 ("Clock Commands")
19985 ("I" . org-clock-in)
19986 ("O" . org-clock-out)
19987 ("Meta Data Editing")
19988 ("t" . org-todo)
19989 ("," . (org-priority))
19990 ("0" . (org-priority ?\ ))
19991 ("1" . (org-priority ?A))
19992 ("2" . (org-priority ?B))
19993 ("3" . (org-priority ?C))
19994 (":" . org-set-tags-command)
19995 ("e" . org-set-effort)
19996 ("E" . org-inc-effort)
19997 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19998 (org-entry-put (point) "APPT_WARNTIME" m)))
19999 ("Agenda Views etc")
20000 ("v" . org-agenda)
20001 ("/" . org-sparse-tree)
20002 ("Misc")
20003 ("o" . org-open-at-point)
20004 ("?" . org-speed-command-help)
20005 ("<" . (org-agenda-set-restriction-lock 'subtree))
20006 (">" . (org-agenda-remove-restriction-lock))
20008 "The default speed commands.")
20010 (defun org-print-speed-command (e)
20011 (if (> (length (car e)) 1)
20012 (progn
20013 (princ "\n")
20014 (princ (car e))
20015 (princ "\n")
20016 (princ (make-string (length (car e)) ?-))
20017 (princ "\n"))
20018 (princ (car e))
20019 (princ " ")
20020 (if (symbolp (cdr e))
20021 (princ (symbol-name (cdr e)))
20022 (prin1 (cdr e)))
20023 (princ "\n")))
20025 (defun org-speed-command-help ()
20026 "Show the available speed commands."
20027 (interactive)
20028 (if (not org-use-speed-commands)
20029 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20030 (with-output-to-temp-buffer "*Help*"
20031 (princ "User-defined Speed commands\n===========================\n")
20032 (mapc #'org-print-speed-command org-speed-commands-user)
20033 (princ "\n")
20034 (princ "Built-in Speed commands\n=======================\n")
20035 (mapc #'org-print-speed-command org-speed-commands-default))
20036 (with-current-buffer "*Help*"
20037 (setq truncate-lines t))))
20039 (defun org-speed-move-safe (cmd)
20040 "Execute CMD, but make sure that the cursor always ends up in a headline.
20041 If not, return to the original position and throw an error."
20042 (interactive)
20043 (let ((pos (point)))
20044 (call-interactively cmd)
20045 (unless (and (bolp) (org-at-heading-p))
20046 (goto-char pos)
20047 (error "Boundary reached while executing %s" cmd))))
20049 (defvar org-self-insert-command-undo-counter 0)
20051 (defvar org-table-auto-blank-field) ; defined in org-table.el
20052 (defvar org-speed-command nil)
20054 (define-obsolete-function-alias
20055 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20057 (defun org-speed-command-activate (keys)
20058 "Hook for activating single-letter speed commands.
20059 `org-speed-commands-default' specifies a minimal command set.
20060 Use `org-speed-commands-user' for further customization."
20061 (when (or (and (bolp) (looking-at org-outline-regexp))
20062 (and (functionp org-use-speed-commands)
20063 (funcall org-use-speed-commands)))
20064 (cdr (assoc keys (append org-speed-commands-user
20065 org-speed-commands-default)))))
20067 (define-obsolete-function-alias
20068 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20070 (defun org-babel-speed-command-activate (keys)
20071 "Hook for activating single-letter code block commands."
20072 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20073 (cdr (assoc keys org-babel-key-bindings))))
20075 (defcustom org-speed-command-hook
20076 '(org-speed-command-default-hook org-babel-speed-command-hook)
20077 "Hook for activating speed commands at strategic locations.
20078 Hook functions are called in sequence until a valid handler is
20079 found.
20081 Each hook takes a single argument, a user-pressed command key
20082 which is also a `self-insert-command' from the global map.
20084 Within the hook, examine the cursor position and the command key
20085 and return nil or a valid handler as appropriate. Handler could
20086 be one of an interactive command, a function, or a form.
20088 Set `org-use-speed-commands' to non-nil value to enable this
20089 hook. The default setting is `org-speed-command-activate'."
20090 :group 'org-structure
20091 :version "24.1"
20092 :type 'hook)
20094 (defun org-self-insert-command (N)
20095 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20096 If the cursor is in a table looking at whitespace, the whitespace is
20097 overwritten, and the table is not marked as requiring realignment."
20098 (interactive "p")
20099 (org-check-before-invisible-edit 'insert)
20100 (cond
20101 ((and org-use-speed-commands
20102 (let ((kv (this-command-keys-vector)))
20103 (setq org-speed-command
20104 (run-hook-with-args-until-success
20105 'org-speed-command-hook
20106 (make-string 1 (aref kv (1- (length kv))))))))
20107 (cond
20108 ((commandp org-speed-command)
20109 (setq this-command org-speed-command)
20110 (call-interactively org-speed-command))
20111 ((functionp org-speed-command)
20112 (funcall org-speed-command))
20113 ((and org-speed-command (listp org-speed-command))
20114 (eval org-speed-command))
20115 (t (let (org-use-speed-commands)
20116 (call-interactively 'org-self-insert-command)))))
20117 ((and
20118 (org-at-table-p)
20119 (progn
20120 ;; Check if we blank the field, and if that triggers align.
20121 (and (featurep 'org-table) org-table-auto-blank-field
20122 (memq last-command
20123 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20124 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20125 ;; Got extra space, this field does not determine
20126 ;; column width.
20127 (let (org-table-may-need-update) (org-table-blank-field))
20128 ;; No extra space, this field may determine column
20129 ;; width.
20130 (org-table-blank-field)))
20132 (eq N 1)
20133 (looking-at "[^|\n]* \\( \\)|"))
20134 ;; There is room for insertion without re-aligning the table.
20135 (delete-region (match-beginning 1) (match-end 1))
20136 (self-insert-command N))
20138 (setq org-table-may-need-update t)
20139 (self-insert-command N)
20140 (org-fix-tags-on-the-fly)
20141 (when org-self-insert-cluster-for-undo
20142 (if (not (eq last-command 'org-self-insert-command))
20143 (setq org-self-insert-command-undo-counter 1)
20144 (if (>= org-self-insert-command-undo-counter 20)
20145 (setq org-self-insert-command-undo-counter 1)
20146 (and (> org-self-insert-command-undo-counter 0)
20147 buffer-undo-list (listp buffer-undo-list)
20148 (not (cadr buffer-undo-list)) ; remove nil entry
20149 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20150 (setq org-self-insert-command-undo-counter
20151 (1+ org-self-insert-command-undo-counter))))))))
20153 (defun org-check-before-invisible-edit (kind)
20154 "Check is editing if kind KIND would be dangerous with invisible text around.
20155 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20156 ;; First, try to get out of here as quickly as possible, to reduce overhead
20157 (when (and org-catch-invisible-edits
20158 (or (not (boundp 'visible-mode)) (not visible-mode))
20159 (or (get-char-property (point) 'invisible)
20160 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20161 ;; OK, we need to take a closer look
20162 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20163 (invisible-before-point (unless (bobp) (get-char-property
20164 (1- (point)) 'invisible)))
20165 (border-and-ok-direction
20167 ;; Check if we are acting predictably before invisible text
20168 (and invisible-at-point (not invisible-before-point)
20169 (memq kind '(insert delete-backward)))
20170 ;; Check if we are acting predictably after invisible text
20171 ;; This works not well, and I have turned it off. It seems
20172 ;; better to always show and stop after invisible text.
20173 ;; (and (not invisible-at-point) invisible-before-point
20174 ;; (memq kind '(insert delete)))
20176 (when (or (memq invisible-at-point '(outline org-hide-block t))
20177 (memq invisible-before-point '(outline org-hide-block t)))
20178 (when (eq org-catch-invisible-edits 'error)
20179 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20180 (if (and org-custom-properties-overlays
20181 (y-or-n-p "Display invisible properties in this buffer? "))
20182 (org-toggle-custom-properties-visibility)
20183 ;; Make the area visible
20184 (save-excursion
20185 (when invisible-before-point
20186 (goto-char (previous-single-char-property-change
20187 (point) 'invisible)))
20188 (outline-show-subtree))
20189 (cond
20190 ((eq org-catch-invisible-edits 'show)
20191 ;; That's it, we do the edit after showing
20192 (message
20193 "Unfolding invisible region around point before editing")
20194 (sit-for 1))
20195 ((and (eq org-catch-invisible-edits 'smart)
20196 border-and-ok-direction)
20197 (message "Unfolding invisible region around point before editing"))
20199 ;; Don't do the edit, make the user repeat it in full visibility
20200 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20202 (defun org-fix-tags-on-the-fly ()
20203 (when (and (equal (char-after (point-at-bol)) ?*)
20204 (org-at-heading-p))
20205 (org-align-tags-here org-tags-column)))
20207 (defun org-delete-backward-char (N)
20208 "Like `delete-backward-char', insert whitespace at field end in tables.
20209 When deleting backwards, in tables this function will insert whitespace in
20210 front of the next \"|\" separator, to keep the table aligned. The table will
20211 still be marked for re-alignment if the field did fill the entire column,
20212 because, in this case the deletion might narrow the column."
20213 (interactive "p")
20214 (save-match-data
20215 (org-check-before-invisible-edit 'delete-backward)
20216 (if (and (org-at-table-p)
20217 (eq N 1)
20218 (string-match "|" (buffer-substring (point-at-bol) (point)))
20219 (looking-at ".*?|"))
20220 (let ((pos (point))
20221 (noalign (looking-at "[^|\n\r]* |"))
20222 (c org-table-may-need-update))
20223 (backward-delete-char N)
20224 (unless overwrite-mode
20225 (skip-chars-forward "^|")
20226 (insert " ")
20227 (goto-char (1- pos)))
20228 ;; noalign: if there were two spaces at the end, this field
20229 ;; does not determine the width of the column.
20230 (when noalign (setq org-table-may-need-update c)))
20231 (backward-delete-char N)
20232 (org-fix-tags-on-the-fly))))
20234 (defun org-delete-char (N)
20235 "Like `delete-char', but insert whitespace at field end in tables.
20236 When deleting characters, in tables this function will insert whitespace in
20237 front of the next \"|\" separator, to keep the table aligned. The table will
20238 still be marked for re-alignment if the field did fill the entire column,
20239 because, in this case the deletion might narrow the column."
20240 (interactive "p")
20241 (save-match-data
20242 (org-check-before-invisible-edit 'delete)
20243 (if (and (org-at-table-p)
20244 (not (bolp))
20245 (not (= (char-after) ?|))
20246 (eq N 1))
20247 (if (looking-at ".*?|")
20248 (let ((pos (point))
20249 (noalign (looking-at "[^|\n\r]* |"))
20250 (c org-table-may-need-update))
20251 (replace-match
20252 (concat (substring (match-string 0) 1 -1) " |") nil t)
20253 (goto-char pos)
20254 ;; noalign: if there were two spaces at the end, this field
20255 ;; does not determine the width of the column.
20256 (when noalign (setq org-table-may-need-update c)))
20257 (delete-char N))
20258 (delete-char N)
20259 (org-fix-tags-on-the-fly))))
20261 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20262 (put 'org-self-insert-command 'delete-selection
20263 (lambda ()
20264 (not (run-hook-with-args-until-success
20265 'self-insert-uses-region-functions))))
20266 (put 'orgtbl-self-insert-command 'delete-selection
20267 (lambda ()
20268 (not (run-hook-with-args-until-success
20269 'self-insert-uses-region-functions))))
20270 (put 'org-delete-char 'delete-selection 'supersede)
20271 (put 'org-delete-backward-char 'delete-selection 'supersede)
20272 (put 'org-yank 'delete-selection 'yank)
20274 ;; Make `flyspell-mode' delay after some commands
20275 (put 'org-self-insert-command 'flyspell-delayed t)
20276 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20277 (put 'org-delete-char 'flyspell-delayed t)
20278 (put 'org-delete-backward-char 'flyspell-delayed t)
20280 ;; Make pabbrev-mode expand after org-mode commands
20281 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20282 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20284 (defun org-remap (map &rest commands)
20285 "In MAP, remap the functions given in COMMANDS.
20286 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20287 (let (new old)
20288 (while commands
20289 (setq old (pop commands) new (pop commands))
20290 (if (fboundp 'command-remapping)
20291 (org-defkey map (vector 'remap old) new)
20292 (substitute-key-definition old new map global-map)))))
20294 (defun org-transpose-words ()
20295 "Transpose words for Org.
20296 This uses the `org-mode-transpose-word-syntax-table' syntax
20297 table, which interprets characters in `org-emphasis-alist' as
20298 word constituents."
20299 (interactive)
20300 (with-syntax-table org-mode-transpose-word-syntax-table
20301 (call-interactively 'transpose-words)))
20302 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20304 (when (eq org-enable-table-editor 'optimized)
20305 ;; If the user wants maximum table support, we need to hijack
20306 ;; some standard editing functions
20307 (org-remap org-mode-map
20308 'self-insert-command 'org-self-insert-command
20309 'delete-char 'org-delete-char
20310 'delete-backward-char 'org-delete-backward-char)
20311 (org-defkey org-mode-map "|" 'org-force-self-insert))
20313 (defvar org-ctrl-c-ctrl-c-hook nil
20314 "Hook for functions attaching themselves to `C-c C-c'.
20316 This can be used to add additional functionality to the C-c C-c
20317 key which executes context-dependent commands. This hook is run
20318 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20319 run after the last test.
20321 Each function will be called with no arguments. The function
20322 must check if the context is appropriate for it to act. If yes,
20323 it should do its thing and then return a non-nil value. If the
20324 context is wrong, just do nothing and return nil.")
20326 (defvar org-ctrl-c-ctrl-c-final-hook nil
20327 "Hook for functions attaching themselves to `C-c C-c'.
20329 This can be used to add additional functionality to the C-c C-c
20330 key which executes context-dependent commands. This hook is run
20331 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20332 before the first test.
20334 Each function will be called with no arguments. The function
20335 must check if the context is appropriate for it to act. If yes,
20336 it should do its thing and then return a non-nil value. If the
20337 context is wrong, just do nothing and return nil.")
20339 (defvar org-tab-first-hook nil
20340 "Hook for functions to attach themselves to TAB.
20341 See `org-ctrl-c-ctrl-c-hook' for more information.
20342 This hook runs as the first action when TAB is pressed, even before
20343 `org-cycle' messes around with the `outline-regexp' to cater for
20344 inline tasks and plain list item folding.
20345 If any function in this hook returns t, any other actions that
20346 would have been caused by TAB (such as table field motion or visibility
20347 cycling) will not occur.")
20349 (defvar org-tab-after-check-for-table-hook nil
20350 "Hook for functions to attach themselves to TAB.
20351 See `org-ctrl-c-ctrl-c-hook' for more information.
20352 This hook runs after it has been established that the cursor is not in a
20353 table, but before checking if the cursor is in a headline or if global cycling
20354 should be done.
20355 If any function in this hook returns t, not other actions like visibility
20356 cycling will be done.")
20358 (defvar org-tab-after-check-for-cycling-hook nil
20359 "Hook for functions to attach themselves to TAB.
20360 See `org-ctrl-c-ctrl-c-hook' for more information.
20361 This hook runs after it has been established that not table field motion and
20362 not visibility should be done because of current context. This is probably
20363 the place where a package like yasnippets can hook in.")
20365 (defvar org-tab-before-tab-emulation-hook nil
20366 "Hook for functions to attach themselves to TAB.
20367 See `org-ctrl-c-ctrl-c-hook' for more information.
20368 This hook runs after every other options for TAB have been exhausted, but
20369 before indentation and \t insertion takes place.")
20371 (defvar org-metaleft-hook nil
20372 "Hook for functions attaching themselves to `M-left'.
20373 See `org-ctrl-c-ctrl-c-hook' for more information.")
20374 (defvar org-metaright-hook nil
20375 "Hook for functions attaching themselves to `M-right'.
20376 See `org-ctrl-c-ctrl-c-hook' for more information.")
20377 (defvar org-metaup-hook nil
20378 "Hook for functions attaching themselves to `M-up'.
20379 See `org-ctrl-c-ctrl-c-hook' for more information.")
20380 (defvar org-metadown-hook nil
20381 "Hook for functions attaching themselves to `M-down'.
20382 See `org-ctrl-c-ctrl-c-hook' for more information.")
20383 (defvar org-shiftmetaleft-hook nil
20384 "Hook for functions attaching themselves to `M-S-left'.
20385 See `org-ctrl-c-ctrl-c-hook' for more information.")
20386 (defvar org-shiftmetaright-hook nil
20387 "Hook for functions attaching themselves to `M-S-right'.
20388 See `org-ctrl-c-ctrl-c-hook' for more information.")
20389 (defvar org-shiftmetaup-hook nil
20390 "Hook for functions attaching themselves to `M-S-up'.
20391 See `org-ctrl-c-ctrl-c-hook' for more information.")
20392 (defvar org-shiftmetadown-hook nil
20393 "Hook for functions attaching themselves to `M-S-down'.
20394 See `org-ctrl-c-ctrl-c-hook' for more information.")
20395 (defvar org-metareturn-hook nil
20396 "Hook for functions attaching themselves to `M-RET'.
20397 See `org-ctrl-c-ctrl-c-hook' for more information.")
20398 (defvar org-shiftup-hook nil
20399 "Hook for functions attaching themselves to `S-up'.
20400 See `org-ctrl-c-ctrl-c-hook' for more information.")
20401 (defvar org-shiftup-final-hook nil
20402 "Hook for functions attaching themselves to `S-up'.
20403 This one runs after all other options except shift-select have been excluded.
20404 See `org-ctrl-c-ctrl-c-hook' for more information.")
20405 (defvar org-shiftdown-hook nil
20406 "Hook for functions attaching themselves to `S-down'.
20407 See `org-ctrl-c-ctrl-c-hook' for more information.")
20408 (defvar org-shiftdown-final-hook nil
20409 "Hook for functions attaching themselves to `S-down'.
20410 This one runs after all other options except shift-select have been excluded.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.")
20412 (defvar org-shiftleft-hook nil
20413 "Hook for functions attaching themselves to `S-left'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-shiftleft-final-hook nil
20416 "Hook for functions attaching themselves to `S-left'.
20417 This one runs after all other options except shift-select have been excluded.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.")
20419 (defvar org-shiftright-hook nil
20420 "Hook for functions attaching themselves to `S-right'.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.")
20422 (defvar org-shiftright-final-hook nil
20423 "Hook for functions attaching themselves to `S-right'.
20424 This one runs after all other options except shift-select have been excluded.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defun org-modifier-cursor-error ()
20428 "Throw an error, a modified cursor command was applied in wrong context."
20429 (user-error "This command is active in special context like tables, headlines or items"))
20431 (defun org-shiftselect-error ()
20432 "Throw an error because Shift-Cursor command was applied in wrong context."
20433 (if (and (boundp 'shift-select-mode) shift-select-mode)
20434 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20435 (user-error "This command works only in special context like headlines or timestamps")))
20437 (defun org-call-for-shift-select (cmd)
20438 (let ((this-command-keys-shift-translated t))
20439 (call-interactively cmd)))
20441 (defun org-shifttab (&optional arg)
20442 "Global visibility cycling or move to previous table field.
20443 Call `org-table-previous-field' within a table.
20444 When ARG is nil, cycle globally through visibility states.
20445 When ARG is a numeric prefix, show contents of this level."
20446 (interactive "P")
20447 (cond
20448 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20449 ((integerp arg)
20450 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20451 (message "Content view to level: %d" arg)
20452 (org-content (prefix-numeric-value arg2))
20453 (org-cycle-show-empty-lines t)
20454 (setq org-cycle-global-status 'overview)))
20455 (t (call-interactively 'org-global-cycle))))
20457 (defun org-shiftmetaleft ()
20458 "Promote subtree or delete table column.
20459 Calls `org-promote-subtree', `org-outdent-item-tree', or
20460 `org-table-delete-column', depending on context. See the
20461 individual commands for more information."
20462 (interactive)
20463 (cond
20464 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20465 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20466 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20467 ((if (not (org-region-active-p)) (org-at-item-p)
20468 (save-excursion (goto-char (region-beginning))
20469 (org-at-item-p)))
20470 (call-interactively 'org-outdent-item-tree))
20471 (t (org-modifier-cursor-error))))
20473 (defun org-shiftmetaright ()
20474 "Demote subtree or insert table column.
20475 Calls `org-demote-subtree', `org-indent-item-tree', or
20476 `org-table-insert-column', depending on context. See the
20477 individual commands for more information."
20478 (interactive)
20479 (cond
20480 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20481 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20482 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20483 ((if (not (org-region-active-p)) (org-at-item-p)
20484 (save-excursion (goto-char (region-beginning))
20485 (org-at-item-p)))
20486 (call-interactively 'org-indent-item-tree))
20487 (t (org-modifier-cursor-error))))
20489 (defun org-shiftmetaup (&optional _arg)
20490 "Drag the line at point up.
20491 In a table, kill the current row.
20492 On a clock timestamp, update the value of the timestamp like `S-<up>'
20493 but also adjust the previous clocked item in the clock history.
20494 Everywhere else, drag the line at point up."
20495 (interactive "P")
20496 (cond
20497 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20498 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20499 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20500 (call-interactively 'org-timestamp-up)))
20501 (t (call-interactively 'org-drag-line-backward))))
20503 (defun org-shiftmetadown (&optional _arg)
20504 "Drag the line at point down.
20505 In a table, insert an empty row at the current line.
20506 On a clock timestamp, update the value of the timestamp like `S-<down>'
20507 but also adjust the previous clocked item in the clock history.
20508 Everywhere else, drag the line at point down."
20509 (interactive "P")
20510 (cond
20511 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20512 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20513 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20514 (call-interactively 'org-timestamp-down)))
20515 (t (call-interactively 'org-drag-line-forward))))
20517 (defsubst org-hidden-tree-error ()
20518 (user-error
20519 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20521 (defun org-metaleft (&optional _arg)
20522 "Promote heading, list item at point or move table column left.
20524 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20525 depending on context. With no specific context, calls the Emacs
20526 default `backward-word'. See the individual commands for more
20527 information.
20529 This function runs the hook `org-metaleft-hook' as a first step,
20530 and returns at first non-nil value."
20531 (interactive "P")
20532 (cond
20533 ((run-hook-with-args-until-success 'org-metaleft-hook))
20534 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20535 ((org-with-limited-levels
20536 (or (org-at-heading-p)
20537 (and (org-region-active-p)
20538 (save-excursion
20539 (goto-char (region-beginning))
20540 (org-at-heading-p)))))
20541 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20542 (call-interactively 'org-do-promote))
20543 ;; At an inline task.
20544 ((org-at-heading-p)
20545 (call-interactively 'org-inlinetask-promote))
20546 ((or (org-at-item-p)
20547 (and (org-region-active-p)
20548 (save-excursion
20549 (goto-char (region-beginning))
20550 (org-at-item-p))))
20551 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20552 (call-interactively 'org-outdent-item))
20553 (t (call-interactively 'backward-word))))
20555 (defun org-metaright (&optional _arg)
20556 "Demote heading, list item at point or move table column right.
20558 In front of a drawer or a block keyword, indent it correctly.
20560 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20561 `org-indnet-drawer' or `org-indent-block' depending on context.
20562 With no specific context, calls the Emacs default `forward-word'.
20563 See the individual commands for more information.
20565 This function runs the hook `org-metaright-hook' as a first step,
20566 and returns at first non-nil value."
20567 (interactive "P")
20568 (cond
20569 ((run-hook-with-args-until-success 'org-metaright-hook))
20570 ((org-at-table-p) (call-interactively 'org-table-move-column))
20571 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20572 ((org-at-block-p) (call-interactively 'org-indent-block))
20573 ((org-with-limited-levels
20574 (or (org-at-heading-p)
20575 (and (org-region-active-p)
20576 (save-excursion
20577 (goto-char (region-beginning))
20578 (org-at-heading-p)))))
20579 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20580 (call-interactively 'org-do-demote))
20581 ;; At an inline task.
20582 ((org-at-heading-p)
20583 (call-interactively 'org-inlinetask-demote))
20584 ((or (org-at-item-p)
20585 (and (org-region-active-p)
20586 (save-excursion
20587 (goto-char (region-beginning))
20588 (org-at-item-p))))
20589 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20590 (call-interactively 'org-indent-item))
20591 (t (call-interactively 'forward-word))))
20593 (defun org-check-for-hidden (what)
20594 "Check if there are hidden headlines/items in the current visual line.
20595 WHAT can be either `headlines' or `items'. If the current line is
20596 an outline or item heading and it has a folded subtree below it,
20597 this function returns t, nil otherwise."
20598 (let ((re (cond
20599 ((eq what 'headlines) org-outline-regexp-bol)
20600 ((eq what 'items) (org-item-beginning-re))
20601 (t (error "This should not happen"))))
20602 beg end)
20603 (save-excursion
20604 (catch 'exit
20605 (unless (org-region-active-p)
20606 (setq beg (point-at-bol))
20607 (beginning-of-line 2)
20608 (while (and (not (eobp)) ;; this is like `next-line'
20609 (get-char-property (1- (point)) 'invisible))
20610 (beginning-of-line 2))
20611 (setq end (point))
20612 (goto-char beg)
20613 (goto-char (point-at-eol))
20614 (setq end (max end (point)))
20615 (while (re-search-forward re end t)
20616 (when (get-char-property (match-beginning 0) 'invisible)
20617 (throw 'exit t))))
20618 nil))))
20620 (defun org-metaup (&optional _arg)
20621 "Move subtree up or move table row up.
20622 Calls `org-move-subtree-up' or `org-table-move-row' or
20623 `org-move-item-up', depending on context. See the individual commands
20624 for more information."
20625 (interactive "P")
20626 (cond
20627 ((run-hook-with-args-until-success 'org-metaup-hook))
20628 ((org-region-active-p)
20629 (let* ((a (min (region-beginning) (region-end)))
20630 (b (1- (max (region-beginning) (region-end))))
20631 (c (save-excursion (goto-char a)
20632 (move-beginning-of-line 0)))
20633 (d (save-excursion (goto-char a)
20634 (move-end-of-line 0) (point))))
20635 (transpose-regions a b c d)
20636 (goto-char c)))
20637 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20638 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20639 ((org-at-item-p) (call-interactively 'org-move-item-up))
20640 (t (org-drag-element-backward))))
20642 (defun org-metadown (&optional _arg)
20643 "Move subtree down or move table row down.
20644 Calls `org-move-subtree-down' or `org-table-move-row' or
20645 `org-move-item-down', depending on context. See the individual
20646 commands for more information."
20647 (interactive "P")
20648 (cond
20649 ((run-hook-with-args-until-success 'org-metadown-hook))
20650 ((org-region-active-p)
20651 (let* ((a (min (region-beginning) (region-end)))
20652 (b (max (region-beginning) (region-end)))
20653 (c (save-excursion (goto-char b)
20654 (move-beginning-of-line 1)))
20655 (d (save-excursion (goto-char b)
20656 (move-end-of-line 1) (1+ (point)))))
20657 (transpose-regions a b c d)
20658 (goto-char d)))
20659 ((org-at-table-p) (call-interactively 'org-table-move-row))
20660 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20661 ((org-at-item-p) (call-interactively 'org-move-item-down))
20662 (t (org-drag-element-forward))))
20664 (defun org-shiftup (&optional arg)
20665 "Increase item in timestamp or increase priority of current headline.
20666 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20667 depending on context. See the individual commands for more information."
20668 (interactive "P")
20669 (cond
20670 ((run-hook-with-args-until-success 'org-shiftup-hook))
20671 ((and org-support-shift-select (org-region-active-p))
20672 (org-call-for-shift-select 'previous-line))
20673 ((org-at-timestamp-p t)
20674 (call-interactively (if org-edit-timestamp-down-means-later
20675 'org-timestamp-down 'org-timestamp-up)))
20676 ((and (not (eq org-support-shift-select 'always))
20677 org-enable-priority-commands
20678 (org-at-heading-p))
20679 (call-interactively 'org-priority-up))
20680 ((and (not org-support-shift-select) (org-at-item-p))
20681 (call-interactively 'org-previous-item))
20682 ((org-clocktable-try-shift 'up arg))
20683 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20684 (org-support-shift-select
20685 (org-call-for-shift-select 'previous-line))
20686 (t (org-shiftselect-error))))
20688 (defun org-shiftdown (&optional arg)
20689 "Decrease item in timestamp or decrease priority of current headline.
20690 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20691 depending on context. See the individual commands for more information."
20692 (interactive "P")
20693 (cond
20694 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20695 ((and org-support-shift-select (org-region-active-p))
20696 (org-call-for-shift-select 'next-line))
20697 ((org-at-timestamp-p t)
20698 (call-interactively (if org-edit-timestamp-down-means-later
20699 'org-timestamp-up 'org-timestamp-down)))
20700 ((and (not (eq org-support-shift-select 'always))
20701 org-enable-priority-commands
20702 (org-at-heading-p))
20703 (call-interactively 'org-priority-down))
20704 ((and (not org-support-shift-select) (org-at-item-p))
20705 (call-interactively 'org-next-item))
20706 ((org-clocktable-try-shift 'down arg))
20707 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20708 (org-support-shift-select
20709 (org-call-for-shift-select 'next-line))
20710 (t (org-shiftselect-error))))
20712 (defun org-shiftright (&optional arg)
20713 "Cycle the thing at point or in the current line, depending on context.
20714 Depending on context, this does one of the following:
20716 - switch a timestamp at point one day into the future
20717 - on a headline, switch to the next TODO keyword.
20718 - on an item, switch entire list to the next bullet type
20719 - on a property line, switch to the next allowed value
20720 - on a clocktable definition line, move time block into the future"
20721 (interactive "P")
20722 (cond
20723 ((run-hook-with-args-until-success 'org-shiftright-hook))
20724 ((and org-support-shift-select (org-region-active-p))
20725 (org-call-for-shift-select 'forward-char))
20726 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20727 ((and (not (eq org-support-shift-select 'always))
20728 (org-at-heading-p))
20729 (let ((org-inhibit-logging
20730 (not org-treat-S-cursor-todo-selection-as-state-change))
20731 (org-inhibit-blocking
20732 (not org-treat-S-cursor-todo-selection-as-state-change)))
20733 (org-call-with-arg 'org-todo 'right)))
20734 ((or (and org-support-shift-select
20735 (not (eq org-support-shift-select 'always))
20736 (org-at-item-bullet-p))
20737 (and (not org-support-shift-select) (org-at-item-p)))
20738 (org-call-with-arg 'org-cycle-list-bullet nil))
20739 ((and (not (eq org-support-shift-select 'always))
20740 (org-at-property-p))
20741 (call-interactively 'org-property-next-allowed-value))
20742 ((org-clocktable-try-shift 'right arg))
20743 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20744 (org-support-shift-select
20745 (org-call-for-shift-select 'forward-char))
20746 (t (org-shiftselect-error))))
20748 (defun org-shiftleft (&optional arg)
20749 "Cycle the thing at point or in the current line, depending on context.
20750 Depending on context, this does one of the following:
20752 - switch a timestamp at point one day into the past
20753 - on a headline, switch to the previous TODO keyword.
20754 - on an item, switch entire list to the previous bullet type
20755 - on a property line, switch to the previous allowed value
20756 - on a clocktable definition line, move time block into the past"
20757 (interactive "P")
20758 (cond
20759 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20760 ((and org-support-shift-select (org-region-active-p))
20761 (org-call-for-shift-select 'backward-char))
20762 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20763 ((and (not (eq org-support-shift-select 'always))
20764 (org-at-heading-p))
20765 (let ((org-inhibit-logging
20766 (not org-treat-S-cursor-todo-selection-as-state-change))
20767 (org-inhibit-blocking
20768 (not org-treat-S-cursor-todo-selection-as-state-change)))
20769 (org-call-with-arg 'org-todo 'left)))
20770 ((or (and org-support-shift-select
20771 (not (eq org-support-shift-select 'always))
20772 (org-at-item-bullet-p))
20773 (and (not org-support-shift-select) (org-at-item-p)))
20774 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20775 ((and (not (eq org-support-shift-select 'always))
20776 (org-at-property-p))
20777 (call-interactively 'org-property-previous-allowed-value))
20778 ((org-clocktable-try-shift 'left arg))
20779 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20780 (org-support-shift-select
20781 (org-call-for-shift-select 'backward-char))
20782 (t (org-shiftselect-error))))
20784 (defun org-shiftcontrolright ()
20785 "Switch to next TODO set."
20786 (interactive)
20787 (cond
20788 ((and org-support-shift-select (org-region-active-p))
20789 (org-call-for-shift-select 'forward-word))
20790 ((and (not (eq org-support-shift-select 'always))
20791 (org-at-heading-p))
20792 (org-call-with-arg 'org-todo 'nextset))
20793 (org-support-shift-select
20794 (org-call-for-shift-select 'forward-word))
20795 (t (org-shiftselect-error))))
20797 (defun org-shiftcontrolleft ()
20798 "Switch to previous TODO set."
20799 (interactive)
20800 (cond
20801 ((and org-support-shift-select (org-region-active-p))
20802 (org-call-for-shift-select 'backward-word))
20803 ((and (not (eq org-support-shift-select 'always))
20804 (org-at-heading-p))
20805 (org-call-with-arg 'org-todo 'previousset))
20806 (org-support-shift-select
20807 (org-call-for-shift-select 'backward-word))
20808 (t (org-shiftselect-error))))
20810 (defun org-shiftcontrolup (&optional n)
20811 "Change timestamps synchronously up in CLOCK log lines.
20812 Optional argument N tells to change by that many units."
20813 (interactive "P")
20814 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20815 (let (org-support-shift-select)
20816 (org-clock-timestamps-up n))
20817 (user-error "Not at a clock log")))
20819 (defun org-shiftcontroldown (&optional n)
20820 "Change timestamps synchronously down in CLOCK log lines.
20821 Optional argument N tells to change by that many units."
20822 (interactive "P")
20823 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20824 (let (org-support-shift-select)
20825 (org-clock-timestamps-down n))
20826 (user-error "Not at a clock log")))
20828 (defun org-increase-number-at-point (&optional inc)
20829 "Increment the number at point.
20830 With an optional prefix numeric argument INC, increment using
20831 this numeric value."
20832 (interactive "p")
20833 (if (not (number-at-point))
20834 (user-error "Not on a number")
20835 (unless inc (setq inc 1))
20836 (let ((pos (point))
20837 (beg (skip-chars-backward "-+^/*0-9eE."))
20838 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20839 (setq nap (buffer-substring-no-properties
20840 (+ pos beg) (+ pos beg end)))
20841 (delete-region (+ pos beg) (+ pos beg end))
20842 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20843 (when (org-at-table-p)
20844 (org-table-align)
20845 (org-table-end-of-field 1))))
20847 (defun org-decrease-number-at-point (&optional inc)
20848 "Decrement the number at point.
20849 With an optional prefix numeric argument INC, decrement using
20850 this numeric value."
20851 (interactive "p")
20852 (org-increase-number-at-point (- (or inc 1))))
20854 (defun org-ctrl-c-ret ()
20855 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20856 (interactive)
20857 (cond
20858 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20859 (t (call-interactively 'org-insert-heading))))
20861 (defun org-find-visible ()
20862 (let ((s (point)))
20863 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20864 (get-char-property s 'invisible)))
20866 (defun org-find-invisible ()
20867 (let ((s (point)))
20868 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20869 (not (get-char-property s 'invisible))))
20872 (defun org-copy-visible (beg end)
20873 "Copy the visible parts of the region."
20874 (interactive "r")
20875 (let (snippets s)
20876 (save-excursion
20877 (save-restriction
20878 (narrow-to-region beg end)
20879 (setq s (goto-char (point-min)))
20880 (while (not (= (point) (point-max)))
20881 (goto-char (org-find-invisible))
20882 (push (buffer-substring s (point)) snippets)
20883 (setq s (goto-char (org-find-visible))))))
20884 (kill-new (apply 'concat (nreverse snippets)))))
20886 (defun org-copy-special ()
20887 "Copy region in table or copy current subtree.
20888 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20889 See the individual commands for more information."
20890 (interactive)
20891 (call-interactively
20892 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20894 (defun org-cut-special ()
20895 "Cut region in table or cut current subtree.
20896 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20897 See the individual commands for more information."
20898 (interactive)
20899 (call-interactively
20900 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20902 (defun org-paste-special (arg)
20903 "Paste rectangular region into table, or past subtree relative to level.
20904 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20905 See the individual commands for more information."
20906 (interactive "P")
20907 (if (org-at-table-p)
20908 (org-table-paste-rectangle)
20909 (org-paste-subtree arg)))
20911 (defsubst org-in-fixed-width-region-p ()
20912 "Is point in a fixed-width region?"
20913 (save-match-data
20914 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20916 (defun org-edit-special (&optional arg)
20917 "Call a special editor for the element at point.
20918 When at a table, call the formula editor with `org-table-edit-formulas'.
20919 When in a source code block, call `org-edit-src-code'.
20920 When in a fixed-width region, call `org-edit-fixed-width-region'.
20921 When in an export block, call `org-edit-export-block'.
20922 When at an #+INCLUDE keyword, visit the included file.
20923 When at a footnote reference, call `org-edit-footnote-reference'
20924 On a link, call `ffap' to visit the link at point.
20925 Otherwise, return a user error."
20926 (interactive "P")
20927 (let ((element (org-element-at-point)))
20928 (cl-assert (not buffer-read-only) nil
20929 "Buffer is read-only: %s" (buffer-name))
20930 (pcase (org-element-type element)
20931 (`src-block
20932 (if (not arg) (org-edit-src-code)
20933 (let* ((info (org-babel-get-src-block-info))
20934 (lang (nth 0 info))
20935 (params (nth 2 info))
20936 (session (cdr (assq :session params))))
20937 (if (not session) (org-edit-src-code)
20938 ;; At a src-block with a session and function called with
20939 ;; an ARG: switch to the buffer related to the inferior
20940 ;; process.
20941 (switch-to-buffer
20942 (funcall (intern (concat "org-babel-prep-session:" lang))
20943 session params))))))
20944 (`keyword
20945 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20946 (org-open-link-from-string
20947 (format "[[%s]]"
20948 (expand-file-name
20949 (let ((value (org-element-property :value element)))
20950 (cond ((not (org-string-nw-p value))
20951 (user-error "No file to edit"))
20952 ((string-match "\\`\"\\(.*?\\)\"" value)
20953 (match-string 1 value))
20954 ((string-match "\\`[^ \t\"]\\S-*" value)
20955 (match-string 0 value))
20956 (t (user-error "No valid file specified")))))))
20957 (user-error "No special environment to edit here")))
20958 (`table
20959 (if (eq (org-element-property :type element) 'table.el)
20960 (org-edit-table.el)
20961 (call-interactively 'org-table-edit-formulas)))
20962 ;; Only Org tables contain `table-row' type elements.
20963 (`table-row (call-interactively 'org-table-edit-formulas))
20964 (`example-block (org-edit-src-code))
20965 (`export-block (org-edit-export-block))
20966 (`fixed-width (org-edit-fixed-width-region))
20968 ;; No notable element at point. Though, we may be at a link or
20969 ;; a footnote reference, which are objects. Thus, scan deeper.
20970 (let ((context (org-element-context element)))
20971 (pcase (org-element-type context)
20972 (`footnote-reference (org-edit-footnote-reference))
20973 (`inline-src-block (org-edit-inline-src-code))
20974 (`link (call-interactively #'ffap))
20975 (_ (user-error "No special environment to edit here"))))))))
20977 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20978 (defun org-ctrl-c-ctrl-c (&optional arg)
20979 "Set tags in headline, or update according to changed information at point.
20981 This command does many different things, depending on context:
20983 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20984 this is what we do.
20986 - If the cursor is on a statistics cookie, update it.
20988 - If the cursor is in a headline, prompt for tags and insert them
20989 into the current line, aligned to `org-tags-column'. When called
20990 with prefix arg, realign all tags in the current buffer.
20992 - If the cursor is in one of the special #+KEYWORD lines, this
20993 triggers scanning the buffer for these lines and updating the
20994 information.
20996 - If the cursor is inside a table, realign the table. This command
20997 works even if the automatic table editor has been turned off.
20999 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21000 the entire table.
21002 - If the cursor is at a footnote reference or definition, jump to
21003 the corresponding definition or references, respectively.
21005 - If the cursor is a the beginning of a dynamic block, update it.
21007 - If the current buffer is a capture buffer, close note and file it.
21009 - If the cursor is on a <<<target>>>, update radio targets and
21010 corresponding links in this buffer.
21012 - If the cursor is on a numbered item in a plain list, renumber the
21013 ordered list.
21015 - If the cursor is on a checkbox, toggle it.
21017 - If the cursor is on a code block, evaluate it. The variable
21018 `org-confirm-babel-evaluate' can be used to control prompting
21019 before code block evaluation, by default every code block
21020 evaluation requires confirmation. Code block evaluation can be
21021 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21022 (interactive "P")
21023 (cond
21024 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21025 org-occur-highlights)
21026 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21027 (org-remove-occur-highlights)
21028 (message "Temporary highlights/overlays removed from current buffer"))
21029 ((and (local-variable-p 'org-finish-function (current-buffer))
21030 (fboundp org-finish-function))
21031 (funcall org-finish-function))
21032 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21034 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21035 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21036 (user-error "C-c C-c can do nothing useful at this location"))
21037 (let* ((context (org-element-context))
21038 (type (org-element-type context)))
21039 (cl-case type
21040 ;; When at a link, act according to the parent instead.
21041 (link (setq context (org-element-property :parent context))
21042 (setq type (org-element-type context)))
21043 ;; Unsupported object types: refer to the first supported
21044 ;; element or object containing it.
21045 ((bold code entity export-snippet inline-babel-call inline-src-block
21046 italic latex-fragment line-break macro strike-through subscript
21047 superscript underline verbatim)
21048 (setq context
21049 (org-element-lineage
21050 context '(radio-target paragraph verse-block table-cell)))))
21051 ;; For convenience: at the first line of a paragraph on the
21052 ;; same line as an item, apply function on that item instead.
21053 (when (eq type 'paragraph)
21054 (let ((parent (org-element-property :parent context)))
21055 (when (and (eq (org-element-type parent) 'item)
21056 (= (line-beginning-position)
21057 (org-element-property :begin parent)))
21058 (setq context parent type 'item))))
21059 ;; Act according to type of element or object at point.
21060 (cl-case type
21061 (clock (org-clock-update-time-maybe))
21062 (dynamic-block
21063 (save-excursion
21064 (goto-char (org-element-property :post-affiliated context))
21065 (org-update-dblock)))
21066 (footnote-definition
21067 (goto-char (org-element-property :post-affiliated context))
21068 (call-interactively 'org-footnote-action))
21069 (footnote-reference (call-interactively 'org-footnote-action))
21070 ((headline inlinetask)
21071 (save-excursion (goto-char (org-element-property :begin context))
21072 (call-interactively 'org-set-tags)))
21073 (item
21074 ;; At an item: a double C-u set checkbox to "[-]"
21075 ;; unconditionally, whereas a single one will toggle its
21076 ;; presence. Without a universal argument, if the item
21077 ;; has a checkbox, toggle it. Otherwise repair the list.
21078 (let* ((box (org-element-property :checkbox context))
21079 (struct (org-element-property :structure context))
21080 (old-struct (copy-tree struct))
21081 (parents (org-list-parents-alist struct))
21082 (prevs (org-list-prevs-alist struct))
21083 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21084 (org-list-set-checkbox
21085 (org-element-property :begin context) struct
21086 (cond ((equal arg '(16)) "[-]")
21087 ((and (not box) (equal arg '(4))) "[ ]")
21088 ((or (not box) (equal arg '(4))) nil)
21089 ((eq box 'on) "[ ]")
21090 (t "[X]")))
21091 ;; Mimic `org-list-write-struct' but with grabbing
21092 ;; a return value from `org-list-struct-fix-box'.
21093 (org-list-struct-fix-ind struct parents 2)
21094 (org-list-struct-fix-item-end struct)
21095 (org-list-struct-fix-bul struct prevs)
21096 (org-list-struct-fix-ind struct parents)
21097 (let ((block-item
21098 (org-list-struct-fix-box struct parents prevs orderedp)))
21099 (if (and box (equal struct old-struct))
21100 (if (equal arg '(16))
21101 (message "Checkboxes already reset")
21102 (user-error "Cannot toggle this checkbox: %s"
21103 (if (eq box 'on)
21104 "all subitems checked"
21105 "unchecked subitems")))
21106 (org-list-struct-apply-struct struct old-struct)
21107 (org-update-checkbox-count-maybe))
21108 (when block-item
21109 (message "Checkboxes were removed due to empty box at line %d"
21110 (org-current-line block-item))))))
21111 (keyword
21112 (let ((org-inhibit-startup-visibility-stuff t)
21113 (org-startup-align-all-tables nil))
21114 (when (boundp 'org-table-coordinate-overlays)
21115 (mapc #'delete-overlay org-table-coordinate-overlays)
21116 (setq org-table-coordinate-overlays nil))
21117 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21118 (message "Local setup has been refreshed"))
21119 (plain-list
21120 ;; At a plain list, with a double C-u argument, set
21121 ;; checkboxes of each item to "[-]", whereas a single one
21122 ;; will toggle their presence according to the state of the
21123 ;; first item in the list. Without an argument, repair the
21124 ;; list.
21125 (let* ((begin (org-element-property :contents-begin context))
21126 (beginm (move-marker (make-marker) begin))
21127 (struct (org-element-property :structure context))
21128 (old-struct (copy-tree struct))
21129 (first-box (save-excursion
21130 (goto-char begin)
21131 (looking-at org-list-full-item-re)
21132 (match-string-no-properties 3)))
21133 (new-box (cond ((equal arg '(16)) "[-]")
21134 ((equal arg '(4)) (unless first-box "[ ]"))
21135 ((equal first-box "[X]") "[ ]")
21136 (t "[X]"))))
21137 (cond
21138 (arg
21139 (dolist (pos
21140 (org-list-get-all-items
21141 begin struct (org-list-prevs-alist struct)))
21142 (org-list-set-checkbox pos struct new-box)))
21143 ((and first-box (eq (point) begin))
21144 ;; For convenience, when point is at bol on the first
21145 ;; item of the list and no argument is provided, simply
21146 ;; toggle checkbox of that item, if any.
21147 (org-list-set-checkbox begin struct new-box)))
21148 (org-list-write-struct
21149 struct (org-list-parents-alist struct) old-struct)
21150 (org-update-checkbox-count-maybe)
21151 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21152 ((property-drawer node-property)
21153 (call-interactively 'org-property-action))
21154 ((radio-target target)
21155 (call-interactively 'org-update-radio-target-regexp))
21156 (statistics-cookie
21157 (call-interactively 'org-update-statistics-cookies))
21158 ((table table-cell table-row)
21159 ;; At a table, recalculate every field and align it. Also
21160 ;; send the table if necessary. If the table has
21161 ;; a `table.el' type, just give up. At a table row or
21162 ;; cell, maybe recalculate line but always align table.
21163 (if (eq (org-element-property :type context) 'table.el)
21164 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21165 Use \\[org-edit-special] to edit table.el tables"))
21166 (let ((org-enable-table-editor t))
21167 (if (or (eq type 'table)
21168 ;; Check if point is at a TBLFM line.
21169 (and (eq type 'table-row)
21170 (= (point) (org-element-property :end context))))
21171 (save-excursion
21172 (if (org-at-TBLFM-p)
21173 (progn (require 'org-table)
21174 (org-table-calc-current-TBLFM))
21175 (goto-char (org-element-property :contents-begin context))
21176 (org-call-with-arg 'org-table-recalculate (or arg t))
21177 (orgtbl-send-table 'maybe)))
21178 (org-table-maybe-eval-formula)
21179 (cond (arg (call-interactively 'org-table-recalculate))
21180 ((org-table-maybe-recalculate-line))
21181 (t (org-table-align)))))))
21182 (timestamp (org-timestamp-change 0 'day))
21183 (otherwise
21184 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21185 (user-error
21186 "C-c C-c can do nothing useful at this location")))))))))
21188 (defun org-mode-restart ()
21189 (interactive)
21190 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21191 (funcall major-mode)
21192 (hack-local-variables)
21193 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21194 (org-indent-mode -1)))
21195 (message "%s restarted" major-mode))
21197 (defun org-kill-note-or-show-branches ()
21198 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21199 (interactive)
21200 (if (not org-finish-function)
21201 (progn
21202 (outline-hide-subtree)
21203 (call-interactively 'outline-show-branches))
21204 (let ((org-note-abort t))
21205 (funcall org-finish-function))))
21207 (defun org-delete-indentation (&optional ARG)
21208 "Join current line to previous and fix whitespace at join.
21210 If previous line is a headline add to headline title. Otherwise
21211 the function calls `delete-indentation'.
21213 With argument, join this line to following line."
21214 (interactive "*P")
21215 (if (save-excursion
21216 (if ARG (beginning-of-line)
21217 (forward-line -1))
21218 (looking-at org-complex-heading-regexp))
21219 ;; At headline.
21220 (let ((tags-column (when (match-beginning 5)
21221 (save-excursion (goto-char (match-beginning 5))
21222 (current-column))))
21223 (string (concat " " (progn (when ARG (forward-line 1))
21224 (org-trim (delete-and-extract-region
21225 (line-beginning-position)
21226 (line-end-position)))))))
21227 (unless (bobp) (delete-region (point) (1- (point))))
21228 (goto-char (or (match-end 4)
21229 (match-beginning 5)
21230 (match-end 0)))
21231 (skip-chars-backward " \t")
21232 (save-excursion (insert string))
21233 ;; Adjust alignment of tags.
21234 (when tags-column
21235 (org-align-tags-here (if org-auto-align-tags
21236 org-tags-column
21237 tags-column))))
21238 (delete-indentation ARG)))
21240 (defun org-open-line (n)
21241 "Insert a new row in tables, call `open-line' elsewhere.
21242 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21243 (interactive "*p")
21244 (cond
21245 ((not org-special-ctrl-o)
21246 (open-line n))
21247 ((org-at-table-p)
21248 (org-table-insert-row))
21250 (open-line n))))
21252 (defun org-return (&optional indent)
21253 "Goto next table row or insert a newline.
21255 Calls `org-table-next-row' or `newline', depending on context.
21257 When optional INDENT argument is non-nil, call
21258 `newline-and-indent' instead of `newline'.
21260 When `org-return-follows-link' is non-nil and point is on
21261 a timestamp or a link, call `org-open-at-point'. However, it
21262 will not happen if point is in a table or on a \"dead\"
21263 object (e.g., within a comment). In these case, you need to use
21264 `org-open-at-point' directly."
21265 (interactive)
21266 (let ((context (if org-return-follows-link (org-element-context)
21267 (org-element-at-point))))
21268 (cond
21269 ;; In a table, call `org-table-next-row'.
21270 ((or (and (eq (org-element-type context) 'table)
21271 (>= (point) (org-element-property :contents-begin context))
21272 (< (point) (org-element-property :contents-end context)))
21273 (org-element-lineage context '(table-row table-cell) t))
21274 (org-table-justify-field-maybe)
21275 (call-interactively #'org-table-next-row))
21276 ;; On a link or a timestamp, call `org-open-at-point' if
21277 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21278 ;; locations, e.g., in a comment, as `org-open-at-point'.
21279 ((and org-return-follows-link
21280 (or (org-in-regexp org-ts-regexp-both nil t)
21281 (org-in-regexp org-tsr-regexp-both nil t)
21282 (org-in-regexp org-any-link-re nil t)))
21283 (call-interactively #'org-open-at-point))
21284 ;; Insert newline in heading, but preserve tags.
21285 ((and (not (bolp))
21286 (save-excursion (beginning-of-line)
21287 (looking-at org-complex-heading-regexp)))
21288 ;; At headline. Split line. However, if point is on keyword,
21289 ;; priority cookie or tags, do not break any of them: add
21290 ;; a newline after the headline instead.
21291 (let ((tags-column (and (match-beginning 5)
21292 (save-excursion (goto-char (match-beginning 5))
21293 (current-column))))
21294 (string
21295 (when (and (match-end 4)
21296 (>= (point)
21297 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21298 (<= (point) (match-end 4)))
21299 (delete-and-extract-region (point) (match-end 4)))))
21300 (when (and tags-column string) ; Adjust tag alignment.
21301 (org-align-tags-here
21302 (if org-auto-align-tags org-tags-column tags-column)))
21303 (end-of-line)
21304 (org-show-entry)
21305 (if indent (newline-and-indent) (newline))
21306 (when string (save-excursion (insert (org-trim string))))))
21307 ;; In a list, make sure indenting keeps trailing text within.
21308 ((and indent
21309 (not (eolp))
21310 (org-element-lineage context '(item)))
21311 (let ((trailing-data
21312 (delete-and-extract-region (point) (line-end-position))))
21313 (newline-and-indent)
21314 (save-excursion (insert trailing-data))))
21315 (t (if indent (newline-and-indent) (newline))))))
21317 (defun org-return-indent ()
21318 "Goto next table row or insert a newline and indent.
21319 Calls `org-table-next-row' or `newline-and-indent', depending on
21320 context. See the individual commands for more information."
21321 (interactive)
21322 (org-return t))
21324 (defun org-ctrl-c-star ()
21325 "Compute table, or change heading status of lines.
21326 Calls `org-table-recalculate' or `org-toggle-heading',
21327 depending on context."
21328 (interactive)
21329 (cond
21330 ((org-at-table-p)
21331 (call-interactively 'org-table-recalculate))
21333 ;; Convert all lines in region to list items
21334 (call-interactively 'org-toggle-heading))))
21336 (defun org-ctrl-c-minus ()
21337 "Insert separator line in table or modify bullet status of line.
21338 Also turns a plain line or a region of lines into list items.
21339 Calls `org-table-insert-hline', `org-toggle-item', or
21340 `org-cycle-list-bullet', depending on context."
21341 (interactive)
21342 (cond
21343 ((org-at-table-p)
21344 (call-interactively 'org-table-insert-hline))
21345 ((org-region-active-p)
21346 (call-interactively 'org-toggle-item))
21347 ((org-in-item-p)
21348 (call-interactively 'org-cycle-list-bullet))
21350 (call-interactively 'org-toggle-item))))
21352 (defun org-toggle-item (arg)
21353 "Convert headings or normal lines to items, items to normal lines.
21354 If there is no active region, only the current line is considered.
21356 If the first non blank line in the region is a headline, convert
21357 all headlines to items, shifting text accordingly.
21359 If it is an item, convert all items to normal lines.
21361 If it is normal text, change region into a list of items.
21362 With a prefix argument ARG, change the region in a single item."
21363 (interactive "P")
21364 (let ((shift-text
21365 (function
21366 ;; Shift text in current section to IND, from point to END.
21367 ;; The function leaves point to END line.
21368 (lambda (ind end)
21369 (let ((min-i 1000) (end (copy-marker end)))
21370 ;; First determine the minimum indentation (MIN-I) of
21371 ;; the text.
21372 (save-excursion
21373 (catch 'exit
21374 (while (< (point) end)
21375 (let ((i (org-get-indentation)))
21376 (cond
21377 ;; Skip blank lines and inline tasks.
21378 ((looking-at "^[ \t]*$"))
21379 ((looking-at org-outline-regexp-bol))
21380 ;; We can't find less than 0 indentation.
21381 ((zerop i) (throw 'exit (setq min-i 0)))
21382 ((< i min-i) (setq min-i i))))
21383 (forward-line))))
21384 ;; Then indent each line so that a line indented to
21385 ;; MIN-I becomes indented to IND. Ignore blank lines
21386 ;; and inline tasks in the process.
21387 (let ((delta (- ind min-i)))
21388 (while (< (point) end)
21389 (unless (or (looking-at "^[ \t]*$")
21390 (looking-at org-outline-regexp-bol))
21391 (org-indent-line-to (+ (org-get-indentation) delta)))
21392 (forward-line)))))))
21393 (skip-blanks
21394 (function
21395 ;; Return beginning of first non-blank line, starting from
21396 ;; line at POS.
21397 (lambda (pos)
21398 (save-excursion
21399 (goto-char pos)
21400 (skip-chars-forward " \r\t\n")
21401 (point-at-bol)))))
21402 beg end)
21403 ;; Determine boundaries of changes.
21404 (if (org-region-active-p)
21405 (setq beg (funcall skip-blanks (region-beginning))
21406 end (copy-marker (region-end)))
21407 (setq beg (funcall skip-blanks (point-at-bol))
21408 end (copy-marker (point-at-eol))))
21409 ;; Depending on the starting line, choose an action on the text
21410 ;; between BEG and END.
21411 (org-with-limited-levels
21412 (save-excursion
21413 (goto-char beg)
21414 (cond
21415 ;; Case 1. Start at an item: de-itemize. Note that it only
21416 ;; happens when a region is active: `org-ctrl-c-minus'
21417 ;; would call `org-cycle-list-bullet' otherwise.
21418 ((org-at-item-p)
21419 (while (< (point) end)
21420 (when (org-at-item-p)
21421 (skip-chars-forward " \t")
21422 (delete-region (point) (match-end 0)))
21423 (forward-line)))
21424 ;; Case 2. Start at an heading: convert to items.
21425 ((org-at-heading-p)
21426 (let* ((bul (org-list-bullet-string "-"))
21427 (bul-len (length bul))
21428 (done (org-entry-is-done-p))
21429 (todo (org-entry-is-todo-p))
21430 ;; Indentation of the first heading. It should be
21431 ;; relative to the indentation of its parent, if any.
21432 (start-ind (save-excursion
21433 (cond
21434 ((not org-adapt-indentation) 0)
21435 ((not (outline-previous-heading)) 0)
21436 (t (length (match-string 0))))))
21437 ;; Level of first heading. Further headings will be
21438 ;; compared to it to determine hierarchy in the list.
21439 (ref-level (org-reduced-level (org-outline-level))))
21440 (when (or done todo) (org-todo ""))
21441 (while (< (point) end)
21442 (let* ((level (org-reduced-level (org-outline-level)))
21443 (delta (max 0 (- level ref-level))))
21444 ;; If current headline is less indented than the first
21445 ;; one, set it as reference, in order to preserve
21446 ;; subtrees.
21447 (when (< level ref-level) (setq ref-level level))
21448 (replace-match bul t t)
21449 (org-indent-line-to (+ start-ind (* delta bul-len)))
21450 (when (or done todo)
21451 (let* ((struct (org-list-struct))
21452 (old (copy-tree struct)))
21453 (org-list-set-checkbox (line-beginning-position)
21454 struct
21455 (if done "[X]" "[ ]"))
21456 (org-list-write-struct struct
21457 (org-list-parents-alist struct)
21458 old)))
21459 ;; Ensure all text down to END (or SECTION-END) belongs
21460 ;; to the newly created item.
21461 (let ((section-end (save-excursion
21462 (or (outline-next-heading) (point)))))
21463 (forward-line)
21464 (funcall shift-text
21465 (+ start-ind (* (1+ delta) bul-len))
21466 (min end section-end)))))))
21467 ;; Case 3. Normal line with ARG: make the first line of region
21468 ;; an item, and shift indentation of others lines to
21469 ;; set them as item's body.
21470 (arg (let* ((bul (org-list-bullet-string "-"))
21471 (bul-len (length bul))
21472 (ref-ind (org-get-indentation)))
21473 (skip-chars-forward " \t")
21474 (insert bul)
21475 (forward-line)
21476 (while (< (point) end)
21477 ;; Ensure that lines less indented than first one
21478 ;; still get included in item body.
21479 (funcall shift-text
21480 (+ ref-ind bul-len)
21481 (min end (save-excursion (or (outline-next-heading)
21482 (point)))))
21483 (forward-line))))
21484 ;; Case 4. Normal line without ARG: turn each non-item line
21485 ;; into an item.
21487 (while (< (point) end)
21488 (unless (or (org-at-heading-p) (org-at-item-p))
21489 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21490 (replace-match
21491 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21492 (forward-line))))))))
21494 (defun org-toggle-heading (&optional nstars)
21495 "Convert headings to normal text, or items or text to headings.
21496 If there is no active region, only convert the current line.
21498 With a \\[universal-argument] prefix, convert the whole list at
21499 point into heading.
21501 In a region:
21503 - If the first non blank line is a headline, remove the stars
21504 from all headlines in the region.
21506 - If it is a normal line, turn each and every normal line (i.e.,
21507 not an heading or an item) in the region into headings. If you
21508 want to convert only the first line of this region, use one
21509 universal prefix argument.
21511 - If it is a plain list item, turn all plain list items into headings.
21513 When converting a line into a heading, the number of stars is chosen
21514 such that the lines become children of the current entry. However,
21515 when a numeric prefix argument is given, its value determines the
21516 number of stars to add."
21517 (interactive "P")
21518 (let ((skip-blanks
21519 (function
21520 ;; Return beginning of first non-blank line, starting from
21521 ;; line at POS.
21522 (lambda (pos)
21523 (save-excursion
21524 (goto-char pos)
21525 (while (org-at-comment-p) (forward-line))
21526 (skip-chars-forward " \r\t\n")
21527 (point-at-bol)))))
21528 beg end toggled)
21529 ;; Determine boundaries of changes. If a universal prefix has
21530 ;; been given, put the list in a region. If region ends at a bol,
21531 ;; do not consider the last line to be in the region.
21533 (when (and current-prefix-arg (org-at-item-p))
21534 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21535 (org-mark-element))
21537 (if (org-region-active-p)
21538 (setq beg (funcall skip-blanks (region-beginning))
21539 end (copy-marker (save-excursion
21540 (goto-char (region-end))
21541 (if (bolp) (point) (point-at-eol)))))
21542 (setq beg (funcall skip-blanks (point-at-bol))
21543 end (copy-marker (point-at-eol))))
21544 ;; Ensure inline tasks don't count as headings.
21545 (org-with-limited-levels
21546 (save-excursion
21547 (goto-char beg)
21548 (cond
21549 ;; Case 1. Started at an heading: de-star headings.
21550 ((org-at-heading-p)
21551 (while (< (point) end)
21552 (when (org-at-heading-p t)
21553 (looking-at org-outline-regexp) (replace-match "")
21554 (setq toggled t))
21555 (forward-line)))
21556 ;; Case 2. Started at an item: change items into headlines.
21557 ;; One star will be added by `org-list-to-subtree'.
21558 ((org-at-item-p)
21559 (while (< (point) end)
21560 (when (org-at-item-p)
21561 ;; Pay attention to cases when region ends before list.
21562 (let* ((struct (org-list-struct))
21563 (list-end
21564 (min (org-list-get-bottom-point struct) (1+ end))))
21565 (save-restriction
21566 (narrow-to-region (point) list-end)
21567 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21568 (setq toggled t))
21569 (forward-line)))
21570 ;; Case 3. Started at normal text: make every line an heading,
21571 ;; skipping headlines and items.
21572 (t (let* ((stars
21573 (make-string
21574 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21575 (add-stars
21576 (cond (nstars "") ; stars from prefix only
21577 ((equal stars "") "*") ; before first heading
21578 (org-odd-levels-only "**") ; inside heading, odd
21579 (t "*"))) ; inside heading, oddeven
21580 (rpl (concat stars add-stars " "))
21581 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21582 (while (< (point) (if (equal nstars '(4)) lend end))
21583 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21584 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21585 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21586 (forward-line)))))))
21587 (unless toggled (message "Cannot toggle heading from here"))))
21589 (defun org-meta-return (&optional _arg)
21590 "Insert a new heading or wrap a region in a table.
21591 Calls `org-insert-heading' or `org-table-wrap-region', depending
21592 on context. See the individual commands for more information."
21593 (interactive)
21594 (org-check-before-invisible-edit 'insert)
21595 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21596 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21597 #'org-insert-heading))))
21599 ;;; Menu entries
21601 (defsubst org-in-subtree-not-table-p ()
21602 "Are we in a subtree and not in a table?"
21603 (and (not (org-before-first-heading-p))
21604 (not (org-at-table-p))))
21606 ;; Define the Org-mode menus
21607 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21608 '("Tbl"
21609 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21610 ["Next Field" org-cycle (org-at-table-p)]
21611 ["Previous Field" org-shifttab (org-at-table-p)]
21612 ["Next Row" org-return (org-at-table-p)]
21613 "--"
21614 ["Blank Field" org-table-blank-field (org-at-table-p)]
21615 ["Edit Field" org-table-edit-field (org-at-table-p)]
21616 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21617 "--"
21618 ("Column"
21619 ["Move Column Left" org-metaleft (org-at-table-p)]
21620 ["Move Column Right" org-metaright (org-at-table-p)]
21621 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21622 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21623 ("Row"
21624 ["Move Row Up" org-metaup (org-at-table-p)]
21625 ["Move Row Down" org-metadown (org-at-table-p)]
21626 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21627 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21628 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21629 "--"
21630 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21631 ("Rectangle"
21632 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21633 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21634 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21635 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21636 "--"
21637 ("Calculate"
21638 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21639 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21640 ["Edit Formulas" org-edit-special (org-at-table-p)]
21641 "--"
21642 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21643 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21644 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21645 "--"
21646 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21647 "--"
21648 ["Sum Column/Rectangle" org-table-sum
21649 (or (org-at-table-p) (org-region-active-p))]
21650 ["Which Column?" org-table-current-column (org-at-table-p)])
21651 ["Debug Formulas"
21652 org-table-toggle-formula-debugger
21653 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21654 ["Show Col/Row Numbers"
21655 org-table-toggle-coordinate-overlays
21656 :style toggle
21657 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21658 "--"
21659 ["Create" org-table-create (and (not (org-at-table-p))
21660 org-enable-table-editor)]
21661 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21662 ["Import from File" org-table-import (not (org-at-table-p))]
21663 ["Export to File" org-table-export (org-at-table-p)]
21664 "--"
21665 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21666 "--"
21667 ("Plot"
21668 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21669 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21671 (easy-menu-define org-org-menu org-mode-map "Org menu"
21672 '("Org"
21673 ("Show/Hide"
21674 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21675 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21676 ["Sparse Tree..." org-sparse-tree t]
21677 ["Reveal Context" org-reveal t]
21678 ["Show All" outline-show-all t]
21679 "--"
21680 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21681 "--"
21682 ["New Heading" org-insert-heading t]
21683 ("Navigate Headings"
21684 ["Up" outline-up-heading t]
21685 ["Next" outline-next-visible-heading t]
21686 ["Previous" outline-previous-visible-heading t]
21687 ["Next Same Level" outline-forward-same-level t]
21688 ["Previous Same Level" outline-backward-same-level t]
21689 "--"
21690 ["Jump" org-goto t])
21691 ("Edit Structure"
21692 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21693 "--"
21694 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21695 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21696 "--"
21697 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21698 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21699 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21700 "--"
21701 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21702 "--"
21703 ["Copy visible text" org-copy-visible t]
21704 "--"
21705 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21706 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21707 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21708 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21709 "--"
21710 ["Sort Region/Children" org-sort t]
21711 "--"
21712 ["Convert to odd levels" org-convert-to-odd-levels t]
21713 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21714 ("Editing"
21715 ["Emphasis..." org-emphasize t]
21716 ["Edit Source Example" org-edit-special t]
21717 "--"
21718 ["Footnote new/jump" org-footnote-action t]
21719 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21720 ("Archive"
21721 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21722 "--"
21723 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21724 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21725 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21727 "--"
21728 ("Hyperlinks"
21729 ["Store Link (Global)" org-store-link t]
21730 ["Find existing link to here" org-occur-link-in-agenda-files t]
21731 ["Insert Link" org-insert-link t]
21732 ["Follow Link" org-open-at-point t]
21733 "--"
21734 ["Next link" org-next-link t]
21735 ["Previous link" org-previous-link t]
21736 "--"
21737 ["Descriptive Links"
21738 org-toggle-link-display
21739 :style radio
21740 :selected org-descriptive-links
21742 ["Literal Links"
21743 org-toggle-link-display
21744 :style radio
21745 :selected (not org-descriptive-links)])
21746 "--"
21747 ("TODO Lists"
21748 ["TODO/DONE/-" org-todo t]
21749 ("Select keyword"
21750 ["Next keyword" org-shiftright (org-at-heading-p)]
21751 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21752 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21753 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21754 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21755 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21756 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21757 "--"
21758 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21759 :selected org-enforce-todo-dependencies :style toggle :active t]
21760 "Settings for tree at point"
21761 ["Do Children sequentially" org-toggle-ordered-property :style radio
21762 :selected (org-entry-get nil "ORDERED")
21763 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21764 ["Do Children parallel" org-toggle-ordered-property :style radio
21765 :selected (not (org-entry-get nil "ORDERED"))
21766 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21767 "--"
21768 ["Set Priority" org-priority t]
21769 ["Priority Up" org-shiftup t]
21770 ["Priority Down" org-shiftdown t]
21771 "--"
21772 ["Get news from all feeds" org-feed-update-all t]
21773 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21774 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21775 ("TAGS and Properties"
21776 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21777 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21778 "--"
21779 ["Set property" org-set-property (not (org-before-first-heading-p))]
21780 ["Column view of properties" org-columns t]
21781 ["Insert Column View DBlock" org-columns-insert-dblock t])
21782 ("Dates and Scheduling"
21783 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21784 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21785 ("Change Date"
21786 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21787 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21788 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21789 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21790 ["Compute Time Range" org-evaluate-time-range t]
21791 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21792 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21793 "--"
21794 ["Custom time format" org-toggle-time-stamp-overlays
21795 :style radio :selected org-display-custom-times]
21796 "--"
21797 ["Goto Calendar" org-goto-calendar t]
21798 ["Date from Calendar" org-date-from-calendar t]
21799 "--"
21800 ["Start/Restart Timer" org-timer-start t]
21801 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21802 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21803 ["Insert Timer String" org-timer t]
21804 ["Insert Timer Item" org-timer-item t])
21805 ("Logging work"
21806 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21807 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21808 ["Clock out" org-clock-out t]
21809 ["Clock cancel" org-clock-cancel t]
21810 "--"
21811 ["Mark as default task" org-clock-mark-default-task t]
21812 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21813 ["Goto running clock" org-clock-goto t]
21814 "--"
21815 ["Display times" org-clock-display t]
21816 ["Create clock table" org-clock-report t]
21817 "--"
21818 ["Record DONE time"
21819 (progn (setq org-log-done (not org-log-done))
21820 (message "Switching to %s will %s record a timestamp"
21821 (car org-done-keywords)
21822 (if org-log-done "automatically" "not")))
21823 :style toggle :selected org-log-done])
21824 "--"
21825 ["Agenda Command..." org-agenda t]
21826 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21827 ("File List for Agenda")
21828 ("Special views current file"
21829 ["TODO Tree" org-show-todo-tree t]
21830 ["Check Deadlines" org-check-deadlines t]
21831 ["Timeline" org-timeline t]
21832 ["Tags/Property tree" org-match-sparse-tree t])
21833 "--"
21834 ["Export/Publish..." org-export-dispatch t]
21835 ("LaTeX"
21836 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21837 :selected org-cdlatex-mode]
21838 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21839 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21840 ["Modify math symbol" org-cdlatex-math-modify
21841 (org-inside-LaTeX-fragment-p)]
21842 ["Insert citation" org-reftex-citation t]
21843 "--"
21844 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21845 "--"
21846 ("MobileOrg"
21847 ["Push Files and Views" org-mobile-push t]
21848 ["Get Captured and Flagged" org-mobile-pull t]
21849 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21850 "--"
21851 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21852 "--"
21853 ("Documentation"
21854 ["Show Version" org-version t]
21855 ["Info Documentation" org-info t])
21856 ("Customize"
21857 ["Browse Org Group" org-customize t]
21858 "--"
21859 ["Expand This Menu" org-create-customize-menu
21860 (fboundp 'customize-menu-create)])
21861 ["Send bug report" org-submit-bug-report t]
21862 "--"
21863 ("Refresh/Reload"
21864 ["Refresh setup current buffer" org-mode-restart t]
21865 ["Reload Org (after update)" org-reload t]
21866 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21869 (defun org-info (&optional node)
21870 "Read documentation for Org-mode in the info system.
21871 With optional NODE, go directly to that node."
21872 (interactive)
21873 (info (format "(org)%s" (or node ""))))
21875 ;;;###autoload
21876 (defun org-submit-bug-report ()
21877 "Submit a bug report on Org-mode via mail.
21879 Don't hesitate to report any problems or inaccurate documentation.
21881 If you don't have setup sending mail from (X)Emacs, please copy the
21882 output buffer into your mail program, as it gives us important
21883 information about your Org-mode version and configuration."
21884 (interactive)
21885 (require 'reporter)
21886 (defvar reporter-prompt-for-summary-p)
21887 (org-load-modules-maybe)
21888 (org-require-autoloaded-modules)
21889 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21890 (reporter-submit-bug-report
21891 "emacs-orgmode@gnu.org"
21892 (org-version nil 'full)
21893 (let (list)
21894 (save-window-excursion
21895 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21896 (delete-other-windows)
21897 (erase-buffer)
21898 (insert "You are about to submit a bug report to the Org-mode mailing list.
21900 We would like to add your full Org-mode and Outline configuration to the
21901 bug report. This greatly simplifies the work of the maintainer and
21902 other experts on the mailing list.
21904 HOWEVER, some variables you have customized may contain private
21905 information. The names of customers, colleagues, or friends, might
21906 appear in the form of file names, tags, todo states, or search strings.
21907 If you answer yes to the prompt, you might want to check and remove
21908 such private information before sending the email.")
21909 (add-text-properties (point-min) (point-max) '(face org-warning))
21910 (when (yes-or-no-p "Include your Org-mode configuration ")
21911 (mapatoms
21912 (lambda (v)
21913 (and (boundp v)
21914 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21915 (or (and (symbol-value v)
21916 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21917 (and
21918 (get v 'custom-type) (get v 'standard-value)
21919 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21920 (push v list)))))
21921 (kill-buffer (get-buffer "*Warn about privacy*"))
21922 list))
21923 nil nil
21924 "Remember to cover the basics, that is, what you expected to happen and
21925 what in fact did happen. You don't know how to make a good report? See
21927 http://orgmode.org/manual/Feedback.html#Feedback
21929 Your bug report will be posted to the Org-mode mailing list.
21930 ------------------------------------------------------------------------")
21931 (save-excursion
21932 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21933 (replace-match "\\1Bug: \\3 [\\2]")))))
21936 (defun org-install-agenda-files-menu ()
21937 (let ((bl (buffer-list)))
21938 (save-excursion
21939 (while bl
21940 (set-buffer (pop bl))
21941 (when (derived-mode-p 'org-mode) (setq bl nil)))
21942 (when (derived-mode-p 'org-mode)
21943 (easy-menu-change
21944 '("Org") "File List for Agenda"
21945 (append
21946 (list
21947 ["Edit File List" (org-edit-agenda-file-list) t]
21948 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21949 ["Remove Current File from List" org-remove-file t]
21950 ["Cycle through agenda files" org-cycle-agenda-files t]
21951 ["Occur in all agenda files" org-occur-in-agenda-files t]
21952 "--")
21953 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21955 ;;;; Documentation
21957 (defun org-require-autoloaded-modules ()
21958 (interactive)
21959 (mapc #'require
21960 '(org-agenda org-archive org-attach org-clock org-colview org-id
21961 org-table org-timer)))
21963 ;;;###autoload
21964 (defun org-reload (&optional uncompiled)
21965 "Reload all org lisp files.
21966 With prefix arg UNCOMPILED, load the uncompiled versions."
21967 (interactive "P")
21968 (require 'loadhist)
21969 (let* ((org-dir (org-find-library-dir "org"))
21970 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21971 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21972 (remove-re (mapconcat 'identity
21973 (mapcar (lambda (f) (concat "^" f "$"))
21974 (list (if (featurep 'xemacs)
21975 "org-colview"
21976 "org-colview-xemacs")
21977 "org" "org-loaddefs" "org-version"))
21978 "\\|"))
21979 (feats (delete-dups
21980 (mapcar 'file-name-sans-extension
21981 (mapcar 'file-name-nondirectory
21982 (delq nil
21983 (mapcar 'feature-file
21984 features))))))
21985 (lfeat (append
21986 (sort
21987 (setq feats
21988 (delq nil (mapcar
21989 (lambda (f)
21990 (if (and (string-match feature-re f)
21991 (not (string-match remove-re f)))
21992 f nil))
21993 feats)))
21994 'string-lessp)
21995 (list "org-version" "org")))
21996 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21997 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21998 load-uncore load-misses)
21999 (setq load-misses
22000 (delq 't
22001 (mapcar (lambda (f)
22002 (or (org-load-noerror-mustsuffix (concat org-dir f))
22003 (and (string= org-dir contrib-dir)
22004 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22005 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22006 (add-to-list 'load-uncore f 'append)
22009 lfeat)))
22010 (when load-uncore
22011 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22012 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22013 (if load-misses
22014 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22015 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22016 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22018 ;;;###autoload
22019 (defun org-customize ()
22020 "Call the customize function with org as argument."
22021 (interactive)
22022 (org-load-modules-maybe)
22023 (org-require-autoloaded-modules)
22024 (customize-browse 'org))
22026 (defun org-create-customize-menu ()
22027 "Create a full customization menu for Org-mode, insert it into the menu."
22028 (interactive)
22029 (org-load-modules-maybe)
22030 (org-require-autoloaded-modules)
22031 (if (fboundp 'customize-menu-create)
22032 (progn
22033 (easy-menu-change
22034 '("Org") "Customize"
22035 `(["Browse Org group" org-customize t]
22036 "--"
22037 ,(customize-menu-create 'org)
22038 ["Set" Custom-set t]
22039 ["Save" Custom-save t]
22040 ["Reset to Current" Custom-reset-current t]
22041 ["Reset to Saved" Custom-reset-saved t]
22042 ["Reset to Standard Settings" Custom-reset-standard t]))
22043 (message "\"Org\"-menu now contains full customization menu"))
22044 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22046 ;;;; Miscellaneous stuff
22048 ;;; Generally useful functions
22050 (defun org-get-at-eol (property n)
22051 "Get text property PROPERTY at the end of line less N characters."
22052 (get-text-property (- (point-at-eol) n) property))
22054 (defun org-find-text-property-in-string (prop s)
22055 "Return the first non-nil value of property PROP in string S."
22056 (or (get-text-property 0 prop s)
22057 (get-text-property (or (next-single-property-change 0 prop s) 0)
22058 prop s)))
22060 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22061 "Display the given MESSAGE as a warning."
22062 (if (fboundp 'display-warning)
22063 (display-warning 'org message
22064 (if (featurep 'xemacs) 'warning :warning))
22065 (let ((buf (get-buffer-create "*Org warnings*")))
22066 (with-current-buffer buf
22067 (goto-char (point-max))
22068 (insert "Warning (Org): " message)
22069 (unless (bolp)
22070 (newline)))
22071 (display-buffer buf)
22072 (sit-for 0))))
22074 (defun org-eval (form)
22075 "Eval FORM and return result."
22076 (condition-case error
22077 (eval form)
22078 (error (format "%%![Error: %s]" error))))
22080 (defun org-in-clocktable-p ()
22081 "Check if the cursor is in a clocktable."
22082 (let ((pos (point)) start)
22083 (save-excursion
22084 (end-of-line 1)
22085 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22086 (setq start (match-beginning 0))
22087 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22088 (>= (match-end 0) pos)
22089 start))))
22091 (defun org-in-verbatim-emphasis ()
22092 (save-match-data
22093 (and (org-in-regexp org-emph-re 2)
22094 (>= (point) (match-beginning 3))
22095 (<= (point) (match-end 4))
22096 (member (match-string 3) '("=" "~")))))
22098 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22099 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22100 (if (and marker (marker-buffer marker)
22101 (buffer-live-p (marker-buffer marker)))
22102 (progn
22103 (org-pop-to-buffer-same-window (marker-buffer marker))
22104 (when (or (> marker (point-max)) (< marker (point-min)))
22105 (widen))
22106 (goto-char marker)
22107 (org-show-context 'org-goto))
22108 (if bookmark
22109 (bookmark-jump bookmark)
22110 (error "Cannot find location"))))
22112 (defun org-quote-csv-field (s)
22113 "Quote field for inclusion in CSV material."
22114 (if (string-match "[\",]" s)
22115 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22118 (defun org-force-self-insert (N)
22119 "Needed to enforce self-insert under remapping."
22120 (interactive "p")
22121 (self-insert-command N))
22123 (defun org-string-width (s)
22124 "Compute width of string, ignoring invisible characters.
22125 This ignores character with invisibility property `org-link', and also
22126 characters with property `org-cwidth', because these will become invisible
22127 upon the next fontification round."
22128 (let (b l)
22129 (when (or (eq t buffer-invisibility-spec)
22130 (assq 'org-link buffer-invisibility-spec))
22131 (while (setq b (text-property-any 0 (length s)
22132 'invisible 'org-link s))
22133 (setq s (concat (substring s 0 b)
22134 (substring s (or (next-single-property-change
22135 b 'invisible s)
22136 (length s)))))))
22137 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22138 (setq s (concat (substring s 0 b)
22139 (substring s (or (next-single-property-change
22140 b 'org-cwidth s)
22141 (length s))))))
22142 (setq l (string-width s) b -1)
22143 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22144 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22147 (defun org-shorten-string (s maxlength)
22148 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22149 If the string is shorter or has length MAXLENGTH, just return the
22150 original string. If it is longer, the functions finds a space in the
22151 string, breaks this string off at that locations and adds three dots
22152 as ellipsis. Including the ellipsis, the string will not be longer
22153 than MAXLENGTH. If finding a good breaking point in the string does
22154 not work, the string is just chopped off in the middle of a word
22155 if necessary."
22156 (if (<= (length s) maxlength)
22158 (let* ((n (max (- maxlength 4) 1))
22159 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22160 (if (string-match re s)
22161 (concat (match-string 1 s) "...")
22162 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22164 (defun org-get-indentation (&optional line)
22165 "Get the indentation of the current line, interpreting tabs.
22166 When LINE is given, assume it represents a line and compute its indentation."
22167 (if line
22168 (when (string-match "^ *" (org-remove-tabs line))
22169 (match-end 0))
22170 (save-excursion
22171 (beginning-of-line 1)
22172 (skip-chars-forward " \t")
22173 (current-column))))
22175 (defun org-get-string-indentation (s)
22176 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22177 (let ((n -1) (i 0) (w tab-width) c)
22178 (catch 'exit
22179 (while (< (setq n (1+ n)) (length s))
22180 (setq c (aref s n))
22181 (cond ((= c ?\ ) (setq i (1+ i)))
22182 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22183 (t (throw 'exit t)))))
22186 (defun org-remove-tabs (s &optional width)
22187 "Replace tabulators in S with spaces.
22188 Assumes that s is a single line, starting in column 0."
22189 (setq width (or width tab-width))
22190 (while (string-match "\t" s)
22191 (setq s (replace-match
22192 (make-string
22193 (- (* width (/ (+ (match-beginning 0) width) width))
22194 (match-beginning 0)) ?\ )
22195 t t s)))
22198 (defun org-fix-indentation (line ind)
22199 "Fix indentation in LINE.
22200 IND is a cons cell with target and minimum indentation.
22201 If the current indentation in LINE is smaller than the minimum,
22202 leave it alone. If it is larger than ind, set it to the target."
22203 (let* ((l (org-remove-tabs line))
22204 (i (org-get-indentation l))
22205 (i1 (car ind)) (i2 (cdr ind)))
22206 (when (>= i i2) (setq l (substring line i2)))
22207 (if (> i1 0)
22208 (concat (make-string i1 ?\ ) l)
22209 l)))
22211 (defun org-remove-indentation (code &optional n)
22212 "Remove maximum common indentation in string CODE and return it.
22213 N may optionally be the number of columns to remove. Return CODE
22214 as-is if removal failed."
22215 (with-temp-buffer
22216 (insert code)
22217 (if (org-do-remove-indentation n) (buffer-string) code)))
22219 (defun org-do-remove-indentation (&optional n)
22220 "Remove the maximum common indentation from the buffer.
22221 When optional argument N is a positive integer, remove exactly
22222 that much characters from indentation, if possible. Return nil
22223 if it fails."
22224 (catch :exit
22225 (goto-char (point-min))
22226 ;; Find maximum common indentation, if not specified.
22227 (let ((n (or n
22228 (let ((min-ind (point-max)))
22229 (save-excursion
22230 (while (re-search-forward "^[ \t]*\\S-" nil t)
22231 (let ((ind (1- (current-column))))
22232 (if (zerop ind) (throw :exit nil)
22233 (setq min-ind (min min-ind ind))))))
22234 min-ind))))
22235 (if (zerop n) (throw :exit nil)
22236 ;; Remove exactly N indentation, but give up if not possible.
22237 (while (not (eobp))
22238 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22239 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22240 ((< ind n) (throw :exit nil))
22241 (t (org-indent-line-to (- ind n))))
22242 (forward-line)))
22243 ;; Signal success.
22244 t))))
22246 (defun org-fill-template (template alist)
22247 "Find each %key of ALIST in TEMPLATE and replace it."
22248 (let ((case-fold-search nil))
22249 (dolist (entry (sort (copy-sequence alist)
22250 (lambda (a b) (< (length (car a)) (length (car b))))))
22251 (setq template
22252 (replace-regexp-in-string
22253 (concat "%" (regexp-quote (car entry)))
22254 (or (cdr entry) "") template t t)))
22255 template))
22257 (defun org-base-buffer (buffer)
22258 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22259 (if (not buffer)
22260 buffer
22261 (or (buffer-base-buffer buffer)
22262 buffer)))
22264 (defun org-wrap (string &optional width lines)
22265 "Wrap string to either a number of lines, or a width in characters.
22266 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22267 that costs. If there is a word longer than WIDTH, the text is actually
22268 wrapped to the length of that word.
22269 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22270 many lines, whatever width that takes.
22271 The return value is a list of lines, without newlines at the end."
22272 (let* ((words (org-split-string string "[ \t\n]+"))
22273 (maxword (apply 'max (mapcar 'org-string-width words)))
22274 w ll)
22275 (cond (width
22276 (org-do-wrap words (max maxword width)))
22277 (lines
22278 (setq w maxword)
22279 (setq ll (org-do-wrap words maxword))
22280 (if (<= (length ll) lines)
22282 (setq ll words)
22283 (while (> (length ll) lines)
22284 (setq w (1+ w))
22285 (setq ll (org-do-wrap words w)))
22286 ll))
22287 (t (error "Cannot wrap this")))))
22289 (defun org-do-wrap (words width)
22290 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22291 (let (lines line)
22292 (while words
22293 (setq line (pop words))
22294 (while (and words (< (+ (length line) (length (car words))) width))
22295 (setq line (concat line " " (pop words))))
22296 (setq lines (push line lines)))
22297 (nreverse lines)))
22299 (defun org-split-string (string &optional separators)
22300 "Splits STRING into substrings at SEPARATORS.
22301 SEPARATORS is a regular expression.
22302 No empty strings are returned if there are matches at the beginning
22303 and end of string."
22304 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22305 (let ((start 0) notfirst list)
22306 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22307 (if (and notfirst
22308 (= start (match-beginning 0))
22309 (< start (length string)))
22310 (1+ start) start))
22311 (< (match-beginning 0) (length string)))
22312 (setq notfirst t)
22313 (or (eq (match-beginning 0) 0)
22314 (and (eq (match-beginning 0) (match-end 0))
22315 (eq (match-beginning 0) start))
22316 (push (substring string start (match-beginning 0)) list))
22317 (setq start (match-end 0)))
22318 (or (eq start (length string))
22319 (push (substring string start) list))
22320 (nreverse list)))
22322 (defun org-quote-vert (s)
22323 "Replace \"|\" with \"\\vert\"."
22324 (while (string-match "|" s)
22325 (setq s (replace-match "\\vert" t t s)))
22328 (defun org-uuidgen-p (s)
22329 "Is S an ID created by UUIDGEN?"
22330 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22332 (defun org-in-src-block-p (&optional inside)
22333 "Whether point is in a code source block.
22334 When INSIDE is non-nil, don't consider we are within a src block
22335 when point is at #+BEGIN_SRC or #+END_SRC."
22336 (let ((case-fold-search t))
22337 (or (and (eq (get-char-property (point) 'src-block) t))
22338 (and (not inside)
22339 (save-match-data
22340 (save-excursion
22341 (beginning-of-line)
22342 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22344 (defun org-context ()
22345 "Return a list of contexts of the current cursor position.
22346 If several contexts apply, all are returned.
22347 Each context entry is a list with a symbol naming the context, and
22348 two positions indicating start and end of the context. Possible
22349 contexts are:
22351 :headline anywhere in a headline
22352 :headline-stars on the leading stars in a headline
22353 :todo-keyword on a TODO keyword (including DONE) in a headline
22354 :tags on the TAGS in a headline
22355 :priority on the priority cookie in a headline
22356 :item on the first line of a plain list item
22357 :item-bullet on the bullet/number of a plain list item
22358 :checkbox on the checkbox in a plain list item
22359 :table in an org-mode table
22360 :table-special on a special filed in a table
22361 :table-table in a table.el table
22362 :clocktable in a clocktable
22363 :src-block in a source block
22364 :link on a hyperlink
22365 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22366 :target on a <<target>>
22367 :radio-target on a <<<radio-target>>>
22368 :latex-fragment on a LaTeX fragment
22369 :latex-preview on a LaTeX fragment with overlaid preview image
22371 This function expects the position to be visible because it uses font-lock
22372 faces as a help to recognize the following contexts: :table-special, :link,
22373 and :keyword."
22374 (let* ((f (get-text-property (point) 'face))
22375 (faces (if (listp f) f (list f)))
22376 (case-fold-search t)
22377 (p (point)) clist o)
22378 ;; First the large context
22379 (cond
22380 ((org-at-heading-p t)
22381 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22382 (when (progn
22383 (beginning-of-line 1)
22384 (looking-at org-todo-line-tags-regexp))
22385 (push (org-point-in-group p 1 :headline-stars) clist)
22386 (push (org-point-in-group p 2 :todo-keyword) clist)
22387 (push (org-point-in-group p 4 :tags) clist))
22388 (goto-char p)
22389 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22390 (when (looking-at "\\[#[A-Z0-9]\\]")
22391 (push (org-point-in-group p 0 :priority) clist)))
22393 ((org-at-item-p)
22394 (push (org-point-in-group p 2 :item-bullet) clist)
22395 (push (list :item (point-at-bol)
22396 (save-excursion (org-end-of-item) (point)))
22397 clist)
22398 (and (org-at-item-checkbox-p)
22399 (push (org-point-in-group p 0 :checkbox) clist)))
22401 ((org-at-table-p)
22402 (push (list :table (org-table-begin) (org-table-end)) clist)
22403 (when (memq 'org-formula faces)
22404 (push (list :table-special
22405 (previous-single-property-change p 'face)
22406 (next-single-property-change p 'face)) clist)))
22407 ((org-at-table-p 'any)
22408 (push (list :table-table) clist)))
22409 (goto-char p)
22411 (let ((case-fold-search t))
22412 ;; New the "medium" contexts: clocktables, source blocks
22413 (cond ((org-in-clocktable-p)
22414 (push (list :clocktable
22415 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22416 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22417 (match-beginning 1))
22418 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22419 (match-end 0))) clist))
22420 ((org-in-src-block-p)
22421 (push (list :src-block
22422 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22423 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22424 (match-beginning 1))
22425 (and (search-forward "#+END_SRC" nil t)
22426 (match-beginning 0))) clist))))
22427 (goto-char p)
22429 ;; Now the small context
22430 (cond
22431 ((org-at-timestamp-p)
22432 (push (org-point-in-group p 0 :timestamp) clist))
22433 ((memq 'org-link faces)
22434 (push (list :link
22435 (previous-single-property-change p 'face)
22436 (next-single-property-change p 'face)) clist))
22437 ((memq 'org-special-keyword faces)
22438 (push (list :keyword
22439 (previous-single-property-change p 'face)
22440 (next-single-property-change p 'face)) clist))
22441 ((org-at-target-p)
22442 (push (org-point-in-group p 0 :target) clist)
22443 (goto-char (1- (match-beginning 0)))
22444 (when (looking-at org-radio-target-regexp)
22445 (push (org-point-in-group p 0 :radio-target) clist))
22446 (goto-char p))
22447 ((setq o (cl-some
22448 (lambda (o)
22449 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22451 (overlays-at (point))))
22452 (push (list :latex-fragment
22453 (overlay-start o) (overlay-end o)) clist)
22454 (push (list :latex-preview
22455 (overlay-start o) (overlay-end o)) clist))
22456 ((org-inside-LaTeX-fragment-p)
22457 ;; FIXME: positions wrong.
22458 (push (list :latex-fragment (point) (point)) clist)))
22460 (setq clist (nreverse (delq nil clist)))
22461 clist))
22463 (defun org-in-regexp (regexp &optional nlines visually)
22464 "Check if point is inside a match of REGEXP.
22466 Normally only the current line is checked, but you can include
22467 NLINES extra lines around point into the search. If VISUALLY is
22468 set, require that the cursor is not after the match but really
22469 on, so that the block visually is on the match.
22471 Return nil or a cons cell (BEG . END) where BEG and END are,
22472 respectively, the positions at the beginning and the end of the
22473 match."
22474 (catch :exit
22475 (let ((pos (point))
22476 (eol (line-end-position (if nlines (1+ nlines) 1))))
22477 (save-excursion
22478 (beginning-of-line (- 1 (or nlines 0)))
22479 (while (and (re-search-forward regexp eol t)
22480 (<= (match-beginning 0) pos))
22481 (let ((end (match-end 0)))
22482 (when (or (> end pos) (and (= end pos) (not visually)))
22483 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22484 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22485 "Org mode 8.3")
22487 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22488 "Non-nil when point is between matches of START-RE and END-RE.
22490 Also return a non-nil value when point is on one of the matches.
22492 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22493 buffer positions. Default values are the positions of headlines
22494 surrounding the point.
22496 The functions returns a cons cell whose car (resp. cdr) is the
22497 position before START-RE (resp. after END-RE)."
22498 (save-match-data
22499 (let ((pos (point))
22500 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22501 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22502 beg end)
22503 (save-excursion
22504 ;; Point is on a block when on START-RE or if START-RE can be
22505 ;; found before it...
22506 (and (or (org-in-regexp start-re)
22507 (re-search-backward start-re limit-up t))
22508 (setq beg (match-beginning 0))
22509 ;; ... and END-RE after it...
22510 (goto-char (match-end 0))
22511 (re-search-forward end-re limit-down t)
22512 (> (setq end (match-end 0)) pos)
22513 ;; ... without another START-RE in-between.
22514 (goto-char (match-beginning 0))
22515 (not (re-search-backward start-re (1+ beg) t))
22516 ;; Return value.
22517 (cons beg end))))))
22519 (defun org-in-block-p (names)
22520 "Non-nil when point belongs to a block whose name belongs to NAMES.
22522 NAMES is a list of strings containing names of blocks.
22524 Return first block name matched, or nil. Beware that in case of
22525 nested blocks, the returned name may not belong to the closest
22526 block from point."
22527 (save-match-data
22528 (catch 'exit
22529 (let ((case-fold-search t)
22530 (lim-up (save-excursion (outline-previous-heading)))
22531 (lim-down (save-excursion (outline-next-heading))))
22532 (dolist (name names)
22533 (let ((n (regexp-quote name)))
22534 (when (org-between-regexps-p
22535 (concat "^[ \t]*#\\+begin_" n)
22536 (concat "^[ \t]*#\\+end_" n)
22537 lim-up lim-down)
22538 (throw 'exit n)))))
22539 nil)))
22541 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22542 "Call `multi-occur' with buffers for all agenda files."
22543 (interactive "sOrg-files matching: ")
22544 (let* ((files (org-agenda-files))
22545 (tnames (mapcar #'file-truename files))
22546 (extra org-agenda-text-search-extra-files))
22547 (when (eq (car extra) 'agenda-archives)
22548 (setq extra (cdr extra))
22549 (setq files (org-add-archive-files files)))
22550 (dolist (f extra)
22551 (unless (member (file-truename f) tnames)
22552 (unless (member f files) (setq files (append files (list f))))
22553 (setq tnames (append tnames (list (file-truename f))))))
22554 (multi-occur
22555 (mapcar (lambda (x)
22556 (with-current-buffer
22557 ;; FIXME: Why not just (find-file-noselect x)?
22558 ;; Is it to avoid the "revert buffer" prompt?
22559 (or (get-file-buffer x) (find-file-noselect x))
22560 (widen)
22561 (current-buffer)))
22562 files)
22563 regexp)))
22565 (if (boundp 'occur-mode-find-occurrence-hook)
22566 ;; Emacs 23
22567 (add-hook 'occur-mode-find-occurrence-hook
22568 (lambda ()
22569 (when (derived-mode-p 'org-mode)
22570 (org-reveal))))
22571 ;; Emacs 22
22572 (defadvice occur-mode-goto-occurrence
22573 (after org-occur-reveal activate)
22574 (and (derived-mode-p 'org-mode) (org-reveal)))
22575 (defadvice occur-mode-goto-occurrence-other-window
22576 (after org-occur-reveal activate)
22577 (and (derived-mode-p 'org-mode) (org-reveal)))
22578 (defadvice occur-mode-display-occurrence
22579 (after org-occur-reveal activate)
22580 (when (derived-mode-p 'org-mode)
22581 (let ((pos (occur-mode-find-occurrence)))
22582 (with-current-buffer (marker-buffer pos)
22583 (save-excursion
22584 (goto-char pos)
22585 (org-reveal)))))))
22587 (defun org-occur-link-in-agenda-files ()
22588 "Create a link and search for it in the agendas.
22589 The link is not stored in `org-stored-links', it is just created
22590 for the search purpose."
22591 (interactive)
22592 (let ((link (condition-case nil
22593 (org-store-link nil)
22594 (error "Unable to create a link to here"))))
22595 (org-occur-in-agenda-files (regexp-quote link))))
22597 (defun org-reverse-string (string)
22598 "Return the reverse of STRING."
22599 (apply 'string (reverse (string-to-list string))))
22601 ;; defsubst org-uniquify must be defined before first use
22603 (defun org-uniquify-alist (alist)
22604 "Merge elements of ALIST with the same key.
22606 For example, in this alist:
22608 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22609 => \\='((a 1 3) (b 2))
22611 merge (a 1) and (a 3) into (a 1 3).
22613 The function returns the new ALIST."
22614 (let (rtn)
22615 (dolist (e alist rtn)
22616 (let (n)
22617 (if (not (assoc (car e) rtn))
22618 (push e rtn)
22619 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22620 (setq rtn (assq-delete-all (car e) rtn))
22621 (push n rtn))))))
22623 (defun org-delete-all (elts list)
22624 "Remove all elements in ELTS from LIST."
22625 (while elts
22626 (setq list (delete (pop elts) list)))
22627 list)
22629 (defun org-back-over-empty-lines ()
22630 "Move backwards over whitespace, to the beginning of the first empty line.
22631 Returns the number of empty lines passed."
22632 (let ((pos (point)))
22633 (if (cdr (assoc 'heading org-blank-before-new-entry))
22634 (skip-chars-backward " \t\n\r")
22635 (unless (eobp)
22636 (forward-line -1)))
22637 (beginning-of-line 2)
22638 (goto-char (min (point) pos))
22639 (count-lines (point) pos)))
22641 (defun org-skip-whitespace ()
22642 (skip-chars-forward " \t\n\r"))
22644 (defun org-point-in-group (point group &optional context)
22645 "Check if POINT is in match-group GROUP.
22646 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22647 match. If the match group does not exist or point is not inside it,
22648 return nil."
22649 (and (match-beginning group)
22650 (>= point (match-beginning group))
22651 (<= point (match-end group))
22652 (if context
22653 (list context (match-beginning group) (match-end group))
22654 t)))
22656 (defun org-switch-to-buffer-other-window (&rest args)
22657 "Switch to buffer in a second window on the current frame.
22658 In particular, do not allow pop-up frames.
22659 Returns the newly created buffer."
22660 (org-no-popups
22661 (apply 'switch-to-buffer-other-window args)))
22663 (defun org-combine-plists (&rest plists)
22664 "Create a single property list from all plists in PLISTS.
22665 The process starts by copying the first list, and then setting properties
22666 from the other lists. Settings in the last list are the most significant
22667 ones and overrule settings in the other lists."
22668 (let ((rtn (copy-sequence (pop plists)))
22669 p v ls)
22670 (while plists
22671 (setq ls (pop plists))
22672 (while ls
22673 (setq p (pop ls) v (pop ls))
22674 (setq rtn (plist-put rtn p v))))
22675 rtn))
22677 (defun org-replace-escapes (string table)
22678 "Replace %-escapes in STRING with values in TABLE.
22679 TABLE is an association list with keys like \"%a\" and string values.
22680 The sequences in STRING may contain normal field width and padding information,
22681 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22682 so values can contain further %-escapes if they are define later in TABLE."
22683 (let ((tbl (copy-alist table))
22684 (case-fold-search nil)
22685 (pchg 0)
22686 re rpl)
22687 (dolist (e tbl)
22688 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22689 (when (and (cdr e) (string-match re (cdr e)))
22690 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22691 (safe "SREF"))
22692 (add-text-properties 0 3 (list 'sref sref) safe)
22693 (setcdr e (replace-match safe t t (cdr e)))))
22694 (while (string-match re string)
22695 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22696 (cdr e)))
22697 (setq string (replace-match rpl t t string))))
22698 (while (setq pchg (next-property-change pchg string))
22699 (let ((sref (get-text-property pchg 'sref string)))
22700 (when (and sref (string-match "SREF" string pchg))
22701 (setq string (replace-match sref t t string)))))
22702 string))
22704 (defun org-sublist (list start end)
22705 "Return a section of LIST, from START to END.
22707 Counting starts at 1."
22708 (cl-subseq list (1- start) end))
22709 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22711 (defun org-find-base-buffer-visiting (file)
22712 "Like `find-buffer-visiting' but always return the base buffer and
22713 not an indirect buffer."
22714 (let ((buf (or (get-file-buffer file)
22715 (find-buffer-visiting file))))
22716 (if buf
22717 (or (buffer-base-buffer buf) buf)
22718 nil)))
22720 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22721 "Org 9.0")
22723 ;;; TODO: Only called once, from ox-odt which should probably use
22724 ;;; org-export-inline-image-p or something.
22725 (defun org-file-image-p (file)
22726 "Return non-nil if FILE is an image."
22727 (save-match-data
22728 (string-match (image-file-name-regexp) file)))
22730 (defun org-get-cursor-date (&optional with-time)
22731 "Return the date at cursor in as a time.
22732 This works in the calendar and in the agenda, anywhere else it just
22733 returns the current time.
22734 If WITH-TIME is non-nil, returns the time of the event at point (in
22735 the agenda) or the current time of the day."
22736 (let (date day defd tp hod mod)
22737 (when with-time
22738 (setq tp (get-text-property (point) 'time))
22739 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22740 (setq hod (string-to-number (match-string 1 tp))
22741 mod (string-to-number (match-string 2 tp))))
22742 (or tp (let ((now (decode-time)))
22743 (setq hod (nth 2 now)
22744 mod (nth 1 now)))))
22745 (cond
22746 ((eq major-mode 'calendar-mode)
22747 (setq date (calendar-cursor-to-date)
22748 defd (encode-time 0 (or mod 0) (or hod 0)
22749 (nth 1 date) (nth 0 date) (nth 2 date))))
22750 ((eq major-mode 'org-agenda-mode)
22751 (setq day (get-text-property (point) 'day))
22752 (when day
22753 (setq date (calendar-gregorian-from-absolute day)
22754 defd (encode-time 0 (or mod 0) (or hod 0)
22755 (nth 1 date) (nth 0 date) (nth 2 date))))))
22756 (or defd (current-time))))
22758 (defun org-mark-subtree (&optional up)
22759 "Mark the current subtree.
22760 This puts point at the start of the current subtree, and mark at
22761 the end. If a numeric prefix UP is given, move up into the
22762 hierarchy of headlines by UP levels before marking the subtree."
22763 (interactive "P")
22764 (org-with-limited-levels
22765 (cond ((org-at-heading-p) (beginning-of-line))
22766 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22767 (t (outline-previous-visible-heading 1))))
22768 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22769 (if (org-called-interactively-p 'any)
22770 (call-interactively 'org-mark-element)
22771 (org-mark-element)))
22774 ;;; Indentation
22776 (defun org--get-expected-indentation (element contentsp)
22777 "Expected indentation column for current line, according to ELEMENT.
22778 ELEMENT is an element containing point. CONTENTSP is non-nil
22779 when indentation is to be computed according to contents of
22780 ELEMENT."
22781 (let ((type (org-element-type element))
22782 (start (org-element-property :begin element))
22783 (post-affiliated (org-element-property :post-affiliated element)))
22784 (org-with-wide-buffer
22785 (cond
22786 (contentsp
22787 (cl-case type
22788 ((diary-sexp footnote-definition) 0)
22789 ((headline inlinetask nil)
22790 (if (not org-adapt-indentation) 0
22791 (let ((level (org-current-level)))
22792 (if level (1+ level) 0))))
22793 ((item plain-list) (org-list-item-body-column post-affiliated))
22795 (goto-char start)
22796 (org-get-indentation))))
22797 ((memq type '(headline inlinetask nil))
22798 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22799 (org--get-expected-indentation element t)
22801 ((memq type '(diary-sexp footnote-definition)) 0)
22802 ;; First paragraph of a footnote definition or an item.
22803 ;; Indent like parent.
22804 ((< (line-beginning-position) start)
22805 (org--get-expected-indentation
22806 (org-element-property :parent element) t))
22807 ;; At first line: indent according to previous sibling, if any,
22808 ;; ignoring footnote definitions and inline tasks, or parent's
22809 ;; contents.
22810 ((= (line-beginning-position) start)
22811 (catch 'exit
22812 (while t
22813 (if (= (point-min) start) (throw 'exit 0)
22814 (goto-char (1- start))
22815 (let* ((previous (org-element-at-point))
22816 (parent previous))
22817 (while (and parent (<= (org-element-property :end parent) start))
22818 (setq previous parent
22819 parent (org-element-property :parent parent)))
22820 (cond
22821 ((not previous) (throw 'exit 0))
22822 ((> (org-element-property :end previous) start)
22823 (throw 'exit (org--get-expected-indentation previous t)))
22824 ((memq (org-element-type previous)
22825 '(footnote-definition inlinetask))
22826 (setq start (org-element-property :begin previous)))
22827 (t (goto-char (org-element-property :begin previous))
22828 (throw 'exit
22829 (if (bolp) (org-get-indentation)
22830 ;; At first paragraph in an item or
22831 ;; a footnote definition.
22832 (org--get-expected-indentation
22833 (org-element-property :parent previous) t))))))))))
22834 ;; Otherwise, move to the first non-blank line above.
22836 (beginning-of-line)
22837 (let ((pos (point)))
22838 (skip-chars-backward " \r\t\n")
22839 (cond
22840 ;; Two blank lines end a footnote definition or a plain
22841 ;; list. When we indent an empty line after them, the
22842 ;; containing list or footnote definition is over, so it
22843 ;; qualifies as a previous sibling. Therefore, we indent
22844 ;; like its first line.
22845 ((and (memq type '(footnote-definition plain-list))
22846 (> (count-lines (point) pos) 2))
22847 (goto-char start)
22848 (org-get-indentation))
22849 ;; Line above is the first one of a paragraph at the
22850 ;; beginning of an item or a footnote definition. Indent
22851 ;; like parent.
22852 ((< (line-beginning-position) start)
22853 (org--get-expected-indentation
22854 (org-element-property :parent element) t))
22855 ;; Line above is the beginning of an element, i.e., point
22856 ;; was originally on the blank lines between element's start
22857 ;; and contents.
22858 ((= (line-beginning-position) post-affiliated)
22859 (org--get-expected-indentation element t))
22860 ;; POS is after contents in a greater element. Indent like
22861 ;; the beginning of the element.
22863 ;; As a special case, if point is at the end of a footnote
22864 ;; definition or an item, indent like the very last element
22865 ;; within. If that last element is an item, indent like its
22866 ;; contents.
22867 ((and (not (eq type 'paragraph))
22868 (let ((cend (org-element-property :contents-end element)))
22869 (and cend (<= cend pos))))
22870 (if (memq type '(footnote-definition item plain-list))
22871 (let ((last (org-element-at-point)))
22872 (org--get-expected-indentation
22873 last (eq (org-element-type last) 'item)))
22874 (goto-char start)
22875 (org-get-indentation)))
22876 ;; In any other case, indent like the current line.
22877 (t (org-get-indentation)))))))))
22879 (defun org--align-node-property ()
22880 "Align node property at point.
22881 Alignment is done according to `org-property-format', which see."
22882 (when (save-excursion
22883 (beginning-of-line)
22884 (looking-at org-property-re))
22885 (replace-match
22886 (concat (match-string 4)
22887 (org-trim
22888 (format org-property-format (match-string 1) (match-string 3))))
22889 t t)))
22891 (defun org-indent-line ()
22892 "Indent line depending on context.
22894 Indentation is done according to the following rules:
22896 - Footnote definitions, diary sexps, headlines and inline tasks
22897 have to start at column 0.
22899 - On the very first line of an element, consider, in order, the
22900 next rules until one matches:
22902 1. If there's a sibling element before, ignoring footnote
22903 definitions and inline tasks, indent like its first line.
22905 2. If element has a parent, indent like its contents. More
22906 precisely, if parent is an item, indent after the
22907 description part, if any, or the bullet (see
22908 `org-list-description-max-indent'). Else, indent like
22909 parent's first line.
22911 3. Otherwise, indent relatively to current level, if
22912 `org-adapt-indentation' is non-nil, or to left margin.
22914 - On a blank line at the end of an element, indent according to
22915 the type of the element. More precisely
22917 1. If element is a plain list, an item, or a footnote
22918 definition, indent like the very last element within.
22920 2. If element is a paragraph, indent like its last non blank
22921 line.
22923 3. Otherwise, indent like its very first line.
22925 - In the code part of a source block, use language major mode
22926 to indent current line if `org-src-tab-acts-natively' is
22927 non-nil. If it is nil, do nothing.
22929 - Otherwise, indent like the first non-blank line above.
22931 The function doesn't indent an item as it could break the whole
22932 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22933 \\[org-shiftmetaright].
22935 Also align node properties according to `org-property-format'."
22936 (interactive)
22937 (cond
22938 (orgstruct-is-++
22939 (let ((indent-line-function
22940 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22941 (indent-according-to-mode)))
22942 ((org-at-heading-p) 'noindent)
22944 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22945 (type (org-element-type element)))
22946 (cond ((and (memq type '(plain-list item))
22947 (= (line-beginning-position)
22948 (org-element-property :post-affiliated element)))
22949 'noindent)
22950 ((and (eq type 'src-block)
22951 org-src-tab-acts-natively
22952 (> (line-beginning-position)
22953 (org-element-property :post-affiliated element))
22954 (< (line-beginning-position)
22955 (org-with-wide-buffer
22956 (goto-char (org-element-property :end element))
22957 (skip-chars-backward " \r\t\n")
22958 (line-beginning-position))))
22959 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22961 (let ((column (org--get-expected-indentation element nil)))
22962 ;; Preserve current column.
22963 (if (<= (current-column) (current-indentation))
22964 (org-indent-line-to column)
22965 (save-excursion (org-indent-line-to column))))
22966 ;; Align node property. Also preserve current column.
22967 (when (eq type 'node-property)
22968 (let ((column (current-column)))
22969 (org--align-node-property)
22970 (org-move-to-column column)))))))))
22972 (defun org-indent-region (start end)
22973 "Indent each non-blank line in the region.
22974 Called from a program, START and END specify the region to
22975 indent. The function will not indent contents of example blocks,
22976 verse blocks and export blocks as leading white spaces are
22977 assumed to be significant there."
22978 (interactive "r")
22979 (save-excursion
22980 (goto-char start)
22981 (skip-chars-forward " \r\t\n")
22982 (unless (eobp) (beginning-of-line))
22983 (let ((indent-to
22984 (lambda (ind pos)
22985 ;; Set IND as indentation for all lines between point and
22986 ;; POS. Blank lines are ignored. Leave point after POS
22987 ;; once done.
22988 (let ((limit (copy-marker pos)))
22989 (while (< (point) limit)
22990 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22991 (forward-line))
22992 (set-marker limit nil))))
22993 (end (copy-marker end)))
22994 (while (< (point) end)
22995 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22996 (let* ((element (org-element-at-point))
22997 (type (org-element-type element))
22998 (element-end (copy-marker (org-element-property :end element)))
22999 (ind (org--get-expected-indentation element nil)))
23000 (cond
23001 ((or (memq type '(paragraph table table-row))
23002 (not (or (org-element-property :contents-begin element)
23003 (memq type
23004 '(example-block export-block src-block)))))
23005 ;; Elements here are indented as a single block. Also
23006 ;; align node properties.
23007 (when (eq type 'node-property)
23008 (org--align-node-property)
23009 (beginning-of-line))
23010 (funcall indent-to ind (min element-end end)))
23012 ;; Elements in this category consist of three parts:
23013 ;; before the contents, the contents, and after the
23014 ;; contents. The contents are treated specially,
23015 ;; according to the element type, or not indented at
23016 ;; all. Other parts are indented as a single block.
23017 (let* ((post (copy-marker
23018 (org-element-property :post-affiliated element)))
23019 (cbeg
23020 (copy-marker
23021 (cond
23022 ((not (org-element-property :contents-begin element))
23023 ;; Fake contents for source blocks.
23024 (org-with-wide-buffer
23025 (goto-char post)
23026 (forward-line)
23027 (point)))
23028 ((memq type '(footnote-definition item plain-list))
23029 ;; Contents in these elements could start on
23030 ;; the same line as the beginning of the
23031 ;; element. Make sure we start indenting
23032 ;; from the second line.
23033 (org-with-wide-buffer
23034 (goto-char post)
23035 (end-of-line)
23036 (skip-chars-forward " \r\t\n")
23037 (if (eobp) (point) (line-beginning-position))))
23038 (t (org-element-property :contents-begin element)))))
23039 (cend (copy-marker
23040 (or (org-element-property :contents-end element)
23041 ;; Fake contents for source blocks.
23042 (org-with-wide-buffer
23043 (goto-char element-end)
23044 (skip-chars-backward " \r\t\n")
23045 (line-beginning-position)))
23046 t)))
23047 ;; Do not change items indentation individually as it
23048 ;; might break the list as a whole. On the other
23049 ;; hand, when at a plain list, indent it as a whole.
23050 (cond ((eq type 'plain-list)
23051 (let ((offset (- ind (org-get-indentation))))
23052 (unless (zerop offset)
23053 (indent-rigidly (org-element-property :begin element)
23054 (org-element-property :end element)
23055 offset))
23056 (goto-char cbeg)))
23057 ((eq type 'item) (goto-char cbeg))
23058 (t (funcall indent-to ind (min cbeg end))))
23059 (when (< (point) end)
23060 (cl-case type
23061 ((example-block export-block verse-block))
23062 (src-block
23063 ;; In a source block, indent source code
23064 ;; according to language major mode, but only if
23065 ;; `org-src-tab-acts-natively' is non-nil.
23066 (when (and (< (point) end) org-src-tab-acts-natively)
23067 (ignore-errors
23068 (org-babel-do-in-edit-buffer
23069 (indent-region (point-min) (point-max))))))
23070 (t (org-indent-region (point) (min cend end))))
23071 (goto-char (min cend end))
23072 (when (< (point) end)
23073 (funcall indent-to ind (min element-end end))))
23074 (set-marker post nil)
23075 (set-marker cbeg nil)
23076 (set-marker cend nil))))
23077 (set-marker element-end nil))))
23078 (set-marker end nil))))
23080 (defun org-indent-drawer ()
23081 "Indent the drawer at point."
23082 (interactive)
23083 (unless (save-excursion
23084 (beginning-of-line)
23085 (org-looking-at-p org-drawer-regexp))
23086 (user-error "Not at a drawer"))
23087 (let ((element (org-element-at-point)))
23088 (unless (memq (org-element-type element) '(drawer property-drawer))
23089 (user-error "Not at a drawer"))
23090 (org-with-wide-buffer
23091 (org-indent-region (org-element-property :begin element)
23092 (org-element-property :end element))))
23093 (message "Drawer at point indented"))
23095 (defun org-indent-block ()
23096 "Indent the block at point."
23097 (interactive)
23098 (unless (save-excursion
23099 (beginning-of-line)
23100 (let ((case-fold-search t))
23101 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23102 (user-error "Not at a block"))
23103 (let ((element (org-element-at-point)))
23104 (unless (memq (org-element-type element)
23105 '(comment-block center-block dynamic-block example-block
23106 export-block quote-block special-block
23107 src-block verse-block))
23108 (user-error "Not at a block"))
23109 (org-with-wide-buffer
23110 (org-indent-region (org-element-property :begin element)
23111 (org-element-property :end element))))
23112 (message "Block at point indented"))
23115 ;;; Filling
23117 ;; We use our own fill-paragraph and auto-fill functions.
23119 ;; `org-fill-paragraph' relies on adaptive filling and context
23120 ;; checking. Appropriate `fill-prefix' is computed with
23121 ;; `org-adaptive-fill-function'.
23123 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23124 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23125 ;; `org-adaptive-fill-function' value. Internally,
23126 ;; `org-comment-line-break-function' breaks the line.
23128 ;; `org-setup-filling' installs filling and auto-filling related
23129 ;; variables during `org-mode' initialization.
23131 (defvar org-element-paragraph-separate) ; org-element.el
23132 (defun org-setup-filling ()
23133 (require 'org-element)
23134 ;; Prevent auto-fill from inserting unwanted new items.
23135 (when (boundp 'fill-nobreak-predicate)
23136 (setq-local
23137 fill-nobreak-predicate
23138 (org-uniquify
23139 (append fill-nobreak-predicate
23140 '(org-fill-line-break-nobreak-p
23141 org-fill-paragraph-with-timestamp-nobreak-p)))))
23142 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23143 (setq-local paragraph-start paragraph-ending)
23144 (setq-local paragraph-separate paragraph-ending))
23145 (setq-local fill-paragraph-function 'org-fill-paragraph)
23146 (setq-local auto-fill-inhibit-regexp nil)
23147 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23148 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23149 (setq-local comment-line-break-function 'org-comment-line-break-function))
23151 (defun org-fill-line-break-nobreak-p ()
23152 "Non-nil when a new line at point would create an Org line break."
23153 (save-excursion
23154 (skip-chars-backward "[ \t]")
23155 (skip-chars-backward "\\\\")
23156 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23158 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23159 "Non-nil when a new line at point would split a timestamp."
23160 (and (org-at-timestamp-p t)
23161 (not (looking-at org-ts-regexp-both))))
23163 (declare-function message-in-body-p "message" ())
23164 (defvar orgtbl-line-start-regexp) ; From org-table.el
23165 (defun org-adaptive-fill-function ()
23166 "Compute a fill prefix for the current line.
23167 Return fill prefix, as a string, or nil if current line isn't
23168 meant to be filled. For convenience, if `adaptive-fill-regexp'
23169 matches in paragraphs or comments, use it."
23170 (catch 'exit
23171 (when (derived-mode-p 'message-mode)
23172 (save-excursion
23173 (beginning-of-line)
23174 (cond ((not (message-in-body-p)) (throw 'exit nil))
23175 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23176 ((looking-at message-cite-prefix-regexp)
23177 (throw 'exit (match-string-no-properties 0)))
23178 ((looking-at org-outline-regexp)
23179 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23180 (org-with-wide-buffer
23181 (unless (org-at-heading-p)
23182 (let* ((p (line-beginning-position))
23183 (element (save-excursion
23184 (beginning-of-line)
23185 (org-element-at-point)))
23186 (type (org-element-type element))
23187 (post-affiliated (org-element-property :post-affiliated element)))
23188 (unless (< p post-affiliated)
23189 (cl-case type
23190 (comment
23191 (save-excursion
23192 (beginning-of-line)
23193 (looking-at "[ \t]*")
23194 (concat (match-string 0) "# ")))
23195 (footnote-definition "")
23196 ((item plain-list)
23197 (make-string (org-list-item-body-column post-affiliated) ?\s))
23198 (paragraph
23199 ;; Fill prefix is usually the same as the current line,
23200 ;; unless the paragraph is at the beginning of an item.
23201 (let ((parent (org-element-property :parent element)))
23202 (save-excursion
23203 (beginning-of-line)
23204 (cond ((eq (org-element-type parent) 'item)
23205 (make-string (org-list-item-body-column
23206 (org-element-property :begin parent))
23207 ?\s))
23208 ((and adaptive-fill-regexp
23209 ;; Locally disable
23210 ;; `adaptive-fill-function' to let
23211 ;; `fill-context-prefix' handle
23212 ;; `adaptive-fill-regexp' variable.
23213 (let (adaptive-fill-function)
23214 (fill-context-prefix
23215 post-affiliated
23216 (org-element-property :end element)))))
23217 ((looking-at "[ \t]+") (match-string 0))
23218 (t "")))))
23219 (comment-block
23220 ;; Only fill contents if P is within block boundaries.
23221 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23222 (forward-line)
23223 (point)))
23224 (cend (save-excursion
23225 (goto-char (org-element-property :end element))
23226 (skip-chars-backward " \r\t\n")
23227 (line-beginning-position))))
23228 (when (and (>= p cbeg) (< p cend))
23229 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23230 (match-string 0)
23231 "")))))))))))
23233 (declare-function message-goto-body "message" ())
23234 (defvar message-cite-prefix-regexp) ; From message.el
23235 (defun org-fill-paragraph (&optional justify)
23236 "Fill element at point, when applicable.
23238 This function only applies to comment blocks, comments, example
23239 blocks and paragraphs. Also, as a special case, re-align table
23240 when point is at one.
23242 If JUSTIFY is non-nil (interactively, with prefix argument),
23243 justify as well. If `sentence-end-double-space' is non-nil, then
23244 period followed by one space does not end a sentence, so don't
23245 break a line there. The variable `fill-column' controls the
23246 width for filling.
23248 For convenience, when point is at a plain list, an item or
23249 a footnote definition, try to fill the first paragraph within."
23250 (interactive)
23251 (if (and (derived-mode-p 'message-mode)
23252 (or (not (message-in-body-p))
23253 (save-excursion (move-beginning-of-line 1)
23254 (looking-at message-cite-prefix-regexp))))
23255 ;; First ensure filling is correct in message-mode.
23256 (let ((fill-paragraph-function
23257 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23258 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23259 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23260 (paragraph-separate
23261 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23262 (fill-paragraph nil))
23263 (with-syntax-table org-mode-transpose-word-syntax-table
23264 ;; Move to end of line in order to get the first paragraph
23265 ;; within a plain list or a footnote definition.
23266 (let ((element (save-excursion
23267 (end-of-line)
23268 (or (ignore-errors (org-element-at-point))
23269 (user-error "An element cannot be parsed line %d"
23270 (line-number-at-pos (point)))))))
23271 ;; First check if point is in a blank line at the beginning of
23272 ;; the buffer. In that case, ignore filling.
23273 (cl-case (org-element-type element)
23274 ;; Use major mode filling function is src blocks.
23275 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23276 ;; Align Org tables, leave table.el tables as-is.
23277 (table-row (org-table-align) t)
23278 (table
23279 (when (eq (org-element-property :type element) 'org)
23280 (save-excursion
23281 (goto-char (org-element-property :post-affiliated element))
23282 (org-table-align)))
23284 (paragraph
23285 ;; Paragraphs may contain `line-break' type objects.
23286 (let ((beg (max (point-min)
23287 (org-element-property :contents-begin element)))
23288 (end (min (point-max)
23289 (org-element-property :contents-end element))))
23290 ;; Do nothing if point is at an affiliated keyword.
23291 (if (< (line-end-position) beg) t
23292 (when (derived-mode-p 'message-mode)
23293 ;; In `message-mode', do not fill following citation
23294 ;; in current paragraph nor text before message body.
23295 (let ((body-start (save-excursion (message-goto-body))))
23296 (when body-start (setq beg (max body-start beg))))
23297 (when (save-excursion
23298 (re-search-forward
23299 (concat "^" message-cite-prefix-regexp) end t))
23300 (setq end (match-beginning 0))))
23301 ;; Fill paragraph, taking line breaks into account.
23302 (save-excursion
23303 (goto-char beg)
23304 (let ((cuts (list beg)))
23305 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23306 (when (eq 'line-break
23307 (org-element-type
23308 (save-excursion (backward-char)
23309 (org-element-context))))
23310 (push (point) cuts)))
23311 (dolist (c (delq end cuts))
23312 (fill-region-as-paragraph c end justify)
23313 (setq end c))))
23314 t)))
23315 ;; Contents of `comment-block' type elements should be
23316 ;; filled as plain text, but only if point is within block
23317 ;; markers.
23318 (comment-block
23319 (let* ((case-fold-search t)
23320 (beg (save-excursion
23321 (goto-char (org-element-property :begin element))
23322 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23323 (forward-line)
23324 (point)))
23325 (end (save-excursion
23326 (goto-char (org-element-property :end element))
23327 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23328 (line-beginning-position))))
23329 (if (or (< (point) beg) (> (point) end)) t
23330 (fill-region-as-paragraph
23331 (save-excursion (end-of-line)
23332 (re-search-backward "^[ \t]*$" beg 'move)
23333 (line-beginning-position))
23334 (save-excursion (beginning-of-line)
23335 (re-search-forward "^[ \t]*$" end 'move)
23336 (line-beginning-position))
23337 justify))))
23338 ;; Fill comments.
23339 (comment
23340 (let ((begin (org-element-property :post-affiliated element))
23341 (end (org-element-property :end element)))
23342 (when (and (>= (point) begin) (<= (point) end))
23343 (let ((begin (save-excursion
23344 (end-of-line)
23345 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23346 (progn (forward-line) (point))
23347 begin)))
23348 (end (save-excursion
23349 (end-of-line)
23350 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23351 (1- (line-beginning-position))
23352 (skip-chars-backward " \r\t\n")
23353 (line-end-position)))))
23354 ;; Do not fill comments when at a blank line.
23355 (when (> end begin)
23356 (let ((fill-prefix
23357 (save-excursion
23358 (beginning-of-line)
23359 (looking-at "[ \t]*#")
23360 (let ((comment-prefix (match-string 0)))
23361 (goto-char (match-end 0))
23362 (if (looking-at adaptive-fill-regexp)
23363 (concat comment-prefix (match-string 0))
23364 (concat comment-prefix " "))))))
23365 (save-excursion
23366 (fill-region-as-paragraph begin end justify))))))
23368 ;; Ignore every other element.
23369 (otherwise t))))))
23371 (defun org-auto-fill-function ()
23372 "Auto-fill function."
23373 ;; Check if auto-filling is meaningful.
23374 (let ((fc (current-fill-column)))
23375 (when (and fc (> (current-column) fc))
23376 (let* ((fill-prefix (org-adaptive-fill-function))
23377 ;; Enforce empty fill prefix, if required. Otherwise, it
23378 ;; will be computed again.
23379 (adaptive-fill-mode (not (equal fill-prefix ""))))
23380 (when fill-prefix (do-auto-fill))))))
23382 (defun org-comment-line-break-function (&optional soft)
23383 "Break line at point and indent, continuing comment if within one.
23384 The inserted newline is marked hard if variable
23385 `use-hard-newlines' is true, unless optional argument SOFT is
23386 non-nil."
23387 (if soft (insert-and-inherit ?\n) (newline 1))
23388 (save-excursion (forward-char -1) (delete-horizontal-space))
23389 (delete-horizontal-space)
23390 (indent-to-left-margin)
23391 (insert-before-markers-and-inherit fill-prefix))
23394 ;;; Fixed Width Areas
23396 (defun org-toggle-fixed-width ()
23397 "Toggle fixed-width markup.
23399 Add or remove fixed-width markup on current line, whenever it
23400 makes sense. Return an error otherwise.
23402 If a region is active and if it contains only fixed-width areas
23403 or blank lines, remove all fixed-width markup in it. If the
23404 region contains anything else, convert all non-fixed-width lines
23405 to fixed-width ones.
23407 Blank lines at the end of the region are ignored unless the
23408 region only contains such lines."
23409 (interactive)
23410 (if (not (org-region-active-p))
23411 ;; No region:
23413 ;; Remove fixed width marker only in a fixed-with element.
23415 ;; Add fixed width maker in paragraphs, in blank lines after
23416 ;; elements or at the beginning of a headline or an inlinetask,
23417 ;; and before any one-line elements (e.g., a clock).
23418 (progn
23419 (beginning-of-line)
23420 (let* ((element (org-element-at-point))
23421 (type (org-element-type element)))
23422 (cond
23423 ((and (eq type 'fixed-width)
23424 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23425 (replace-match
23426 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23427 ((and (memq type '(babel-call clock comment diary-sexp headline
23428 horizontal-rule keyword paragraph
23429 planning))
23430 (<= (org-element-property :post-affiliated element) (point)))
23431 (skip-chars-forward " \t")
23432 (insert ": "))
23433 ((and (org-looking-at-p "[ \t]*$")
23434 (or (eq type 'inlinetask)
23435 (save-excursion
23436 (skip-chars-forward " \r\t\n")
23437 (<= (org-element-property :end element) (point)))))
23438 (delete-region (point) (line-end-position))
23439 (org-indent-line)
23440 (insert ": "))
23441 (t (user-error "Cannot insert a fixed-width line here")))))
23442 ;; Region active.
23443 (let* ((begin (save-excursion
23444 (goto-char (region-beginning))
23445 (line-beginning-position)))
23446 (end (copy-marker
23447 (save-excursion
23448 (goto-char (region-end))
23449 (unless (eolp) (beginning-of-line))
23450 (if (save-excursion (re-search-backward "\\S-" begin t))
23451 (progn (skip-chars-backward " \r\t\n") (point))
23452 (point)))))
23453 (all-fixed-width-p
23454 (catch 'not-all-p
23455 (save-excursion
23456 (goto-char begin)
23457 (skip-chars-forward " \r\t\n")
23458 (when (eobp) (throw 'not-all-p nil))
23459 (while (< (point) end)
23460 (let ((element (org-element-at-point)))
23461 (if (eq (org-element-type element) 'fixed-width)
23462 (goto-char (org-element-property :end element))
23463 (throw 'not-all-p nil))))
23464 t))))
23465 (if all-fixed-width-p
23466 (save-excursion
23467 (goto-char begin)
23468 (while (< (point) end)
23469 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23470 (replace-match
23471 "" nil nil nil
23472 (if (= (line-end-position) (match-end 0)) 0 1)))
23473 (forward-line)))
23474 (let ((min-ind (point-max)))
23475 ;; Find minimum indentation across all lines.
23476 (save-excursion
23477 (goto-char begin)
23478 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23479 (setq min-ind 0)
23480 (catch 'zerop
23481 (while (< (point) end)
23482 (unless (org-looking-at-p "[ \t]*$")
23483 (let ((ind (org-get-indentation)))
23484 (setq min-ind (min min-ind ind))
23485 (when (zerop ind) (throw 'zerop t))))
23486 (forward-line)))))
23487 ;; Loop over all lines and add fixed-width markup everywhere
23488 ;; but in fixed-width lines.
23489 (save-excursion
23490 (goto-char begin)
23491 (while (< (point) end)
23492 (cond
23493 ((org-at-heading-p)
23494 (insert ": ")
23495 (forward-line)
23496 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23497 (insert ":")
23498 (forward-line)))
23499 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23500 (let* ((element (org-element-at-point))
23501 (element-end (org-element-property :end element)))
23502 (if (eq (org-element-type element) 'fixed-width)
23503 (progn (goto-char element-end)
23504 (skip-chars-backward " \r\t\n")
23505 (forward-line))
23506 (let ((limit (min end element-end)))
23507 (while (< (point) limit)
23508 (org-move-to-column min-ind t)
23509 (insert ": ")
23510 (forward-line))))))
23512 (org-move-to-column min-ind t)
23513 (insert ": ")
23514 (forward-line)))))))
23515 (set-marker end nil))))
23518 ;;; Comments
23520 ;; Org comments syntax is quite complex. It requires the entire line
23521 ;; to be just a comment. Also, even with the right syntax at the
23522 ;; beginning of line, some some elements (i.e. verse-block or
23523 ;; example-block) don't accept comments. Usual Emacs comment commands
23524 ;; cannot cope with those requirements. Therefore, Org replaces them.
23526 ;; Org still relies on `comment-dwim', but cannot trust
23527 ;; `comment-only-p'. So, `comment-region-function' and
23528 ;; `uncomment-region-function' both point
23529 ;; to`org-comment-or-uncomment-region'. Eventually,
23530 ;; `org-insert-comment' takes care of insertion of comments at the
23531 ;; beginning of line.
23533 ;; `org-setup-comments-handling' install comments related variables
23534 ;; during `org-mode' initialization.
23536 (defun org-setup-comments-handling ()
23537 (interactive)
23538 (setq-local comment-use-syntax nil)
23539 (setq-local comment-start "# ")
23540 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23541 (setq-local comment-insert-comment-function 'org-insert-comment)
23542 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23543 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23545 (defun org-insert-comment ()
23546 "Insert an empty comment above current line.
23547 If the line is empty, insert comment at its beginning. When
23548 point is within a source block, comment according to the related
23549 major mode."
23550 (if (let ((element (org-element-at-point)))
23551 (and (eq (org-element-type element) 'src-block)
23552 (< (save-excursion
23553 (goto-char (org-element-property :post-affiliated element))
23554 (line-end-position))
23555 (point))
23556 (> (save-excursion
23557 (goto-char (org-element-property :end element))
23558 (skip-chars-backward " \r\t\n")
23559 (line-beginning-position))
23560 (point))))
23561 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23562 (beginning-of-line)
23563 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23564 (open-line 1))
23565 (org-indent-line)
23566 (insert "# ")))
23568 (defvar comment-empty-lines) ; From newcomment.el.
23569 (defun org-comment-or-uncomment-region (beg end &rest _)
23570 "Comment or uncomment each non-blank line in the region.
23571 Uncomment each non-blank line between BEG and END if it only
23572 contains commented lines. Otherwise, comment them. If region is
23573 strictly within a source block, use appropriate comment syntax."
23574 (if (let ((element (org-element-at-point)))
23575 (and (eq (org-element-type element) 'src-block)
23576 (< (save-excursion
23577 (goto-char (org-element-property :post-affiliated element))
23578 (line-end-position))
23579 beg)
23580 (>= (save-excursion
23581 (goto-char (org-element-property :end element))
23582 (skip-chars-backward " \r\t\n")
23583 (line-beginning-position))
23584 end)))
23585 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23586 (save-restriction
23587 ;; Restrict region
23588 (narrow-to-region (save-excursion (goto-char beg)
23589 (skip-chars-forward " \r\t\n" end)
23590 (line-beginning-position))
23591 (save-excursion (goto-char end)
23592 (skip-chars-backward " \r\t\n" beg)
23593 (line-end-position)))
23594 (let ((uncommentp
23595 ;; UNCOMMENTP is non-nil when every non blank line between
23596 ;; BEG and END is a comment.
23597 (save-excursion
23598 (goto-char (point-min))
23599 (while (and (not (eobp))
23600 (let ((element (org-element-at-point)))
23601 (and (eq (org-element-type element) 'comment)
23602 (goto-char (min (point-max)
23603 (org-element-property
23604 :end element)))))))
23605 (eobp))))
23606 (if uncommentp
23607 ;; Only blank lines and comments in region: uncomment it.
23608 (save-excursion
23609 (goto-char (point-min))
23610 (while (not (eobp))
23611 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23612 (replace-match "" nil nil nil 1))
23613 (forward-line)))
23614 ;; Comment each line in region.
23615 (let ((min-indent (point-max)))
23616 ;; First find the minimum indentation across all lines.
23617 (save-excursion
23618 (goto-char (point-min))
23619 (while (and (not (eobp)) (not (zerop min-indent)))
23620 (unless (looking-at "[ \t]*$")
23621 (setq min-indent (min min-indent (current-indentation))))
23622 (forward-line)))
23623 ;; Then loop over all lines.
23624 (save-excursion
23625 (goto-char (point-min))
23626 (while (not (eobp))
23627 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23628 ;; Don't get fooled by invisible text (e.g. link path)
23629 ;; when moving to column MIN-INDENT.
23630 (let ((buffer-invisibility-spec nil))
23631 (org-move-to-column min-indent t))
23632 (insert comment-start))
23633 (forward-line)))))))))
23635 (defun org-comment-dwim (_arg)
23636 "Call `comment-dwim' within a source edit buffer if needed."
23637 (interactive "*P")
23638 (if (org-in-src-block-p)
23639 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23640 (call-interactively 'comment-dwim)))
23643 ;;; Timestamps API
23645 ;; This section contains tools to operate on timestamp objects, as
23646 ;; returned by, e.g. `org-element-context'.
23648 (defun org-timestamp--to-internal-time (timestamp &optional end)
23649 "Encode TIMESTAMP object into Emacs internal time.
23650 Use end of date range or time range when END is non-nil."
23651 (apply #'encode-time
23652 (cons 0
23653 (mapcar
23654 (lambda (prop) (or (org-element-property prop timestamp) 0))
23655 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23656 '(:minute-start :hour-start :day-start :month-start
23657 :year-start))))))
23659 (defun org-timestamp-has-time-p (timestamp)
23660 "Non-nil when TIMESTAMP has a time specified."
23661 (org-element-property :hour-start timestamp))
23663 (defun org-timestamp-format (timestamp format &optional end utc)
23664 "Format a TIMESTAMP object into a string.
23666 FORMAT is a format specifier to be passed to
23667 `format-time-string'.
23669 When optional argument END is non-nil, use end of date-range or
23670 time-range, if possible.
23672 When optional argument UTC is non-nil, time will be expressed as
23673 Universal Time."
23674 (format-time-string
23675 format (org-timestamp--to-internal-time timestamp end) utc))
23677 (defun org-timestamp-split-range (timestamp &optional end)
23678 "Extract a TIMESTAMP object from a date or time range.
23680 END, when non-nil, means extract the end of the range.
23681 Otherwise, extract its start.
23683 Return a new timestamp object."
23684 (let ((type (org-element-property :type timestamp)))
23685 (if (memq type '(active inactive diary)) timestamp
23686 (let ((split-ts (org-element-copy timestamp)))
23687 ;; Set new type.
23688 (org-element-put-property
23689 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23690 ;; Copy start properties over end properties if END is
23691 ;; non-nil. Otherwise, copy end properties over `start' ones.
23692 (let ((p-alist '((:minute-start . :minute-end)
23693 (:hour-start . :hour-end)
23694 (:day-start . :day-end)
23695 (:month-start . :month-end)
23696 (:year-start . :year-end))))
23697 (dolist (p-cell p-alist)
23698 (org-element-put-property
23699 split-ts
23700 (funcall (if end #'car #'cdr) p-cell)
23701 (org-element-property
23702 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23703 ;; Eventually refresh `:raw-value'.
23704 (org-element-put-property split-ts :raw-value nil)
23705 (org-element-put-property
23706 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23708 (defun org-timestamp-translate (timestamp &optional boundary)
23709 "Translate TIMESTAMP object to custom format.
23711 Format string is defined in `org-time-stamp-custom-formats',
23712 which see.
23714 When optional argument BOUNDARY is non-nil, it is either the
23715 symbol `start' or `end'. In this case, only translate the
23716 starting or ending part of TIMESTAMP if it is a date or time
23717 range. Otherwise, translate both parts.
23719 Return timestamp as-is if `org-display-custom-times' is nil or if
23720 it has a `diary' type."
23721 (let ((type (org-element-property :type timestamp)))
23722 (if (or (not org-display-custom-times) (eq type 'diary))
23723 (org-element-interpret-data timestamp)
23724 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23725 org-time-stamp-custom-formats)))
23726 (if (and (not boundary) (memq type '(active-range inactive-range)))
23727 (concat (org-timestamp-format timestamp fmt)
23728 "--"
23729 (org-timestamp-format timestamp fmt t))
23730 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23734 ;;; Other stuff.
23736 (defvar reftex-docstruct-symbol)
23737 (defvar reftex-cite-format)
23738 (defvar org--rds)
23740 (defun org-reftex-citation ()
23741 "Use reftex-citation to insert a citation into the buffer.
23742 This looks for a line like
23744 #+BIBLIOGRAPHY: foo plain option:-d
23746 and derives from it that foo.bib is the bibliography file relevant
23747 for this document. It then installs the necessary environment for RefTeX
23748 to work in this buffer and calls `reftex-citation' to insert a citation
23749 into the buffer.
23751 Export of such citations to both LaTeX and HTML is handled by the contributed
23752 package ox-bibtex by Taru Karttunen."
23753 (interactive)
23754 (let ((reftex-docstruct-symbol 'org--rds)
23755 (reftex-cite-format "\\cite{%l}")
23756 org--rds bib)
23757 (save-excursion
23758 (save-restriction
23759 (widen)
23760 (let ((case-fold-search t)
23761 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23762 (if (not (save-excursion
23763 (or (re-search-forward re nil t)
23764 (re-search-backward re nil t))))
23765 (user-error "No bibliography defined in file")
23766 (setq bib (concat (match-string 1) ".bib")
23767 org--rds (list (list 'bib bib)))))))
23768 (call-interactively 'reftex-citation)))
23770 ;;;; Functions extending outline functionality
23772 (defun org-beginning-of-line (&optional arg)
23773 "Go to the beginning of the current line. If that is invisible, continue
23774 to a visible line beginning. This makes the function of C-a more intuitive.
23775 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23776 first attempt, and only move to after the tags when the cursor is already
23777 beyond the end of the headline."
23778 (interactive "P")
23779 (let ((pos (point))
23780 (special (if (consp org-special-ctrl-a/e)
23781 (car org-special-ctrl-a/e)
23782 org-special-ctrl-a/e))
23783 deactivate-mark refpos)
23784 (if (org-bound-and-true-p visual-line-mode)
23785 (beginning-of-visual-line 1)
23786 (beginning-of-line 1))
23787 (if (and arg (fboundp 'move-beginning-of-line))
23788 (call-interactively 'move-beginning-of-line)
23789 (unless (bobp)
23790 (backward-char 1)
23791 (if (org-truely-invisible-p)
23792 (while (and (not (bobp)) (org-truely-invisible-p))
23793 (backward-char 1)
23794 (beginning-of-line 1))
23795 (forward-char 1))))
23796 (when special
23797 (cond
23798 ((and (looking-at org-complex-heading-regexp)
23799 (eq (char-after (match-end 1)) ?\s))
23800 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23801 (point-at-eol)))
23802 (goto-char
23803 (if (eq special t)
23804 (cond ((> pos refpos) refpos)
23805 ((= pos (point)) refpos)
23806 (t (point)))
23807 (cond ((> pos (point)) (point))
23808 ((not (eq last-command this-command)) (point))
23809 (t refpos)))))
23810 ((org-at-item-p)
23811 ;; Being at an item and not looking at an the item means point
23812 ;; was previously moved to beginning of a visual line, which
23813 ;; doesn't contain the item. Therefore, do nothing special,
23814 ;; just stay here.
23815 (when (looking-at org-list-full-item-re)
23816 ;; Set special position at first white space character after
23817 ;; bullet, and check-box, if any.
23818 (let ((after-bullet
23819 (let ((box (match-end 3)))
23820 (if (not box) (match-end 1)
23821 (let ((after (char-after box)))
23822 (if (and after (= after ? )) (1+ box) box))))))
23823 ;; Special case: Move point to special position when
23824 ;; currently after it or at beginning of line.
23825 (if (eq special t)
23826 (when (or (> pos after-bullet) (= (point) pos))
23827 (goto-char after-bullet))
23828 ;; Reversed case: Move point to special position when
23829 ;; point was already at beginning of line and command is
23830 ;; repeated.
23831 (when (and (= (point) pos) (eq last-command this-command))
23832 (goto-char after-bullet))))))))
23833 (org-no-warnings
23834 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23835 (setq disable-point-adjustment
23836 (or (not (invisible-p (point)))
23837 (not (invisible-p (max (point-min) (1- (point))))))))
23839 (defun org-end-of-line (&optional arg)
23840 "Go to the end of the line.
23841 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23842 tags on the first attempt, and only move to after the tags when
23843 the cursor is already beyond the end of the headline."
23844 (interactive "P")
23845 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23846 org-special-ctrl-a/e))
23847 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23848 'end-of-visual-line)
23849 ((fboundp 'move-end-of-line) 'move-end-of-line)
23850 (t 'end-of-line)))
23851 deactivate-mark)
23852 (if (or (not special) arg) (call-interactively move-fun)
23853 (let* ((element (save-excursion (beginning-of-line)
23854 (org-element-at-point)))
23855 (type (org-element-type element)))
23856 (cond
23857 ((memq type '(headline inlinetask))
23858 (let ((pos (point)))
23859 (beginning-of-line 1)
23860 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23861 (if (eq special t)
23862 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23863 (goto-char (match-beginning 1))
23864 (goto-char (match-end 0)))
23865 (if (or (< pos (match-end 0))
23866 (not (eq this-command last-command)))
23867 (goto-char (match-end 0))
23868 (goto-char (match-beginning 1))))
23869 (call-interactively move-fun))))
23870 ((outline-invisible-p (line-end-position))
23871 ;; If element is hidden, `move-end-of-line' would put point
23872 ;; after it. Use `end-of-line' to stay on current line.
23873 (call-interactively 'end-of-line))
23874 (t (call-interactively move-fun)))))
23875 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23876 (setq disable-point-adjustment
23877 (or (not (invisible-p (point)))
23878 (not (invisible-p (max (point-min) (1- (point))))))))
23880 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23881 (define-key org-mode-map "\C-e" 'org-end-of-line)
23883 (defun org-backward-sentence (&optional _arg)
23884 "Go to beginning of sentence, or beginning of table field.
23885 This will call `backward-sentence' or `org-table-beginning-of-field',
23886 depending on context."
23887 (interactive)
23888 (let* ((element (org-element-at-point))
23889 (contents-begin (org-element-property :contents-begin element))
23890 (table (org-element-lineage element '(table) t)))
23891 (if (and table
23892 (> (point) contents-begin)
23893 (<= (point) (org-element-property :contents-end table)))
23894 (call-interactively #'org-table-beginning-of-field)
23895 (save-restriction
23896 (when (and contents-begin
23897 (< (point-min) contents-begin)
23898 (> (point) contents-begin))
23899 (narrow-to-region contents-begin
23900 (org-element-property :contents-end element)))
23901 (call-interactively #'backward-sentence)))))
23903 (defun org-forward-sentence (&optional _arg)
23904 "Go to end of sentence, or end of table field.
23905 This will call `forward-sentence' or `org-table-end-of-field',
23906 depending on context."
23907 (interactive)
23908 (let* ((element (org-element-at-point))
23909 (contents-end (org-element-property :contents-end element))
23910 (table (org-element-lineage element '(table) t)))
23911 (if (and table
23912 (>= (point) (org-element-property :contents-begin table))
23913 (< (point) contents-end))
23914 (call-interactively #'org-table-end-of-field)
23915 (save-restriction
23916 (when (and contents-end
23917 (> (point-max) contents-end)
23918 ;; Skip blank lines between elements.
23919 (< (org-element-property :end element)
23920 (save-excursion (goto-char contents-end)
23921 (skip-chars-forward " \r\t\n"))))
23922 (narrow-to-region (org-element-property :contents-begin element)
23923 contents-end))
23924 (call-interactively #'forward-sentence)))))
23926 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23927 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23929 (defun org-kill-line (&optional _arg)
23930 "Kill line, to tags or end of line."
23931 (interactive)
23932 (cond
23933 ((or (not org-special-ctrl-k)
23934 (bolp)
23935 (not (org-at-heading-p)))
23936 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23937 org-ctrl-k-protect-subtree
23938 (or (eq org-ctrl-k-protect-subtree 'error)
23939 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23940 (user-error "C-k aborted as it would kill a hidden subtree"))
23941 (call-interactively
23942 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23943 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23944 (kill-region (point) (match-beginning 1))
23945 (org-set-tags nil t))
23946 (t (kill-region (point) (point-at-eol)))))
23948 (define-key org-mode-map "\C-k" 'org-kill-line)
23950 (defun org-yank (&optional arg)
23951 "Yank. If the kill is a subtree, treat it specially.
23952 This command will look at the current kill and check if is a single
23953 subtree, or a series of subtrees[1]. If it passes the test, and if the
23954 cursor is at the beginning of a line or after the stars of a currently
23955 empty headline, then the yank is handled specially. How exactly depends
23956 on the value of the following variables, both set by default.
23958 `org-yank-folded-subtrees'
23959 When set, the subtree(s) will be folded after insertion, but only
23960 if doing so would now swallow text after the yanked text.
23962 `org-yank-adjusted-subtrees'
23963 When set, the subtree will be promoted or demoted in order to
23964 fit into the local outline tree structure, which means that the
23965 level will be adjusted so that it becomes the smaller one of the
23966 two *visible* surrounding headings.
23968 Any prefix to this command will cause `yank' to be called directly with
23969 no special treatment. In particular, a simple \\[universal-argument] prefix \
23970 will just
23971 plainly yank the text as it is.
23973 \[1] The test checks if the first non-white line is a heading
23974 and if there are no other headings with fewer stars."
23975 (interactive "P")
23976 (org-yank-generic 'yank arg))
23978 (defun org-yank-generic (command arg)
23979 "Perform some yank-like command.
23981 This function implements the behavior described in the `org-yank'
23982 documentation. However, it has been generalized to work for any
23983 interactive command with similar behavior."
23985 ;; pretend to be command COMMAND
23986 (setq this-command command)
23988 (if arg
23989 (call-interactively command)
23991 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23992 (and (org-kill-is-subtree-p)
23993 (or (bolp)
23994 (and (looking-at "[ \t]*$")
23995 (string-match
23996 "\\`\\*+\\'"
23997 (buffer-substring (point-at-bol) (point)))))))
23998 swallowp)
23999 (cond
24000 ((and subtreep org-yank-folded-subtrees)
24001 (let ((beg (point))
24002 end)
24003 (if (and subtreep org-yank-adjusted-subtrees)
24004 (org-paste-subtree nil nil 'for-yank)
24005 (call-interactively command))
24007 (setq end (point))
24008 (goto-char beg)
24009 (when (and (bolp) subtreep
24010 (not (setq swallowp
24011 (org-yank-folding-would-swallow-text beg end))))
24012 (org-with-limited-levels
24013 (or (looking-at org-outline-regexp)
24014 (re-search-forward org-outline-regexp-bol end t))
24015 (while (and (< (point) end) (looking-at org-outline-regexp))
24016 (outline-hide-subtree)
24017 (org-cycle-show-empty-lines 'folded)
24018 (condition-case nil
24019 (outline-forward-same-level 1)
24020 (error (goto-char end))))))
24021 (when swallowp
24022 (message
24023 "Inserted text not folded because that would swallow text"))
24025 (goto-char end)
24026 (skip-chars-forward " \t\n\r")
24027 (beginning-of-line 1)
24028 (push-mark beg 'nomsg)))
24029 ((and subtreep org-yank-adjusted-subtrees)
24030 (let ((beg (point-at-bol)))
24031 (org-paste-subtree nil nil 'for-yank)
24032 (push-mark beg 'nomsg)))
24034 (call-interactively command))))))
24036 (defun org-yank-folding-would-swallow-text (beg end)
24037 "Would hide-subtree at BEG swallow any text after END?"
24038 (let (level)
24039 (org-with-limited-levels
24040 (save-excursion
24041 (goto-char beg)
24042 (when (or (looking-at org-outline-regexp)
24043 (re-search-forward org-outline-regexp-bol end t))
24044 (setq level (org-outline-level)))
24045 (goto-char end)
24046 (skip-chars-forward " \t\r\n\v\f")
24047 (not (or (eobp)
24048 (and (bolp) (looking-at-p org-outline-regexp)
24049 (<= (org-outline-level) level))))))))
24051 (define-key org-mode-map "\C-y" 'org-yank)
24053 (defun org-truely-invisible-p ()
24054 "Check if point is at a character currently not visible.
24055 This version does not only check the character property, but also
24056 `visible-mode'."
24057 ;; Early versions of noutline don't have `outline-invisible-p'.
24058 (unless (org-bound-and-true-p visible-mode)
24059 (outline-invisible-p)))
24061 (defun org-invisible-p2 ()
24062 "Check if point is at a character currently not visible."
24063 (save-excursion
24064 (when (and (eolp) (not (bobp))) (backward-char 1))
24065 ;; Early versions of noutline don't have `outline-invisible-p'.
24066 (outline-invisible-p)))
24068 (defun org-back-to-heading (&optional invisible-ok)
24069 "Call `outline-back-to-heading', but provide a better error message."
24070 (condition-case nil
24071 (outline-back-to-heading invisible-ok)
24072 (error (error "Before first headline at position %d in buffer %s"
24073 (point) (current-buffer)))))
24075 (defun org-before-first-heading-p ()
24076 "Before first heading?"
24077 (save-excursion
24078 (end-of-line)
24079 (null (re-search-backward org-outline-regexp-bol nil t))))
24081 (defun org-at-heading-p (&optional ignored)
24082 (outline-on-heading-p t))
24083 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24084 ;;; warning was only added in Org 9.0, which should be taken into
24085 ;;; account when deciding when to remove the alias.
24086 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24088 (defun org-in-commented-heading-p (&optional no-inheritance)
24089 "Non-nil if point is under a commented heading.
24090 This function also checks ancestors of the current headline,
24091 unless optional argument NO-INHERITANCE is non-nil."
24092 (cond
24093 ((org-before-first-heading-p) nil)
24094 ((let ((headline (nth 4 (org-heading-components))))
24095 (and headline
24096 (let ((case-fold-search nil))
24097 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24098 headline)))))
24099 (no-inheritance nil)
24101 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24103 (defun org-at-comment-p nil
24104 "Is cursor in a commented line?"
24105 (save-excursion
24106 (save-match-data
24107 (beginning-of-line)
24108 (looking-at "^[ \t]*# "))))
24110 (defun org-at-drawer-p nil
24111 "Is cursor at a drawer keyword?"
24112 (save-excursion
24113 (move-beginning-of-line 1)
24114 (looking-at org-drawer-regexp)))
24116 (defun org-at-block-p nil
24117 "Is cursor at a block keyword?"
24118 (save-excursion
24119 (move-beginning-of-line 1)
24120 (looking-at org-block-regexp)))
24122 (defun org-point-at-end-of-empty-headline ()
24123 "If point is at the end of an empty headline, return t, else nil.
24124 If the heading only contains a TODO keyword, it is still still considered
24125 empty."
24126 (and (looking-at "[ \t]*$")
24127 (when org-todo-line-regexp
24128 (save-excursion
24129 (beginning-of-line 1)
24130 (let ((case-fold-search nil))
24131 (looking-at org-todo-line-regexp)
24132 (string= (match-string 3) ""))))))
24134 (defun org-at-heading-or-item-p ()
24135 (or (org-at-heading-p) (org-at-item-p)))
24137 (defun org-at-target-p ()
24138 (or (org-in-regexp org-radio-target-regexp)
24139 (org-in-regexp org-target-regexp)))
24140 ;; Compatibility alias with Org versions < 7.8.03
24141 (defalias 'org-on-target-p 'org-at-target-p)
24143 (defun org-up-heading-all (arg)
24144 "Move to the heading line of which the present line is a subheading.
24145 This function considers both visible and invisible heading lines.
24146 With argument, move up ARG levels."
24147 (if (fboundp 'outline-up-heading-all)
24148 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24149 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24151 (defun org-up-heading-safe ()
24152 "Move to the heading line of which the present line is a subheading.
24153 This version will not throw an error. It will return the level of the
24154 headline found, or nil if no higher level is found.
24156 Also, this function will be a lot faster than `outline-up-heading',
24157 because it relies on stars being the outline starters. This can really
24158 make a significant difference in outlines with very many siblings."
24159 (when (ignore-errors (org-back-to-heading t))
24160 (let ((level-up (1- (funcall outline-level))))
24161 (and (> level-up 0)
24162 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24163 (funcall outline-level)))))
24165 (defun org-first-sibling-p ()
24166 "Is this heading the first child of its parents?"
24167 (interactive)
24168 (let ((re org-outline-regexp-bol)
24169 level l)
24170 (unless (org-at-heading-p t)
24171 (user-error "Not at a heading"))
24172 (setq level (funcall outline-level))
24173 (save-excursion
24174 (if (not (re-search-backward re nil t))
24176 (setq l (funcall outline-level))
24177 (< l level)))))
24179 (defun org-goto-sibling (&optional previous)
24180 "Goto the next sibling, even if it is invisible.
24181 When PREVIOUS is set, go to the previous sibling instead. Returns t
24182 when a sibling was found. When none is found, return nil and don't
24183 move point."
24184 (let ((fun (if previous 're-search-backward 're-search-forward))
24185 (pos (point))
24186 (re org-outline-regexp-bol)
24187 level l)
24188 (when (ignore-errors (org-back-to-heading t))
24189 (setq level (funcall outline-level))
24190 (catch 'exit
24191 (or previous (forward-char 1))
24192 (while (funcall fun re nil t)
24193 (setq l (funcall outline-level))
24194 (when (< l level) (goto-char pos) (throw 'exit nil))
24195 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24196 (goto-char pos)
24197 nil))))
24199 (defun org-show-siblings ()
24200 "Show all siblings of the current headline."
24201 (save-excursion
24202 (while (org-goto-sibling) (org-flag-heading nil)))
24203 (save-excursion
24204 (while (org-goto-sibling 'previous)
24205 (org-flag-heading nil))))
24207 (defun org-goto-first-child ()
24208 "Goto the first child, even if it is invisible.
24209 Return t when a child was found. Otherwise don't move point and
24210 return nil."
24211 (let (level (pos (point)) (re org-outline-regexp-bol))
24212 (when (ignore-errors (org-back-to-heading t))
24213 (setq level (outline-level))
24214 (forward-char 1)
24215 (if (and (re-search-forward re nil t) (> (outline-level) level))
24216 (progn (goto-char (match-beginning 0)) t)
24217 (goto-char pos) nil))))
24219 (defun org-show-hidden-entry ()
24220 "Show an entry where even the heading is hidden."
24221 (save-excursion
24222 (org-show-entry)))
24224 (defun org-flag-heading (flag &optional entry)
24225 "Flag the current heading. FLAG non-nil means make invisible.
24226 When ENTRY is non-nil, show the entire entry."
24227 (save-excursion
24228 (org-back-to-heading t)
24229 ;; Check if we should show the entire entry
24230 (if entry
24231 (progn
24232 (org-show-entry)
24233 (save-excursion
24234 (and (outline-next-heading)
24235 (org-flag-heading nil))))
24236 (outline-flag-region (max (point-min) (1- (point)))
24237 (save-excursion (outline-end-of-heading) (point))
24238 flag))))
24240 (defun org-get-next-sibling ()
24241 "Move to next heading of the same level, and return point.
24242 If there is no such heading, return nil.
24243 This is like outline-next-sibling, but invisible headings are ok."
24244 (let ((level (funcall outline-level)))
24245 (outline-next-heading)
24246 (while (and (not (eobp)) (> (funcall outline-level) level))
24247 (outline-next-heading))
24248 (unless (or (eobp) (< (funcall outline-level) level))
24249 (point))))
24251 (defun org-get-last-sibling ()
24252 "Move to previous heading of the same level, and return point.
24253 If there is no such heading, return nil."
24254 (let ((opoint (point))
24255 (level (funcall outline-level)))
24256 (outline-previous-heading)
24257 (when (and (/= (point) opoint) (outline-on-heading-p t))
24258 (while (and (> (funcall outline-level) level)
24259 (not (bobp)))
24260 (outline-previous-heading))
24261 (unless (< (funcall outline-level) level)
24262 (point)))))
24264 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24265 "Goto to the end of a subtree."
24266 ;; This contains an exact copy of the original function, but it uses
24267 ;; `org-back-to-heading', to make it work also in invisible
24268 ;; trees. And is uses an invisible-ok argument.
24269 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24270 ;; Furthermore, when used inside Org, finding the end of a large subtree
24271 ;; with many children and grandchildren etc, this can be much faster
24272 ;; than the outline version.
24273 (org-back-to-heading invisible-ok)
24274 (let ((first t)
24275 (level (funcall outline-level)))
24276 (if (and (derived-mode-p 'org-mode) (< level 1000))
24277 ;; A true heading (not a plain list item), in Org-mode
24278 ;; This means we can easily find the end by looking
24279 ;; only for the right number of stars. Using a regexp to do
24280 ;; this is so much faster than using a Lisp loop.
24281 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24282 (forward-char 1)
24283 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24284 ;; something else, do it the slow way
24285 (while (and (not (eobp))
24286 (or first (> (funcall outline-level) level)))
24287 (setq first nil)
24288 (outline-next-heading)))
24289 (unless to-heading
24290 (when (memq (preceding-char) '(?\n ?\^M))
24291 ;; Go to end of line before heading
24292 (forward-char -1)
24293 (when (memq (preceding-char) '(?\n ?\^M))
24294 ;; leave blank line before heading
24295 (forward-char -1)))))
24296 (point))
24298 (defun org-end-of-meta-data (&optional full)
24299 "Skip planning line and properties drawer in current entry.
24300 When optional argument FULL is non-nil, also skip empty lines,
24301 clocking lines and regular drawers at the beginning of the
24302 entry."
24303 (org-back-to-heading t)
24304 (forward-line)
24305 (when (org-looking-at-p org-planning-line-re) (forward-line))
24306 (when (looking-at org-property-drawer-re)
24307 (goto-char (match-end 0))
24308 (forward-line))
24309 (when (and full (not (org-at-heading-p)))
24310 (catch 'exit
24311 (let ((end (save-excursion (outline-next-heading) (point)))
24312 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24313 (while (not (eobp))
24314 (cond ((org-looking-at-p org-drawer-regexp)
24315 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24316 (forward-line)
24317 (throw 'exit t)))
24318 ((org-looking-at-p re) (forward-line))
24319 (t (throw 'exit t))))))))
24321 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24322 "Move forward to the ARG'th subheading at same level as this one.
24323 Stop at the first and last subheadings of a superior heading.
24324 Normally this only looks at visible headings, but when INVISIBLE-OK is
24325 non-nil it will also look at invisible ones."
24326 (interactive "p")
24327 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24328 (if (and arg (< arg 0))
24329 (goto-char (point-min))
24330 (outline-next-heading))
24331 (org-at-heading-p)
24332 (let ((level (- (match-end 0) (match-beginning 0) 1))
24333 (f (if (and arg (< arg 0))
24334 're-search-backward
24335 're-search-forward))
24336 (count (if arg (abs arg) 1))
24337 (result (point)))
24338 (while (and (prog1 (> count 0)
24339 (forward-char (if (and arg (< arg 0)) -1 1)))
24340 (funcall f org-outline-regexp-bol nil 'move))
24341 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24342 (cond ((< l level) (setq count 0))
24343 ((and (= l level)
24344 (or invisible-ok
24345 (progn
24346 (goto-char (line-beginning-position))
24347 (not (outline-invisible-p)))))
24348 (setq count (1- count))
24349 (when (eq l level)
24350 (setq result (point)))))))
24351 (goto-char result))
24352 (beginning-of-line 1)))
24354 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24355 "Move backward to the ARG'th subheading at same level as this one.
24356 Stop at the first and last subheadings of a superior heading."
24357 (interactive "p")
24358 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24360 (defun org-next-visible-heading (arg)
24361 "Move to the next visible heading.
24363 This function wraps `outline-next-visible-heading' with
24364 `org-with-limited-levels' in order to skip over inline tasks and
24365 respect customization of `org-odd-levels-only'."
24366 (interactive "p")
24367 (org-with-limited-levels
24368 (outline-next-visible-heading arg)))
24370 (defun org-previous-visible-heading (arg)
24371 "Move to the previous visible heading.
24373 This function wraps `outline-previous-visible-heading' with
24374 `org-with-limited-levels' in order to skip over inline tasks and
24375 respect customization of `org-odd-levels-only'."
24376 (interactive "p")
24377 (org-with-limited-levels
24378 (outline-previous-visible-heading arg)))
24380 (defun org-next-block (arg &optional backward block-regexp)
24381 "Jump to the next block.
24383 With a prefix argument ARG, jump forward ARG many blocks.
24385 When BACKWARD is non-nil, jump to the previous block.
24387 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24388 Match data is set according to this regexp when the function
24389 returns.
24391 Return point at beginning of the opening line of found block.
24392 Throw an error if no block is found."
24393 (interactive "p")
24394 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24395 (case-fold-search t)
24396 (search-fn (if backward #'re-search-backward #'re-search-forward))
24397 (count (or arg 1))
24398 (origin (point))
24399 last-element)
24400 (if backward (beginning-of-line) (end-of-line))
24401 (while (and (> count 0) (funcall search-fn re nil t))
24402 (let ((element (save-excursion
24403 (goto-char (match-beginning 0))
24404 (save-match-data (org-element-at-point)))))
24405 (when (and (memq (org-element-type element)
24406 '(center-block comment-block dynamic-block
24407 example-block export-block quote-block
24408 special-block src-block verse-block))
24409 (<= (match-beginning 0)
24410 (org-element-property :post-affiliated element)))
24411 (setq last-element element)
24412 (cl-decf count))))
24413 (if (= count 0)
24414 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24415 (save-match-data (org-show-context)))
24416 (goto-char origin)
24417 (user-error "No %s code blocks" (if backward "previous" "further")))))
24419 (defun org-previous-block (arg &optional block-regexp)
24420 "Jump to the previous block.
24421 With a prefix argument ARG, jump backward ARG many source blocks.
24422 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24423 (interactive "p")
24424 (org-next-block arg t block-regexp))
24426 (defun org-forward-paragraph ()
24427 "Move forward to beginning of next paragraph or equivalent.
24429 The function moves point to the beginning of the next visible
24430 structural element, which can be a paragraph, a table, a list
24431 item, etc. It also provides some special moves for convenience:
24433 - On an affiliated keyword, jump to the beginning of the
24434 relative element.
24435 - On an item or a footnote definition, move to the second
24436 element inside, if any.
24437 - On a table or a property drawer, jump after it.
24438 - On a verse or source block, stop after blank lines."
24439 (interactive)
24440 (when (eobp) (user-error "Cannot move further down"))
24441 (let* ((deactivate-mark nil)
24442 (element (org-element-at-point))
24443 (type (org-element-type element))
24444 (post-affiliated (org-element-property :post-affiliated element))
24445 (contents-begin (org-element-property :contents-begin element))
24446 (contents-end (org-element-property :contents-end element))
24447 (end (let ((end (org-element-property :end element)) (parent element))
24448 (while (and (setq parent (org-element-property :parent parent))
24449 (= (org-element-property :contents-end parent) end))
24450 (setq end (org-element-property :end parent)))
24451 end)))
24452 (cond ((not element)
24453 (skip-chars-forward " \r\t\n")
24454 (or (eobp) (beginning-of-line)))
24455 ;; On affiliated keywords, move to element's beginning.
24456 ((< (point) post-affiliated)
24457 (goto-char post-affiliated))
24458 ;; At a table row, move to the end of the table. Similarly,
24459 ;; at a node property, move to the end of the property
24460 ;; drawer.
24461 ((memq type '(node-property table-row))
24462 (goto-char (org-element-property
24463 :end (org-element-property :parent element))))
24464 ((memq type '(property-drawer table)) (goto-char end))
24465 ;; Consider blank lines as separators in verse and source
24466 ;; blocks to ease editing.
24467 ((memq type '(src-block verse-block))
24468 (when (eq type 'src-block)
24469 (setq contents-end
24470 (save-excursion (goto-char end)
24471 (skip-chars-backward " \r\t\n")
24472 (line-beginning-position))))
24473 (beginning-of-line)
24474 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24475 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24476 (goto-char end)
24477 (skip-chars-forward " \r\t\n")
24478 (if (= (point) contents-end) (goto-char end)
24479 (beginning-of-line))))
24480 ;; With no contents, just skip element.
24481 ((not contents-begin) (goto-char end))
24482 ;; If contents are invisible, skip the element altogether.
24483 ((outline-invisible-p (line-end-position))
24484 (cl-case type
24485 (headline
24486 (org-with-limited-levels (outline-next-visible-heading 1)))
24487 ;; At a plain list, make sure we move to the next item
24488 ;; instead of skipping the whole list.
24489 (plain-list (forward-char)
24490 (org-forward-paragraph))
24491 (otherwise (goto-char end))))
24492 ((>= (point) contents-end) (goto-char end))
24493 ((>= (point) contents-begin)
24494 ;; This can only happen on paragraphs and plain lists.
24495 (cl-case type
24496 (paragraph (goto-char end))
24497 ;; At a plain list, try to move to second element in
24498 ;; first item, if possible.
24499 (plain-list (end-of-line)
24500 (org-forward-paragraph))))
24501 ;; When contents start on the middle of a line (e.g. in
24502 ;; items and footnote definitions), try to reach first
24503 ;; element starting after current line.
24504 ((> (line-end-position) contents-begin)
24505 (end-of-line)
24506 (org-forward-paragraph))
24507 (t (goto-char contents-begin)))))
24509 (defun org-backward-paragraph ()
24510 "Move backward to start of previous paragraph or equivalent.
24512 The function moves point to the beginning of the current
24513 structural element, which can be a paragraph, a table, a list
24514 item, etc., or to the beginning of the previous visible one if
24515 point is already there. It also provides some special moves for
24516 convenience:
24518 - On an affiliated keyword, jump to the first one.
24519 - On a table or a property drawer, move to its beginning.
24520 - On a verse or source block, stop before blank lines."
24521 (interactive)
24522 (when (bobp) (user-error "Cannot move further up"))
24523 (let* ((deactivate-mark nil)
24524 (element (org-element-at-point))
24525 (type (org-element-type element))
24526 (contents-begin (org-element-property :contents-begin element))
24527 (contents-end (org-element-property :contents-end element))
24528 (post-affiliated (org-element-property :post-affiliated element))
24529 (begin (org-element-property :begin element)))
24530 (cond
24531 ((not element) (goto-char (point-min)))
24532 ((= (point) begin)
24533 (backward-char)
24534 (org-backward-paragraph))
24535 ((<= (point) post-affiliated) (goto-char begin))
24536 ((memq type '(node-property table-row))
24537 (goto-char (org-element-property
24538 :post-affiliated (org-element-property :parent element))))
24539 ((memq type '(property-drawer table)) (goto-char begin))
24540 ((memq type '(src-block verse-block))
24541 (when (eq type 'src-block)
24542 (setq contents-begin
24543 (save-excursion (goto-char begin) (forward-line) (point))))
24544 (if (= (point) contents-begin) (goto-char post-affiliated)
24545 ;; Inside a verse block, see blank lines as paragraph
24546 ;; separators.
24547 (let ((origin (point)))
24548 (skip-chars-backward " \r\t\n" contents-begin)
24549 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24550 (skip-chars-forward " \r\t\n" origin)
24551 (if (= (point) origin) (goto-char contents-begin)
24552 (beginning-of-line))))))
24553 ((not contents-begin) (goto-char (or post-affiliated begin)))
24554 ((eq type 'paragraph)
24555 (goto-char contents-begin)
24556 ;; When at first paragraph in an item or a footnote definition,
24557 ;; move directly to beginning of line.
24558 (let ((parent-contents
24559 (org-element-property
24560 :contents-begin (org-element-property :parent element))))
24561 (when (and parent-contents (= parent-contents contents-begin))
24562 (beginning-of-line))))
24563 ;; At the end of a greater element, move to the beginning of the
24564 ;; last element within.
24565 ((>= (point) contents-end)
24566 (goto-char (1- contents-end))
24567 (org-backward-paragraph))
24568 (t (goto-char (or post-affiliated begin))))
24569 ;; Ensure we never leave point invisible.
24570 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24572 (defun org-forward-element ()
24573 "Move forward by one element.
24574 Move to the next element at the same level, when possible."
24575 (interactive)
24576 (cond ((eobp) (user-error "Cannot move further down"))
24577 ((org-with-limited-levels (org-at-heading-p))
24578 (let ((origin (point)))
24579 (goto-char (org-end-of-subtree nil t))
24580 (unless (org-with-limited-levels (org-at-heading-p))
24581 (goto-char origin)
24582 (user-error "Cannot move further down"))))
24584 (let* ((elem (org-element-at-point))
24585 (end (org-element-property :end elem))
24586 (parent (org-element-property :parent elem)))
24587 (cond ((and parent (= (org-element-property :contents-end parent) end))
24588 (goto-char (org-element-property :end parent)))
24589 ((integer-or-marker-p end) (goto-char end))
24590 (t (message "No element at point")))))))
24592 (defun org-backward-element ()
24593 "Move backward by one element.
24594 Move to the previous element at the same level, when possible."
24595 (interactive)
24596 (cond ((bobp) (user-error "Cannot move further up"))
24597 ((org-with-limited-levels (org-at-heading-p))
24598 ;; At a headline, move to the previous one, if any, or stay
24599 ;; here.
24600 (let ((origin (point)))
24601 (org-with-limited-levels (org-backward-heading-same-level 1))
24602 ;; When current headline has no sibling above, move to its
24603 ;; parent.
24604 (when (= (point) origin)
24605 (or (org-with-limited-levels (org-up-heading-safe))
24606 (progn (goto-char origin)
24607 (user-error "Cannot move further up"))))))
24609 (let* ((elem (org-element-at-point))
24610 (beg (org-element-property :begin elem)))
24611 (cond
24612 ;; Move to beginning of current element if point isn't
24613 ;; there already.
24614 ((null beg) (message "No element at point"))
24615 ((/= (point) beg) (goto-char beg))
24616 (t (goto-char beg)
24617 (skip-chars-backward " \r\t\n")
24618 (unless (bobp)
24619 (let ((prev (org-element-at-point)))
24620 (goto-char (org-element-property :begin prev))
24621 (while (and (setq prev (org-element-property :parent prev))
24622 (<= (org-element-property :end prev) beg))
24623 (goto-char (org-element-property :begin prev)))))))))))
24625 (defun org-up-element ()
24626 "Move to upper element."
24627 (interactive)
24628 (if (org-with-limited-levels (org-at-heading-p))
24629 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24630 (let* ((elem (org-element-at-point))
24631 (parent (org-element-property :parent elem)))
24632 (if parent (goto-char (org-element-property :begin parent))
24633 (if (org-with-limited-levels (org-before-first-heading-p))
24634 (user-error "No surrounding element")
24635 (org-with-limited-levels (org-back-to-heading)))))))
24637 (defvar org-element-greater-elements)
24638 (defun org-down-element ()
24639 "Move to inner element."
24640 (interactive)
24641 (let ((element (org-element-at-point)))
24642 (cond
24643 ((memq (org-element-type element) '(plain-list table))
24644 (goto-char (org-element-property :contents-begin element))
24645 (forward-char))
24646 ((memq (org-element-type element) org-element-greater-elements)
24647 ;; If contents are hidden, first disclose them.
24648 (when (outline-invisible-p (line-end-position)) (org-cycle))
24649 (goto-char (or (org-element-property :contents-begin element)
24650 (user-error "No content for this element"))))
24651 (t (user-error "No inner element")))))
24653 (defun org-drag-element-backward ()
24654 "Move backward element at point."
24655 (interactive)
24656 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24657 (let* ((elem (org-element-at-point))
24658 (prev-elem
24659 (save-excursion
24660 (goto-char (org-element-property :begin elem))
24661 (skip-chars-backward " \r\t\n")
24662 (unless (bobp)
24663 (let* ((beg (org-element-property :begin elem))
24664 (prev (org-element-at-point))
24665 (up prev))
24666 (while (and (setq up (org-element-property :parent up))
24667 (<= (org-element-property :end up) beg))
24668 (setq prev up))
24669 prev)))))
24670 ;; Error out if no previous element or previous element is
24671 ;; a parent of the current one.
24672 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24673 (user-error "Cannot drag element backward")
24674 (let ((pos (point)))
24675 (org-element-swap-A-B prev-elem elem)
24676 (goto-char (+ (org-element-property :begin prev-elem)
24677 (- pos (org-element-property :begin elem)))))))))
24679 (defun org-drag-element-forward ()
24680 "Move forward element at point."
24681 (interactive)
24682 (let* ((pos (point))
24683 (elem (org-element-at-point)))
24684 (when (= (point-max) (org-element-property :end elem))
24685 (user-error "Cannot drag element forward"))
24686 (goto-char (org-element-property :end elem))
24687 (let ((next-elem (org-element-at-point)))
24688 (when (or (org-element-nested-p elem next-elem)
24689 (and (eq (org-element-type next-elem) 'headline)
24690 (not (eq (org-element-type elem) 'headline))))
24691 (goto-char pos)
24692 (user-error "Cannot drag element forward"))
24693 ;; Compute new position of point: it's shifted by NEXT-ELEM
24694 ;; body's length (without final blanks) and by the length of
24695 ;; blanks between ELEM and NEXT-ELEM.
24696 (let ((size-next (- (save-excursion
24697 (goto-char (org-element-property :end next-elem))
24698 (skip-chars-backward " \r\t\n")
24699 (forward-line)
24700 ;; Small correction if buffer doesn't end
24701 ;; with a newline character.
24702 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24703 (org-element-property :begin next-elem)))
24704 (size-blank (- (org-element-property :end elem)
24705 (save-excursion
24706 (goto-char (org-element-property :end elem))
24707 (skip-chars-backward " \r\t\n")
24708 (forward-line)
24709 (point)))))
24710 (org-element-swap-A-B elem next-elem)
24711 (goto-char (+ pos size-next size-blank))))))
24713 (defun org-drag-line-forward (arg)
24714 "Drag the line at point ARG lines forward."
24715 (interactive "p")
24716 (dotimes (_ (abs arg))
24717 (let ((c (current-column)))
24718 (if (< 0 arg)
24719 (progn
24720 (beginning-of-line 2)
24721 (transpose-lines 1)
24722 (beginning-of-line 0))
24723 (transpose-lines 1)
24724 (beginning-of-line -1))
24725 (org-move-to-column c))))
24727 (defun org-drag-line-backward (arg)
24728 "Drag the line at point ARG lines backward."
24729 (interactive "p")
24730 (org-drag-line-forward (- arg)))
24732 (defun org-mark-element ()
24733 "Put point at beginning of this element, mark at end.
24735 Interactively, if this command is repeated or (in Transient Mark
24736 mode) if the mark is active, it marks the next element after the
24737 ones already marked."
24738 (interactive)
24739 (let (deactivate-mark)
24740 (if (and (org-called-interactively-p 'any)
24741 (or (and (eq last-command this-command) (mark t))
24742 (and transient-mark-mode mark-active)))
24743 (set-mark
24744 (save-excursion
24745 (goto-char (mark))
24746 (goto-char (org-element-property :end (org-element-at-point)))))
24747 (let ((element (org-element-at-point)))
24748 (end-of-line)
24749 (push-mark (org-element-property :end element) t t)
24750 (goto-char (org-element-property :begin element))))))
24752 (defun org-narrow-to-element ()
24753 "Narrow buffer to current element."
24754 (interactive)
24755 (let ((elem (org-element-at-point)))
24756 (cond
24757 ((eq (car elem) 'headline)
24758 (narrow-to-region
24759 (org-element-property :begin elem)
24760 (org-element-property :end elem)))
24761 ((memq (car elem) org-element-greater-elements)
24762 (narrow-to-region
24763 (org-element-property :contents-begin elem)
24764 (org-element-property :contents-end elem)))
24766 (narrow-to-region
24767 (org-element-property :begin elem)
24768 (org-element-property :end elem))))))
24770 (defun org-transpose-element ()
24771 "Transpose current and previous elements, keeping blank lines between.
24772 Point is moved after both elements."
24773 (interactive)
24774 (org-skip-whitespace)
24775 (let ((end (org-element-property :end (org-element-at-point))))
24776 (org-drag-element-backward)
24777 (goto-char end)))
24779 (defun org-unindent-buffer ()
24780 "Un-indent the visible part of the buffer.
24781 Relative indentation (between items, inside blocks, etc.) isn't
24782 modified."
24783 (interactive)
24784 (unless (eq major-mode 'org-mode)
24785 (user-error "Cannot un-indent a buffer not in Org mode"))
24786 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24787 (unindent-tree
24788 (lambda (contents)
24789 (dolist (element (reverse contents))
24790 (if (memq (org-element-type element) '(headline section))
24791 (funcall unindent-tree (org-element-contents element))
24792 (save-excursion
24793 (save-restriction
24794 (narrow-to-region
24795 (org-element-property :begin element)
24796 (org-element-property :end element))
24797 (org-do-remove-indentation))))))))
24798 (funcall unindent-tree (org-element-contents parse-tree))))
24800 (defun org-show-children (&optional level)
24801 "Show all direct subheadings of this heading.
24802 Prefix arg LEVEL is how many levels below the current level
24803 should be shown. Default is enough to cause the following
24804 heading to appear."
24805 (interactive "p")
24806 ;; If `orgstruct-mode' is active, use the slower version.
24807 (if orgstruct-mode (call-interactively #'outline-show-children)
24808 (save-excursion
24809 (org-back-to-heading t)
24810 (let* ((current-level (funcall outline-level))
24811 (max-level (org-get-valid-level
24812 current-level
24813 (if level (prefix-numeric-value level) 1)))
24814 (end (save-excursion (org-end-of-subtree t t)))
24815 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24816 (past-first-child nil)
24817 ;; Make sure to skip inlinetasks.
24818 (re (format regexp-fmt
24819 current-level
24820 (cond
24821 ((not (featurep 'org-inlinetask)) "")
24822 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24824 (t (1- org-inlinetask-min-level))))))
24825 ;; Display parent heading.
24826 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24827 (forward-line)
24828 ;; Display children. First child may be deeper than expected
24829 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24830 ;; MAX-LEVEL accordingly.
24831 (while (re-search-forward re end t)
24832 (unless past-first-child
24833 (setq re (format regexp-fmt
24834 current-level
24835 (max (funcall outline-level) max-level)))
24836 (setq past-first-child t))
24837 (outline-flag-region
24838 (line-end-position 0) (line-end-position) nil))))))
24840 (defun org-show-subtree ()
24841 "Show everything after this heading at deeper levels."
24842 (interactive)
24843 (outline-flag-region
24844 (point)
24845 (save-excursion
24846 (org-end-of-subtree t t))
24847 nil))
24849 (defun org-show-entry ()
24850 "Show the body directly following this heading.
24851 Show the heading too, if it is currently invisible."
24852 (interactive)
24853 (save-excursion
24854 (ignore-errors
24855 (org-back-to-heading t)
24856 (outline-flag-region
24857 (max (point-min) (1- (point)))
24858 (save-excursion
24859 (if (re-search-forward
24860 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24861 (match-beginning 1)
24862 (point-max)))
24863 nil)
24864 (org-cycle-hide-drawers 'children))))
24866 (defun org-make-options-regexp (kwds &optional extra)
24867 "Make a regular expression for keyword lines.
24868 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24869 when non-nil, is a regexp matching keywords names."
24870 (concat "^[ \t]*#\\+\\("
24871 (regexp-opt kwds)
24872 (and extra (concat (and kwds "\\|") extra))
24873 "\\):[ \t]*\\(.*\\)"))
24875 ;;;; Integration with and fixes for other packages
24877 ;;; Imenu support
24879 (defvar-local org-imenu-markers nil
24880 "All markers currently used by Imenu.")
24882 (defun org-imenu-new-marker (&optional pos)
24883 "Return a new marker for use by Imenu, and remember the marker."
24884 (let ((m (make-marker)))
24885 (move-marker m (or pos (point)))
24886 (push m org-imenu-markers)
24889 (defun org-imenu-get-tree ()
24890 "Produce the index for Imenu."
24891 (dolist (x org-imenu-markers) (move-marker x nil))
24892 (setq org-imenu-markers nil)
24893 (let* ((n org-imenu-depth)
24894 (re (concat "^" (org-get-limited-outline-regexp)))
24895 (subs (make-vector (1+ n) nil))
24896 (last-level 0)
24897 m level head0 head)
24898 (save-excursion
24899 (save-restriction
24900 (widen)
24901 (goto-char (point-max))
24902 (while (re-search-backward re nil t)
24903 (setq level (org-reduced-level (funcall outline-level)))
24904 (when (and (<= level n)
24905 (looking-at org-complex-heading-regexp)
24906 (setq head0 (org-match-string-no-properties 4)))
24907 (setq head (org-link-display-format head0)
24908 m (org-imenu-new-marker))
24909 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24910 (if (>= level last-level)
24911 (push (cons head m) (aref subs level))
24912 (push (cons head (aref subs (1+ level))) (aref subs level))
24913 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24914 (setq last-level level)))))
24915 (aref subs 1)))
24917 (eval-after-load "imenu"
24918 '(progn
24919 (add-hook 'imenu-after-jump-hook
24920 (lambda ()
24921 (when (derived-mode-p 'org-mode)
24922 (org-show-context 'org-goto))))))
24924 (defun org-link-display-format (s)
24925 "Replace links in string S with their description.
24926 If there is no description, use the link target."
24927 (save-match-data
24928 (replace-regexp-in-string
24929 org-bracket-link-analytic-regexp
24930 (lambda (m)
24931 (if (match-end 5) (match-string 5 m)
24932 (concat (match-string 1 m) (match-string 3 m))))
24933 s nil t)))
24935 (defun org-toggle-link-display ()
24936 "Toggle the literal or descriptive display of links."
24937 (interactive)
24938 (if org-descriptive-links
24939 (progn (org-remove-from-invisibility-spec '(org-link))
24940 (org-restart-font-lock)
24941 (setq org-descriptive-links nil))
24942 (progn (add-to-invisibility-spec '(org-link))
24943 (org-restart-font-lock)
24944 (setq org-descriptive-links t))))
24946 ;; Speedbar support
24948 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24949 "Overlay marking the agenda restriction line in speedbar.")
24950 (overlay-put org-speedbar-restriction-lock-overlay
24951 'face 'org-agenda-restriction-lock)
24952 (overlay-put org-speedbar-restriction-lock-overlay
24953 'help-echo "Agendas are currently limited to this item.")
24954 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24956 (defun org-speedbar-set-agenda-restriction ()
24957 "Restrict future agenda commands to the location at point in speedbar.
24958 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24959 (interactive)
24960 (require 'org-agenda)
24961 (let (p m tp np dir txt)
24962 (cond
24963 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24964 'org-imenu t))
24965 (setq m (get-text-property p 'org-imenu-marker))
24966 (with-current-buffer (marker-buffer m)
24967 (goto-char m)
24968 (org-agenda-set-restriction-lock 'subtree)))
24969 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24970 'speedbar-function 'speedbar-find-file))
24971 (setq tp (previous-single-property-change
24972 (1+ p) 'speedbar-function)
24973 np (next-single-property-change
24974 tp 'speedbar-function)
24975 dir (speedbar-line-directory)
24976 txt (buffer-substring-no-properties (or tp (point-min))
24977 (or np (point-max))))
24978 (with-current-buffer (find-file-noselect
24979 (let ((default-directory dir))
24980 (expand-file-name txt)))
24981 (unless (derived-mode-p 'org-mode)
24982 (user-error "Cannot restrict to non-Org-mode file"))
24983 (org-agenda-set-restriction-lock 'file)))
24984 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24985 (move-overlay org-speedbar-restriction-lock-overlay
24986 (point-at-bol) (point-at-eol))
24987 (setq current-prefix-arg nil)
24988 (org-agenda-maybe-redo)))
24990 (defvar speedbar-file-key-map)
24991 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24992 (eval-after-load "speedbar"
24993 '(progn
24994 (speedbar-add-supported-extension ".org")
24995 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24996 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24997 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24998 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24999 (add-hook 'speedbar-visiting-tag-hook
25000 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25002 ;;; Fixes and Hacks for problems with other packages
25004 (defun org--flyspell-object-check-p (element)
25005 "Non-nil when Flyspell can check object at point.
25006 ELEMENT is the element at point."
25007 (let ((object (save-excursion
25008 (when (org-looking-at-p "\\>") (backward-char))
25009 (org-element-context element))))
25010 (cl-case (org-element-type object)
25011 ;; Prevent checks in links due to keybinding conflict with
25012 ;; Flyspell.
25013 ((code entity export-snippet inline-babel-call
25014 inline-src-block line-break latex-fragment link macro
25015 statistics-cookie target timestamp verbatim)
25016 nil)
25017 (footnote-reference
25018 ;; Only in inline footnotes, within the definition.
25019 (and (eq (org-element-property :type object) 'inline)
25020 (< (save-excursion
25021 (goto-char (org-element-property :begin object))
25022 (search-forward ":" nil t 2))
25023 (point))))
25024 (otherwise t))))
25026 (defun org-mode-flyspell-verify ()
25027 "Function used for `flyspell-generic-check-word-predicate'."
25028 (if (org-at-heading-p)
25029 ;; At a headline or an inlinetask, check title only. This is
25030 ;; faster than relying on `org-element-at-point'.
25031 (and (save-excursion (beginning-of-line)
25032 (and (let ((case-fold-search t))
25033 (not (looking-at "\\*+ END[ \t]*$")))
25034 (looking-at org-complex-heading-regexp)))
25035 (match-beginning 4)
25036 (>= (point) (match-beginning 4))
25037 (or (not (match-beginning 5))
25038 (< (point) (match-beginning 5))))
25039 (let* ((element (org-element-at-point))
25040 (post-affiliated (org-element-property :post-affiliated element)))
25041 (cond
25042 ;; Ignore checks in all affiliated keywords but captions.
25043 ((< (point) post-affiliated)
25044 (and (save-excursion
25045 (beginning-of-line)
25046 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25047 (> (point) (match-end 0))
25048 (org--flyspell-object-check-p element)))
25049 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25050 ((let ((log (org-log-into-drawer)))
25051 (and log
25052 (let ((drawer (org-element-lineage element '(drawer))))
25053 (and drawer
25054 (eq (compare-strings
25055 log nil nil
25056 (org-element-property :drawer-name drawer) nil nil t)
25057 t)))))
25058 nil)
25060 (cl-case (org-element-type element)
25061 ((comment quote-section) t)
25062 (comment-block
25063 ;; Allow checks between block markers, not on them.
25064 (and (> (line-beginning-position) post-affiliated)
25065 (save-excursion
25066 (end-of-line)
25067 (skip-chars-forward " \r\t\n")
25068 (< (point) (org-element-property :end element)))))
25069 ;; Arbitrary list of keywords where checks are meaningful.
25070 ;; Make sure point is on the value part of the element.
25071 (keyword
25072 (and (member (org-element-property :key element)
25073 '("DESCRIPTION" "TITLE"))
25074 (save-excursion
25075 (search-backward ":" (line-beginning-position) t))))
25076 ;; Check is globally allowed in paragraphs verse blocks and
25077 ;; table rows (after affiliated keywords) but some objects
25078 ;; must not be affected.
25079 ((paragraph table-row verse-block)
25080 (let ((cbeg (org-element-property :contents-begin element))
25081 (cend (org-element-property :contents-end element)))
25082 (and cbeg (>= (point) cbeg) (< (point) cend)
25083 (org--flyspell-object-check-p element))))))))))
25084 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25086 (defun org-remove-flyspell-overlays-in (beg end)
25087 "Remove flyspell overlays in region."
25088 (and (org-bound-and-true-p flyspell-mode)
25089 (fboundp 'flyspell-delete-region-overlays)
25090 (flyspell-delete-region-overlays beg end)))
25092 (defvar flyspell-delayed-commands)
25093 (eval-after-load "flyspell"
25094 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25096 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25097 (eval-after-load "bookmark"
25098 '(if (boundp 'bookmark-after-jump-hook)
25099 ;; We can use the hook
25100 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25101 ;; Hook not available, use advice
25102 (defadvice bookmark-jump (after org-make-visible activate)
25103 "Make the position visible."
25104 (org-bookmark-jump-unhide))))
25106 ;; Make sure saveplace shows the location if it was hidden
25107 (eval-after-load "saveplace"
25108 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25109 "Make the position visible."
25110 (org-bookmark-jump-unhide)))
25112 ;; Make sure ecb shows the location if it was hidden
25113 (eval-after-load "ecb"
25114 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25115 "Make hierarchy visible when jumping into location from ECB tree buffer."
25116 (when (derived-mode-p 'org-mode)
25117 (org-show-context))))
25119 (defun org-bookmark-jump-unhide ()
25120 "Unhide the current position, to show the bookmark location."
25121 (and (derived-mode-p 'org-mode)
25122 (or (outline-invisible-p)
25123 (save-excursion (goto-char (max (point-min) (1- (point))))
25124 (outline-invisible-p)))
25125 (org-show-context 'bookmark-jump)))
25127 (defun org-mark-jump-unhide ()
25128 "Make the point visible with `org-show-context' after jumping to the mark."
25129 (when (and (derived-mode-p 'org-mode)
25130 (outline-invisible-p))
25131 (org-show-context 'mark-goto)))
25133 (eval-after-load "simple"
25134 '(defadvice pop-to-mark-command (after org-make-visible activate)
25135 "Make the point visible with `org-show-context'."
25136 (org-mark-jump-unhide)))
25138 (eval-after-load "simple"
25139 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25140 "Make the point visible with `org-show-context'."
25141 (org-mark-jump-unhide)))
25143 (eval-after-load "simple"
25144 '(defadvice pop-global-mark (after org-make-visible activate)
25145 "Make the point visible with `org-show-context'."
25146 (org-mark-jump-unhide)))
25148 ;; Make session.el ignore our circular variable
25149 (defvar session-globals-exclude)
25150 (eval-after-load "session"
25151 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25153 ;;;; Finish up
25155 (provide 'org)
25157 (run-hooks 'org-load-hook)
25159 ;;; org.el ends here