Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob126acbca30a3115b25b6fedf8afb59b393edc476
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 (t . "open %s")
2146 (system . "open %s")
2147 ("ps.gz" . "gv %s")
2148 ("eps.gz" . "gv %s")
2149 ("dvi" . "xdvi %s")
2150 ("fig" . "xfig %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
2158 '(remote . emacs)
2159 (cons t
2160 (list (if (featurep 'xemacs)
2161 'mswindows-shell-execute
2162 'w32-shell-execute)
2163 "open" 'file))
2164 (cons 'system
2165 (list (if (featurep 'xemacs)
2166 'mswindows-shell-execute
2167 'w32-shell-execute)
2168 "open" 'file)))
2169 "Default file applications on a Windows NT system.
2170 The system \"open\" is used for most files.
2171 See `org-file-apps'.")
2173 (defcustom org-file-apps
2174 '((auto-mode . emacs)
2175 ("\\.mm\\'" . default)
2176 ("\\.x?html?\\'" . default)
2177 ("\\.pdf\\'" . default))
2178 "External applications for opening `file:path' items in a document.
2179 Org-mode uses system defaults for different file types, but
2180 you can use this variable to set the application for a given file
2181 extension. The entries in this list are cons cells where the car identifies
2182 files and the cdr the corresponding command. Possible values for the
2183 file identifier are
2184 \"string\" A string as a file identifier can be interpreted in different
2185 ways, depending on its contents:
2187 - Alphanumeric characters only:
2188 Match links with this file extension.
2189 Example: (\"pdf\" . \"evince %s\")
2190 to open PDFs with evince.
2192 - Regular expression: Match links where the
2193 filename matches the regexp. If you want to
2194 use groups here, use shy groups.
2196 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2197 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2198 to open *.html and *.xhtml with firefox.
2200 - Regular expression which contains (non-shy) groups:
2201 Match links where the whole link, including \"::\", and
2202 anything after that, matches the regexp.
2203 In a custom command string, %1, %2, etc. are replaced with
2204 the parts of the link that were matched by the groups.
2205 For backwards compatibility, if a command string is given
2206 that does not use any of the group matches, this case is
2207 handled identically to the second one (i.e. match against
2208 file name only).
2209 In a custom lisp form, you can access the group matches with
2210 (match-string n link).
2212 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2213 to open [[file:document.pdf::5]] with evince at page 5.
2215 `directory' Matches a directory
2216 `remote' Matches a remote file, accessible through tramp or efs.
2217 Remote files most likely should be visited through Emacs
2218 because external applications cannot handle such paths.
2219 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2220 so all files Emacs knows how to handle. Using this with
2221 command `emacs' will open most files in Emacs. Beware that this
2222 will also open html files inside Emacs, unless you add
2223 (\"html\" . default) to the list as well.
2224 t Default for files not matched by any of the other options.
2225 `system' The system command to open files, like `open' on Windows
2226 and Mac OS X, and mailcap under GNU/Linux. This is the command
2227 that will be selected if you call `C-c C-o' with a double
2228 \\[universal-argument] \\[universal-argument] prefix.
2230 Possible values for the command are:
2231 `emacs' The file will be visited by the current Emacs process.
2232 `default' Use the default application for this file type, which is the
2233 association for t in the list, most likely in the system-specific
2234 part.
2235 This can be used to overrule an unwanted setting in the
2236 system-specific variable.
2237 `system' Use the system command for opening files, like \"open\".
2238 This command is specified by the entry whose car is `system'.
2239 Most likely, the system-specific version of this variable
2240 does define this command, but you can overrule/replace it
2241 here.
2242 string A command to be executed by a shell; %s will be replaced
2243 by the path to the file.
2244 sexp A Lisp form which will be evaluated. The file path will
2245 be available in the Lisp variable `file'.
2246 For more examples, see the system specific constants
2247 `org-file-apps-defaults-macosx'
2248 `org-file-apps-defaults-windowsnt'
2249 `org-file-apps-defaults-gnu'."
2250 :group 'org-link-follow
2251 :type '(repeat
2252 (cons (choice :value ""
2253 (string :tag "Extension")
2254 (const :tag "System command to open files" system)
2255 (const :tag "Default for unrecognized files" t)
2256 (const :tag "Remote file" remote)
2257 (const :tag "Links to a directory" directory)
2258 (const :tag "Any files that have Emacs modes"
2259 auto-mode))
2260 (choice :value ""
2261 (const :tag "Visit with Emacs" emacs)
2262 (const :tag "Use default" default)
2263 (const :tag "Use the system command" system)
2264 (string :tag "Command")
2265 (sexp :tag "Lisp form")))))
2267 (defcustom org-doi-server-url "http://dx.doi.org/"
2268 "The URL of the DOI server."
2269 :type 'string
2270 :version "24.3"
2271 :group 'org-link-follow)
2273 (defgroup org-refile nil
2274 "Options concerning refiling entries in Org-mode."
2275 :tag "Org Refile"
2276 :group 'org)
2278 (defcustom org-directory "~/org"
2279 "Directory with Org files.
2280 This is just a default location to look for Org files. There is no need
2281 at all to put your files into this directory. It is used in the
2282 following situations:
2284 1. When a capture template specifies a target file that is not an
2285 absolute path. The path will then be interpreted relative to
2286 `org-directory'
2287 2. When the value of variable `org-agenda-files' is a single file, any
2288 relative paths in this file will be taken as relative to
2289 `org-directory'."
2290 :group 'org-refile
2291 :group 'org-capture
2292 :type 'directory)
2294 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2295 "Default target for storing notes.
2296 Used as a fall back file for org-capture.el, for templates that
2297 do not specify a target file."
2298 :group 'org-refile
2299 :group 'org-capture
2300 :type 'file)
2302 (defcustom org-goto-interface 'outline
2303 "The default interface to be used for `org-goto'.
2304 Allowed values are:
2305 outline The interface shows an outline of the relevant file
2306 and the correct heading is found by moving through
2307 the outline or by searching with incremental search.
2308 outline-path-completion Headlines in the current buffer are offered via
2309 completion. This is the interface also used by
2310 the refile command."
2311 :group 'org-refile
2312 :type '(choice
2313 (const :tag "Outline" outline)
2314 (const :tag "Outline-path-completion" outline-path-completion)))
2316 (defcustom org-goto-max-level 5
2317 "Maximum target level when running `org-goto' with refile interface."
2318 :group 'org-refile
2319 :type 'integer)
2321 (defcustom org-reverse-note-order nil
2322 "Non-nil means store new notes at the beginning of a file or entry.
2323 When nil, new notes will be filed to the end of a file or entry.
2324 This can also be a list with cons cells of regular expressions that
2325 are matched against file names, and values."
2326 :group 'org-capture
2327 :group 'org-refile
2328 :type '(choice
2329 (const :tag "Reverse always" t)
2330 (const :tag "Reverse never" nil)
2331 (repeat :tag "By file name regexp"
2332 (cons regexp boolean))))
2334 (defcustom org-log-refile nil
2335 "Information to record when a task is refiled.
2337 Possible values are:
2339 nil Don't add anything
2340 time Add a time stamp to the task
2341 note Prompt for a note and add it with template `org-log-note-headings'
2343 This option can also be set with on a per-file-basis with
2345 #+STARTUP: nologrefile
2346 #+STARTUP: logrefile
2347 #+STARTUP: lognoterefile
2349 You can have local logging settings for a subtree by setting the LOGGING
2350 property to one or more of these keywords.
2352 When bulk-refiling from the agenda, the value `note' is forbidden and
2353 will temporarily be changed to `time'."
2354 :group 'org-refile
2355 :group 'org-progress
2356 :version "24.1"
2357 :type '(choice
2358 (const :tag "No logging" nil)
2359 (const :tag "Record timestamp" time)
2360 (const :tag "Record timestamp with note." note)))
2362 (defcustom org-refile-targets nil
2363 "Targets for refiling entries with \\[org-refile].
2364 This is a list of cons cells. Each cell contains:
2365 - a specification of the files to be considered, either a list of files,
2366 or a symbol whose function or variable value will be used to retrieve
2367 a file name or a list of file names. If you use `org-agenda-files' for
2368 that, all agenda files will be scanned for targets. Nil means consider
2369 headings in the current buffer.
2370 - A specification of how to find candidate refile targets. This may be
2371 any of:
2372 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2373 This tag has to be present in all target headlines, inheritance will
2374 not be considered.
2375 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2376 todo keyword.
2377 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2378 headlines that are refiling targets.
2379 - a cons cell (:level . N). Any headline of level N is considered 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.
2382 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2383 Note that, when `org-odd-levels-only' is set, level corresponds to
2384 order in hierarchy, not to the number of stars.
2386 Each element of this list generates a set of possible targets.
2387 The union of these sets is presented (with completion) to
2388 the user by `org-refile'.
2390 You can set the variable `org-refile-target-verify-function' to a function
2391 to verify each headline found by the simple criteria above.
2393 When this variable is nil, all top-level headlines in the current buffer
2394 are used, equivalent to the value `((nil . (:level . 1))'."
2395 :group 'org-refile
2396 :type '(repeat
2397 (cons
2398 (choice :value org-agenda-files
2399 (const :tag "All agenda files" org-agenda-files)
2400 (const :tag "Current buffer" nil)
2401 (function) (variable) (file))
2402 (choice :tag "Identify target headline by"
2403 (cons :tag "Specific tag" (const :value :tag) (string))
2404 (cons :tag "TODO keyword" (const :value :todo) (string))
2405 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2406 (cons :tag "Level number" (const :value :level) (integer))
2407 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2409 (defcustom org-refile-target-verify-function nil
2410 "Function to verify if the headline at point should be a refile target.
2411 The function will be called without arguments, with point at the
2412 beginning of the headline. It should return t and leave point
2413 where it is if the headline is a valid target for refiling.
2415 If the target should not be selected, the function must return nil.
2416 In addition to this, it may move point to a place from where the search
2417 should be continued. For example, the function may decide that the entire
2418 subtree of the current entry should be excluded and move point to the end
2419 of the subtree."
2420 :group 'org-refile
2421 :type '(choice
2422 (const nil)
2423 (function)))
2425 (defcustom org-refile-use-cache nil
2426 "Non-nil means cache refile targets to speed up the process.
2427 \\<org-mode-map>\
2428 The cache for a particular file will be updated automatically when
2429 the buffer has been killed, or when any of the marker used for flagging
2430 refile targets no longer points at a live buffer.
2431 If you have added new entries to a buffer that might themselves be targets,
2432 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2433 if you find that easier, \
2434 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2435 \\[org-refile]'."
2436 :group 'org-refile
2437 :version "24.1"
2438 :type 'boolean)
2440 (defcustom org-refile-use-outline-path nil
2441 "Non-nil means provide refile targets as paths.
2442 So a level 3 headline will be available as level1/level2/level3.
2444 When the value is `file', also include the file name (without directory)
2445 into the path. In this case, you can also stop the completion after
2446 the file name, to get entries inserted as top level in the file.
2448 When `full-file-path', include the full file path."
2449 :group 'org-refile
2450 :type '(choice
2451 (const :tag "Not" nil)
2452 (const :tag "Yes" t)
2453 (const :tag "Start with file name" file)
2454 (const :tag "Start with full file path" full-file-path)))
2456 (defcustom org-outline-path-complete-in-steps t
2457 "Non-nil means complete the outline path in hierarchical steps.
2458 When Org-mode uses the refile interface to select an outline path
2459 \(see variable `org-refile-use-outline-path'), the completion of
2460 the path can be done in a single go, or it can be done in steps down
2461 the headline hierarchy. Going in steps is probably the best if you
2462 do not use a special completion package like `ido' or `icicles'.
2463 However, when using these packages, going in one step can be very
2464 fast, while still showing the whole path to the entry."
2465 :group 'org-refile
2466 :type 'boolean)
2468 (defcustom org-refile-allow-creating-parent-nodes nil
2469 "Non-nil means allow to create new nodes as refile targets.
2470 New nodes are then created by adding \"/new node name\" to the completion
2471 of an existing node. When the value of this variable is `confirm',
2472 new node creation must be confirmed by the user (recommended).
2473 When nil, the completion must match an existing entry.
2475 Note that, if the new heading is not seen by the criteria
2476 listed in `org-refile-targets', multiple instances of the same
2477 heading would be created by trying again to file under the new
2478 heading."
2479 :group 'org-refile
2480 :type '(choice
2481 (const :tag "Never" nil)
2482 (const :tag "Always" t)
2483 (const :tag "Prompt for confirmation" confirm)))
2485 (defcustom org-refile-active-region-within-subtree nil
2486 "Non-nil means also refile active region within a subtree.
2488 By default `org-refile' doesn't allow refiling regions if they
2489 don't contain a set of subtrees, but it might be convenient to
2490 do so sometimes: in that case, the first line of the region is
2491 converted to a headline before refiling."
2492 :group 'org-refile
2493 :version "24.1"
2494 :type 'boolean)
2496 (defgroup org-todo nil
2497 "Options concerning TODO items in Org-mode."
2498 :tag "Org TODO"
2499 :group 'org)
2501 (defgroup org-progress nil
2502 "Options concerning Progress logging in Org-mode."
2503 :tag "Org Progress"
2504 :group 'org-time)
2506 (defvar org-todo-interpretation-widgets
2507 '((:tag "Sequence (cycling hits every state)" sequence)
2508 (:tag "Type (cycling directly to DONE)" type))
2509 "The available interpretation symbols for customizing `org-todo-keywords'.
2510 Interested libraries should add to this list.")
2512 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2513 "List of TODO entry keyword sequences and their interpretation.
2514 \\<org-mode-map>This is a list of sequences.
2516 Each sequence starts with a symbol, either `sequence' or `type',
2517 indicating if the keywords should be interpreted as a sequence of
2518 action steps, or as different types of TODO items. The first
2519 keywords are states requiring action - these states will select a headline
2520 for inclusion into the global TODO list Org-mode produces. If one of
2521 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2522 signify that no further action is necessary. If \"|\" is not found,
2523 the last keyword is treated as the only DONE state of the sequence.
2525 The command \\[org-todo] cycles an entry through these states, and one
2526 additional state where no keyword is present. For details about this
2527 cycling, see the manual.
2529 TODO keywords and interpretation can also be set on a per-file basis with
2530 the special #+SEQ_TODO and #+TYP_TODO lines.
2532 Each keyword can optionally specify a character for fast state selection
2533 \(in combination with the variable `org-use-fast-todo-selection')
2534 and specifiers for state change logging, using the same syntax that
2535 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2536 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2537 indicates to record a time stamp each time this state is selected.
2539 Each keyword may also specify if a timestamp or a note should be
2540 recorded when entering or leaving the state, by adding additional
2541 characters in the parenthesis after the keyword. This looks like this:
2542 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2543 record only the time of the state change. With X and Y being either
2544 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2545 Y when leaving the state if and only if the *target* state does not
2546 define X. You may omit any of the fast-selection key or X or /Y,
2547 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2549 For backward compatibility, this variable may also be just a list
2550 of keywords. In this case the interpretation (sequence or type) will be
2551 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2552 :group 'org-todo
2553 :group 'org-keywords
2554 :type '(choice
2555 (repeat :tag "Old syntax, just keywords"
2556 (string :tag "Keyword"))
2557 (repeat :tag "New syntax"
2558 (cons
2559 (choice
2560 :tag "Interpretation"
2561 ;;Quick and dirty way to see
2562 ;;`org-todo-interpretations'. This takes the
2563 ;;place of item arguments
2564 :convert-widget
2565 (lambda (widget)
2566 (widget-put widget
2567 :args (mapcar
2568 (lambda (x)
2569 (widget-convert
2570 (cons 'const x)))
2571 org-todo-interpretation-widgets))
2572 widget))
2573 (repeat
2574 (string :tag "Keyword"))))))
2576 (defvar-local org-todo-keywords-1 nil
2577 "All TODO and DONE keywords active in a buffer.")
2578 (defvar org-todo-keywords-for-agenda nil)
2579 (defvar org-done-keywords-for-agenda nil)
2580 (defvar org-todo-keyword-alist-for-agenda nil)
2581 (defvar org-tag-alist-for-agenda nil
2582 "Alist of all tags from all agenda files.")
2583 (defvar org-tag-groups-alist-for-agenda nil
2584 "Alist of all groups tags from all current agenda files.")
2585 (defvar-local org-tag-groups-alist nil)
2586 (defvar org-agenda-contributing-files nil)
2587 (defvar-local org-not-done-keywords nil)
2588 (defvar-local org-done-keywords nil)
2589 (defvar-local org-todo-heads nil)
2590 (defvar-local org-todo-sets nil)
2591 (defvar-local org-todo-log-states nil)
2592 (defvar-local org-todo-kwd-alist nil)
2593 (defvar-local org-todo-key-alist nil)
2594 (defvar-local org-todo-key-trigger nil)
2596 (defcustom org-todo-interpretation 'sequence
2597 "Controls how TODO keywords are interpreted.
2598 This variable is in principle obsolete and is only used for
2599 backward compatibility, if the interpretation of todo keywords is
2600 not given already in `org-todo-keywords'. See that variable for
2601 more information."
2602 :group 'org-todo
2603 :group 'org-keywords
2604 :type '(choice (const sequence)
2605 (const type)))
2607 (defcustom org-use-fast-todo-selection t
2608 "\\<org-mode-map>\
2609 Non-nil means use the fast todo selection scheme with \\[org-todo].
2610 This variable describes if and under what circumstances the cycling
2611 mechanism for TODO keywords will be replaced by a single-key, direct
2612 selection scheme.
2614 When nil, fast selection is never used.
2616 When the symbol `prefix', it will be used when `org-todo' is called
2617 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2618 in an Org-mode buffer, and
2619 `\\[universal-argument] t' in an agenda buffer.
2621 When t, fast selection is used by default. In this case, the prefix
2622 argument forces cycling instead.
2624 In all cases, the special interface is only used if access keys have
2625 actually been assigned by the user, i.e. if keywords in the configuration
2626 are followed by a letter in parenthesis, like TODO(t)."
2627 :group 'org-todo
2628 :type '(choice
2629 (const :tag "Never" nil)
2630 (const :tag "By default" t)
2631 (const :tag "Only with C-u C-c C-t" prefix)))
2633 (defcustom org-provide-todo-statistics t
2634 "Non-nil means update todo statistics after insert and toggle.
2635 ALL-HEADLINES means update todo statistics by including headlines
2636 with no TODO keyword as well, counting them as not done.
2637 A list of TODO keywords means the same, but skip keywords that are
2638 not in this list.
2639 When set to a list of two lists, the first list contains keywords
2640 to consider as TODO keywords, the second list contains keywords
2641 to consider as DONE keywords.
2643 When this is set, todo statistics is updated in the parent of the
2644 current entry each time a todo state is changed."
2645 :group 'org-todo
2646 :type '(choice
2647 (const :tag "Yes, only for TODO entries" t)
2648 (const :tag "Yes, including all entries" all-headlines)
2649 (repeat :tag "Yes, for TODOs in this list"
2650 (string :tag "TODO keyword"))
2651 (list :tag "Yes, for TODOs and DONEs in these lists"
2652 (repeat (string :tag "TODO keyword"))
2653 (repeat (string :tag "DONE keyword")))
2654 (other :tag "No TODO statistics" nil)))
2656 (defcustom org-hierarchical-todo-statistics t
2657 "Non-nil means TODO statistics covers just direct children.
2658 When nil, all entries in the subtree are considered.
2659 This has only an effect if `org-provide-todo-statistics' is set.
2660 To set this to nil for only a single subtree, use a COOKIE_DATA
2661 property and include the word \"recursive\" into the value."
2662 :group 'org-todo
2663 :type 'boolean)
2665 (defcustom org-after-todo-state-change-hook nil
2666 "Hook which is run after the state of a TODO item was changed.
2667 The new state (a string with a TODO keyword, or nil) is available in the
2668 Lisp variable `org-state'."
2669 :group 'org-todo
2670 :type 'hook)
2672 (defvar org-blocker-hook nil
2673 "Hook for functions that are allowed to block a state change.
2675 Functions in this hook should not modify the buffer.
2676 Each function gets as its single argument a property list,
2677 see `org-trigger-hook' for more information about this list.
2679 If any of the functions in this hook returns nil, the state change
2680 is blocked.")
2682 (defvar org-trigger-hook nil
2683 "Hook for functions that are triggered by a state change.
2685 Each function gets as its single argument a property list with at
2686 least the following elements:
2688 (:type type-of-change :position pos-at-entry-start
2689 :from old-state :to new-state)
2691 Depending on the type, more properties may be present.
2693 This mechanism is currently implemented for:
2695 TODO state changes
2696 ------------------
2697 :type todo-state-change
2698 :from previous state (keyword as a string), or nil, or a symbol
2699 `todo' or `done', to indicate the general type of state.
2700 :to new state, like in :from")
2702 (defcustom org-enforce-todo-dependencies nil
2703 "Non-nil means undone TODO entries will block switching the parent to DONE.
2704 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2705 be blocked if any prior sibling is not yet done.
2706 Finally, if the parent is blocked because of ordered siblings of its own,
2707 the child will also be blocked."
2708 :set (lambda (var val)
2709 (set var val)
2710 (if val
2711 (add-hook 'org-blocker-hook
2712 'org-block-todo-from-children-or-siblings-or-parent)
2713 (remove-hook 'org-blocker-hook
2714 'org-block-todo-from-children-or-siblings-or-parent)))
2715 :group 'org-todo
2716 :type 'boolean)
2718 (defcustom org-enforce-todo-checkbox-dependencies nil
2719 "Non-nil means unchecked boxes will block switching the parent to DONE.
2720 When this is nil, checkboxes have no influence on switching TODO states.
2721 When non-nil, you first need to check off all check boxes before the TODO
2722 entry can be switched to DONE.
2723 This variable needs to be set before org.el is loaded, and you need to
2724 restart Emacs after a change to make the change effective. The only way
2725 to change is while Emacs is running is through the customize interface."
2726 :set (lambda (var val)
2727 (set var val)
2728 (if val
2729 (add-hook 'org-blocker-hook
2730 'org-block-todo-from-checkboxes)
2731 (remove-hook 'org-blocker-hook
2732 'org-block-todo-from-checkboxes)))
2733 :group 'org-todo
2734 :type 'boolean)
2736 (defcustom org-treat-insert-todo-heading-as-state-change nil
2737 "Non-nil means inserting a TODO heading is treated as state change.
2738 So when the command \\[org-insert-todo-heading] is used, state change
2739 logging will apply if appropriate. When nil, the new TODO item will
2740 be inserted directly, and no logging will take place."
2741 :group 'org-todo
2742 :type 'boolean)
2744 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2745 "Non-nil means switching TODO states with S-cursor counts as state change.
2746 This is the default behavior. However, setting this to nil allows a
2747 convenient way to select a TODO state and bypass any logging associated
2748 with that."
2749 :group 'org-todo
2750 :type 'boolean)
2752 (defcustom org-todo-state-tags-triggers nil
2753 "Tag changes that should be triggered by TODO state changes.
2754 This is a list. Each entry is
2756 (state-change (tag . flag) .......)
2758 State-change can be a string with a state, and empty string to indicate the
2759 state that has no TODO keyword, or it can be one of the symbols `todo'
2760 or `done', meaning any not-done or done state, respectively."
2761 :group 'org-todo
2762 :group 'org-tags
2763 :type '(repeat
2764 (cons (choice :tag "When changing to"
2765 (const :tag "Not-done state" todo)
2766 (const :tag "Done state" done)
2767 (string :tag "State"))
2768 (repeat
2769 (cons :tag "Tag action"
2770 (string :tag "Tag")
2771 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2773 (defcustom org-log-done nil
2774 "Information to record when a task moves to the DONE state.
2776 Possible values are:
2778 nil Don't add anything, just change the keyword
2779 time Add a time stamp to the task
2780 note Prompt for a note and add it with template `org-log-note-headings'
2782 This option can also be set with on a per-file-basis with
2784 #+STARTUP: nologdone
2785 #+STARTUP: logdone
2786 #+STARTUP: lognotedone
2788 You can have local logging settings for a subtree by setting the LOGGING
2789 property to one or more of these keywords."
2790 :group 'org-todo
2791 :group 'org-progress
2792 :type '(choice
2793 (const :tag "No logging" nil)
2794 (const :tag "Record CLOSED timestamp" time)
2795 (const :tag "Record CLOSED timestamp with note." note)))
2797 ;; Normalize old uses of org-log-done.
2798 (cond
2799 ((eq org-log-done t) (setq org-log-done 'time))
2800 ((and (listp org-log-done) (memq 'done org-log-done))
2801 (setq org-log-done 'note)))
2803 (defcustom org-log-reschedule nil
2804 "Information to record when the scheduling date of a tasks is modified.
2806 Possible values are:
2808 nil Don't add anything, just change the date
2809 time Add a time stamp to the task
2810 note Prompt for a note and add it with template `org-log-note-headings'
2812 This option can also be set with on a per-file-basis with
2814 #+STARTUP: nologreschedule
2815 #+STARTUP: logreschedule
2816 #+STARTUP: lognotereschedule"
2817 :group 'org-todo
2818 :group 'org-progress
2819 :type '(choice
2820 (const :tag "No logging" nil)
2821 (const :tag "Record timestamp" time)
2822 (const :tag "Record timestamp with note." note)))
2824 (defcustom org-log-redeadline nil
2825 "Information to record when the deadline date of a tasks is modified.
2827 Possible values are:
2829 nil Don't add anything, just change the date
2830 time Add a time stamp to the task
2831 note Prompt for a note and add it with template `org-log-note-headings'
2833 This option can also be set with on a per-file-basis with
2835 #+STARTUP: nologredeadline
2836 #+STARTUP: logredeadline
2837 #+STARTUP: lognoteredeadline
2839 You can have local logging settings for a subtree by setting the LOGGING
2840 property to one or more of these keywords."
2841 :group 'org-todo
2842 :group 'org-progress
2843 :type '(choice
2844 (const :tag "No logging" nil)
2845 (const :tag "Record timestamp" time)
2846 (const :tag "Record timestamp with note." note)))
2848 (defcustom org-log-note-clock-out nil
2849 "Non-nil means record a note when clocking out of an item.
2850 This can also be configured on a per-file basis by adding one of
2851 the following lines anywhere in the buffer:
2853 #+STARTUP: lognoteclock-out
2854 #+STARTUP: nolognoteclock-out"
2855 :group 'org-todo
2856 :group 'org-progress
2857 :type 'boolean)
2859 (defcustom org-log-done-with-time t
2860 "Non-nil means the CLOSED time stamp will contain date and time.
2861 When nil, only the date will be recorded."
2862 :group 'org-progress
2863 :type 'boolean)
2865 (defcustom org-log-note-headings
2866 '((done . "CLOSING NOTE %t")
2867 (state . "State %-12s from %-12S %t")
2868 (note . "Note taken on %t")
2869 (reschedule . "Rescheduled from %S on %t")
2870 (delschedule . "Not scheduled, was %S on %t")
2871 (redeadline . "New deadline from %S on %t")
2872 (deldeadline . "Removed deadline, was %S on %t")
2873 (refile . "Refiled on %t")
2874 (clock-out . ""))
2875 "Headings for notes added to entries.
2877 The value is an alist, with the car being a symbol indicating the
2878 note context, and the cdr is the heading to be used. The heading
2879 may also be the empty string. The following placeholders can be
2880 used:
2882 %t a time stamp.
2883 %T an active time stamp instead the default inactive one
2884 %d a short-format time stamp.
2885 %D an active short-format time stamp.
2886 %s the new TODO state or time stamp (inactive), in double quotes.
2887 %S the old TODO state or time stamp (inactive), in double quotes.
2888 %u the user name.
2889 %U full user name.
2891 In fact, it is not a good idea to change the `state' entry,
2892 because Agenda Log mode depends on the format of these entries."
2893 :group 'org-todo
2894 :group 'org-progress
2895 :type '(list :greedy t
2896 (cons (const :tag "Heading when closing an item" done) string)
2897 (cons (const :tag
2898 "Heading when changing todo state (todo sequence only)"
2899 state) string)
2900 (cons (const :tag "Heading when just taking a note" note) string)
2901 (cons (const :tag "Heading when rescheduling" reschedule) string)
2902 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2903 (cons (const :tag "Heading when changing deadline" redeadline) string)
2904 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2905 (cons (const :tag "Heading when refiling" refile) string)
2906 (cons (const :tag "Heading when clocking out" clock-out) string)))
2908 (unless (assq 'note org-log-note-headings)
2909 (push '(note . "%t") org-log-note-headings))
2911 (defcustom org-log-into-drawer nil
2912 "Non-nil means insert state change notes and time stamps into a drawer.
2913 When nil, state changes notes will be inserted after the headline and
2914 any scheduling and clock lines, but not inside a drawer.
2916 The value of this variable should be the name of the drawer to use.
2917 LOGBOOK is proposed as the default drawer for this purpose, you can
2918 also set this to a string to define the drawer of your choice.
2920 A value of t is also allowed, representing \"LOGBOOK\".
2922 A value of t or nil can also be set with on a per-file-basis with
2924 #+STARTUP: logdrawer
2925 #+STARTUP: nologdrawer
2927 If this variable is set, `org-log-state-notes-insert-after-drawers'
2928 will be ignored.
2930 You can set the property LOG_INTO_DRAWER to overrule this setting for
2931 a subtree.
2933 Do not check directly this variable in a Lisp program. Call
2934 function `org-log-into-drawer' instead."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(choice
2938 (const :tag "Not into a drawer" nil)
2939 (const :tag "LOGBOOK" t)
2940 (string :tag "Other")))
2942 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2944 (defun org-log-into-drawer ()
2945 "Name of the log drawer, as a string, or nil.
2946 This is the value of `org-log-into-drawer'. However, if the
2947 current entry has or inherits a LOG_INTO_DRAWER property, it will
2948 be used instead of the default value."
2949 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2950 (cond ((equal p "nil") nil)
2951 ((equal p "t") "LOGBOOK")
2952 ((stringp p) p)
2953 (p "LOGBOOK")
2954 ((stringp org-log-into-drawer) org-log-into-drawer)
2955 (org-log-into-drawer "LOGBOOK"))))
2957 (defcustom org-log-state-notes-insert-after-drawers nil
2958 "Non-nil means insert state change notes after any drawers in entry.
2959 Only the drawers that *immediately* follow the headline and the
2960 deadline/scheduled line are skipped.
2961 When nil, insert notes right after the heading and perhaps the line
2962 with deadline/scheduling if present.
2964 This variable will have no effect if `org-log-into-drawer' is
2965 set."
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-states-order-reversed t
2971 "Non-nil means the latest state note will be directly after heading.
2972 When nil, the state change notes will be ordered according to time.
2974 This option can also be set with on a per-file-basis with
2976 #+STARTUP: logstatesreversed
2977 #+STARTUP: nologstatesreversed"
2978 :group 'org-todo
2979 :group 'org-progress
2980 :type 'boolean)
2982 (defcustom org-todo-repeat-to-state nil
2983 "The TODO state to which a repeater should return the repeating task.
2984 By default this is the first task in a TODO sequence, or the previous state
2985 in a TODO_TYP set. But you can specify another task here.
2986 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2987 :group 'org-todo
2988 :version "24.1"
2989 :type '(choice (const :tag "Head of sequence" nil)
2990 (string :tag "Specific state")))
2992 (defcustom org-log-repeat 'time
2993 "Non-nil means record moving through the DONE state when triggering repeat.
2994 An auto-repeating task is immediately switched back to TODO when
2995 marked DONE. If you are not logging state changes (by adding \"@\"
2996 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2997 record a closing note, there will be no record of the task moving
2998 through DONE. This variable forces taking a note anyway.
3000 nil Don't force a record
3001 time Record a time stamp
3002 note Prompt for a note and add it with template `org-log-note-headings'
3004 This option can also be set with on a per-file-basis with
3006 #+STARTUP: nologrepeat
3007 #+STARTUP: logrepeat
3008 #+STARTUP: lognoterepeat
3010 You can have local logging settings for a subtree by setting the LOGGING
3011 property to one or more of these keywords."
3012 :group 'org-todo
3013 :group 'org-progress
3014 :type '(choice
3015 (const :tag "Don't force a record" nil)
3016 (const :tag "Force recording the DONE state" time)
3017 (const :tag "Force recording a note with the DONE state" note)))
3020 (defgroup org-priorities nil
3021 "Priorities in Org-mode."
3022 :tag "Org Priorities"
3023 :group 'org-todo)
3025 (defcustom org-enable-priority-commands t
3026 "Non-nil means priority commands are active.
3027 When nil, these commands will be disabled, so that you never accidentally
3028 set a priority."
3029 :group 'org-priorities
3030 :type 'boolean)
3032 (defcustom org-highest-priority ?A
3033 "The highest priority of TODO items. A character like ?A, ?B etc.
3034 Must have a smaller ASCII number than `org-lowest-priority'."
3035 :group 'org-priorities
3036 :type 'character)
3038 (defcustom org-lowest-priority ?C
3039 "The lowest priority of TODO items. A character like ?A, ?B etc.
3040 Must have a larger ASCII number than `org-highest-priority'."
3041 :group 'org-priorities
3042 :type 'character)
3044 (defcustom org-default-priority ?B
3045 "The default priority of TODO items.
3046 This is the priority an item gets if no explicit priority is given.
3047 When starting to cycle on an empty priority the first step in the cycle
3048 depends on `org-priority-start-cycle-with-default'. The resulting first
3049 step priority must not exceed the range from `org-highest-priority' to
3050 `org-lowest-priority' which means that `org-default-priority' has to be
3051 in this range exclusive or inclusive the range boundaries. Else the
3052 first step refuses to set the default and the second will fall back
3053 to (depending on the command used) the highest or lowest priority."
3054 :group 'org-priorities
3055 :type 'character)
3057 (defcustom org-priority-start-cycle-with-default t
3058 "Non-nil means start with default priority when starting to cycle.
3059 When this is nil, the first step in the cycle will be (depending on the
3060 command used) one higher or lower than the default priority.
3061 See also `org-default-priority'."
3062 :group 'org-priorities
3063 :type 'boolean)
3065 (defcustom org-get-priority-function nil
3066 "Function to extract the priority from a string.
3067 The string is normally the headline. If this is nil Org computes the
3068 priority from the priority cookie like [#A] in the headline. It returns
3069 an integer, increasing by 1000 for each priority level.
3070 The user can set a different function here, which should take a string
3071 as an argument and return the numeric priority."
3072 :group 'org-priorities
3073 :version "24.1"
3074 :type '(choice
3075 (const nil)
3076 (function)))
3078 (defgroup org-time nil
3079 "Options concerning time stamps and deadlines in Org-mode."
3080 :tag "Org Time"
3081 :group 'org)
3083 (defcustom org-time-stamp-rounding-minutes '(0 5)
3084 "Number of minutes to round time stamps to.
3085 \\<org-mode-map>\
3086 These are two values, the first applies when first creating a time stamp.
3087 The second applies when changing it with the commands `S-up' and `S-down'.
3088 When changing the time stamp, this means that it will change in steps
3089 of N minutes, as given by the second value.
3091 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3092 numbers should be factors of 60, so for example 5, 10, 15.
3094 When this is larger than 1, you can still force an exact time stamp by using
3095 a double prefix argument to a time stamp command like \
3096 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3097 and by using a prefix arg to `S-up/down' to specify the exact number
3098 of minutes to shift."
3099 :group 'org-time
3100 :get (lambda (var) ; Make sure both elements are there
3101 (if (integerp (default-value var))
3102 (list (default-value var) 5)
3103 (default-value var)))
3104 :type '(list
3105 (integer :tag "when inserting times")
3106 (integer :tag "when modifying times")))
3108 ;; Normalize old customizations of this variable.
3109 (when (integerp org-time-stamp-rounding-minutes)
3110 (setq org-time-stamp-rounding-minutes
3111 (list org-time-stamp-rounding-minutes
3112 org-time-stamp-rounding-minutes)))
3114 (defcustom org-display-custom-times nil
3115 "Non-nil means overlay custom formats over all time stamps.
3116 The formats are defined through the variable `org-time-stamp-custom-formats'.
3117 To turn this on on a per-file basis, insert anywhere in the file:
3118 #+STARTUP: customtime"
3119 :group 'org-time
3120 :set 'set-default
3121 :type 'sexp)
3122 (make-variable-buffer-local 'org-display-custom-times)
3124 (defcustom org-time-stamp-custom-formats
3125 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3126 "Custom formats for time stamps. See `format-time-string' for the syntax.
3127 These are overlaid over the default ISO format if the variable
3128 `org-display-custom-times' is set. Time like %H:%M should be at the
3129 end of the second format. The custom formats are also honored by export
3130 commands, if custom time display is turned on at the time of export."
3131 :group 'org-time
3132 :type 'sexp)
3134 (defun org-time-stamp-format (&optional long inactive)
3135 "Get the right format for a time string."
3136 (let ((f (if long (cdr org-time-stamp-formats)
3137 (car org-time-stamp-formats))))
3138 (if inactive
3139 (concat "[" (substring f 1 -1) "]")
3140 f)))
3142 (defcustom org-time-clocksum-format
3143 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3144 "The format string used when creating CLOCKSUM lines.
3145 This is also used when Org mode generates a time duration.
3147 The value can be a single format string containing two
3148 %-sequences, which will be filled with the number of hours and
3149 minutes in that order.
3151 Alternatively, the value can be a plist associating any of the
3152 keys :years, :months, :weeks, :days, :hours or :minutes with
3153 format strings. The time duration is formatted using only the
3154 time components that are needed and concatenating the results.
3155 If a time unit in absent, it falls back to the next smallest
3156 unit.
3158 The keys :require-years, :require-months, :require-days,
3159 :require-weeks, :require-hours, :require-minutes are also
3160 meaningful. A non-nil value for these keys indicates that the
3161 corresponding time component should always be included, even if
3162 its value is 0.
3165 For example,
3167 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3168 :require-minutes t)
3170 means durations longer than a day will be expressed in days,
3171 hours and minutes, and durations less than a day will always be
3172 expressed in hours and minutes (even for durations less than an
3173 hour).
3175 The value
3177 (:days \"%dd\" :minutes \"%dm\")
3179 means durations longer than a day will be expressed in days and
3180 minutes, and durations less than a day will be expressed entirely
3181 in minutes (even for durations longer than an hour)."
3182 :group 'org-time
3183 :group 'org-clock
3184 :version "24.4"
3185 :package-version '(Org . "8.0")
3186 :type '(choice (string :tag "Format string")
3187 (set :tag "Plist"
3188 (group :inline t (const :tag "Years" :years)
3189 (string :tag "Format string"))
3190 (group :inline t
3191 (const :tag "Always show years" :require-years)
3192 (const t))
3193 (group :inline t (const :tag "Months" :months)
3194 (string :tag "Format string"))
3195 (group :inline t
3196 (const :tag "Always show months" :require-months)
3197 (const t))
3198 (group :inline t (const :tag "Weeks" :weeks)
3199 (string :tag "Format string"))
3200 (group :inline t
3201 (const :tag "Always show weeks" :require-weeks)
3202 (const t))
3203 (group :inline t (const :tag "Days" :days)
3204 (string :tag "Format string"))
3205 (group :inline t
3206 (const :tag "Always show days" :require-days)
3207 (const t))
3208 (group :inline t (const :tag "Hours" :hours)
3209 (string :tag "Format string"))
3210 (group :inline t
3211 (const :tag "Always show hours" :require-hours)
3212 (const t))
3213 (group :inline t (const :tag "Minutes" :minutes)
3214 (string :tag "Format string"))
3215 (group :inline t
3216 (const :tag "Always show minutes" :require-minutes)
3217 (const t)))))
3219 (defcustom org-time-clocksum-use-fractional nil
3220 "When non-nil, \\[org-clock-display] uses fractional times.
3221 See `org-time-clocksum-format' for more on time clock formats."
3222 :group 'org-time
3223 :group 'org-clock
3224 :version "24.3"
3225 :type 'boolean)
3227 (defcustom org-time-clocksum-use-effort-durations nil
3228 "When non-nil, \\[org-clock-display] uses effort durations.
3229 E.g. by default, one day is considered to be a 8 hours effort,
3230 so a task that has been clocked for 16 hours will be displayed
3231 as during 2 days in the clock display or in the clocktable.
3233 See `org-effort-durations' on how to set effort durations
3234 and `org-time-clocksum-format' for more on time clock formats."
3235 :group 'org-time
3236 :group 'org-clock
3237 :version "24.4"
3238 :package-version '(Org . "8.0")
3239 :type 'boolean)
3241 (defcustom org-time-clocksum-fractional-format "%.2f"
3242 "The format string used when creating CLOCKSUM lines,
3243 or when Org mode generates a time duration, if
3244 `org-time-clocksum-use-fractional' is enabled.
3246 The value can be a single format string containing one
3247 %-sequence, which will be filled with the number of hours as
3248 a float.
3250 Alternatively, the value can be a plist associating any of the
3251 keys :years, :months, :weeks, :days, :hours or :minutes with
3252 a format string. The time duration is formatted using the
3253 largest time unit which gives a non-zero integer part. If all
3254 specified formats have zero integer part, the smallest time unit
3255 is used."
3256 :group 'org-time
3257 :type '(choice (string :tag "Format string")
3258 (set (group :inline t (const :tag "Years" :years)
3259 (string :tag "Format string"))
3260 (group :inline t (const :tag "Months" :months)
3261 (string :tag "Format string"))
3262 (group :inline t (const :tag "Weeks" :weeks)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Days" :days)
3265 (string :tag "Format string"))
3266 (group :inline t (const :tag "Hours" :hours)
3267 (string :tag "Format string"))
3268 (group :inline t (const :tag "Minutes" :minutes)
3269 (string :tag "Format string")))))
3271 (defcustom org-deadline-warning-days 14
3272 "Number of days before expiration during which a deadline becomes active.
3273 This variable governs the display in sparse trees and in the agenda.
3274 When 0 or negative, it means use this number (the absolute value of it)
3275 even if a deadline has a different individual lead time specified.
3277 Custom commands can set this variable in the options section."
3278 :group 'org-time
3279 :group 'org-agenda-daily/weekly
3280 :type 'integer)
3282 (defcustom org-scheduled-delay-days 0
3283 "Number of days before a scheduled item becomes active.
3284 This variable governs the display in sparse trees and in the agenda.
3285 The default value (i.e. 0) means: don't delay scheduled item.
3286 When negative, it means use this number (the absolute value of it)
3287 even if a scheduled item has a different individual delay time
3288 specified.
3290 Custom commands can set this variable in the options section."
3291 :group 'org-time
3292 :group 'org-agenda-daily/weekly
3293 :version "24.4"
3294 :package-version '(Org . "8.0")
3295 :type 'integer)
3297 (defcustom org-read-date-prefer-future t
3298 "Non-nil means assume future for incomplete date input from user.
3299 This affects the following situations:
3300 1. The user gives a month but not a year.
3301 For example, if it is April and you enter \"feb 2\", this will be read
3302 as Feb 2, *next* year. \"May 5\", however, will be this year.
3303 2. The user gives a day, but no month.
3304 For example, if today is the 15th, and you enter \"3\", Org-mode will
3305 read this as the third of *next* month. However, if you enter \"17\",
3306 it will be considered as *this* month.
3308 If you set this variable to the symbol `time', then also the following
3309 will work:
3311 3. If the user gives a time.
3312 If the time is before now, it will be interpreted as tomorrow.
3314 Currently none of this works for ISO week specifications.
3316 When this option is nil, the current day, month and year will always be
3317 used as defaults.
3319 See also `org-agenda-jump-prefer-future'."
3320 :group 'org-time
3321 :type '(choice
3322 (const :tag "Never" nil)
3323 (const :tag "Check month and day" t)
3324 (const :tag "Check month, day, and time" time)))
3326 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3327 "Should the agenda jump command prefer the future for incomplete dates?
3328 The default is to do the same as configured in `org-read-date-prefer-future'.
3329 But you can also set a deviating value here.
3330 This may t or nil, or the symbol `org-read-date-prefer-future'."
3331 :group 'org-agenda
3332 :group 'org-time
3333 :version "24.1"
3334 :type '(choice
3335 (const :tag "Use org-read-date-prefer-future"
3336 org-read-date-prefer-future)
3337 (const :tag "Never" nil)
3338 (const :tag "Always" t)))
3340 (defcustom org-read-date-force-compatible-dates t
3341 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3343 Depending on the system Emacs is running on, certain dates cannot
3344 be represented with the type used internally to represent time.
3345 Dates between 1970-1-1 and 2038-1-1 can always be represented
3346 correctly. Some systems allow for earlier dates, some for later,
3347 some for both. One way to find out it to insert any date into an
3348 Org buffer, putting the cursor on the year and hitting S-up and
3349 S-down to test the range.
3351 When this variable is set to t, the date/time prompt will not let
3352 you specify dates outside the 1970-2037 range, so it is certain that
3353 these dates will work in whatever version of Emacs you are
3354 running, and also that you can move a file from one Emacs implementation
3355 to another. WHenever Org is forcing the year for you, it will display
3356 a message and beep.
3358 When this variable is nil, Org will check if the date is
3359 representable in the specific Emacs implementation you are using.
3360 If not, it will force a year, usually the current year, and beep
3361 to remind you. Currently this setting is not recommended because
3362 the likelihood that you will open your Org files in an Emacs that
3363 has limited date range is not negligible.
3365 A workaround for this problem is to use diary sexp dates for time
3366 stamps outside of this range."
3367 :group 'org-time
3368 :version "24.1"
3369 :type 'boolean)
3371 (defcustom org-read-date-display-live t
3372 "Non-nil means display current interpretation of date prompt live.
3373 This display will be in an overlay, in the minibuffer."
3374 :group 'org-time
3375 :type 'boolean)
3377 (defcustom org-read-date-popup-calendar t
3378 "Non-nil means pop up a calendar when prompting for a date.
3379 In the calendar, the date can be selected with mouse-1. However, the
3380 minibuffer will also be active, and you can simply enter the date as well.
3381 When nil, only the minibuffer will be available."
3382 :group 'org-time
3383 :type 'boolean)
3384 (org-defvaralias 'org-popup-calendar-for-date-prompt
3385 'org-read-date-popup-calendar)
3387 (make-obsolete-variable
3388 'org-read-date-minibuffer-setup-hook
3389 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3390 (defcustom org-read-date-minibuffer-setup-hook nil
3391 "Hook to be used to set up keys for the date/time interface.
3392 Add key definitions to `minibuffer-local-map', which will be a
3393 temporary copy.
3395 WARNING: This option is obsolete, you should use
3396 `org-read-date-minibuffer-local-map' to set up keys."
3397 :group 'org-time
3398 :type 'hook)
3400 (defcustom org-extend-today-until 0
3401 "The hour when your day really ends. Must be an integer.
3402 This has influence for the following applications:
3403 - When switching the agenda to \"today\". It it is still earlier than
3404 the time given here, the day recognized as TODAY is actually yesterday.
3405 - When a date is read from the user and it is still before the time given
3406 here, the current date and time will be assumed to be yesterday, 23:59.
3407 Also, timestamps inserted in capture templates follow this rule.
3409 IMPORTANT: This is a feature whose implementation is and likely will
3410 remain incomplete. Really, it is only here because past midnight seems to
3411 be the favorite working time of John Wiegley :-)"
3412 :group 'org-time
3413 :type 'integer)
3415 (defcustom org-use-effective-time nil
3416 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3417 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3418 \"effective time\" of any timestamps between midnight and 8am will be
3419 23:59 of the previous day."
3420 :group 'org-time
3421 :version "24.1"
3422 :type 'boolean)
3424 (defcustom org-use-last-clock-out-time-as-effective-time nil
3425 "When non-nil, use the last clock out time for `org-todo'.
3426 Note that this option has precedence over the combined use of
3427 `org-use-effective-time' and `org-extend-today-until'."
3428 :group 'org-time
3429 :version "24.4"
3430 :package-version '(Org . "8.0")
3431 :type 'boolean)
3433 (defcustom org-edit-timestamp-down-means-later nil
3434 "Non-nil means S-down will increase the time in a time stamp.
3435 When nil, S-up will increase."
3436 :group 'org-time
3437 :type 'boolean)
3439 (defcustom org-calendar-follow-timestamp-change t
3440 "Non-nil means make the calendar window follow timestamp changes.
3441 When a timestamp is modified and the calendar window is visible, it will be
3442 moved to the new date."
3443 :group 'org-time
3444 :type 'boolean)
3446 (defgroup org-tags nil
3447 "Options concerning tags in Org-mode."
3448 :tag "Org Tags"
3449 :group 'org)
3451 (defcustom org-tag-alist nil
3452 "List of tags allowed in Org-mode files.
3453 When this list is nil, Org-mode will base TAG input on what is already in the
3454 buffer.
3455 The value of this variable is an alist, the car of each entry must be a
3456 keyword as a string, the cdr may be a character that is used to select
3457 that tag through the fast-tag-selection interface.
3458 See the manual for details."
3459 :group 'org-tags
3460 :type '(repeat
3461 (choice
3462 (cons (string :tag "Tag name")
3463 (character :tag "Access char"))
3464 (list :tag "Start radio group"
3465 (const :startgroup)
3466 (option (string :tag "Group description")))
3467 (list :tag "Start tag group, non distinct"
3468 (const :startgrouptag)
3469 (option (string :tag "Group description")))
3470 (list :tag "Group tags delimiter"
3471 (const :grouptags))
3472 (list :tag "End radio group"
3473 (const :endgroup)
3474 (option (string :tag "Group description")))
3475 (list :tag "End tag group, non distinct"
3476 (const :endgrouptag)
3477 (option (string :tag "Group description")))
3478 (const :tag "New line" (:newline)))))
3480 (defcustom org-tag-persistent-alist nil
3481 "List of tags that will always appear in all Org-mode files.
3482 This is in addition to any in buffer settings or customizations
3483 of `org-tag-alist'.
3484 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3485 The value of this variable is an alist, the car of each entry must be a
3486 keyword as a string, the cdr may be a character that is used to select
3487 that tag through the fast-tag-selection interface.
3488 See the manual for details.
3489 To disable these tags on a per-file basis, insert anywhere in the file:
3490 #+STARTUP: noptag"
3491 :group 'org-tags
3492 :type '(repeat
3493 (choice
3494 (cons (string :tag "Tag name")
3495 (character :tag "Access char"))
3496 (const :tag "Start radio group" (:startgroup))
3497 (const :tag "Group tags delimiter" (:grouptags))
3498 (const :tag "End radio group" (:endgroup))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org-mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-string-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Check if PROPERTY is one that should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defcustom org-columns-modify-value-for-display-function nil
3744 "Function that modifies values for display in column view.
3745 For example, it can be used to cut out a certain part from a time stamp.
3746 The function must take 2 arguments:
3748 column-title The title of the column (*not* the property name)
3749 value The value that should be modified.
3751 The function should return the value that should be displayed,
3752 or nil if the normal value should be used."
3753 :group 'org-properties
3754 :type '(choice (const nil) (function)))
3756 (defconst org-global-properties-fixed
3757 '(("VISIBILITY_ALL" . "folded children content all")
3758 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3759 "List of property/value pairs that can be inherited by any entry.
3761 These are fixed values, for the preset properties. The user variable
3762 that can be used to add to this list is `org-global-properties'.
3764 The entries in this list are cons cells where the car is a property
3765 name and cdr is a string with the value. If the value represents
3766 multiple items like an \"_ALL\" property, separate the items by
3767 spaces.")
3769 (defcustom org-global-properties nil
3770 "List of property/value pairs that can be inherited by any entry.
3772 This list will be combined with the constant `org-global-properties-fixed'.
3774 The entries in this list are cons cells where the car is a property
3775 name and cdr is a string with the value.
3777 You can set buffer-local values for the same purpose in the variable
3778 `org-file-properties' this by adding lines like
3780 #+PROPERTY: NAME VALUE"
3781 :group 'org-properties
3782 :type '(repeat
3783 (cons (string :tag "Property")
3784 (string :tag "Value"))))
3786 (defvar-local org-file-properties nil
3787 "List of property/value pairs that can be inherited by any entry.
3788 Valid for the current buffer.
3789 This variable is populated from #+PROPERTY lines.")
3791 (defgroup org-agenda nil
3792 "Options concerning agenda views in Org-mode."
3793 :tag "Org Agenda"
3794 :group 'org)
3796 (defvar-local org-category nil
3797 "Variable used by org files to set a category for agenda display.
3798 Such files should use a file variable to set it, for example
3800 # -*- mode: org; org-category: \"ELisp\"
3802 or contain a special line
3804 #+CATEGORY: ELisp
3806 If the file does not specify a category, then file's base name
3807 is used instead.")
3808 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3810 (defcustom org-agenda-files nil
3811 "The files to be used for agenda display.
3812 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3813 \\[org-remove-file]. You can also use customize to edit the list.
3815 If an entry is a directory, all files in that directory that are matched by
3816 `org-agenda-file-regexp' will be part of the file list.
3818 If the value of the variable is not a list but a single file name, then
3819 the list of agenda files is actually stored and maintained in that file, one
3820 agenda file per line. In this file paths can be given relative to
3821 `org-directory'. Tilde expansion and environment variable substitution
3822 are also made."
3823 :group 'org-agenda
3824 :type '(choice
3825 (repeat :tag "List of files and directories" file)
3826 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3828 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3829 "Regular expression to match files for `org-agenda-files'.
3830 If any element in the list in that variable contains a directory instead
3831 of a normal file, all files in that directory that are matched by this
3832 regular expression will be included."
3833 :group 'org-agenda
3834 :type 'regexp)
3836 (defcustom org-agenda-text-search-extra-files nil
3837 "List of extra files to be searched by text search commands.
3838 These files will be searched in addition to the agenda files by the
3839 commands `org-search-view' (`\\[org-agenda] s') \
3840 and `org-occur-in-agenda-files'.
3841 Note that these files will only be searched for text search commands,
3842 not for the other agenda views like todo lists, tag searches or the weekly
3843 agenda. This variable is intended to list notes and possibly archive files
3844 that should also be searched by these two commands.
3845 In fact, if the first element in the list is the symbol `agenda-archives',
3846 then all archive files of all agenda files will be added to the search
3847 scope."
3848 :group 'org-agenda
3849 :type '(set :greedy t
3850 (const :tag "Agenda Archives" agenda-archives)
3851 (repeat :inline t (file))))
3853 (org-defvaralias 'org-agenda-multi-occur-extra-files
3854 'org-agenda-text-search-extra-files)
3856 (defcustom org-agenda-skip-unavailable-files nil
3857 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3858 A nil value means to remove them, after a query, from the list."
3859 :group 'org-agenda
3860 :type 'boolean)
3862 (defcustom org-calendar-to-agenda-key [?c]
3863 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3864 The command `org-calendar-goto-agenda' will be bound to this key. The
3865 default is the character `c' because then `c' can be used to switch back and
3866 forth between agenda and calendar."
3867 :group 'org-agenda
3868 :type 'sexp)
3870 (defcustom org-calendar-insert-diary-entry-key [?i]
3871 "The key to be installed in `calendar-mode-map' for adding diary entries.
3872 This option is irrelevant until `org-agenda-diary-file' has been configured
3873 to point to an Org-mode file. When that is the case, the command
3874 `org-agenda-diary-entry' will be bound to the key given here, by default
3875 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3876 if you want to continue doing this, you need to change this to a different
3877 key."
3878 :group 'org-agenda
3879 :type 'sexp)
3881 (defcustom org-agenda-diary-file 'diary-file
3882 "File to which to add new entries with the `i' key in agenda and calendar.
3883 When this is the symbol `diary-file', the functionality in the Emacs
3884 calendar will be used to add entries to the `diary-file'. But when this
3885 points to a file, `org-agenda-diary-entry' will be used instead."
3886 :group 'org-agenda
3887 :type '(choice
3888 (const :tag "The standard Emacs diary file" diary-file)
3889 (file :tag "Special Org file diary entries")))
3891 (eval-after-load "calendar"
3892 '(progn
3893 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3894 'org-calendar-goto-agenda)
3895 (add-hook 'calendar-mode-hook
3896 (lambda ()
3897 (unless (eq org-agenda-diary-file 'diary-file)
3898 (define-key calendar-mode-map
3899 org-calendar-insert-diary-entry-key
3900 'org-agenda-diary-entry))))))
3902 (defgroup org-latex nil
3903 "Options for embedding LaTeX code into Org-mode."
3904 :tag "Org LaTeX"
3905 :group 'org)
3907 (defcustom org-format-latex-options
3908 '(:foreground default :background default :scale 1.0
3909 :html-foreground "Black" :html-background "Transparent"
3910 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3911 "Options for creating images from LaTeX fragments.
3912 This is a property list with the following properties:
3913 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3914 `default' means use the foreground of the default face.
3915 `auto' means use the foreground from the text face.
3916 :background the background color, or \"Transparent\".
3917 `default' means use the background of the default face.
3918 `auto' means use the background from the text face.
3919 :scale a scaling factor for the size of the images, to get more pixels
3920 :html-foreground, :html-background, :html-scale
3921 the same numbers for HTML export.
3922 :matchers a list indicating which matchers should be used to
3923 find LaTeX fragments. Valid members of this list are:
3924 \"begin\" find environments
3925 \"$1\" find single characters surrounded by $.$
3926 \"$\" find math expressions surrounded by $...$
3927 \"$$\" find math expressions surrounded by $$....$$
3928 \"\\(\" find math expressions surrounded by \\(...\\)
3929 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3930 :group 'org-latex
3931 :type 'plist)
3933 (defcustom org-format-latex-signal-error t
3934 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3935 When nil, just push out a message."
3936 :group 'org-latex
3937 :version "24.1"
3938 :type 'boolean)
3940 (defcustom org-latex-to-mathml-jar-file nil
3941 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3942 Use this to specify additional executable file say a jar file.
3944 When using MathToWeb as the converter, specify the full-path to
3945 your mathtoweb.jar file."
3946 :group 'org-latex
3947 :version "24.1"
3948 :type '(choice
3949 (const :tag "None" nil)
3950 (file :tag "JAR file" :must-match t)))
3952 (defcustom org-latex-to-mathml-convert-command nil
3953 "Command to convert LaTeX fragments to MathML.
3954 Replace format-specifiers in the command as noted below and use
3955 `shell-command' to convert LaTeX to MathML.
3956 %j: Executable file in fully expanded form as specified by
3957 `org-latex-to-mathml-jar-file'.
3958 %I: Input LaTeX file in fully expanded form.
3959 %i: The latex fragment to be converted.
3960 %o: Output MathML file.
3962 This command is used by `org-create-math-formula'.
3964 When using MathToWeb as the converter, set this option to
3965 \"java -jar %j -unicode -force -df %o %I\".
3967 When using LaTeXML set this option to
3968 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3969 :group 'org-latex
3970 :version "24.1"
3971 :type '(choice
3972 (const :tag "None" nil)
3973 (string :tag "\nShell command")))
3975 (defcustom org-latex-create-formula-image-program 'dvipng
3976 "Program to convert LaTeX fragments with.
3978 dvipng Process the LaTeX fragments to dvi file, then convert
3979 dvi files to png files using dvipng.
3980 This will also include processing of non-math environments.
3981 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3982 to convert pdf files to png files"
3983 :group 'org-latex
3984 :version "24.1"
3985 :type '(choice
3986 (const :tag "dvipng" dvipng)
3987 (const :tag "imagemagick" imagemagick)))
3989 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3990 "Path to store latex preview images.
3991 A relative path here creates many directories relative to the
3992 processed org files paths. An absolute path puts all preview
3993 images at the same place."
3994 :group 'org-latex
3995 :version "24.3"
3996 :type 'string)
3998 (defun org-format-latex-mathml-available-p ()
3999 "Return t if `org-latex-to-mathml-convert-command' is usable."
4000 (save-match-data
4001 (when (and (boundp 'org-latex-to-mathml-convert-command)
4002 org-latex-to-mathml-convert-command)
4003 (let ((executable (car (split-string
4004 org-latex-to-mathml-convert-command))))
4005 (when (executable-find executable)
4006 (if (string-match
4007 "%j" org-latex-to-mathml-convert-command)
4008 (file-readable-p org-latex-to-mathml-jar-file)
4009 t))))))
4011 (defcustom org-format-latex-header "\\documentclass{article}
4012 \\usepackage[usenames]{color}
4013 \[PACKAGES]
4014 \[DEFAULT-PACKAGES]
4015 \\pagestyle{empty} % do not remove
4016 % The settings below are copied from fullpage.sty
4017 \\setlength{\\textwidth}{\\paperwidth}
4018 \\addtolength{\\textwidth}{-3cm}
4019 \\setlength{\\oddsidemargin}{1.5cm}
4020 \\addtolength{\\oddsidemargin}{-2.54cm}
4021 \\setlength{\\evensidemargin}{\\oddsidemargin}
4022 \\setlength{\\textheight}{\\paperheight}
4023 \\addtolength{\\textheight}{-\\headheight}
4024 \\addtolength{\\textheight}{-\\headsep}
4025 \\addtolength{\\textheight}{-\\footskip}
4026 \\addtolength{\\textheight}{-3cm}
4027 \\setlength{\\topmargin}{1.5cm}
4028 \\addtolength{\\topmargin}{-2.54cm}"
4029 "The document header used for processing LaTeX fragments.
4030 It is imperative that this header make sure that no page number
4031 appears on the page. The package defined in the variables
4032 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4033 will either replace the placeholder \"[PACKAGES]\" in this
4034 header, or they will be appended."
4035 :group 'org-latex
4036 :type 'string)
4038 (defun org-set-packages-alist (var val)
4039 "Set the packages alist and make sure it has 3 elements per entry."
4040 (set var (mapcar (lambda (x)
4041 (if (and (consp x) (= (length x) 2))
4042 (list (car x) (nth 1 x) t)
4044 val)))
4046 (defun org-get-packages-alist (var)
4047 "Get the packages alist and make sure it has 3 elements per entry."
4048 (mapcar (lambda (x)
4049 (if (and (consp x) (= (length x) 2))
4050 (list (car x) (nth 1 x) t)
4052 (default-value var)))
4054 (defcustom org-latex-default-packages-alist
4055 '(("AUTO" "inputenc" t ("pdflatex"))
4056 ("T1" "fontenc" t ("pdflatex"))
4057 ("" "graphicx" t)
4058 ("" "grffile" t)
4059 ("" "longtable" nil)
4060 ("" "wrapfig" nil)
4061 ("" "rotating" nil)
4062 ("normalem" "ulem" t)
4063 ("" "amsmath" t)
4064 ("" "textcomp" t)
4065 ("" "amssymb" t)
4066 ("" "capt-of" nil)
4067 ("" "hyperref" nil))
4068 "Alist of default packages to be inserted in the header.
4070 Change this only if one of the packages here causes an
4071 incompatibility with another package you are using.
4073 The packages in this list are needed by one part or another of
4074 Org mode to function properly:
4076 - inputenc, fontenc: for basic font and character selection
4077 - graphicx: for including images
4078 - grffile: allow periods and spaces in graphics file names
4079 - longtable: For multipage tables
4080 - wrapfig: for figure placement
4081 - rotating: for sideways figures and tables
4082 - ulem: for underline and strike-through
4083 - amsmath: for subscript and superscript and math environments
4084 - textcomp, amssymb: for various symbols used
4085 for interpreting the entities in `org-entities'. You can skip
4086 some of these packages if you don't use any of their symbols.
4087 - capt-of: for captions outside of floats
4088 - hyperref: for cross references
4090 Therefore you should not modify this variable unless you know
4091 what you are doing. The one reason to change it anyway is that
4092 you might be loading some other package that conflicts with one
4093 of the default packages. Each element is either a cell or
4094 a string.
4096 A cell is of the format
4098 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4100 If SNIPPET-FLAG is non-nil, the package also needs to be included
4101 when compiling LaTeX snippets into images for inclusion into
4102 non-LaTeX output. COMPILERS is a list of compilers that should
4103 include the package, see `org-latex-compiler'. If the document
4104 compiler is not in the list, and the list is non-nil, the package
4105 will not be inserted in the final document.
4107 A string will be inserted as-is in the header of the document."
4108 :group 'org-latex
4109 :group 'org-export-latex
4110 :set 'org-set-packages-alist
4111 :get 'org-get-packages-alist
4112 :version "25.1"
4113 :package-version '(Org . "8.3")
4114 :type '(repeat
4115 (choice
4116 (list :tag "options/package pair"
4117 (string :tag "options")
4118 (string :tag "package")
4119 (boolean :tag "Snippet"))
4120 (string :tag "A line of LaTeX"))))
4122 (defcustom org-latex-packages-alist nil
4123 "Alist of packages to be inserted in every LaTeX header.
4125 These will be inserted after `org-latex-default-packages-alist'.
4126 Each element is either a cell or a string.
4128 A cell is of the format:
4130 (\"options\" \"package\" SNIPPET-FLAG)
4132 SNIPPET-FLAG, when non-nil, indicates that this package is also
4133 needed when turning LaTeX snippets into images for inclusion into
4134 non-LaTeX output.
4136 A string will be inserted as-is in the header of the document.
4138 Make sure that you only list packages here which:
4140 - you want in every file;
4141 - do not conflict with the setup in `org-format-latex-header';
4142 - do not conflict with the default packages in
4143 `org-latex-default-packages-alist'."
4144 :group 'org-latex
4145 :group 'org-export-latex
4146 :set 'org-set-packages-alist
4147 :get 'org-get-packages-alist
4148 :type '(repeat
4149 (choice
4150 (list :tag "options/package pair"
4151 (string :tag "options")
4152 (string :tag "package")
4153 (boolean :tag "Snippet"))
4154 (string :tag "A line of LaTeX"))))
4156 (defgroup org-appearance nil
4157 "Settings for Org-mode appearance."
4158 :tag "Org Appearance"
4159 :group 'org)
4161 (defcustom org-level-color-stars-only nil
4162 "Non-nil means fontify only the stars in each headline.
4163 When nil, the entire headline is fontified.
4164 Changing it requires restart of `font-lock-mode' to become effective
4165 also in regions already fontified."
4166 :group 'org-appearance
4167 :type 'boolean)
4169 (defcustom org-hide-leading-stars nil
4170 "Non-nil means hide the first N-1 stars in a headline.
4171 This works by using the face `org-hide' for these stars. This
4172 face is white for a light background, and black for a dark
4173 background. You may have to customize the face `org-hide' to
4174 make this work.
4175 Changing it requires restart of `font-lock-mode' to become effective
4176 also in regions already fontified.
4177 You may also set this on a per-file basis by adding one of the following
4178 lines to the buffer:
4180 #+STARTUP: hidestars
4181 #+STARTUP: showstars"
4182 :group 'org-appearance
4183 :type 'boolean)
4185 (defcustom org-hidden-keywords nil
4186 "List of symbols corresponding to keywords to be hidden the org buffer.
4187 For example, a value \\='(title) for this list will make the document's title
4188 appear in the buffer without the initial #+TITLE: keyword."
4189 :group 'org-appearance
4190 :version "24.1"
4191 :type '(set (const :tag "#+AUTHOR" author)
4192 (const :tag "#+DATE" date)
4193 (const :tag "#+EMAIL" email)
4194 (const :tag "#+TITLE" title)))
4196 (defcustom org-custom-properties nil
4197 "List of properties (as strings) with a special meaning.
4198 The default use of these custom properties is to let the user
4199 hide them with `org-toggle-custom-properties-visibility'."
4200 :group 'org-properties
4201 :group 'org-appearance
4202 :version "24.3"
4203 :type '(repeat (string :tag "Property Name")))
4205 (defcustom org-fontify-done-headline nil
4206 "Non-nil means change the face of a headline if it is marked DONE.
4207 Normally, only the TODO/DONE keyword indicates the state of a headline.
4208 When this is non-nil, the headline after the keyword is set to the
4209 `org-headline-done' as an additional indication."
4210 :group 'org-appearance
4211 :type 'boolean)
4213 (defcustom org-fontify-emphasized-text t
4214 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4215 Changing this variable requires a restart of Emacs to take effect."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-fontify-whole-heading-line nil
4220 "Non-nil means fontify the whole line for headings.
4221 This is useful when setting a background color for the
4222 org-level-* faces."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-highlight-latex-and-related nil
4227 "Non-nil means highlight LaTeX related syntax in the buffer.
4228 When non nil, the value should be a list containing any of the
4229 following symbols:
4230 `latex' Highlight LaTeX snippets and environments.
4231 `script' Highlight subscript and superscript.
4232 `entities' Highlight entities."
4233 :group 'org-appearance
4234 :version "24.4"
4235 :package-version '(Org . "8.0")
4236 :type '(choice
4237 (const :tag "No highlighting" nil)
4238 (set :greedy t :tag "Highlight"
4239 (const :tag "LaTeX snippets and environments" latex)
4240 (const :tag "Subscript and superscript" script)
4241 (const :tag "Entities" entities))))
4243 (defcustom org-hide-emphasis-markers nil
4244 "Non-nil mean font-lock should hide the emphasis marker characters."
4245 :group 'org-appearance
4246 :type 'boolean)
4248 (defcustom org-hide-macro-markers nil
4249 "Non-nil mean font-lock should hide the brackets marking macro calls."
4250 :group 'org-appearance
4251 :type 'boolean)
4253 (defcustom org-pretty-entities nil
4254 "Non-nil means show entities as UTF8 characters.
4255 When nil, the \\name form remains in the buffer."
4256 :group 'org-appearance
4257 :version "24.1"
4258 :type 'boolean)
4260 (defcustom org-pretty-entities-include-sub-superscripts t
4261 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4262 :group 'org-appearance
4263 :version "24.1"
4264 :type 'boolean)
4266 (defvar org-emph-re nil
4267 "Regular expression for matching emphasis.
4268 After a match, the match groups contain these elements:
4269 0 The match of the full regular expression, including the characters
4270 before and after the proper match
4271 1 The character before the proper match, or empty at beginning of line
4272 2 The proper match, including the leading and trailing markers
4273 3 The leading marker like * or /, indicating the type of highlighting
4274 4 The text between the emphasis markers, not including the markers
4275 5 The character after the match, empty at the end of a line")
4276 (defvar org-verbatim-re nil
4277 "Regular expression for matching verbatim text.")
4278 (defvar org-emphasis-regexp-components) ; defined just below
4279 (defvar org-emphasis-alist) ; defined just below
4280 (defun org-set-emph-re (var val)
4281 "Set variable and compute the emphasis regular expression."
4282 (set var val)
4283 (when (and (boundp 'org-emphasis-alist)
4284 (boundp 'org-emphasis-regexp-components)
4285 org-emphasis-alist org-emphasis-regexp-components)
4286 (let* ((e org-emphasis-regexp-components)
4287 (pre (car e))
4288 (post (nth 1 e))
4289 (border (nth 2 e))
4290 (body (nth 3 e))
4291 (nl (nth 4 e))
4292 (body1 (concat body "*?"))
4293 (markers (mapconcat 'car org-emphasis-alist ""))
4294 (vmarkers (mapconcat
4295 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4296 org-emphasis-alist "")))
4297 ;; make sure special characters appear at the right position in the class
4298 (if (string-match "\\^" markers)
4299 (setq markers (concat (replace-match "" t t markers) "^")))
4300 (if (string-match "-" markers)
4301 (setq markers (concat (replace-match "" t t markers) "-")))
4302 (if (string-match "\\^" vmarkers)
4303 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4304 (if (string-match "-" vmarkers)
4305 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4306 (if (> nl 0)
4307 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4308 (int-to-string nl) "\\}")))
4309 ;; Make the regexp
4310 (setq org-emph-re
4311 (concat "\\([" pre "]\\|^\\)"
4312 "\\("
4313 "\\([" markers "]\\)"
4314 "\\("
4315 "[^" border "]\\|"
4316 "[^" border "]"
4317 body1
4318 "[^" border "]"
4319 "\\)"
4320 "\\3\\)"
4321 "\\([" post "]\\|$\\)"))
4322 (setq org-verbatim-re
4323 (concat "\\([" pre "]\\|^\\)"
4324 "\\("
4325 "\\([" vmarkers "]\\)"
4326 "\\("
4327 "[^" border "]\\|"
4328 "[^" border "]"
4329 body1
4330 "[^" border "]"
4331 "\\)"
4332 "\\3\\)"
4333 "\\([" post "]\\|$\\)")))))
4335 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4336 ;; set this option proved cumbersome. See this message/thread:
4337 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4338 (defvar org-emphasis-regexp-components
4339 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4340 "Components used to build the regular expression for emphasis.
4341 This is a list with five entries. Terminology: In an emphasis string
4342 like \" *strong word* \", we call the initial space PREMATCH, the final
4343 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4344 and \"trong wor\" is the body. The different components in this variable
4345 specify what is allowed/forbidden in each part:
4347 pre Chars allowed as prematch. Beginning of line will be allowed too.
4348 post Chars allowed as postmatch. End of line will be allowed too.
4349 border The chars *forbidden* as border characters.
4350 body-regexp A regexp like \".\" to match a body character. Don't use
4351 non-shy groups here, and don't allow newline here.
4352 newline The maximum number of newlines allowed in an emphasis exp.
4354 You need to reload Org or to restart Emacs after customizing this.")
4356 (defcustom org-emphasis-alist
4357 `(("*" bold)
4358 ("/" italic)
4359 ("_" underline)
4360 ("=" org-verbatim verbatim)
4361 ("~" org-code verbatim)
4362 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4363 "Alist of characters and faces to emphasize text.
4364 Text starting and ending with a special character will be emphasized,
4365 for example *bold*, _underlined_ and /italic/. This variable sets the
4366 marker characters and the face to be used by font-lock for highlighting
4367 in Org-mode Emacs buffers.
4369 You need to reload Org or to restart Emacs after customizing this."
4370 :group 'org-appearance
4371 :set 'org-set-emph-re
4372 :version "24.4"
4373 :package-version '(Org . "8.0")
4374 :type '(repeat
4375 (list
4376 (string :tag "Marker character")
4377 (choice
4378 (face :tag "Font-lock-face")
4379 (plist :tag "Face property list"))
4380 (option (const verbatim)))))
4382 (defvar org-protecting-blocks '("src" "example" "export")
4383 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4384 This is needed for font-lock setup.")
4386 ;;; Miscellaneous options
4388 (defgroup org-completion nil
4389 "Completion in Org-mode."
4390 :tag "Org Completion"
4391 :group 'org)
4393 (defcustom org-completion-use-ido nil
4394 "Non-nil means use ido completion wherever possible.
4395 Note that `ido-mode' must be active for this variable to be relevant.
4396 If you decide to turn this variable on, you might well want to turn off
4397 `org-outline-path-complete-in-steps'.
4398 See also `org-completion-use-iswitchb'."
4399 :group 'org-completion
4400 :type 'boolean)
4402 (defcustom org-completion-use-iswitchb nil
4403 "Non-nil means use iswitchb completion wherever possible.
4404 Note that `iswitchb-mode' must be active for this variable to be relevant.
4405 If you decide to turn this variable on, you might well want to turn off
4406 `org-outline-path-complete-in-steps'.
4407 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4408 :group 'org-completion
4409 :type 'boolean)
4411 (defcustom org-completion-fallback-command 'hippie-expand
4412 "The expansion command called by \\[pcomplete] in normal context.
4413 Normal means, no org-mode-specific context."
4414 :group 'org-completion
4415 :type 'function)
4417 ;;; Functions and variables from their packages
4418 ;; Declared here to avoid compiler warnings
4420 ;; XEmacs only
4421 (defvar outline-mode-menu-heading)
4422 (defvar outline-mode-menu-show)
4423 (defvar outline-mode-menu-hide)
4424 (defvar zmacs-regions) ; XEmacs regions
4426 ;; Emacs only
4427 (defvar mark-active)
4429 ;; Various packages
4430 (declare-function calc-eval "calc" (str &optional separator &rest args))
4431 (declare-function calendar-forward-day "cal-move" (arg))
4432 (declare-function calendar-goto-date "cal-move" (date))
4433 (declare-function calendar-goto-today "cal-move" ())
4434 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4435 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4436 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4437 (declare-function cdlatex-tab "ext:cdlatex" ())
4438 (declare-function dired-get-filename
4439 "dired"
4440 (&optional localp no-error-if-not-filep))
4441 (declare-function iswitchb-read-buffer
4442 "iswitchb"
4443 (prompt &optional default require-match start matches-set))
4444 (declare-function org-agenda-change-all-lines
4445 "org-agenda"
4446 (newhead hdmarker &optional fixface just-this))
4447 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4448 "org-agenda"
4449 (&optional end))
4450 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4451 (declare-function org-agenda-format-item
4452 "org-agenda"
4453 (extra txt &optional level category tags dotime noprefix
4454 remove-re habitp))
4455 (declare-function org-agenda-maybe-redo "org-agenda" ())
4456 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4457 (declare-function org-agenda-save-markers-for-cut-and-paste
4458 "org-agenda"
4459 (beg end))
4460 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4461 (declare-function org-agenda-skip "org-agenda" ())
4462 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4463 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4464 (declare-function org-indent-mode "org-indent" (&optional arg))
4465 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4466 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4467 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4468 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4469 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4470 (declare-function parse-time-string "parse-time" (string))
4471 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4472 (declare-function table--at-cell-p
4473 "table"
4474 (position &optional object at-column))
4476 (defvar align-mode-rules-list)
4477 (defvar calc-embedded-close-formula)
4478 (defvar calc-embedded-open-formula)
4479 (defvar calc-embedded-open-mode)
4480 (defvar font-lock-unfontify-region-function)
4481 (defvar iswitchb-temp-buflist)
4482 (defvar org-agenda-tags-todo-honor-ignore-options)
4483 (defvar remember-data-file)
4484 (defvar texmathp-why)
4486 ;;;###autoload
4487 (defun turn-on-orgtbl ()
4488 "Unconditionally turn on `orgtbl-mode'."
4489 (require 'org-table)
4490 (orgtbl-mode 1))
4492 (defun org-at-table-p (&optional table-type)
4493 "Non-nil if the cursor is inside an Org table.
4494 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4495 If `org-enable-table-editor' is nil, return nil unconditionally."
4496 (and
4497 org-enable-table-editor
4498 (save-excursion
4499 (beginning-of-line)
4500 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4501 (or (not (derived-mode-p 'org-mode))
4502 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4503 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4506 (defun org-at-table.el-p ()
4507 "Non-nil when point is at a table.el table."
4508 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4509 (let ((element (org-element-at-point)))
4510 (and (eq (org-element-type element) 'table)
4511 (eq (org-element-property :type element) 'table.el)))))
4513 (defun org-table-recognize-table.el ()
4514 "If there is a table.el table nearby, recognize it and move into it."
4515 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4516 (beginning-of-line)
4517 (unless (or (looking-at org-table-dataline-regexp)
4518 (not (looking-at org-table1-hline-regexp)))
4519 (forward-line)
4520 (when (looking-at org-table-any-border-regexp)
4521 (forward-line -2)))
4522 (if (re-search-forward "|" (org-table-end t) t)
4523 (progn
4524 (require 'table)
4525 (if (table--at-cell-p (point)) t
4526 (message "recognizing table.el table...")
4527 (table-recognize-table)
4528 (message "recognizing table.el table...done")))
4529 (error "This should not happen"))))
4530 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4531 (make-obsolete 'org-table-recognize-table.el
4532 "please notify the org mailing list if you use this function."
4533 "Org 9.0")
4535 (defun org-at-table-hline-p ()
4536 "Non-nil when point is inside a hline in a table.
4537 Assume point is already in a table. If `org-enable-table-editor'
4538 is nil, return nil unconditionally."
4539 (and org-enable-table-editor
4540 (save-excursion
4541 (beginning-of-line)
4542 (looking-at org-table-hline-regexp))))
4544 (defun org-table-map-tables (function &optional quietly)
4545 "Apply FUNCTION to the start of all tables in the buffer."
4546 (save-excursion
4547 (save-restriction
4548 (widen)
4549 (goto-char (point-min))
4550 (while (re-search-forward org-table-any-line-regexp nil t)
4551 (unless quietly
4552 (message "Mapping tables: %d%%"
4553 (floor (* 100.0 (point)) (buffer-size))))
4554 (beginning-of-line 1)
4555 (when (and (looking-at org-table-line-regexp)
4556 ;; Exclude tables in src/example/verbatim/clocktable blocks
4557 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4558 (save-excursion (funcall function))
4559 (or (looking-at org-table-line-regexp)
4560 (forward-char 1)))
4561 (re-search-forward org-table-any-border-regexp nil 1))))
4562 (unless quietly (message "Mapping tables: done")))
4564 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4565 (declare-function org-clock-update-mode-line "org-clock" ())
4566 (declare-function org-resolve-clocks "org-clock"
4567 (&optional also-non-dangling-p prompt last-valid))
4569 (defun org-at-TBLFM-p (&optional pos)
4570 "Non-nil when point (or POS) is in #+TBLFM line."
4571 (save-excursion
4572 (goto-char (or pos (point)))
4573 (beginning-of-line)
4574 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4575 (eq (org-element-type (org-element-at-point)) 'table))))
4577 (defvar org-clock-start-time)
4578 (defvar org-clock-marker (make-marker)
4579 "Marker recording the last clock-in.")
4580 (defvar org-clock-hd-marker (make-marker)
4581 "Marker recording the last clock-in, but the headline position.")
4582 (defvar org-clock-heading ""
4583 "The heading of the current clock entry.")
4584 (defun org-clock-is-active ()
4585 "Return the buffer where the clock is currently running.
4586 Return nil if no clock is running."
4587 (marker-buffer org-clock-marker))
4589 (defun org-check-running-clock ()
4590 "Check if the current buffer contains the running clock.
4591 If yes, offer to stop it and to save the buffer with the changes."
4592 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4593 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4594 (buffer-name))))
4595 (org-clock-out)
4596 (when (y-or-n-p "Save changed buffer?")
4597 (save-buffer))))
4599 (defun org-clocktable-try-shift (dir n)
4600 "Check if this line starts a clock table, if yes, shift the time block."
4601 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4602 (org-clocktable-shift dir n)))
4604 ;;;###autoload
4605 (defun org-clock-persistence-insinuate ()
4606 "Set up hooks for clock persistence."
4607 (require 'org-clock)
4608 (add-hook 'org-mode-hook 'org-clock-load)
4609 (add-hook 'kill-emacs-hook 'org-clock-save))
4611 (defgroup org-archive nil
4612 "Options concerning archiving in Org-mode."
4613 :tag "Org Archive"
4614 :group 'org-structure)
4616 (defcustom org-archive-location "%s_archive::"
4617 "The location where subtrees should be archived.
4619 The value of this variable is a string, consisting of two parts,
4620 separated by a double-colon. The first part is a filename and
4621 the second part is a headline.
4623 When the filename is omitted, archiving happens in the same file.
4624 %s in the filename will be replaced by the current file
4625 name (without the directory part). Archiving to a different file
4626 is useful to keep archived entries from contributing to the
4627 Org-mode Agenda.
4629 The archived entries will be filed as subtrees of the specified
4630 headline. When the headline is omitted, the subtrees are simply
4631 filed away at the end of the file, as top-level entries. Also in
4632 the heading you can use %s to represent the file name, this can be
4633 useful when using the same archive for a number of different files.
4635 Here are a few examples:
4636 \"%s_archive::\"
4637 If the current file is Projects.org, archive in file
4638 Projects.org_archive, as top-level trees. This is the default.
4640 \"::* Archived Tasks\"
4641 Archive in the current file, under the top-level headline
4642 \"* Archived Tasks\".
4644 \"~/org/archive.org::\"
4645 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4647 \"~/org/archive.org::* From %s\"
4648 Archive in file ~/org/archive.org (absolute path), under headlines
4649 \"From FILENAME\" where file name is the current file name.
4651 \"~/org/datetree.org::datetree/* Finished Tasks\"
4652 The \"datetree/\" string is special, signifying to archive
4653 items to the datetree. Items are placed in either the CLOSED
4654 date of the item, or the current date if there is no CLOSED date.
4655 The heading will be a subentry to the current date. There doesn't
4656 need to be a heading, but there always needs to be a slash after
4657 datetree. For example, to store archived items directly in the
4658 datetree, use \"~/org/datetree.org::datetree/\".
4660 \"basement::** Finished Tasks\"
4661 Archive in file ./basement (relative path), as level 3 trees
4662 below the level 2 heading \"** Finished Tasks\".
4664 You may set this option on a per-file basis by adding to the buffer a
4665 line like
4667 #+ARCHIVE: basement::** Finished Tasks
4669 You may also define it locally for a subtree by setting an ARCHIVE property
4670 in the entry. If such a property is found in an entry, or anywhere up
4671 the hierarchy, it will be used."
4672 :group 'org-archive
4673 :type 'string)
4675 (defcustom org-agenda-skip-archived-trees t
4676 "Non-nil means the agenda will skip any items located in archived trees.
4677 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4678 variable is no longer recommended, you should leave it at the value t.
4679 Instead, use the key `v' to cycle the archives-mode in the agenda."
4680 :group 'org-archive
4681 :group 'org-agenda-skip
4682 :type 'boolean)
4684 (defcustom org-columns-skip-archived-trees t
4685 "Non-nil means ignore archived trees when creating column view."
4686 :group 'org-archive
4687 :group 'org-properties
4688 :type 'boolean)
4690 (defcustom org-cycle-open-archived-trees nil
4691 "Non-nil means `org-cycle' will open archived trees.
4692 An archived tree is a tree marked with the tag ARCHIVE.
4693 When nil, archived trees will stay folded. You can still open them with
4694 normal outline commands like `show-all', but not with the cycling commands."
4695 :group 'org-archive
4696 :group 'org-cycle
4697 :type 'boolean)
4699 (defcustom org-sparse-tree-open-archived-trees nil
4700 "Non-nil means sparse tree construction shows matches in archived trees.
4701 When nil, matches in these trees are highlighted, but the trees are kept in
4702 collapsed state."
4703 :group 'org-archive
4704 :group 'org-sparse-trees
4705 :type 'boolean)
4707 (defcustom org-sparse-tree-default-date-type nil
4708 "The default date type when building a sparse tree.
4709 When this is nil, a date is a scheduled or a deadline timestamp.
4710 Otherwise, these types are allowed:
4712 all: all timestamps
4713 active: only active timestamps (<...>)
4714 inactive: only inactive timestamps ([...])
4715 scheduled: only scheduled timestamps
4716 deadline: only deadline timestamps"
4717 :type '(choice (const :tag "Scheduled or deadline" nil)
4718 (const :tag "All timestamps" all)
4719 (const :tag "Only active timestamps" active)
4720 (const :tag "Only inactive timestamps" inactive)
4721 (const :tag "Only scheduled timestamps" scheduled)
4722 (const :tag "Only deadline timestamps" deadline)
4723 (const :tag "Only closed timestamps" closed))
4724 :version "25.1"
4725 :package-version '(Org . "8.3")
4726 :group 'org-sparse-trees)
4728 (defun org-cycle-hide-archived-subtrees (state)
4729 "Re-hide all archived subtrees after a visibility state change."
4730 (when (and (not org-cycle-open-archived-trees)
4731 (not (memq state '(overview folded))))
4732 (save-excursion
4733 (let* ((globalp (memq state '(contents all)))
4734 (beg (if globalp (point-min) (point)))
4735 (end (if globalp (point-max) (org-end-of-subtree t))))
4736 (org-hide-archived-subtrees beg end)
4737 (goto-char beg)
4738 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4739 (message "%s" (substitute-command-keys
4740 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4742 (defun org-force-cycle-archived ()
4743 "Cycle subtree even if it is archived."
4744 (interactive)
4745 (setq this-command 'org-cycle)
4746 (let ((org-cycle-open-archived-trees t))
4747 (call-interactively 'org-cycle)))
4749 (defun org-hide-archived-subtrees (beg end)
4750 "Re-hide all archived subtrees after a visibility state change."
4751 (org-with-wide-buffer
4752 (let ((case-fold-search nil)
4753 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4754 (goto-char beg)
4755 ;; Include headline point is currently on.
4756 (beginning-of-line)
4757 (while (and (< (point) end) (re-search-forward re end t))
4758 (when (member org-archive-tag (org-get-tags))
4759 (org-flag-subtree t)
4760 (org-end-of-subtree t))))))
4762 (declare-function outline-end-of-heading "outline" ())
4763 (declare-function outline-flag-region "outline" (from to flag))
4764 (defun org-flag-subtree (flag)
4765 (save-excursion
4766 (org-back-to-heading t)
4767 (outline-end-of-heading)
4768 (outline-flag-region (point)
4769 (progn (org-end-of-subtree t) (point))
4770 flag)))
4772 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4774 ;; Declare Column View Code
4776 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4777 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4778 (declare-function org-columns-compute "org-colview" (property))
4780 ;; Declare ID code
4782 (declare-function org-id-store-link "org-id")
4783 (declare-function org-id-locations-load "org-id")
4784 (declare-function org-id-locations-save "org-id")
4785 (defvar org-id-track-globally)
4787 ;;; Variables for pre-computed regular expressions, all buffer local
4789 (defvar-local org-todo-regexp nil
4790 "Matches any of the TODO state keywords.")
4791 (defvar-local org-not-done-regexp nil
4792 "Matches any of the TODO state keywords except the last one.")
4793 (defvar-local org-not-done-heading-regexp nil
4794 "Matches a TODO headline that is not done.")
4795 (defvar-local org-todo-line-regexp nil
4796 "Matches a headline and puts TODO state into group 2 if present.")
4797 (defvar-local org-complex-heading-regexp nil
4798 "Matches a headline and puts everything into groups:
4799 group 1: the stars
4800 group 2: The todo keyword, maybe
4801 group 3: Priority cookie
4802 group 4: True headline
4803 group 5: Tags")
4804 (defvar-local org-complex-heading-regexp-format nil
4805 "Printf format to make regexp to match an exact headline.
4806 This regexp will match the headline of any node which has the
4807 exact headline text that is put into the format, but may have any
4808 TODO state, priority and tags.")
4809 (defvar-local org-todo-line-tags-regexp nil
4810 "Matches a headline and puts TODO state into group 2 if present.
4811 Also put tags into group 4 if tags are present.")
4813 (defconst org-plain-time-of-day-regexp
4814 (concat
4815 "\\(\\<[012]?[0-9]"
4816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4817 "\\(--?"
4818 "\\(\\<[012]?[0-9]"
4819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4820 "\\)?")
4821 "Regular expression to match a plain time or time range.
4822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4823 groups carry important information:
4824 0 the full match
4825 1 the first time, range or not
4826 8 the second time, if it is a range.")
4828 (defconst org-plain-time-extension-regexp
4829 (concat
4830 "\\(\\<[012]?[0-9]"
4831 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4832 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4833 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4834 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4835 groups carry important information:
4836 0 the full match
4837 7 hours of duration
4838 9 minutes of duration")
4840 (defconst org-stamp-time-of-day-regexp
4841 (concat
4842 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4843 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4844 "\\(--?"
4845 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4846 "Regular expression to match a timestamp time or time range.
4847 After a match, the following groups carry important information:
4848 0 the full match
4849 1 date plus weekday, for back referencing to make sure both times are on the same day
4850 2 the first time, range or not
4851 4 the second time, if it is a range.")
4853 (defconst org-startup-options
4854 '(("fold" org-startup-folded t)
4855 ("overview" org-startup-folded t)
4856 ("nofold" org-startup-folded nil)
4857 ("showall" org-startup-folded nil)
4858 ("showeverything" org-startup-folded showeverything)
4859 ("content" org-startup-folded content)
4860 ("indent" org-startup-indented t)
4861 ("noindent" org-startup-indented nil)
4862 ("hidestars" org-hide-leading-stars t)
4863 ("showstars" org-hide-leading-stars nil)
4864 ("odd" org-odd-levels-only t)
4865 ("oddeven" org-odd-levels-only nil)
4866 ("align" org-startup-align-all-tables t)
4867 ("noalign" org-startup-align-all-tables nil)
4868 ("inlineimages" org-startup-with-inline-images t)
4869 ("noinlineimages" org-startup-with-inline-images nil)
4870 ("latexpreview" org-startup-with-latex-preview t)
4871 ("nolatexpreview" org-startup-with-latex-preview nil)
4872 ("customtime" org-display-custom-times t)
4873 ("logdone" org-log-done time)
4874 ("lognotedone" org-log-done note)
4875 ("nologdone" org-log-done nil)
4876 ("lognoteclock-out" org-log-note-clock-out t)
4877 ("nolognoteclock-out" org-log-note-clock-out nil)
4878 ("logrepeat" org-log-repeat state)
4879 ("lognoterepeat" org-log-repeat note)
4880 ("logdrawer" org-log-into-drawer t)
4881 ("nologdrawer" org-log-into-drawer nil)
4882 ("logstatesreversed" org-log-states-order-reversed t)
4883 ("nologstatesreversed" org-log-states-order-reversed nil)
4884 ("nologrepeat" org-log-repeat nil)
4885 ("logreschedule" org-log-reschedule time)
4886 ("lognotereschedule" org-log-reschedule note)
4887 ("nologreschedule" org-log-reschedule nil)
4888 ("logredeadline" org-log-redeadline time)
4889 ("lognoteredeadline" org-log-redeadline note)
4890 ("nologredeadline" org-log-redeadline nil)
4891 ("logrefile" org-log-refile time)
4892 ("lognoterefile" org-log-refile note)
4893 ("nologrefile" org-log-refile nil)
4894 ("fninline" org-footnote-define-inline t)
4895 ("nofninline" org-footnote-define-inline nil)
4896 ("fnlocal" org-footnote-section nil)
4897 ("fnauto" org-footnote-auto-label t)
4898 ("fnprompt" org-footnote-auto-label nil)
4899 ("fnconfirm" org-footnote-auto-label confirm)
4900 ("fnplain" org-footnote-auto-label plain)
4901 ("fnadjust" org-footnote-auto-adjust t)
4902 ("nofnadjust" org-footnote-auto-adjust nil)
4903 ("constcgs" constants-unit-system cgs)
4904 ("constSI" constants-unit-system SI)
4905 ("noptag" org-tag-persistent-alist nil)
4906 ("hideblocks" org-hide-block-startup t)
4907 ("nohideblocks" org-hide-block-startup nil)
4908 ("beamer" org-startup-with-beamer-mode t)
4909 ("entitiespretty" org-pretty-entities t)
4910 ("entitiesplain" org-pretty-entities nil))
4911 "Variable associated with STARTUP options for org-mode.
4912 Each element is a list of three items: the startup options (as written
4913 in the #+STARTUP line), the corresponding variable, and the value to set
4914 this variable to if the option is found. An optional forth element PUSH
4915 means to push this value onto the list in the variable.")
4917 (defcustom org-group-tags t
4918 "When non-nil (the default), use group tags.
4919 This can be turned on/off through `org-toggle-tags-groups'."
4920 :group 'org-tags
4921 :group 'org-startup
4922 :type 'boolean)
4924 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4926 (defun org-toggle-tags-groups ()
4927 "Toggle support for group tags.
4928 Support for group tags is controlled by the option
4929 `org-group-tags', which is non-nil by default."
4930 (interactive)
4931 (setq org-group-tags (not org-group-tags))
4932 (cond ((and (derived-mode-p 'org-agenda-mode)
4933 org-group-tags)
4934 (org-agenda-redo))
4935 ((derived-mode-p 'org-mode)
4936 (let ((org-inhibit-startup t)) (org-mode))))
4937 (message "Groups tags support has been turned %s"
4938 (if org-group-tags "on" "off")))
4940 (defun org-set-regexps-and-options (&optional tags-only)
4941 "Precompute regular expressions used in the current buffer.
4942 When optional argument TAGS-ONLY is non-nil, only compute tags
4943 related expressions."
4944 (when (derived-mode-p 'org-mode)
4945 (let ((alist (org--setup-collect-keywords
4946 (org-make-options-regexp
4947 (append '("FILETAGS" "TAGS" "SETUPFILE")
4948 (and (not tags-only)
4949 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4950 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4951 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4952 (org--setup-process-tags
4953 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4954 (unless tags-only
4955 ;; File properties.
4956 (setq-local org-file-properties (cdr (assq 'property alist)))
4957 ;; Archive location.
4958 (let ((archive (cdr (assq 'archive alist))))
4959 (when archive (setq-local org-archive-location archive)))
4960 ;; Category.
4961 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4962 (when cat
4963 (setq-local org-category (intern cat))
4964 (setq-local org-file-properties
4965 (org--update-property-plist
4966 "CATEGORY" cat org-file-properties))))
4967 ;; Columns.
4968 (let ((column (cdr (assq 'columns alist))))
4969 (when column (setq-local org-columns-default-format column)))
4970 ;; Constants.
4971 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4972 ;; Link abbreviations.
4973 (let ((links (cdr (assq 'link alist))))
4974 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4975 ;; Priorities.
4976 (let ((priorities (cdr (assq 'priorities alist))))
4977 (when priorities
4978 (setq-local org-highest-priority (nth 0 priorities))
4979 (setq-local org-lowest-priority (nth 1 priorities))
4980 (setq-local org-default-priority (nth 2 priorities))))
4981 ;; Scripts.
4982 (let ((scripts (assq 'scripts alist)))
4983 (when scripts
4984 (setq-local org-use-sub-superscripts (cdr scripts))))
4985 ;; Startup options.
4986 (let ((startup (cdr (assq 'startup alist))))
4987 (dolist (option startup)
4988 (let ((entry (assoc-string option org-startup-options t)))
4989 (when entry
4990 (let ((var (nth 1 entry))
4991 (val (nth 2 entry)))
4992 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4993 (unless (listp (symbol-value var))
4994 (set (make-local-variable var) nil))
4995 (add-to-list var val)))))))
4996 ;; TODO keywords.
4997 (setq-local org-todo-kwd-alist nil)
4998 (setq-local org-todo-key-alist nil)
4999 (setq-local org-todo-key-trigger nil)
5000 (setq-local org-todo-keywords-1 nil)
5001 (setq-local org-done-keywords nil)
5002 (setq-local org-todo-heads nil)
5003 (setq-local org-todo-sets nil)
5004 (setq-local org-todo-log-states nil)
5005 (let ((todo-sequences
5006 (or (nreverse (cdr (assq 'todo alist)))
5007 (let ((d (default-value 'org-todo-keywords)))
5008 (if (not (stringp (car d))) d
5009 ;; XXX: Backward compatibility code.
5010 (list (cons org-todo-interpretation d)))))))
5011 (dolist (sequence todo-sequences)
5012 (let* ((sequence (or (run-hook-with-args-until-success
5013 'org-todo-setup-filter-hook sequence)
5014 sequence))
5015 (sequence-type (car sequence))
5016 (keywords (cdr sequence))
5017 (sep (member "|" keywords))
5018 names alist)
5019 (dolist (k (remove "|" keywords))
5020 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5022 (error "Invalid TODO keyword %s" k))
5023 (let ((name (match-string 1 k))
5024 (key (match-string 2 k))
5025 (log (org-extract-log-state-settings k)))
5026 (push name names)
5027 (push (cons name (and key (string-to-char key))) alist)
5028 (when log (push log org-todo-log-states))))
5029 (let* ((names (nreverse names))
5030 (done (if sep (org-remove-keyword-keys (cdr sep))
5031 (last names)))
5032 (head (car names))
5033 (tail (list sequence-type head (car done) (org-last done))))
5034 (add-to-list 'org-todo-heads head 'append)
5035 (push names org-todo-sets)
5036 (setq org-done-keywords (append org-done-keywords done nil))
5037 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5038 (setq org-todo-key-alist
5039 (append org-todo-key-alist
5040 (and alist
5041 (append '((:startgroup))
5042 (nreverse alist)
5043 '((:endgroup))))))
5044 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5045 (setq org-todo-sets (nreverse org-todo-sets)
5046 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5047 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5048 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5049 ;; Compute the regular expressions and other local variables.
5050 ;; Using `org-outline-regexp-bol' would complicate them much,
5051 ;; because of the fixed white space at the end of that string.
5052 (unless org-done-keywords
5053 (setq org-done-keywords
5054 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5055 (setq org-not-done-keywords
5056 (org-delete-all org-done-keywords
5057 (copy-sequence org-todo-keywords-1))
5058 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5059 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5060 org-not-done-heading-regexp
5061 (format org-heading-keyword-regexp-format org-not-done-regexp)
5062 org-todo-line-regexp
5063 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5064 org-complex-heading-regexp
5065 (concat "^\\(\\*+\\)"
5066 "\\(?: +" org-todo-regexp "\\)?"
5067 "\\(?: +\\(\\[#.\\]\\)\\)?"
5068 "\\(?: +\\(.*?\\)\\)??"
5069 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5070 "[ \t]*$")
5071 org-complex-heading-regexp-format
5072 (concat "^\\(\\*+\\)"
5073 "\\(?: +" org-todo-regexp "\\)?"
5074 "\\(?: +\\(\\[#.\\]\\)\\)?"
5075 "\\(?: +"
5076 ;; Stats cookies can be stuck to body.
5077 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5078 "\\(%s\\)"
5079 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5080 "\\)"
5081 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5082 "[ \t]*$")
5083 org-todo-line-tags-regexp
5084 (concat "^\\(\\*+\\)"
5085 "\\(?: +" org-todo-regexp "\\)?"
5086 "\\(?: +\\(.*?\\)\\)??"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5088 "[ \t]*$"))
5089 (org-compute-latex-and-related-regexp)))))
5091 (defun org--setup-collect-keywords (regexp &optional files alist)
5092 "Return setup keywords values as an alist.
5094 REGEXP matches a subset of setup keywords. FILES is a list of
5095 file names already visited. It is used to avoid circular setup
5096 files. ALIST, when non-nil, is the alist computed so far.
5098 Return value contains the following keys: `archive', `category',
5099 `columns', `constants', `filetags', `link', `priorities',
5100 `property', `scripts', `startup', `tags' and `todo'."
5101 (org-with-wide-buffer
5102 (goto-char (point-min))
5103 (let ((case-fold-search t))
5104 (while (re-search-forward regexp nil t)
5105 (let ((element (org-element-at-point)))
5106 (when (eq (org-element-type element) 'keyword)
5107 (let ((key (org-element-property :key element))
5108 (value (org-element-property :value element)))
5109 (cond
5110 ((equal key "ARCHIVE")
5111 (when (org-string-nw-p value)
5112 (push (cons 'archive value) alist)))
5113 ((equal key "CATEGORY") (push (cons 'category value) alist))
5114 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5115 ((equal key "CONSTANTS")
5116 (let* ((constants (assq 'constants alist))
5117 (store (cdr constants)))
5118 (dolist (pair (org-split-string value))
5119 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5120 pair)
5121 (let* ((name (match-string 1 pair))
5122 (value (match-string 2 pair))
5123 (old (assoc name store)))
5124 (if old (setcdr old value)
5125 (push (cons name value) store)))))
5126 (if constants (setcdr constants store)
5127 (push (cons 'constants store) alist))))
5128 ((equal key "FILETAGS")
5129 (when (org-string-nw-p value)
5130 (let ((old (assq 'filetags alist))
5131 (new (apply #'nconc
5132 (mapcar (lambda (x) (org-split-string x ":"))
5133 (org-split-string value)))))
5134 (if old (setcdr old (append new (cdr old)))
5135 (push (cons 'filetags new) alist)))))
5136 ((equal key "LINK")
5137 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5138 (let ((links (assq 'link alist))
5139 (pair (cons (org-match-string-no-properties 1 value)
5140 (org-match-string-no-properties 2 value))))
5141 (if links (push pair (cdr links))
5142 (push (list 'link pair) alist)))))
5143 ((equal key "OPTIONS")
5144 (when (and (org-string-nw-p value)
5145 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5146 (push (cons 'scripts (read (match-string 1 value))) alist)))
5147 ((equal key "PRIORITIES")
5148 (push (cons 'priorities
5149 (let ((prio (org-split-string value)))
5150 (if (< (length prio) 3) '(?A ?C ?B)
5151 (mapcar #'string-to-char prio))))
5152 alist))
5153 ((equal key "PROPERTY")
5154 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5155 (let* ((property (assq 'property alist))
5156 (value (org--update-property-plist
5157 (org-match-string-no-properties 1 value)
5158 (org-match-string-no-properties 2 value)
5159 (cdr property))))
5160 (if property (setcdr property value)
5161 (push (cons 'property value) alist)))))
5162 ((equal key "STARTUP")
5163 (let ((startup (assq 'startup alist)))
5164 (if startup
5165 (setcdr startup
5166 (append (cdr startup) (org-split-string value)))
5167 (push (cons 'startup (org-split-string value)) alist))))
5168 ((equal key "TAGS")
5169 (let ((tag-cell (assq 'tags alist)))
5170 (if tag-cell
5171 (setcdr tag-cell
5172 (append (cdr tag-cell)
5173 '("\\n")
5174 (org-split-string value)))
5175 (push (cons 'tags (org-split-string value)) alist))))
5176 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5177 (let ((todo (assq 'todo alist))
5178 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5179 (org-split-string value))))
5180 (if todo (push value (cdr todo))
5181 (push (list 'todo value) alist))))
5182 ((equal key "SETUPFILE")
5183 (unless buffer-read-only ; Do not check in Gnus messages.
5184 (let ((f (and (org-string-nw-p value)
5185 (expand-file-name
5186 (org-remove-double-quotes value)))))
5187 (when (and f (file-readable-p f) (not (member f files)))
5188 (with-temp-buffer
5189 (setq default-directory (file-name-directory f))
5190 (insert-file-contents f)
5191 (setq alist
5192 ;; Fake Org mode to benefit from cache
5193 ;; without recurring needlessly.
5194 (let ((major-mode 'org-mode))
5195 (org--setup-collect-keywords
5196 regexp (cons f files) alist)))))))))))))))
5197 alist)
5199 (defun org--setup-process-tags (tags filetags)
5200 "Precompute variables used for tags.
5201 TAGS is a list of tags and tag group symbols, as strings.
5202 FILETAGS is a list of tags, as strings."
5203 ;; Process the file tags.
5204 (setq-local org-file-tags
5205 (mapcar #'org-add-prop-inherited filetags))
5206 ;; Provide default tags if no local tags are found.
5207 (when (and (not tags) org-tag-alist)
5208 (setq tags
5209 (mapcar (lambda (tag)
5210 (cl-case (car tag)
5211 (:startgroup "{")
5212 (:endgroup "}")
5213 (:startgrouptag "[")
5214 (:endgrouptag "]")
5215 (:grouptags ":")
5216 (:newline "\\n")
5217 (otherwise (concat (car tag)
5218 (and (characterp (cdr tag))
5219 (format "(%c)" (cdr tag)))))))
5220 org-tag-alist)))
5221 ;; Process the tags.
5222 (setq-local org-tag-groups-alist nil)
5223 (setq-local org-tag-alist nil)
5224 (let (group-flag)
5225 (while tags
5226 (let ((e (car tags)))
5227 (setq tags (cdr tags))
5228 (cond
5229 ((equal e "{")
5230 (push '(:startgroup) org-tag-alist)
5231 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5232 ((equal e "}")
5233 (push '(:endgroup) org-tag-alist)
5234 (setq group-flag nil))
5235 ((equal e "[")
5236 (push '(:startgrouptag) org-tag-alist)
5237 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5238 ((equal e "]")
5239 (push '(:endgrouptag) org-tag-alist)
5240 (setq group-flag nil))
5241 ((equal e ":")
5242 (push '(:grouptags) org-tag-alist)
5243 (setq group-flag 'append))
5244 ((equal e "\\n") (push '(:newline) org-tag-alist))
5245 ((string-match
5246 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5247 "\\|{.+?}\\)" ; regular expression
5248 "\\(?:(\\(.\\))\\)?\\'")) e)
5249 (let ((tag (match-string 1 e))
5250 (key (and (match-beginning 2)
5251 (string-to-char (match-string 2 e)))))
5252 (cond ((eq group-flag 'append)
5253 (setcar org-tag-groups-alist
5254 (append (car org-tag-groups-alist) (list tag))))
5255 (group-flag (push (list tag) org-tag-groups-alist)))
5256 ;; Push all tags in groups, no matter if they already exist.
5257 (unless (and (not group-flag) (assoc tag org-tag-alist))
5258 (push (cons tag key) org-tag-alist))))))))
5259 (setq org-tag-alist (nreverse org-tag-alist)))
5261 (defun org-file-contents (file &optional noerror)
5262 "Return the contents of FILE, as a string."
5263 (if (and file (file-readable-p file))
5264 (with-temp-buffer
5265 (insert-file-contents file)
5266 (buffer-string))
5267 (funcall (if noerror 'message 'error)
5268 "Cannot read file \"%s\"%s"
5269 file
5270 (let ((from (buffer-file-name (buffer-base-buffer))))
5271 (if from (concat " (referenced in file \"" from "\")") "")))))
5273 (defun org-extract-log-state-settings (x)
5274 "Extract the log state setting from a TODO keyword string.
5275 This will extract info from a string like \"WAIT(w@/!)\"."
5276 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5277 (let ((kw (match-string 1 x))
5278 (log1 (and (match-end 3) (match-string 3 x)))
5279 (log2 (and (match-end 4) (match-string 4 x))))
5280 (and (or log1 log2)
5281 (list kw
5282 (and log1 (if (equal log1 "!") 'time 'note))
5283 (and log2 (if (equal log2 "!") 'time 'note)))))))
5285 (defun org-remove-keyword-keys (list)
5286 "Remove a pair of parenthesis at the end of each string in LIST."
5287 (mapcar (lambda (x)
5288 (if (string-match "(.*)$" x)
5289 (substring x 0 (match-beginning 0))
5291 list))
5293 (defun org-assign-fast-keys (alist)
5294 "Assign fast keys to a keyword-key alist.
5295 Respect keys that are already there."
5296 (let (new e (alt ?0))
5297 (while (setq e (pop alist))
5298 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5299 (cdr e)) ;; Key already assigned.
5300 (push e new)
5301 (let ((clist (string-to-list (downcase (car e))))
5302 (used (append new alist)))
5303 (when (= (car clist) ?@)
5304 (pop clist))
5305 (while (and clist (rassoc (car clist) used))
5306 (pop clist))
5307 (unless clist
5308 (while (rassoc alt used)
5309 (cl-incf alt)))
5310 (push (cons (car e) (or (car clist) alt)) new))))
5311 (nreverse new)))
5313 ;;; Some variables used in various places
5315 (defvar org-window-configuration nil
5316 "Used in various places to store a window configuration.")
5317 (defvar org-selected-window nil
5318 "Used in various places to store a window configuration.")
5319 (defvar org-finish-function nil
5320 "Function to be called when `C-c C-c' is used.
5321 This is for getting out of special buffers like capture.")
5322 (defvar org-last-state)
5324 ;; Defined somewhere in this file, but used before definition.
5325 (defvar org-entities) ;; defined in org-entities.el
5326 (defvar org-struct-menu)
5327 (defvar org-org-menu)
5328 (defvar org-tbl-menu)
5330 ;;;; Define the Org-mode
5332 ;; We use a before-change function to check if a table might need
5333 ;; an update.
5334 (defvar org-table-may-need-update t
5335 "Indicates that a table might need an update.
5336 This variable is set by `org-before-change-function'.
5337 `org-table-align' sets it back to nil.")
5338 (defun org-before-change-function (_beg _end)
5339 "Every change indicates that a table might need an update."
5340 (setq org-table-may-need-update t))
5341 (defvar org-mode-map)
5342 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5343 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5344 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5345 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5346 (defvar org-table-buffer-is-an nil)
5348 (defvar bidi-paragraph-direction)
5349 (defvar buffer-face-mode-face)
5351 (require 'outline)
5352 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5353 (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"))
5354 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5356 ;; Other stuff we need.
5357 (require 'time-date)
5358 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5359 (require 'easymenu)
5360 (autoload 'easy-menu-add "easymenu")
5361 (require 'overlay)
5363 ;; (require 'org-macs) moved higher up in the file before it is first used
5364 (require 'org-entities)
5365 ;; (require 'org-compat) moved higher up in the file before it is first used
5366 (require 'org-faces)
5367 (require 'org-list)
5368 (require 'org-pcomplete)
5369 (require 'org-src)
5370 (require 'org-footnote)
5371 (require 'org-macro)
5373 ;; babel
5374 (require 'ob)
5376 ;;;###autoload
5377 (define-derived-mode org-mode outline-mode "Org"
5378 "Outline-based notes management and organizer, alias
5379 \"Carsten's outline-mode for keeping track of everything.\"
5381 Org-mode develops organizational tasks around a NOTES file which
5382 contains information about projects as plain text. Org-mode is
5383 implemented on top of outline-mode, which is ideal to keep the content
5384 of large files well structured. It supports ToDo items, deadlines and
5385 time stamps, which magically appear in the diary listing of the Emacs
5386 calendar. Tables are easily created with a built-in table editor.
5387 Plain text URL-like links connect to websites, emails (VM), Usenet
5388 messages (Gnus), BBDB entries, and any files related to the project.
5389 For printing and sharing of notes, an Org-mode file (or a part of it)
5390 can be exported as a structured ASCII or HTML file.
5392 The following commands are available:
5394 \\{org-mode-map}"
5396 ;; Get rid of Outline menus, they are not needed
5397 ;; Need to do this here because define-derived-mode sets up
5398 ;; the keymap so late. Still, it is a waste to call this each time
5399 ;; we switch another buffer into org-mode.
5400 (if (featurep 'xemacs)
5401 (when (boundp 'outline-mode-menu-heading)
5402 ;; Assume this is Greg's port, it uses easymenu
5403 (easy-menu-remove outline-mode-menu-heading)
5404 (easy-menu-remove outline-mode-menu-show)
5405 (easy-menu-remove outline-mode-menu-hide))
5406 (define-key org-mode-map [menu-bar headings] 'undefined)
5407 (define-key org-mode-map [menu-bar hide] 'undefined)
5408 (define-key org-mode-map [menu-bar show] 'undefined))
5410 (org-load-modules-maybe)
5411 (when (featurep 'xemacs)
5412 (easy-menu-add org-org-menu)
5413 (easy-menu-add org-tbl-menu))
5414 (org-install-agenda-files-menu)
5415 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5416 (add-to-invisibility-spec '(org-cwidth))
5417 (add-to-invisibility-spec '(org-hide-block . t))
5418 (when (featurep 'xemacs)
5419 (setq-local line-move-ignore-invisible t))
5420 (setq-local outline-regexp org-outline-regexp)
5421 (setq-local outline-level 'org-outline-level)
5422 (setq bidi-paragraph-direction 'left-to-right)
5423 (when (and org-ellipsis
5424 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5425 (fboundp 'make-glyph-code))
5426 (unless org-display-table
5427 (setq org-display-table (make-display-table)))
5428 (set-display-table-slot
5429 org-display-table 4
5430 (vconcat (mapcar
5431 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5432 org-ellipsis)))
5433 (if (stringp org-ellipsis) org-ellipsis "..."))))
5434 (setq buffer-display-table org-display-table))
5435 (org-set-regexps-and-options)
5436 (org-set-font-lock-defaults)
5437 (when (and org-tag-faces (not org-tags-special-faces-re))
5438 ;; tag faces set outside customize.... force initialization.
5439 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5440 ;; Calc embedded
5441 (setq-local calc-embedded-open-mode "# ")
5442 ;; Modify a few syntax entries
5443 (modify-syntax-entry ?@ "w")
5444 (modify-syntax-entry ?\" "\"")
5445 (modify-syntax-entry ?\\ "_")
5446 (modify-syntax-entry ?~ "_")
5447 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5448 ;; Activate before-change-function
5449 (setq-local org-table-may-need-update t)
5450 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5451 ;; Check for running clock before killing a buffer
5452 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5453 ;; Initialize macros templates.
5454 (org-macro-initialize-templates)
5455 ;; Initialize radio targets.
5456 (org-update-radio-target-regexp)
5457 ;; Indentation.
5458 (setq-local indent-line-function 'org-indent-line)
5459 (setq-local indent-region-function 'org-indent-region)
5460 ;; Filling and auto-filling.
5461 (org-setup-filling)
5462 ;; Comments.
5463 (org-setup-comments-handling)
5464 ;; Initialize cache.
5465 (org-element-cache-reset)
5466 ;; Beginning/end of defun
5467 (setq-local beginning-of-defun-function 'org-backward-element)
5468 (setq-local end-of-defun-function
5469 (lambda ()
5470 (if (not (org-at-heading-p))
5471 (org-forward-element)
5472 (org-forward-element)
5473 (forward-char -1))))
5474 ;; Next error for sparse trees
5475 (setq-local next-error-function 'org-occur-next-match)
5476 ;; Make sure dependence stuff works reliably, even for users who set it
5477 ;; too late :-(
5478 (if org-enforce-todo-dependencies
5479 (add-hook 'org-blocker-hook
5480 'org-block-todo-from-children-or-siblings-or-parent)
5481 (remove-hook 'org-blocker-hook
5482 'org-block-todo-from-children-or-siblings-or-parent))
5483 (if org-enforce-todo-checkbox-dependencies
5484 (add-hook 'org-blocker-hook
5485 'org-block-todo-from-checkboxes)
5486 (remove-hook 'org-blocker-hook
5487 'org-block-todo-from-checkboxes))
5489 ;; Align options lines
5490 (setq-local
5491 align-mode-rules-list
5492 '((org-in-buffer-settings
5493 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5494 (modes . '(org-mode)))))
5496 ;; Imenu
5497 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5499 ;; Make isearch reveal context
5500 (setq-local outline-isearch-open-invisible-function
5501 (lambda (&rest _) (org-show-context 'isearch)))
5503 ;; Setup the pcomplete hooks
5504 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5505 (setq-local pcomplete-command-name-function 'org-command-at-point)
5506 (setq-local pcomplete-default-completion-function 'ignore)
5507 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5508 (setq-local pcomplete-termination-string "")
5509 (setq-local buffer-face-mode-face 'org-default)
5511 ;; If empty file that did not turn on Org mode automatically, make
5512 ;; it to.
5513 (when (and org-insert-mode-line-in-empty-file
5514 (org-called-interactively-p 'any)
5515 (= (point-min) (point-max)))
5516 (insert "# -*- mode: org -*-\n\n"))
5517 (unless org-inhibit-startup
5518 (org-unmodified
5519 (when org-startup-with-beamer-mode (org-beamer-mode))
5520 (when org-startup-align-all-tables
5521 (org-table-map-tables #'org-table-align t))
5522 (when org-startup-with-inline-images (org-display-inline-images))
5523 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5524 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5525 (when org-startup-truncated (setq truncate-lines t))
5526 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5527 (org-refresh-effort-properties)))
5528 ;; Try to set `org-hide' face correctly.
5529 (let ((foreground (org-find-invisible-foreground)))
5530 (when foreground
5531 (set-face-foreground 'org-hide foreground))))
5533 ;; Update `customize-package-emacs-version-alist'
5534 (add-to-list 'customize-package-emacs-version-alist
5535 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5536 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5537 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5539 (defvar org-mode-transpose-word-syntax-table
5540 (let ((st (make-syntax-table text-mode-syntax-table)))
5541 (dolist (c org-emphasis-alist st)
5542 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5544 (when (fboundp 'abbrev-table-put)
5545 (abbrev-table-put org-mode-abbrev-table
5546 :parents (list text-mode-abbrev-table)))
5548 (defun org-find-invisible-foreground ()
5549 (let ((candidates (remove
5550 "unspecified-bg"
5551 (nconc
5552 (list (face-background 'default)
5553 (face-background 'org-default))
5554 (mapcar
5555 (lambda (alist)
5556 (when (boundp alist)
5557 (cdr (assoc 'background-color (symbol-value alist)))))
5558 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5559 (list (face-foreground 'org-hide))))))
5560 (car (remove nil candidates))))
5562 (defun org-current-time (&optional rounding-minutes past)
5563 "Current time, possibly rounded to ROUNDING-MINUTES.
5564 When ROUNDING-MINUTES is not an integer, fall back on the car of
5565 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5566 the rounding returns a past time."
5567 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5568 (car org-time-stamp-rounding-minutes)))
5569 (time (decode-time)) res)
5570 (if (< r 1)
5571 (current-time)
5572 (setq res
5573 (apply 'encode-time
5574 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5575 (nthcdr 2 time))))
5576 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5577 (seconds-to-time (- (org-float-time res) (* r 60)))
5578 res))))
5580 (defun org-today ()
5581 "Return today date, considering `org-extend-today-until'."
5582 (time-to-days
5583 (time-subtract (current-time)
5584 (list 0 (* 3600 org-extend-today-until) 0))))
5586 ;;;; Font-Lock stuff, including the activators
5588 (defvar org-mouse-map (make-sparse-keymap))
5589 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5590 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5591 (when org-mouse-1-follows-link
5592 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5593 (when org-tab-follows-link
5594 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5595 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5597 (require 'font-lock)
5599 (defconst org-non-link-chars "]\t\n\r<>")
5600 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5601 "file+sys" "news" "shell" "elisp" "doi" "message"
5602 "help"))
5603 (defvar org-link-types-re nil
5604 "Matches a link that has a url-like prefix like \"http:\"")
5605 (defvar org-link-re-with-space nil
5606 "Matches a link with spaces, optional angular brackets around it.")
5607 (defvar org-link-re-with-space2 nil
5608 "Matches a link with spaces, optional angular brackets around it.")
5609 (defvar org-link-re-with-space3 nil
5610 "Matches a link with spaces, only for internal part in bracket links.")
5611 (defvar org-angle-link-re nil
5612 "Matches link with angular brackets, spaces are allowed.")
5613 (defvar org-plain-link-re nil
5614 "Matches plain link, without spaces.")
5615 (defvar org-bracket-link-regexp nil
5616 "Matches a link in double brackets.")
5617 (defvar org-bracket-link-analytic-regexp nil
5618 "Regular expression used to analyze links.
5619 Here is what the match groups contain after a match:
5620 1: http:
5621 2: http
5622 3: path
5623 4: [desc]
5624 5: desc")
5625 (defvar org-bracket-link-analytic-regexp++ nil
5626 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5627 (defvar org-any-link-re nil
5628 "Regular expression matching any link.")
5630 (defconst org-match-sexp-depth 3
5631 "Number of stacked braces for sub/superscript matching.")
5633 (defun org-create-multibrace-regexp (left right n)
5634 "Create a regular expression which will match a balanced sexp.
5635 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5636 as single character strings.
5637 The regexp returned will match the entire expression including the
5638 delimiters. It will also define a single group which contains the
5639 match except for the outermost delimiters. The maximum depth of
5640 stacked delimiters is N. Escaping delimiters is not possible."
5641 (let* ((nothing (concat "[^" left right "]*?"))
5642 (or "\\|")
5643 (re nothing)
5644 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5645 (while (> n 1)
5646 (setq n (1- n)
5647 re (concat re or next)
5648 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5649 (concat left "\\(" re "\\)" right)))
5651 (defconst org-match-substring-regexp
5652 (concat
5653 "\\(\\S-\\)\\([_^]\\)\\("
5654 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5655 "\\|"
5656 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5657 "\\|"
5658 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5659 "The regular expression matching a sub- or superscript.")
5661 (defconst org-match-substring-with-braces-regexp
5662 (concat
5663 "\\(\\S-\\)\\([_^]\\)"
5664 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5665 "The regular expression matching a sub- or superscript, forcing braces.")
5667 (defun org-make-link-regexps ()
5668 "Update the link regular expressions.
5669 This should be called after the variable `org-link-types' has changed."
5670 (let ((types-re (regexp-opt org-link-types t)))
5671 (setq org-link-types-re
5672 (concat "\\`" types-re ":")
5673 org-link-re-with-space
5674 (concat "<?" types-re ":"
5675 "\\([^" org-non-link-chars " ]"
5676 "[^" org-non-link-chars "]*"
5677 "[^" org-non-link-chars " ]\\)>?")
5678 org-link-re-with-space2
5679 (concat "<?" types-re ":"
5680 "\\([^" org-non-link-chars " ]"
5681 "[^\t\n\r]*"
5682 "[^" org-non-link-chars " ]\\)>?")
5683 org-link-re-with-space3
5684 (concat "<?" types-re ":"
5685 "\\([^" org-non-link-chars " ]"
5686 "[^\t\n\r]*\\)")
5687 org-angle-link-re
5688 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5689 types-re)
5690 org-plain-link-re
5691 (concat
5692 "\\<" types-re ":"
5693 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5694 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5695 org-bracket-link-regexp
5696 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5697 org-bracket-link-analytic-regexp
5698 (concat
5699 "\\[\\["
5700 "\\(" types-re ":\\)?"
5701 "\\([^]]+\\)"
5702 "\\]"
5703 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5704 "\\]")
5705 org-bracket-link-analytic-regexp++
5706 (concat
5707 "\\[\\["
5708 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5709 "\\([^]]+\\)"
5710 "\\]"
5711 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5712 "\\]")
5713 org-any-link-re
5714 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5715 org-angle-link-re "\\)\\|\\("
5716 org-plain-link-re "\\)"))))
5718 (org-make-link-regexps)
5720 (defvar org-emph-face nil)
5722 (defun org-do-emphasis-faces (limit)
5723 "Run through the buffer and emphasize strings."
5724 (let (rtn a)
5725 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5726 (let* ((border (char-after (match-beginning 3)))
5727 (bre (regexp-quote (char-to-string border))))
5728 (when (and (not (= border (char-after (match-beginning 4))))
5729 (not (string-match-p (concat bre ".*" bre)
5730 (replace-regexp-in-string
5731 "\n" " "
5732 (substring (match-string 2) 1 -1)))))
5733 (setq rtn t)
5734 (setq a (assoc (match-string 3) org-emphasis-alist))
5735 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5736 'face
5737 (nth 1 a))
5738 (and (nth 2 a)
5739 (org-remove-flyspell-overlays-in
5740 (match-beginning 0) (match-end 0)))
5741 (add-text-properties (match-beginning 2) (match-end 2)
5742 '(font-lock-multiline t org-emphasis t))
5743 (when org-hide-emphasis-markers
5744 (add-text-properties (match-end 4) (match-beginning 5)
5745 '(invisible org-link))
5746 (add-text-properties (match-beginning 3) (match-end 3)
5747 '(invisible org-link)))))
5748 (goto-char (1+ (match-beginning 0))))
5749 rtn))
5751 (defun org-emphasize (&optional char)
5752 "Insert or change an emphasis, i.e. a font like bold or italic.
5753 If there is an active region, change that region to a new emphasis.
5754 If there is no region, just insert the marker characters and position
5755 the cursor between them.
5756 CHAR should be the marker character. If it is a space, it means to
5757 remove the emphasis of the selected region.
5758 If CHAR is not given (for example in an interactive call) it will be
5759 prompted for."
5760 (interactive)
5761 (let ((erc org-emphasis-regexp-components)
5762 (string "") beg end move s)
5763 (if (org-region-active-p)
5764 (setq beg (region-beginning)
5765 end (region-end)
5766 string (buffer-substring beg end))
5767 (setq move t))
5769 (unless char
5770 (message "Emphasis marker or tag: [%s]"
5771 (mapconcat #'car org-emphasis-alist ""))
5772 (setq char (read-char-exclusive)))
5773 (if (equal char ?\s)
5774 (setq s ""
5775 move nil)
5776 (unless (assoc (char-to-string char) org-emphasis-alist)
5777 (user-error "No such emphasis marker: \"%c\"" char))
5778 (setq s (char-to-string char)))
5779 (while (and (> (length string) 1)
5780 (equal (substring string 0 1) (substring string -1))
5781 (assoc (substring string 0 1) org-emphasis-alist))
5782 (setq string (substring string 1 -1)))
5783 (setq string (concat s string s))
5784 (when beg (delete-region beg end))
5785 (unless (or (bolp)
5786 (string-match (concat "[" (nth 0 erc) "\n]")
5787 (char-to-string (char-before (point)))))
5788 (insert " "))
5789 (unless (or (eobp)
5790 (string-match (concat "[" (nth 1 erc) "\n]")
5791 (char-to-string (char-after (point)))))
5792 (insert " ") (backward-char 1))
5793 (insert string)
5794 (and move (backward-char 1))))
5796 (defconst org-nonsticky-props
5797 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5799 (defsubst org-rear-nonsticky-at (pos)
5800 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5802 (defun org-activate-plain-links (limit)
5803 "Add link properties for plain links."
5804 (let (f hl)
5805 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5806 (not (member 'org-tag
5807 (get-text-property (cond
5808 ((= 1 (match-beginning 0)) 1)
5809 (t (1- (match-beginning 0))))
5810 'face)))
5811 (not (org-in-src-block-p)))
5812 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5813 (setq f (get-text-property (match-beginning 0) 'face))
5814 (setq hl (org-match-string-no-properties 0))
5815 (unless (or (eq f 'org-tag)
5816 (and (listp f) (memq 'org-tag f)))
5817 (add-text-properties (match-beginning 0) (match-end 0)
5818 (list 'mouse-face 'highlight
5819 'face 'org-link
5820 'htmlize-link `(:uri ,hl)
5821 'keymap org-mouse-map))
5822 (org-rear-nonsticky-at (match-end 0)))
5823 t)))
5825 (defun org-activate-code (limit)
5826 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (remove-text-properties (match-beginning 0) (match-end 0)
5829 '(display t invisible t intangible t))
5832 (defcustom org-src-fontify-natively t
5833 "When non-nil, fontify code in code blocks."
5834 :type 'boolean
5835 :version "24.4"
5836 :package-version '(Org . "8.3")
5837 :group 'org-appearance
5838 :group 'org-babel)
5840 (defcustom org-allow-promoting-top-level-subtree nil
5841 "When non-nil, allow promoting a top level subtree.
5842 The leading star of the top level headline will be replaced
5843 by a #."
5844 :type 'boolean
5845 :version "24.1"
5846 :group 'org-appearance)
5848 (defun org-fontify-meta-lines-and-blocks (limit)
5849 (condition-case nil
5850 (org-fontify-meta-lines-and-blocks-1 limit)
5851 (error (message "org-mode fontification error"))))
5853 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5854 "Fontify #+ lines and blocks."
5855 (let ((case-fold-search t))
5856 (when (re-search-forward
5857 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5858 limit t)
5859 (let ((beg (match-beginning 0))
5860 (block-start (match-end 0))
5861 (block-end nil)
5862 (lang (match-string 7))
5863 (beg1 (line-beginning-position 2))
5864 (dc1 (downcase (match-string 2)))
5865 (dc3 (downcase (match-string 3)))
5866 end end1 quoting block-type)
5867 (cond
5868 ((and (match-end 4) (equal dc3 "+begin"))
5869 ;; Truly a block
5870 (setq block-type (downcase (match-string 5))
5871 quoting (member block-type org-protecting-blocks))
5872 (when (re-search-forward
5873 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5874 nil t) ;; on purpose, we look further than LIMIT
5875 (setq end (min (point-max) (match-end 0))
5876 end1 (min (point-max) (1- (match-beginning 0))))
5877 (setq block-end (match-beginning 0))
5878 (when quoting
5879 (org-remove-flyspell-overlays-in beg1 end1)
5880 (remove-text-properties beg end
5881 '(display t invisible t intangible t)))
5882 (add-text-properties
5883 beg end '(font-lock-fontified t font-lock-multiline t))
5884 (add-text-properties beg beg1 '(face org-meta-line))
5885 (org-remove-flyspell-overlays-in beg beg1)
5886 (add-text-properties ; For end_src
5887 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5888 (org-remove-flyspell-overlays-in end1 end)
5889 (cond
5890 ((and lang (not (string= lang "")) org-src-fontify-natively)
5891 (org-src-font-lock-fontify-block lang block-start block-end)
5892 (add-text-properties beg1 block-end '(src-block t)))
5893 (quoting
5894 (add-text-properties beg1 (min (point-max) (1+ end1))
5895 '(face org-block))) ; end of source block
5896 ((not org-fontify-quote-and-verse-blocks))
5897 ((string= block-type "quote")
5898 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5899 ((string= block-type "verse")
5900 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5901 (add-text-properties beg beg1 '(face org-block-begin-line))
5902 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5903 '(face org-block-end-line))
5905 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5906 (org-remove-flyspell-overlays-in
5907 (match-beginning 0)
5908 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5909 (add-text-properties
5910 beg (match-end 3)
5911 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5912 '(font-lock-fontified t invisible t)
5913 '(font-lock-fontified t face org-document-info-keyword)))
5914 (add-text-properties
5915 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5916 (if (string-equal dc1 "+title:")
5917 '(font-lock-fontified t face org-document-title)
5918 '(font-lock-fontified t face org-document-info))))
5919 ((equal dc1 "+caption:")
5920 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5921 (remove-text-properties (match-beginning 0) (match-end 0)
5922 '(display t invisible t intangible t))
5923 (add-text-properties (match-beginning 1) (match-end 3)
5924 '(font-lock-fontified t face org-meta-line))
5925 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5926 '(font-lock-fontified t face org-block))
5928 ((member dc3 '(" " ""))
5929 (org-remove-flyspell-overlays-in beg (match-end 0))
5930 (add-text-properties
5931 beg (match-end 0)
5932 '(font-lock-fontified t face font-lock-comment-face)))
5933 (t ;; just any other in-buffer setting, but not indented
5934 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5935 (remove-text-properties (match-beginning 0) (match-end 0)
5936 '(display t invisible t intangible t))
5937 (add-text-properties beg (match-end 0)
5938 '(font-lock-fontified t face org-meta-line))
5939 t))))))
5941 (defun org-fontify-drawers (limit)
5942 "Fontify drawers."
5943 (when (re-search-forward org-drawer-regexp limit t)
5944 (add-text-properties
5945 (match-beginning 0) (match-end 0)
5946 '(font-lock-fontified t face org-special-keyword))
5947 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5950 (defun org-fontify-macros (limit)
5951 "Fontify macros."
5952 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5953 (add-text-properties
5954 (match-beginning 0) (match-end 0)
5955 '(font-lock-fontified t face org-macro))
5956 (when org-hide-macro-markers
5957 (add-text-properties (match-end 2) (match-beginning 2)
5958 '(invisible t))
5959 (add-text-properties (match-beginning 1) (match-end 1)
5960 '(invisible t)))
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (defun org-activate-angle-links (limit)
5965 "Add text properties for angle links."
5966 (when (and (re-search-forward org-angle-link-re limit t)
5967 (not (org-in-src-block-p)))
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (add-text-properties (match-beginning 0) (match-end 0)
5970 (list 'mouse-face 'highlight
5971 'keymap org-mouse-map
5972 'font-lock-multiline t))
5973 (org-rear-nonsticky-at (match-end 0))
5976 (defun org-activate-footnote-links (limit)
5977 "Add text properties for footnotes."
5978 (let ((fn (org-footnote-next-reference-or-definition limit)))
5979 (when fn
5980 (let* ((beg (nth 1 fn))
5981 (end (nth 2 fn))
5982 (label (car fn))
5983 (referencep (/= (line-beginning-position) beg)))
5984 (when (and referencep (nth 3 fn))
5985 (save-excursion
5986 (goto-char beg)
5987 (search-forward (or label "fn:"))
5988 (org-remove-flyspell-overlays-in beg (match-end 0))))
5989 (add-text-properties beg end
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map
5992 'help-echo
5993 (if referencep "Footnote reference"
5994 "Footnote definition")
5995 'font-lock-fontified t
5996 'font-lock-multiline t
5997 'face 'org-footnote))))))
5999 (defun org-activate-bracket-links (limit)
6000 "Add text properties for bracketed links."
6001 (when (and (re-search-forward org-bracket-link-regexp limit t)
6002 (not (org-in-src-block-p)))
6003 (let* ((hl (org-match-string-no-properties 1))
6004 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6005 (ip (org-maybe-intangible
6006 (list 'invisible 'org-link
6007 'keymap org-mouse-map 'mouse-face 'highlight
6008 'font-lock-multiline t 'help-echo help
6009 'htmlize-link `(:uri ,hl))))
6010 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6011 'font-lock-multiline t 'help-echo help
6012 'htmlize-link `(:uri ,hl))))
6013 ;; We need to remove the invisible property here. Table narrowing
6014 ;; may have made some of this invisible.
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (remove-text-properties (match-beginning 0) (match-end 0)
6017 '(invisible nil))
6018 (if (match-end 3)
6019 (progn
6020 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6021 (org-rear-nonsticky-at (match-beginning 3))
6022 (add-text-properties (match-beginning 3) (match-end 3) vp)
6023 (org-rear-nonsticky-at (match-end 3))
6024 (add-text-properties (match-end 3) (match-end 0) ip)
6025 (org-rear-nonsticky-at (match-end 0)))
6026 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6027 (org-rear-nonsticky-at (match-beginning 1))
6028 (add-text-properties (match-beginning 1) (match-end 1) vp)
6029 (org-rear-nonsticky-at (match-end 1))
6030 (add-text-properties (match-end 1) (match-end 0) ip)
6031 (org-rear-nonsticky-at (match-end 0)))
6032 t)))
6034 (defun org-activate-dates (limit)
6035 "Add text properties for dates."
6036 (when (and (re-search-forward org-tsr-regexp-both limit t)
6037 (not (equal (char-before (match-beginning 0)) 91)))
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6039 (add-text-properties (match-beginning 0) (match-end 0)
6040 (list 'mouse-face 'highlight
6041 'keymap org-mouse-map))
6042 (org-rear-nonsticky-at (match-end 0))
6043 (when org-display-custom-times
6044 (if (match-end 3)
6045 (org-display-custom-time (match-beginning 3) (match-end 3))
6046 (org-display-custom-time (match-beginning 1) (match-end 1))))
6049 (defvar-local org-target-link-regexp nil
6050 "Regular expression matching radio targets in plain text.")
6052 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6053 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6054 border border border))
6055 "Regular expression matching a link target.")
6057 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6058 "Regular expression matching a radio target.")
6060 (defconst org-any-target-regexp
6061 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6062 "Regular expression matching any target.")
6064 (defun org-activate-target-links (limit)
6065 "Add text properties for target matches."
6066 (when org-target-link-regexp
6067 (let ((case-fold-search t))
6068 (when (re-search-forward org-target-link-regexp limit t)
6069 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6070 (add-text-properties (match-beginning 1) (match-end 1)
6071 (list 'mouse-face 'highlight
6072 'keymap org-mouse-map
6073 'help-echo "Radio target link"
6074 'org-linked-text t))
6075 (org-rear-nonsticky-at (match-end 1))
6076 t))))
6078 (defun org-update-radio-target-regexp ()
6079 "Find all radio targets in this file and update the regular expression.
6080 Also refresh fontification if needed."
6081 (interactive)
6082 (let ((old-regexp org-target-link-regexp)
6083 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6084 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6085 (targets
6086 (org-with-wide-buffer
6087 (goto-char (point-min))
6088 (let (rtn)
6089 (while (re-search-forward org-radio-target-regexp nil t)
6090 ;; Make sure point is really within the object.
6091 (backward-char)
6092 (let ((obj (org-element-context)))
6093 (when (eq (org-element-type obj) 'radio-target)
6094 (cl-pushnew (org-element-property :value obj) rtn
6095 :test #'equal))))
6096 rtn))))
6097 (setq org-target-link-regexp
6098 (and targets
6099 (concat before-re
6100 (mapconcat
6101 (lambda (x)
6102 (replace-regexp-in-string
6103 " +" "\\s-+" (regexp-quote x) t t))
6104 targets
6105 "\\|")
6106 after-re)))
6107 (unless (equal old-regexp org-target-link-regexp)
6108 ;; Clean-up cache.
6109 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6110 ((not org-target-link-regexp) old-regexp)
6112 (concat before-re
6113 (mapconcat
6114 (lambda (re)
6115 (substring re (length before-re)
6116 (- (length after-re))))
6117 (list old-regexp org-target-link-regexp)
6118 "\\|")
6119 after-re)))))
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (while (re-search-forward regexp nil t)
6123 (org-element-cache-refresh (match-beginning 1)))))
6124 ;; Re fontify buffer.
6125 (when (memq 'radio org-highlight-links)
6126 (org-restart-font-lock)))))
6128 (defun org-hide-wide-columns (limit)
6129 (let (s e)
6130 (setq s (text-property-any (point) (or limit (point-max))
6131 'org-cwidth t))
6132 (when s
6133 (setq e (next-single-property-change s 'org-cwidth))
6134 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6135 (goto-char e)
6136 t)))
6138 (defvar org-latex-and-related-regexp nil
6139 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6141 (defun org-compute-latex-and-related-regexp ()
6142 "Compute regular expression for LaTeX, entities and sub/superscript.
6143 Result depends on variable `org-highlight-latex-and-related'."
6144 (setq-local
6145 org-latex-and-related-regexp
6146 (let* ((re-sub
6147 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6148 ((eq org-use-sub-superscripts '{})
6149 (list org-match-substring-with-braces-regexp))
6150 (org-use-sub-superscripts (list org-match-substring-regexp))))
6151 (re-latex
6152 (when (memq 'latex org-highlight-latex-and-related)
6153 (let ((matchers (plist-get org-format-latex-options :matchers)))
6154 (delq nil
6155 (mapcar (lambda (x)
6156 (and (member (car x) matchers) (nth 1 x)))
6157 org-latex-regexps)))))
6158 (re-entities
6159 (when (memq 'entities org-highlight-latex-and-related)
6160 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6161 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6163 (defun org-do-latex-and-related (limit)
6164 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6165 LIMIT bounds the search for syntax to highlight. Stop at first
6166 highlighted object, if any. Return t if some highlighting was
6167 done, nil otherwise."
6168 (when (org-string-nw-p org-latex-and-related-regexp)
6169 (catch 'found
6170 (while (re-search-forward org-latex-and-related-regexp limit t)
6171 (unless
6172 (cl-some
6173 (lambda (f)
6174 (memq f '(org-code org-verbatim underline org-special-keyword)))
6175 (save-excursion
6176 (goto-char (1+ (match-beginning 0)))
6177 (face-at-point nil t)))
6178 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6179 '(?_ ?^))
6181 0)))
6182 (font-lock-prepend-text-property
6183 (+ offset (match-beginning 0)) (match-end 0)
6184 'face 'org-latex-and-related)
6185 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6186 '(font-lock-multiline t)))
6187 (throw 'found t)))
6188 nil)))
6190 (defun org-restart-font-lock ()
6191 "Restart `font-lock-mode', to force refontification."
6192 (when (and (boundp 'font-lock-mode) font-lock-mode)
6193 (font-lock-mode -1)
6194 (font-lock-mode 1)))
6196 (defun org-activate-tags (limit)
6197 (when (re-search-forward
6198 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6199 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6200 (add-text-properties (match-beginning 1) (match-end 1)
6201 (list 'mouse-face 'highlight
6202 'keymap org-mouse-map))
6203 (org-rear-nonsticky-at (match-end 1))
6206 (defun org-outline-level ()
6207 "Compute the outline level of the heading at point.
6209 If this is called at a normal headline, the level is the number
6210 of stars. Use `org-reduced-level' to remove the effect of
6211 `org-odd-levels'. Unlike to `org-current-level', this function
6212 takes into consideration inlinetasks."
6213 (org-with-wide-buffer
6214 (end-of-line)
6215 (if (re-search-backward org-outline-regexp-bol nil t)
6216 (1- (- (match-end 0) (match-beginning 0)))
6217 0)))
6219 (defvar org-font-lock-keywords nil)
6221 (defsubst org-re-property (property &optional literal allow-null value)
6222 "Return a regexp matching a PROPERTY line.
6224 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6225 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6226 non-nil, match properties even without a value.
6228 Match group 3 is set to the value when it exists. If there is no
6229 value and ALLOW-NULL is non-nil, it is set to the empty string.
6231 With optional argument VALUE, match only property lines with
6232 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6233 unless LITERAL is non-nil."
6234 (concat
6235 "^\\(?4:[ \t]*\\)"
6236 (format "\\(?1::\\(?2:%s\\):\\)"
6237 (if literal property (regexp-quote property)))
6238 (cond (value
6239 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6240 (if literal value (regexp-quote value))))
6241 (allow-null
6242 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6244 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6246 (defconst org-property-re
6247 (org-re-property "\\S-+" 'literal t)
6248 "Regular expression matching a property line.
6249 There are four matching groups:
6250 1: :PROPKEY: including the leading and trailing colon,
6251 2: PROPKEY without the leading and trailing colon,
6252 3: PROPVAL without leading or trailing spaces,
6253 4: the indentation of the current line,
6254 5: trailing whitespace.")
6256 (defvar org-font-lock-hook nil
6257 "Functions to be called for special font lock stuff.")
6259 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6261 (defvar org-font-lock-set-keywords-hook nil
6262 "Functions that can manipulate `org-font-lock-extra-keywords'.
6263 This is called after `org-font-lock-extra-keywords' is defined, but before
6264 it is installed to be used by font lock. This can be useful if something
6265 needs to be inserted at a specific position in the font-lock sequence.")
6267 (defun org-font-lock-hook (limit)
6268 "Run `org-font-lock-hook' within LIMIT."
6269 (run-hook-with-args 'org-font-lock-hook limit))
6271 (defun org-set-font-lock-defaults ()
6272 "Set font lock defaults for the current buffer."
6273 (let* ((em org-fontify-emphasized-text)
6274 (lk org-highlight-links)
6275 (org-font-lock-extra-keywords
6276 (list
6277 ;; Call the hook
6278 '(org-font-lock-hook)
6279 ;; Headlines
6280 `(,(if org-fontify-whole-heading-line
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6282 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6283 (1 (org-get-level-face 1))
6284 (2 (org-get-level-face 2))
6285 (3 (org-get-level-face 3)))
6286 ;; Table lines
6287 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6288 (1 'org-table t))
6289 ;; Table internals
6290 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6291 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6292 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6293 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6294 ;; Drawers
6295 '(org-fontify-drawers)
6296 ;; Properties
6297 (list org-property-re
6298 '(1 'org-special-keyword t)
6299 '(3 'org-property-value t))
6300 ;; Links
6301 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6302 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6303 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6304 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6305 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6306 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6307 (when (memq 'footnote lk) '(org-activate-footnote-links))
6308 ;; Targets.
6309 (list org-any-target-regexp '(0 'org-target t))
6310 ;; Diary sexps.
6311 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6312 ;; Macro
6313 '(org-fontify-macros)
6314 '(org-hide-wide-columns (0 nil append))
6315 ;; TODO keyword
6316 (list (format org-heading-keyword-regexp-format
6317 org-todo-regexp)
6318 '(2 (org-get-todo-face 2) t))
6319 ;; DONE
6320 (if org-fontify-done-headline
6321 (list (format org-heading-keyword-regexp-format
6322 (concat
6323 "\\(?:"
6324 (mapconcat 'regexp-quote org-done-keywords "\\|")
6325 "\\)"))
6326 '(2 'org-headline-done t))
6327 nil)
6328 ;; Priorities
6329 '(org-font-lock-add-priority-faces)
6330 ;; Tags
6331 '(org-font-lock-add-tag-faces)
6332 ;; Tags groups
6333 (when (and org-group-tags org-tag-groups-alist)
6334 (list (concat org-outline-regexp-bol ".+\\(:"
6335 (regexp-opt (mapcar 'car org-tag-groups-alist))
6336 ":\\).*$")
6337 '(1 'org-tag-group prepend)))
6338 ;; Special keywords
6339 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6340 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6341 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6343 ;; Emphasis
6344 (when em
6345 (if (featurep 'xemacs)
6346 '(org-do-emphasis-faces (0 nil append))
6347 '(org-do-emphasis-faces)))
6348 ;; Checkboxes
6349 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6350 1 'org-checkbox prepend)
6351 (when (cdr (assq 'checkbox org-list-automatic-rules))
6352 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6353 (0 (org-get-checkbox-statistics-face) t)))
6354 ;; Description list items
6355 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6356 1 'org-list-dt prepend)
6357 ;; ARCHIVEd headings
6358 (list (concat
6359 org-outline-regexp-bol
6360 "\\(.*:" org-archive-tag ":.*\\)")
6361 '(1 'org-archived prepend))
6362 ;; Specials
6363 '(org-do-latex-and-related)
6364 '(org-fontify-entities)
6365 '(org-raise-scripts)
6366 ;; Code
6367 '(org-activate-code (1 'org-code t))
6368 ;; COMMENT
6369 (list (format
6370 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6371 org-todo-regexp
6372 org-comment-string)
6373 '(9 'org-special-keyword t))
6374 ;; Blocks and meta lines
6375 '(org-fontify-meta-lines-and-blocks))))
6376 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6377 (run-hooks 'org-font-lock-set-keywords-hook)
6378 ;; Now set the full font-lock-keywords
6379 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6380 (setq-local font-lock-defaults
6381 '(org-font-lock-keywords t nil nil backward-paragraph))
6382 (kill-local-variable 'font-lock-keywords) nil))
6384 (defun org-toggle-pretty-entities ()
6385 "Toggle the composition display of entities as UTF8 characters."
6386 (interactive)
6387 (setq-local org-pretty-entities (not org-pretty-entities))
6388 (org-restart-font-lock)
6389 (if org-pretty-entities
6390 (message "Entities are now displayed as UTF8 characters")
6391 (save-restriction
6392 (widen)
6393 (org-decompose-region (point-min) (point-max))
6394 (message "Entities are now displayed as plain text"))))
6396 (defvar-local org-custom-properties-overlays nil
6397 "List of overlays used for custom properties.")
6399 (defun org-toggle-custom-properties-visibility ()
6400 "Display or hide properties in `org-custom-properties'."
6401 (interactive)
6402 (if org-custom-properties-overlays
6403 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6404 (setq org-custom-properties-overlays nil))
6405 (when org-custom-properties
6406 (org-with-wide-buffer
6407 (goto-char (point-min))
6408 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6409 (while (re-search-forward regexp nil t)
6410 (let ((end (cdr (save-match-data (org-get-property-block)))))
6411 (when (and end (< (point) end))
6412 ;; Hide first custom property in current drawer.
6413 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6414 (overlay-put o 'invisible t)
6415 (overlay-put o 'org-custom-property t)
6416 (push o org-custom-properties-overlays))
6417 ;; Hide additional custom properties in the same drawer.
6418 (while (re-search-forward regexp end t)
6419 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6420 (overlay-put o 'invisible t)
6421 (overlay-put o 'org-custom-property t)
6422 (push o org-custom-properties-overlays)))))
6423 ;; Each entry is limited to a single property drawer.
6424 (outline-next-heading)))))))
6426 (defun org-fontify-entities (limit)
6427 "Find an entity to fontify."
6428 (let (ee)
6429 (when org-pretty-entities
6430 (catch 'match
6431 ;; "\_ "-family is left out on purpose. Only the first one,
6432 ;; i.e., "\_ ", could be fontified anyway, and it would be
6433 ;; confusing when adding a second white space character.
6434 (while (re-search-forward
6435 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6436 limit t)
6437 (when (and (not (org-at-comment-p))
6438 (setq ee (org-entity-get (match-string 1)))
6439 (= (length (nth 6 ee)) 1))
6440 (let* ((end (if (equal (match-string 2) "{}")
6441 (match-end 2)
6442 (match-end 1))))
6443 (add-text-properties
6444 (match-beginning 0) end
6445 (list 'font-lock-fontified t))
6446 (compose-region (match-beginning 0) end
6447 (nth 6 ee) nil)
6448 (backward-char 1)
6449 (throw 'match t))))
6450 nil))))
6452 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6453 "Fontify string S like in Org-mode."
6454 (with-temp-buffer
6455 (insert s)
6456 (let ((org-odd-levels-only odd-levels))
6457 (org-mode)
6458 (font-lock-ensure)
6459 (buffer-string))))
6461 (defvar org-m nil)
6462 (defvar org-l nil)
6463 (defvar org-f nil)
6464 (defun org-get-level-face (n)
6465 "Get the right face for match N in font-lock matching of headlines."
6466 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6467 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6468 (if org-cycle-level-faces
6469 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6470 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6471 (cond
6472 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6473 ((eq n 2) org-f)
6474 (t (unless org-level-color-stars-only org-f))))
6476 (defun org-face-from-face-or-color (context inherit face-or-color)
6477 "Create a face list that inherits INHERIT, but sets the foreground color.
6478 When FACE-OR-COLOR is not a string, just return it."
6479 (if (stringp face-or-color)
6480 (list :inherit inherit
6481 (cdr (assoc context org-faces-easy-properties))
6482 face-or-color)
6483 face-or-color))
6485 (defun org-get-todo-face (kwd)
6486 "Get the right face for a TODO keyword KWD.
6487 If KWD is a number, get the corresponding match group."
6488 (when (numberp kwd) (setq kwd (match-string kwd)))
6489 (or (org-face-from-face-or-color
6490 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6491 (and (member kwd org-done-keywords) 'org-done)
6492 'org-todo))
6494 (defun org-get-priority-face (priority)
6495 "Get the right face for PRIORITY.
6496 PRIORITY is a character."
6497 (or (org-face-from-face-or-color
6498 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6499 'org-priority))
6501 (defun org-get-tag-face (tag)
6502 "Get the right face for TAG.
6503 If TAG is a number, get the corresponding match group."
6504 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6505 (or (org-face-from-face-or-color
6506 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6507 'org-tag)))
6509 (defun org-font-lock-add-priority-faces (limit)
6510 "Add the special priority faces."
6511 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6512 (add-text-properties
6513 (match-beginning 1) (match-end 1)
6514 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6515 'font-lock-fontified t))))
6517 (defun org-font-lock-add-tag-faces (limit)
6518 "Add the special tag faces."
6519 (when (and org-tag-faces org-tags-special-faces-re)
6520 (while (re-search-forward org-tags-special-faces-re limit t)
6521 (add-text-properties (match-beginning 1) (match-end 1)
6522 (list 'face (org-get-tag-face 1)
6523 'font-lock-fontified t))
6524 (backward-char 1))))
6526 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6527 "Remove fontification and activation overlays from links."
6528 (font-lock-default-unfontify-region beg end)
6529 (let* ((buffer-undo-list t)
6530 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6531 (inhibit-modification-hooks t)
6532 deactivate-mark buffer-file-name buffer-file-truename)
6533 (org-decompose-region beg end)
6534 (remove-text-properties beg end
6535 '(mouse-face t keymap t org-linked-text t
6536 invisible t intangible t
6537 org-emphasis t))
6538 (org-remove-font-lock-display-properties beg end)))
6540 (defconst org-script-display '(((raise -0.3) (height 0.7))
6541 ((raise 0.3) (height 0.7))
6542 ((raise -0.5))
6543 ((raise 0.5)))
6544 "Display properties for showing superscripts and subscripts.")
6546 (defun org-remove-font-lock-display-properties (beg end)
6547 "Remove specific display properties that have been added by font lock.
6548 The will remove the raise properties that are used to show superscripts
6549 and subscripts."
6550 (let (next prop)
6551 (while (< beg end)
6552 (setq next (next-single-property-change beg 'display nil end)
6553 prop (get-text-property beg 'display))
6554 (when (member prop org-script-display)
6555 (put-text-property beg next 'display nil))
6556 (setq beg next))))
6558 (defun org-raise-scripts (limit)
6559 "Add raise properties to sub/superscripts."
6560 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6561 (re-search-forward
6562 (if (eq org-use-sub-superscripts t)
6563 org-match-substring-regexp
6564 org-match-substring-with-braces-regexp)
6565 limit t))
6566 (let* ((pos (point)) table-p comment-p
6567 (mpos (match-beginning 3))
6568 (emph-p (get-text-property mpos 'org-emphasis))
6569 (link-p (get-text-property mpos 'mouse-face))
6570 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6571 (goto-char (point-at-bol))
6572 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6573 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6574 (goto-char pos)
6575 ;; Handle a_b^c
6576 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6577 (unless (or comment-p emph-p link-p keyw-p)
6578 (put-text-property (match-beginning 3) (match-end 0)
6579 'display
6580 (if (equal (char-after (match-beginning 2)) ?^)
6581 (nth (if table-p 3 1) org-script-display)
6582 (nth (if table-p 2 0) org-script-display)))
6583 (add-text-properties (match-beginning 2) (match-end 2)
6584 (list 'invisible t
6585 'org-dwidth t 'org-dwidth-n 1))
6586 (if (and (eq (char-after (match-beginning 3)) ?{)
6587 (eq (char-before (match-end 3)) ?}))
6588 (progn
6589 (add-text-properties
6590 (match-beginning 3) (1+ (match-beginning 3))
6591 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6592 (add-text-properties
6593 (1- (match-end 3)) (match-end 3)
6594 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6595 t)))
6597 ;;;; Visibility cycling, including org-goto and indirect buffer
6599 ;;; Cycling
6601 (defvar-local org-cycle-global-status nil)
6602 (put 'org-cycle-global-status 'org-state t)
6603 (defvar-local org-cycle-subtree-status nil)
6604 (put 'org-cycle-subtree-status 'org-state t)
6606 (defvar org-inlinetask-min-level)
6608 (defun org-unlogged-message (&rest args)
6609 "Display a message, but avoid logging it in the *Messages* buffer."
6610 (let ((message-log-max nil))
6611 (apply 'message args)))
6613 ;;;###autoload
6614 (defun org-cycle (&optional arg)
6615 "TAB-action and visibility cycling for Org-mode.
6617 This is the command invoked in Org-mode by the TAB key. Its main purpose
6618 is outline visibility cycling, but it also invokes other actions
6619 in special contexts.
6621 - When this function is called with a prefix argument, rotate the entire
6622 buffer through 3 states (global cycling)
6623 1. OVERVIEW: Show only top-level headlines.
6624 2. CONTENTS: Show all headlines of all levels, but no body text.
6625 3. SHOW ALL: Show everything.
6626 With a double \\[universal-argument] prefix argument, \
6627 switch to the startup visibility,
6628 determined by the variable `org-startup-folded', and by any VISIBILITY
6629 properties in the buffer.
6630 With a triple \\[universal-argument] prefix argument, \
6631 show the entire buffer, including any drawers.
6633 - When inside a table, re-align the table and move to the next field.
6635 - When point is at the beginning of a headline, rotate the subtree started
6636 by this line through 3 different states (local cycling)
6637 1. FOLDED: Only the main headline is shown.
6638 2. CHILDREN: The main headline and the direct children are shown.
6639 From this state, you can move to one of the children
6640 and zoom in further.
6641 3. SUBTREE: Show the entire subtree, including body text.
6642 If there is no subtree, switch directly from CHILDREN to FOLDED.
6644 - When point is at the beginning of an empty headline and the variable
6645 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6646 of the headline by demoting and promoting it to likely levels. This
6647 speeds up creation document structure by pressing TAB once or several
6648 times right after creating a new headline.
6650 - When there is a numeric prefix, go up to a heading with level ARG, do
6651 a `show-subtree' and return to the previous cursor position. If ARG
6652 is negative, go up that many levels.
6654 - When point is not at the beginning of a headline, execute the global
6655 binding for TAB, which is re-indenting the line. See the option
6656 `org-cycle-emulate-tab' for details.
6658 - Special case: if point is at the beginning of the buffer and there is
6659 no headline in line 1, this function will act as if called with prefix arg
6660 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6661 But only if also the variable `org-cycle-global-at-bob' is t."
6662 (interactive "P")
6663 (org-load-modules-maybe)
6664 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6665 (and org-cycle-level-after-item/entry-creation
6666 (or (org-cycle-level)
6667 (org-cycle-item-indentation))))
6668 (let* ((limit-level
6669 (or org-cycle-max-level
6670 (and (boundp 'org-inlinetask-min-level)
6671 org-inlinetask-min-level
6672 (1- org-inlinetask-min-level))))
6673 (nstars (and limit-level
6674 (if org-odd-levels-only
6675 (and limit-level (1- (* limit-level 2)))
6676 limit-level)))
6677 (org-outline-regexp
6678 (if (not (derived-mode-p 'org-mode))
6679 outline-regexp
6680 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6681 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6682 (not (looking-at org-outline-regexp))))
6683 (org-cycle-hook
6684 (if bob-special
6685 (delq 'org-optimize-window-after-visibility-change
6686 (copy-sequence org-cycle-hook))
6687 org-cycle-hook))
6688 (pos (point)))
6690 (when (or bob-special (equal arg '(4)))
6691 ;; special case: use global cycling
6692 (setq arg t))
6694 (cond
6696 ((equal arg '(16))
6697 (setq last-command 'dummy)
6698 (org-set-startup-visibility)
6699 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6701 ((equal arg '(64))
6702 (outline-show-all)
6703 (org-unlogged-message "Entire buffer visible, including drawers"))
6705 ;; Try cdlatex TAB completion
6706 ((org-try-cdlatex-tab))
6708 ;; Table: enter it or move to the next field.
6709 ((org-at-table-p 'any)
6710 (if (org-at-table.el-p)
6711 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6712 Use \\[org-edit-special] to edit table.el tables"))
6713 (if arg (org-table-edit-field t)
6714 (org-table-justify-field-maybe)
6715 (call-interactively 'org-table-next-field))))
6717 ((run-hook-with-args-until-success
6718 'org-tab-after-check-for-table-hook))
6720 ;; Global cycling: delegate to `org-cycle-internal-global'.
6721 ((eq arg t) (org-cycle-internal-global))
6723 ;; Drawers: delegate to `org-flag-drawer'.
6724 ((save-excursion
6725 (beginning-of-line 1)
6726 (looking-at org-drawer-regexp))
6727 (org-flag-drawer ; toggle block visibility
6728 (not (get-char-property (match-end 0) 'invisible))))
6730 ;; Show-subtree, ARG levels up from here.
6731 ((integerp arg)
6732 (save-excursion
6733 (org-back-to-heading)
6734 (outline-up-heading (if (< arg 0) (- arg)
6735 (- (funcall outline-level) arg)))
6736 (org-show-subtree)))
6738 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6739 ((and (featurep 'org-inlinetask)
6740 (org-inlinetask-at-task-p)
6741 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6742 (org-inlinetask-toggle-visibility))
6744 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6745 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6746 (save-excursion (move-beginning-of-line 1)
6747 (looking-at org-outline-regexp)))
6748 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6749 (org-cycle-internal-local))
6751 ;; From there: TAB emulation and template completion.
6752 (buffer-read-only (org-back-to-heading))
6754 ((run-hook-with-args-until-success
6755 'org-tab-after-check-for-cycling-hook))
6757 ((org-try-structure-completion))
6759 ((run-hook-with-args-until-success
6760 'org-tab-before-tab-emulation-hook))
6762 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6763 (or (not (bolp))
6764 (not (looking-at org-outline-regexp))))
6765 (call-interactively (global-key-binding "\t")))
6767 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6768 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6769 (or (and (eq org-cycle-emulate-tab 'white)
6770 (= (match-end 0) (point-at-eol)))
6771 (and (eq org-cycle-emulate-tab 'whitestart)
6772 (>= (match-end 0) pos))))
6774 (eq org-cycle-emulate-tab t))
6775 (call-interactively (global-key-binding "\t")))
6777 (t (save-excursion
6778 (org-back-to-heading)
6779 (org-cycle)))))))
6781 (defun org-cycle-internal-global ()
6782 "Do the global cycling action."
6783 ;; Hack to avoid display of messages for .org attachments in Gnus
6784 (let ((ga (string-match "\\*fontification" (buffer-name))))
6785 (cond
6786 ((and (eq last-command this-command)
6787 (eq org-cycle-global-status 'overview))
6788 ;; We just created the overview - now do table of contents
6789 ;; This can be slow in very large buffers, so indicate action
6790 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6791 (unless ga (org-unlogged-message "CONTENTS..."))
6792 (org-content)
6793 (unless ga (org-unlogged-message "CONTENTS...done"))
6794 (setq org-cycle-global-status 'contents)
6795 (run-hook-with-args 'org-cycle-hook 'contents))
6797 ((and (eq last-command this-command)
6798 (eq org-cycle-global-status 'contents))
6799 ;; We just showed the table of contents - now show everything
6800 (run-hook-with-args 'org-pre-cycle-hook 'all)
6801 (outline-show-all)
6802 (unless ga (org-unlogged-message "SHOW ALL"))
6803 (setq org-cycle-global-status 'all)
6804 (run-hook-with-args 'org-cycle-hook 'all))
6807 ;; Default action: go to overview
6808 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6809 (org-overview)
6810 (unless ga (org-unlogged-message "OVERVIEW"))
6811 (setq org-cycle-global-status 'overview)
6812 (run-hook-with-args 'org-cycle-hook 'overview)))))
6814 (defvar org-called-with-limited-levels nil
6815 "Non-nil when `org-with-limited-levels' is currently active.")
6817 (defun org-cycle-internal-local ()
6818 "Do the local cycling action."
6819 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6820 ;; First, determine end of headline (EOH), end of subtree or item
6821 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6822 (save-excursion
6823 (if (org-at-item-p)
6824 (progn
6825 (beginning-of-line)
6826 (setq struct (org-list-struct))
6827 (setq eoh (point-at-eol))
6828 (setq eos (org-list-get-item-end-before-blank (point) struct))
6829 (setq has-children (org-list-has-child-p (point) struct)))
6830 (org-back-to-heading)
6831 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6832 (setq eos (save-excursion (org-end-of-subtree t t)
6833 (when (bolp) (backward-char)) (point)))
6834 (setq has-children
6835 (or (save-excursion
6836 (let ((level (funcall outline-level)))
6837 (outline-next-heading)
6838 (and (org-at-heading-p t)
6839 (> (funcall outline-level) level))))
6840 (save-excursion
6841 (org-list-search-forward (org-item-beginning-re) eos t)))))
6842 ;; Determine end invisible part of buffer (EOL)
6843 (beginning-of-line 2)
6844 ;; XEmacs doesn't have `next-single-char-property-change'
6845 (if (featurep 'xemacs)
6846 (while (and (not (eobp)) ;; this is like `next-line'
6847 (get-char-property (1- (point)) 'invisible))
6848 (beginning-of-line 2))
6849 (while (and (not (eobp)) ;; this is like `next-line'
6850 (get-char-property (1- (point)) 'invisible))
6851 (goto-char (next-single-char-property-change (point) 'invisible))
6852 (and (eolp) (beginning-of-line 2))))
6853 (setq eol (point)))
6854 ;; Find out what to do next and set `this-command'
6855 (cond
6856 ((= eos eoh)
6857 ;; Nothing is hidden behind this heading
6858 (unless (org-before-first-heading-p)
6859 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6860 (org-unlogged-message "EMPTY ENTRY")
6861 (setq org-cycle-subtree-status nil)
6862 (save-excursion
6863 (goto-char eos)
6864 (outline-next-heading)
6865 (when (outline-invisible-p) (org-flag-heading nil))))
6866 ((and (or (>= eol eos)
6867 (not (string-match "\\S-" (buffer-substring eol eos))))
6868 (or has-children
6869 (not (setq children-skipped
6870 org-cycle-skip-children-state-if-no-children))))
6871 ;; Entire subtree is hidden in one line: children view
6872 (unless (org-before-first-heading-p)
6873 (run-hook-with-args 'org-pre-cycle-hook 'children))
6874 (if (org-at-item-p)
6875 (org-list-set-item-visibility (point-at-bol) struct 'children)
6876 (org-show-entry)
6877 (org-with-limited-levels (org-show-children))
6878 ;; FIXME: This slows down the func way too much.
6879 ;; How keep drawers hidden in subtree anyway?
6880 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6881 ;; (org-cycle-hide-drawers 'subtree))
6883 ;; Fold every list in subtree to top-level items.
6884 (when (eq org-cycle-include-plain-lists 'integrate)
6885 (save-excursion
6886 (org-back-to-heading)
6887 (while (org-list-search-forward (org-item-beginning-re) eos t)
6888 (beginning-of-line 1)
6889 (let* ((struct (org-list-struct))
6890 (prevs (org-list-prevs-alist struct))
6891 (end (org-list-get-bottom-point struct)))
6892 (dolist (e (org-list-get-all-items (point) struct prevs))
6893 (org-list-set-item-visibility e struct 'folded))
6894 (goto-char (if (< end eos) end eos)))))))
6895 (org-unlogged-message "CHILDREN")
6896 (save-excursion
6897 (goto-char eos)
6898 (outline-next-heading)
6899 (when (outline-invisible-p) (org-flag-heading nil)))
6900 (setq org-cycle-subtree-status 'children)
6901 (unless (org-before-first-heading-p)
6902 (run-hook-with-args 'org-cycle-hook 'children)))
6903 ((or children-skipped
6904 (and (eq last-command this-command)
6905 (eq org-cycle-subtree-status 'children)))
6906 ;; We just showed the children, or no children are there,
6907 ;; now show everything.
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6910 (outline-flag-region eoh eos nil)
6911 (org-unlogged-message
6912 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6913 (setq org-cycle-subtree-status 'subtree)
6914 (unless (org-before-first-heading-p)
6915 (run-hook-with-args 'org-cycle-hook 'subtree)))
6917 ;; Default action: hide the subtree.
6918 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6919 (outline-flag-region eoh eos t)
6920 (org-unlogged-message "FOLDED")
6921 (setq org-cycle-subtree-status 'folded)
6922 (unless (org-before-first-heading-p)
6923 (run-hook-with-args 'org-cycle-hook 'folded))))))
6925 ;;;###autoload
6926 (defun org-global-cycle (&optional arg)
6927 "Cycle the global visibility. For details see `org-cycle'.
6928 With \\[universal-argument] prefix arg, switch to startup visibility.
6929 With a numeric prefix, show all headlines up to that level."
6930 (interactive "P")
6931 (let ((org-cycle-include-plain-lists
6932 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6933 (cond
6934 ((integerp arg)
6935 (outline-show-all)
6936 (outline-hide-sublevels arg)
6937 (setq org-cycle-global-status 'contents))
6938 ((equal arg '(4))
6939 (org-set-startup-visibility)
6940 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6942 (org-cycle '(4))))))
6944 (defun org-set-startup-visibility ()
6945 "Set the visibility required by startup options and properties."
6946 (cond
6947 ((eq org-startup-folded t)
6948 (org-overview))
6949 ((eq org-startup-folded 'content)
6950 (org-content))
6951 ((or (eq org-startup-folded 'showeverything)
6952 (eq org-startup-folded nil))
6953 (outline-show-all)))
6954 (unless (eq org-startup-folded 'showeverything)
6955 (when org-hide-block-startup (org-hide-block-all))
6956 (org-set-visibility-according-to-property 'no-cleanup)
6957 (org-cycle-hide-archived-subtrees 'all)
6958 (org-cycle-hide-drawers 'all)
6959 (org-cycle-show-empty-lines t)))
6961 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6962 "Switch subtree visibilities according to :VISIBILITY: property."
6963 (interactive)
6964 (org-with-wide-buffer
6965 (goto-char (point-min))
6966 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6967 (if (not (org-at-property-p)) (outline-next-heading)
6968 (let ((state (match-string 3)))
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (outline-hide-subtree)
6972 (org-reveal)
6973 (cond
6974 ((equal state "folded")
6975 (outline-hide-subtree))
6976 ((equal state "children")
6977 (org-show-hidden-entry)
6978 (org-show-children))
6979 ((equal state "content")
6980 (save-excursion
6981 (save-restriction
6982 (org-narrow-to-subtree)
6983 (org-content))))
6984 ((member state '("all" "showall"))
6985 (outline-show-subtree)))))))
6986 (unless no-cleanup
6987 (org-cycle-hide-archived-subtrees 'all)
6988 (org-cycle-hide-drawers 'all)
6989 (org-cycle-show-empty-lines 'all))))
6991 ;; This function uses outline-regexp instead of the more fundamental
6992 ;; org-outline-regexp so that org-cycle-global works outside of Org
6993 ;; buffers, where outline-regexp is needed.
6994 (defun org-overview ()
6995 "Switch to overview mode, showing only top-level headlines.
6996 This shows all headlines with a level equal or greater than the level
6997 of the first headline in the buffer. This is important, because if the
6998 first headline is not level one, then (hide-sublevels 1) gives confusing
6999 results."
7000 (interactive)
7001 (save-excursion
7002 (let ((level
7003 (save-excursion
7004 (goto-char (point-min))
7005 (when (re-search-forward (concat "^" outline-regexp) nil t)
7006 (goto-char (match-beginning 0))
7007 (funcall outline-level)))))
7008 (and level (outline-hide-sublevels level)))))
7010 (defun org-content (&optional arg)
7011 "Show all headlines in the buffer, like a table of contents.
7012 With numerical argument N, show content up to level N."
7013 (interactive "P")
7014 (org-overview)
7015 (save-excursion
7016 ;; Visit all headings and show their offspring
7017 (and (integerp arg) (org-overview))
7018 (goto-char (point-max))
7019 (catch 'exit
7020 (while (and (progn (condition-case nil
7021 (outline-previous-visible-heading 1)
7022 (error (goto-char (point-min))))
7024 (looking-at org-outline-regexp))
7025 (if (integerp arg)
7026 (org-show-children (1- arg))
7027 (outline-show-branches))
7028 (when (bobp) (throw 'exit nil))))))
7030 (defun org-optimize-window-after-visibility-change (state)
7031 "Adjust the window after a change in outline visibility.
7032 This function is the default value of the hook `org-cycle-hook'."
7033 (when (get-buffer-window (current-buffer))
7034 (cond
7035 ((eq state 'content) nil)
7036 ((eq state 'all) nil)
7037 ((eq state 'folded) nil)
7038 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7039 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7041 (defun org-remove-empty-overlays-at (pos)
7042 "Remove outline overlays that do not contain non-white stuff."
7043 (dolist (o (overlays-at pos))
7044 (and (eq 'outline (overlay-get o 'invisible))
7045 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7046 (overlay-end o))))
7047 (delete-overlay o))))
7049 (defun org-clean-visibility-after-subtree-move ()
7050 "Fix visibility issues after moving a subtree."
7051 ;; First, find a reasonable region to look at:
7052 ;; Start two siblings above, end three below
7053 (let* ((beg (save-excursion
7054 (and (org-get-last-sibling)
7055 (org-get-last-sibling))
7056 (point)))
7057 (end (save-excursion
7058 (and (org-get-next-sibling)
7059 (org-get-next-sibling)
7060 (org-get-next-sibling))
7061 (if (org-at-heading-p)
7062 (point-at-eol)
7063 (point))))
7064 (level (looking-at "\\*+"))
7065 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7066 (save-excursion
7067 (save-restriction
7068 (narrow-to-region beg end)
7069 (when re
7070 ;; Properly fold already folded siblings
7071 (goto-char (point-min))
7072 (while (re-search-forward re nil t)
7073 (when (and (not (outline-invisible-p))
7074 (save-excursion
7075 (goto-char (point-at-eol)) (outline-invisible-p)))
7076 (outline-hide-entry))))
7077 (org-cycle-show-empty-lines 'overview)
7078 (org-cycle-hide-drawers 'overview)))))
7080 (defun org-cycle-show-empty-lines (state)
7081 "Show empty lines above all visible headlines.
7082 The region to be covered depends on STATE when called through
7083 `org-cycle-hook'. Lisp program can use t for STATE to get the
7084 entire buffer covered. Note that an empty line is only shown if there
7085 are at least `org-cycle-separator-lines' empty lines before the headline."
7086 (when (/= org-cycle-separator-lines 0)
7087 (save-excursion
7088 (let* ((n (abs org-cycle-separator-lines))
7089 (re (cond
7090 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7091 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7092 (t (let ((ns (number-to-string (- n 2))))
7093 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7094 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7095 beg end)
7096 (cond
7097 ((memq state '(overview contents t))
7098 (setq beg (point-min) end (point-max)))
7099 ((memq state '(children folded))
7100 (setq beg (point)
7101 end (progn (org-end-of-subtree t t)
7102 (line-beginning-position 2)))))
7103 (when beg
7104 (goto-char beg)
7105 (while (re-search-forward re end t)
7106 (unless (get-char-property (match-end 1) 'invisible)
7107 (let ((e (match-end 1))
7108 (b (if (>= org-cycle-separator-lines 0)
7109 (match-beginning 1)
7110 (save-excursion
7111 (goto-char (match-beginning 0))
7112 (skip-chars-backward " \t\n")
7113 (line-end-position)))))
7114 (outline-flag-region b e nil))))))))
7115 ;; Never hide empty lines at the end of the file.
7116 (save-excursion
7117 (goto-char (point-max))
7118 (outline-previous-heading)
7119 (outline-end-of-heading)
7120 (when (and (looking-at "[ \t\n]+")
7121 (= (match-end 0) (point-max)))
7122 (outline-flag-region (point) (match-end 0) nil))))
7124 (defun org-show-empty-lines-in-parent ()
7125 "Move to the parent and re-show empty lines before visible headlines."
7126 (save-excursion
7127 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7128 (org-cycle-show-empty-lines context))))
7130 (defun org-files-list ()
7131 "Return `org-agenda-files' list, plus all open org-mode files.
7132 This is useful for operations that need to scan all of a user's
7133 open and agenda-wise Org files."
7134 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7135 (dolist (buf (buffer-list))
7136 (with-current-buffer buf
7137 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7138 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7139 files))
7141 (defsubst org-entry-beginning-position ()
7142 "Return the beginning position of the current entry."
7143 (save-excursion (org-back-to-heading t) (point)))
7145 (defsubst org-entry-end-position ()
7146 "Return the end position of the current entry."
7147 (save-excursion (outline-next-heading) (point)))
7149 (defun org-cycle-hide-drawers (state &optional exceptions)
7150 "Re-hide all drawers after a visibility state change.
7151 When non-nil, optional argument EXCEPTIONS is a list of strings
7152 specifying which drawers should not be hidden."
7153 (when (and (derived-mode-p 'org-mode)
7154 (not (memq state '(overview folded contents))))
7155 (save-excursion
7156 (let* ((globalp (memq state '(contents all)))
7157 (beg (if globalp (point-min) (point)))
7158 (end (if globalp (point-max)
7159 (if (eq state 'children)
7160 (save-excursion (outline-next-heading) (point))
7161 (org-end-of-subtree t)))))
7162 (goto-char beg)
7163 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7164 (unless (member-ignore-case (match-string 1) exceptions)
7165 (let ((drawer (org-element-at-point)))
7166 (when (memq (org-element-type drawer) '(drawer property-drawer))
7167 (org-flag-drawer t drawer)
7168 ;; Make sure to skip drawer entirely or we might flag
7169 ;; it another time when matching its ending line with
7170 ;; `org-drawer-regexp'.
7171 (goto-char (org-element-property :end drawer))))))))))
7173 (defun org-flag-drawer (flag &optional element)
7174 "When FLAG is non-nil, hide the drawer we are at.
7175 Otherwise make it visible. When optional argument ELEMENT is
7176 a parsed drawer, as returned by `org-element-at-point', hide or
7177 show that drawer instead."
7178 (when (save-excursion
7179 (beginning-of-line)
7180 (org-looking-at-p org-drawer-regexp))
7181 (let ((drawer (or element (org-element-at-point))))
7182 (when (memq (org-element-type drawer) '(drawer property-drawer))
7183 (let ((post (org-element-property :post-affiliated drawer)))
7184 (save-excursion
7185 (outline-flag-region
7186 (progn (goto-char post) (line-end-position))
7187 (progn (goto-char (org-element-property :end drawer))
7188 (skip-chars-backward " \r\t\n")
7189 (line-end-position))
7190 flag))
7191 ;; When the drawer is hidden away, make sure point lies in
7192 ;; a visible part of the buffer.
7193 (when (and flag (> (line-beginning-position) post))
7194 (goto-char post)))))))
7196 (defun org-subtree-end-visible-p ()
7197 "Is the end of the current subtree visible?"
7198 (pos-visible-in-window-p
7199 (save-excursion (org-end-of-subtree t) (point))))
7201 (defun org-first-headline-recenter ()
7202 "Move cursor to the first headline and recenter the headline."
7203 (goto-char (point-min))
7204 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7205 (set-window-start (selected-window) (point-at-bol))))
7207 ;;; Saving and restoring visibility
7209 (defun org-outline-overlay-data (&optional use-markers)
7210 "Return a list of the locations of all outline overlays.
7211 These are overlays with the `invisible' property value `outline'.
7212 The return value is a list of cons cells, with start and stop
7213 positions for each overlay.
7214 If USE-MARKERS is set, return the positions as markers."
7215 (let (beg end)
7216 (save-excursion
7217 (save-restriction
7218 (widen)
7219 (delq nil
7220 (mapcar (lambda (o)
7221 (when (eq (overlay-get o 'invisible) 'outline)
7222 (setq beg (overlay-start o)
7223 end (overlay-end o))
7224 (and beg end (> end beg)
7225 (if use-markers
7226 (cons (copy-marker beg)
7227 (copy-marker end t))
7228 (cons beg end)))))
7229 (overlays-in (point-min) (point-max))))))))
7231 (defun org-set-outline-overlay-data (data)
7232 "Create visibility overlays for all positions in DATA.
7233 DATA should have been made by `org-outline-overlay-data'."
7234 (org-with-wide-buffer
7235 (outline-show-all)
7236 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7238 ;;; Folding of blocks
7240 (defvar-local org-hide-block-overlays nil
7241 "Overlays hiding blocks.")
7243 (defun org-block-map (function &optional start end)
7244 "Call FUNCTION at the head of all source blocks in the current buffer.
7245 Optional arguments START and END can be used to limit the range."
7246 (let ((start (or start (point-min)))
7247 (end (or end (point-max))))
7248 (save-excursion
7249 (goto-char start)
7250 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7251 (save-excursion
7252 (save-match-data
7253 (goto-char (match-beginning 0))
7254 (funcall function)))))))
7256 (defun org-hide-block-toggle-all ()
7257 "Toggle the visibility of all blocks in the current buffer."
7258 (org-block-map 'org-hide-block-toggle))
7260 (defun org-hide-block-all ()
7261 "Fold all blocks in the current buffer."
7262 (interactive)
7263 (org-show-block-all)
7264 (org-block-map 'org-hide-block-toggle-maybe))
7266 (defun org-show-block-all ()
7267 "Unfold all blocks in the current buffer."
7268 (interactive)
7269 (mapc #'delete-overlay org-hide-block-overlays)
7270 (setq org-hide-block-overlays nil))
7272 (defun org-hide-block-toggle-maybe ()
7273 "Toggle visibility of block at point.
7274 Unlike to `org-hide-block-toggle', this function does not throw
7275 an error. Return a non-nil value when toggling is successful."
7276 (interactive)
7277 (ignore-errors (org-hide-block-toggle)))
7279 (defun org-hide-block-toggle (&optional force)
7280 "Toggle the visibility of the current block.
7281 When optional argument FORCE is `off', make block visible. If it
7282 is non-nil, hide it unconditionally. Throw an error when not at
7283 a block. Return a non-nil value when toggling is successful."
7284 (interactive)
7285 (let ((element (org-element-at-point)))
7286 (unless (memq (org-element-type element)
7287 '(center-block comment-block dynamic-block example-block
7288 export-block quote-block special-block
7289 src-block verse-block))
7290 (user-error "Not at a block"))
7291 (let* ((start (save-excursion
7292 (goto-char (org-element-property :post-affiliated element))
7293 (line-end-position)))
7294 (end (save-excursion
7295 (goto-char (org-element-property :end element))
7296 (skip-chars-backward " \r\t\n")
7297 (line-end-position)))
7298 (overlays (overlays-at start)))
7299 (cond
7300 ;; Do nothing when not before or at the block opening line or
7301 ;; at the block closing line.
7302 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7303 ((and (not (eq force 'off))
7304 (not (memq t (mapcar
7305 (lambda (o)
7306 (eq (overlay-get o 'invisible) 'org-hide-block))
7307 overlays))))
7308 (let ((ov (make-overlay start end)))
7309 (overlay-put ov 'invisible 'org-hide-block)
7310 ;; Make the block accessible to `isearch'.
7311 (overlay-put
7312 ov 'isearch-open-invisible
7313 (lambda (ov)
7314 (when (memq ov org-hide-block-overlays)
7315 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7316 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7317 (delete-overlay ov))))
7318 (push ov org-hide-block-overlays)
7319 ;; When the block is hidden away, make sure point is left in
7320 ;; a visible part of the buffer.
7321 (when (> (line-beginning-position) start)
7322 (goto-char start)
7323 (beginning-of-line))
7324 ;; Signal successful toggling.
7326 ((or (not force) (eq force 'off))
7327 (dolist (ov overlays t)
7328 (when (memq ov org-hide-block-overlays)
7329 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7330 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7331 (delete-overlay ov))))))))
7333 ;; org-tab-after-check-for-cycling-hook
7334 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7335 ;; Remove overlays when changing major mode
7336 (add-hook 'org-mode-hook
7337 (lambda () (org-add-hook 'change-major-mode-hook
7338 'org-show-block-all 'append 'local)))
7340 ;;; Org-goto
7342 (defvar org-goto-window-configuration nil)
7343 (defvar org-goto-marker nil)
7344 (defvar org-goto-map)
7345 (defun org-goto-map ()
7346 "Set the keymap `org-goto'."
7347 (setq org-goto-map
7348 (let ((map (make-sparse-keymap)))
7349 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7350 mouse-drag-region universal-argument org-occur)))
7351 (dolist (cmd cmds)
7352 (substitute-key-definition cmd cmd map global-map)))
7353 (suppress-keymap map)
7354 (org-defkey map "\C-m" 'org-goto-ret)
7355 (org-defkey map [(return)] 'org-goto-ret)
7356 (org-defkey map [(left)] 'org-goto-left)
7357 (org-defkey map [(right)] 'org-goto-right)
7358 (org-defkey map [(control ?g)] 'org-goto-quit)
7359 (org-defkey map "\C-i" 'org-cycle)
7360 (org-defkey map [(tab)] 'org-cycle)
7361 (org-defkey map [(down)] 'outline-next-visible-heading)
7362 (org-defkey map [(up)] 'outline-previous-visible-heading)
7363 (if org-goto-auto-isearch
7364 (if (fboundp 'define-key-after)
7365 (define-key-after map [t] 'org-goto-local-auto-isearch)
7366 nil)
7367 (org-defkey map "q" 'org-goto-quit)
7368 (org-defkey map "n" 'outline-next-visible-heading)
7369 (org-defkey map "p" 'outline-previous-visible-heading)
7370 (org-defkey map "f" 'outline-forward-same-level)
7371 (org-defkey map "b" 'outline-backward-same-level)
7372 (org-defkey map "u" 'outline-up-heading))
7373 (org-defkey map "/" 'org-occur)
7374 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7375 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7376 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7377 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7378 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7379 map)))
7381 (defconst org-goto-help
7382 "Browse buffer copy, to find location or copy text.%s
7383 RET=jump to location C-g=quit and return to previous location
7384 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7386 (defvar org-goto-start-pos) ; dynamically scoped parameter
7388 (defun org-goto (&optional alternative-interface)
7389 "Look up a different location in the current file, keeping current visibility.
7391 When you want look-up or go to a different location in a
7392 document, the fastest way is often to fold the entire buffer and
7393 then dive into the tree. This method has the disadvantage, that
7394 the previous location will be folded, which may not be what you
7395 want.
7397 This command works around this by showing a copy of the current
7398 buffer in an indirect buffer, in overview mode. You can dive
7399 into the tree in that copy, use org-occur and incremental search
7400 to find a location. When pressing RET or `Q', the command
7401 returns to the original buffer in which the visibility is still
7402 unchanged. After RET it will also jump to the location selected
7403 in the indirect buffer and expose the headline hierarchy above.
7405 With a prefix argument, use the alternative interface: e.g., if
7406 `org-goto-interface' is `outline' use `outline-path-completion'."
7407 (interactive "P")
7408 (org-goto-map)
7409 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7410 (org-refile-use-outline-path t)
7411 (org-refile-target-verify-function nil)
7412 (interface
7413 (if (not alternative-interface)
7414 org-goto-interface
7415 (if (eq org-goto-interface 'outline)
7416 'outline-path-completion
7417 'outline)))
7418 (org-goto-start-pos (point))
7419 (selected-point
7420 (if (eq interface 'outline)
7421 (car (org-get-location (current-buffer) org-goto-help))
7422 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7423 (org-refile-check-position pa)
7424 (nth 3 pa)))))
7425 (if selected-point
7426 (progn
7427 (org-mark-ring-push org-goto-start-pos)
7428 (goto-char selected-point)
7429 (when (or (outline-invisible-p) (org-invisible-p2))
7430 (org-show-context 'org-goto)))
7431 (message "Quit"))))
7433 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7434 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7435 (defvar org-goto-local-auto-isearch-map) ; defined below
7437 (defun org-get-location (_buf help)
7438 "Let the user select a location in current buffer.
7439 This function uses a recursive edit. It returns the selected position
7440 or nil."
7441 (org-no-popups
7442 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7443 (isearch-hide-immediately nil)
7444 (isearch-search-fun-function
7445 (lambda () 'org-goto-local-search-headings))
7446 (org-goto-selected-point org-goto-exit-command))
7447 (save-excursion
7448 (save-window-excursion
7449 (delete-other-windows)
7450 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7451 (org-pop-to-buffer-same-window
7452 (condition-case nil
7453 (make-indirect-buffer (current-buffer) "*org-goto*")
7454 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7455 (with-output-to-temp-buffer "*Org Help*"
7456 (princ (format help (if org-goto-auto-isearch
7457 " Just type for auto-isearch."
7458 " n/p/f/b/u to navigate, q to quit."))))
7459 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7460 (setq buffer-read-only nil)
7461 (let ((org-startup-truncated t)
7462 (org-startup-folded nil)
7463 (org-startup-align-all-tables nil))
7464 (org-mode)
7465 (org-overview))
7466 (setq buffer-read-only t)
7467 (if (and (boundp 'org-goto-start-pos)
7468 (integer-or-marker-p org-goto-start-pos))
7469 (progn (goto-char org-goto-start-pos)
7470 (when (outline-invisible-p)
7471 (org-show-set-visibility 'lineage)))
7472 (goto-char (point-min)))
7473 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7474 (message "Select location and press RET")
7475 (use-local-map org-goto-map)
7476 (recursive-edit)))
7477 (kill-buffer "*org-goto*")
7478 (cons org-goto-selected-point org-goto-exit-command))))
7480 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7481 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7482 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7483 (if (fboundp 'isearch-other-control-char)
7484 (progn
7485 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7486 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7487 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7488 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7489 (define-key org-goto-local-auto-isearch-map [return] nil))
7491 (defun org-goto-local-search-headings (string bound noerror)
7492 "Search and make sure that any matches are in headlines."
7493 (catch 'return
7494 (while (if isearch-forward
7495 (search-forward string bound noerror)
7496 (search-backward string bound noerror))
7497 (when (save-match-data
7498 (and (save-excursion
7499 (beginning-of-line)
7500 (looking-at org-complex-heading-regexp))
7501 (or (not (match-beginning 5))
7502 (< (point) (match-beginning 5)))))
7503 (throw 'return (point))))))
7505 (defun org-goto-local-auto-isearch ()
7506 "Start isearch."
7507 (interactive)
7508 (goto-char (point-min))
7509 (let ((keys (this-command-keys)))
7510 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7511 (isearch-mode t)
7512 (isearch-process-search-char (string-to-char keys)))))
7514 (defun org-goto-ret (&optional _arg)
7515 "Finish `org-goto' by going to the new location."
7516 (interactive "P")
7517 (setq org-goto-selected-point (point))
7518 (setq org-goto-exit-command 'return)
7519 (throw 'exit nil))
7521 (defun org-goto-left ()
7522 "Finish `org-goto' by going to the new location."
7523 (interactive)
7524 (if (org-at-heading-p)
7525 (progn
7526 (beginning-of-line 1)
7527 (setq org-goto-selected-point (point)
7528 org-goto-exit-command 'left)
7529 (throw 'exit nil))
7530 (user-error "Not on a heading")))
7532 (defun org-goto-right ()
7533 "Finish `org-goto' by going to the new location."
7534 (interactive)
7535 (if (org-at-heading-p)
7536 (progn
7537 (setq org-goto-selected-point (point)
7538 org-goto-exit-command 'right)
7539 (throw 'exit nil))
7540 (user-error "Not on a heading")))
7542 (defun org-goto-quit ()
7543 "Finish `org-goto' without cursor motion."
7544 (interactive)
7545 (setq org-goto-selected-point nil)
7546 (setq org-goto-exit-command 'quit)
7547 (throw 'exit nil))
7549 ;;; Indirect buffer display of subtrees
7551 (defvar org-indirect-dedicated-frame nil
7552 "This is the frame being used for indirect tree display.")
7553 (defvar org-last-indirect-buffer nil)
7555 (defun org-tree-to-indirect-buffer (&optional arg)
7556 "Create indirect buffer and narrow it to current subtree.
7557 With a numerical prefix ARG, go up to this level and then take that tree.
7558 If ARG is negative, go up that many levels.
7560 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7561 indirect buffer previously made with this command, to avoid proliferation of
7562 indirect buffers. However, when you call the command with a \
7563 \\[universal-argument] prefix, or
7564 when `org-indirect-buffer-display' is `new-frame', the last buffer
7565 is kept so that you can work with several indirect buffers at the same time.
7566 If `org-indirect-buffer-display' is `dedicated-frame', the \
7567 \\[universal-argument] prefix also
7568 requests that a new frame be made for the new buffer, so that the dedicated
7569 frame is not changed."
7570 (interactive "P")
7571 (let ((cbuf (current-buffer))
7572 (cwin (selected-window))
7573 (pos (point))
7574 beg end level heading ibuf)
7575 (save-excursion
7576 (org-back-to-heading t)
7577 (when (numberp arg)
7578 (setq level (org-outline-level))
7579 (when (< arg 0) (setq arg (+ level arg)))
7580 (while (> (setq level (org-outline-level)) arg)
7581 (org-up-heading-safe)))
7582 (setq beg (point)
7583 heading (org-get-heading 'no-tags))
7584 (org-end-of-subtree t t)
7585 (when (org-at-heading-p) (backward-char 1))
7586 (setq end (point)))
7587 (when (and (buffer-live-p org-last-indirect-buffer)
7588 (not (eq org-indirect-buffer-display 'new-frame))
7589 (not arg))
7590 (kill-buffer org-last-indirect-buffer))
7591 (setq ibuf (org-get-indirect-buffer cbuf heading)
7592 org-last-indirect-buffer ibuf)
7593 (cond
7594 ((or (eq org-indirect-buffer-display 'new-frame)
7595 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7596 (select-frame (make-frame))
7597 (delete-other-windows)
7598 (org-pop-to-buffer-same-window ibuf)
7599 (org-set-frame-title heading))
7600 ((eq org-indirect-buffer-display 'dedicated-frame)
7601 (raise-frame
7602 (select-frame (or (and org-indirect-dedicated-frame
7603 (frame-live-p org-indirect-dedicated-frame)
7604 org-indirect-dedicated-frame)
7605 (setq org-indirect-dedicated-frame (make-frame)))))
7606 (delete-other-windows)
7607 (org-pop-to-buffer-same-window ibuf)
7608 (org-set-frame-title (concat "Indirect: " heading)))
7609 ((eq org-indirect-buffer-display 'current-window)
7610 (org-pop-to-buffer-same-window ibuf))
7611 ((eq org-indirect-buffer-display 'other-window)
7612 (pop-to-buffer ibuf))
7613 (t (error "Invalid value")))
7614 (when (featurep 'xemacs)
7615 (save-excursion (org-mode) (turn-on-font-lock)))
7616 (narrow-to-region beg end)
7617 (outline-show-all)
7618 (goto-char pos)
7619 (run-hook-with-args 'org-cycle-hook 'all)
7620 (and (window-live-p cwin) (select-window cwin))))
7622 (defun org-get-indirect-buffer (&optional buffer heading)
7623 (setq buffer (or buffer (current-buffer)))
7624 (let ((n 1) (base (buffer-name buffer)) bname)
7625 (while (buffer-live-p
7626 (get-buffer
7627 (setq bname
7628 (concat base "-"
7629 (if heading (concat heading "-" (number-to-string n))
7630 (number-to-string n))))))
7631 (setq n (1+ n)))
7632 (condition-case nil
7633 (make-indirect-buffer buffer bname 'clone)
7634 (error (make-indirect-buffer buffer bname)))))
7636 (defun org-set-frame-title (title)
7637 "Set the title of the current frame to the string TITLE."
7638 ;; FIXME: how to name a single frame in XEmacs???
7639 (unless (featurep 'xemacs)
7640 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7642 ;;;; Structure editing
7644 ;;; Inserting headlines
7646 (defun org--line-empty-p (n)
7647 "Is the Nth next line empty?
7649 Counts the current line as N = 1 and the previous line as N = 0;
7650 see `beginning-of-line'."
7651 (save-excursion
7652 (and (not (bobp))
7653 (or (beginning-of-line n) t)
7654 (save-match-data
7655 (looking-at "[ \t]*$")))))
7657 (defun org-previous-line-empty-p ()
7658 "Is the previous line a blank line?
7659 When NEXT is non-nil, check the next line instead."
7660 (org--line-empty-p 0))
7662 (defun org-next-line-empty-p ()
7663 "Is the previous line a blank line?
7664 When NEXT is non-nil, check the next line instead."
7665 (org--line-empty-p 2))
7667 (defun org-insert-heading (&optional arg invisible-ok top)
7668 "Insert a new heading or an item with the same depth at point.
7670 If point is at the beginning of a heading or a list item, insert
7671 a new heading or a new item above the current one. If point is
7672 at the beginning of a normal line, turn the line into a heading.
7674 If point is in the middle of a headline or a list item, split the
7675 headline or the item and create a new headline/item with the text
7676 in the current line after point \(see `org-M-RET-may-split-line'
7677 on how to modify this behavior).
7679 With one universal prefix argument, set the user option
7680 `org-insert-heading-respect-content' to t for the duration of
7681 the command. This modifies the behavior described above in this
7682 ways: on list items and at the beginning of normal lines, force
7683 the insertion of a heading after the current subtree.
7685 With two universal prefix arguments, insert the heading at the
7686 end of the grandparent subtree. For example, if point is within
7687 a 2nd-level heading, then it will insert a 2nd-level heading at
7688 the end of the 1st-level parent heading.
7690 If point is at the beginning of a headline, insert a sibling
7691 before the current headline. If point is not at the beginning,
7692 split the line and create a new headline with the text in the
7693 current line after point \(see `org-M-RET-may-split-line' on how
7694 to modify this behavior).
7696 If point is at the beginning of a normal line, turn this line
7697 into a heading.
7699 When INVISIBLE-OK is set, stop at invisible headlines when going
7700 back. This is important for non-interactive uses of the
7701 command.
7703 When optional argument TOP is non-nil, insert a level 1 heading,
7704 unconditionally."
7705 (interactive "P")
7706 (when (org-called-interactively-p 'any) (org-reveal))
7707 (let ((itemp (and (not top) (org-in-item-p)))
7708 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7709 (respect-content (or org-insert-heading-respect-content
7710 (equal arg '(4))))
7711 (initial-content ""))
7713 (cond
7715 ((or (= (buffer-size) 0)
7716 (and (not (save-excursion
7717 (and (ignore-errors (org-back-to-heading invisible-ok))
7718 (org-at-heading-p))))
7719 (or arg (not itemp))))
7720 ;; At beginning of buffer or so high up that only a heading
7721 ;; makes sense.
7722 (cond ((and (bolp) (not respect-content)) (insert "* "))
7723 ((not respect-content)
7724 (unless may-split (end-of-line))
7725 (insert "\n* "))
7726 ((re-search-forward org-outline-regexp-bol nil t)
7727 (beginning-of-line)
7728 (insert "* \n")
7729 (backward-char))
7730 (t (goto-char (point-max))
7731 (insert "\n* ")))
7732 (run-hooks 'org-insert-heading-hook))
7734 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7737 ;; Maybe move at the end of the subtree
7738 (when (equal arg '(16))
7739 (org-up-heading-safe)
7740 (org-end-of-subtree t))
7741 ;; Insert a heading
7742 (save-restriction
7743 (widen)
7744 (let* ((level nil)
7745 (on-heading (org-at-heading-p))
7746 (empty-line-p (if on-heading
7747 (org-previous-line-empty-p)
7748 ;; We will decide later
7749 nil))
7750 ;; Get a level string to fall back on.
7751 (fix-level
7752 (if (org-before-first-heading-p) "*"
7753 (save-excursion
7754 (org-back-to-heading t)
7755 (when (org-previous-line-empty-p) (setq empty-line-p t))
7756 (looking-at org-outline-regexp)
7757 (make-string (1- (length (match-string 0))) ?*))))
7758 (stars
7759 (save-excursion
7760 (condition-case nil
7761 (if top "* "
7762 (org-back-to-heading invisible-ok)
7763 (when (and (not on-heading)
7764 (featurep 'org-inlinetask)
7765 (integerp org-inlinetask-min-level)
7766 (>= (length (match-string 0))
7767 org-inlinetask-min-level))
7768 ;; Find a heading level before the inline
7769 ;; task.
7770 (while (and (setq level (org-up-heading-safe))
7771 (>= level org-inlinetask-min-level)))
7772 (if (org-at-heading-p)
7773 (org-back-to-heading invisible-ok)
7774 (error "This should not happen")))
7775 (unless (and (save-excursion
7776 (save-match-data
7777 (org-backward-heading-same-level
7778 1 invisible-ok))
7779 (= (point) (match-beginning 0)))
7780 (not (org-next-line-empty-p)))
7781 (setq empty-line-p (or empty-line-p
7782 (org-previous-line-empty-p))))
7783 (match-string 0))
7784 (error (or fix-level "* ")))))
7785 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7786 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7788 ;; If we insert after content, move there and clean up
7789 ;; whitespace.
7790 (when (and respect-content
7791 (not (org-looking-at-p org-outline-regexp-bol)))
7792 (if (not (org-before-first-heading-p))
7793 (org-end-of-subtree nil t)
7794 (re-search-forward org-outline-regexp-bol)
7795 (beginning-of-line 0))
7796 (skip-chars-backward " \r\t\n")
7797 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7798 (looking-at "[ \t]+") (replace-match ""))
7799 (unless (eobp) (forward-char 1))
7800 (when (looking-at "^\\*")
7801 (unless (bobp) (backward-char 1))
7802 (insert "\n")))
7804 ;; If we are splitting, grab the text that should be moved
7805 ;; to the new headline.
7806 (when may-split
7807 (if (org-at-heading-p)
7808 ;; This is a heading: split intelligently (keeping
7809 ;; tags).
7810 (let ((pos (point)))
7811 (beginning-of-line)
7812 (unless (looking-at org-complex-heading-regexp)
7813 (error "This should not happen"))
7814 (when (and (match-beginning 4)
7815 (> pos (match-beginning 4))
7816 (< pos (match-end 4)))
7817 (setq initial-content (buffer-substring pos (match-end 4)))
7818 (goto-char pos)
7819 (delete-region (point) (match-end 4))
7820 (if (looking-at "[ \t]*$")
7821 (replace-match "")
7822 (insert (make-string (length initial-content) ?\s)))
7823 (setq initial-content (org-trim initial-content)))
7824 (goto-char pos))
7825 ;; A normal line.
7826 (setq initial-content
7827 (org-trim
7828 (delete-and-extract-region (point) (line-end-position))))))
7830 ;; If we are at the beginning of the line, insert before it.
7831 ;; Otherwise, after it.
7832 (cond
7833 ((and (bolp) (looking-at "[ \t]*$")))
7834 ((bolp) (save-excursion (insert "\n")))
7835 (t (end-of-line)
7836 (insert "\n")))
7838 ;; Insert the new heading
7839 (insert stars)
7840 (just-one-space)
7841 (insert initial-content)
7842 (unless (and blank (org-previous-line-empty-p))
7843 (org-N-empty-lines-before-current (if blank 1 0)))
7844 ;; Adjust visibility, which may be messed up if we removed
7845 ;; blank lines while previous entry was hidden.
7846 (let ((bol (line-beginning-position)))
7847 (dolist (o (overlays-at (1- bol)))
7848 (when (and (eq (overlay-get o 'invisible) 'outline)
7849 (eq (overlay-end o) bol))
7850 (move-overlay o (overlay-start o) (1- bol)))))
7851 (run-hooks 'org-insert-heading-hook)))))))
7853 (defun org-N-empty-lines-before-current (N)
7854 "Make the number of empty lines before current exactly N.
7855 So this will delete or add empty lines."
7856 (save-excursion
7857 (beginning-of-line)
7858 (let ((p (point)))
7859 (skip-chars-backward " \r\t\n")
7860 (unless (bolp) (forward-line))
7861 (delete-region (point) p))
7862 (when (> N 0) (insert (make-string N ?\n)))))
7864 (defun org-get-heading (&optional no-tags no-todo)
7865 "Return the heading of the current entry, without the stars.
7866 When NO-TAGS is non-nil, don't include tags.
7867 When NO-TODO is non-nil, don't include TODO keywords."
7868 (save-excursion
7869 (org-back-to-heading t)
7870 (cond
7871 ((and no-tags no-todo)
7872 (looking-at org-complex-heading-regexp)
7873 (match-string 4))
7874 (no-tags
7875 (looking-at (concat org-outline-regexp
7876 "\\(.*?\\)"
7877 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7878 (match-string 1))
7879 (no-todo
7880 (looking-at org-todo-line-regexp)
7881 (match-string 3))
7882 (t (looking-at org-heading-regexp)
7883 (match-string 2)))))
7885 (defvar orgstruct-mode) ; defined below
7887 (defun org-heading-components ()
7888 "Return the components of the current heading.
7889 This is a list with the following elements:
7890 - the level as an integer
7891 - the reduced level, different if `org-odd-levels-only' is set.
7892 - the TODO keyword, or nil
7893 - the priority character, like ?A, or nil if no priority is given
7894 - the headline text itself, or the tags string if no headline text
7895 - the tags string, or nil."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (when (let (case-fold-search)
7899 (looking-at
7900 (if orgstruct-mode
7901 org-heading-regexp
7902 org-complex-heading-regexp)))
7903 (if orgstruct-mode
7904 (list (length (match-string 1))
7905 (org-reduced-level (length (match-string 1)))
7908 (match-string 2)
7909 nil)
7910 (list (length (match-string 1))
7911 (org-reduced-level (length (match-string 1)))
7912 (org-match-string-no-properties 2)
7913 (and (match-end 3) (aref (match-string 3) 2))
7914 (org-match-string-no-properties 4)
7915 (org-match-string-no-properties 5))))))
7917 (defun org-get-entry ()
7918 "Get the entry text, after heading, entire subtree."
7919 (save-excursion
7920 (org-back-to-heading t)
7921 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7923 (defun org-insert-heading-after-current ()
7924 "Insert a new heading with same level as current, after current subtree."
7925 (interactive)
7926 (org-back-to-heading)
7927 (org-insert-heading)
7928 (org-move-subtree-down)
7929 (end-of-line 1))
7931 (defun org-insert-heading-respect-content (&optional invisible-ok)
7932 "Insert heading with `org-insert-heading-respect-content' set to t."
7933 (interactive)
7934 (org-insert-heading '(4) invisible-ok))
7936 (defun org-insert-todo-heading-respect-content (&optional force-state)
7937 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7938 (interactive)
7939 (org-insert-todo-heading force-state '(4)))
7941 (defun org-insert-todo-heading (arg &optional force-heading)
7942 "Insert a new heading with the same level and TODO state as current heading.
7943 If the heading has no TODO state, or if the state is DONE, use the first
7944 state (TODO by default). Also with one prefix arg, force first state. With
7945 two prefix args, force inserting at the end of the parent subtree."
7946 (interactive "P")
7947 (when (or force-heading (not (org-insert-item 'checkbox)))
7948 (org-insert-heading (or (and (equal arg '(16)) '(16))
7949 force-heading))
7950 (save-excursion
7951 (org-back-to-heading)
7952 (outline-previous-heading)
7953 (looking-at org-todo-line-regexp))
7954 (let*
7955 ((new-mark-x
7956 (if (or (equal arg '(4))
7957 (not (match-beginning 2))
7958 (member (match-string 2) org-done-keywords))
7959 (car org-todo-keywords-1)
7960 (match-string 2)))
7961 (new-mark
7963 (run-hook-with-args-until-success
7964 'org-todo-get-default-hook new-mark-x nil)
7965 new-mark-x)))
7966 (beginning-of-line 1)
7967 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7968 (if org-treat-insert-todo-heading-as-state-change
7969 (org-todo new-mark)
7970 (insert new-mark " "))))
7971 (when org-provide-todo-statistics
7972 (org-update-parent-todo-statistics))))
7974 (defun org-insert-subheading (arg)
7975 "Insert a new subheading and demote it.
7976 Works for outline headings and for plain lists alike."
7977 (interactive "P")
7978 (org-insert-heading arg)
7979 (cond
7980 ((org-at-heading-p) (org-do-demote))
7981 ((org-at-item-p) (org-indent-item))))
7983 (defun org-insert-todo-subheading (arg)
7984 "Insert a new subheading with TODO keyword or checkbox and demote it.
7985 Works for outline headings and for plain lists alike."
7986 (interactive "P")
7987 (org-insert-todo-heading arg)
7988 (cond
7989 ((org-at-heading-p) (org-do-demote))
7990 ((org-at-item-p) (org-indent-item))))
7992 ;;; Promotion and Demotion
7994 (defvar org-after-demote-entry-hook nil
7995 "Hook run after an entry has been demoted.
7996 The cursor will be at the beginning of the entry.
7997 When a subtree is being demoted, the hook will be called for each node.")
7999 (defvar org-after-promote-entry-hook nil
8000 "Hook run after an entry has been promoted.
8001 The cursor will be at the beginning of the entry.
8002 When a subtree is being promoted, the hook will be called for each node.")
8004 (defun org-promote-subtree ()
8005 "Promote the entire subtree.
8006 See also `org-promote'."
8007 (interactive)
8008 (save-excursion
8009 (org-with-limited-levels (org-map-tree 'org-promote)))
8010 (org-fix-position-after-promote))
8012 (defun org-demote-subtree ()
8013 "Demote the entire subtree.
8014 See `org-demote' and `org-promote'."
8015 (interactive)
8016 (save-excursion
8017 (org-with-limited-levels (org-map-tree 'org-demote)))
8018 (org-fix-position-after-promote))
8020 (defun org-do-promote ()
8021 "Promote the current heading higher up the tree.
8022 If the region is active in `transient-mark-mode', promote all
8023 headings in the region."
8024 (interactive)
8025 (save-excursion
8026 (if (org-region-active-p)
8027 (org-map-region 'org-promote (region-beginning) (region-end))
8028 (org-promote)))
8029 (org-fix-position-after-promote))
8031 (defun org-do-demote ()
8032 "Demote the current heading lower down the tree.
8033 If the region is active in `transient-mark-mode', demote all
8034 headings in the region."
8035 (interactive)
8036 (save-excursion
8037 (if (org-region-active-p)
8038 (org-map-region 'org-demote (region-beginning) (region-end))
8039 (org-demote)))
8040 (org-fix-position-after-promote))
8042 (defun org-fix-position-after-promote ()
8043 "Fix cursor position and indentation after demoting/promoting."
8044 (let ((pos (point)))
8045 (when (save-excursion
8046 (beginning-of-line 1)
8047 (looking-at org-todo-line-regexp)
8048 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8049 (cond ((eobp) (insert " "))
8050 ((eolp) (insert " "))
8051 ((equal (char-after) ?\ ) (forward-char 1))))))
8053 (defun org-current-level ()
8054 "Return the level of the current entry, or nil if before the first headline.
8055 The level is the number of stars at the beginning of the
8056 headline. Use `org-reduced-level' to remove the effect of
8057 `org-odd-levels'. Unlike to `org-outline-level', this function
8058 ignores inlinetasks."
8059 (let ((level (org-with-limited-levels (org-outline-level))))
8060 (and (> level 0) level)))
8062 (defun org-get-previous-line-level ()
8063 "Return the outline depth of the last headline before the current line.
8064 Returns 0 for the first headline in the buffer, and nil if before the
8065 first headline."
8066 (and (org-current-level)
8067 (or (and (/= (line-beginning-position) (point-min))
8068 (save-excursion (beginning-of-line 0) (org-current-level)))
8069 0)))
8071 (defun org-reduced-level (l)
8072 "Compute the effective level of a heading.
8073 This takes into account the setting of `org-odd-levels-only'."
8074 (cond
8075 ((zerop l) 0)
8076 (org-odd-levels-only (1+ (floor (/ l 2))))
8077 (t l)))
8079 (defun org-level-increment ()
8080 "Return the number of stars that will be added or removed at a
8081 time to headlines when structure editing, based on the value of
8082 `org-odd-levels-only'."
8083 (if org-odd-levels-only 2 1))
8085 (defun org-get-valid-level (level &optional change)
8086 "Rectify a level change under the influence of `org-odd-levels-only'
8087 LEVEL is a current level, CHANGE is by how much the level should be
8088 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8089 even level numbers will become the next higher odd number."
8090 (if org-odd-levels-only
8091 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8092 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8093 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8094 (max 1 (+ level (or change 0)))))
8095 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8097 (defun org-promote ()
8098 "Promote the current heading higher up the tree."
8099 (org-with-wide-buffer
8100 (org-back-to-heading t)
8101 (let* ((after-change-functions (remq 'flyspell-after-change-function
8102 after-change-functions))
8103 (level (save-match-data (funcall outline-level)))
8104 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8105 (diff (abs (- level (length up-head) -1))))
8106 (cond
8107 ((and (= level 1) org-allow-promoting-top-level-subtree)
8108 (replace-match "# " nil t))
8109 ((= level 1)
8110 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8111 (t (replace-match up-head nil t)))
8112 (unless (= level 1)
8113 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8114 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8115 (run-hooks 'org-after-promote-entry-hook))))
8117 (defun org-demote ()
8118 "Demote the current heading lower down the tree."
8119 (org-with-wide-buffer
8120 (org-back-to-heading t)
8121 (let* ((after-change-functions (remq 'flyspell-after-change-function
8122 after-change-functions))
8123 (level (save-match-data (funcall outline-level)))
8124 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8125 (diff (abs (- level (length down-head) -1))))
8126 (replace-match down-head nil t)
8127 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8128 (when org-adapt-indentation (org-fixup-indentation diff))
8129 (run-hooks 'org-after-demote-entry-hook))))
8131 (defun org-cycle-level ()
8132 "Cycle the level of an empty headline through possible states.
8133 This goes first to child, then to parent, level, then up the hierarchy.
8134 After top level, it switches back to sibling level."
8135 (interactive)
8136 (let ((org-adapt-indentation nil))
8137 (when (org-point-at-end-of-empty-headline)
8138 (setq this-command 'org-cycle-level) ; Only needed for caching
8139 (let ((cur-level (org-current-level))
8140 (prev-level (org-get-previous-line-level)))
8141 (cond
8142 ;; If first headline in file, promote to top-level.
8143 ((= prev-level 0)
8144 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8145 do (org-do-promote)))
8146 ;; If same level as prev, demote one.
8147 ((= prev-level cur-level)
8148 (org-do-demote))
8149 ;; If parent is top-level, promote to top level if not already.
8150 ((= prev-level 1)
8151 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8152 do (org-do-promote)))
8153 ;; If top-level, return to prev-level.
8154 ((= cur-level 1)
8155 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8156 do (org-do-demote)))
8157 ;; If less than prev-level, promote one.
8158 ((< cur-level prev-level)
8159 (org-do-promote))
8160 ;; If deeper than prev-level, promote until higher than
8161 ;; prev-level.
8162 ((> cur-level prev-level)
8163 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8164 do (org-do-promote))))
8165 t))))
8167 (defun org-map-tree (fun)
8168 "Call FUN for every heading underneath the current one."
8169 (org-back-to-heading)
8170 (let ((level (funcall outline-level)))
8171 (save-excursion
8172 (funcall fun)
8173 (while (and (progn
8174 (outline-next-heading)
8175 (> (funcall outline-level) level))
8176 (not (eobp)))
8177 (funcall fun)))))
8179 (defun org-map-region (fun beg end)
8180 "Call FUN for every heading between BEG and END."
8181 (let ((org-ignore-region t))
8182 (save-excursion
8183 (setq end (copy-marker end))
8184 (goto-char beg)
8185 (when (and (re-search-forward org-outline-regexp-bol nil t)
8186 (< (point) end))
8187 (funcall fun))
8188 (while (and (progn
8189 (outline-next-heading)
8190 (< (point) end))
8191 (not (eobp)))
8192 (funcall fun)))))
8194 (defun org-fixup-indentation (diff)
8195 "Change the indentation in the current entry by DIFF.
8197 DIFF is an integer. Indentation is done according to the
8198 following rules:
8200 - Planning information and property drawers are always indented
8201 according to the new level of the headline;
8203 - Footnote definitions and their contents are ignored;
8205 - Inlinetasks' boundaries are not shifted;
8207 - Empty lines are ignored;
8209 - Other lines' indentation are shifted by DIFF columns, unless
8210 it would introduce a structural change in the document, in
8211 which case no shifting is done at all.
8213 Assume point is at a heading or an inlinetask beginning."
8214 (org-with-wide-buffer
8215 (narrow-to-region (line-beginning-position)
8216 (save-excursion
8217 (if (org-with-limited-levels (org-at-heading-p))
8218 (org-with-limited-levels (outline-next-heading))
8219 (org-inlinetask-goto-end))
8220 (point)))
8221 (forward-line)
8222 ;; Indent properly planning info and property drawer.
8223 (when (org-looking-at-p org-planning-line-re)
8224 (org-indent-line)
8225 (forward-line))
8226 (when (looking-at org-property-drawer-re)
8227 (goto-char (match-end 0))
8228 (forward-line)
8229 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8230 (catch 'no-shift
8231 (when (zerop diff) (throw 'no-shift nil))
8232 ;; If DIFF is negative, first check if a shift is possible at all
8233 ;; (e.g., it doesn't break structure). This can only happen if
8234 ;; some contents are not properly indented.
8235 (let ((case-fold-search t))
8236 (when (< diff 0)
8237 (let ((diff (- diff))
8238 (forbidden-re (concat org-outline-regexp
8239 "\\|"
8240 (substring org-footnote-definition-re 1))))
8241 (save-excursion
8242 (while (not (eobp))
8243 (cond
8244 ((org-looking-at-p "[ \t]*$") (forward-line))
8245 ((and (org-looking-at-p org-footnote-definition-re)
8246 (let ((e (org-element-at-point)))
8247 (and (eq (org-element-type e) 'footnote-definition)
8248 (goto-char (org-element-property :end e))))))
8249 ((org-looking-at-p org-outline-regexp) (forward-line))
8250 ;; Give up if shifting would move before column 0 or
8251 ;; if it would introduce a headline or a footnote
8252 ;; definition.
8254 (skip-chars-forward " \t")
8255 (let ((ind (current-column)))
8256 (when (or (< ind diff)
8257 (and (= ind diff) (org-looking-at-p forbidden-re)))
8258 (throw 'no-shift nil)))
8259 ;; Ignore contents of example blocks and source
8260 ;; blocks if their indentation is meant to be
8261 ;; preserved. Jump to block's closing line.
8262 (beginning-of-line)
8263 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8264 (let ((e (org-element-at-point)))
8265 (and (memq (org-element-type e)
8266 '(example-block src-block))
8267 (or org-src-preserve-indentation
8268 (org-element-property :preserve-indent e))
8269 (goto-char (org-element-property :end e))
8270 (progn (skip-chars-backward " \r\t\n")
8271 (beginning-of-line)
8272 t))))
8273 (forward-line))))))))
8274 ;; Shift lines but footnote definitions, inlinetasks boundaries
8275 ;; by DIFF. Also skip contents of source or example blocks
8276 ;; when indentation is meant to be preserved.
8277 (while (not (eobp))
8278 (cond
8279 ((and (org-looking-at-p org-footnote-definition-re)
8280 (let ((e (org-element-at-point)))
8281 (and (eq (org-element-type e) 'footnote-definition)
8282 (goto-char (org-element-property :end e))))))
8283 ((org-looking-at-p org-outline-regexp) (forward-line))
8284 ((org-looking-at-p "[ \t]*$") (forward-line))
8286 (org-indent-line-to (+ (org-get-indentation) diff))
8287 (beginning-of-line)
8288 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8289 (let ((e (org-element-at-point)))
8290 (and (memq (org-element-type e)
8291 '(example-block src-block))
8292 (or org-src-preserve-indentation
8293 (org-element-property :preserve-indent e))
8294 (goto-char (org-element-property :end e))
8295 (progn (skip-chars-backward " \r\t\n")
8296 (beginning-of-line)
8297 t))))
8298 (forward-line)))))))))
8300 (defun org-convert-to-odd-levels ()
8301 "Convert an org-mode file with all levels allowed to one with odd levels.
8302 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8303 level 5 etc."
8304 (interactive)
8305 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8306 (let ((outline-level 'org-outline-level)
8307 (org-odd-levels-only nil) n)
8308 (save-excursion
8309 (goto-char (point-min))
8310 (while (re-search-forward "^\\*\\*+ " nil t)
8311 (setq n (- (length (match-string 0)) 2))
8312 (while (>= (setq n (1- n)) 0)
8313 (org-demote))
8314 (end-of-line 1))))))
8316 (defun org-convert-to-oddeven-levels ()
8317 "Convert an org-mode file with only odd levels to one with odd/even levels.
8318 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8319 file contains a section with an even level, conversion would
8320 destroy the structure of the file. An error is signaled in this
8321 case."
8322 (interactive)
8323 (goto-char (point-min))
8324 ;; First check if there are no even levels
8325 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8326 (org-show-set-visibility 'canonical)
8327 (error "Not all levels are odd in this file. Conversion not possible"))
8328 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8329 (let ((outline-regexp org-outline-regexp)
8330 (outline-level 'org-outline-level)
8331 (org-odd-levels-only nil) n)
8332 (save-excursion
8333 (goto-char (point-min))
8334 (while (re-search-forward "^\\*\\*+ " nil t)
8335 (setq n (/ (1- (length (match-string 0))) 2))
8336 (while (>= (setq n (1- n)) 0)
8337 (org-promote))
8338 (end-of-line 1))))))
8340 (defun org-tr-level (n)
8341 "Make N odd if required."
8342 (if org-odd-levels-only (1+ (/ n 2)) n))
8344 ;;; Vertical tree motion, cutting and pasting of subtrees
8346 (defun org-move-subtree-up (&optional arg)
8347 "Move the current subtree up past ARG headlines of the same level."
8348 (interactive "p")
8349 (org-move-subtree-down (- (prefix-numeric-value arg))))
8351 (defun org-move-subtree-down (&optional arg)
8352 "Move the current subtree down past ARG headlines of the same level."
8353 (interactive "p")
8354 (setq arg (prefix-numeric-value arg))
8355 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8356 'org-get-last-sibling))
8357 (ins-point (make-marker))
8358 (cnt (abs arg))
8359 (col (current-column))
8360 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8361 ;; Select the tree
8362 (org-back-to-heading)
8363 (setq beg0 (point))
8364 (save-excursion
8365 (setq ne-beg (org-back-over-empty-lines))
8366 (setq beg (point)))
8367 (save-match-data
8368 (save-excursion (outline-end-of-heading)
8369 (setq folded (outline-invisible-p)))
8370 (progn (org-end-of-subtree nil t)
8371 (unless (eobp) (backward-char))))
8372 (outline-next-heading)
8373 (setq ne-end (org-back-over-empty-lines))
8374 (setq end (point))
8375 (goto-char beg0)
8376 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8377 ;; include less whitespace
8378 (save-excursion
8379 (goto-char beg)
8380 (forward-line (- ne-beg ne-end))
8381 (setq beg (point))))
8382 ;; Find insertion point, with error handling
8383 (while (> cnt 0)
8384 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8385 (progn (goto-char beg0)
8386 (user-error "Cannot move past superior level or buffer limit")))
8387 (setq cnt (1- cnt)))
8388 (when (> arg 0)
8389 ;; Moving forward - still need to move over subtree
8390 (org-end-of-subtree t t)
8391 (save-excursion
8392 (org-back-over-empty-lines)
8393 (or (bolp) (newline))))
8394 (setq ne-ins (org-back-over-empty-lines))
8395 (move-marker ins-point (point))
8396 (setq txt (buffer-substring beg end))
8397 (org-save-markers-in-region beg end)
8398 (delete-region beg end)
8399 (org-remove-empty-overlays-at beg)
8400 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8401 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8402 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8403 (let ((bbb (point)))
8404 (insert-before-markers txt)
8405 (org-reinstall-markers-in-region bbb)
8406 (move-marker ins-point bbb))
8407 (or (bolp) (insert "\n"))
8408 (setq ins-end (point))
8409 (goto-char ins-point)
8410 (org-skip-whitespace)
8411 (when (and (< arg 0)
8412 (org-first-sibling-p)
8413 (> ne-ins ne-beg))
8414 ;; Move whitespace back to beginning
8415 (save-excursion
8416 (goto-char ins-end)
8417 (let ((kill-whole-line t))
8418 (kill-line (- ne-ins ne-beg)) (point)))
8419 (insert (make-string (- ne-ins ne-beg) ?\n)))
8420 (move-marker ins-point nil)
8421 (if folded
8422 (outline-hide-subtree)
8423 (org-show-entry)
8424 (org-show-children)
8425 (org-cycle-hide-drawers 'children))
8426 (org-clean-visibility-after-subtree-move)
8427 ;; move back to the initial column we were at
8428 (move-to-column col)))
8430 (defvar org-subtree-clip ""
8431 "Clipboard for cut and paste of subtrees.
8432 This is actually only a copy of the kill, because we use the normal kill
8433 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8435 (defvar org-subtree-clip-folded nil
8436 "Was the last copied subtree folded?
8437 This is used to fold the tree back after pasting.")
8439 (defun org-cut-subtree (&optional n)
8440 "Cut the current subtree into the clipboard.
8441 With prefix arg N, cut this many sequential subtrees.
8442 This is a short-hand for marking the subtree and then cutting it."
8443 (interactive "p")
8444 (org-copy-subtree n 'cut))
8446 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8447 "Copy the current subtree it in the clipboard.
8448 With prefix arg N, copy this many sequential subtrees.
8449 This is a short-hand for marking the subtree and then copying it.
8450 If CUT is non-nil, actually cut the subtree.
8451 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8452 of some markers in the region, even if CUT is non-nil. This is
8453 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8454 (interactive "p")
8455 (let (beg end folded (beg0 (point)))
8456 (if (org-called-interactively-p 'any)
8457 (org-back-to-heading nil) ; take what looks like a subtree
8458 (org-back-to-heading t)) ; take what is really there
8459 (setq beg (point))
8460 (skip-chars-forward " \t\r\n")
8461 (save-match-data
8462 (if nosubtrees
8463 (outline-next-heading)
8464 (save-excursion (outline-end-of-heading)
8465 (setq folded (outline-invisible-p)))
8466 (ignore-errors (org-forward-heading-same-level (1- n) t))
8467 (org-end-of-subtree t t)))
8468 ;; Include the end of an inlinetask
8469 (when (and (featurep 'org-inlinetask)
8470 (looking-at-p (concat (org-inlinetask-outline-regexp)
8471 "END[ \t]*$")))
8472 (end-of-line))
8473 (setq end (point))
8474 (goto-char beg0)
8475 (when (> end beg)
8476 (setq org-subtree-clip-folded folded)
8477 (when (or cut force-store-markers)
8478 (org-save-markers-in-region beg end))
8479 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8480 (setq org-subtree-clip (current-kill 0))
8481 (message "%s: Subtree(s) with %d characters"
8482 (if cut "Cut" "Copied")
8483 (length org-subtree-clip)))))
8485 (defun org-paste-subtree (&optional level tree for-yank remove)
8486 "Paste the clipboard as a subtree, with modification of headline level.
8487 The entire subtree is promoted or demoted in order to match a new headline
8488 level.
8490 If the cursor is at the beginning of a headline, the same level as
8491 that headline is used to paste the tree.
8493 If not, the new level is derived from the *visible* headings
8494 before and after the insertion point, and taken to be the inferior headline
8495 level of the two. So if the previous visible heading is level 3 and the
8496 next is level 4 (or vice versa), level 4 will be used for insertion.
8497 This makes sure that the subtree remains an independent subtree and does
8498 not swallow low level entries.
8500 You can also force a different level, either by using a numeric prefix
8501 argument, or by inserting the heading marker by hand. For example, if the
8502 cursor is after \"*****\", then the tree will be shifted to level 5.
8504 If optional TREE is given, use this text instead of the kill ring.
8506 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8507 move back over whitespace before inserting, and move point to the end of
8508 the inserted text when done.
8510 When REMOVE is non-nil, remove the subtree from the clipboard."
8511 (interactive "P")
8512 (setq tree (or tree (and kill-ring (current-kill 0))))
8513 (unless (org-kill-is-subtree-p tree)
8514 (user-error "%s"
8515 (substitute-command-keys
8516 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8517 (org-with-limited-levels
8518 (let* ((visp (not (outline-invisible-p)))
8519 (txt tree)
8520 (^re_ "\\(\\*+\\)[ \t]*")
8521 (old-level (if (string-match org-outline-regexp-bol txt)
8522 (- (match-end 0) (match-beginning 0) 1)
8523 -1))
8524 (force-level (cond (level (prefix-numeric-value level))
8525 ((and (looking-at "[ \t]*$")
8526 (string-match
8527 "^\\*+$" (buffer-substring
8528 (point-at-bol) (point))))
8529 (- (match-end 0) (match-beginning 0)))
8530 ((and (bolp)
8531 (looking-at org-outline-regexp))
8532 (- (match-end 0) (point) 1))))
8533 (previous-level (save-excursion
8534 (condition-case nil
8535 (progn
8536 (outline-previous-visible-heading 1)
8537 (if (looking-at ^re_)
8538 (- (match-end 0) (match-beginning 0) 1)
8540 (error 1))))
8541 (next-level (save-excursion
8542 (condition-case nil
8543 (progn
8544 (or (looking-at org-outline-regexp)
8545 (outline-next-visible-heading 1))
8546 (if (looking-at ^re_)
8547 (- (match-end 0) (match-beginning 0) 1)
8549 (error 1))))
8550 (new-level (or force-level (max previous-level next-level)))
8551 (shift (if (or (= old-level -1)
8552 (= new-level -1)
8553 (= old-level new-level))
8555 (- new-level old-level)))
8556 (delta (if (> shift 0) -1 1))
8557 (func (if (> shift 0) 'org-demote 'org-promote))
8558 (org-odd-levels-only nil)
8559 beg end newend)
8560 ;; Remove the forced level indicator
8561 (when force-level
8562 (delete-region (point-at-bol) (point)))
8563 ;; Paste
8564 (beginning-of-line (if (bolp) 1 2))
8565 (setq beg (point))
8566 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8567 (insert-before-markers txt)
8568 (unless (string-match "\n\\'" txt) (insert "\n"))
8569 (setq newend (point))
8570 (org-reinstall-markers-in-region beg)
8571 (setq end (point))
8572 (goto-char beg)
8573 (skip-chars-forward " \t\n\r")
8574 (setq beg (point))
8575 (when (and (outline-invisible-p) visp)
8576 (save-excursion (outline-show-heading)))
8577 ;; Shift if necessary
8578 (unless (= shift 0)
8579 (save-restriction
8580 (narrow-to-region beg end)
8581 (while (not (= shift 0))
8582 (org-map-region func (point-min) (point-max))
8583 (setq shift (+ delta shift)))
8584 (goto-char (point-min))
8585 (setq newend (point-max))))
8586 (when (or (org-called-interactively-p 'interactive) for-yank)
8587 (message "Clipboard pasted as level %d subtree" new-level))
8588 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8589 kill-ring
8590 (eq org-subtree-clip (current-kill 0))
8591 org-subtree-clip-folded)
8592 ;; The tree was folded before it was killed/copied
8593 (outline-hide-subtree))
8594 (and for-yank (goto-char newend))
8595 (and remove (setq kill-ring (cdr kill-ring))))))
8597 (defun org-kill-is-subtree-p (&optional txt)
8598 "Check if the current kill is an outline subtree, or a set of trees.
8599 Returns nil if kill does not start with a headline, or if the first
8600 headline level is not the largest headline level in the tree.
8601 So this will actually accept several entries of equal levels as well,
8602 which is OK for `org-paste-subtree'.
8603 If optional TXT is given, check this string instead of the current kill."
8604 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8605 (re (org-get-limited-outline-regexp))
8606 (^re (concat "^" re))
8607 (start-level (and kill
8608 (string-match
8609 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8610 kill)
8611 (- (match-end 2) (match-beginning 2) 1)))
8612 (start (1+ (or (match-beginning 2) -1))))
8613 (if (not start-level)
8614 (progn
8615 nil) ;; does not even start with a heading
8616 (catch 'exit
8617 (while (setq start (string-match ^re kill (1+ start)))
8618 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8619 (throw 'exit nil)))
8620 t))))
8622 (defvar org-markers-to-move nil
8623 "Markers that should be moved with a cut-and-paste operation.
8624 Those markers are stored together with their positions relative to
8625 the start of the region.")
8627 (defun org-save-markers-in-region (beg end)
8628 "Check markers in region.
8629 If these markers are between BEG and END, record their position relative
8630 to BEG, so that after moving the block of text, we can put the markers back
8631 into place.
8632 This function gets called just before an entry or tree gets cut from the
8633 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8634 called immediately, to move the markers with the entries."
8635 (setq org-markers-to-move nil)
8636 (when (featurep 'org-clock)
8637 (org-clock-save-markers-for-cut-and-paste beg end))
8638 (when (featurep 'org-agenda)
8639 (org-agenda-save-markers-for-cut-and-paste beg end)))
8641 (defun org-check-and-save-marker (marker beg end)
8642 "Check if MARKER is between BEG and END.
8643 If yes, remember the marker and the distance to BEG."
8644 (when (and (marker-buffer marker)
8645 (equal (marker-buffer marker) (current-buffer))
8646 (>= marker beg) (< marker end))
8647 (push (cons marker (- marker beg)) org-markers-to-move)))
8649 (defun org-reinstall-markers-in-region (beg)
8650 "Move all remembered markers to their position relative to BEG."
8651 (dolist (x org-markers-to-move)
8652 (move-marker (car x) (+ beg (cdr x))))
8653 (setq org-markers-to-move nil))
8655 (defun org-narrow-to-subtree ()
8656 "Narrow buffer to the current subtree."
8657 (interactive)
8658 (save-excursion
8659 (save-match-data
8660 (org-with-limited-levels
8661 (narrow-to-region
8662 (progn (org-back-to-heading t) (point))
8663 (progn (org-end-of-subtree t t)
8664 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8665 (point)))))))
8667 (defun org-narrow-to-block ()
8668 "Narrow buffer to the current block."
8669 (interactive)
8670 (let* ((case-fold-search t)
8671 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8672 "^[ \t]*#\\+end_.*")))
8673 (if blockp
8674 (narrow-to-region (car blockp) (cdr blockp))
8675 (user-error "Not in a block"))))
8677 (defun org-clone-subtree-with-time-shift (n &optional shift)
8678 "Clone the task (subtree) at point N times.
8679 The clones will be inserted as siblings.
8681 In interactive use, the user will be prompted for the number of
8682 clones to be produced. If the entry has a timestamp, the user
8683 will also be prompted for a time shift, which may be a repeater
8684 as used in time stamps, for example `+3d'. To disable this,
8685 you can call the function with a universal prefix argument.
8687 When a valid repeater is given and the entry contains any time
8688 stamps, the clones will become a sequence in time, with time
8689 stamps in the subtree shifted for each clone produced. If SHIFT
8690 is nil or the empty string, time stamps will be left alone. The
8691 ID property of the original subtree is removed.
8693 If the original subtree did contain time stamps with a repeater,
8694 the following will happen:
8695 - the repeater will be removed in each clone
8696 - an additional clone will be produced, with the current, unshifted
8697 date(s) in the entry.
8698 - the original entry will be placed *after* all the clones, with
8699 repeater intact.
8700 - the start days in the repeater in the original entry will be shifted
8701 to past the last clone.
8702 In this way you can spell out a number of instances of a repeating task,
8703 and still retain the repeater to cover future instances of the task.
8705 As described above, N+1 clones are produced when the original
8706 subtree has a repeater. Setting N to 0, then, can be used to
8707 remove the repeater from a subtree and create a shifted clone
8708 with the original repeater."
8709 (interactive "nNumber of clones to produce: ")
8710 (let ((shift
8711 (or shift
8712 (if (and (not (equal current-prefix-arg '(4)))
8713 (save-excursion
8714 (re-search-forward org-ts-regexp-both
8715 (save-excursion
8716 (org-end-of-subtree t)
8717 (point)) t)))
8718 (read-from-minibuffer
8719 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8720 ""))) ;; No time shift
8721 (n-no-remove -1)
8722 (drawer-re org-drawer-regexp)
8723 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8724 beg end template task idprop
8725 shift-n shift-what doshift nmin nmax)
8726 (unless (wholenump n)
8727 (user-error "Invalid number of replications %s" n))
8728 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8729 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8730 shift)))
8731 (user-error "Invalid shift specification %s" shift))
8732 (when doshift
8733 (setq shift-n (string-to-number (match-string 1 shift))
8734 shift-what (cdr (assoc (match-string 2 shift)
8735 '(("d" . day) ("w" . week)
8736 ("m" . month) ("y" . year))))))
8737 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8738 (setq nmin 1 nmax n)
8739 (org-back-to-heading t)
8740 (setq beg (point))
8741 (setq idprop (org-entry-get nil "ID"))
8742 (org-end-of-subtree t t)
8743 (or (bolp) (insert "\n"))
8744 (setq end (point))
8745 (setq template (buffer-substring beg end))
8746 (when (and doshift
8747 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8748 (delete-region beg end)
8749 (setq end beg)
8750 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8751 (goto-char end)
8752 (cl-loop for n from nmin to nmax do
8753 ;; prepare clone
8754 (with-temp-buffer
8755 (insert template)
8756 (org-mode)
8757 (goto-char (point-min))
8758 (org-show-subtree)
8759 (and idprop (if org-clone-delete-id
8760 (org-entry-delete nil "ID")
8761 (org-id-get-create t)))
8762 (unless (= n 0)
8763 (while (re-search-forward org-clock-re nil t)
8764 (kill-whole-line))
8765 (goto-char (point-min))
8766 (while (re-search-forward drawer-re nil t)
8767 (org-remove-empty-drawer-at (point))))
8768 (goto-char (point-min))
8769 (when doshift
8770 (while (re-search-forward org-ts-regexp-both nil t)
8771 (org-timestamp-change (* n shift-n) shift-what))
8772 (unless (= n n-no-remove)
8773 (goto-char (point-min))
8774 (while (re-search-forward org-ts-regexp nil t)
8775 (save-excursion
8776 (goto-char (match-beginning 0))
8777 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8778 (delete-region (match-beginning 1) (match-end 1)))))))
8779 (setq task (buffer-string)))
8780 (insert task))
8781 (goto-char beg)))
8783 ;;; Outline Sorting
8785 (defun org-sort (with-case)
8786 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8787 Optional argument WITH-CASE means sort case-sensitively."
8788 (interactive "P")
8789 (cond
8790 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8791 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8793 (org-call-with-arg 'org-sort-entries with-case))))
8795 (defun org-sort-remove-invisible (s)
8796 "Remove invisible links from string S."
8797 (remove-text-properties 0 (length s) org-rm-props s)
8798 (while (string-match org-bracket-link-regexp s)
8799 (setq s (replace-match (if (match-end 2)
8800 (match-string 3 s)
8801 (match-string 1 s))
8802 t t s)))
8803 (let ((st (format " %s " s)))
8804 (while (string-match org-emph-re st)
8805 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8806 (setq s (substring st 1 -1)))
8809 (defvar org-priority-regexp) ; defined later in the file
8811 (defvar org-after-sorting-entries-or-items-hook nil
8812 "Hook that is run after a bunch of entries or items have been sorted.
8813 When children are sorted, the cursor is in the parent line when this
8814 hook gets called. When a region or a plain list is sorted, the cursor
8815 will be in the first entry of the sorted region/list.")
8817 (defun org-sort-entries
8818 (&optional with-case sorting-type getkey-func compare-func property)
8819 "Sort entries on a certain level of an outline tree.
8820 If there is an active region, the entries in the region are sorted.
8821 Else, if the cursor is before the first entry, sort the top-level items.
8822 Else, the children of the entry at point are sorted.
8824 Sorting can be alphabetically, numerically, by date/time as given by
8825 a time stamp, by a property, by priority order, or by a custom function.
8827 The command prompts for the sorting type unless it has been given to the
8828 function through the SORTING-TYPE argument, which needs to be a character,
8829 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8830 the precise meaning of each character:
8832 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8833 c By creation time, which is assumed to be the first inactive time stamp
8834 at the beginning of a line.
8835 d By deadline date/time.
8836 k By clocking time.
8837 n Numerically, by converting the beginning of the entry/item to a number.
8838 o By order of TODO keywords.
8839 p By priority according to the cookie.
8840 r By the value of a property.
8841 s By scheduled date/time.
8842 t By date/time, either the first active time stamp in the entry, or, if
8843 none exist, by the first inactive one.
8845 Capital letters will reverse the sort order.
8847 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8848 called with point at the beginning of the record. It must return either
8849 a string or a number that should serve as the sorting key for that record.
8851 Comparing entries ignores case by default. However, with an optional argument
8852 WITH-CASE, the sorting considers case as well.
8854 Sorting is done against the visible part of the headlines, it ignores hidden
8855 links.
8857 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8858 (interactive "P")
8859 (let ((case-func (if with-case 'identity 'downcase))
8860 (cmstr
8861 ;; The clock marker is lost when using `sort-subr', let's
8862 ;; store the clocking string.
8863 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8864 (save-excursion
8865 (goto-char org-clock-marker)
8866 (buffer-substring-no-properties (line-beginning-position)
8867 (point)))))
8868 start beg end stars re re2
8869 txt what tmp)
8870 ;; Find beginning and end of region to sort
8871 (cond
8872 ((org-region-active-p)
8873 ;; we will sort the region
8874 (setq end (region-end)
8875 what "region")
8876 (goto-char (region-beginning))
8877 (unless (org-at-heading-p) (outline-next-heading))
8878 (setq start (point)))
8879 ((or (org-at-heading-p)
8880 (ignore-errors (progn (org-back-to-heading) t)))
8881 ;; we will sort the children of the current headline
8882 (org-back-to-heading)
8883 (setq start (point)
8884 end (progn (org-end-of-subtree t t)
8885 (or (bolp) (insert "\n"))
8886 (when (>= (org-back-over-empty-lines) 1)
8887 (forward-line 1))
8888 (point))
8889 what "children")
8890 (goto-char start)
8891 (outline-show-subtree)
8892 (outline-next-heading))
8894 ;; we will sort the top-level entries in this file
8895 (goto-char (point-min))
8896 (or (org-at-heading-p) (outline-next-heading))
8897 (setq start (point))
8898 (goto-char (point-max))
8899 (beginning-of-line 1)
8900 (when (looking-at ".*?\\S-")
8901 ;; File ends in a non-white line
8902 (end-of-line 1)
8903 (insert "\n"))
8904 (setq end (point-max))
8905 (setq what "top-level")
8906 (goto-char start)
8907 (outline-show-all)))
8909 (setq beg (point))
8910 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8912 (looking-at "\\(\\*+\\)")
8913 (setq stars (match-string 1)
8914 re (concat "^" (regexp-quote stars) " +")
8915 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8916 txt (buffer-substring beg end))
8917 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8918 (when (and (not (equal stars "*")) (string-match re2 txt))
8919 (user-error "Region to sort contains a level above the first entry"))
8921 (unless sorting-type
8922 (message
8923 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8924 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8925 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8926 what)
8927 (setq sorting-type (read-char-exclusive))
8929 (unless getkey-func
8930 (and (= (downcase sorting-type) ?f)
8931 (setq getkey-func
8932 (completing-read "Sort using function: "
8933 obarray 'fboundp t nil nil))
8934 (setq getkey-func (intern getkey-func))))
8936 (and (= (downcase sorting-type) ?r)
8937 (not property)
8938 (setq property
8939 (completing-read "Property: "
8940 (mapcar #'list (org-buffer-property-keys t))
8941 nil t))))
8943 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8944 (message "Sorting entries...")
8946 (save-restriction
8947 (narrow-to-region start end)
8948 (let ((dcst (downcase sorting-type))
8949 (case-fold-search nil)
8950 (now (current-time)))
8951 (sort-subr
8952 (/= dcst sorting-type)
8953 ;; This function moves to the beginning character of the "record" to
8954 ;; be sorted.
8955 (lambda nil
8956 (if (re-search-forward re nil t)
8957 (goto-char (match-beginning 0))
8958 (goto-char (point-max))))
8959 ;; This function moves to the last character of the "record" being
8960 ;; sorted.
8961 (lambda nil
8962 (save-match-data
8963 (condition-case nil
8964 (outline-forward-same-level 1)
8965 (error
8966 (goto-char (point-max))))))
8967 ;; This function returns the value that gets sorted against.
8968 (lambda nil
8969 (cond
8970 ((= dcst ?n)
8971 (if (looking-at org-complex-heading-regexp)
8972 (string-to-number (org-sort-remove-invisible (match-string 4)))
8973 nil))
8974 ((= dcst ?a)
8975 (if (looking-at org-complex-heading-regexp)
8976 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8977 nil))
8978 ((= dcst ?k)
8979 (or (get-text-property (point) :org-clock-minutes) 0))
8980 ((= dcst ?t)
8981 (let ((end (save-excursion (outline-next-heading) (point))))
8982 (if (or (re-search-forward org-ts-regexp end t)
8983 (re-search-forward org-ts-regexp-both end t))
8984 (org-time-string-to-seconds (match-string 0))
8985 (org-float-time now))))
8986 ((= dcst ?c)
8987 (let ((end (save-excursion (outline-next-heading) (point))))
8988 (if (re-search-forward
8989 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8990 end t)
8991 (org-time-string-to-seconds (match-string 0))
8992 (org-float-time now))))
8993 ((= dcst ?s)
8994 (let ((end (save-excursion (outline-next-heading) (point))))
8995 (if (re-search-forward org-scheduled-time-regexp end t)
8996 (org-time-string-to-seconds (match-string 1))
8997 (org-float-time now))))
8998 ((= dcst ?d)
8999 (let ((end (save-excursion (outline-next-heading) (point))))
9000 (if (re-search-forward org-deadline-time-regexp end t)
9001 (org-time-string-to-seconds (match-string 1))
9002 (org-float-time now))))
9003 ((= dcst ?p)
9004 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9005 (string-to-char (match-string 2))
9006 org-default-priority))
9007 ((= dcst ?r)
9008 (or (org-entry-get nil property) ""))
9009 ((= dcst ?o)
9010 (when (looking-at org-complex-heading-regexp)
9011 (let* ((m (match-string 2))
9012 (s (if (member m org-done-keywords) '- '+)))
9013 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9014 ((= dcst ?f)
9015 (if getkey-func
9016 (progn
9017 (setq tmp (funcall getkey-func))
9018 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9019 tmp)
9020 (error "Invalid key function `%s'" getkey-func)))
9021 (t (error "Invalid sorting type `%c'" sorting-type))))
9023 (cond
9024 ((= dcst ?a) 'string<)
9025 ((= dcst ?f) compare-func)
9026 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9027 (run-hooks 'org-after-sorting-entries-or-items-hook)
9028 ;; Reset the clock marker if needed
9029 (when cmstr
9030 (save-excursion
9031 (goto-char start)
9032 (search-forward cmstr nil t)
9033 (move-marker org-clock-marker (point))))
9034 (message "Sorting entries...done")))
9036 ;;; The orgstruct minor mode
9038 ;; Define a minor mode which can be used in other modes in order to
9039 ;; integrate the org-mode structure editing commands.
9041 ;; This is really a hack, because the org-mode structure commands use
9042 ;; keys which normally belong to the major mode. Here is how it
9043 ;; works: The minor mode defines all the keys necessary to operate the
9044 ;; structure commands, but wraps the commands into a function which
9045 ;; tests if the cursor is currently at a headline or a plain list
9046 ;; item. If that is the case, the structure command is used,
9047 ;; temporarily setting many Org-mode variables like regular
9048 ;; expressions for filling etc. However, when any of those keys is
9049 ;; used at a different location, function uses `key-binding' to look
9050 ;; up if the key has an associated command in another currently active
9051 ;; keymap (minor modes, major mode, global), and executes that
9052 ;; command. There might be problems if any of the keys is otherwise
9053 ;; used as a prefix key.
9055 (defcustom orgstruct-heading-prefix-regexp ""
9056 "Regexp that matches the custom prefix of Org headlines in
9057 orgstruct(++)-mode."
9058 :group 'org
9059 :version "24.4"
9060 :package-version '(Org . "8.3")
9061 :type 'regexp)
9062 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9064 (defcustom orgstruct-setup-hook nil
9065 "Hook run after orgstruct-mode-map is filled."
9066 :group 'org
9067 :version "24.4"
9068 :package-version '(Org . "8.0")
9069 :type 'hook)
9071 (defvar orgstruct-initialized nil)
9073 (defvar org-local-vars nil
9074 "List of local variables, for use by `orgstruct-mode'.")
9076 ;;;###autoload
9077 (define-minor-mode orgstruct-mode
9078 "Toggle the minor mode `orgstruct-mode'.
9079 This mode is for using Org-mode structure commands in other
9080 modes. The following keys behave as if Org-mode were active, if
9081 the cursor is on a headline, or on a plain list item (both as
9082 defined by Org-mode)."
9083 nil " OrgStruct" (make-sparse-keymap)
9084 (funcall (if orgstruct-mode
9085 'add-to-invisibility-spec
9086 'remove-from-invisibility-spec)
9087 '(outline . t))
9088 (when orgstruct-mode
9089 (org-load-modules-maybe)
9090 (unless orgstruct-initialized
9091 (orgstruct-setup)
9092 (setq orgstruct-initialized t))))
9094 ;;;###autoload
9095 (defun turn-on-orgstruct ()
9096 "Unconditionally turn on `orgstruct-mode'."
9097 (orgstruct-mode 1))
9099 (defvar-local orgstruct-is-++ nil
9100 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9101 (defvar-local org-fb-vars nil)
9102 (defun orgstruct++-mode (&optional arg)
9103 "Toggle `orgstruct-mode', the enhanced version of it.
9104 In addition to setting orgstruct-mode, this also exports all
9105 indentation and autofilling variables from org-mode into the
9106 buffer. It will also recognize item context in multiline items."
9107 (interactive "P")
9108 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9109 (if (< arg 1)
9110 (progn (orgstruct-mode -1)
9111 (dolist (v org-fb-vars)
9112 (set (make-local-variable (car v))
9113 (if (eq (car-safe (cadr v)) 'quote)
9114 (cl-cadadr v)
9115 (nth 1 v)))))
9116 (orgstruct-mode 1)
9117 (setq org-fb-vars nil)
9118 (unless org-local-vars
9119 (setq org-local-vars (org-get-local-variables)))
9120 (let (var val)
9121 (dolist (x org-local-vars)
9122 (when (string-match
9123 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9124 \\|fill-prefix\\|indent-\\)"
9125 (symbol-name (car x)))
9126 (setq var (car x) val (nth 1 x))
9127 (push (list var `(quote ,(eval var))) org-fb-vars)
9128 (set (make-local-variable var)
9129 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9130 (setq-local orgstruct-is-++ t))))
9132 ;;;###autoload
9133 (defun turn-on-orgstruct++ ()
9134 "Unconditionally turn on `orgstruct++-mode'."
9135 (orgstruct++-mode 1))
9137 (defun orgstruct-error ()
9138 "Error when there is no default binding for a structure key."
9139 (interactive)
9140 (funcall (if (fboundp 'user-error)
9141 'user-error
9142 'error)
9143 "This key has no function outside structure elements"))
9145 (defun orgstruct-setup ()
9146 "Setup orgstruct keymap."
9147 (dolist (cell '((org-demote . t)
9148 (org-metaleft . t)
9149 (org-metaright . t)
9150 (org-promote . t)
9151 (org-shiftmetaleft . t)
9152 (org-shiftmetaright . t)
9153 org-backward-element
9154 org-backward-heading-same-level
9155 org-ctrl-c-ret
9156 org-ctrl-c-minus
9157 org-ctrl-c-star
9158 org-cycle
9159 org-forward-heading-same-level
9160 org-insert-heading
9161 org-insert-heading-respect-content
9162 org-kill-note-or-show-branches
9163 org-mark-subtree
9164 org-meta-return
9165 org-metadown
9166 org-metaup
9167 org-narrow-to-subtree
9168 org-promote-subtree
9169 org-reveal
9170 org-shiftdown
9171 org-shiftleft
9172 org-shiftmetadown
9173 org-shiftmetaup
9174 org-shiftright
9175 org-shifttab
9176 org-shifttab
9177 org-shiftup
9178 org-show-children
9179 org-show-subtree
9180 org-sort
9181 org-up-element
9182 outline-demote
9183 outline-next-visible-heading
9184 outline-previous-visible-heading
9185 outline-promote
9186 outline-up-heading))
9187 (let ((f (or (car-safe cell) cell))
9188 (disable-when-heading-prefix (cdr-safe cell)))
9189 (when (fboundp f)
9190 (let ((new-bindings))
9191 (dolist (binding (nconc (where-is-internal f org-mode-map)
9192 (where-is-internal f outline-mode-map)))
9193 (push binding new-bindings)
9194 ;; TODO use local-function-key-map
9195 (dolist (rep '(("<tab>" . "TAB")
9196 ("<return>" . "RET")
9197 ("<escape>" . "ESC")
9198 ("<delete>" . "DEL")))
9199 (setq binding (read-kbd-macro
9200 (let ((case-fold-search))
9201 (replace-regexp-in-string
9202 (regexp-quote (cdr rep))
9203 (car rep)
9204 (key-description binding)))))
9205 (cl-pushnew binding new-bindings :test 'equal)))
9206 (dolist (binding new-bindings)
9207 (let ((key (lookup-key orgstruct-mode-map binding)))
9208 (when (or (not key) (numberp key))
9209 (ignore-errors
9210 (org-defkey orgstruct-mode-map
9211 binding
9212 (orgstruct-make-binding
9213 f binding disable-when-heading-prefix))))))))))
9214 (run-hooks 'orgstruct-setup-hook))
9216 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9217 "Create a function for binding in the structure minor mode.
9218 FUN is the command to call inside a table. KEY is the key that
9219 should be checked in for a command to execute outside of tables.
9220 Non-nil `disable-when-heading-prefix' means to disable the command
9221 if `orgstruct-heading-prefix-regexp' is not empty."
9222 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9223 (let ((nname name)
9224 (i 0))
9225 (while (fboundp (intern nname))
9226 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9227 (setq name (intern nname)))
9228 (eval
9229 (let ((bindings '((org-heading-regexp
9230 (concat "^"
9231 orgstruct-heading-prefix-regexp
9232 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9233 (org-outline-regexp
9234 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9235 (org-outline-regexp-bol
9236 (concat "^" org-outline-regexp))
9237 (outline-regexp org-outline-regexp)
9238 (outline-heading-end-regexp "\n")
9239 (outline-level 'org-outline-level)
9240 (outline-heading-alist))))
9241 `(defun ,name (arg)
9242 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9243 "Outside of structure, run the binding of `"
9244 (key-description key) "'."
9245 (when disable-when-heading-prefix
9246 (concat
9247 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9248 "back to the default binding due to limitations of Org's implementation of\n"
9249 "`" (symbol-name fun) "'.")))
9250 (interactive "p")
9251 (let* ((disable
9252 ,(and disable-when-heading-prefix
9253 '(not (string= orgstruct-heading-prefix-regexp ""))))
9254 (fallback
9255 (or disable
9256 (not
9257 (let* ,bindings
9258 (org-context-p 'headline 'item
9259 ,(when (memq fun
9260 '(org-insert-heading
9261 org-insert-heading-respect-content
9262 org-meta-return))
9263 '(when orgstruct-is-++
9264 'item-body))))))))
9265 (if fallback
9266 (let* ((orgstruct-mode)
9267 (binding
9268 (let ((key ,key))
9269 (catch 'exit
9270 (dolist
9271 (rep
9272 '(nil
9273 ("<\\([^>]*\\)tab>" . "\\1TAB")
9274 ("<\\([^>]*\\)return>" . "\\1RET")
9275 ("<\\([^>]*\\)escape>" . "\\1ESC")
9276 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9277 nil)
9278 (when rep
9279 (setq key (read-kbd-macro
9280 (let ((case-fold-search))
9281 (replace-regexp-in-string
9282 (car rep)
9283 (cdr rep)
9284 (key-description key))))))
9285 (when (key-binding key)
9286 (throw 'exit (key-binding key))))))))
9287 (if (keymapp binding)
9288 (org-set-transient-map binding)
9289 (let ((func (or binding
9290 (unless disable
9291 'orgstruct-error))))
9292 (when func
9293 (call-interactively func)))))
9294 (org-run-like-in-org-mode
9295 (lambda ()
9296 (interactive)
9297 (let* ,bindings
9298 (call-interactively ',fun)))))))))
9299 name))
9301 (defun org-contextualize-keys (alist contexts)
9302 "Return valid elements in ALIST depending on CONTEXTS.
9304 `org-agenda-custom-commands' or `org-capture-templates' are the
9305 values used for ALIST, and `org-agenda-custom-commands-contexts'
9306 or `org-capture-templates-contexts' are the associated contexts
9307 definitions."
9308 (let ((contexts
9309 ;; normalize contexts
9310 (mapcar
9311 (lambda(c) (cond ((listp (cadr c))
9312 (list (car c) (car c) (nth 1 c)))
9313 ((string= "" (cadr c))
9314 (list (car c) (car c) (nth 2 c)))
9315 (t c)))
9316 contexts))
9317 (a alist) r s)
9318 ;; loop over all commands or templates
9319 (dolist (c a)
9320 (let (vrules repl)
9321 (cond
9322 ((not (assoc (car c) contexts))
9323 (push c r))
9324 ((and (assoc (car c) contexts)
9325 (setq vrules (org-contextualize-validate-key
9326 (car c) contexts)))
9327 (mapc (lambda (vr)
9328 (unless (equal (car vr) (cadr vr))
9329 (setq repl vr)))
9330 vrules)
9331 (if (not repl) (push c r)
9332 (push (cadr repl) s)
9333 (push
9334 (cons (car c)
9335 (cdr (or (assoc (cadr repl) alist)
9336 (error "Undefined key `%s' as contextual replacement for `%s'"
9337 (cadr repl) (car c)))))
9338 r))))))
9339 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9340 (delq
9342 (delete-dups
9343 (mapcar (lambda (x)
9344 (let ((tpl (car x)))
9345 (unless (delq
9347 (mapcar (lambda (y)
9348 (equal y tpl))
9350 x)))
9351 (reverse r))))))
9353 (defun org-contextualize-validate-key (key contexts)
9354 "Check CONTEXTS for agenda or capture KEY."
9355 (let (res)
9356 (dolist (r contexts)
9357 (dolist (rr (car (last r)))
9358 (when
9359 (and (equal key (car r))
9360 (if (functionp rr) (funcall rr)
9361 (or (and (eq (car rr) 'in-file)
9362 (buffer-file-name)
9363 (string-match (cdr rr) (buffer-file-name)))
9364 (and (eq (car rr) 'in-mode)
9365 (string-match (cdr rr) (symbol-name major-mode)))
9366 (and (eq (car rr) 'in-buffer)
9367 (string-match (cdr rr) (buffer-name)))
9368 (when (and (eq (car rr) 'not-in-file)
9369 (buffer-file-name))
9370 (not (string-match (cdr rr) (buffer-file-name))))
9371 (when (eq (car rr) 'not-in-mode)
9372 (not (string-match (cdr rr) (symbol-name major-mode))))
9373 (when (eq (car rr) 'not-in-buffer)
9374 (not (string-match (cdr rr) (buffer-name)))))))
9375 (push r res))))
9376 (delete-dups (delq nil res))))
9378 (defun org-context-p (&rest contexts)
9379 "Check if local context is any of CONTEXTS.
9380 Possible values in the list of contexts are `table', `headline', and `item'."
9381 (let ((pos (point)))
9382 (goto-char (point-at-bol))
9383 (prog1 (or (and (memq 'table contexts)
9384 (looking-at "[ \t]*|"))
9385 (and (memq 'headline contexts)
9386 (looking-at org-outline-regexp))
9387 (and (memq 'item contexts)
9388 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9389 (and (memq 'item-body contexts)
9390 (org-in-item-p)))
9391 (goto-char pos))))
9393 (defconst org-unique-local-variables
9394 '(org-element--cache
9395 org-element--cache-objects
9396 org-element--cache-sync-keys
9397 org-element--cache-sync-requests
9398 org-element--cache-sync-timer)
9399 "List of local variables that cannot be transferred to another buffer.")
9401 (defun org-get-local-variables ()
9402 "Return a list of all local variables in an Org mode buffer."
9403 (delq nil
9404 (mapcar
9405 (lambda (x)
9406 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9407 (name (car binding)))
9408 (and (not (get name 'org-state))
9409 (not (memq name org-unique-local-variables))
9410 (string-match-p
9411 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9412 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9413 (symbol-name name))
9414 binding)))
9415 (with-temp-buffer
9416 (org-mode)
9417 (buffer-local-variables)))))
9419 (defun org-clone-local-variables (from-buffer &optional regexp)
9420 "Clone local variables from FROM-BUFFER.
9421 Optional argument REGEXP selects variables to clone."
9422 (dolist (pair (buffer-local-variables from-buffer))
9423 (let ((name (car pair)))
9424 (when (and (symbolp name)
9425 (not (memq name org-unique-local-variables))
9426 (or (null regexp) (string-match regexp (symbol-name name))))
9427 (set (make-local-variable name) (cdr pair))))))
9429 ;;;###autoload
9430 (defun org-run-like-in-org-mode (cmd)
9431 "Run a command, pretending that the current buffer is in Org-mode.
9432 This will temporarily bind local variables that are typically bound in
9433 Org-mode to the values they have in Org-mode, and then interactively
9434 call CMD."
9435 (org-load-modules-maybe)
9436 (unless org-local-vars
9437 (setq org-local-vars (org-get-local-variables)))
9438 (let (binds)
9439 (dolist (var org-local-vars)
9440 (when (or (not (boundp (car var)))
9441 (eq (symbol-value (car var))
9442 (default-value (car var))))
9443 (push (list (car var) `(quote ,(cadr var))) binds)))
9444 (eval `(let ,binds
9445 (call-interactively (quote ,cmd))))))
9447 (defun org-get-category (&optional pos force-refresh)
9448 "Get the category applying to position POS."
9449 (save-match-data
9450 (when force-refresh (org-refresh-category-properties))
9451 (let ((pos (or pos (point))))
9452 (or (get-text-property pos 'org-category)
9453 (progn (org-refresh-category-properties)
9454 (get-text-property pos 'org-category))))))
9456 ;;; Refresh properties
9458 (defun org-refresh-properties (dprop tprop)
9459 "Refresh buffer text properties.
9460 DPROP is the drawer property and TPROP is either the
9461 corresponding text property to set, or an alist with each element
9462 being a text property (as a symbol) and a function to apply to
9463 the value of the drawer property."
9464 (let ((case-fold-search t)
9465 (inhibit-read-only t))
9466 (org-with-silent-modifications
9467 (save-excursion
9468 (save-restriction
9469 (widen)
9470 (goto-char (point-min))
9471 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9472 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9474 (defun org-refresh-property (tprop p)
9475 "Refresh the buffer text property TPROP from the drawer property P.
9476 The refresh happens only for the current tree (not subtree)."
9477 (unless (org-before-first-heading-p)
9478 (save-excursion
9479 (org-back-to-heading t)
9480 (if (symbolp tprop)
9481 ;; TPROP is a text property symbol
9482 (put-text-property
9483 (point) (or (outline-next-heading) (point-max)) tprop p)
9484 ;; TPROP is an alist with (properties . function) elements
9485 (dolist (al tprop)
9486 (save-excursion
9487 (put-text-property
9488 (line-beginning-position) (or (outline-next-heading) (point-max))
9489 (car al)
9490 (funcall (cdr al) p))))))))
9492 (defun org-refresh-category-properties ()
9493 "Refresh category text properties in the buffer."
9494 (let ((case-fold-search t)
9495 (inhibit-read-only t)
9496 (default-category
9497 (cond ((null org-category)
9498 (if buffer-file-name
9499 (file-name-sans-extension
9500 (file-name-nondirectory buffer-file-name))
9501 "???"))
9502 ((symbolp org-category) (symbol-name org-category))
9503 (t org-category))))
9504 (org-with-silent-modifications
9505 (org-with-wide-buffer
9506 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9507 ;; This is the default category for the buffer. If none is
9508 ;; found, fall-back to `org-category' or buffer file name.
9509 (put-text-property
9510 (point-min) (point-max)
9511 'org-category
9512 (catch 'buffer-category
9513 (goto-char (point-max))
9514 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9515 (let ((element (org-element-at-point)))
9516 (when (eq (org-element-type element) 'keyword)
9517 (throw 'buffer-category
9518 (org-element-property :value element)))))
9519 default-category))
9520 ;; Set sub-tree specific categories.
9521 (goto-char (point-min))
9522 (let ((regexp (org-re-property "CATEGORY")))
9523 (while (re-search-forward regexp nil t)
9524 (let ((value (org-match-string-no-properties 3)))
9525 (when (org-at-property-p)
9526 (put-text-property
9527 (save-excursion (org-back-to-heading t) (point))
9528 (save-excursion (org-end-of-subtree t t) (point))
9529 'org-category
9530 value)))))))))
9532 (defun org-refresh-stats-properties ()
9533 "Refresh stats text properties in the buffer."
9534 (let (stats)
9535 (org-with-silent-modifications
9536 (save-excursion
9537 (save-restriction
9538 (widen)
9539 (goto-char (point-min))
9540 (while (re-search-forward
9541 (concat org-outline-regexp-bol ".*"
9542 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9543 nil t)
9544 (setq stats (cond ((equal (match-string 3) "0") 0)
9545 ((match-string 2)
9546 (/ (* (string-to-number (match-string 2)) 100)
9547 (string-to-number (match-string 3))))
9548 (t (string-to-number (match-string 1)))))
9549 (org-back-to-heading t)
9550 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9551 'org-stats stats)))))))
9553 (defun org-refresh-effort-properties ()
9554 "Refresh effort properties"
9555 (org-refresh-properties
9556 org-effort-property
9557 '((effort . identity)
9558 (effort-minutes . org-duration-string-to-minutes))))
9560 ;;;; Link Stuff
9562 ;;; Link abbreviations
9564 (defun org-link-expand-abbrev (link)
9565 "Apply replacements as defined in `org-link-abbrev-alist'."
9566 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9567 (let* ((key (match-string 1 link))
9568 (as (or (assoc key org-link-abbrev-alist-local)
9569 (assoc key org-link-abbrev-alist)))
9570 (tag (and (match-end 2) (match-string 3 link)))
9571 rpl)
9572 (if (not as)
9573 link
9574 (setq rpl (cdr as))
9575 (cond
9576 ((symbolp rpl) (funcall rpl tag))
9577 ((string-match "%(\\([^)]+\\))" rpl)
9578 (replace-match
9579 (save-match-data
9580 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9581 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9582 ((string-match "%h" rpl)
9583 (replace-match (url-hexify-string (or tag "")) t t rpl))
9584 (t (concat rpl tag)))))
9585 link))
9587 ;;; Storing and inserting links
9589 (defvar org-insert-link-history nil
9590 "Minibuffer history for links inserted with `org-insert-link'.")
9592 (defvar org-stored-links nil
9593 "Contains the links stored with `org-store-link'.")
9595 (defvar org-store-link-plist nil
9596 "Plist with info about the most recently link created with `org-store-link'.")
9598 (defvar org-link-protocols nil
9599 "Link protocols added to Org-mode using `org-add-link-type'.")
9601 (defvar org-store-link-functions nil
9602 "List of functions that are called to create and store a link.
9603 Each function will be called in turn until one returns a non-nil
9604 value. Each function should check if it is responsible for creating
9605 this link (for example by looking at the major mode).
9606 If not, it must exit and return nil.
9607 If yes, it should return a non-nil value after a calling
9608 `org-store-link-props' with a list of properties and values.
9609 Special properties are:
9611 :type The link prefix, like \"http\". This must be given.
9612 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9613 This is obligatory as well.
9614 :description Optional default description for the second pair
9615 of brackets in an Org-mode link. The user can still change
9616 this when inserting this link into an Org-mode buffer.
9618 In addition to these, any additional properties can be specified
9619 and then used in capture templates.")
9621 (defun org-add-link-type (type &optional follow export)
9622 "Add TYPE to the list of `org-link-types'.
9623 Re-compute all regular expressions depending on `org-link-types'
9625 FOLLOW and EXPORT are two functions.
9627 FOLLOW should take the link path as the single argument and do whatever
9628 is necessary to follow the link, for example find a file or display
9629 a mail message.
9631 EXPORT should format the link path for export to one of the export formats.
9632 It should be a function accepting three arguments:
9634 path the path of the link, the text after the prefix (like \"http:\")
9635 desc the description of the link, if any
9636 format the export format, a symbol like `html' or `latex' or `ascii'.
9638 The function may use the FORMAT information to return different values
9639 depending on the format. The return value will be put literally into
9640 the exported file. If the return value is nil, this means Org should
9641 do what it normally does with links which do not have EXPORT defined.
9643 Org mode has a built-in default for exporting links. If you are happy with
9644 this default, there is no need to define an export function for the link
9645 type. For a simple example of an export function, see `org-bbdb.el'."
9646 (add-to-list 'org-link-types type t)
9647 (org-make-link-regexps)
9648 (org-element-update-syntax)
9649 (if (assoc type org-link-protocols)
9650 (setcdr (assoc type org-link-protocols) (list follow export))
9651 (push (list type follow export) org-link-protocols)))
9653 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9654 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9656 ;;;###autoload
9657 (defun org-store-link (arg)
9658 "\\<org-mode-map>Store an org-link to the current location.
9659 This link is added to `org-stored-links' and can later be inserted
9660 into an Org buffer with \\[org-insert-link].
9662 For some link types, a prefix ARG is interpreted.
9663 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9664 For file links, ARG negates `org-context-in-file-links'.
9666 A double prefix ARG force skipping storing functions that are not
9667 part of Org's core.
9669 A triple prefix ARG force storing a link for each line in the
9670 active region."
9671 (interactive "P")
9672 (org-load-modules-maybe)
9673 (if (and (equal arg '(64)) (org-region-active-p))
9674 (save-excursion
9675 (let ((end (region-end)))
9676 (goto-char (region-beginning))
9677 (set-mark (point))
9678 (while (< (point-at-eol) end)
9679 (move-end-of-line 1) (activate-mark)
9680 (let (current-prefix-arg)
9681 (call-interactively 'org-store-link))
9682 (move-beginning-of-line 2)
9683 (set-mark (point)))))
9684 (org-with-limited-levels
9685 (setq org-store-link-plist nil)
9686 (let (link cpltxt desc description search
9687 txt custom-id agenda-link sfuns sfunsn)
9688 (cond
9690 ;; Store a link using an external link type
9691 ((and (not (equal arg '(16)))
9692 (setq sfuns
9693 (delq
9694 nil (mapcar (lambda (f)
9695 (let (fs) (if (funcall f) (push f fs))))
9696 org-store-link-functions))
9697 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9698 (or (and (cdr sfuns)
9699 (funcall (intern
9700 (completing-read
9701 "Which function for creating the link? "
9702 sfunsn nil t (car sfunsn)))))
9703 (funcall (caar sfuns)))
9704 (setq link (plist-get org-store-link-plist :link)
9705 desc (or (plist-get org-store-link-plist
9706 :description)
9707 link))))
9709 ;; Store a link from a source code buffer.
9710 ((org-src-edit-buffer-p)
9711 (cond
9712 ((save-excursion
9713 (beginning-of-line)
9714 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9715 "[ \t]*$")))
9716 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9717 ((org-called-interactively-p 'any)
9718 (let (label)
9719 (while (or (not label)
9720 (org-with-wide-buffer
9721 (goto-char (point-min))
9722 (re-search-forward
9723 (regexp-quote (format org-coderef-label-format label))
9724 nil t)))
9725 (when label (message "Label exists already") (sit-for 2))
9726 (setq label (read-string "Code line label: " label)))
9727 (end-of-line)
9728 (setq link (format org-coderef-label-format label))
9729 (let ((gc (- 79 (length link))))
9730 (if (< (current-column) gc) (org-move-to-column gc t)
9731 (insert " ")))
9732 (insert link)
9733 (setq link (concat "(" label ")") desc nil)))
9734 (t (setq link nil))))
9736 ;; We are in the agenda, link to referenced location
9737 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9738 (let ((m (or (get-text-property (point) 'org-hd-marker)
9739 (get-text-property (point) 'org-marker))))
9740 (when m
9741 (org-with-point-at m
9742 (setq agenda-link
9743 (if (org-called-interactively-p 'any)
9744 (call-interactively 'org-store-link)
9745 (org-store-link nil)))))))
9747 ((eq major-mode 'calendar-mode)
9748 (let ((cd (calendar-cursor-to-date)))
9749 (setq link
9750 (format-time-string
9751 (car org-time-stamp-formats)
9752 (apply 'encode-time
9753 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9754 nil nil nil))))
9755 (org-store-link-props :type "calendar" :date cd)))
9757 ((eq major-mode 'help-mode)
9758 (setq link (concat "help:" (save-excursion
9759 (goto-char (point-min))
9760 (looking-at "^[^ ]+")
9761 (match-string 0))))
9762 (org-store-link-props :type "help"))
9764 ((eq major-mode 'w3-mode)
9765 (setq cpltxt (if (and (buffer-name)
9766 (not (string-match "Untitled" (buffer-name))))
9767 (buffer-name)
9768 (url-view-url t))
9769 link (url-view-url t))
9770 (org-store-link-props :type "w3" :url (url-view-url t)))
9772 ((eq major-mode 'image-mode)
9773 (setq cpltxt (concat "file:"
9774 (abbreviate-file-name buffer-file-name))
9775 link cpltxt)
9776 (org-store-link-props :type "image" :file buffer-file-name))
9778 ;; In dired, store a link to the file of the current line
9779 ((derived-mode-p 'dired-mode)
9780 (let ((file (dired-get-filename nil t)))
9781 (setq file (if file
9782 (abbreviate-file-name
9783 (expand-file-name (dired-get-filename nil t)))
9784 ;; otherwise, no file so use current directory.
9785 default-directory))
9786 (setq cpltxt (concat "file:" file)
9787 link cpltxt)))
9789 ((setq search (run-hook-with-args-until-success
9790 'org-create-file-search-functions))
9791 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9792 "::" search))
9793 (setq cpltxt (or description link)))
9795 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9796 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9797 (cond
9798 ;; Store a link using the target at point
9799 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9800 (setq cpltxt
9801 (concat "file:"
9802 (abbreviate-file-name
9803 (buffer-file-name (buffer-base-buffer)))
9804 "::" (match-string 1))
9805 link cpltxt))
9806 ((and (featurep 'org-id)
9807 (or (eq org-id-link-to-org-use-id t)
9808 (and (org-called-interactively-p 'any)
9809 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9810 (and (eq org-id-link-to-org-use-id
9811 'create-if-interactive-and-no-custom-id)
9812 (not custom-id))))
9813 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9814 ;; Store a link using the ID at point
9815 (setq link (condition-case nil
9816 (prog1 (org-id-store-link)
9817 (setq desc (or (plist-get org-store-link-plist
9818 :description)
9819 "")))
9820 (error
9821 ;; Probably before first headline, link only to file
9822 (concat "file:"
9823 (abbreviate-file-name
9824 (buffer-file-name (buffer-base-buffer))))))))
9826 ;; Just link to current headline
9827 (setq cpltxt (concat "file:"
9828 (abbreviate-file-name
9829 (buffer-file-name (buffer-base-buffer)))))
9830 ;; Add a context search string
9831 (when (org-xor org-context-in-file-links arg)
9832 (let* ((ee (org-element-at-point))
9833 (et (org-element-type ee))
9834 (ev (plist-get (cadr ee) :value))
9835 (ek (plist-get (cadr ee) :key))
9836 (eok (and (stringp ek) (string-match "name" ek))))
9837 (setq txt (cond
9838 ((org-at-heading-p) nil)
9839 ((and (eq et 'keyword) eok) ev)
9840 ((org-region-active-p)
9841 (buffer-substring (region-beginning) (region-end)))))
9842 (when (or (null txt) (string-match "\\S-" txt))
9843 (setq cpltxt
9844 (concat cpltxt "::"
9845 (condition-case nil
9846 (org-make-org-heading-search-string txt)
9847 (error "")))
9848 desc (or (and (eq et 'keyword) eok ev)
9849 (nth 4 (ignore-errors (org-heading-components)))
9850 "NONE")))))
9851 (when (string-match "::\\'" cpltxt)
9852 (setq cpltxt (substring cpltxt 0 -2)))
9853 (setq link cpltxt))))
9855 ((buffer-file-name (buffer-base-buffer))
9856 ;; Just link to this file here.
9857 (setq cpltxt (concat "file:"
9858 (abbreviate-file-name
9859 (buffer-file-name (buffer-base-buffer)))))
9860 ;; Add a context string.
9861 (when (org-xor org-context-in-file-links arg)
9862 (setq txt (if (org-region-active-p)
9863 (buffer-substring (region-beginning) (region-end))
9864 (buffer-substring (point-at-bol) (point-at-eol))))
9865 ;; Only use search option if there is some text.
9866 (when (string-match "\\S-" txt)
9867 (setq cpltxt
9868 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9869 desc "NONE")))
9870 (setq link cpltxt))
9872 ((org-called-interactively-p 'interactive)
9873 (user-error "No method for storing a link from this buffer"))
9875 (t (setq link nil)))
9877 ;; We're done setting link and desc, clean up
9878 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9879 (setq link (or link cpltxt)
9880 desc (or desc cpltxt))
9881 (cond ((equal desc "NONE") (setq desc nil))
9882 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9883 (let ((d0 (match-string 3 desc))
9884 (p0 (match-string 5 desc)))
9885 (setq desc
9886 (replace-regexp-in-string
9887 org-bracket-link-regexp
9888 (concat (or p0 d0)
9889 (if (equal (length (match-string 0 desc))
9890 (length desc)) "*" "")) desc)))))
9892 ;; Return the link
9893 (if (not (and (or (org-called-interactively-p 'any)
9894 executing-kbd-macro)
9895 link))
9896 (or agenda-link (and link (org-make-link-string link desc)))
9897 (push (list link desc) org-stored-links)
9898 (message "Stored: %s" (or desc link))
9899 (when custom-id
9900 (setq link (concat "file:" (abbreviate-file-name
9901 (buffer-file-name)) "::#" custom-id))
9902 (push (list link desc) org-stored-links))
9903 (car org-stored-links))))))
9905 (defun org-store-link-props (&rest plist)
9906 "Store link properties, extract names, addresses and dates."
9907 (let ((x (plist-get plist :from)))
9908 (when x
9909 (let ((adr (mail-extract-address-components x)))
9910 (setq plist (plist-put plist :fromname (car adr)))
9911 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9912 (let ((x (plist-get plist :to)))
9913 (when x
9914 (let ((adr (mail-extract-address-components x)))
9915 (setq plist (plist-put plist :toname (car adr)))
9916 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9917 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9918 (when x
9919 (setq plist (plist-put plist :date-timestamp
9920 (format-time-string
9921 (org-time-stamp-format t) x)))
9922 (setq plist (plist-put plist :date-timestamp-inactive
9923 (format-time-string
9924 (org-time-stamp-format t t) x)))))
9925 (let ((from (plist-get plist :from))
9926 (to (plist-get plist :to)))
9927 (when (and from to org-from-is-user-regexp)
9928 (setq plist
9929 (plist-put plist :fromto
9930 (if (string-match org-from-is-user-regexp from)
9931 (concat "to %t")
9932 (concat "from %f"))))))
9933 (setq org-store-link-plist plist))
9935 (defun org-add-link-props (&rest plist)
9936 "Add these properties to the link property list."
9937 (let (key value)
9938 (while plist
9939 (setq key (pop plist) value (pop plist))
9940 (setq org-store-link-plist
9941 (plist-put org-store-link-plist key value)))))
9943 (defun org-email-link-description (&optional fmt)
9944 "Return the description part of an email link.
9945 This takes information from `org-store-link-plist' and formats it
9946 according to FMT (default from `org-email-link-description-format')."
9947 (setq fmt (or fmt org-email-link-description-format))
9948 (let* ((p org-store-link-plist)
9949 (to (plist-get p :toaddress))
9950 (from (plist-get p :fromaddress))
9951 (table
9952 (list
9953 (cons "%c" (plist-get p :fromto))
9954 (cons "%F" (plist-get p :from))
9955 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9956 (cons "%T" (plist-get p :to))
9957 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9958 (cons "%s" (plist-get p :subject))
9959 (cons "%d" (plist-get p :date))
9960 (cons "%m" (plist-get p :message-id)))))
9961 (when (string-match "%c" fmt)
9962 ;; Check if the user wrote this message
9963 (if (and org-from-is-user-regexp from to
9964 (save-match-data (string-match org-from-is-user-regexp from)))
9965 (setq fmt (replace-match "to %t" t t fmt))
9966 (setq fmt (replace-match "from %f" t t fmt))))
9967 (org-replace-escapes fmt table)))
9969 (defun org-make-org-heading-search-string (&optional string)
9970 "Make search string for the current headline or STRING."
9971 (let ((s (or string
9972 (and (derived-mode-p 'org-mode)
9973 (save-excursion
9974 (org-back-to-heading t)
9975 (org-element-property :raw-value (org-element-at-point))))))
9976 (lines org-context-in-file-links))
9977 (or string (setq s (concat "*" s))) ; Add * for headlines
9978 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9979 (when (and string (integerp lines) (> lines 0))
9980 (let ((slines (org-split-string s "\n")))
9981 (when (< lines (length slines))
9982 (setq s (mapconcat
9983 'identity
9984 (reverse (nthcdr (- (length slines) lines)
9985 (reverse slines))) "\n")))))
9986 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9988 (defun org-make-link-string (link &optional description)
9989 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9990 (unless (org-string-nw-p link) (error "Empty link"))
9991 (let ((uri (cond ((string-match org-link-types-re link)
9992 (concat (match-string 1 link)
9993 (org-link-escape (substring link (match-end 1)))))
9994 ;; For readability, url-encode internal links only
9995 ;; when absolutely needed (i.e, when they contain
9996 ;; square brackets). File links however, are
9997 ;; encoded since, e.g., spaces are significant.
9998 ((or (file-name-absolute-p link)
9999 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10000 (org-link-escape link))
10001 (t link)))
10002 (description
10003 (and (org-string-nw-p description)
10004 ;; Remove brackets from description, as they are fatal.
10005 (replace-regexp-in-string
10006 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10007 (org-trim description)))))
10008 (format "[[%s]%s]"
10010 (if description (format "[%s]" description) ""))))
10012 (defconst org-link-escape-chars
10013 ;;%20 %5B %5D %25
10014 '(?\s ?\[ ?\] ?%)
10015 "List of characters that should be escaped in a link when stored to Org.
10016 This is the list that is used for internal purposes.")
10018 (defconst org-link-escape-chars-browser
10019 ;;%20 %22
10020 '(?\s ?\")
10021 "List of characters to be escaped before handing over to the browser.
10022 If you consider using this constant then you probably want to use
10023 the function `org-link-escape-browser' instead. See there why
10024 this constant is a candidate to be removed once Org drops support
10025 for Emacs 24.1 and 24.2.")
10027 (defun org-link-escape (text &optional table merge)
10028 "Return percent escaped representation of TEXT.
10029 TEXT is a string with the text to escape.
10030 Optional argument TABLE is a list with characters that should be
10031 escaped. When nil, `org-link-escape-chars' is used.
10032 If optional argument MERGE is set, merge TABLE into
10033 `org-link-escape-chars'."
10034 (let ((characters-to-encode
10035 (cond ((null table) org-link-escape-chars)
10036 (merge (append org-link-escape-chars table))
10037 (t table))))
10038 (mapconcat
10039 (lambda (c)
10040 (if (or (memq c characters-to-encode)
10041 (and org-url-hexify-p (or (< c 32) (> c 126))))
10042 (mapconcat (lambda (e) (format "%%%.2X" e))
10043 (or (encode-coding-char c 'utf-8)
10044 (error "Unable to percent escape character: %c" c))
10046 (char-to-string c)))
10047 text "")))
10049 (defun org-link-escape-browser (text)
10050 "Escape some characters before handing over to the browser.
10051 This function is a candidate to be removed together with the
10052 constant `org-link-escape-chars-browser' once Org drops support
10053 for Emacs 24.1 and 24.2. All calls to this function will have to
10054 be replaced with `url-encode-url' which is available since Emacs
10055 24.3.1."
10056 ;; Example with the Org link
10057 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10058 ;; to open the browser with +subject:"Release 8.2" filled into the
10059 ;; query field: In this case the variable TEXT contains the
10060 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10061 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10062 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10063 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10064 (if (fboundp 'url-encode-url)
10065 (url-encode-url text)
10066 (if (org-string-match-p
10067 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10068 text)
10069 (org-link-escape text org-link-escape-chars-browser)
10070 text)))
10072 (defun org-link-unescape (str)
10073 "Unhex hexified Unicode parts in string STR.
10074 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10075 reciprocal of `org-link-escape', which see."
10076 (if (org-string-nw-p str)
10077 (replace-regexp-in-string
10078 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10079 str))
10081 (defun org-link-unescape-compound (hex)
10082 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10083 Note: this function also decodes single byte encodings like
10084 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10085 (save-match-data
10086 (let* ((bytes (cdr (split-string hex "%")))
10087 (ret "")
10088 (eat 0)
10089 (sum 0))
10090 (while bytes
10091 (let* ((val (string-to-number (pop bytes) 16))
10092 (shift-xor
10093 (if (= 0 eat)
10094 (cond
10095 ((>= val 252) (cons 6 252))
10096 ((>= val 248) (cons 5 248))
10097 ((>= val 240) (cons 4 240))
10098 ((>= val 224) (cons 3 224))
10099 ((>= val 192) (cons 2 192))
10100 (t (cons 0 0)))
10101 (cons 6 128))))
10102 (when (>= val 192) (setq eat (car shift-xor)))
10103 (setq val (logxor val (cdr shift-xor)))
10104 (setq sum (+ (lsh sum (car shift-xor)) val))
10105 (when (> eat 0) (setq eat (- eat 1)))
10106 (cond
10107 ((= 0 eat) ;multi byte
10108 (setq ret (concat ret (org-char-to-string sum)))
10109 (setq sum 0))
10110 ((not bytes) ; single byte(s)
10111 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10112 ret)))
10114 (defun org-link-unescape-single-byte-sequence (hex)
10115 "Unhexify hex-encoded single byte character sequences."
10116 (mapconcat (lambda (byte)
10117 (char-to-string (string-to-number byte 16)))
10118 (cdr (split-string hex "%")) ""))
10120 (defun org-xor (a b)
10121 "Exclusive or."
10122 (if a (not b) b))
10124 (defun org-fixup-message-id-for-http (s)
10125 "Replace special characters in a message id, so it can be used in an http query."
10126 (when (string-match "%" s)
10127 (setq s (mapconcat (lambda (c)
10128 (if (eq c ?%)
10129 "%25"
10130 (char-to-string c)))
10131 s "")))
10132 (while (string-match "<" s)
10133 (setq s (replace-match "%3C" t t s)))
10134 (while (string-match ">" s)
10135 (setq s (replace-match "%3E" t t s)))
10136 (while (string-match "@" s)
10137 (setq s (replace-match "%40" t t s)))
10140 (defun org-link-prettify (link)
10141 "Return a human-readable representation of LINK.
10142 The car of LINK must be a raw link.
10143 The cdr of LINK must be either a link description or nil."
10144 (let ((desc (or (cadr link) "<no description>")))
10145 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10146 "<" (car link) ">")))
10148 ;;;###autoload
10149 (defun org-insert-link-global ()
10150 "Insert a link like Org-mode does.
10151 This command can be called in any mode to insert a link in Org-mode syntax."
10152 (interactive)
10153 (org-load-modules-maybe)
10154 (org-run-like-in-org-mode 'org-insert-link))
10156 (defun org-insert-all-links (arg &optional pre post)
10157 "Insert all links in `org-stored-links'.
10158 When a universal prefix, do not delete the links from `org-stored-links'.
10159 When `ARG' is a number, insert the last N link(s).
10160 `PRE' and `POST' are optional arguments to define a string to
10161 prepend or to append."
10162 (interactive "P")
10163 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10164 (links (copy-sequence org-stored-links))
10165 (pr (or pre "- "))
10166 (po (or post "\n"))
10167 (cnt 1) l)
10168 (if (null org-stored-links)
10169 (message "No link to insert")
10170 (while (and (or (listp arg) (>= arg cnt))
10171 (setq l (if (listp arg)
10172 (pop links)
10173 (pop org-stored-links))))
10174 (setq cnt (1+ cnt))
10175 (insert pr)
10176 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10177 (insert po)))))
10179 (defun org-insert-last-stored-link (arg)
10180 "Insert the last link stored in `org-stored-links'."
10181 (interactive "p")
10182 (org-insert-all-links arg "" "\n"))
10184 (defun org-link-fontify-links-to-this-file ()
10185 "Fontify links to the current file in `org-stored-links'."
10186 (let ((f (buffer-file-name)) a b)
10187 (setq a (mapcar (lambda(l)
10188 (let ((ll (car l)))
10189 (when (and (string-match "^file:\\(.+\\)::" ll)
10190 (equal f (expand-file-name (match-string 1 ll))))
10191 ll)))
10192 org-stored-links))
10193 (when (featurep 'org-id)
10194 (setq b (mapcar (lambda(l)
10195 (let ((ll (car l)))
10196 (when (and (string-match "^id:\\(.+\\)$" ll)
10197 (equal f (expand-file-name
10198 (or (org-id-find-id-file
10199 (match-string 1 ll)) ""))))
10200 ll)))
10201 org-stored-links)))
10202 (mapcar (lambda(l)
10203 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10204 (delq nil (append a b)))))
10206 (defvar org--links-history nil)
10207 (defun org-insert-link (&optional complete-file link-location default-description)
10208 "Insert a link. At the prompt, enter the link.
10210 Completion can be used to insert any of the link protocol prefixes like
10211 http or ftp in use.
10213 The history can be used to select a link previously stored with
10214 `org-store-link'. When the empty string is entered (i.e. if you just
10215 press RET at the prompt), the link defaults to the most recently
10216 stored link. As SPC triggers completion in the minibuffer, you need to
10217 use M-SPC or C-q SPC to force the insertion of a space character.
10219 You will also be prompted for a description, and if one is given, it will
10220 be displayed in the buffer instead of the link.
10222 If there is already a link at point, this command will allow you to edit link
10223 and description parts.
10225 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10226 be selected using completion. The path to the file will be relative to the
10227 current directory if the file is in the current directory or a subdirectory.
10228 Otherwise, the link will be the absolute path as completed in the minibuffer
10229 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10230 option `org-link-file-path-type'.
10232 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10233 the current directory or below.
10235 With three \\[universal-argument] prefixes, negate the meaning of
10236 `org-keep-stored-link-after-insertion'.
10238 If `org-make-link-description-function' is non-nil, this function will be
10239 called with the link target, and the result will be the default
10240 link description.
10242 If the LINK-LOCATION parameter is non-nil, this value will be
10243 used as the link location instead of reading one interactively.
10245 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10246 be used as the default description."
10247 (interactive "P")
10248 (let* ((wcf (current-window-configuration))
10249 (origbuf (current-buffer))
10250 (region (when (org-region-active-p)
10251 (buffer-substring (region-beginning) (region-end))))
10252 (remove (and region (list (region-beginning) (region-end))))
10253 (desc region)
10254 (link link-location)
10255 (abbrevs org-link-abbrev-alist-local)
10256 entry all-prefixes auto-desc)
10257 (cond
10258 (link-location) ; specified by arg, just use it.
10259 ((org-in-regexp org-bracket-link-regexp 1)
10260 ;; We do have a link at point, and we are going to edit it.
10261 (setq remove (list (match-beginning 0) (match-end 0)))
10262 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10263 (setq link (read-string "Link: "
10264 (org-link-unescape
10265 (org-match-string-no-properties 1)))))
10266 ((or (org-in-regexp org-angle-link-re)
10267 (org-in-regexp org-plain-link-re))
10268 ;; Convert to bracket link
10269 (setq remove (list (match-beginning 0) (match-end 0))
10270 link (read-string "Link: "
10271 (org-remove-angle-brackets (match-string 0)))))
10272 ((member complete-file '((4) (16)))
10273 ;; Completing read for file names.
10274 (setq link (org-file-complete-link complete-file)))
10276 ;; Read link, with completion for stored links.
10277 (org-link-fontify-links-to-this-file)
10278 (org-switch-to-buffer-other-window "*Org Links*")
10279 (with-current-buffer "*Org Links*"
10280 (erase-buffer)
10281 (insert "Insert a link.
10282 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10283 (when org-stored-links
10284 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10285 (insert (mapconcat 'org-link-prettify
10286 (reverse org-stored-links) "\n")))
10287 (goto-char (point-min)))
10288 (let ((cw (selected-window)))
10289 (select-window (get-buffer-window "*Org Links*" 'visible))
10290 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10291 (unless (pos-visible-in-window-p (point-max))
10292 (org-fit-window-to-buffer))
10293 (and (window-live-p cw) (select-window cw)))
10294 (setq all-prefixes (append (mapcar 'car abbrevs)
10295 (mapcar 'car org-link-abbrev-alist)
10296 org-link-types))
10297 (unwind-protect
10298 ;; Fake a link history, containing the stored links.
10299 (let ((org--links-history
10300 (append (mapcar #'car org-stored-links)
10301 org-insert-link-history)))
10302 (setq link
10303 (org-completing-read
10304 "Link: "
10305 (append
10306 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10307 (mapcar #'car org-stored-links))
10308 nil nil nil
10309 'org--links-history
10310 (caar org-stored-links)))
10311 (unless (org-string-nw-p link) (user-error "No link selected"))
10312 (dolist (l org-stored-links)
10313 (when (equal link (cadr l))
10314 (setq link (car l))
10315 (setq auto-desc t)))
10316 (when (or (member link all-prefixes)
10317 (and (equal ":" (substring link -1))
10318 (member (substring link 0 -1) all-prefixes)
10319 (setq link (substring link 0 -1))))
10320 (setq link (with-current-buffer origbuf
10321 (org-link-try-special-completion link)))))
10322 (set-window-configuration wcf)
10323 (kill-buffer "*Org Links*"))
10324 (setq entry (assoc link org-stored-links))
10325 (or entry (push link org-insert-link-history))
10326 (setq desc (or desc (nth 1 entry)))))
10328 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10329 (not org-keep-stored-link-after-insertion))
10330 (setq org-stored-links (delq (assoc link org-stored-links)
10331 org-stored-links)))
10333 (when (and (string-match org-plain-link-re link)
10334 (not (string-match org-ts-regexp link)))
10335 ;; URL-like link, normalize the use of angular brackets.
10336 (setq link (org-remove-angle-brackets link)))
10338 ;; Check if we are linking to the current file with a search
10339 ;; option If yes, simplify the link by using only the search
10340 ;; option.
10341 (when (and buffer-file-name
10342 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10343 (let* ((path (match-string 1 link))
10344 (case-fold-search nil)
10345 (search (match-string 2 link)))
10346 (save-match-data
10347 (when (equal (file-truename buffer-file-name) (file-truename path))
10348 ;; We are linking to this same file, with a search option
10349 (setq link search)))))
10351 ;; Check if we can/should use a relative path. If yes, simplify the link
10352 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10353 (let* ((type (match-string 1 link))
10354 (path (match-string 2 link))
10355 (origpath path)
10356 (case-fold-search nil))
10357 (cond
10358 ((or (eq org-link-file-path-type 'absolute)
10359 (equal complete-file '(16)))
10360 (setq path (abbreviate-file-name (expand-file-name path))))
10361 ((eq org-link-file-path-type 'noabbrev)
10362 (setq path (expand-file-name path)))
10363 ((eq org-link-file-path-type 'relative)
10364 (setq path (file-relative-name path)))
10366 (save-match-data
10367 (if (string-match (concat "^" (regexp-quote
10368 (expand-file-name
10369 (file-name-as-directory
10370 default-directory))))
10371 (expand-file-name path))
10372 ;; We are linking a file with relative path name.
10373 (setq path (substring (expand-file-name path)
10374 (match-end 0)))
10375 (setq path (abbreviate-file-name (expand-file-name path)))))))
10376 (setq link (concat type path))
10377 (when (equal desc origpath)
10378 (setq desc path))))
10380 (if org-make-link-description-function
10381 (setq desc
10382 (or (condition-case nil
10383 (funcall org-make-link-description-function link desc)
10384 (error (progn (message "Can't get link description from `%s'"
10385 (symbol-name org-make-link-description-function))
10386 (sit-for 2) nil)))
10387 (read-string "Description: " default-description)))
10388 (if default-description (setq desc default-description)
10389 (setq desc (or (and auto-desc desc)
10390 (read-string "Description: " desc)))))
10392 (unless (string-match "\\S-" desc) (setq desc nil))
10393 (when remove (apply 'delete-region remove))
10394 (insert (org-make-link-string link desc))
10395 ;; Redisplay so as the new link has proper invisible characters.
10396 (sit-for 0)))
10398 (defun org-link-try-special-completion (type)
10399 "If there is completion support for link type TYPE, offer it."
10400 (let ((fun (intern (concat "org-" type "-complete-link"))))
10401 (if (functionp fun)
10402 (funcall fun)
10403 (read-string "Link (no completion support): " (concat type ":")))))
10405 (defun org-file-complete-link (&optional arg)
10406 "Create a file link using completion."
10407 (let ((file (org-iread-file-name "File: "))
10408 (pwd (file-name-as-directory (expand-file-name ".")))
10409 (pwd1 (file-name-as-directory (abbreviate-file-name
10410 (expand-file-name ".")))))
10411 (cond ((equal arg '(16))
10412 (concat "file:"
10413 (abbreviate-file-name (expand-file-name file))))
10414 ((string-match
10415 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10416 (concat "file:" (match-string 1 file)))
10417 ((string-match
10418 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10419 (expand-file-name file))
10420 (concat "file:"
10421 (match-string 1 (expand-file-name file))))
10422 (t (concat "file:" file)))))
10424 (defvar ido-enter-matching-directory)
10425 (defun org-iread-file-name (&rest args)
10426 "Read-file-name using `ido-mode' speedup if available.
10427 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10428 See `read-file-name' for a description of parameters."
10429 (org-without-partial-completion
10430 (if (and org-completion-use-ido
10431 (fboundp 'ido-read-file-name)
10432 (org-bound-and-true-p ido-mode)
10433 (listp (nth 1 args)))
10434 (let ((ido-enter-matching-directory nil))
10435 (apply #'ido-read-file-name args))
10436 (apply #'read-file-name args))))
10438 (defun org-completing-read (&rest args)
10439 "Completing-read with SPACE being a normal character."
10440 (let ((enable-recursive-minibuffers t)
10441 (minibuffer-local-completion-map
10442 (copy-keymap minibuffer-local-completion-map)))
10443 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10444 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10445 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10446 'org-time-stamp-inactive)
10447 (apply #'completing-read args)))
10449 (define-obsolete-function-alias
10450 'org-completing-read-no-i 'completing-read "Org 9.0")
10451 (define-obsolete-function-alias
10452 'org-icompleting-read 'completing-read "Org 9.0")
10454 ;;; Opening/following a link
10456 (defvar org-link-search-failed nil)
10458 (defvar org-open-link-functions nil
10459 "Hook for functions finding a plain text link.
10460 These functions must take a single argument, the link content.
10461 They will be called for links that look like [[link text][description]]
10462 when LINK TEXT does not have a protocol like \"http:\" and does not look
10463 like a filename (e.g. \"./blue.png\").
10465 These functions will be called *before* Org attempts to resolve the
10466 link by doing text searches in the current buffer - so if you want a
10467 link \"[[target]]\" to still find \"<<target>>\", your function should
10468 handle this as a special case.
10470 When the function does handle the link, it must return a non-nil value.
10471 If it decides that it is not responsible for this link, it must return
10472 nil to indicate that that Org-mode can continue with other options
10473 like exact and fuzzy text search.")
10475 (defun org-next-link (&optional search-backward)
10476 "Move forward to the next link.
10477 If the link is in hidden text, expose it."
10478 (interactive "P")
10479 (when (and org-link-search-failed (eq this-command last-command))
10480 (goto-char (point-min))
10481 (message "Link search wrapped back to beginning of buffer"))
10482 (setq org-link-search-failed nil)
10483 (let* ((pos (point))
10484 (ct (org-context))
10485 (a (assoc :link ct))
10486 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10487 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10488 ((looking-at org-any-link-re)
10489 ;; Don't stay stuck at link without an org-link face
10490 (forward-char (if search-backward -1 1))))
10491 (if (funcall srch-fun org-any-link-re nil t)
10492 (progn
10493 (goto-char (match-beginning 0))
10494 (when (outline-invisible-p) (org-show-context)))
10495 (goto-char pos)
10496 (setq org-link-search-failed t)
10497 (message "No further link found"))))
10499 (defun org-previous-link ()
10500 "Move backward to the previous link.
10501 If the link is in hidden text, expose it."
10502 (interactive)
10503 (funcall 'org-next-link t))
10505 (defun org-translate-link (s)
10506 "Translate a link string if a translation function has been defined."
10507 (with-temp-buffer
10508 (insert (org-trim s))
10509 (org-trim (org-element-interpret-data (org-element-context)))))
10511 (defun org-translate-link-from-planner (type path)
10512 "Translate a link from Emacs Planner syntax so that Org can follow it.
10513 This is still an experimental function, your mileage may vary."
10514 (cond
10515 ((member type '("http" "https" "news" "ftp"))
10516 ;; standard Internet links are the same.
10517 nil)
10518 ((and (equal type "irc") (string-match "^//" path))
10519 ;; Planner has two / at the beginning of an irc link, we have 1.
10520 ;; We should have zero, actually....
10521 (setq path (substring path 1)))
10522 ((and (equal type "lisp") (string-match "^/" path))
10523 ;; Planner has a slash, we do not.
10524 (setq type "elisp" path (substring path 1)))
10525 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10526 ;; A typical message link. Planner has the id after the final slash,
10527 ;; we separate it with a hash mark
10528 (setq path (concat (match-string 1 path) "#"
10529 (org-remove-angle-brackets (match-string 2 path))))))
10530 (cons type path))
10532 (defun org-find-file-at-mouse (ev)
10533 "Open file link or URL at mouse."
10534 (interactive "e")
10535 (mouse-set-point ev)
10536 (org-open-at-point 'in-emacs))
10538 (defun org-open-at-mouse (ev)
10539 "Open file link or URL at mouse.
10540 See the docstring of `org-open-file' for details."
10541 (interactive "e")
10542 (mouse-set-point ev)
10543 (when (eq major-mode 'org-agenda-mode)
10544 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10545 (org-open-at-point))
10547 (defvar org-window-config-before-follow-link nil
10548 "The window configuration before following a link.
10549 This is saved in case the need arises to restore it.")
10551 ;;;###autoload
10552 (defun org-open-at-point-global ()
10553 "Follow a link like Org-mode does.
10554 This command can be called in any mode to follow a link that has
10555 Org-mode syntax."
10556 (interactive)
10557 (org-run-like-in-org-mode 'org-open-at-point))
10559 ;;;###autoload
10560 (defun org-open-link-from-string (s &optional arg reference-buffer)
10561 "Open a link in the string S, as if it was in Org-mode."
10562 (interactive "sLink: \nP")
10563 (let ((reference-buffer (or reference-buffer (current-buffer))))
10564 (with-temp-buffer
10565 (let ((org-inhibit-startup (not reference-buffer)))
10566 (org-mode)
10567 (insert s)
10568 (goto-char (point-min))
10569 (when reference-buffer
10570 (setq org-link-abbrev-alist-local
10571 (with-current-buffer reference-buffer
10572 org-link-abbrev-alist-local)))
10573 (org-open-at-point arg reference-buffer)))))
10575 (defvar org-open-at-point-functions nil
10576 "Hook that is run when following a link at point.
10578 Functions in this hook must return t if they identify and follow
10579 a link at point. If they don't find anything interesting at point,
10580 they must return nil.")
10582 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10583 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10584 (defun org-open-at-point (&optional arg reference-buffer)
10585 "Open link, timestamp, footnote or tags at point.
10587 When point is on a link, follow it. Normally, files will be
10588 opened by an appropriate application. If the optional prefix
10589 argument ARG is non-nil, Emacs will visit the file. With
10590 a double prefix argument, try to open outside of Emacs, in the
10591 application the system uses for this file type.
10593 When point is on a timestamp, open the agenda at the day
10594 specified.
10596 When point is a footnote definition, move to the first reference
10597 found. If it is on a reference, move to the associated
10598 definition.
10600 When point is on a headline, display a list of every link in the
10601 entry, so it is possible to pick one, or all, of them. If point
10602 is on a tag, call `org-tags-view' instead.
10604 When optional argument REFERENCE-BUFFER is non-nil, it should
10605 specify a buffer from where the link search should happen. This
10606 is used internally by `org-open-link-from-string'.
10608 On top of syntactically correct links, this function will open
10609 the link at point in comments or comment blocks and the first
10610 link in a property drawer line."
10611 (interactive "P")
10612 ;; On a code block, open block's results.
10613 (unless (call-interactively 'org-babel-open-src-block-result)
10614 (org-load-modules-maybe)
10615 (setq org-window-config-before-follow-link (current-window-configuration))
10616 (org-remove-occur-highlights nil nil t)
10617 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10618 (let* ((context
10619 ;; Only consider supported types, even if they are not
10620 ;; the closest one.
10621 (org-element-lineage
10622 (org-element-context)
10623 '(clock comment comment-block footnote-definition
10624 footnote-reference headline inlinetask keyword link
10625 node-property timestamp)
10627 (type (org-element-type context))
10628 (value (org-element-property :value context)))
10629 (cond
10630 ((not context) (user-error "No link found"))
10631 ;; Exception: open timestamps and links in properties
10632 ;; drawers, keywords and comments.
10633 ((memq type '(comment comment-block keyword node-property))
10634 (cond ((org-in-regexp org-any-link-re)
10635 (org-open-link-from-string (match-string-no-properties 0)))
10636 ((or (org-in-regexp org-ts-regexp-both nil t)
10637 (org-in-regexp org-tsr-regexp-both nil t))
10638 (org-follow-timestamp-link))
10639 (t (user-error "No link found"))))
10640 ;; On a headline or an inlinetask, but not on a timestamp,
10641 ;; a link, a footnote reference or on tags.
10642 ((and (memq type '(headline inlinetask))
10643 ;; Not on tags.
10644 (progn (save-excursion (beginning-of-line)
10645 (looking-at org-complex-heading-regexp))
10646 (or (not (match-beginning 5))
10647 (< (point) (match-beginning 5)))))
10648 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10649 (links (car data))
10650 (links-end (cdr data)))
10651 (if links
10652 (dolist (link (if (stringp links) (list links) links))
10653 (search-forward link nil links-end)
10654 (goto-char (match-beginning 0))
10655 (org-open-at-point))
10656 (require 'org-attach)
10657 (org-attach-reveal 'if-exists))))
10658 ;; On a clock line, make sure point is on the timestamp
10659 ;; before opening it.
10660 ((and (eq type 'clock)
10661 value
10662 (>= (point) (org-element-property :begin value))
10663 (<= (point) (org-element-property :end value)))
10664 (org-follow-timestamp-link))
10665 ;; Do nothing on white spaces after an object.
10666 ((>= (point)
10667 (save-excursion
10668 (goto-char (org-element-property :end context))
10669 (skip-chars-backward " \t")
10670 (point)))
10671 (user-error "No link found"))
10672 ((eq type 'timestamp) (org-follow-timestamp-link))
10673 ;; On tags within a headline or an inlinetask.
10674 ((and (memq type '(headline inlinetask))
10675 (progn (save-excursion (beginning-of-line)
10676 (looking-at org-complex-heading-regexp))
10677 (and (match-beginning 5)
10678 (>= (point) (match-beginning 5)))))
10679 (org-tags-view arg (substring (match-string 5) 0 -1)))
10680 ((eq type 'link)
10681 ;; When link is located within the description of another
10682 ;; link (e.g., an inline image), always open the parent
10683 ;; link.
10684 (let*((link (let ((up (org-element-property :parent context)))
10685 (if (eq (org-element-type up) 'link) up context)))
10686 (type (org-element-property :type link))
10687 (path (org-link-unescape (org-element-property :path link))))
10688 ;; Switch back to REFERENCE-BUFFER needed when called in
10689 ;; a temporary buffer through `org-open-link-from-string'.
10690 (with-current-buffer (or reference-buffer (current-buffer))
10691 (cond
10692 ((equal type "file")
10693 (if (string-match "[*?{]" (file-name-nondirectory path))
10694 (dired path)
10695 ;; Look into `org-link-protocols' in order to find
10696 ;; a DEDICATED-FUNCTION to open file. The function
10697 ;; will be applied on raw link instead of parsed
10698 ;; link due to the limitation in `org-add-link-type'
10699 ;; ("open" function called with a single argument).
10700 ;; If no such function is found, fallback to
10701 ;; `org-open-file'.
10703 ;; Note : "file+emacs" and "file+sys" types are
10704 ;; hard-coded in order to escape the previous
10705 ;; limitation.
10706 (let* ((option (org-element-property :search-option link))
10707 (app (org-element-property :application link))
10708 (dedicated-function
10709 (nth 1 (assoc app org-link-protocols))))
10710 (if dedicated-function
10711 (funcall dedicated-function
10712 (concat path
10713 (and option (concat "::" option))))
10714 (apply #'org-open-file
10715 path
10716 (cond (arg)
10717 ((equal app "emacs") 'emacs)
10718 ((equal app "sys") 'system))
10719 (cond ((not option) nil)
10720 ((org-string-match-p "\\`[0-9]+\\'" option)
10721 (list (string-to-number option)))
10722 (t (list nil
10723 (org-link-unescape option)))))))))
10724 ((assoc type org-link-protocols)
10725 (funcall (nth 1 (assoc type org-link-protocols)) path))
10726 ((equal type "help")
10727 (let ((f-or-v (intern path)))
10728 (cond ((fboundp f-or-v) (describe-function f-or-v))
10729 ((boundp f-or-v) (describe-variable f-or-v))
10730 (t (error "Not a known function or variable")))))
10731 ((member type '("http" "https" "ftp" "mailto" "news"))
10732 (browse-url (org-link-escape-browser (concat type ":" path))))
10733 ((equal type "doi")
10734 (browse-url
10735 (org-link-escape-browser (concat org-doi-server-url path))))
10736 ((equal type "message") (browse-url (concat type ":" path)))
10737 ((equal type "shell")
10738 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10739 (cmd path))
10740 (if (or (and (org-string-nw-p
10741 org-confirm-shell-link-not-regexp)
10742 (string-match
10743 org-confirm-shell-link-not-regexp cmd))
10744 (not org-confirm-shell-link-function)
10745 (funcall org-confirm-shell-link-function
10746 (format "Execute \"%s\" in shell? "
10747 (org-add-props cmd nil
10748 'face 'org-warning))))
10749 (progn
10750 (message "Executing %s" cmd)
10751 (shell-command cmd buf)
10752 (when (featurep 'midnight)
10753 (setq clean-buffer-list-kill-buffer-names
10754 (cons (buffer-name buf)
10755 clean-buffer-list-kill-buffer-names))))
10756 (user-error "Abort"))))
10757 ((equal type "elisp")
10758 (let ((cmd path))
10759 (if (or (and (org-string-nw-p
10760 org-confirm-elisp-link-not-regexp)
10761 (org-string-match-p
10762 org-confirm-elisp-link-not-regexp cmd))
10763 (not org-confirm-elisp-link-function)
10764 (funcall org-confirm-elisp-link-function
10765 (format "Execute \"%s\" as elisp? "
10766 (org-add-props cmd nil
10767 'face 'org-warning))))
10768 (message "%s => %s" cmd
10769 (if (eq (string-to-char cmd) ?\()
10770 (eval (read cmd))
10771 (call-interactively (read cmd))))
10772 (user-error "Abort"))))
10773 ((equal type "id")
10774 (require 'org-id)
10775 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10776 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10777 (unless (run-hook-with-args-until-success
10778 'org-open-link-functions path)
10779 (if (not arg) (org-mark-ring-push)
10780 (switch-to-buffer-other-window
10781 (org-get-buffer-for-internal-link (current-buffer))))
10782 (let ((destination
10783 (org-with-wide-buffer
10784 (if (equal type "radio")
10785 (org-search-radio-target
10786 (org-element-property :path link))
10787 (org-link-search
10788 (if (member type '("custom-id" "coderef"))
10789 (org-element-property :raw-link link)
10790 path)
10791 ;; Prevent fuzzy links from matching
10792 ;; themselves.
10793 (and (equal type "fuzzy")
10794 (+ 2 (org-element-property :begin link)))))
10795 (point))))
10796 (unless (and (<= (point-min) destination)
10797 (>= (point-max) destination))
10798 (widen))
10799 (goto-char destination))))
10800 (t (browse-url-at-point))))))
10801 ;; On a footnote reference or at a footnote definition's label.
10802 ((or (eq type 'footnote-reference)
10803 (and (eq type 'footnote-definition)
10804 (save-excursion
10805 ;; Do not validate action when point is on the
10806 ;; spaces right after the footnote label, in
10807 ;; order to be on par with behaviour on links.
10808 (skip-chars-forward " \t")
10809 (let ((begin
10810 (org-element-property :contents-begin context)))
10811 (if begin (< (point) begin)
10812 (= (org-element-property :post-affiliated context)
10813 (line-beginning-position)))))))
10814 (org-footnote-action))
10815 (t (user-error "No link found")))))
10816 (run-hook-with-args 'org-follow-link-hook)))
10818 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10819 "Offer links in the current entry and return the selected link.
10820 If there is only one link, return it.
10821 If NTH is an integer, return the NTH link found.
10822 If ZERO is a string, check also this string for a link, and if
10823 there is one, return it."
10824 (with-current-buffer buffer
10825 (save-excursion
10826 (save-restriction
10827 (widen)
10828 (goto-char marker)
10829 (let ((cnt ?0)
10830 have-zero end links link c)
10831 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10832 (push (match-string 0 zero) links)
10833 (setq cnt (1- cnt) have-zero t))
10834 (save-excursion
10835 (org-back-to-heading t)
10836 (setq end (save-excursion (outline-next-heading) (point)))
10837 (while (re-search-forward org-any-link-re end t)
10838 (push (match-string 0) links))
10839 (setq links (org-uniquify (reverse links))))
10840 (cond
10841 ((null links)
10842 (message "No links"))
10843 ((equal (length links) 1)
10844 (setq link (car links)))
10845 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10846 (setq link (nth (if have-zero nth (1- nth)) links)))
10847 (t ; we have to select a link
10848 (save-excursion
10849 (save-window-excursion
10850 (delete-other-windows)
10851 (with-output-to-temp-buffer "*Select Link*"
10852 (dolist (l links)
10853 (cond
10854 ((not (string-match org-bracket-link-regexp l))
10855 (princ (format "[%c] %s\n" (cl-incf cnt)
10856 (org-remove-angle-brackets l))))
10857 ((match-end 3)
10858 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10859 (match-string 3 l) (match-string 1 l))))
10860 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10861 (match-string 1 l)))))))
10862 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10863 (message "Select link to open, RET to open all:")
10864 (setq c (read-char-exclusive))
10865 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10866 (when (equal c ?q) (user-error "Abort"))
10867 (if (equal c ?\C-m)
10868 (setq link links)
10869 (setq nth (- c ?0))
10870 (when have-zero (setq nth (1+ nth)))
10871 (unless (and (integerp nth) (>= (length links) nth))
10872 (user-error "Invalid link selection"))
10873 (setq link (nth (1- nth) links)))))
10874 (cons link end))))))
10876 ;; TODO: These functions are deprecated since `org-open-at-point'
10877 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10878 (defun org-open-file-with-system (path)
10879 "Open file at PATH using the system way of opening it."
10880 (org-open-file path 'system))
10881 (defun org-open-file-with-emacs (path)
10882 "Open file at PATH in Emacs."
10883 (org-open-file path 'emacs))
10886 ;;; File search
10888 (defvar org-create-file-search-functions nil
10889 "List of functions to construct the right search string for a file link.
10890 These functions are called in turn with point at the location to
10891 which the link should point.
10893 A function in the hook should first test if it would like to
10894 handle this file type, for example by checking the `major-mode'
10895 or the file extension. If it decides not to handle this file, it
10896 should just return nil to give other functions a chance. If it
10897 does handle the file, it must return the search string to be used
10898 when following the link. The search string will be part of the
10899 file link, given after a double colon, and `org-open-at-point'
10900 will automatically search for it. If special measures must be
10901 taken to make the search successful, another function should be
10902 added to the companion hook `org-execute-file-search-functions',
10903 which see.
10905 A function in this hook may also use `setq' to set the variable
10906 `description' to provide a suggestion for the descriptive text to
10907 be used for this link when it gets inserted into an Org-mode
10908 buffer with \\[org-insert-link].")
10910 (defvar org-execute-file-search-functions nil
10911 "List of functions to execute a file search triggered by a link.
10913 Functions added to this hook must accept a single argument, the
10914 search string that was part of the file link, the part after the
10915 double colon. The function must first check if it would like to
10916 handle this search, for example by checking the `major-mode' or
10917 the file extension. If it decides not to handle this search, it
10918 should just return nil to give other functions a chance. If it
10919 does handle the search, it must return a non-nil value to keep
10920 other functions from trying.
10922 Each function can access the current prefix argument through the
10923 variable `current-prefix-arg'. Note that a single prefix is used
10924 to force opening a link in Emacs, so it may be good to only use a
10925 numeric or double prefix to guide the search function.
10927 In case this is needed, a function in this hook can also restore
10928 the window configuration before `org-open-at-point' was called using:
10930 \(set-window-configuration org-window-config-before-follow-link)")
10932 (defun org-search-radio-target (target)
10933 "Search a radio target matching TARGET in current buffer.
10934 White spaces are not significant."
10935 (let ((re (format "<<<%s>>>"
10936 (mapconcat #'regexp-quote
10937 (org-split-string target "[ \t\n]+")
10938 "[ \t]+\\(?:\n[ \t]*\\)?")))
10939 (origin (point)))
10940 (goto-char (point-min))
10941 (catch :radio-match
10942 (while (re-search-forward re nil t)
10943 (backward-char)
10944 (let ((object (org-element-context)))
10945 (when (eq (org-element-type object) 'radio-target)
10946 (goto-char (org-element-property :begin object))
10947 (org-show-context 'link-search)
10948 (throw :radio-match nil))))
10949 (goto-char origin)
10950 (user-error "No match for radio target: %s" target))))
10952 (defun org-link-search (s &optional avoid-pos stealth)
10953 "Search for a search string S.
10955 If S starts with \"#\", it triggers a custom ID search.
10957 If S is enclosed within parenthesis, it initiates a coderef
10958 search.
10960 If S is surrounded by forward slashes, it is interpreted as
10961 a regular expression. In Org mode files, this will create an
10962 `org-occur' sparse tree. In ordinary files, `occur' will be used
10963 to list matches. If the current buffer is in `dired-mode', grep
10964 will be used to search in all files.
10966 When AVOID-POS is given, ignore matches near that position.
10968 When optional argument STEALTH is non-nil, do not modify
10969 visibility around point, thus ignoring `org-show-context-detail'
10970 variable.
10972 Search is case-insensitive and ignores white spaces. Return type
10973 of matched result, with is either `dedicated' or `fuzzy'."
10974 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10975 (let* ((case-fold-search t)
10976 (origin (point))
10977 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10978 (words (org-split-string s "[ \t\n]+"))
10979 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10980 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10981 type)
10982 (cond
10983 ;; Check if there are any special search functions.
10984 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10985 ((eq (string-to-char s) ?#)
10986 ;; Look for a custom ID S if S starts with "#".
10987 (let* ((id (substring normalized 1))
10988 (match (org-find-property "CUSTOM_ID" id)))
10989 (if match (progn (goto-char match) (setf type 'dedicated))
10990 (error "No match for custom ID: %s" id))))
10991 ((string-match "\\`(\\(.*\\))\\'" normalized)
10992 ;; Look for coderef targets if S is enclosed within parenthesis.
10993 (let ((coderef (match-string-no-properties 1 normalized))
10994 (re (substring s-single-re 1 -1)))
10995 (goto-char (point-min))
10996 (catch :coderef-match
10997 (while (re-search-forward re nil t)
10998 (let ((element (org-element-at-point)))
10999 (when (and (memq (org-element-type element)
11000 '(example-block src-block))
11001 ;; Build proper regexp according to current
11002 ;; block's label format.
11003 (let ((label-fmt
11004 (regexp-quote
11005 (or (org-element-property :label-fmt element)
11006 org-coderef-label-format))))
11007 (save-excursion
11008 (beginning-of-line)
11009 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11010 (format label-fmt coderef))))))
11011 (setq type 'dedicated)
11012 (goto-char (match-beginning 1))
11013 (throw :coderef-match nil))))
11014 (goto-char origin)
11015 (error "No match for coderef: %s" coderef))))
11016 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11017 ;; Look for a regular expression.
11018 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11019 (match-string 1 s)))
11020 ;; Fuzzy links.
11022 (let ((starred (eq (string-to-char normalized) ?*)))
11023 (cond
11024 ;; Look for targets, only if not in a headline search.
11025 ((and (not starred)
11026 (let ((target (format "<<%s>>" s-multi-re)))
11027 (catch :target-match
11028 (goto-char (point-min))
11029 (while (re-search-forward target nil t)
11030 (backward-char)
11031 (let ((context (org-element-context)))
11032 (when (eq (org-element-type context) 'target)
11033 (setq type 'dedicated)
11034 (goto-char (org-element-property :begin context))
11035 (throw :target-match t))))
11036 nil))))
11037 ;; Look for elements named after S, only if not in a headline
11038 ;; search.
11039 ((and (not starred)
11040 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11041 (catch :name-match
11042 (goto-char (point-min))
11043 (while (re-search-forward name nil t)
11044 (let ((element (org-element-at-point)))
11045 (when (equal (org-split-string
11046 (org-element-property :name element)
11047 "[ \t]+")
11048 words)
11049 (setq type 'dedicated)
11050 (beginning-of-line)
11051 (throw :name-match t))))
11052 nil))))
11053 ;; Regular text search. Prefer headlines in Org mode
11054 ;; buffers.
11055 ((and (derived-mode-p 'org-mode)
11056 (let* ((wspace "[ \t]")
11057 (wspaceopt (concat wspace "*"))
11058 (cookie (concat "\\(?:"
11059 wspaceopt
11060 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11061 wspaceopt
11062 "\\)"))
11063 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11064 (re (concat
11065 org-outline-regexp-bol
11066 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11067 "\\(?:\\[#.\\][ \t]+\\)?"
11068 "\\(?:" org-comment-string "[ \t]+\\)?"
11069 sep "?"
11070 (let ((title (mapconcat #'regexp-quote
11071 words
11072 sep)))
11073 (if starred (substring title 1) title))
11074 sep "?"
11075 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11076 "[ \t]*$")))
11077 (goto-char (point-min))
11078 (re-search-forward re nil t)))
11079 (goto-char (match-beginning 0))
11080 (setq type 'dedicated))
11081 ;; Offer to create non-existent headline depending on
11082 ;; `org-link-search-must-match-exact-headline'.
11083 ((and (derived-mode-p 'org-mode)
11084 (not org-link-search-inhibit-query)
11085 (eq org-link-search-must-match-exact-headline 'query-to-create)
11086 (yes-or-no-p "No match - create this as a new heading? "))
11087 (goto-char (point-max))
11088 (unless (bolp) (newline))
11089 (org-insert-heading nil t t)
11090 (insert s "\n")
11091 (beginning-of-line 0))
11092 ;; Only headlines are looked after. No need to process
11093 ;; further: throw an error.
11094 ((and (derived-mode-p 'org-mode)
11095 (or starred org-link-search-must-match-exact-headline))
11096 (goto-char origin)
11097 (error "No match for fuzzy expression: %s" normalized))
11098 ;; Regular text search.
11099 ((catch :fuzzy-match
11100 (goto-char (point-min))
11101 (while (re-search-forward s-multi-re nil t)
11102 ;; Skip match if it contains AVOID-POS or it is included
11103 ;; in a link with a description but outside the
11104 ;; description.
11105 (unless (or (and avoid-pos
11106 (<= (match-beginning 0) avoid-pos)
11107 (> (match-end 0) avoid-pos))
11108 (and (save-match-data
11109 (org-in-regexp org-bracket-link-regexp))
11110 (match-beginning 3)
11111 (or (> (match-beginning 3) (point))
11112 (<= (match-end 3) (point)))
11113 (org-element-lineage
11114 (save-match-data (org-element-context))
11115 '(link) t)))
11116 (goto-char (match-beginning 0))
11117 (setq type 'fuzzy)
11118 (throw :fuzzy-match t)))
11119 nil))
11120 ;; All failed. Throw an error.
11121 (t (goto-char origin)
11122 (error "No match for fuzzy expression: %s" normalized))))))
11123 ;; Disclose surroundings of match, if appropriate.
11124 (when (and (derived-mode-p 'org-mode) (not stealth))
11125 (org-show-context 'link-search))
11126 type))
11128 (defun org-get-buffer-for-internal-link (buffer)
11129 "Return a buffer to be used for displaying the link target of internal links."
11130 (cond
11131 ((not org-display-internal-link-with-indirect-buffer)
11132 buffer)
11133 ((string-match "(Clone)$" (buffer-name buffer))
11134 (message "Buffer is already a clone, not making another one")
11135 ;; we also do not modify visibility in this case
11136 buffer)
11137 (t ; make a new indirect buffer for displaying the link
11138 (let* ((bn (buffer-name buffer))
11139 (ibn (concat bn "(Clone)"))
11140 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11141 (with-current-buffer ib (org-overview))
11142 ib))))
11144 (defun org-do-occur (regexp &optional cleanup)
11145 "Call the Emacs command `occur'.
11146 If CLEANUP is non-nil, remove the printout of the regular expression
11147 in the *Occur* buffer. This is useful if the regex is long and not useful
11148 to read."
11149 (occur regexp)
11150 (when cleanup
11151 (let ((cwin (selected-window)) win beg end)
11152 (when (setq win (get-buffer-window "*Occur*"))
11153 (select-window win))
11154 (goto-char (point-min))
11155 (when (re-search-forward "match[a-z]+" nil t)
11156 (setq beg (match-end 0))
11157 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11158 (setq end (1- (match-beginning 0)))))
11159 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11160 (goto-char (point-min))
11161 (select-window cwin))))
11163 ;;; The mark ring for links jumps
11165 (defvar org-mark-ring nil
11166 "Mark ring for positions before jumps in Org-mode.")
11167 (defvar org-mark-ring-last-goto nil
11168 "Last position in the mark ring used to go back.")
11169 ;; Fill and close the ring
11170 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11171 (dotimes (_ org-mark-ring-length)
11172 (push (make-marker) org-mark-ring))
11173 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11174 org-mark-ring)
11176 (defun org-mark-ring-push (&optional pos buffer)
11177 "Put the current position or POS into the mark ring and rotate it."
11178 (interactive)
11179 (setq pos (or pos (point)))
11180 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11181 (move-marker (car org-mark-ring)
11182 (or pos (point))
11183 (or buffer (current-buffer)))
11184 (message "%s"
11185 (substitute-command-keys
11186 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11188 (defun org-mark-ring-goto (&optional n)
11189 "Jump to the previous position in the mark ring.
11190 With prefix arg N, jump back that many stored positions. When
11191 called several times in succession, walk through the entire ring.
11192 Org-mode commands jumping to a different position in the current file,
11193 or to another Org-mode file, automatically push the old position
11194 onto the ring."
11195 (interactive "p")
11196 (let (p m)
11197 (if (eq last-command this-command)
11198 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11199 (setq p org-mark-ring))
11200 (setq org-mark-ring-last-goto p)
11201 (setq m (car p))
11202 (org-pop-to-buffer-same-window (marker-buffer m))
11203 (goto-char m)
11204 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11206 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11207 ;;; Emacs 24.4+
11208 (defun org-remove-angle-brackets (s)
11209 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11210 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11212 (defun org-add-angle-brackets (s)
11213 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11214 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11216 (defun org-remove-double-quotes (s)
11217 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11218 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11221 ;;; Following specific links
11223 (defvar org-agenda-buffer-tmp-name)
11224 (defvar org-agenda-start-on-weekday)
11225 (defun org-follow-timestamp-link ()
11226 "Open an agenda view for the time-stamp date/range at point."
11227 (cond
11228 ((org-at-date-range-p t)
11229 (let ((org-agenda-start-on-weekday)
11230 (t1 (match-string 1))
11231 (t2 (match-string 2)) tt1 tt2)
11232 (setq tt1 (time-to-days (org-time-string-to-time t1))
11233 tt2 (time-to-days (org-time-string-to-time t2)))
11234 (let ((org-agenda-buffer-tmp-name
11235 (format "*Org Agenda(a:%s)"
11236 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11237 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11238 ((org-at-timestamp-p t)
11239 (let ((org-agenda-buffer-tmp-name
11240 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11241 (org-agenda-list nil (time-to-days (org-time-string-to-time
11242 (substring (match-string 1) 0 10)))
11243 1)))
11244 (t (error "This should not happen"))))
11247 ;;; Following file links
11248 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11249 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11250 (declare-function mailcap-mime-info
11251 "mailcap" (string &optional request no-decode))
11252 (defvar org-wait nil)
11253 (defun org-open-file (path &optional in-emacs line search)
11254 "Open the file at PATH.
11255 First, this expands any special file name abbreviations. Then the
11256 configuration variable `org-file-apps' is checked if it contains an
11257 entry for this file type, and if yes, the corresponding command is launched.
11259 If no application is found, Emacs simply visits the file.
11261 With optional prefix argument IN-EMACS, Emacs will visit the file.
11262 With a double \\[universal-argument] \\[universal-argument] \
11263 prefix arg, Org tries to avoid opening in Emacs
11264 and to use an external application to visit the file.
11266 Optional LINE specifies a line to go to, optional SEARCH a string
11267 to search for. If LINE or SEARCH is given, the file will be
11268 opened in Emacs, unless an entry from org-file-apps that makes
11269 use of groups in a regexp matches.
11271 If you want to change the way frames are used when following a
11272 link, please customize `org-link-frame-setup'.
11274 If the file does not exist, an error is thrown."
11275 (let* ((file (if (equal path "")
11276 buffer-file-name
11277 (substitute-in-file-name (expand-file-name path))))
11278 (file-apps (append org-file-apps (org-default-apps)))
11279 (apps (cl-remove-if
11280 'org-file-apps-entry-match-against-dlink-p file-apps))
11281 (apps-dlink (cl-remove-if-not
11282 'org-file-apps-entry-match-against-dlink-p file-apps))
11283 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11284 (dirp (unless remp (file-directory-p file)))
11285 (file (if (and dirp org-open-directory-means-index-dot-org)
11286 (concat (file-name-as-directory file) "index.org")
11287 file))
11288 (a-m-a-p (assq 'auto-mode apps))
11289 (dfile (downcase file))
11290 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11291 (link (cond ((and (eq line nil)
11292 (eq search nil))
11293 file)
11294 (line
11295 (concat file "::" (number-to-string line)))
11296 (search
11297 (concat file "::" search))))
11298 (dlink (downcase link))
11299 (old-buffer (current-buffer))
11300 (old-pos (point))
11301 (old-mode major-mode)
11302 ext cmd link-match-data)
11303 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11304 (setq ext (match-string 1 dfile))
11305 (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11306 (setq ext (match-string 1 dfile))))
11307 (cond
11308 ((member in-emacs '((16) system))
11309 (setq cmd (cdr (assoc 'system apps))))
11310 (in-emacs (setq cmd 'emacs))
11312 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11313 (and dirp (cdr (assoc 'directory apps)))
11314 ; first, try matching against apps-dlink
11315 ; if we get a match here, store the match data for later
11316 (let ((match (assoc-default dlink apps-dlink
11317 'string-match)))
11318 (if match
11319 (progn (setq link-match-data (match-data))
11320 match)
11321 (progn (setq in-emacs (or in-emacs line search))
11322 nil))) ; if we have no match in apps-dlink,
11323 ; always open the file in emacs if line or search
11324 ; is given (for backwards compatibility)
11325 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11326 'string-match)
11327 (cdr (assoc ext apps))
11328 (cdr (assoc t apps))))))
11329 (when (eq cmd 'system)
11330 (setq cmd (cdr (assoc 'system apps))))
11331 (when (eq cmd 'default)
11332 (setq cmd (cdr (assoc t apps))))
11333 (when (eq cmd 'mailcap)
11334 (require 'mailcap)
11335 (mailcap-parse-mailcaps)
11336 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11337 (command (mailcap-mime-info mime-type)))
11338 (if (stringp command)
11339 (setq cmd command)
11340 (setq cmd 'emacs))))
11341 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11342 (not (file-exists-p file))
11343 (not org-open-non-existing-files))
11344 (user-error "No such file: %s" file))
11345 (cond
11346 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11347 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11348 (while (string-match "['\"]%s['\"]" cmd)
11349 (setq cmd (replace-match "%s" t t cmd)))
11350 (while (string-match "%s" cmd)
11351 (setq cmd (replace-match
11352 (save-match-data
11353 (shell-quote-argument
11354 (convert-standard-filename file)))
11355 t t cmd)))
11357 ;; Replace "%1", "%2" etc. in command with group matches from regex
11358 (save-match-data
11359 (let ((match-index 1)
11360 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11361 (set-match-data link-match-data)
11362 (while (<= match-index number-of-groups)
11363 (let ((regex (concat "%" (number-to-string match-index)))
11364 (replace-with (match-string match-index dlink)))
11365 (while (string-match regex cmd)
11366 (setq cmd (replace-match replace-with t t cmd))))
11367 (setq match-index (+ match-index 1)))))
11369 (save-window-excursion
11370 (message "Running %s...done" cmd)
11371 (start-process-shell-command cmd nil cmd)
11372 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11373 ((or (stringp cmd)
11374 (eq cmd 'emacs))
11375 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11376 (widen)
11377 (if line (progn (org-goto-line line)
11378 (when (derived-mode-p 'org-mode)
11379 (org-reveal)))
11380 (when search (org-link-search search))))
11381 ((consp cmd)
11382 (save-match-data
11383 (set-match-data link-match-data)
11384 (eval cmd `((file . ,(convert-standard-filename file))))))
11385 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11386 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11387 (or (not (equal old-buffer (current-buffer)))
11388 (not (equal old-pos (point))))
11389 (org-mark-ring-push old-pos old-buffer))))
11391 (defun org-file-apps-entry-match-against-dlink-p (entry)
11392 "This function returns non-nil if `entry' uses a regular
11393 expression which should be matched against the whole link by
11394 org-open-file.
11396 It assumes that is the case when the entry uses a regular
11397 expression which has at least one grouping construct and the
11398 action is either a lisp form or a command string containing
11399 `%1', i.e. using at least one subexpression match as a
11400 parameter."
11401 (let ((selector (car entry))
11402 (action (cdr entry)))
11403 (if (stringp selector)
11404 (and (> (regexp-opt-depth selector) 0)
11405 (or (and (stringp action)
11406 (string-match "%[0-9]" action))
11407 (consp action)))
11408 nil)))
11410 (defun org-default-apps ()
11411 "Return the default applications for this operating system."
11412 (cond
11413 ((eq system-type 'darwin)
11414 org-file-apps-defaults-macosx)
11415 ((eq system-type 'windows-nt)
11416 org-file-apps-defaults-windowsnt)
11417 (t org-file-apps-defaults-gnu)))
11419 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11420 "Convert extensions to regular expressions in the cars of LIST.
11421 Also, weed out any non-string entries, because the return value is used
11422 only for regexp matching.
11423 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11424 point to the symbol `emacs', indicating that the file should
11425 be opened in Emacs."
11426 (append
11427 (delq nil
11428 (mapcar (lambda (x)
11429 (unless (not (stringp (car x)))
11430 (if (string-match "\\W" (car x))
11432 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11433 list))
11434 (when add-auto-mode
11435 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11437 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11438 (defun org-file-remote-p (file)
11439 "Test whether FILE specifies a location on a remote system.
11440 Return non-nil if the location is indeed remote.
11442 For example, the filename \"/user@host:/foo\" specifies a location
11443 on the system \"/user@host:\"."
11444 (cond ((fboundp 'file-remote-p)
11445 (file-remote-p file))
11446 ((fboundp 'tramp-handle-file-remote-p)
11447 (tramp-handle-file-remote-p file))
11448 ((and (boundp 'ange-ftp-name-format)
11449 (string-match (car ange-ftp-name-format) file))
11450 t)))
11453 ;;;; Refiling
11455 (defun org-get-org-file ()
11456 "Read a filename, with default directory `org-directory'."
11457 (let ((default (or org-default-notes-file remember-data-file)))
11458 (read-file-name (format "File name [%s]: " default)
11459 (file-name-as-directory org-directory)
11460 default)))
11462 (defun org-notes-order-reversed-p ()
11463 "Check if the current file should receive notes in reversed order."
11464 (cond
11465 ((not org-reverse-note-order) nil)
11466 ((eq t org-reverse-note-order) t)
11467 ((not (listp org-reverse-note-order)) nil)
11468 (t (catch 'exit
11469 (dolist (entry org-reverse-note-order)
11470 (when (string-match (car entry) buffer-file-name)
11471 (throw 'exit (cdr entry))))))))
11473 (defvar org-refile-target-table nil
11474 "The list of refile targets, created by `org-refile'.")
11476 (defvar org-agenda-new-buffers nil
11477 "Buffers created to visit agenda files.")
11479 (defvar org-refile-cache nil
11480 "Cache for refile targets.")
11482 (defvar org-refile-markers nil
11483 "All the markers used for caching refile locations.")
11485 (defun org-refile-marker (pos)
11486 "Get a new refile marker, but only if caching is in use."
11487 (if (not org-refile-use-cache)
11489 (let ((m (make-marker)))
11490 (move-marker m pos)
11491 (push m org-refile-markers)
11492 m)))
11494 (defun org-refile-cache-clear ()
11495 "Clear the refile cache and disable all the markers."
11496 (dolist (m org-refile-markers) (move-marker m nil))
11497 (setq org-refile-markers nil)
11498 (setq org-refile-cache nil)
11499 (message "Refile cache has been cleared"))
11501 (defun org-refile-cache-check-set (set)
11502 "Check if all the markers in the cache still have live buffers."
11503 (let (marker)
11504 (catch 'exit
11505 (while (and set (setq marker (nth 3 (pop set))))
11506 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11507 (when (and marker (null (marker-buffer marker)))
11508 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11509 (sit-for 3)
11510 (throw 'exit nil)))
11511 t)))
11513 (defun org-refile-cache-put (set &rest identifiers)
11514 "Push the refile targets SET into the cache, under IDENTIFIERS."
11515 (let* ((key (sha1 (prin1-to-string identifiers)))
11516 (entry (assoc key org-refile-cache)))
11517 (if entry
11518 (setcdr entry set)
11519 (push (cons key set) org-refile-cache))))
11521 (defun org-refile-cache-get (&rest identifiers)
11522 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11523 (cond
11524 ((not org-refile-cache) nil)
11525 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11527 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11528 org-refile-cache))))
11529 (and set (org-refile-cache-check-set set) set)))))
11531 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11532 "Produce a table with refile targets."
11533 (let ((case-fold-search nil)
11534 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11535 (entries (or org-refile-targets '((nil . (:level . 1)))))
11536 targets tgs txt re files desc descre fast-path-p level pos0)
11537 (message "Getting targets...")
11538 (with-current-buffer (or default-buffer (current-buffer))
11539 (dolist (entry entries)
11540 (setq files (car entry) desc (cdr entry))
11541 (setq fast-path-p nil)
11542 (cond
11543 ((null files) (setq files (list (current-buffer))))
11544 ((eq files 'org-agenda-files)
11545 (setq files (org-agenda-files 'unrestricted)))
11546 ((and (symbolp files) (fboundp files))
11547 (setq files (funcall files)))
11548 ((and (symbolp files) (boundp files))
11549 (setq files (symbol-value files))))
11550 (when (stringp files) (setq files (list files)))
11551 (cond
11552 ((eq (car desc) :tag)
11553 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11554 ((eq (car desc) :todo)
11555 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11556 ((eq (car desc) :regexp)
11557 (setq descre (cdr desc)))
11558 ((eq (car desc) :level)
11559 (setq descre (concat "^\\*\\{" (number-to-string
11560 (if org-odd-levels-only
11561 (1- (* 2 (cdr desc)))
11562 (cdr desc)))
11563 "\\}[ \t]")))
11564 ((eq (car desc) :maxlevel)
11565 (setq fast-path-p t)
11566 (setq descre (concat "^\\*\\{1," (number-to-string
11567 (if org-odd-levels-only
11568 (1- (* 2 (cdr desc)))
11569 (cdr desc)))
11570 "\\}[ \t]")))
11571 (t (error "Bad refiling target description %s" desc)))
11572 (dolist (f files)
11573 (with-current-buffer
11574 (if (bufferp f) f (org-get-agenda-file-buffer f))
11576 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11577 (progn
11578 (when (bufferp f) (setq f (buffer-file-name
11579 (buffer-base-buffer f))))
11580 (setq f (and f (expand-file-name f)))
11581 (when (eq org-refile-use-outline-path 'file)
11582 (push (list (file-name-nondirectory f) f nil nil) tgs))
11583 (save-excursion
11584 (save-restriction
11585 (widen)
11586 (goto-char (point-min))
11587 (while (re-search-forward descre nil t)
11588 (goto-char (setq pos0 (point-at-bol)))
11589 (catch 'next
11590 (when org-refile-target-verify-function
11591 (save-match-data
11592 (or (funcall org-refile-target-verify-function)
11593 (throw 'next t))))
11594 (when (and (looking-at org-complex-heading-regexp)
11595 (not (member (match-string 4) excluded-entries))
11596 (match-string 4))
11597 (setq level (org-reduced-level
11598 (- (match-end 1) (match-beginning 1)))
11599 txt (org-link-display-format (match-string 4))
11600 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11601 re (format org-complex-heading-regexp-format
11602 (regexp-quote (match-string 4))))
11603 (when org-refile-use-outline-path
11604 (setq txt (mapconcat
11605 'org-protect-slash
11606 (append
11607 (if (eq org-refile-use-outline-path
11608 'file)
11609 (list (file-name-nondirectory
11610 (buffer-file-name
11611 (buffer-base-buffer))))
11612 (when (eq org-refile-use-outline-path
11613 'full-file-path)
11614 (list (buffer-file-name
11615 (buffer-base-buffer)))))
11616 (org-get-outline-path fast-path-p
11617 level txt)
11618 (list txt))
11619 "/")))
11620 (push (list txt f re (org-refile-marker (point)))
11621 tgs)))
11622 (when (= (point) pos0)
11623 ;; verification function has not moved point
11624 (goto-char (point-at-eol))))))))
11625 (when org-refile-use-cache
11626 (org-refile-cache-put tgs (buffer-file-name) descre))
11627 (setq targets (append tgs targets))))))
11628 (message "Getting targets...done")
11629 (nreverse targets)))
11631 (defun org-protect-slash (s)
11632 (while (string-match "/" s)
11633 (setq s (replace-match "\\" t t s)))
11636 (defvar org-olpa (make-vector 20 nil))
11638 (defun org-get-outline-path (&optional fastp level heading)
11639 "Return the outline path to the current entry, as a list.
11641 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11642 routine which makes outline path derivations for an entire file,
11643 avoiding backtracing. Refile target collection makes use of that."
11644 (if fastp
11645 (progn
11646 (when (> level 19)
11647 (error "Outline path failure, more than 19 levels"))
11648 (cl-loop for i from level upto 19 do
11649 (aset org-olpa i nil))
11650 (prog1
11651 (delq nil (append org-olpa nil))
11652 (aset org-olpa level heading)))
11653 (let (rtn case-fold-search)
11654 (save-excursion
11655 (save-restriction
11656 (widen)
11657 (while (org-up-heading-safe)
11658 (when (looking-at org-complex-heading-regexp)
11659 (push (org-trim
11660 (replace-regexp-in-string
11661 ;; Remove statistical/checkboxes cookies
11662 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11663 (org-match-string-no-properties 4)))
11664 rtn)))
11665 rtn)))))
11667 (defun org-format-outline-path (path &optional width prefix separator)
11668 "Format the outline path PATH for display.
11669 WIDTH is the maximum number of characters that is available.
11670 PREFIX is a prefix to be included in the returned string,
11671 such as the file name.
11672 SEPARATOR is inserted between the different parts of the path,
11673 the default is \"/\"."
11674 (setq width (or width 79))
11675 (setq path (delq nil path))
11676 (unless (> width 0)
11677 (user-error "Argument `width' must be positive"))
11678 (setq separator (or separator "/"))
11679 (let* ((org-odd-levels-only nil)
11680 (fpath (concat
11681 prefix (and prefix path separator)
11682 (mapconcat
11683 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11684 (cl-loop for head in path
11685 for n from 0
11686 collect (org-add-props
11687 head nil 'face
11688 (nth (% n org-n-level-faces) org-level-faces)))
11689 separator))))
11690 (when (> (length fpath) width)
11691 (if (< width 7)
11692 ;; It's unlikely that `width' will be this small, but don't
11693 ;; waste characters by adding ".." if it is.
11694 (setq fpath (substring fpath 0 width))
11695 (setf (substring fpath (- width 2)) "..")))
11696 fpath))
11698 (defun org-display-outline-path (&optional file current separator just-return-string)
11699 "Display the current outline path in the echo area.
11701 If FILE is non-nil, prepend the output with the file name.
11702 If CURRENT is non-nil, append the current heading to the output.
11703 SEPARATOR is passed through to `org-format-outline-path'. It separates
11704 the different parts of the path and defaults to \"/\".
11705 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11706 (interactive "P")
11707 (let* (case-fold-search
11708 (bfn (buffer-file-name (buffer-base-buffer)))
11709 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11710 res)
11711 (when current (setq path (append path
11712 (save-excursion
11713 (org-back-to-heading t)
11714 (when (looking-at org-complex-heading-regexp)
11715 (list (match-string 4)))))))
11716 (setq res
11717 (org-format-outline-path
11718 path
11719 (1- (frame-width))
11720 (and file bfn (concat (file-name-nondirectory bfn) separator))
11721 separator))
11722 (if just-return-string
11723 (org-no-properties res)
11724 (org-unlogged-message "%s" res))))
11726 (defvar org-refile-history nil
11727 "History for refiling operations.")
11729 (defvar org-after-refile-insert-hook nil
11730 "Hook run after `org-refile' has inserted its stuff at the new location.
11731 Note that this is still *before* the stuff will be removed from
11732 the *old* location.")
11734 (defvar org-capture-last-stored-marker)
11735 (defvar org-refile-keep nil
11736 "Non-nil means `org-refile' will copy instead of refile.")
11738 (defun org-copy ()
11739 "Like `org-refile', but copy."
11740 (interactive)
11741 (let ((org-refile-keep t))
11742 (funcall 'org-refile nil nil nil "Copy")))
11744 (defun org-refile (&optional arg default-buffer rfloc msg)
11745 "Move the entry or entries at point to another heading.
11746 The list of target headings is compiled using the information in
11747 `org-refile-targets', which see.
11749 At the target location, the entry is filed as a subitem of the
11750 target heading. Depending on `org-reverse-note-order', the new
11751 subitem will either be the first or the last subitem.
11753 If there is an active region, all entries in that region will be
11754 refiled. However, the region must fulfill the requirement that
11755 the first heading sets the top-level of the moved text.
11757 With prefix arg ARG, the command will only visit the target
11758 location and not actually move anything.
11760 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11761 refiling operation has put the subtree.
11763 With a numeric prefix argument of `2', refile to the running clock.
11765 With a numeric prefix argument of `3', emulate `org-refile-keep'
11766 being set to t and copy to the target location, don't move it.
11767 Beware that keeping refiled entries may result in duplicated ID
11768 properties.
11770 RFLOC can be a refile location obtained in a different way.
11772 MSG is a string to replace \"Refile\" in the default prompt with
11773 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11775 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11777 If you are using target caching (see `org-refile-use-cache'), you
11778 have to clear the target cache in order to find new targets.
11779 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11780 prefix argument (`C-u C-u C-u C-c C-w')."
11781 (interactive "P")
11782 (if (member arg '(0 (64)))
11783 (org-refile-cache-clear)
11784 (let* ((actionmsg (cond (msg msg)
11785 ((equal arg 3) "Refile (and keep)")
11786 (t "Refile")))
11787 (regionp (org-region-active-p))
11788 (region-start (and regionp (region-beginning)))
11789 (region-end (and regionp (region-end)))
11790 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11791 pos it nbuf file level reversed)
11792 (setq last-command nil)
11793 (when regionp
11794 (goto-char region-start)
11795 (or (bolp) (goto-char (point-at-bol)))
11796 (setq region-start (point))
11797 (unless (or (org-kill-is-subtree-p
11798 (buffer-substring region-start region-end))
11799 (prog1 org-refile-active-region-within-subtree
11800 (let ((s (point-at-eol)))
11801 (org-toggle-heading)
11802 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11803 (user-error "The region is not a (sequence of) subtree(s)")))
11804 (if (equal arg '(16))
11805 (org-refile-goto-last-stored)
11806 (when (or
11807 (and (equal arg 2)
11808 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11809 (prog1
11810 (setq it (list (or org-clock-heading "running clock")
11811 (buffer-file-name
11812 (marker-buffer org-clock-hd-marker))
11814 (marker-position org-clock-hd-marker)))
11815 (setq arg nil)))
11816 (setq it (or rfloc
11817 (let (heading-text)
11818 (save-excursion
11819 (unless (and arg (listp arg))
11820 (org-back-to-heading t)
11821 (setq heading-text
11822 (replace-regexp-in-string
11823 org-bracket-link-regexp
11824 "\\3"
11825 (nth 4 (org-heading-components)))))
11826 (org-refile-get-location
11827 (cond ((and arg (listp arg)) "Goto")
11828 (regionp (concat actionmsg " region to"))
11829 (t (concat actionmsg " subtree \""
11830 heading-text "\" to")))
11831 default-buffer
11832 (and (not (equal '(4) arg))
11833 org-refile-allow-creating-parent-nodes)
11834 arg))))))
11835 (setq file (nth 1 it)
11836 pos (nth 3 it))
11837 (when (and (not arg)
11839 (equal (buffer-file-name) file)
11840 (if regionp
11841 (and (>= pos region-start)
11842 (<= pos region-end))
11843 (and (>= pos (point))
11844 (< pos (save-excursion
11845 (org-end-of-subtree t t))))))
11846 (error "Cannot refile to position inside the tree or region"))
11847 (setq nbuf (or (find-buffer-visiting file)
11848 (find-file-noselect file)))
11849 (if (and arg (not (equal arg 3)))
11850 (progn
11851 (org-pop-to-buffer-same-window nbuf)
11852 (goto-char pos)
11853 (org-show-context 'org-goto))
11854 (if regionp
11855 (progn
11856 (org-kill-new (buffer-substring region-start region-end))
11857 (org-save-markers-in-region region-start region-end))
11858 (org-copy-subtree 1 nil t))
11859 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11860 (find-file-noselect file)))
11861 (setq reversed (org-notes-order-reversed-p))
11862 (save-excursion
11863 (save-restriction
11864 (widen)
11865 (if pos
11866 (progn
11867 (goto-char pos)
11868 (looking-at org-outline-regexp)
11869 (setq level (org-get-valid-level (funcall outline-level) 1))
11870 (goto-char
11871 (if reversed
11872 (or (outline-next-heading) (point-max))
11873 (or (save-excursion (org-get-next-sibling))
11874 (org-end-of-subtree t t)
11875 (point-max)))))
11876 (setq level 1)
11877 (if (not reversed)
11878 (goto-char (point-max))
11879 (goto-char (point-min))
11880 (or (outline-next-heading) (goto-char (point-max)))))
11881 (unless (bolp) (newline))
11882 (org-paste-subtree level nil nil t)
11883 (when org-log-refile
11884 (org-add-log-setup 'refile nil nil org-log-refile)
11885 (unless (eq org-log-refile 'note)
11886 (save-excursion (org-add-log-note))))
11887 (and org-auto-align-tags
11888 (let ((org-loop-over-headlines-in-active-region nil))
11889 (org-set-tags nil t)))
11890 (let ((bookmark-name (plist-get org-bookmark-names-plist
11891 :last-refile)))
11892 (when bookmark-name
11893 (with-demoted-errors
11894 (bookmark-set bookmark-name))))
11895 ;; If we are refiling for capture, make sure that the
11896 ;; last-capture pointers point here
11897 (when (org-bound-and-true-p org-capture-is-refiling)
11898 (let ((bookmark-name (plist-get org-bookmark-names-plist
11899 :last-capture-marker)))
11900 (when bookmark-name
11901 (with-demoted-errors
11902 (bookmark-set bookmark-name))))
11903 (move-marker org-capture-last-stored-marker (point)))
11904 (when (fboundp 'deactivate-mark) (deactivate-mark))
11905 (run-hooks 'org-after-refile-insert-hook))))
11906 (unless org-refile-keep
11907 (if regionp
11908 (delete-region (point) (+ (point) (- region-end region-start)))
11909 (delete-region
11910 (and (org-back-to-heading t) (point))
11911 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11912 (when (featurep 'org-inlinetask)
11913 (org-inlinetask-remove-END-maybe))
11914 (setq org-markers-to-move nil)
11915 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11917 (defun org-refile-goto-last-stored ()
11918 "Go to the location where the last refile was stored."
11919 (interactive)
11920 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11921 (message "This is the location of the last refile"))
11923 (defun org-refile--get-location (refloc tbl)
11924 "When user refile to REFLOC, find the associated target in TBL.
11925 Also check `org-refile-target-table'."
11926 (car (delq
11928 (mapcar
11929 (lambda (r) (or (assoc r tbl)
11930 (assoc r org-refile-target-table)))
11931 (list (replace-regexp-in-string "/$" "" refloc)
11932 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11934 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11935 no-exclude)
11936 "Prompt the user for a refile location, using PROMPT.
11937 PROMPT should not be suffixed with a colon and a space, because
11938 this function appends the default value from
11939 `org-refile-history' automatically, if that is not empty.
11940 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11941 this is used for the GOTO interface."
11942 (let ((org-refile-targets org-refile-targets)
11943 (org-refile-use-outline-path org-refile-use-outline-path)
11944 excluded-entries)
11945 (when (and (derived-mode-p 'org-mode)
11946 (not org-refile-use-cache)
11947 (not no-exclude))
11948 (org-map-tree
11949 (lambda()
11950 (setq excluded-entries
11951 (append excluded-entries (list (org-get-heading t t)))))))
11952 (setq org-refile-target-table
11953 (org-refile-get-targets default-buffer excluded-entries)))
11954 (unless org-refile-target-table
11955 (user-error "No refile targets"))
11956 (let* ((cbuf (current-buffer))
11957 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11958 (cfunc (if (and org-refile-use-outline-path
11959 org-outline-path-complete-in-steps)
11960 #'org-olpath-completing-read
11961 #'completing-read))
11962 (extra (if org-refile-use-outline-path "/" ""))
11963 (cbnex (concat (buffer-name) extra))
11964 (filename (and cfn (expand-file-name cfn)))
11965 (tbl (mapcar
11966 (lambda (x)
11967 (if (and (not (member org-refile-use-outline-path
11968 '(file full-file-path)))
11969 (not (equal filename (nth 1 x))))
11970 (cons (concat (car x) extra " ("
11971 (file-name-nondirectory (nth 1 x)) ")")
11972 (cdr x))
11973 (cons (concat (car x) extra) (cdr x))))
11974 org-refile-target-table))
11975 (completion-ignore-case t)
11976 cdef
11977 (prompt (concat prompt
11978 (or (and (car org-refile-history)
11979 (concat " (default " (car org-refile-history) ")"))
11980 (and (assoc cbnex tbl) (setq cdef cbnex)
11981 (concat " (default " cbnex ")"))) ": "))
11982 pa answ parent-target child parent old-hist)
11983 (setq old-hist org-refile-history)
11984 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11985 nil 'org-refile-history (or cdef (car org-refile-history))))
11986 (if (setq pa (org-refile--get-location answ tbl))
11987 (progn
11988 (org-refile-check-position pa)
11989 (when (or (not org-refile-history)
11990 (not (eq old-hist org-refile-history))
11991 (not (equal (car pa) (car org-refile-history))))
11992 (setq org-refile-history
11993 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11994 org-refile-history
11995 (cdr org-refile-history))))
11996 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11997 (pop org-refile-history)))
11999 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12000 (progn
12001 (setq parent (match-string 1 answ)
12002 child (match-string 2 answ))
12003 (setq parent-target (org-refile--get-location parent tbl))
12004 (when (and parent-target
12005 (or (eq new-nodes t)
12006 (and (eq new-nodes 'confirm)
12007 (y-or-n-p (format "Create new node \"%s\"? "
12008 child)))))
12009 (org-refile-new-child parent-target child)))
12010 (user-error "Invalid target location")))))
12012 (declare-function org-string-nw-p "org-macs" (s))
12013 (defun org-refile-check-position (refile-pointer)
12014 "Check if the refile pointer matches the headline to which it points."
12015 (let* ((file (nth 1 refile-pointer))
12016 (re (nth 2 refile-pointer))
12017 (pos (nth 3 refile-pointer))
12018 buffer)
12019 (if (and (not (markerp pos)) (not file))
12020 (user-error "Please indicate a target file in the refile path")
12021 (when (org-string-nw-p re)
12022 (setq buffer (if (markerp pos)
12023 (marker-buffer pos)
12024 (or (find-buffer-visiting file)
12025 (find-file-noselect file))))
12026 (with-current-buffer buffer
12027 (save-excursion
12028 (save-restriction
12029 (widen)
12030 (goto-char pos)
12031 (beginning-of-line 1)
12032 (unless (org-looking-at-p re)
12033 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12035 (defun org-refile-new-child (parent-target child)
12036 "Use refile target PARENT-TARGET to add new CHILD below it."
12037 (unless parent-target
12038 (error "Cannot find parent for new node"))
12039 (let ((file (nth 1 parent-target))
12040 (pos (nth 3 parent-target))
12041 level)
12042 (with-current-buffer (or (find-buffer-visiting file)
12043 (find-file-noselect file))
12044 (save-excursion
12045 (save-restriction
12046 (widen)
12047 (if pos
12048 (goto-char pos)
12049 (goto-char (point-max))
12050 (unless (bolp) (newline)))
12051 (when (looking-at org-outline-regexp)
12052 (setq level (funcall outline-level))
12053 (org-end-of-subtree t t))
12054 (org-back-over-empty-lines)
12055 (insert "\n" (make-string
12056 (if pos (org-get-valid-level level 1) 1) ?*)
12057 " " child "\n")
12058 (beginning-of-line 0)
12059 (list (concat (car parent-target) "/" child) file "" (point)))))))
12061 (defun org-olpath-completing-read (prompt collection &rest args)
12062 "Read an outline path like a file name."
12063 (let ((thetable collection))
12064 (apply #'completing-read
12065 prompt
12066 (lambda (string predicate &optional flag)
12067 (cond
12068 ((eq flag nil) (try-completion string thetable))
12069 ((eq flag t)
12070 (let ((l (length string)))
12071 (mapcar (lambda (x)
12072 (let ((r (substring x l))
12073 (f (if (string-match " ([^)]*)$" x)
12074 (match-string 0 x)
12075 "")))
12076 (if (string-match "/" r)
12077 (concat string (substring r 0 (match-end 0)) f)
12078 x)))
12079 (all-completions string thetable predicate))))
12080 ;; Exact match?
12081 ((eq flag 'lambda) (assoc string thetable))))
12082 args)))
12084 ;;;; Dynamic blocks
12086 (defun org-find-dblock (name)
12087 "Find the first dynamic block with name NAME in the buffer.
12088 If not found, stay at current position and return nil."
12089 (let ((case-fold-search t) pos)
12090 (save-excursion
12091 (goto-char (point-min))
12092 (setq pos (and (re-search-forward
12093 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12094 (match-beginning 0))))
12095 (when pos (goto-char pos))
12096 pos))
12098 (defun org-create-dblock (plist)
12099 "Create a dynamic block section, with parameters taken from PLIST.
12100 PLIST must contain a :name entry which is used as the name of the block."
12101 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12102 (end-of-line 1)
12103 (newline))
12104 (let ((col (current-column))
12105 (name (plist-get plist :name)))
12106 (insert "#+BEGIN: " name)
12107 (while plist
12108 (if (eq (car plist) :name)
12109 (setq plist (cddr plist))
12110 (insert " " (prin1-to-string (pop plist)))))
12111 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12112 (beginning-of-line -2)))
12114 (defun org-prepare-dblock ()
12115 "Prepare dynamic block for refresh.
12116 This empties the block, puts the cursor at the insert position and returns
12117 the property list including an extra property :name with the block name."
12118 (unless (looking-at org-dblock-start-re)
12119 (user-error "Not at a dynamic block"))
12120 (let* ((begdel (1+ (match-end 0)))
12121 (name (org-no-properties (match-string 1)))
12122 (params (append (list :name name)
12123 (read (concat "(" (match-string 3) ")")))))
12124 (save-excursion
12125 (beginning-of-line 1)
12126 (skip-chars-forward " \t")
12127 (setq params (plist-put params :indentation-column (current-column))))
12128 (unless (re-search-forward org-dblock-end-re nil t)
12129 (error "Dynamic block not terminated"))
12130 (setq params
12131 (append params
12132 (list :content (buffer-substring
12133 begdel (match-beginning 0)))))
12134 (delete-region begdel (match-beginning 0))
12135 (goto-char begdel)
12136 (open-line 1)
12137 params))
12139 (defun org-map-dblocks (&optional command)
12140 "Apply COMMAND to all dynamic blocks in the current buffer.
12141 If COMMAND is not given, use `org-update-dblock'."
12142 (let ((cmd (or command 'org-update-dblock)))
12143 (save-excursion
12144 (goto-char (point-min))
12145 (while (re-search-forward org-dblock-start-re nil t)
12146 (goto-char (match-beginning 0))
12147 (save-excursion
12148 (condition-case nil
12149 (funcall cmd)
12150 (error (message "Error during update of dynamic block"))))
12151 (unless (re-search-forward org-dblock-end-re nil t)
12152 (error "Dynamic block not terminated"))))))
12154 (defun org-dblock-update (&optional arg)
12155 "User command for updating dynamic blocks.
12156 Update the dynamic block at point. With prefix ARG, update all dynamic
12157 blocks in the buffer."
12158 (interactive "P")
12159 (if arg
12160 (org-update-all-dblocks)
12161 (or (looking-at org-dblock-start-re)
12162 (org-beginning-of-dblock))
12163 (org-update-dblock)))
12165 (defun org-update-dblock ()
12166 "Update the dynamic block at point.
12167 This means to empty the block, parse for parameters and then call
12168 the correct writing function."
12169 (interactive)
12170 (save-excursion
12171 (let* ((win (selected-window))
12172 (pos (point))
12173 (line (org-current-line))
12174 (params (org-prepare-dblock))
12175 (name (plist-get params :name))
12176 (indent (plist-get params :indentation-column))
12177 (cmd (intern (concat "org-dblock-write:" name))))
12178 (message "Updating dynamic block `%s' at line %d..." name line)
12179 (funcall cmd params)
12180 (message "Updating dynamic block `%s' at line %d...done" name line)
12181 (goto-char pos)
12182 (when (and indent (> indent 0))
12183 (setq indent (make-string indent ?\ ))
12184 (save-excursion
12185 (select-window win)
12186 (org-beginning-of-dblock)
12187 (forward-line 1)
12188 (while (not (looking-at org-dblock-end-re))
12189 (insert indent)
12190 (beginning-of-line 2))
12191 (when (looking-at org-dblock-end-re)
12192 (and (looking-at "[ \t]+")
12193 (replace-match ""))
12194 (insert indent)))))))
12196 (defun org-beginning-of-dblock ()
12197 "Find the beginning of the dynamic block at point.
12198 Error if there is no such block at point."
12199 (let ((pos (point))
12200 beg)
12201 (end-of-line 1)
12202 (if (and (re-search-backward org-dblock-start-re nil t)
12203 (setq beg (match-beginning 0))
12204 (re-search-forward org-dblock-end-re nil t)
12205 (> (match-end 0) pos))
12206 (goto-char beg)
12207 (goto-char pos)
12208 (error "Not in a dynamic block"))))
12210 (defun org-update-all-dblocks ()
12211 "Update all dynamic blocks in the buffer.
12212 This function can be used in a hook."
12213 (interactive)
12214 (when (derived-mode-p 'org-mode)
12215 (org-map-dblocks 'org-update-dblock)))
12218 ;;;; Completion
12220 (declare-function org-export-backend-name "org-export" (cl-x))
12221 (declare-function org-export-backend-options "org-export" (cl-x))
12222 (defun org-get-export-keywords ()
12223 "Return a list of all currently understood export keywords.
12224 Export keywords include options, block names, attributes and
12225 keywords relative to each registered export back-end."
12226 (let (keywords)
12227 (dolist (backend
12228 (org-bound-and-true-p org-export-registered-backends)
12229 (delq nil keywords))
12230 ;; Back-end name (for keywords, like #+LATEX:)
12231 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12232 (dolist (option-entry (org-export-backend-options backend))
12233 ;; Back-end options.
12234 (push (nth 1 option-entry) keywords)))))
12236 (defconst org-options-keywords
12237 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12238 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12239 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12240 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12241 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12243 (defcustom org-structure-template-alist
12244 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12245 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12246 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12247 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12248 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12249 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12250 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12251 ("L" "#+LaTeX: ")
12252 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12253 ("H" "#+HTML: ")
12254 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12255 ("A" "#+ASCII: ")
12256 ("i" "#+INDEX: ?")
12257 ("I" "#+INCLUDE: %file ?"))
12258 "Structure completion elements.
12259 This is a list of abbreviation keys and values. The value gets inserted
12260 if you type `<' followed by the key and then press the completion key,
12261 usually `TAB'. %file will be replaced by a file name after prompting
12262 for the file using completion. The cursor will be placed at the position
12263 of the `?' in the template.
12264 There are two templates for each key, the first uses the original Org syntax,
12265 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12266 the default when the /org-mtags.el/ module has been loaded. See also the
12267 variable `org-mtags-prefer-muse-templates'."
12268 :group 'org-completion
12269 :type '(repeat
12270 (list
12271 (string :tag "Key")
12272 (string :tag "Template")))
12273 :version "25.1"
12274 :package-version '(Org . "8.3"))
12276 (defun org-try-structure-completion ()
12277 "Try to complete a structure template before point.
12278 This looks for strings like \"<e\" on an otherwise empty line and
12279 expands them."
12280 (let ((l (buffer-substring (point-at-bol) (point)))
12282 (when (and (looking-at "[ \t]*$")
12283 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12284 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12285 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12286 (match-beginning 1)) a)
12287 t)))
12289 (defun org-complete-expand-structure-template (start cell)
12290 "Expand a structure template."
12291 (let ((rpl (nth 1 cell))
12292 (ind ""))
12293 (delete-region start (point))
12294 (when (string-match "\\`[ \t]*#\\+" rpl)
12295 (cond
12296 ((bolp))
12297 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12298 (setq ind (buffer-substring (point-at-bol) (point))))
12299 (t (newline))))
12300 (setq start (point))
12301 (when (string-match "%file" rpl)
12302 (setq rpl (replace-match
12303 (concat
12304 "\""
12305 (save-match-data
12306 (abbreviate-file-name (read-file-name "Include file: ")))
12307 "\"")
12308 t t rpl)))
12309 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12310 (concat "\n" ind)))
12311 (insert rpl)
12312 (when (re-search-backward "\\?" start t) (delete-char 1))))
12314 ;;;; TODO, DEADLINE, Comments
12316 (defun org-toggle-comment ()
12317 "Change the COMMENT state of an entry."
12318 (interactive)
12319 (save-excursion
12320 (org-back-to-heading)
12321 (looking-at org-complex-heading-regexp)
12322 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12323 (skip-chars-forward " \t")
12324 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12325 (if (org-in-commented-heading-p t)
12326 (delete-region (point)
12327 (progn (search-forward " " (line-end-position) 'move)
12328 (skip-chars-forward " \t")
12329 (point)))
12330 (insert org-comment-string)
12331 (unless (eolp) (insert " ")))))
12333 (defvar org-last-todo-state-is-todo nil
12334 "This is non-nil when the last TODO state change led to a TODO state.
12335 If the last change removed the TODO tag or switched to DONE, then
12336 this is nil.")
12338 (defvar org-setting-tags nil) ; dynamically skipped
12340 (defvar org-todo-setup-filter-hook nil
12341 "Hook for functions that pre-filter todo specs.
12342 Each function takes a todo spec and returns either nil or the spec
12343 transformed into canonical form." )
12345 (defvar org-todo-get-default-hook nil
12346 "Hook for functions that get a default item for todo.
12347 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12348 nil or a string to be used for the todo mark." )
12350 (defvar org-agenda-headline-snapshot-before-repeat)
12352 (defun org-current-effective-time ()
12353 "Return current time adjusted for `org-extend-today-until' variable."
12354 (let* ((ct (org-current-time))
12355 (dct (decode-time ct))
12356 (ct1
12357 (cond
12358 (org-use-last-clock-out-time-as-effective-time
12359 (or (org-clock-get-last-clock-out-time) ct))
12360 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12361 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12362 (t ct))))
12363 ct1))
12365 (defun org-todo-yesterday (&optional arg)
12366 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12367 (interactive "P")
12368 (if (eq major-mode 'org-agenda-mode)
12369 (apply 'org-agenda-todo-yesterday arg)
12370 (let* ((org-use-effective-time t)
12371 (hour (nth 2 (decode-time (org-current-time))))
12372 (org-extend-today-until (1+ hour)))
12373 (org-todo arg))))
12375 (defvar org-block-entry-blocking ""
12376 "First entry preventing the TODO state change.")
12378 (defun org-cancel-repeater ()
12379 "Cancel a repeater by setting its numeric value to zero."
12380 (interactive)
12381 (save-excursion
12382 (org-back-to-heading t)
12383 (let ((bound1 (point))
12384 (bound0 (save-excursion (outline-next-heading) (point))))
12385 (when (and (re-search-forward
12386 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12387 org-deadline-time-regexp "\\)\\|\\("
12388 org-ts-regexp "\\)")
12389 bound0 t)
12390 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12391 bound1 t))
12392 (replace-match "0" t nil nil 1)))))
12394 (defvar org-state) ;; dynamically scoped into this function
12395 (defun org-todo (&optional arg)
12396 "Change the TODO state of an item.
12397 The state of an item is given by a keyword at the start of the heading,
12398 like
12399 *** TODO Write paper
12400 *** DONE Call mom
12402 The different keywords are specified in the variable `org-todo-keywords'.
12403 By default the available states are \"TODO\" and \"DONE\".
12404 So for this example: when the item starts with TODO, it is changed to DONE.
12405 When it starts with DONE, the DONE is removed. And when neither TODO nor
12406 DONE are present, add TODO at the beginning of the heading.
12408 With \\[universal-argument] prefix arg, use completion to determine the new \
12409 state.
12410 With numeric prefix arg, switch to that state.
12411 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12412 keywords (nextset).
12413 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12414 With a numeric prefix arg of 0, inhibit note taking for the change.
12415 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12417 When called through ELisp, arg is also interpreted in the following way:
12418 `none' -> empty state
12419 \"\"(empty string) -> switch to empty state
12420 `done' -> switch to DONE
12421 `nextset' -> switch to the next set of keywords
12422 `previousset' -> switch to the previous set of keywords
12423 \"WAITING\" -> switch to the specified keyword, but only if it
12424 really is a member of `org-todo-keywords'."
12425 (interactive "P")
12426 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12427 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12428 'region-start-level 'region))
12429 org-loop-over-headlines-in-active-region)
12430 (org-map-entries
12431 `(org-todo ,arg)
12432 org-loop-over-headlines-in-active-region
12433 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12434 (when (equal arg '(16)) (setq arg 'nextset))
12435 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12436 (let ((org-blocker-hook org-blocker-hook)
12437 commentp
12438 case-fold-search)
12439 (when (equal arg '(64))
12440 (setq arg nil org-blocker-hook nil))
12441 (when (and org-blocker-hook
12442 (or org-inhibit-blocking
12443 (org-entry-get nil "NOBLOCKING")))
12444 (setq org-blocker-hook nil))
12445 (save-excursion
12446 (catch 'exit
12447 (org-back-to-heading t)
12448 (when (org-in-commented-heading-p t)
12449 (org-toggle-comment)
12450 (setq commentp t))
12451 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12452 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12453 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12454 (let* ((match-data (match-data))
12455 (startpos (point-at-bol))
12456 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12457 (org-log-done org-log-done)
12458 (org-log-repeat org-log-repeat)
12459 (org-todo-log-states org-todo-log-states)
12460 (org-inhibit-logging
12461 (if (equal arg 0)
12462 (progn (setq arg nil) 'note) org-inhibit-logging))
12463 (this (match-string 1))
12464 (hl-pos (match-beginning 0))
12465 (head (org-get-todo-sequence-head this))
12466 (ass (assoc head org-todo-kwd-alist))
12467 (interpret (nth 1 ass))
12468 (done-word (nth 3 ass))
12469 (final-done-word (nth 4 ass))
12470 (org-last-state (or this ""))
12471 (completion-ignore-case t)
12472 (member (member this org-todo-keywords-1))
12473 (tail (cdr member))
12474 (org-state (cond
12475 ((and org-todo-key-trigger
12476 (or (and (equal arg '(4))
12477 (eq org-use-fast-todo-selection 'prefix))
12478 (and (not arg) org-use-fast-todo-selection
12479 (not (eq org-use-fast-todo-selection
12480 'prefix)))))
12481 ;; Use fast selection
12482 (org-fast-todo-selection))
12483 ((and (equal arg '(4))
12484 (or (not org-use-fast-todo-selection)
12485 (not org-todo-key-trigger)))
12486 ;; Read a state with completion
12487 (completing-read
12488 "State: " (mapcar #'list org-todo-keywords-1)
12489 nil t))
12490 ((eq arg 'right)
12491 (if this
12492 (if tail (car tail) nil)
12493 (car org-todo-keywords-1)))
12494 ((eq arg 'left)
12495 (unless (equal member org-todo-keywords-1)
12496 (if this
12497 (nth (- (length org-todo-keywords-1)
12498 (length tail) 2)
12499 org-todo-keywords-1)
12500 (org-last org-todo-keywords-1))))
12501 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12502 (setq arg nil))) ; hack to fall back to cycling
12503 (arg
12504 ;; user or caller requests a specific state
12505 (cond
12506 ((equal arg "") nil)
12507 ((eq arg 'none) nil)
12508 ((eq arg 'done) (or done-word (car org-done-keywords)))
12509 ((eq arg 'nextset)
12510 (or (car (cdr (member head org-todo-heads)))
12511 (car org-todo-heads)))
12512 ((eq arg 'previousset)
12513 (let ((org-todo-heads (reverse org-todo-heads)))
12514 (or (car (cdr (member head org-todo-heads)))
12515 (car org-todo-heads))))
12516 ((car (member arg org-todo-keywords-1)))
12517 ((stringp arg)
12518 (user-error "State `%s' not valid in this file" arg))
12519 ((nth (1- (prefix-numeric-value arg))
12520 org-todo-keywords-1))))
12521 ((null member) (or head (car org-todo-keywords-1)))
12522 ((equal this final-done-word) nil) ;; -> make empty
12523 ((null tail) nil) ;; -> first entry
12524 ((memq interpret '(type priority))
12525 (if (eq this-command last-command)
12526 (car tail)
12527 (if (> (length tail) 0)
12528 (or done-word (car org-done-keywords))
12529 nil)))
12531 (car tail))))
12532 (org-state (or
12533 (run-hook-with-args-until-success
12534 'org-todo-get-default-hook org-state org-last-state)
12535 org-state))
12536 (next (if org-state (concat " " org-state " ") " "))
12537 (change-plist (list :type 'todo-state-change :from this :to org-state
12538 :position startpos))
12539 dolog now-done-p)
12540 (when org-blocker-hook
12541 (setq org-last-todo-state-is-todo
12542 (not (member this org-done-keywords)))
12543 (unless (save-excursion
12544 (save-match-data
12545 (org-with-wide-buffer
12546 (run-hook-with-args-until-failure
12547 'org-blocker-hook change-plist))))
12548 (if (org-called-interactively-p 'interactive)
12549 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12550 this org-state org-block-entry-blocking)
12551 ;; fail silently
12552 (message "TODO state change from %s to %s blocked (by \"%s\")"
12553 this org-state org-block-entry-blocking)
12554 (throw 'exit nil))))
12555 (store-match-data match-data)
12556 (replace-match next t t)
12557 (cond ((equal this org-state)
12558 (message "TODO state was already %s" (org-trim next)))
12559 ((pos-visible-in-window-p hl-pos)
12560 (message "TODO state changed to %s" (org-trim next))))
12561 (unless head
12562 (setq head (org-get-todo-sequence-head org-state)
12563 ass (assoc head org-todo-kwd-alist)
12564 interpret (nth 1 ass)
12565 done-word (nth 3 ass)
12566 final-done-word (nth 4 ass)))
12567 (when (memq arg '(nextset previousset))
12568 (message "Keyword-Set %d/%d: %s"
12569 (- (length org-todo-sets) -1
12570 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12571 (length org-todo-sets)
12572 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12573 (setq org-last-todo-state-is-todo
12574 (not (member org-state org-done-keywords)))
12575 (setq now-done-p (and (member org-state org-done-keywords)
12576 (not (member this org-done-keywords))))
12577 (and logging (org-local-logging logging))
12578 (when (and (or org-todo-log-states org-log-done)
12579 (not (eq org-inhibit-logging t))
12580 (not (memq arg '(nextset previousset))))
12581 ;; we need to look at recording a time and note
12582 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12583 (nth 2 (assoc this org-todo-log-states))))
12584 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12585 (setq dolog 'time))
12586 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12587 (and org-state
12588 (member org-state org-not-done-keywords)
12589 (not (member this org-not-done-keywords))))
12590 ;; This is now a todo state and was not one before
12591 ;; If there was a CLOSED time stamp, get rid of it.
12592 (org-add-planning-info nil nil 'closed))
12593 (when (and now-done-p org-log-done)
12594 ;; It is now done, and it was not done before
12595 (org-add-planning-info 'closed (org-current-effective-time))
12596 (when (and (not dolog) (eq 'note org-log-done))
12597 (org-add-log-setup 'done org-state this 'note)))
12598 (when (and org-state dolog)
12599 ;; This is a non-nil state, and we need to log it
12600 (org-add-log-setup 'state org-state this dolog)))
12601 ;; Fixup tag positioning
12602 (org-todo-trigger-tag-changes org-state)
12603 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12604 (when org-provide-todo-statistics
12605 (org-update-parent-todo-statistics))
12606 (run-hooks 'org-after-todo-state-change-hook)
12607 (when (and arg (not (member org-state org-done-keywords)))
12608 (setq head (org-get-todo-sequence-head org-state)))
12609 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12610 ;; Do we need to trigger a repeat?
12611 (when now-done-p
12612 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12613 ;; This is for the agenda, take a snapshot of the headline.
12614 (save-match-data
12615 (setq org-agenda-headline-snapshot-before-repeat
12616 (org-get-heading))))
12617 (org-auto-repeat-maybe org-state))
12618 ;; Fixup cursor location if close to the keyword
12619 (when (and (outline-on-heading-p)
12620 (not (bolp))
12621 (save-excursion (beginning-of-line 1)
12622 (looking-at org-todo-line-regexp))
12623 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12624 (goto-char (or (match-end 2) (match-end 1)))
12625 (and (looking-at " ") (just-one-space)))
12626 (when org-trigger-hook
12627 (save-excursion
12628 (run-hook-with-args 'org-trigger-hook change-plist)))
12629 (when commentp (org-toggle-comment))))))))
12631 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12632 "Block turning an entry into a TODO, using the hierarchy.
12633 This checks whether the current task should be blocked from state
12634 changes. Such blocking occurs when:
12636 1. The task has children which are not all in a completed state.
12638 2. A task has a parent with the property :ORDERED:, and there
12639 are siblings prior to the current task with incomplete
12640 status.
12642 3. The parent of the task is blocked because it has siblings that should
12643 be done first, or is child of a block grandparent TODO entry."
12645 (if (not org-enforce-todo-dependencies)
12646 t ; if locally turned off don't block
12647 (catch 'dont-block
12648 ;; If this is not a todo state change, or if this entry is already DONE,
12649 ;; do not block
12650 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12651 (member (plist-get change-plist :from)
12652 (cons 'done org-done-keywords))
12653 (member (plist-get change-plist :to)
12654 (cons 'todo org-not-done-keywords))
12655 (not (plist-get change-plist :to)))
12656 (throw 'dont-block t))
12657 ;; If this task has children, and any are undone, it's blocked
12658 (save-excursion
12659 (org-back-to-heading t)
12660 (let ((this-level (funcall outline-level)))
12661 (outline-next-heading)
12662 (let ((child-level (funcall outline-level)))
12663 (while (and (not (eobp))
12664 (> child-level this-level))
12665 ;; this todo has children, check whether they are all
12666 ;; completed
12667 (when (and (not (org-entry-is-done-p))
12668 (org-entry-is-todo-p))
12669 (setq org-block-entry-blocking (org-get-heading))
12670 (throw 'dont-block nil))
12671 (outline-next-heading)
12672 (setq child-level (funcall outline-level))))))
12673 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12674 ;; any previous siblings are undone, it's blocked
12675 (save-excursion
12676 (org-back-to-heading t)
12677 (let* ((pos (point))
12678 (parent-pos (and (org-up-heading-safe) (point))))
12679 (unless parent-pos (throw 'dont-block t)) ; no parent
12680 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12681 (forward-line 1)
12682 (re-search-forward org-not-done-heading-regexp pos t))
12683 (setq org-block-entry-blocking (match-string 0))
12684 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12685 ;; Search further up the hierarchy, to see if an ancestor is blocked
12686 (while t
12687 (goto-char parent-pos)
12688 (unless (looking-at org-not-done-heading-regexp)
12689 (throw 'dont-block t)) ; do not block, parent is not a TODO
12690 (setq pos (point))
12691 (setq parent-pos (and (org-up-heading-safe) (point)))
12692 (unless parent-pos (throw 'dont-block t)) ; no parent
12693 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12694 (forward-line 1)
12695 (re-search-forward org-not-done-heading-regexp pos t)
12696 (setq org-block-entry-blocking (org-get-heading)))
12697 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12699 (defcustom org-track-ordered-property-with-tag nil
12700 "Should the ORDERED property also be shown as a tag?
12701 The ORDERED property decides if an entry should require subtasks to be
12702 completed in sequence. Since a property is not very visible, setting
12703 this option means that toggling the ORDERED property with the command
12704 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12705 not relevant for the behavior, but it makes things more visible.
12707 Note that toggling the tag with tags commands will not change the property
12708 and therefore not influence behavior!
12710 This can be t, meaning the tag ORDERED should be used, It can also be a
12711 string to select a different tag for this task."
12712 :group 'org-todo
12713 :type '(choice
12714 (const :tag "No tracking" nil)
12715 (const :tag "Track with ORDERED tag" t)
12716 (string :tag "Use other tag")))
12718 (defun org-toggle-ordered-property ()
12719 "Toggle the ORDERED property of the current entry.
12720 For better visibility, you can track the value of this property with a tag.
12721 See variable `org-track-ordered-property-with-tag'."
12722 (interactive)
12723 (let* ((t1 org-track-ordered-property-with-tag)
12724 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12725 (save-excursion
12726 (org-back-to-heading)
12727 (if (org-entry-get nil "ORDERED")
12728 (progn
12729 (org-delete-property "ORDERED")
12730 (and tag (org-toggle-tag tag 'off))
12731 (message "Subtasks can be completed in arbitrary order"))
12732 (org-entry-put nil "ORDERED" "t")
12733 (and tag (org-toggle-tag tag 'on))
12734 (message "Subtasks must be completed in sequence")))))
12736 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12737 (defun org-block-todo-from-checkboxes (change-plist)
12738 "Block turning an entry into a TODO, using checkboxes.
12739 This checks whether the current task should be blocked from state
12740 changes because there are unchecked boxes in this entry."
12741 (if (not org-enforce-todo-checkbox-dependencies)
12742 t ; if locally turned off don't block
12743 (catch 'dont-block
12744 ;; If this is not a todo state change, or if this entry is already DONE,
12745 ;; do not block
12746 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12747 (member (plist-get change-plist :from)
12748 (cons 'done org-done-keywords))
12749 (member (plist-get change-plist :to)
12750 (cons 'todo org-not-done-keywords))
12751 (not (plist-get change-plist :to)))
12752 (throw 'dont-block t))
12753 ;; If this task has checkboxes that are not checked, it's blocked
12754 (save-excursion
12755 (org-back-to-heading t)
12756 (let ((beg (point)) end)
12757 (outline-next-heading)
12758 (setq end (point))
12759 (goto-char beg)
12760 (when (org-list-search-forward
12761 (concat (org-item-beginning-re)
12762 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12763 "\\[[- ]\\]")
12764 end t)
12765 (when (boundp 'org-blocked-by-checkboxes)
12766 (setq org-blocked-by-checkboxes t))
12767 (throw 'dont-block nil))))
12768 t))) ; do not block
12770 (defun org-entry-blocked-p ()
12771 "Non-nil if entry at point is blocked."
12772 (and (not (org-entry-get nil "NOBLOCKING"))
12773 (member (org-entry-get nil "TODO") org-not-done-keywords)
12774 (not (run-hook-with-args-until-failure
12775 'org-blocker-hook
12776 (list :type 'todo-state-change
12777 :position (point)
12778 :from 'todo
12779 :to 'done)))))
12781 (defun org-update-statistics-cookies (all)
12782 "Update the statistics cookie, either from TODO or from checkboxes.
12783 This should be called with the cursor in a line with a statistics cookie."
12784 (interactive "P")
12785 (if all
12786 (progn
12787 (org-update-checkbox-count 'all)
12788 (org-map-entries 'org-update-parent-todo-statistics))
12789 (if (not (org-at-heading-p))
12790 (org-update-checkbox-count)
12791 (let ((pos (point-marker))
12792 end l1 l2)
12793 (ignore-errors (org-back-to-heading t))
12794 (if (not (org-at-heading-p))
12795 (org-update-checkbox-count)
12796 (setq l1 (org-outline-level))
12797 (setq end (save-excursion
12798 (outline-next-heading)
12799 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12800 (point)))
12801 (if (and (save-excursion
12802 (re-search-forward
12803 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12804 (not (save-excursion (re-search-forward
12805 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12806 (org-update-checkbox-count)
12807 (if (and l2 (> l2 l1))
12808 (progn
12809 (goto-char end)
12810 (org-update-parent-todo-statistics))
12811 (goto-char pos)
12812 (beginning-of-line 1)
12813 (while (re-search-forward
12814 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12815 (point-at-eol) t)
12816 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12817 (goto-char pos)
12818 (move-marker pos nil)))))
12820 (defvar org-entry-property-inherited-from) ;; defined below
12821 (defun org-update-parent-todo-statistics ()
12822 "Update any statistics cookie in the parent of the current headline.
12823 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12824 the entire subtree and this will travel up the hierarchy and update
12825 statistics everywhere."
12826 (let* ((prop (save-excursion (org-up-heading-safe)
12827 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12828 (recursive (or (not org-hierarchical-todo-statistics)
12829 (and prop (string-match "\\<recursive\\>" prop))))
12830 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12832 (first t)
12833 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12834 level ltoggle l1 new ndel
12835 (cnt-all 0) (cnt-done 0) is-percent kwd
12836 checkbox-beg ov ovs ove cookie-present)
12837 (catch 'exit
12838 (save-excursion
12839 (beginning-of-line 1)
12840 (setq ltoggle (funcall outline-level))
12841 ;; Three situations are to consider:
12843 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12844 ;; to the top-level ancestor on the headline;
12846 ;; 2. If parent has "recursive" property, repeat up to the
12847 ;; headline setting that property, taking inheritance into
12848 ;; account;
12850 ;; 3. Else, move up to direct parent and proceed only once.
12851 (while (and (setq level (org-up-heading-safe))
12852 (or recursive first)
12853 (>= (point) lim))
12854 (setq first nil cookie-present nil)
12855 (unless (and level
12856 (not (string-match
12857 "\\<checkbox\\>"
12858 (downcase (or (org-entry-get nil "COOKIE_DATA")
12859 "")))))
12860 (throw 'exit nil))
12861 (while (re-search-forward box-re (point-at-eol) t)
12862 (setq cnt-all 0 cnt-done 0 cookie-present t)
12863 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12864 (save-match-data
12865 (unless (outline-next-heading) (throw 'exit nil))
12866 (while (and (looking-at org-complex-heading-regexp)
12867 (> (setq l1 (length (match-string 1))) level))
12868 (setq kwd (and (or recursive (= l1 ltoggle))
12869 (match-string 2)))
12870 (if (or (eq org-provide-todo-statistics 'all-headlines)
12871 (and (eq org-provide-todo-statistics t)
12872 (or (member kwd org-done-keywords)))
12873 (and (listp org-provide-todo-statistics)
12874 (stringp (car org-provide-todo-statistics))
12875 (or (member kwd org-provide-todo-statistics)
12876 (member kwd org-done-keywords)))
12877 (and (listp org-provide-todo-statistics)
12878 (listp (car org-provide-todo-statistics))
12879 (or (member kwd (car org-provide-todo-statistics))
12880 (and (member kwd org-done-keywords)
12881 (member kwd (cadr org-provide-todo-statistics))))))
12882 (setq cnt-all (1+ cnt-all))
12883 (and (eq org-provide-todo-statistics t)
12885 (setq cnt-all (1+ cnt-all))))
12886 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12887 (member kwd org-done-keywords))
12888 (and (listp org-provide-todo-statistics)
12889 (listp (car org-provide-todo-statistics))
12890 (member kwd org-done-keywords)
12891 (member kwd (cadr org-provide-todo-statistics)))
12892 (and (listp org-provide-todo-statistics)
12893 (stringp (car org-provide-todo-statistics))
12894 (member kwd org-done-keywords)))
12895 (setq cnt-done (1+ cnt-done)))
12896 (outline-next-heading)))
12897 (setq new
12898 (if is-percent
12899 (format "[%d%%]" (floor (* 100.0 cnt-done)
12900 (max 1 cnt-all)))
12901 (format "[%d/%d]" cnt-done cnt-all))
12902 ndel (- (match-end 0) checkbox-beg))
12903 ;; handle overlays when updating cookie from column view
12904 (when (setq ov (car (overlays-at checkbox-beg)))
12905 (setq ovs (overlay-start ov) ove (overlay-end ov))
12906 (delete-overlay ov))
12907 (goto-char checkbox-beg)
12908 (insert new)
12909 (delete-region (point) (+ (point) ndel))
12910 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12911 (when ov (move-overlay ov ovs ove)))
12912 (when cookie-present
12913 (run-hook-with-args 'org-after-todo-statistics-hook
12914 cnt-done (- cnt-all cnt-done))))))
12915 (run-hooks 'org-todo-statistics-hook)))
12917 (defvar org-after-todo-statistics-hook nil
12918 "Hook that is called after a TODO statistics cookie has been updated.
12919 Each function is called with two arguments: the number of not-done entries
12920 and the number of done entries.
12922 For example, the following function, when added to this hook, will switch
12923 an entry to DONE when all children are done, and back to TODO when new
12924 entries are set to a TODO status. Note that this hook is only called
12925 when there is a statistics cookie in the headline!
12927 \(defun org-summary-todo (n-done n-not-done)
12928 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12929 \(let (org-log-done org-log-states) ; turn off logging
12930 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12933 (defvar org-todo-statistics-hook nil
12934 "Hook that is run whenever Org thinks TODO statistics should be updated.
12935 This hook runs even if there is no statistics cookie present, in which case
12936 `org-after-todo-statistics-hook' would not run.")
12938 (defun org-todo-trigger-tag-changes (state)
12939 "Apply the changes defined in `org-todo-state-tags-triggers'."
12940 (let ((l org-todo-state-tags-triggers)
12941 changes)
12942 (when (or (not state) (equal state ""))
12943 (setq changes (append changes (cdr (assoc "" l)))))
12944 (when (and (stringp state) (> (length state) 0))
12945 (setq changes (append changes (cdr (assoc state l)))))
12946 (when (member state org-not-done-keywords)
12947 (setq changes (append changes (cdr (assoc 'todo l)))))
12948 (when (member state org-done-keywords)
12949 (setq changes (append changes (cdr (assoc 'done l)))))
12950 (dolist (c changes)
12951 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12953 (defun org-local-logging (value)
12954 "Get logging settings from a property VALUE."
12955 ;; Directly set the variables, they are already local.
12956 (setq org-log-done nil
12957 org-log-repeat nil
12958 org-todo-log-states nil)
12959 (dolist (w (org-split-string value))
12960 (let (a)
12961 (cond
12962 ((setq a (assoc w org-startup-options))
12963 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12964 (set (nth 1 a) (nth 2 a))))
12965 ((setq a (org-extract-log-state-settings w))
12966 (and (member (car a) org-todo-keywords-1)
12967 (push a org-todo-log-states)))))))
12969 (defun org-get-todo-sequence-head (kwd)
12970 "Return the head of the TODO sequence to which KWD belongs.
12971 If KWD is not set, check if there is a text property remembering the
12972 right sequence."
12973 (let (p)
12974 (cond
12975 ((not kwd)
12976 (or (get-text-property (point-at-bol) 'org-todo-head)
12977 (progn
12978 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12979 nil (point-at-eol)))
12980 (get-text-property p 'org-todo-head))))
12981 ((not (member kwd org-todo-keywords-1))
12982 (car org-todo-keywords-1))
12983 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12985 (defun org-fast-todo-selection ()
12986 "Fast TODO keyword selection with single keys.
12987 Returns the new TODO keyword, or nil if no state change should occur."
12988 (let* ((fulltable org-todo-key-alist)
12989 (done-keywords org-done-keywords) ;; needed for the faces.
12990 (maxlen (apply 'max (mapcar
12991 (lambda (x)
12992 (if (stringp (car x)) (string-width (car x)) 0))
12993 fulltable)))
12994 (expert nil)
12995 (fwidth (+ maxlen 3 1 3))
12996 (ncol (/ (- (window-width) 4) fwidth))
12997 tg cnt e c tbl
12998 groups ingroup)
12999 (save-excursion
13000 (save-window-excursion
13001 (if expert
13002 (set-buffer (get-buffer-create " *Org todo*"))
13003 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13004 (erase-buffer)
13005 (setq-local org-done-keywords done-keywords)
13006 (setq tbl fulltable cnt 0)
13007 (while (setq e (pop tbl))
13008 (cond
13009 ((equal e '(:startgroup))
13010 (push '() groups) (setq ingroup t)
13011 (unless (= cnt 0)
13012 (setq cnt 0)
13013 (insert "\n"))
13014 (insert "{ "))
13015 ((equal e '(:endgroup))
13016 (setq ingroup nil cnt 0)
13017 (insert "}\n"))
13018 ((equal e '(:newline))
13019 (unless (= cnt 0)
13020 (setq cnt 0)
13021 (insert "\n")
13022 (setq e (car tbl))
13023 (while (equal (car tbl) '(:newline))
13024 (insert "\n")
13025 (setq tbl (cdr tbl)))))
13027 (setq tg (car e) c (cdr e))
13028 (when ingroup (push tg (car groups)))
13029 (setq tg (org-add-props tg nil 'face
13030 (org-get-todo-face tg)))
13031 (when (and (= cnt 0) (not ingroup)) (insert " "))
13032 (insert "[" c "] " tg (make-string
13033 (- fwidth 4 (length tg)) ?\ ))
13034 (when (= (setq cnt (1+ cnt)) ncol)
13035 (insert "\n")
13036 (when ingroup (insert " "))
13037 (setq cnt 0)))))
13038 (insert "\n")
13039 (goto-char (point-min))
13040 (unless expert (org-fit-window-to-buffer))
13041 (message "[a-z..]:Set [SPC]:clear")
13042 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13043 (cond
13044 ((or (= c ?\C-g)
13045 (and (= c ?q) (not (rassoc c fulltable))))
13046 (setq quit-flag t))
13047 ((= c ?\ ) nil)
13048 ((setq e (rassoc c fulltable) tg (car e))
13050 (t (setq quit-flag t)))))))
13052 (defun org-entry-is-todo-p ()
13053 (member (org-get-todo-state) org-not-done-keywords))
13055 (defun org-entry-is-done-p ()
13056 (member (org-get-todo-state) org-done-keywords))
13058 (defun org-get-todo-state ()
13059 "Return the TODO keyword of the current subtree."
13060 (save-excursion
13061 (org-back-to-heading t)
13062 (and (looking-at org-todo-line-regexp)
13063 (match-end 2)
13064 (match-string 2))))
13066 (defun org-at-date-range-p (&optional inactive-ok)
13067 "Non-nil if point is inside a date range.
13069 When optional argument INACTIVE-OK is non-nil, also consider
13070 inactive time ranges.
13072 When this function returns a non-nil value, match data is set
13073 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13074 on INACTIVE-OK."
13075 (interactive)
13076 (save-excursion
13077 (catch 'exit
13078 (let ((pos (point)))
13079 (skip-chars-backward "^[<\r\n")
13080 (skip-chars-backward "<[")
13081 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13082 (>= (match-end 0) pos)
13083 (throw 'exit t))
13084 (skip-chars-backward "^<[\r\n")
13085 (skip-chars-backward "<[")
13086 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13087 (>= (match-end 0) pos)
13088 (throw 'exit t)))
13089 nil)))
13091 (defun org-get-repeat (&optional tagline)
13092 "Check if there is a deadline/schedule with repeater in this entry."
13093 (save-match-data
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (and (re-search-forward (if tagline
13097 (concat tagline "\\s-*" org-repeat-re)
13098 org-repeat-re)
13099 (org-entry-end-position) t)
13100 (match-string-no-properties 1)))))
13102 (defvar org-last-changed-timestamp)
13103 (defvar org-last-inserted-timestamp)
13104 (defvar org-log-post-message)
13105 (defvar org-log-note-purpose)
13106 (defvar org-log-note-how nil)
13107 (defvar org-log-note-extra)
13108 (defun org-auto-repeat-maybe (done-word)
13109 "Check if the current headline contains a repeated time-stamp.
13111 If yes, set TODO state back to what it was and change the base date
13112 of repeating deadline/scheduled time stamps to new date.
13114 This function is run automatically after each state change to a DONE state."
13115 (let* ((repeat (org-get-repeat))
13116 (aa (assoc org-last-state org-todo-kwd-alist))
13117 (interpret (nth 1 aa))
13118 (head (nth 2 aa))
13119 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13120 (msg "Entry repeats: ")
13121 (org-log-done nil)
13122 (org-todo-log-states nil))
13123 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13124 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13125 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13126 org-todo-repeat-to-state)))
13127 (unless (and to-state (member to-state org-todo-keywords-1))
13128 (setq to-state (if (eq interpret 'type) org-last-state head)))
13129 (org-todo to-state))
13130 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13131 (org-entry-put nil "LAST_REPEAT" (format-time-string
13132 (org-time-stamp-format t t))))
13133 (when org-log-repeat
13134 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13135 (memq 'org-add-log-note post-command-hook))
13136 ;; We are already setup for some record.
13137 (when (eq org-log-repeat 'note)
13138 ;; Make sure we take a note, not only a time stamp.
13139 (setq org-log-note-how 'note))
13140 ;; Set up for taking a record.
13141 (org-add-log-setup 'state
13142 (or done-word (car org-done-keywords))
13143 org-last-state
13144 org-log-repeat)))
13145 (org-back-to-heading t)
13146 (org-add-planning-info nil nil 'closed)
13147 (let ((end (save-excursion (outline-next-heading) (point))))
13148 (while (re-search-forward org-ts-regexp end t)
13149 (when (save-match-data
13150 (or (org-at-planning-p)
13151 (org-at-property-p)
13152 (eq (org-element-type (save-excursion
13153 (backward-char)
13154 (org-element-context)))
13155 'timestamp)))
13156 (let ((type (cond ((match-end 1) org-scheduled-string)
13157 ((match-end 3) org-deadline-string)
13158 (t "Plain:")))
13159 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13160 (cond
13161 ((not
13162 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13163 ;; Time-stamps without a repeater are usually skipped.
13164 ;; However, a SCHEDULED time-stamp without one is
13165 ;; removed, as it is considered as no longer relevant.
13166 (when (equal type org-scheduled-string)
13167 (org-remove-timestamp-with-keyword type)))
13169 (let ((n (string-to-number (match-string 2 ts)))
13170 (what (match-string 3 ts)))
13171 (when (equal what "w") (setq n (* n 7) what "d"))
13172 (when (and (equal what "h")
13173 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13174 ts)))
13175 (user-error
13176 "Cannot repeat in Repeat in %d hour(s) because no hour \
13177 has been set"
13179 ;; Preparation, see if we need to modify the start
13180 ;; date for the change.
13181 (when (match-end 1)
13182 (let ((time (save-match-data (org-time-string-to-time ts))))
13183 (cond
13184 ((equal (match-string 1 ts) ".")
13185 ;; Shift starting date to today
13186 (org-timestamp-change
13187 (- (org-today) (time-to-days time))
13188 'day))
13189 ((equal (match-string 1 ts) "+")
13190 (let ((nshiftmax 10)
13191 (nshift 0))
13192 (while (or (= nshift 0)
13193 (<= (time-to-days time)
13194 (time-to-days (current-time))))
13195 (when (= (cl-incf nshift) nshiftmax)
13196 (or (y-or-n-p
13197 (format "%d repeater intervals were not \
13198 enough to shift date past today. Continue? "
13199 nshift))
13200 (user-error "Abort")))
13201 (org-timestamp-change n (cdr (assoc what whata)))
13202 (org-at-timestamp-p t)
13203 (setq ts (match-string 1))
13204 (setq time
13205 (save-match-data
13206 (org-time-string-to-time ts)))))
13207 (org-timestamp-change (- n) (cdr (assoc what whata)))
13208 ;; Rematch, so that we have everything in
13209 ;; place for the real shift.
13210 (org-at-timestamp-p t)
13211 (setq ts (match-string 1))
13212 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13213 ts)))))
13214 (save-excursion
13215 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13216 (setq msg
13217 (concat
13218 msg type " " org-last-changed-timestamp " ")))))))))
13219 (setq org-log-post-message msg)
13220 (message "%s" msg))))
13222 (defun org-show-todo-tree (arg)
13223 "Make a compact tree which shows all headlines marked with TODO.
13224 The tree will show the lines where the regexp matches, and all higher
13225 headlines above the match.
13226 With a \\[universal-argument] prefix, prompt for a regexp to match.
13227 With a numeric prefix N, construct a sparse tree for the Nth element
13228 of `org-todo-keywords-1'."
13229 (interactive "P")
13230 (let ((case-fold-search nil)
13231 (kwd-re
13232 (cond ((null arg) org-not-done-regexp)
13233 ((equal arg '(4))
13234 (let ((kwd
13235 (completing-read "Keyword (or KWD1|KWD2|...): "
13236 (mapcar #'list org-todo-keywords-1))))
13237 (concat "\\("
13238 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13239 "\\)\\>")))
13240 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13241 (regexp-quote (nth (1- (prefix-numeric-value arg))
13242 org-todo-keywords-1)))
13243 (t (user-error "Invalid prefix argument: %s" arg)))))
13244 (message "%d TODO entries found"
13245 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13247 (defun org-deadline (arg &optional time)
13248 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13249 With one universal prefix argument, remove any deadline from the item.
13250 With two universal prefix arguments, prompt for a warning delay.
13251 With argument TIME, set the deadline at the corresponding date. TIME
13252 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13253 (interactive "P")
13254 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13255 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13256 'region-start-level 'region))
13257 org-loop-over-headlines-in-active-region)
13258 (org-map-entries
13259 `(org-deadline ',arg ,time)
13260 org-loop-over-headlines-in-active-region
13261 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13262 (let* ((old-date (org-entry-get nil "DEADLINE"))
13263 (old-date-time (when old-date (org-time-string-to-time old-date)))
13264 (repeater (and old-date
13265 (string-match
13266 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13267 old-date)
13268 (match-string 1 old-date))))
13269 (cond
13270 ((equal arg '(4))
13271 (when (and old-date org-log-redeadline)
13272 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13273 (org-remove-timestamp-with-keyword org-deadline-string)
13274 (message "Item no longer has a deadline."))
13275 ((equal arg '(16))
13276 (save-excursion
13277 (org-back-to-heading t)
13278 (if (re-search-forward
13279 org-deadline-time-regexp
13280 (save-excursion (outline-next-heading) (point)) t)
13281 (let* ((rpl0 (match-string 1))
13282 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13283 (replace-match
13284 (concat org-deadline-string
13285 " <" rpl
13286 (format " -%dd"
13287 (abs
13288 (- (time-to-days
13289 (save-match-data
13290 (org-read-date nil t nil "Warn starting from" old-date-time)))
13291 (time-to-days old-date-time))))
13292 ">") t t))
13293 (user-error "No deadline information to update"))))
13295 (org-add-planning-info 'deadline time 'closed)
13296 (when (and old-date
13297 org-log-redeadline
13298 (not (equal old-date org-last-inserted-timestamp)))
13299 (org-add-log-setup
13300 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13301 (when repeater
13302 (save-excursion
13303 (org-back-to-heading t)
13304 (when (re-search-forward (concat org-deadline-string " "
13305 org-last-inserted-timestamp)
13306 (save-excursion
13307 (outline-next-heading) (point)) t)
13308 (goto-char (1- (match-end 0)))
13309 (insert " " repeater)
13310 (setq org-last-inserted-timestamp
13311 (concat (substring org-last-inserted-timestamp 0 -1)
13312 " " repeater
13313 (substring org-last-inserted-timestamp -1))))))
13314 (message "Deadline on %s" org-last-inserted-timestamp))))))
13316 (defun org-schedule (arg &optional time)
13317 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13318 With one universal prefix argument, remove any scheduling date from the item.
13319 With two universal prefix arguments, prompt for a delay cookie.
13320 With argument TIME, scheduled at the corresponding date. TIME can
13321 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13322 (interactive "P")
13323 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13324 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13325 'region-start-level 'region))
13326 org-loop-over-headlines-in-active-region)
13327 (org-map-entries
13328 `(org-schedule ',arg ,time)
13329 org-loop-over-headlines-in-active-region
13330 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13331 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13332 (old-date-time (when old-date (org-time-string-to-time old-date)))
13333 (repeater (and old-date
13334 (string-match
13335 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13336 old-date)
13337 (match-string 1 old-date))))
13338 (cond
13339 ((equal arg '(4))
13340 (progn
13341 (when (and old-date org-log-reschedule)
13342 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13343 (org-remove-timestamp-with-keyword org-scheduled-string)
13344 (message "Item is no longer scheduled.")))
13345 ((equal arg '(16))
13346 (save-excursion
13347 (org-back-to-heading t)
13348 (if (re-search-forward
13349 org-scheduled-time-regexp
13350 (save-excursion (outline-next-heading) (point)) t)
13351 (let* ((rpl0 (match-string 1))
13352 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13353 (replace-match
13354 (concat org-scheduled-string
13355 " <" rpl
13356 (format " -%dd"
13357 (abs
13358 (- (time-to-days
13359 (save-match-data
13360 (org-read-date nil t nil "Delay until" old-date-time)))
13361 (time-to-days old-date-time))))
13362 ">") t t))
13363 (user-error "No scheduled information to update"))))
13365 (org-add-planning-info 'scheduled time 'closed)
13366 (when (and old-date
13367 org-log-reschedule
13368 (not (equal old-date org-last-inserted-timestamp)))
13369 (org-add-log-setup
13370 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13371 (when repeater
13372 (save-excursion
13373 (org-back-to-heading t)
13374 (when (re-search-forward (concat org-scheduled-string " "
13375 org-last-inserted-timestamp)
13376 (save-excursion
13377 (outline-next-heading) (point)) t)
13378 (goto-char (1- (match-end 0)))
13379 (insert " " repeater)
13380 (setq org-last-inserted-timestamp
13381 (concat (substring org-last-inserted-timestamp 0 -1)
13382 " " repeater
13383 (substring org-last-inserted-timestamp -1))))))
13384 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13386 (defun org-get-scheduled-time (pom &optional inherit)
13387 "Get the scheduled time as a time tuple, of a format suitable
13388 for calling org-schedule with, or if there is no scheduling,
13389 returns nil."
13390 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13391 (when time
13392 (apply 'encode-time (org-parse-time-string time)))))
13394 (defun org-get-deadline-time (pom &optional inherit)
13395 "Get the deadline as a time tuple, of a format suitable for
13396 calling org-deadline with, or if there is no scheduling, returns
13397 nil."
13398 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13399 (when time
13400 (apply 'encode-time (org-parse-time-string time)))))
13402 (defun org-remove-timestamp-with-keyword (keyword)
13403 "Remove all time stamps with KEYWORD in the current entry."
13404 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13405 beg)
13406 (save-excursion
13407 (org-back-to-heading t)
13408 (setq beg (point))
13409 (outline-next-heading)
13410 (while (re-search-backward re beg t)
13411 (replace-match "")
13412 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13413 (equal (char-before) ?\ ))
13414 (backward-delete-char 1)
13415 (when (string-match "^[ \t]*$" (buffer-substring
13416 (point-at-bol) (point-at-eol)))
13417 (delete-region (point-at-bol)
13418 (min (point-max) (1+ (point-at-eol))))))))))
13420 (defvar org-time-was-given) ; dynamically scoped parameter
13421 (defvar org-end-time-was-given) ; dynamically scoped parameter
13423 (defun org-at-planning-p ()
13424 "Non-nil when point is on a planning info line."
13425 ;; This is as accurate and faster than `org-element-at-point' since
13426 ;; planning info location is fixed in the section.
13427 (org-with-wide-buffer
13428 (beginning-of-line)
13429 (and (org-looking-at-p org-planning-line-re)
13430 (eq (point)
13431 (ignore-errors
13432 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13433 (org-back-to-heading t)
13434 (org-with-limited-levels (org-back-to-heading t)))
13435 (line-beginning-position 2))))))
13437 (defun org-add-planning-info (what &optional time &rest remove)
13438 "Insert new timestamp with keyword in the planning line.
13439 WHAT indicates what kind of time stamp to add. It is a symbol
13440 among `closed', `deadline', `scheduled' and nil. TIME indicates
13441 the time to use. If none is given, the user is prompted for
13442 a date. REMOVE indicates what kind of entries to remove. An old
13443 WHAT entry will also be removed."
13444 (let (org-time-was-given org-end-time-was-given default-time default-input)
13445 (catch 'exit
13446 (when (and (memq what '(scheduled deadline))
13447 (or (not time)
13448 (and (stringp time)
13449 (string-match "^[-+]+[0-9]" time))))
13450 ;; Try to get a default date/time from existing timestamp
13451 (save-excursion
13452 (org-back-to-heading t)
13453 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13454 (when (re-search-forward (if (eq what 'scheduled)
13455 org-scheduled-time-regexp
13456 org-deadline-time-regexp)
13457 end t)
13458 (setq ts (match-string 1)
13459 default-time (apply 'encode-time (org-parse-time-string ts))
13460 default-input (and ts (org-get-compact-tod ts)))))))
13461 (when what
13462 (setq time
13463 (if (stringp time)
13464 ;; This is a string (relative or absolute), set
13465 ;; proper date.
13466 (apply #'encode-time
13467 (org-read-date-analyze
13468 time default-time (decode-time default-time)))
13469 ;; If necessary, get the time from the user
13470 (or time (org-read-date nil 'to-time nil nil
13471 default-time default-input)))))
13473 (org-with-wide-buffer
13474 (org-back-to-heading t)
13475 (forward-line)
13476 (unless (bolp) (insert "\n"))
13477 (cond ((org-looking-at-p org-planning-line-re)
13478 ;; Move to current indentation.
13479 (skip-chars-forward " \t")
13480 ;; Check if we have to remove something.
13481 (dolist (type (if what (cons what remove) remove))
13482 (save-excursion
13483 (when (re-search-forward
13484 (cl-case type
13485 (closed org-closed-time-regexp)
13486 (deadline org-deadline-time-regexp)
13487 (scheduled org-scheduled-time-regexp)
13488 (otherwise
13489 (error "Invalid planning type: %s" type)))
13490 (line-end-position) t)
13491 ;; Delete until next keyword or end of line.
13492 (delete-region
13493 (match-beginning 0)
13494 (if (re-search-forward org-keyword-time-not-clock-regexp
13495 (line-end-position)
13497 (match-beginning 0)
13498 (line-end-position))))))
13499 ;; If there is nothing more to add and no more keyword
13500 ;; is left, remove the line completely.
13501 (if (and (org-looking-at-p "[ \t]*$") (not what))
13502 (delete-region (line-beginning-position)
13503 (line-beginning-position 2))
13504 ;; If we removed last keyword, do not leave trailing
13505 ;; white space at the end of line.
13506 (let ((p (point)))
13507 (save-excursion
13508 (end-of-line)
13509 (unless (= (skip-chars-backward " \t" p) 0)
13510 (delete-region (point) (line-end-position)))))))
13511 ((not what) (throw 'exit nil)) ; Nothing to do.
13512 (t (insert-before-markers "\n")
13513 (backward-char 1)
13514 (when org-adapt-indentation
13515 (org-indent-to-column (1+ (org-outline-level))))))
13516 (when what
13517 ;; Insert planning keyword.
13518 (insert (cl-case what
13519 (closed org-closed-string)
13520 (deadline org-deadline-string)
13521 (scheduled org-scheduled-string)
13522 (otherwise (error "Invalid planning type: %s" what)))
13523 " ")
13524 ;; Insert associated timestamp.
13525 (let ((ts (org-insert-time-stamp
13526 time
13527 (or org-time-was-given
13528 (and (eq what 'closed) org-log-done-with-time))
13529 (eq what 'closed)
13530 nil nil (list org-end-time-was-given))))
13531 (unless (eolp) (insert " "))
13532 ts))))))
13534 (defvar org-log-note-marker (make-marker)
13535 "Marker pointing at the entry where the note is to be inserted.")
13536 (defvar org-log-note-purpose nil)
13537 (defvar org-log-note-state nil)
13538 (defvar org-log-note-previous-state nil)
13539 (defvar org-log-note-extra nil)
13540 (defvar org-log-note-window-configuration nil)
13541 (defvar org-log-note-return-to (make-marker))
13542 (defvar org-log-note-effective-time nil
13543 "Remembered current time so that dynamically scoped
13544 `org-extend-today-until' affects timestamps in state change log")
13546 (defvar org-log-post-message nil
13547 "Message to be displayed after a log note has been stored.
13548 The auto-repeater uses this.")
13550 (defun org-add-note ()
13551 "Add a note to the current entry.
13552 This is done in the same way as adding a state change note."
13553 (interactive)
13554 (org-add-log-setup 'note))
13556 (defun org-log-beginning (&optional create)
13557 "Return expected start of log notes in current entry.
13558 When optional argument CREATE is non-nil, the function creates
13559 a drawer to store notes, if necessary. Returned position ignores
13560 narrowing."
13561 (org-with-wide-buffer
13562 (let ((drawer (org-log-into-drawer)))
13563 (cond
13564 (drawer
13565 (org-end-of-meta-data)
13566 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13567 (end (if (org-at-heading-p) (point)
13568 (save-excursion (outline-next-heading) (point))))
13569 (case-fold-search t))
13570 (catch 'exit
13571 ;; Try to find existing drawer.
13572 (while (re-search-forward regexp end t)
13573 (let ((element (org-element-at-point)))
13574 (when (eq (org-element-type element) 'drawer)
13575 (let ((cend (org-element-property :contents-end element)))
13576 (when (and (not org-log-states-order-reversed) cend)
13577 (goto-char cend)))
13578 (throw 'exit nil))))
13579 ;; No drawer found. Create one, if permitted.
13580 (when create
13581 (unless (bolp) (insert "\n"))
13582 (let ((beg (point)))
13583 (insert ":" drawer ":\n:END:\n")
13584 (org-indent-region beg (point)))
13585 (end-of-line -1)))))
13587 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13588 (skip-chars-forward " \t\n")
13589 (beginning-of-line)
13590 (unless org-log-states-order-reversed
13591 (org-skip-over-state-notes)
13592 (skip-chars-backward " \t\n")
13593 (forward-line)))))
13594 (if (bolp) (point) (line-beginning-position 2))))
13596 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13597 "Set up the post command hook to take a note.
13598 If this is about to TODO state change, the new state is expected in STATE.
13599 HOW is an indicator what kind of note should be created.
13600 EXTRA is additional text that will be inserted into the notes buffer."
13601 (move-marker org-log-note-marker (point))
13602 (setq org-log-note-purpose purpose
13603 org-log-note-state state
13604 org-log-note-previous-state prev-state
13605 org-log-note-how how
13606 org-log-note-extra extra
13607 org-log-note-effective-time (org-current-effective-time))
13608 (add-hook 'post-command-hook 'org-add-log-note 'append))
13610 (defun org-skip-over-state-notes ()
13611 "Skip past the list of State notes in an entry."
13612 (when (ignore-errors (goto-char (org-in-item-p)))
13613 (let* ((struct (org-list-struct))
13614 (prevs (org-list-prevs-alist struct))
13615 (regexp
13616 (concat "[ \t]*- +"
13617 (replace-regexp-in-string
13618 " +" " +"
13619 (org-replace-escapes
13620 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13621 `(("%d" . ,org-ts-regexp-inactive)
13622 ("%D" . ,org-ts-regexp)
13623 ("%s" . "\"\\S-+\"")
13624 ("%S" . "\"\\S-+\"")
13625 ("%t" . ,org-ts-regexp-inactive)
13626 ("%T" . ,org-ts-regexp)
13627 ("%u" . ".*?")
13628 ("%U" . ".*?")))))))
13629 (while (org-looking-at-p regexp)
13630 (goto-char (or (org-list-get-next-item (point) struct prevs)
13631 (org-list-get-item-end (point) struct)))))))
13633 (defun org-add-log-note (&optional _purpose)
13634 "Pop up a window for taking a note, and add this note later."
13635 (remove-hook 'post-command-hook 'org-add-log-note)
13636 (setq org-log-note-window-configuration (current-window-configuration))
13637 (delete-other-windows)
13638 (move-marker org-log-note-return-to (point))
13639 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13640 (goto-char org-log-note-marker)
13641 (org-switch-to-buffer-other-window "*Org Note*")
13642 (erase-buffer)
13643 (if (memq org-log-note-how '(time state))
13644 (let (current-prefix-arg) (org-store-log-note))
13645 (let ((org-inhibit-startup t)) (org-mode))
13646 (insert (format "# Insert note for %s.
13647 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13648 (cond
13649 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13650 ((eq org-log-note-purpose 'done) "closed todo item")
13651 ((eq org-log-note-purpose 'state)
13652 (format "state change from \"%s\" to \"%s\""
13653 (or org-log-note-previous-state "")
13654 (or org-log-note-state "")))
13655 ((eq org-log-note-purpose 'reschedule)
13656 "rescheduling")
13657 ((eq org-log-note-purpose 'delschedule)
13658 "no longer scheduled")
13659 ((eq org-log-note-purpose 'redeadline)
13660 "changing deadline")
13661 ((eq org-log-note-purpose 'deldeadline)
13662 "removing deadline")
13663 ((eq org-log-note-purpose 'refile)
13664 "refiling")
13665 ((eq org-log-note-purpose 'note)
13666 "this entry")
13667 (t (error "This should not happen")))))
13668 (when org-log-note-extra (insert org-log-note-extra))
13669 (setq-local org-finish-function 'org-store-log-note)
13670 (run-hooks 'org-log-buffer-setup-hook)))
13672 (defvar org-note-abort nil) ; dynamically scoped
13673 (defun org-store-log-note ()
13674 "Finish taking a log note, and insert it to where it belongs."
13675 (let ((txt (prog1 (buffer-string)
13676 (kill-buffer)))
13677 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13678 lines)
13679 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13680 (setq txt (replace-match "" t t txt)))
13681 (when (string-match "\\s-+\\'" txt)
13682 (setq txt (replace-match "" t t txt)))
13683 (setq lines (org-split-string txt "\n"))
13684 (when (org-string-nw-p note)
13685 (setq note
13686 (org-replace-escapes
13687 note
13688 (list (cons "%u" (user-login-name))
13689 (cons "%U" user-full-name)
13690 (cons "%t" (format-time-string
13691 (org-time-stamp-format 'long 'inactive)
13692 org-log-note-effective-time))
13693 (cons "%T" (format-time-string
13694 (org-time-stamp-format 'long nil)
13695 org-log-note-effective-time))
13696 (cons "%d" (format-time-string
13697 (org-time-stamp-format nil 'inactive)
13698 org-log-note-effective-time))
13699 (cons "%D" (format-time-string
13700 (org-time-stamp-format nil nil)
13701 org-log-note-effective-time))
13702 (cons "%s" (cond
13703 ((not org-log-note-state) "")
13704 ((org-string-match-p org-ts-regexp
13705 org-log-note-state)
13706 (format "\"[%s]\""
13707 (substring org-log-note-state 1 -1)))
13708 (t (format "\"%s\"" org-log-note-state))))
13709 (cons "%S"
13710 (cond
13711 ((not org-log-note-previous-state) "")
13712 ((org-string-match-p org-ts-regexp
13713 org-log-note-previous-state)
13714 (format "\"[%s]\""
13715 (substring
13716 org-log-note-previous-state 1 -1)))
13717 (t (format "\"%s\""
13718 org-log-note-previous-state)))))))
13719 (when lines (setq note (concat note " \\\\")))
13720 (push note lines))
13721 (when (and lines (not (or current-prefix-arg org-note-abort)))
13722 (with-current-buffer (marker-buffer org-log-note-marker)
13723 (org-with-wide-buffer
13724 ;; Find location for the new note.
13725 (goto-char org-log-note-marker)
13726 (set-marker org-log-note-marker nil)
13727 (goto-char (org-log-beginning t))
13728 ;; Make sure point is at the beginning of an empty line.
13729 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13730 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13731 ;; In an existing list, add a new item at the top level.
13732 ;; Otherwise, indent line like a regular one.
13733 (let ((itemp (org-in-item-p)))
13734 (if itemp
13735 (org-indent-line-to
13736 (let ((struct (save-excursion
13737 (goto-char itemp) (org-list-struct))))
13738 (org-list-get-ind (org-list-get-top-point struct) struct)))
13739 (org-indent-line)))
13740 (insert (org-list-bullet-string "-") (pop lines))
13741 (let ((ind (org-list-item-body-column (line-beginning-position))))
13742 (dolist (line lines)
13743 (insert "\n")
13744 (org-indent-line-to ind)
13745 (insert line)))
13746 (message "Note stored")
13747 (org-back-to-heading t)
13748 (org-cycle-hide-drawers 'children))
13749 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13750 ;; from within `org-add-log-note' because `buffer-undo-list'
13751 ;; is then modified outside of `org-with-remote-undo'.
13752 (when (eq this-command 'org-agenda-todo)
13753 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13754 ;; Don't add undo information when called from `org-agenda-todo'.
13755 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13756 (set-window-configuration org-log-note-window-configuration)
13757 (with-current-buffer (marker-buffer org-log-note-return-to)
13758 (goto-char org-log-note-return-to))
13759 (move-marker org-log-note-return-to nil)
13760 (when org-log-post-message (message "%s" org-log-post-message))))
13762 (defun org-remove-empty-drawer-at (pos)
13763 "Remove an empty drawer at position POS.
13764 POS may also be a marker."
13765 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13766 (org-with-wide-buffer
13767 (goto-char pos)
13768 (let ((drawer (org-element-at-point)))
13769 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13770 (not (org-element-property :contents-begin drawer)))
13771 (delete-region (org-element-property :begin drawer)
13772 (progn (goto-char (org-element-property :end drawer))
13773 (skip-chars-backward " \r\t\n")
13774 (forward-line)
13775 (point))))))))
13777 (defvar org-ts-type nil)
13778 (defun org-sparse-tree (&optional arg type)
13779 "Create a sparse tree, prompt for the details.
13780 This command can create sparse trees. You first need to select the type
13781 of match used to create the tree:
13783 t Show all TODO entries.
13784 T Show entries with a specific TODO keyword.
13785 m Show entries selected by a tags/property match.
13786 p Enter a property name and its value (both with completion on existing
13787 names/values) and show entries with that property.
13788 r Show entries matching a regular expression (`/' can be used as well).
13789 b Show deadlines and scheduled items before a date.
13790 a Show deadlines and scheduled items after a date.
13791 d Show deadlines due within `org-deadline-warning-days'.
13792 D Show deadlines and scheduled items between a date range."
13793 (interactive "P")
13794 (setq type (or type org-sparse-tree-default-date-type))
13795 (setq org-ts-type type)
13796 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13797 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13798 \[c]ycle through date types: %s"
13799 (cl-case type
13800 (all "all timestamps")
13801 (scheduled "only scheduled")
13802 (deadline "only deadline")
13803 (active "only active timestamps")
13804 (inactive "only inactive timestamps")
13805 (closed "with a closed time-stamp")
13806 (otherwise "scheduled/deadline")))
13807 (let ((answer (read-char-exclusive)))
13808 (cl-case answer
13810 (org-sparse-tree
13812 (cadr
13813 (memq type '(nil all scheduled deadline active inactive closed)))))
13814 (?d (call-interactively 'org-check-deadlines))
13815 (?b (call-interactively 'org-check-before-date))
13816 (?a (call-interactively 'org-check-after-date))
13817 (?D (call-interactively 'org-check-dates-range))
13818 (?t (call-interactively 'org-show-todo-tree))
13819 (?T (org-show-todo-tree '(4)))
13820 (?m (call-interactively 'org-match-sparse-tree))
13821 ((?p ?P)
13822 (let* ((kwd (completing-read
13823 "Property: " (mapcar #'list (org-buffer-property-keys))))
13824 (value (completing-read
13825 "Value: " (mapcar #'list (org-property-values kwd)))))
13826 (unless (string-match "\\`{.*}\\'" value)
13827 (setq value (concat "\"" value "\"")))
13828 (org-match-sparse-tree arg (concat kwd "=" value))))
13829 ((?r ?R ?/) (call-interactively 'org-occur))
13830 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13832 (defvar-local org-occur-highlights nil
13833 "List of overlays used for occur matches.")
13834 (defvar-local org-occur-parameters nil
13835 "Parameters of the active org-occur calls.
13836 This is a list, each call to org-occur pushes as cons cell,
13837 containing the regular expression and the callback, onto the list.
13838 The list can contain several entries if `org-occur' has been called
13839 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13840 will only contain one set of parameters. When the highlights are
13841 removed (for example with `C-c C-c', or with the next edit (depending
13842 on `org-remove-highlights-with-change'), this variable is emptied
13843 as well.")
13845 (defun org-occur (regexp &optional keep-previous callback)
13846 "Make a compact tree which shows all matches of REGEXP.
13847 The tree will show the lines where the regexp matches, and all higher
13848 headlines above the match. It will also show the heading after the match,
13849 to make sure editing the matching entry is easy.
13850 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13851 call to `org-occur' will be kept, to allow stacking of calls to this
13852 command.
13853 If CALLBACK is non-nil, it is a function which is called to confirm
13854 that the match should indeed be shown."
13855 (interactive "sRegexp: \nP")
13856 (when (equal regexp "")
13857 (user-error "Regexp cannot be empty"))
13858 (unless keep-previous
13859 (org-remove-occur-highlights nil nil t))
13860 (push (cons regexp callback) org-occur-parameters)
13861 (let ((cnt 0))
13862 (save-excursion
13863 (goto-char (point-min))
13864 (when (or (not keep-previous) ; do not want to keep
13865 (not org-occur-highlights)) ; no previous matches
13866 ;; hide everything
13867 (org-overview))
13868 (while (re-search-forward regexp nil t)
13869 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13870 (when (or (not callback)
13871 (save-match-data (funcall callback)))
13872 (setq cnt (1+ cnt))
13873 (when org-highlight-sparse-tree-matches
13874 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13875 (org-show-context 'occur-tree))))
13876 (when org-remove-highlights-with-change
13877 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13878 nil 'local))
13879 (unless org-sparse-tree-open-archived-trees
13880 (org-hide-archived-subtrees (point-min) (point-max)))
13881 (run-hooks 'org-occur-hook)
13882 (when (org-called-interactively-p 'interactive)
13883 (message "%d match(es) for regexp %s" cnt regexp))
13884 cnt))
13886 (defun org-occur-next-match (&optional n _reset)
13887 "Function for `next-error-function' to find sparse tree matches.
13888 N is the number of matches to move, when negative move backwards.
13889 This function always goes back to the starting point when no
13890 match is found."
13891 (let* ((limit (if (< n 0) (point-min) (point-max)))
13892 (search-func (if (< n 0)
13893 'previous-single-char-property-change
13894 'next-single-char-property-change))
13895 (n (abs n))
13896 (pos (point))
13898 (catch 'exit
13899 (while (setq p1 (funcall search-func (point) 'org-type))
13900 (when (equal p1 limit)
13901 (goto-char pos)
13902 (user-error "No more matches"))
13903 (when (equal (get-char-property p1 'org-type) 'org-occur)
13904 (setq n (1- n))
13905 (when (= n 0)
13906 (goto-char p1)
13907 (throw 'exit (point))))
13908 (goto-char p1))
13909 (goto-char p1)
13910 (user-error "No more matches"))))
13912 (defun org-show-context (&optional key)
13913 "Make sure point and context are visible.
13914 Optional argument KEY, when non-nil, is a symbol. See
13915 `org-show-context-detail' for allowed values and how much is to
13916 be shown."
13917 (org-show-set-visibility
13918 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13919 ((cdr (assq key org-show-context-detail)))
13920 (t (cdr (assq 'default org-show-context-detail))))))
13922 (defun org-show-set-visibility (detail)
13923 "Set visibility around point according to DETAIL.
13924 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13925 `tree', `canonical' or t. See `org-show-context-detail' for more
13926 information."
13927 (unless (org-before-first-heading-p)
13928 ;; Show current heading and possibly its entry, following headline
13929 ;; or all children.
13930 (if (and (org-at-heading-p) (not (eq detail 'local)))
13931 (org-flag-heading nil)
13932 (org-show-entry)
13933 (org-with-limited-levels
13934 (cl-case detail
13935 ((tree canonical t) (org-show-children))
13936 ((nil minimal ancestors))
13937 (t (save-excursion
13938 (outline-next-heading)
13939 (org-flag-heading nil))))))
13940 ;; Show all siblings.
13941 (when (eq detail 'lineage) (org-show-siblings))
13942 ;; Show ancestors, possibly with their children.
13943 (when (memq detail '(ancestors lineage tree canonical t))
13944 (save-excursion
13945 (while (org-up-heading-safe)
13946 (org-flag-heading nil)
13947 (when (memq detail '(canonical t)) (org-show-entry))
13948 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13950 (defvar org-reveal-start-hook nil
13951 "Hook run before revealing a location.")
13953 (defun org-reveal (&optional siblings)
13954 "Show current entry, hierarchy above it, and the following headline.
13956 This can be used to show a consistent set of context around
13957 locations exposed with `org-show-context'.
13959 With optional argument SIBLINGS, on each level of the hierarchy all
13960 siblings are shown. This repairs the tree structure to what it would
13961 look like when opened with hierarchical calls to `org-cycle'.
13963 With double optional argument \\[universal-argument] \\[universal-argument], \
13964 go to the parent and show the
13965 entire tree."
13966 (interactive "P")
13967 (run-hooks 'org-reveal-start-hook)
13968 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13969 ((equal siblings '(16))
13970 (save-excursion
13971 (when (org-up-heading-safe)
13972 (org-show-subtree)
13973 (run-hook-with-args 'org-cycle-hook 'subtree))))
13974 (t (org-show-set-visibility 'lineage))))
13976 (defun org-highlight-new-match (beg end)
13977 "Highlight from BEG to END and mark the highlight is an occur headline."
13978 (let ((ov (make-overlay beg end)))
13979 (overlay-put ov 'face 'secondary-selection)
13980 (overlay-put ov 'org-type 'org-occur)
13981 (push ov org-occur-highlights)))
13983 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13984 "Remove the occur highlights from the buffer.
13985 BEG and END are ignored. If NOREMOVE is nil, remove this function
13986 from the `before-change-functions' in the current buffer."
13987 (interactive)
13988 (unless org-inhibit-highlight-removal
13989 (mapc #'delete-overlay org-occur-highlights)
13990 (setq org-occur-highlights nil)
13991 (setq org-occur-parameters nil)
13992 (unless noremove
13993 (remove-hook 'before-change-functions
13994 'org-remove-occur-highlights 'local))))
13996 ;;;; Priorities
13998 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13999 "Regular expression matching the priority indicator.")
14001 (defvar org-remove-priority-next-time nil)
14003 (defun org-priority-up ()
14004 "Increase the priority of the current item."
14005 (interactive)
14006 (org-priority 'up))
14008 (defun org-priority-down ()
14009 "Decrease the priority of the current item."
14010 (interactive)
14011 (org-priority 'down))
14013 (defun org-priority (&optional action _show)
14014 "Change the priority of an item.
14015 ACTION can be `set', `up', `down', or a character."
14016 (interactive "P")
14017 (if (equal action '(4))
14018 (org-show-priority)
14019 (unless org-enable-priority-commands
14020 (user-error "Priority commands are disabled"))
14021 (setq action (or action 'set))
14022 (let (current new news have remove)
14023 (save-excursion
14024 (org-back-to-heading t)
14025 (when (looking-at org-priority-regexp)
14026 (setq current (string-to-char (match-string 2))
14027 have t))
14028 (cond
14029 ((eq action 'remove)
14030 (setq remove t new ?\ ))
14031 ((or (eq action 'set)
14032 (if (featurep 'xemacs) (characterp action) (integerp action)))
14033 (if (not (eq action 'set))
14034 (setq new action)
14035 (message "Priority %c-%c, SPC to remove: "
14036 org-highest-priority org-lowest-priority)
14037 (save-match-data
14038 (setq new (read-char-exclusive))))
14039 (when (and (= (upcase org-highest-priority) org-highest-priority)
14040 (= (upcase org-lowest-priority) org-lowest-priority))
14041 (setq new (upcase new)))
14042 (cond ((equal new ?\ ) (setq remove t))
14043 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14044 (user-error "Priority must be between `%c' and `%c'"
14045 org-highest-priority org-lowest-priority))))
14046 ((eq action 'up)
14047 (setq new (if have
14048 (1- current) ; normal cycling
14049 ;; last priority was empty
14050 (if (eq last-command this-command)
14051 org-lowest-priority ; wrap around empty to lowest
14052 ;; default
14053 (if org-priority-start-cycle-with-default
14054 org-default-priority
14055 (1- org-default-priority))))))
14056 ((eq action 'down)
14057 (setq new (if have
14058 (1+ current) ; normal cycling
14059 ;; last priority was empty
14060 (if (eq last-command this-command)
14061 org-highest-priority ; wrap around empty to highest
14062 ;; default
14063 (if org-priority-start-cycle-with-default
14064 org-default-priority
14065 (1+ org-default-priority))))))
14066 (t (user-error "Invalid action")))
14067 (when (or (< (upcase new) org-highest-priority)
14068 (> (upcase new) org-lowest-priority))
14069 (if (and (memq action '(up down))
14070 (not have) (not (eq last-command this-command)))
14071 ;; `new' is from default priority
14072 (error
14073 "The default can not be set, see `org-default-priority' why")
14074 ;; normal cycling: `new' is beyond highest/lowest priority
14075 ;; and is wrapped around to the empty priority
14076 (setq remove t)))
14077 (setq news (format "%c" new))
14078 (if have
14079 (if remove
14080 (replace-match "" t t nil 1)
14081 (replace-match news t t nil 2))
14082 (if remove
14083 (user-error "No priority cookie found in line")
14084 (let ((case-fold-search nil))
14085 (looking-at org-todo-line-regexp))
14086 (if (match-end 2)
14087 (progn
14088 (goto-char (match-end 2))
14089 (insert " [#" news "]"))
14090 (goto-char (match-beginning 3))
14091 (insert "[#" news "] "))))
14092 (org-set-tags nil 'align))
14093 (if remove
14094 (message "Priority removed")
14095 (message "Priority of current item set to %s" news)))))
14097 (defun org-show-priority ()
14098 "Show the priority of the current item.
14099 This priority is composed of the main priority given with the [#A] cookies,
14100 and by additional input from the age of a schedules or deadline entry."
14101 (interactive)
14102 (let ((pri (if (eq major-mode 'org-agenda-mode)
14103 (org-get-at-bol 'priority)
14104 (save-excursion
14105 (save-match-data
14106 (beginning-of-line)
14107 (and (looking-at org-heading-regexp)
14108 (org-get-priority (match-string 0))))))))
14109 (message "Priority is %d" (if pri pri -1000))))
14111 (defun org-get-priority (s)
14112 "Find priority cookie and return priority."
14113 (save-match-data
14114 (if (functionp org-get-priority-function)
14115 (funcall org-get-priority-function)
14116 (if (not (string-match org-priority-regexp s))
14117 (* 1000 (- org-lowest-priority org-default-priority))
14118 (* 1000 (- org-lowest-priority
14119 (string-to-char (match-string 2 s))))))))
14121 ;;;; Tags
14123 (defvar org-agenda-archives-mode)
14124 (defvar org-map-continue-from nil
14125 "Position from where mapping should continue.
14126 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14128 (defvar org-scanner-tags nil
14129 "The current tag list while the tags scanner is running.")
14131 (defvar org-trust-scanner-tags nil
14132 "Should `org-get-tags-at' use the tags for the scanner.
14133 This is for internal dynamical scoping only.
14134 When this is non-nil, the function `org-get-tags-at' will return the value
14135 of `org-scanner-tags' instead of building the list by itself. This
14136 can lead to large speed-ups when the tags scanner is used in a file with
14137 many entries, and when the list of tags is retrieved, for example to
14138 obtain a list of properties. Building the tags list for each entry in such
14139 a file becomes an N^2 operation - but with this variable set, it scales
14140 as N.")
14142 (defvar org--matcher-tags-todo-only nil)
14144 (defun org-scan-tags (action matcher todo-only &optional start-level)
14145 "Scan headline tags with inheritance and produce output ACTION.
14147 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14148 or `agenda' to produce an entry list for an agenda view. It can also be
14149 a Lisp form or a function that should be called at each matched headline, in
14150 this case the return value is a list of all return values from these calls.
14152 MATCHER is a function accepting three arguments, returning
14153 a non-nil value whenever a given set of tags qualifies a headline
14154 for inclusion. See `org-make-tags-matcher' for more information.
14155 As a special case, it can also be set to t (respectively nil) in
14156 order to match all (respectively none) headline.
14158 When TODO-ONLY is non-nil, only lines with a not-done TODO
14159 keyword are included in the output.
14161 START-LEVEL can be a string with asterisks, reducing the scope to
14162 headlines matching this string."
14163 (require 'org-agenda)
14164 (let* ((re (concat "^"
14165 (if start-level
14166 ;; Get the correct level to match
14167 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14168 org-outline-regexp)
14169 " *\\(\\<\\("
14170 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14171 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14172 (props (list 'face 'default
14173 'done-face 'org-agenda-done
14174 'undone-face 'default
14175 'mouse-face 'highlight
14176 'org-not-done-regexp org-not-done-regexp
14177 'org-todo-regexp org-todo-regexp
14178 'org-complex-heading-regexp org-complex-heading-regexp
14179 'help-echo
14180 (format "mouse-2 or RET jump to org file %s"
14181 (abbreviate-file-name
14182 (or (buffer-file-name (buffer-base-buffer))
14183 (buffer-name (buffer-base-buffer)))))))
14184 (org-map-continue-from nil)
14185 lspos tags tags-list
14186 (tags-alist (list (cons 0 org-file-tags)))
14187 (llast 0) rtn rtn1 level category i txt
14188 todo marker entry priority
14189 ts-date ts-date-type ts-date-pair)
14190 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14191 (setq action (list 'lambda nil action)))
14192 (save-excursion
14193 (goto-char (point-min))
14194 (when (eq action 'sparse-tree)
14195 (org-overview)
14196 (org-remove-occur-highlights))
14197 (while (let (case-fold-search)
14198 (re-search-forward re nil t))
14199 (setq org-map-continue-from nil)
14200 (catch :skip
14201 (setq todo
14202 ;; TODO: is the 1-2 difference a bug?
14203 (when (match-end 1) (org-match-string-no-properties 2))
14204 tags (when (match-end 4) (org-match-string-no-properties 4)))
14205 (goto-char (setq lspos (match-beginning 0)))
14206 (setq level (org-reduced-level (org-outline-level))
14207 category (org-get-category))
14208 (when (eq action 'agenda)
14209 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14210 ts-date (car ts-date-pair)
14211 ts-date-type (cdr ts-date-pair)))
14212 (setq i llast llast level)
14213 ;; remove tag lists from same and sublevels
14214 (while (>= i level)
14215 (when (setq entry (assoc i tags-alist))
14216 (setq tags-alist (delete entry tags-alist)))
14217 (setq i (1- i)))
14218 ;; add the next tags
14219 (when tags
14220 (setq tags (org-split-string tags ":")
14221 tags-alist
14222 (cons (cons level tags) tags-alist)))
14223 ;; compile tags for current headline
14224 (setq tags-list
14225 (if org-use-tag-inheritance
14226 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14227 tags)
14228 org-scanner-tags tags-list)
14229 (when org-use-tag-inheritance
14230 (setcdr (car tags-alist)
14231 (mapcar (lambda (x)
14232 (setq x (copy-sequence x))
14233 (org-add-prop-inherited x))
14234 (cdar tags-alist))))
14235 (when (and tags org-use-tag-inheritance
14236 (or (not (eq t org-use-tag-inheritance))
14237 org-tags-exclude-from-inheritance))
14238 ;; Selective inheritance, remove uninherited ones.
14239 (setcdr (car tags-alist)
14240 (org-remove-uninherited-tags (cdar tags-alist))))
14241 (when (and
14243 ;; eval matcher only when the todo condition is OK
14244 (and (or (not todo-only) (member todo org-not-done-keywords))
14245 (if (functionp matcher)
14246 (let ((case-fold-search t) (org-trust-scanner-tags t))
14247 (funcall matcher todo tags-list level))
14248 matcher))
14250 ;; Call the skipper, but return t if it does not
14251 ;; skip, so that the `and' form continues evaluating.
14252 (progn
14253 (unless (eq action 'sparse-tree) (org-agenda-skip))
14256 ;; Check if timestamps are deselecting this entry
14257 (or (not todo-only)
14258 (and (member todo org-not-done-keywords)
14259 (or (not org-agenda-tags-todo-honor-ignore-options)
14260 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14262 ;; select this headline
14263 (cond
14264 ((eq action 'sparse-tree)
14265 (and org-highlight-sparse-tree-matches
14266 (org-get-heading) (match-end 0)
14267 (org-highlight-new-match
14268 (match-beginning 1) (match-end 1)))
14269 (org-show-context 'tags-tree))
14270 ((eq action 'agenda)
14271 (setq txt (org-agenda-format-item
14273 (concat
14274 (if (eq org-tags-match-list-sublevels 'indented)
14275 (make-string (1- level) ?.) "")
14276 (org-get-heading))
14277 (make-string level ?\s)
14278 category
14279 tags-list)
14280 priority (org-get-priority txt))
14281 (goto-char lspos)
14282 (setq marker (org-agenda-new-marker))
14283 (org-add-props txt props
14284 'org-marker marker 'org-hd-marker marker 'org-category category
14285 'todo-state todo
14286 'ts-date ts-date
14287 'priority priority
14288 'type (concat "tagsmatch" ts-date-type))
14289 (push txt rtn))
14290 ((functionp action)
14291 (setq org-map-continue-from nil)
14292 (save-excursion
14293 (setq rtn1 (funcall action))
14294 (push rtn1 rtn)))
14295 (t (user-error "Invalid action")))
14297 ;; if we are to skip sublevels, jump to end of subtree
14298 (unless org-tags-match-list-sublevels
14299 (org-end-of-subtree t)
14300 (backward-char 1))))
14301 ;; Get the correct position from where to continue
14302 (if org-map-continue-from
14303 (goto-char org-map-continue-from)
14304 (and (= (point) lspos) (end-of-line 1)))))
14305 (when (and (eq action 'sparse-tree)
14306 (not org-sparse-tree-open-archived-trees))
14307 (org-hide-archived-subtrees (point-min) (point-max)))
14308 (nreverse rtn)))
14310 (defun org-remove-uninherited-tags (tags)
14311 "Remove all tags that are not inherited from the list TAGS."
14312 (cond
14313 ((eq org-use-tag-inheritance t)
14314 (if org-tags-exclude-from-inheritance
14315 (org-delete-all org-tags-exclude-from-inheritance tags)
14316 tags))
14317 ((not org-use-tag-inheritance) nil)
14318 ((stringp org-use-tag-inheritance)
14319 (delq nil (mapcar
14320 (lambda (x)
14321 (if (and (string-match org-use-tag-inheritance x)
14322 (not (member x org-tags-exclude-from-inheritance)))
14323 x nil))
14324 tags)))
14325 ((listp org-use-tag-inheritance)
14326 (delq nil (mapcar
14327 (lambda (x)
14328 (if (member x org-use-tag-inheritance) x nil))
14329 tags)))))
14331 (defun org-match-sparse-tree (&optional todo-only match)
14332 "Create a sparse tree according to tags string MATCH.
14333 MATCH can contain positive and negative selection of tags, like
14334 \"+WORK+URGENT-WITHBOSS\".
14335 If optional argument TODO-ONLY is non-nil, only select lines that are
14336 also TODO lines."
14337 (interactive "P")
14338 (org-agenda-prepare-buffers (list (current-buffer)))
14339 (let ((org--matcher-tags-todo-only todo-only))
14340 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14341 org--matcher-tags-todo-only)))
14343 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14345 (defvar org-cached-props nil)
14346 (defun org-cached-entry-get (pom property)
14347 (if (or (eq t org-use-property-inheritance)
14348 (and (stringp org-use-property-inheritance)
14349 (let ((case-fold-search t))
14350 (org-string-match-p org-use-property-inheritance property)))
14351 (and (listp org-use-property-inheritance)
14352 (member-ignore-case property org-use-property-inheritance)))
14353 ;; Caching is not possible, check it directly.
14354 (org-entry-get pom property 'inherit)
14355 ;; Get all properties, so we can do complicated checks easily.
14356 (cdr (assoc-string property
14357 (or org-cached-props
14358 (setq org-cached-props (org-entry-properties pom)))
14359 t))))
14361 (defun org-global-tags-completion-table (&optional files)
14362 "Return the list of all tags in all agenda buffer/files.
14363 Optional FILES argument is a list of files which can be used
14364 instead of the agenda files."
14365 (save-excursion
14366 (org-uniquify
14367 (delq nil
14368 (apply 'append
14369 (mapcar
14370 (lambda (file)
14371 (set-buffer (find-file-noselect file))
14372 (append (org-get-buffer-tags)
14373 (mapcar (lambda (x) (if (stringp (car-safe x))
14374 (list (car-safe x)) nil))
14375 org-tag-alist)))
14376 (if (and files (car files))
14377 files
14378 (org-agenda-files))))))))
14380 (defun org-make-tags-matcher (match)
14381 "Create the TAGS/TODO matcher form for the selection string MATCH.
14383 Returns a cons of the selection string MATCH and a function
14384 implementing the matcher.
14386 The matcher is to be called at an Org entry, with point on the
14387 headline, and returns non-nil if the entry matches the selection
14388 string MATCH. It must be called with three arguments: the TODO
14389 keyword at the entry (or nil if none), the list of all tags at
14390 the entry including inherited ones and the reduced level of the
14391 headline. Additionally, the category of the entry, if any, must
14392 be specified as the text property `org-category' on the headline.
14394 This function sets the variable `org--matcher-tags-todo-only' to
14395 a non-nil value if the matcher restricts matching to TODO
14396 entries, otherwise it is not touched.
14398 See also `org-scan-tags'."
14399 (unless match
14400 ;; Get a new match request, with completion against the global
14401 ;; tags table and the local tags in current buffer.
14402 (let ((org-last-tags-completion-table
14403 (org-uniquify
14404 (delq nil (append (org-get-buffer-tags)
14405 (org-global-tags-completion-table))))))
14406 (setq match
14407 (completing-read
14408 "Match: "
14409 'org-tags-completion-function nil nil nil 'org-tags-history))))
14411 (let ((match0 match)
14412 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14413 (start 0)
14414 tagsmatch todomatch tagsmatcher todomatcher)
14416 ;; Expand group tags.
14417 (setq match (org-tags-expand match))
14419 ;; Check if there is a TODO part of this match, which would be the
14420 ;; part after a "/". To make sure that this slash is not part of
14421 ;; a property value to be matched against, we also check that
14422 ;; there is no / after that slash. First, find the last slash.
14423 (let ((s 0))
14424 (while (string-match "/+" match s)
14425 (setq start (match-beginning 0))
14426 (setq s (match-end 0))))
14427 (if (and (string-match "/+" match start)
14428 (not (string-match-p "\"" match start)))
14429 ;; Match contains also a TODO-matching request.
14430 (progn
14431 (setq tagsmatch (substring match 0 (match-beginning 0)))
14432 (setq todomatch (substring match (match-end 0)))
14433 (when (string-match "\\`!" todomatch)
14434 (setq org--matcher-tags-todo-only t)
14435 (setq todomatch (substring todomatch 1)))
14436 (when (string-match "\\`\\s-*\\'" todomatch)
14437 (setq todomatch nil)))
14438 ;; Only matching tags.
14439 (setq tagsmatch match)
14440 (setq todomatch nil))
14442 ;; Make the tags matcher.
14443 (when (org-string-nw-p tagsmatch)
14444 (let ((orlist nil)
14445 (orterms (org-split-string tagsmatch "|"))
14446 term)
14447 (while (setq term (pop orterms))
14448 (while (and (equal (substring term -1) "\\") orterms)
14449 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14450 (while (string-match re term)
14451 (let* ((rest (substring term (match-end 0)))
14452 (minus (and (match-end 1)
14453 (equal (match-string 1 term) "-")))
14454 (tag (save-match-data
14455 (replace-regexp-in-string
14456 "\\\\-" "-" (match-string 2 term))))
14457 (regexp (eq (string-to-char tag) ?{))
14458 (levelp (match-end 4))
14459 (propp (match-end 5))
14461 (cond
14462 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14463 (levelp
14464 `(,(org-op-to-function (match-string 3 term))
14465 level
14466 ,(string-to-number (match-string 4 term))))
14467 (propp
14468 (let* ((gv (pcase (upcase (match-string 5 term))
14469 ("CATEGORY"
14470 '(get-text-property (point) 'org-category))
14471 ("TODO" 'todo)
14472 (p `(org-cached-entry-get nil ,p))))
14473 (pv (match-string 7 term))
14474 (regexp (eq (string-to-char pv) ?{))
14475 (strp (eq (string-to-char pv) ?\"))
14476 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14477 (po (org-op-to-function (match-string 6 term)
14478 (if timep 'time strp))))
14479 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14480 (when timep (setq pv (org-matcher-time pv)))
14481 (cond ((and regexp (eq po 'org<>))
14482 `(not (string-match ,pv (or ,gv ""))))
14483 (regexp `(string-match ,pv (or ,gv "")))
14484 (strp `(,po (or ,gv "") ,pv))
14486 `(,po
14487 (string-to-number (or ,gv ""))
14488 ,(string-to-number pv))))))
14489 (t `(member ,tag tags-list)))))
14490 (push (if minus `(not ,mm) mm) tagsmatcher)
14491 (setq term rest)))
14492 (push `(and ,@tagsmatcher) orlist)
14493 (setq tagsmatcher nil))
14494 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14496 ;; Make the TODO matcher.
14497 (when (org-string-nw-p todomatch)
14498 (let ((orlist nil))
14499 (dolist (term (org-split-string todomatch "|"))
14500 (while (string-match re term)
14501 (let* ((minus (and (match-end 1)
14502 (equal (match-string 1 term) "-")))
14503 (kwd (match-string 2 term))
14504 (regexp (eq (string-to-char kwd) ?{))
14505 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14506 `(equal todo ,kwd))))
14507 (push (if minus `(not ,mm) mm) todomatcher))
14508 (setq term (substring term (match-end 0))))
14509 (push (if (> (length todomatcher) 1)
14510 (cons 'and todomatcher)
14511 (car todomatcher))
14512 orlist)
14513 (setq todomatcher nil))
14514 (setq todomatcher (cons 'or orlist))))
14516 ;; Return the string and function of the matcher.
14517 (let ((matcher (if todomatcher `(and ,tagsmatcher ,todomatcher)
14518 tagsmatcher)))
14519 (when org--matcher-tags-todo-only
14520 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14521 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14523 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14524 "Expand group tags in MATCH.
14526 This replaces every group tag in MATCH with a regexp tag search.
14527 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14528 will be replaced like this:
14530 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14531 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14532 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14534 Replacing by a regexp preserves the structure of the match.
14535 E.g., this expansion
14537 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14539 will match anything tagged with \"Lab\" and \"Home\", or tagged
14540 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14542 A group tag in MATCH can contain regular expressions of its own.
14543 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14544 will be replaced like this:
14546 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14548 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14549 assumed to be a single group tag, and the function will return
14550 the list of tags in this group.
14552 When DOWNCASE is non-nil, expand downcased TAGS."
14553 (if org-group-tags
14554 (let* ((case-fold-search t)
14555 (stable org-mode-syntax-table)
14556 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14557 (taggroups (if downcased
14558 (mapcar (lambda (tg) (mapcar #'downcase tg))
14559 taggroups)
14560 taggroups))
14561 (taggroups-keys (mapcar #'car taggroups))
14562 (return-match (if downcased (downcase match) match))
14563 (count 0)
14564 (work-already-expanded tags-already-expanded)
14565 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14566 ;; @ and _ are allowed as word-components in tags.
14567 (modify-syntax-entry ?@ "w" stable)
14568 (modify-syntax-entry ?_ "w" stable)
14569 ;; Temporarily replace regexp-expressions in the match-expression.
14570 (while (string-match "{.+?}" return-match)
14571 (cl-incf count)
14572 (push (match-string 0 return-match) regexps-in-match)
14573 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14574 (while (and taggroups-keys
14575 (with-syntax-table stable
14576 (string-match
14577 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14578 (regexp-opt taggroups-keys) "\\>\\)")
14579 return-match)))
14580 (let* ((dir (match-string 1 return-match))
14581 (tag (match-string 2 return-match))
14582 (tag (if downcased (downcase tag) tag)))
14583 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14584 (member tag work-already-expanded))
14585 (setq tags-in-group (assoc tag taggroups))
14586 (push tag work-already-expanded)
14587 ;; Recursively expand each tag in the group, if the tag hasn't
14588 ;; already been expanded. Restore the match-data after all recursive calls.
14589 (save-match-data
14590 (let (tags-expanded)
14591 (dolist (x (cdr tags-in-group))
14592 (if (and (member x taggroups-keys)
14593 (not (member x work-already-expanded)))
14594 (setq tags-expanded
14595 (delete-dups
14596 (append
14597 (org-tags-expand x t downcased
14598 work-already-expanded)
14599 tags-expanded)))
14600 (setq tags-expanded
14601 (append (list x) tags-expanded)))
14602 (setq work-already-expanded
14603 (delete-dups
14604 (append tags-expanded
14605 work-already-expanded))))
14606 (setq tags-in-group
14607 (delete-dups (cons (car tags-in-group)
14608 tags-expanded)))))
14609 ;; Filter tag-regexps from tags.
14610 (setq regexp-in-group-escaped
14611 (delq nil (mapcar (lambda (x)
14612 (if (stringp x)
14613 (and (equal "{" (substring x 0 1))
14614 (equal "}" (substring x -1))
14617 tags-in-group))
14618 regexp-in-group
14619 (mapcar (lambda (x)
14620 (substring x 1 -1))
14621 regexp-in-group-escaped)
14622 tags-in-group
14623 (delq nil (mapcar (lambda (x)
14624 (if (stringp x)
14625 (and (not (equal "{" (substring x 0 1)))
14626 (not (equal "}" (substring x -1)))
14629 tags-in-group)))
14630 ;; If single-as-list, do no more in the while-loop.
14631 (if (not single-as-list)
14632 (progn
14633 (when regexp-in-group
14634 (setq regexp-in-group
14635 (concat "\\|"
14636 (mapconcat 'identity regexp-in-group
14637 "\\|"))))
14638 (setq tags-in-group
14639 (concat dir
14640 "{\\<"
14641 (regexp-opt tags-in-group)
14642 "\\>"
14643 regexp-in-group
14644 "}"))
14645 (when (stringp tags-in-group)
14646 (org-add-props tags-in-group '(grouptag t)))
14647 (setq return-match
14648 (replace-match tags-in-group t t return-match)))
14649 (setq tags-in-group
14650 (append regexp-in-group-escaped tags-in-group))))
14651 (setq taggroups-keys (delete tag taggroups-keys))))
14652 ;; Add the regular expressions back into the match-expression again.
14653 (while regexps-in-match
14654 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14655 (pop regexps-in-match)
14656 return-match t t))
14657 (cl-decf count))
14658 (if single-as-list
14659 (if tags-in-group tags-in-group (list return-match))
14660 return-match))
14661 (if single-as-list
14662 (list (if downcased (downcase match) match))
14663 match)))
14665 (defun org-op-to-function (op &optional stringp)
14666 "Turn an operator into the appropriate function."
14667 (setq op
14668 (cond
14669 ((equal op "<" ) '(< string< org-time<))
14670 ((equal op ">" ) '(> org-string> org-time>))
14671 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14672 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14673 ((member op '("=" "==")) '(= string= org-time=))
14674 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14675 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14677 (defun org<> (a b) (not (= a b)))
14678 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14679 (defun org-string>= (a b) (not (string< a b)))
14680 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14681 (defun org-string<> (a b) (not (string= a b)))
14682 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14683 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14684 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14685 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14686 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14687 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14688 (defun org-2ft (s)
14689 "Convert S to a floating point time.
14690 If S is already a number, just return it. If it is a string, parse
14691 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14692 (cond
14693 ((numberp s) s)
14694 ((stringp s)
14695 (condition-case nil
14696 (float-time (apply 'encode-time (org-parse-time-string s)))
14697 (error 0.)))
14698 (t 0.)))
14700 (defun org-time-today ()
14701 "Time in seconds today at 0:00.
14702 Returns the float number of seconds since the beginning of the
14703 epoch to the beginning of today (00:00)."
14704 (float-time (apply 'encode-time
14705 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14707 (defun org-matcher-time (s)
14708 "Interpret a time comparison value."
14709 (save-match-data
14710 (cond
14711 ((string= s "<now>") (float-time))
14712 ((string= s "<today>") (org-time-today))
14713 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14714 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14715 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14716 (+ (org-time-today)
14717 (* (string-to-number (match-string 1 s))
14718 (cdr (assoc (match-string 2 s)
14719 '(("d" . 86400.0) ("w" . 604800.0)
14720 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14721 (t (org-2ft s)))))
14723 (defun org-match-any-p (re list)
14724 "Does re match any element of list?"
14725 (setq list (mapcar (lambda (x) (string-match re x)) list))
14726 (delq nil list))
14728 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14729 (defvar org-tags-overlay (make-overlay 1 1))
14730 (org-detach-overlay org-tags-overlay)
14732 (defun org-get-local-tags-at (&optional pos)
14733 "Get a list of tags defined in the current headline."
14734 (org-get-tags-at pos 'local))
14736 (defun org-get-local-tags ()
14737 "Get a list of tags defined in the current headline."
14738 (org-get-tags-at nil 'local))
14740 (defun org-get-tags-at (&optional pos local)
14741 "Get a list of all headline tags applicable at POS.
14742 POS defaults to point. If tags are inherited, the list contains
14743 the targets in the same sequence as the headlines appear, i.e.
14744 the tags of the current headline come last.
14745 When LOCAL is non-nil, only return tags from the current headline,
14746 ignore inherited ones."
14747 (interactive)
14748 (if (and org-trust-scanner-tags
14749 (or (not pos) (equal pos (point)))
14750 (not local))
14751 org-scanner-tags
14752 (let (tags ltags lastpos parent)
14753 (save-excursion
14754 (save-restriction
14755 (widen)
14756 (goto-char (or pos (point)))
14757 (save-match-data
14758 (catch 'done
14759 (condition-case nil
14760 (progn
14761 (org-back-to-heading t)
14762 (while (not (equal lastpos (point)))
14763 (setq lastpos (point))
14764 (when (looking-at
14765 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14766 (setq ltags (org-split-string
14767 (org-match-string-no-properties 1) ":"))
14768 (when parent
14769 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14770 (setq tags (append
14771 (if parent
14772 (org-remove-uninherited-tags ltags)
14773 ltags)
14774 tags)))
14775 (or org-use-tag-inheritance (throw 'done t))
14776 (when local (throw 'done t))
14777 (or (org-up-heading-safe) (error nil))
14778 (setq parent t)))
14779 (error nil)))))
14780 (if local
14781 tags
14782 (reverse (delete-dups
14783 (reverse (append
14784 (org-remove-uninherited-tags
14785 org-file-tags)
14786 tags)))))))))
14788 (defun org-add-prop-inherited (s)
14789 (add-text-properties 0 (length s) '(inherited t) s)
14792 (defun org-toggle-tag (tag &optional onoff)
14793 "Toggle the tag TAG for the current line.
14794 If ONOFF is `on' or `off', don't toggle but set to this state."
14795 (let (res current)
14796 (save-excursion
14797 (org-back-to-heading t)
14798 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14799 (point-at-eol) t)
14800 (progn
14801 (setq current (match-string 1))
14802 (replace-match ""))
14803 (setq current ""))
14804 (setq current (nreverse (org-split-string current ":")))
14805 (cond
14806 ((eq onoff 'on)
14807 (setq res t)
14808 (or (member tag current) (push tag current)))
14809 ((eq onoff 'off)
14810 (or (not (member tag current)) (setq current (delete tag current))))
14811 (t (if (member tag current)
14812 (setq current (delete tag current))
14813 (setq res t)
14814 (push tag current))))
14815 (end-of-line 1)
14816 (if current
14817 (progn
14818 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14819 (org-set-tags nil t))
14820 (delete-horizontal-space))
14821 (run-hooks 'org-after-tags-change-hook))
14822 res))
14824 (defun org-align-tags-here (to-col)
14825 ;; Assumes that this is a headline
14826 "Align tags on the current headline to TO-COL."
14827 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14828 (beginning-of-line 1)
14829 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14830 (< pos (match-beginning 2)))
14831 (progn
14832 (setq tags-l (- (match-end 2) (match-beginning 2)))
14833 (goto-char (match-beginning 1))
14834 (insert " ")
14835 (delete-region (point) (1+ (match-beginning 2)))
14836 (setq ncol (max (current-column)
14837 (1+ col)
14838 (if (> to-col 0)
14839 to-col
14840 (- (abs to-col) tags-l))))
14841 (setq p (point))
14842 (insert (make-string (- ncol (current-column)) ?\ ))
14843 (setq ncol (current-column))
14844 (when indent-tabs-mode (tabify p (point-at-eol)))
14845 (org-move-to-column (min ncol col)))
14846 (goto-char pos))))
14848 (defun org-set-tags-command (&optional arg just-align)
14849 "Call the set-tags command for the current entry."
14850 (interactive "P")
14851 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14852 (org-set-tags arg just-align)
14853 (save-excursion
14854 (unless (and (org-region-active-p)
14855 org-loop-over-headlines-in-active-region)
14856 (org-back-to-heading t))
14857 (org-set-tags arg just-align))))
14859 (defun org-set-tags-to (data)
14860 "Set the tags of the current entry to DATA, replacing the current tags.
14861 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14862 If DATA is nil or the empty string, any tags will be removed."
14863 (interactive "sTags: ")
14864 (setq data
14865 (cond
14866 ((eq data nil) "")
14867 ((equal data "") "")
14868 ((stringp data)
14869 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14870 ":"))
14871 ((listp data)
14872 (concat ":" (mapconcat 'identity data ":") ":"))))
14873 (when data
14874 (save-excursion
14875 (org-back-to-heading t)
14876 (when (looking-at org-complex-heading-regexp)
14877 (if (match-end 5)
14878 (progn
14879 (goto-char (match-beginning 5))
14880 (insert data)
14881 (delete-region (point) (point-at-eol))
14882 (org-set-tags nil 'align))
14883 (goto-char (point-at-eol))
14884 (insert " " data)
14885 (org-set-tags nil 'align)))
14886 (beginning-of-line 1)
14887 (when (looking-at ".*?\\([ \t]+\\)$")
14888 (delete-region (match-beginning 1) (match-end 1))))))
14890 (defun org-align-all-tags ()
14891 "Align the tags i all headings."
14892 (interactive)
14893 (save-excursion
14894 (or (ignore-errors (org-back-to-heading t))
14895 (outline-next-heading))
14896 (if (org-at-heading-p)
14897 (org-set-tags t)
14898 (message "No headings"))))
14900 (defvar org-indent-indentation-per-level)
14901 (defun org-set-tags (&optional arg just-align)
14902 "Set the tags for the current headline.
14903 With prefix ARG, realign all tags in headings in the current buffer.
14904 When JUST-ALIGN is non-nil, only align tags."
14905 (interactive "P")
14906 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14907 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14908 'region-start-level
14909 'region))
14910 org-loop-over-headlines-in-active-region)
14911 (org-map-entries
14912 ;; We don't use ARG and JUST-ALIGN here because these args
14913 ;; are not useful when looping over headlines.
14914 #'org-set-tags
14915 org-loop-over-headlines-in-active-region
14917 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14918 (let ((org-setting-tags t))
14919 (if arg
14920 (save-excursion
14921 (goto-char (point-min))
14922 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14923 (while (re-search-forward org-outline-regexp-bol nil t)
14924 (org-set-tags nil t)
14925 (end-of-line)))
14926 (message "All tags realigned to column %d" org-tags-column))
14927 (let* ((current (org-get-tags-string))
14928 (col (current-column))
14929 (tags
14930 (if just-align current
14931 ;; Get a new set of tags from the user.
14932 (save-excursion
14933 (let* ((table
14934 (setq
14935 org-last-tags-completion-table
14936 (append
14937 org-tag-persistent-alist
14938 (or org-tag-alist (org-get-buffer-tags))
14939 (and
14940 org-complete-tags-always-offer-all-agenda-tags
14941 (org-global-tags-completion-table
14942 (org-agenda-files))))))
14943 (current-tags (org-split-string current ":"))
14944 (inherited-tags
14945 (nreverse (nthcdr (length current-tags)
14946 (nreverse (org-get-tags-at))))))
14947 (replace-regexp-in-string
14948 "\\([-+&]+\\|,\\)"
14950 (if (or (eq t org-use-fast-tag-selection)
14951 (and org-use-fast-tag-selection
14952 (delq nil (mapcar #'cdr table))))
14953 (org-fast-tag-selection
14954 current-tags inherited-tags table
14955 (and org-fast-tag-selection-include-todo
14956 org-todo-key-alist))
14957 (let ((org-add-colon-after-tag-completion
14958 (< 1 (length table))))
14959 (org-trim
14960 (completing-read
14961 "Tags: "
14962 #'org-tags-completion-function
14963 nil nil current 'org-tags-history))))))))))
14965 (when org-tags-sort-function
14966 (setq tags
14967 (mapconcat
14968 #'identity
14969 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14970 org-tags-sort-function)
14971 ":")))
14973 (if (not (org-string-nw-p tags)) (setq tags "")
14974 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14975 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14977 ;; Insert new tags at the correct column
14978 (beginning-of-line)
14979 (let ((level (if (looking-at org-outline-regexp)
14980 (- (match-end 0) (point) 1)
14981 1)))
14982 (cond
14983 ((and (equal current "") (equal tags "")))
14984 ((re-search-forward
14985 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14986 (line-end-position)
14988 (if (equal tags "") (replace-match "" t t)
14989 (goto-char (match-beginning 0))
14990 (let* ((c0 (current-column))
14991 ;; Compute offset for the case of org-indent-mode
14992 ;; active.
14993 (di (if (org-bound-and-true-p org-indent-mode)
14994 (* (1- org-indent-indentation-per-level)
14995 (1- level))
14997 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14998 (tc (+ org-tags-column
14999 (if (> org-tags-column 0) (- di) di)))
15000 (c1 (max (1+ c0)
15001 (if (> tc 0) tc
15002 (- (- tc) (string-width tags)))))
15003 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15004 (replace-match rpl t t)
15005 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15006 (tabify p0 (point))))))
15007 (t (error "Tags alignment failed"))))
15008 (org-move-to-column col))
15009 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15011 (defun org-change-tag-in-region (beg end tag off)
15012 "Add or remove TAG for each entry in the region.
15013 This works in the agenda, and also in an org-mode buffer."
15014 (interactive
15015 (list (region-beginning) (region-end)
15016 (let ((org-last-tags-completion-table
15017 (if (derived-mode-p 'org-mode)
15018 (org-uniquify
15019 (delq nil (append (org-get-buffer-tags)
15020 (org-global-tags-completion-table))))
15021 (org-global-tags-completion-table))))
15022 (completing-read
15023 "Tag: " 'org-tags-completion-function nil nil nil
15024 'org-tags-history))
15025 (progn
15026 (message "[s]et or [r]emove? ")
15027 (equal (read-char-exclusive) ?r))))
15028 (when (fboundp 'deactivate-mark) (deactivate-mark))
15029 (let ((agendap (equal major-mode 'org-agenda-mode))
15030 l1 l2 m buf pos newhead (cnt 0))
15031 (goto-char end)
15032 (setq l2 (1- (org-current-line)))
15033 (goto-char beg)
15034 (setq l1 (org-current-line))
15035 (cl-loop for l from l1 to l2 do
15036 (org-goto-line l)
15037 (setq m (get-text-property (point) 'org-hd-marker))
15038 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15039 (and agendap m))
15040 (setq buf (if agendap (marker-buffer m) (current-buffer))
15041 pos (if agendap m (point)))
15042 (with-current-buffer buf
15043 (save-excursion
15044 (save-restriction
15045 (goto-char pos)
15046 (setq cnt (1+ cnt))
15047 (org-toggle-tag tag (if off 'off 'on))
15048 (setq newhead (org-get-heading)))))
15049 (and agendap (org-agenda-change-all-lines newhead m))))
15050 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15052 (defun org-tags-completion-function (string _predicate &optional flag)
15053 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15054 (confirm (lambda (x) (stringp (car x)))))
15055 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15056 (setq s1 (match-string 1 string)
15057 s2 (match-string 2 string))
15058 (setq s1 "" s2 string))
15059 (cond
15060 ((eq flag nil)
15061 ;; try completion
15062 (setq rtn (try-completion s2 ctable confirm))
15063 (when (stringp rtn)
15064 (setq rtn
15065 (concat s1 s2 (substring rtn (length s2))
15066 (if (and org-add-colon-after-tag-completion
15067 (assoc rtn ctable))
15068 ":" ""))))
15069 rtn)
15070 ((eq flag t)
15071 ;; all-completions
15072 (all-completions s2 ctable confirm))
15073 ((eq flag 'lambda)
15074 ;; exact match?
15075 (assoc s2 ctable)))))
15077 (defun org-fast-tag-insert (kwd tags face &optional end)
15078 "Insert KDW, and the TAGS, the latter with face FACE.
15079 Also insert END."
15080 (insert (format "%-12s" (concat kwd ":"))
15081 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15082 (or end "")))
15084 (defun org-fast-tag-show-exit (flag)
15085 (save-excursion
15086 (org-goto-line 3)
15087 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15088 (replace-match ""))
15089 (when flag
15090 (end-of-line 1)
15091 (org-move-to-column (- (window-width) 19) t)
15092 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15094 (defun org-set-current-tags-overlay (current prefix)
15095 "Add an overlay to CURRENT tag with PREFIX."
15096 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15097 (if (featurep 'xemacs)
15098 (org-overlay-display org-tags-overlay (concat prefix s)
15099 'secondary-selection)
15100 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15101 (org-overlay-display org-tags-overlay (concat prefix s)))))
15103 (defvar org-last-tag-selection-key nil)
15104 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15105 "Fast tag selection with single keys.
15106 CURRENT is the current list of tags in the headline, INHERITED is the
15107 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15108 possibly with grouping information. TODO-TABLE is a similar table with
15109 TODO keywords, should these have keys assigned to them.
15110 If the keys are nil, a-z are automatically assigned.
15111 Returns the new tags string, or nil to not change the current settings."
15112 (let* ((fulltable (append table todo-table))
15113 (maxlen (apply 'max (mapcar
15114 (lambda (x)
15115 (if (stringp (car x)) (string-width (car x)) 0))
15116 fulltable)))
15117 (buf (current-buffer))
15118 (expert (eq org-fast-tag-selection-single-key 'expert))
15119 (buffer-tags nil)
15120 (fwidth (+ maxlen 3 1 3))
15121 (ncol (/ (- (window-width) 4) fwidth))
15122 (i-face 'org-done)
15123 (c-face 'org-todo)
15124 tg cnt e c char c1 c2 ntable tbl rtn
15125 ov-start ov-end ov-prefix
15126 (exit-after-next org-fast-tag-selection-single-key)
15127 (done-keywords org-done-keywords)
15128 groups ingroup intaggroup)
15129 (save-excursion
15130 (beginning-of-line 1)
15131 (if (looking-at
15132 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15133 (setq ov-start (match-beginning 1)
15134 ov-end (match-end 1)
15135 ov-prefix "")
15136 (setq ov-start (1- (point-at-eol))
15137 ov-end (1+ ov-start))
15138 (skip-chars-forward "^\n\r")
15139 (setq ov-prefix
15140 (concat
15141 (buffer-substring (1- (point)) (point))
15142 (if (> (current-column) org-tags-column)
15144 (make-string (- org-tags-column (current-column)) ?\ ))))))
15145 (move-overlay org-tags-overlay ov-start ov-end)
15146 (save-window-excursion
15147 (if expert
15148 (set-buffer (get-buffer-create " *Org tags*"))
15149 (delete-other-windows)
15150 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15151 (org-switch-to-buffer-other-window " *Org tags*"))
15152 (erase-buffer)
15153 (setq-local org-done-keywords done-keywords)
15154 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15155 (org-fast-tag-insert "Current" current c-face "\n\n")
15156 (org-fast-tag-show-exit exit-after-next)
15157 (org-set-current-tags-overlay current ov-prefix)
15158 (setq tbl fulltable char ?a cnt 0)
15159 (while (setq e (pop tbl))
15160 (cond
15161 ((eq (car e) :startgroup)
15162 (push '() groups) (setq ingroup t)
15163 (unless (zerop cnt)
15164 (setq cnt 0)
15165 (insert "\n"))
15166 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15167 ((eq (car e) :endgroup)
15168 (setq ingroup nil cnt 0)
15169 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15170 ((eq (car e) :startgrouptag)
15171 (setq intaggroup t)
15172 (unless (zerop cnt)
15173 (setq cnt 0)
15174 (insert "\n"))
15175 (insert "[ "))
15176 ((eq (car e) :endgrouptag)
15177 (setq intaggroup nil cnt 0)
15178 (insert "]\n"))
15179 ((equal e '(:newline))
15180 (unless (zerop cnt)
15181 (setq cnt 0)
15182 (insert "\n")
15183 (setq e (car tbl))
15184 (while (equal (car tbl) '(:newline))
15185 (insert "\n")
15186 (setq tbl (cdr tbl)))))
15187 ((equal e '(:grouptags)) (insert " : "))
15189 (setq tg (copy-sequence (car e)) c2 nil)
15190 (if (cdr e)
15191 (setq c (cdr e))
15192 ;; automatically assign a character.
15193 (setq c1 (string-to-char
15194 (downcase (substring
15195 tg (if (= (string-to-char tg) ?@) 1 0)))))
15196 (if (or (rassoc c1 ntable) (rassoc c1 table))
15197 (while (or (rassoc char ntable) (rassoc char table))
15198 (setq char (1+ char)))
15199 (setq c2 c1))
15200 (setq c (or c2 char)))
15201 (when ingroup (push tg (car groups)))
15202 (setq tg (org-add-props tg nil 'face
15203 (cond
15204 ((not (assoc tg table))
15205 (org-get-todo-face tg))
15206 ((member tg current) c-face)
15207 ((member tg inherited) i-face))))
15208 (when (equal (caar tbl) :grouptags)
15209 (org-add-props tg nil 'face 'org-tag-group))
15210 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15211 (insert "[" c "] " tg (make-string
15212 (- fwidth 4 (length tg)) ?\ ))
15213 (push (cons tg c) ntable)
15214 (when (= (cl-incf cnt) ncol)
15215 (insert "\n")
15216 (when (or ingroup intaggroup) (insert " "))
15217 (setq cnt 0)))))
15218 (setq ntable (nreverse ntable))
15219 (insert "\n")
15220 (goto-char (point-min))
15221 (unless expert (org-fit-window-to-buffer))
15222 (setq rtn
15223 (catch 'exit
15224 (while t
15225 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15226 (if (not groups) "no " "")
15227 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15228 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15229 (setq org-last-tag-selection-key c)
15230 (cond
15231 ((= c ?\r) (throw 'exit t))
15232 ((= c ?!)
15233 (setq groups (not groups))
15234 (goto-char (point-min))
15235 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15236 ((= c ?\C-c)
15237 (if (not expert)
15238 (org-fast-tag-show-exit
15239 (setq exit-after-next (not exit-after-next)))
15240 (setq expert nil)
15241 (delete-other-windows)
15242 (set-window-buffer (split-window-vertically) " *Org tags*")
15243 (org-switch-to-buffer-other-window " *Org tags*")
15244 (org-fit-window-to-buffer)))
15245 ((or (= c ?\C-g)
15246 (and (= c ?q) (not (rassoc c ntable))))
15247 (org-detach-overlay org-tags-overlay)
15248 (setq quit-flag t))
15249 ((= c ?\ )
15250 (setq current nil)
15251 (when exit-after-next (setq exit-after-next 'now)))
15252 ((= c ?\t)
15253 (condition-case nil
15254 (setq tg (completing-read
15255 "Tag: "
15256 (or buffer-tags
15257 (with-current-buffer buf
15258 (setq buffer-tags
15259 (org-get-buffer-tags))))))
15260 (quit (setq tg "")))
15261 (when (string-match "\\S-" tg)
15262 (cl-pushnew (list tg) buffer-tags :test #'equal)
15263 (if (member tg current)
15264 (setq current (delete tg current))
15265 (push tg current)))
15266 (when exit-after-next (setq exit-after-next 'now)))
15267 ((setq e (rassoc c todo-table) tg (car e))
15268 (with-current-buffer buf
15269 (save-excursion (org-todo tg)))
15270 (when exit-after-next (setq exit-after-next 'now)))
15271 ((setq e (rassoc c ntable) tg (car e))
15272 (if (member tg current)
15273 (setq current (delete tg current))
15274 (cl-loop for g in groups do
15275 (when (member tg g)
15276 (dolist (x g) (setq current (delete x current)))))
15277 (push tg current))
15278 (when exit-after-next (setq exit-after-next 'now))))
15280 ;; Create a sorted list
15281 (setq current
15282 (sort current
15283 (lambda (a b)
15284 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15285 (when (eq exit-after-next 'now) (throw 'exit t))
15286 (goto-char (point-min))
15287 (beginning-of-line 2)
15288 (delete-region (point) (point-at-eol))
15289 (org-fast-tag-insert "Current" current c-face)
15290 (org-set-current-tags-overlay current ov-prefix)
15291 (while (re-search-forward
15292 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15293 (setq tg (match-string 1))
15294 (add-text-properties
15295 (match-beginning 1) (match-end 1)
15296 (list 'face
15297 (cond
15298 ((member tg current) c-face)
15299 ((member tg inherited) i-face)
15300 (t (get-text-property (match-beginning 1) 'face))))))
15301 (goto-char (point-min)))))
15302 (org-detach-overlay org-tags-overlay)
15303 (if rtn
15304 (mapconcat 'identity current ":")
15305 nil))))
15307 (defun org-get-tags-string ()
15308 "Get the TAGS string in the current headline."
15309 (unless (org-at-heading-p t)
15310 (user-error "Not on a heading"))
15311 (save-excursion
15312 (beginning-of-line 1)
15313 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15314 (org-match-string-no-properties 1)
15315 "")))
15317 (defun org-get-tags ()
15318 "Get the list of tags specified in the current headline."
15319 (org-split-string (org-get-tags-string) ":"))
15321 (defun org-get-buffer-tags ()
15322 "Get a table of all tags used in the buffer, for completion."
15323 (org-with-wide-buffer
15324 (goto-char (point-min))
15325 (let ((tag-re (concat org-outline-regexp-bol
15326 "\\(?:.*?[ \t]\\)?"
15327 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15328 tags)
15329 (while (re-search-forward tag-re nil t)
15330 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15331 (push tag tags)))
15332 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15334 ;;;; The mapping API
15336 (defvar org-agenda-skip-comment-trees)
15337 (defvar org-agenda-skip-function)
15338 (defun org-map-entries (func &optional match scope &rest skip)
15339 "Call FUNC at each headline selected by MATCH in SCOPE.
15341 FUNC is a function or a lisp form. The function will be called without
15342 arguments, with the cursor positioned at the beginning of the headline.
15343 The return values of all calls to the function will be collected and
15344 returned as a list.
15346 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15347 does not need to preserve point. After evaluation, the cursor will be
15348 moved to the end of the line (presumably of the headline of the
15349 processed entry) and search continues from there. Under some
15350 circumstances, this may not produce the wanted results. For example,
15351 if you have removed (e.g. archived) the current (sub)tree it could
15352 mean that the next entry will be skipped entirely. In such cases, you
15353 can specify the position from where search should continue by making
15354 FUNC set the variable `org-map-continue-from' to the desired buffer
15355 position.
15357 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15358 Only headlines that are matched by this query will be considered during
15359 the iteration. When MATCH is nil or t, all headlines will be
15360 visited by the iteration.
15362 SCOPE determines the scope of this command. It can be any of:
15364 nil The current buffer, respecting the restriction if any
15365 tree The subtree started with the entry at point
15366 region The entries within the active region, if any
15367 region-start-level
15368 The entries within the active region, but only those at
15369 the same level than the first one.
15370 file The current buffer, without restriction
15371 file-with-archives
15372 The current buffer, and any archives associated with it
15373 agenda All agenda files
15374 agenda-with-archives
15375 All agenda files with any archive files associated with them
15376 \(file1 file2 ...)
15377 If this is a list, all files in the list will be scanned
15379 The remaining args are treated as settings for the skipping facilities of
15380 the scanner. The following items can be given here:
15382 archive skip trees with the archive tag
15383 comment skip trees with the COMMENT keyword
15384 function or Emacs Lisp form:
15385 will be used as value for `org-agenda-skip-function', so
15386 whenever the function returns a position, FUNC will not be
15387 called for that entry and search will continue from the
15388 position returned
15390 If your function needs to retrieve the tags including inherited tags
15391 at the *current* entry, you can use the value of the variable
15392 `org-scanner-tags' which will be much faster than getting the value
15393 with `org-get-tags-at'. If your function gets properties with
15394 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15395 to t around the call to `org-entry-properties' to get the same speedup.
15396 Note that if your function moves around to retrieve tags and properties at
15397 a *different* entry, you cannot use these techniques."
15398 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15399 (not (org-region-active-p)))
15400 (let* ((org-agenda-archives-mode nil) ; just to make sure
15401 (org-agenda-skip-archived-trees (memq 'archive skip))
15402 (org-agenda-skip-comment-trees (memq 'comment skip))
15403 (org-agenda-skip-function
15404 (car (org-delete-all '(comment archive) skip)))
15405 (org-tags-match-list-sublevels t)
15406 (start-level (eq scope 'region-start-level))
15407 matcher res
15408 org-todo-keywords-for-agenda
15409 org-done-keywords-for-agenda
15410 org-todo-keyword-alist-for-agenda
15411 org-tag-alist-for-agenda
15412 org--matcher-tags-todo-only)
15414 (cond
15415 ((eq match t) (setq matcher t))
15416 ((eq match nil) (setq matcher t))
15417 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15419 (save-excursion
15420 (save-restriction
15421 (cond ((eq scope 'tree)
15422 (org-back-to-heading t)
15423 (org-narrow-to-subtree)
15424 (setq scope nil))
15425 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15426 (org-region-active-p))
15427 ;; If needed, set start-level to a string like "2"
15428 (when start-level
15429 (save-excursion
15430 (goto-char (region-beginning))
15431 (unless (org-at-heading-p) (outline-next-heading))
15432 (setq start-level (org-current-level))))
15433 (narrow-to-region (region-beginning)
15434 (save-excursion
15435 (goto-char (region-end))
15436 (unless (and (bolp) (org-at-heading-p))
15437 (outline-next-heading))
15438 (point)))
15439 (setq scope nil)))
15441 (if (not scope)
15442 (progn
15443 (org-agenda-prepare-buffers
15444 (and buffer-file-name (list buffer-file-name)))
15445 (setq res
15446 (org-scan-tags
15447 func matcher org--matcher-tags-todo-only start-level)))
15448 ;; Get the right scope
15449 (cond
15450 ((and scope (listp scope) (symbolp (car scope)))
15451 (setq scope (eval scope)))
15452 ((eq scope 'agenda)
15453 (setq scope (org-agenda-files t)))
15454 ((eq scope 'agenda-with-archives)
15455 (setq scope (org-agenda-files t))
15456 (setq scope (org-add-archive-files scope)))
15457 ((eq scope 'file)
15458 (setq scope (and buffer-file-name (list buffer-file-name))))
15459 ((eq scope 'file-with-archives)
15460 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15461 (org-agenda-prepare-buffers scope)
15462 (dolist (file scope)
15463 (with-current-buffer (org-find-base-buffer-visiting file)
15464 (save-excursion
15465 (save-restriction
15466 (widen)
15467 (goto-char (point-min))
15468 (setq res
15469 (append
15471 (org-scan-tags
15472 func matcher org--matcher-tags-todo-only))))))))))
15473 res)))
15475 ;;; Properties API
15477 (defconst org-special-properties
15478 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15479 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15480 "The special properties valid in Org mode.
15481 These are properties that are not defined in the property drawer,
15482 but in some other way.")
15484 (defconst org-default-properties
15485 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15486 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15487 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15488 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15489 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15490 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15491 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15492 "Some properties that are used by Org mode for various purposes.
15493 Being in this list makes sure that they are offered for completion.")
15495 (defun org--valid-property-p (property)
15496 "Non nil when string PROPERTY is a valid property name."
15497 (not
15498 (or (equal property "")
15499 (org-string-match-p "\\s-" property))))
15501 (defun org--update-property-plist (key val props)
15502 "Associate KEY to VAL in alist PROPS.
15503 Modifications are made by side-effect. Return new alist."
15504 (let* ((appending (string= (substring key -1) "+"))
15505 (key (if appending (substring key 0 -1) key))
15506 (old (assoc-string key props t)))
15507 (if (not old) (cons (cons key val) props)
15508 (setcdr old (if appending (concat (cdr old) " " val) val))
15509 props)))
15511 (defun org-get-property-block (&optional beg force)
15512 "Return the (beg . end) range of the body of the property drawer.
15513 BEG is the beginning of the current subtree, or of the part
15514 before the first headline. If it is not given, it will be found.
15515 If the drawer does not exist, create it if FORCE is non-nil, or
15516 return nil."
15517 (org-with-wide-buffer
15518 (when beg (goto-char beg))
15519 (unless (org-before-first-heading-p)
15520 (let ((beg (cond (beg)
15521 ((or (not (featurep 'org-inlinetask))
15522 (org-inlinetask-in-task-p))
15523 (org-back-to-heading t))
15524 (t (org-with-limited-levels (org-back-to-heading t))))))
15525 (forward-line)
15526 (when (org-looking-at-p org-planning-line-re) (forward-line))
15527 (cond ((looking-at org-property-drawer-re)
15528 (forward-line)
15529 (cons (point) (progn (goto-char (match-end 0))
15530 (line-beginning-position))))
15531 (force
15532 (goto-char beg)
15533 (org-insert-property-drawer)
15534 (let ((pos (save-excursion (search-forward ":END:")
15535 (line-beginning-position))))
15536 (cons pos pos))))))))
15538 (defun org-at-property-p ()
15539 "Non-nil when point is inside a property drawer.
15540 See `org-property-re' for match data, if applicable."
15541 (save-excursion
15542 (beginning-of-line)
15543 (and (looking-at org-property-re)
15544 (let ((property-drawer (save-match-data (org-get-property-block))))
15545 (and property-drawer
15546 (>= (point) (car property-drawer))
15547 (< (point) (cdr property-drawer)))))))
15549 (defun org-property-action ()
15550 "Do an action on properties."
15551 (interactive)
15552 (unless (org-at-property-p) (user-error "Not at a property"))
15553 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15554 (let ((c (read-char-exclusive)))
15555 (cl-case c
15556 (?s (call-interactively #'org-set-property))
15557 (?d (call-interactively #'org-delete-property))
15558 (?D (call-interactively #'org-delete-property-globally))
15559 (?c (call-interactively #'org-compute-property-at-point))
15560 (otherwise (user-error "No such property action %c" c)))))
15562 (defun org-inc-effort ()
15563 "Increment the value of the effort property in the current entry."
15564 (interactive)
15565 (org-set-effort nil t))
15567 (defvar org-clock-effort) ; Defined in org-clock.el.
15568 (defvar org-clock-current-task) ; Defined in org-clock.el.
15569 (defun org-set-effort (&optional value increment)
15570 "Set the effort property of the current entry.
15571 With numerical prefix arg, use the nth allowed value, 0 stands for the
15572 10th allowed value.
15574 When INCREMENT is non-nil, set the property to the next allowed value."
15575 (interactive "P")
15576 (when (equal value 0) (setq value 10))
15577 (let* ((completion-ignore-case t)
15578 (prop org-effort-property)
15579 (cur (org-entry-get nil prop))
15580 (allowed (org-property-get-allowed-values nil prop 'table))
15581 (existing (mapcar 'list (org-property-values prop)))
15582 (heading (nth 4 (org-heading-components)))
15584 (val (cond
15585 ((stringp value) value)
15586 ((and allowed (integerp value))
15587 (or (car (nth (1- value) allowed))
15588 (car (org-last allowed))))
15589 ((and allowed increment)
15590 (or (cl-caadr (member (list cur) allowed))
15591 (user-error "Allowed effort values are not set")))
15592 (allowed
15593 (message "Select 1-9,0, [RET%s]: %s"
15594 (if cur (concat "=" cur) "")
15595 (mapconcat 'car allowed " "))
15596 (setq rpl (read-char-exclusive))
15597 (if (equal rpl ?\r)
15599 (setq rpl (- rpl ?0))
15600 (when (equal rpl 0) (setq rpl 10))
15601 (if (and (> rpl 0) (<= rpl (length allowed)))
15602 (car (nth (1- rpl) allowed))
15603 (org-completing-read "Effort: " allowed nil))))
15605 (let (org-completion-use-ido org-completion-use-iswitchb)
15606 (org-completing-read
15607 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15608 (concat "[" cur "]") "")
15609 ": ")
15610 existing nil nil "" nil cur))))))
15611 (unless (equal (org-entry-get nil prop) val)
15612 (org-entry-put nil prop val))
15613 (org-refresh-property
15614 '((effort . identity)
15615 (effort-minutes . org-duration-string-to-minutes))
15616 val)
15617 (when (string= heading org-clock-current-task)
15618 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15619 (org-clock-update-mode-line))
15620 (message "%s is now %s" prop val)))
15622 (defun org-entry-properties (&optional pom which)
15623 "Get all properties of the current entry.
15625 When POM is a buffer position, get all properties from the entry
15626 there instead.
15628 This includes the TODO keyword, the tags, time strings for
15629 deadline, scheduled, and clocking, and any additional properties
15630 defined in the entry.
15632 If WHICH is nil or `all', get all properties. If WHICH is
15633 `special' or `standard', only get that subclass. If WHICH is
15634 a string, only get that property.
15636 Return value is an alist. Keys are properties, as upcased
15637 strings."
15638 (org-with-point-at pom
15639 (when (and (derived-mode-p 'org-mode)
15640 (ignore-errors (org-back-to-heading t)))
15641 (catch 'exit
15642 (let* ((beg (point))
15643 (specific (and (stringp which) (upcase which)))
15644 (which (cond ((not specific) which)
15645 ((member specific org-special-properties) 'special)
15646 (t 'standard)))
15647 props)
15648 ;; Get the special properties, like TODO and TAGS.
15649 (when (memq which '(nil all special))
15650 (when (or (not specific) (string= specific "CLOCKSUM"))
15651 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15652 (when clocksum
15653 (push (cons "CLOCKSUM"
15654 (org-columns-number-to-string
15655 (/ (float clocksum) 60.) 'add_times))
15656 props)))
15657 (when specific (throw 'exit props)))
15658 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15659 (let ((clocksumt (get-text-property (point)
15660 :org-clock-minutes-today)))
15661 (when clocksumt
15662 (push (cons "CLOCKSUM_T"
15663 (org-columns-number-to-string
15664 (/ (float clocksumt) 60.) 'add_times))
15665 props)))
15666 (when specific (throw 'exit props)))
15667 (when (or (not specific) (string= specific "ITEM"))
15668 (when (looking-at org-complex-heading-regexp)
15669 (push (cons "ITEM"
15670 (concat
15671 (org-match-string-no-properties 1)
15672 (let ((title (org-match-string-no-properties 4)))
15673 (when (org-string-nw-p title)
15674 (concat " " (org-remove-tabs title))))))
15675 props))
15676 (when specific (throw 'exit props)))
15677 (when (or (not specific) (string= specific "TODO"))
15678 (let ((case-fold-search nil))
15679 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15680 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15681 (when specific (throw 'exit props)))
15682 (when (or (not specific) (string= specific "PRIORITY"))
15683 (push (cons "PRIORITY"
15684 (if (looking-at org-priority-regexp)
15685 (org-match-string-no-properties 2)
15686 (char-to-string org-default-priority)))
15687 props)
15688 (when specific (throw 'exit props)))
15689 (when (or (not specific) (string= specific "FILE"))
15690 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15691 props)
15692 (when specific (throw 'exit props)))
15693 (when (or (not specific) (string= specific "TAGS"))
15694 (let ((value (org-string-nw-p (org-get-tags-string))))
15695 (when value (push (cons "TAGS" value) props)))
15696 (when specific (throw 'exit props)))
15697 (when (or (not specific) (string= specific "ALLTAGS"))
15698 (let ((value (org-get-tags-at)))
15699 (when value
15700 (push (cons "ALLTAGS"
15701 (format ":%s:" (mapconcat #'identity value ":")))
15702 props)))
15703 (when specific (throw 'exit props)))
15704 (when (or (not specific) (string= specific "BLOCKED"))
15705 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15706 (when specific (throw 'exit props)))
15707 (when (or (not specific)
15708 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15709 (forward-line)
15710 (when (org-looking-at-p org-planning-line-re)
15711 (end-of-line)
15712 (let ((bol (line-beginning-position))
15713 ;; Backward compatibility: time keywords used to
15714 ;; be configurable (before 8.3). Make sure we
15715 ;; get the correct keyword.
15716 (key-assoc `(("CLOSED" . ,org-closed-string)
15717 ("DEADLINE" . ,org-deadline-string)
15718 ("SCHEDULED" . ,org-scheduled-string))))
15719 (dolist (pair (if specific (list (assoc specific key-assoc))
15720 key-assoc))
15721 (save-excursion
15722 (when (search-backward (cdr pair) bol t)
15723 (goto-char (match-end 0))
15724 (skip-chars-forward " \t")
15725 (and (looking-at org-ts-regexp-both)
15726 (push (cons (car pair)
15727 (org-match-string-no-properties 0))
15728 props)))))))
15729 (when specific (throw 'exit props)))
15730 (when (or (not specific)
15731 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15732 (let ((find-ts
15733 (lambda (end ts)
15734 ;; Fix next time-stamp before END. TS is the
15735 ;; list of time-stamps found so far.
15736 (let ((ts ts)
15737 (regexp (cond
15738 ((string= specific "TIMESTAMP")
15739 org-ts-regexp)
15740 ((string= specific "TIMESTAMP_IA")
15741 org-ts-regexp-inactive)
15742 ((assoc "TIMESTAMP_IA" ts)
15743 org-ts-regexp)
15744 ((assoc "TIMESTAMP" ts)
15745 org-ts-regexp-inactive)
15746 (t org-ts-regexp-both))))
15747 (catch 'next
15748 (while (re-search-forward regexp end t)
15749 (backward-char)
15750 (let ((object (org-element-context)))
15751 ;; Accept to match timestamps in node
15752 ;; properties, too.
15753 (when (memq (org-element-type object)
15754 '(node-property timestamp))
15755 (let ((type
15756 (org-element-property :type object)))
15757 (cond
15758 ((and (memq type '(active active-range))
15759 (not (equal specific "TIMESTAMP_IA")))
15760 (unless (assoc "TIMESTAMP" ts)
15761 (push (cons "TIMESTAMP"
15762 (org-element-property
15763 :raw-value object))
15765 (when specific (throw 'exit ts))))
15766 ((and (memq type '(inactive inactive-range))
15767 (not (string= specific "TIMESTAMP")))
15768 (unless (assoc "TIMESTAMP_IA" ts)
15769 (push (cons "TIMESTAMP_IA"
15770 (org-element-property
15771 :raw-value object))
15773 (when specific (throw 'exit ts))))))
15774 ;; Both timestamp types are found,
15775 ;; move to next part.
15776 (when (= (length ts) 2) (throw 'next ts)))))
15777 ts)))))
15778 (goto-char beg)
15779 ;; First look for timestamps within headline.
15780 (let ((ts (funcall find-ts (line-end-position) nil)))
15781 (if (= (length ts) 2) (setq props (nconc ts props))
15782 (forward-line)
15783 ;; Then find timestamps in the section, skipping
15784 ;; planning line.
15785 (when (org-looking-at-p org-planning-line-re)
15786 (forward-line))
15787 (let ((end (save-excursion (outline-next-heading))))
15788 (setq props (nconc (funcall find-ts end ts) props))))))))
15789 ;; Get the standard properties, like :PROP:.
15790 (when (memq which '(nil all standard))
15791 ;; If we are looking after a specific property, delegate
15792 ;; to `org-entry-get', which is faster. However, make an
15793 ;; exception for "CATEGORY", since it can be also set
15794 ;; through keywords (i.e. #+CATEGORY).
15795 (if (and specific (not (equal specific "CATEGORY")))
15796 (let ((value (org-entry-get beg specific nil t)))
15797 (throw 'exit (and value (list (cons specific value)))))
15798 (let ((range (org-get-property-block beg)))
15799 (when range
15800 (let ((end (cdr range)) seen-base)
15801 (goto-char (car range))
15802 ;; Unlike to `org--update-property-plist', we
15803 ;; handle the case where base values is found
15804 ;; after its extension. We also forbid standard
15805 ;; properties to be named as special properties.
15806 (while (re-search-forward org-property-re end t)
15807 (let* ((key (upcase (org-match-string-no-properties 2)))
15808 (extendp (org-string-match-p "\\+\\'" key))
15809 (key-base (if extendp (substring key 0 -1) key))
15810 (value (org-match-string-no-properties 3)))
15811 (cond
15812 ((member-ignore-case key-base org-special-properties))
15813 (extendp
15814 (setq props
15815 (org--update-property-plist key value props)))
15816 ((member key seen-base))
15817 (t (push key seen-base)
15818 (let ((p (assoc-string key props t)))
15819 (if p (setcdr p (concat value " " (cdr p)))
15820 (push (cons key value) props))))))))))))
15821 (unless (assoc "CATEGORY" props)
15822 (push (cons "CATEGORY" (org-get-category beg)) props)
15823 (when (string= specific "CATEGORY") (throw 'exit props)))
15824 ;; Return value.
15825 props)))))
15827 (defun org-property--local-values (property literal-nil)
15828 "Return value for PROPERTY in current entry.
15829 Value is a list whose care is the base value for PROPERTY and cdr
15830 a list of accumulated values. Return nil if neither is found in
15831 the entry. Also return nil when PROPERTY is set to \"nil\",
15832 unless LITERAL-NIL is non-nil."
15833 (let ((range (org-get-property-block)))
15834 (when range
15835 (goto-char (car range))
15836 (let* ((case-fold-search t)
15837 (end (cdr range))
15838 (value
15839 ;; Base value.
15840 (save-excursion
15841 (let ((v (and (re-search-forward
15842 (org-re-property property nil t) end t)
15843 (org-match-string-no-properties 3))))
15844 (list (if literal-nil v (org-not-nil v)))))))
15845 ;; Find additional values.
15846 (let* ((property+ (org-re-property (concat property "+") nil t)))
15847 (while (re-search-forward property+ end t)
15848 (push (org-match-string-no-properties 3) value)))
15849 ;; Return final values.
15850 (and (not (equal value '(nil))) (nreverse value))))))
15852 (defun org-entry-get (pom property &optional inherit literal-nil)
15853 "Get value of PROPERTY for entry or content at point-or-marker POM.
15855 If INHERIT is non-nil and the entry does not have the property,
15856 then also check higher levels of the hierarchy. If INHERIT is
15857 the symbol `selective', use inheritance only if the setting in
15858 `org-use-property-inheritance' selects PROPERTY for inheritance.
15860 If the property is present but empty, the return value is the
15861 empty string. If the property is not present at all, nil is
15862 returned. In any other case, return the value as a string.
15863 Search is case-insensitive.
15865 If LITERAL-NIL is set, return the string value \"nil\" as
15866 a string, do not interpret it as the list atom nil. This is used
15867 for inheritance when a \"nil\" value can supersede a non-nil
15868 value higher up the hierarchy."
15869 (org-with-point-at pom
15870 (cond
15871 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15872 ;; We need a special property. Use `org-entry-properties' to
15873 ;; retrieve it, but specify the wanted property.
15874 (cdr (assoc-string property (org-entry-properties nil property))))
15875 ((and inherit
15876 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15877 (org-entry-get-with-inheritance property literal-nil))
15879 (let* ((local (org-property--local-values property literal-nil))
15880 (value (and local (mapconcat #'identity (delq nil local) " "))))
15881 (if literal-nil value (org-not-nil value)))))))
15883 (defun org-property-or-variable-value (var &optional inherit)
15884 "Check if there is a property fixing the value of VAR.
15885 If yes, return this value. If not, return the current value of the variable."
15886 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15887 (if (and prop (stringp prop) (string-match "\\S-" prop))
15888 (read prop)
15889 (symbol-value var))))
15891 (defun org-entry-delete (pom property)
15892 "Delete PROPERTY from entry at point-or-marker POM.
15893 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15894 non-nil when a property was removed."
15895 (unless (member property org-special-properties)
15896 (org-with-point-at pom
15897 (let ((range (org-get-property-block)))
15898 (when range
15899 (let* ((begin (car range))
15900 (origin (cdr range))
15901 (end (copy-marker origin))
15902 (re (org-re-property
15903 (concat (regexp-quote property) "\\+?") t t)))
15904 (goto-char begin)
15905 (while (re-search-forward re end t)
15906 (delete-region (match-beginning 0) (line-beginning-position 2)))
15907 ;; If drawer is empty, remove it altogether.
15908 (when (= begin end)
15909 (delete-region (line-beginning-position 0)
15910 (line-beginning-position 2)))
15911 ;; Return non-nil if some property was removed.
15912 (prog1 (/= end origin) (set-marker end nil))))))))
15914 ;; Multi-values properties are properties that contain multiple values
15915 ;; These values are assumed to be single words, separated by whitespace.
15916 (defun org-entry-add-to-multivalued-property (pom property value)
15917 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15918 (let* ((old (org-entry-get pom property))
15919 (values (and old (org-split-string old "[ \t]"))))
15920 (setq value (org-entry-protect-space value))
15921 (unless (member value values)
15922 (setq values (append values (list value)))
15923 (org-entry-put pom property
15924 (mapconcat 'identity values " ")))))
15926 (defun org-entry-remove-from-multivalued-property (pom property value)
15927 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15928 (let* ((old (org-entry-get pom property))
15929 (values (and old (org-split-string old "[ \t]"))))
15930 (setq value (org-entry-protect-space value))
15931 (when (member value values)
15932 (setq values (delete value values))
15933 (org-entry-put pom property
15934 (mapconcat 'identity values " ")))))
15936 (defun org-entry-member-in-multivalued-property (pom property value)
15937 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15938 (let* ((old (org-entry-get pom property))
15939 (values (and old (org-split-string old "[ \t]"))))
15940 (setq value (org-entry-protect-space value))
15941 (member value values)))
15943 (defun org-entry-get-multivalued-property (pom property)
15944 "Return a list of values in a multivalued property."
15945 (let* ((value (org-entry-get pom property))
15946 (values (and value (org-split-string value "[ \t]"))))
15947 (mapcar 'org-entry-restore-space values)))
15949 (defun org-entry-put-multivalued-property (pom property &rest values)
15950 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15951 VALUES should be a list of strings. Spaces will be protected."
15952 (org-entry-put pom property
15953 (mapconcat 'org-entry-protect-space values " "))
15954 (let* ((value (org-entry-get pom property))
15955 (values (and value (org-split-string value "[ \t]"))))
15956 (mapcar 'org-entry-restore-space values)))
15958 (defun org-entry-protect-space (s)
15959 "Protect spaces and newline in string S."
15960 (while (string-match " " s)
15961 (setq s (replace-match "%20" t t s)))
15962 (while (string-match "\n" s)
15963 (setq s (replace-match "%0A" t t s)))
15966 (defun org-entry-restore-space (s)
15967 "Restore spaces and newline in string S."
15968 (while (string-match "%20" s)
15969 (setq s (replace-match " " t t s)))
15970 (while (string-match "%0A" s)
15971 (setq s (replace-match "\n" t t s)))
15974 (defvar org-entry-property-inherited-from (make-marker)
15975 "Marker pointing to the entry from where a property was inherited.
15976 Each call to `org-entry-get-with-inheritance' will set this marker to the
15977 location of the entry where the inheritance search matched. If there was
15978 no match, the marker will point nowhere.
15979 Note that also `org-entry-get' calls this function, if the INHERIT flag
15980 is set.")
15982 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15983 "Get PROPERTY of entry or content at point, search higher levels if needed.
15984 The search will stop at the first ancestor which has the property defined.
15985 If the value found is \"nil\", return nil to show that the property
15986 should be considered as undefined (this is the meaning of nil here).
15987 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15988 (move-marker org-entry-property-inherited-from nil)
15989 (org-with-wide-buffer
15990 (let (value)
15991 (catch 'exit
15992 (while t
15993 (let ((v (org-property--local-values property literal-nil)))
15994 (when v
15995 (setq value
15996 (concat (mapconcat #'identity (delq nil v) " ")
15997 (and value " ")
15998 value)))
15999 (cond
16000 ((car v)
16001 (org-back-to-heading t)
16002 (move-marker org-entry-property-inherited-from (point))
16003 (throw 'exit nil))
16004 ((org-up-heading-safe))
16006 (let ((global
16007 (cdr (or (assoc-string property org-file-properties t)
16008 (assoc-string property org-global-properties t)
16009 (assoc-string property org-global-properties-fixed t)))))
16010 (cond ((not global))
16011 (value (setq value (concat global " " value)))
16012 (t (setq value global))))
16013 (throw 'exit nil))))))
16014 (if literal-nil value (org-not-nil value)))))
16016 (defvar org-property-changed-functions nil
16017 "Hook called when the value of a property has changed.
16018 Each hook function should accept two arguments, the name of the property
16019 and the new value.")
16021 (defun org-entry-put (pom property value)
16022 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16024 If the value is nil, it is converted to the empty string. If it
16025 is not a string, an error is raised. Also raise an error on
16026 invalid property names.
16028 PROPERTY can be any regular property (see
16029 `org-special-properties'). It can also be \"TODO\",
16030 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16032 For the last two properties, VALUE may have any of the special
16033 values \"earlier\" and \"later\". The function then increases or
16034 decreases scheduled or deadline date by one day."
16035 (cond ((null value) (setq value ""))
16036 ((not (stringp value)) (error "Properties values should be strings"))
16037 ((not (org--valid-property-p property))
16038 (user-error "Invalid property name: \"%s\"" property)))
16039 (org-with-point-at pom
16040 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16041 (org-back-to-heading t)
16042 (org-with-limited-levels (org-back-to-heading t)))
16043 (let ((beg (point)))
16044 (cond
16045 ((equal property "TODO")
16046 (cond ((not (org-string-nw-p value)) (setq value 'none))
16047 ((not (member value org-todo-keywords-1))
16048 (user-error "\"%s\" is not a valid TODO state" value)))
16049 (org-todo value)
16050 (org-set-tags nil 'align))
16051 ((equal property "PRIORITY")
16052 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16053 (org-set-tags nil 'align))
16054 ((equal property "SCHEDULED")
16055 (forward-line)
16056 (if (and (org-looking-at-p org-planning-line-re)
16057 (re-search-forward
16058 org-scheduled-time-regexp (line-end-position) t))
16059 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16060 ((string= value "later") (org-timestamp-change 1 'day))
16061 ((string= value "") (org-schedule '(4)))
16062 (t (org-schedule nil value)))
16063 (if (member value '("earlier" "later" ""))
16064 (call-interactively #'org-schedule)
16065 (org-schedule nil value))))
16066 ((equal property "DEADLINE")
16067 (forward-line)
16068 (if (and (org-looking-at-p org-planning-line-re)
16069 (re-search-forward
16070 org-deadline-time-regexp (line-end-position) t))
16071 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16072 ((string= value "later") (org-timestamp-change 1 'day))
16073 ((string= value "") (org-deadline '(4)))
16074 (t (org-deadline nil value)))
16075 (if (member value '("earlier" "later" ""))
16076 (call-interactively #'org-deadline)
16077 (org-deadline nil value))))
16078 ((member property org-special-properties)
16079 (error "The %s property cannot be set with `org-entry-put'" property))
16081 (let* ((range (org-get-property-block beg 'force))
16082 (end (cdr range))
16083 (case-fold-search t))
16084 (goto-char (car range))
16085 (if (re-search-forward (org-re-property property nil t) end t)
16086 (progn (delete-region (match-beginning 0) (match-end 0))
16087 (goto-char (match-beginning 0)))
16088 (goto-char end)
16089 (insert "\n")
16090 (backward-char))
16091 (insert ":" property ":")
16092 (when value (insert " " value))
16093 (org-indent-line)))))
16094 (run-hook-with-args 'org-property-changed-functions property value)))
16096 (defun org-buffer-property-keys
16097 (&optional specials defaults columns ignore-malformed)
16098 "Get all property keys in the current buffer.
16100 When SPECIALS is non-nil, also list the special properties that
16101 reflect things like tags and TODO state.
16103 When DEFAULTS is non-nil, also include properties that has
16104 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16105 DESCRIPTION, LOCATION, and LOGGING and others.
16107 When COLUMNS in non-nil, also include property names given in
16108 COLUMN formats in the current buffer.
16110 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16111 automatically performed, such drawers will be silently ignored."
16112 (let ((case-fold-search t)
16113 (props (append
16114 (and specials org-special-properties)
16115 (and defaults (cons org-effort-property org-default-properties))
16116 nil)))
16117 (org-with-wide-buffer
16118 (goto-char (point-min))
16119 (while (re-search-forward org-property-start-re nil t)
16120 (let ((range (org-get-property-block)))
16121 (catch 'skip
16122 (unless range
16123 (when (and (not ignore-malformed)
16124 (not (org-before-first-heading-p))
16125 (y-or-n-p (format "Malformed drawer at %d, repair?"
16126 (line-beginning-position))))
16127 (org-get-property-block nil t))
16128 (throw 'skip nil))
16129 (goto-char (car range))
16130 (let ((begin (car range))
16131 (end (cdr range)))
16132 ;; Make sure that found property block is not located
16133 ;; before current point, as it would generate an infloop.
16134 ;; It can happen, for example, in the following
16135 ;; situation:
16137 ;; * Headline
16138 ;; :PROPERTIES:
16139 ;; ...
16140 ;; :END:
16141 ;; *************** Inlinetask
16142 ;; #+BEGIN_EXAMPLE
16143 ;; :PROPERTIES:
16144 ;; #+END_EXAMPLE
16146 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16147 (while (< (point) end)
16148 (let ((p (progn (looking-at org-property-re)
16149 (org-match-string-no-properties 2))))
16150 ;; Only add true property name, not extension symbol.
16151 (push (if (not (org-string-match-p "\\+\\'" p)) p
16152 (substring p 0 -1))
16153 props))
16154 (forward-line))))
16155 (outline-next-heading)))
16156 (when columns
16157 (goto-char (point-min))
16158 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16159 (let ((element (org-element-at-point)))
16160 (when (memq (org-element-type element) '(keyword node-property))
16161 (let ((value (org-element-property :value element))
16162 (start 0))
16163 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16164 (setq start (match-end 0))
16165 (let ((p (org-match-string-no-properties 1 value)))
16166 (unless (member-ignore-case p org-special-properties)
16167 (push p props))))))))))
16168 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16170 (defun org-property-values (key)
16171 "List all non-nil values of property KEY in current buffer."
16172 (org-with-wide-buffer
16173 (goto-char (point-min))
16174 (let ((case-fold-search t)
16175 (re (org-re-property key))
16176 values)
16177 (while (re-search-forward re nil t)
16178 (push (org-entry-get (point) key) values))
16179 (delete-dups values))))
16181 (defun org-insert-property-drawer ()
16182 "Insert a property drawer into the current entry."
16183 (org-with-wide-buffer
16184 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16185 (org-back-to-heading t)
16186 (org-with-limited-levels (org-back-to-heading t)))
16187 (forward-line)
16188 (when (org-looking-at-p org-planning-line-re) (forward-line))
16189 (unless (org-looking-at-p org-property-drawer-re)
16190 ;; Make sure we start editing a line from current entry, not from
16191 ;; next one. It prevents extending text properties or overlays
16192 ;; belonging to the latter.
16193 (when (bolp) (backward-char))
16194 (let ((begin (1+ (point)))
16195 (inhibit-read-only t))
16196 (insert "\n:PROPERTIES:\n:END:")
16197 (when (eobp) (insert "\n"))
16198 (org-indent-region begin (point))))))
16200 (defun org-insert-drawer (&optional arg drawer)
16201 "Insert a drawer at point.
16203 When optional argument ARG is non-nil, insert a property drawer.
16205 Optional argument DRAWER, when non-nil, is a string representing
16206 drawer's name. Otherwise, the user is prompted for a name.
16208 If a region is active, insert the drawer around that region
16209 instead.
16211 Point is left between drawer's boundaries."
16212 (interactive "P")
16213 (let* ((drawer (if arg "PROPERTIES"
16214 (or drawer (read-from-minibuffer "Drawer: ")))))
16215 (cond
16216 ;; With C-u, fall back on `org-insert-property-drawer'
16217 (arg (org-insert-property-drawer))
16218 ;; Check validity of suggested drawer's name.
16219 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16220 (user-error "Invalid drawer name"))
16221 ;; With an active region, insert a drawer at point.
16222 ((not (org-region-active-p))
16223 (progn
16224 (unless (bolp) (insert "\n"))
16225 (insert (format ":%s:\n\n:END:\n" drawer))
16226 (forward-line -2)))
16227 ;; Otherwise, insert the drawer at point
16229 (let ((rbeg (region-beginning))
16230 (rend (copy-marker (region-end))))
16231 (unwind-protect
16232 (progn
16233 (goto-char rbeg)
16234 (beginning-of-line)
16235 (when (save-excursion
16236 (re-search-forward org-outline-regexp-bol rend t))
16237 (user-error "Drawers cannot contain headlines"))
16238 ;; Position point at the beginning of the first
16239 ;; non-blank line in region. Insert drawer's opening
16240 ;; there, then indent it.
16241 (org-skip-whitespace)
16242 (beginning-of-line)
16243 (insert ":" drawer ":\n")
16244 (forward-line -1)
16245 (indent-for-tab-command)
16246 ;; Move point to the beginning of the first blank line
16247 ;; after the last non-blank line in region. Insert
16248 ;; drawer's closing, then indent it.
16249 (goto-char rend)
16250 (skip-chars-backward " \r\t\n")
16251 (insert "\n:END:")
16252 (deactivate-mark t)
16253 (indent-for-tab-command)
16254 (unless (eolp) (insert "\n")))
16255 ;; Clear marker, whatever the outcome of insertion is.
16256 (set-marker rend nil)))))))
16258 (defvar org-property-set-functions-alist nil
16259 "Property set function alist.
16260 Each entry should have the following format:
16262 (PROPERTY . READ-FUNCTION)
16264 The read function will be called with the same argument as
16265 `org-completing-read'.")
16267 (defun org-set-property-function (property)
16268 "Get the function that should be used to set PROPERTY.
16269 This is computed according to `org-property-set-functions-alist'."
16270 (or (cdr (assoc property org-property-set-functions-alist))
16271 'org-completing-read))
16273 (defun org-read-property-value (property)
16274 "Read PROPERTY value from user."
16275 (let* ((completion-ignore-case t)
16276 (allowed (org-property-get-allowed-values nil property 'table))
16277 (cur (org-entry-get nil property))
16278 (prompt (concat property " value"
16279 (if (and cur (string-match "\\S-" cur))
16280 (concat " [" cur "]") "") ": "))
16281 (set-function (org-set-property-function property))
16282 (val (if allowed
16283 (funcall set-function prompt allowed nil
16284 (not (get-text-property 0 'org-unrestricted
16285 (caar allowed))))
16286 (let (org-completion-use-ido org-completion-use-iswitchb)
16287 (funcall set-function prompt
16288 (mapcar 'list (org-property-values property))
16289 nil nil "" nil cur)))))
16290 (org-trim val)))
16292 (defvar org-last-set-property nil)
16293 (defvar org-last-set-property-value nil)
16294 (defun org-read-property-name ()
16295 "Read a property name."
16296 (let ((completion-ignore-case t)
16297 (default-prop (or (and (org-at-property-p)
16298 (org-match-string-no-properties 2))
16299 org-last-set-property)))
16300 (org-completing-read
16301 (concat "Property"
16302 (if default-prop (concat " [" default-prop "]") "")
16303 ": ")
16304 (mapcar #'list (org-buffer-property-keys nil t t))
16305 nil nil nil nil default-prop)))
16307 (defun org-set-property-and-value (use-last)
16308 "Allow to set [PROPERTY]: [value] direction from prompt.
16309 When use-default, don't even ask, just use the last
16310 \"[PROPERTY]: [value]\" string from the history."
16311 (interactive "P")
16312 (let* ((completion-ignore-case t)
16313 (pv (or (and use-last org-last-set-property-value)
16314 (org-completing-read
16315 "Enter a \"[Property]: [value]\" pair: "
16316 nil nil nil nil nil
16317 org-last-set-property-value)))
16318 prop val)
16319 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16320 (setq prop (match-string 1 pv)
16321 val (match-string 2 pv))
16322 (org-set-property prop val))))
16324 (defun org-set-property (property value)
16325 "In the current entry, set PROPERTY to VALUE.
16327 When called interactively, this will prompt for a property name, offering
16328 completion on existing and default properties. And then it will prompt
16329 for a value, offering completion either on allowed values (via an inherited
16330 xxx_ALL property) or on existing values in other instances of this property
16331 in the current file.
16333 Throw an error when trying to set a property with an invalid name."
16334 (interactive (list nil nil))
16335 (let ((property (or property (org-read-property-name))))
16336 ;; `org-entry-put' also makes the following check, but this one
16337 ;; avoids polluting `org-last-set-property' and
16338 ;; `org-last-set-property-value' needlessly.
16339 (unless (org--valid-property-p property)
16340 (user-error "Invalid property name: \"%s\"" property))
16341 (let ((value (or value (org-read-property-value property)))
16342 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16343 (setq org-last-set-property property)
16344 (setq org-last-set-property-value (concat property ": " value))
16345 ;; Possibly postprocess the inserted value:
16346 (when fn (setq value (funcall fn value)))
16347 (unless (equal (org-entry-get nil property) value)
16348 (org-entry-put nil property value)))))
16350 (defun org-find-property (property &optional value)
16351 "Find first entry in buffer that sets PROPERTY.
16353 When optional argument VALUE is non-nil, only consider an entry
16354 if it contains PROPERTY set to this value. If PROPERTY should be
16355 explicitly set to nil, use string \"nil\" for VALUE.
16357 Return position where the entry begins, or nil if there is no
16358 such entry. If narrowing is in effect, only search the visible
16359 part of the buffer."
16360 (save-excursion
16361 (goto-char (point-min))
16362 (let ((case-fold-search t)
16363 (re (org-re-property property nil (not value) value)))
16364 (catch 'exit
16365 (while (re-search-forward re nil t)
16366 (when (if value (org-at-property-p)
16367 (org-entry-get (point) property nil t))
16368 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16370 (defun org-delete-property (property)
16371 "In the current entry, delete PROPERTY."
16372 (interactive
16373 (let* ((completion-ignore-case t)
16374 (cat (org-entry-get (point) "CATEGORY"))
16375 (props0 (org-entry-properties nil 'standard))
16376 (props (if cat props0
16377 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16378 (prop (if (< 1 (length props))
16379 (completing-read "Property: " props nil t)
16380 (caar props))))
16381 (list prop)))
16382 (if (not property)
16383 (message "No property to delete in this entry")
16384 (org-entry-delete nil property)
16385 (message "Property \"%s\" deleted" property)))
16387 (defun org-delete-property-globally (property)
16388 "Remove PROPERTY globally, from all entries.
16389 This function ignores narrowing, if any."
16390 (interactive
16391 (let* ((completion-ignore-case t)
16392 (prop (completing-read
16393 "Globally remove property: "
16394 (mapcar #'list (org-buffer-property-keys)))))
16395 (list prop)))
16396 (org-with-wide-buffer
16397 (goto-char (point-min))
16398 (let ((count 0)
16399 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16400 (while (re-search-forward re nil t)
16401 (when (org-entry-delete (point) property) (cl-incf count)))
16402 (message "Property \"%s\" removed from %d entries" property count))))
16404 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16406 (defun org-compute-property-at-point ()
16407 "Compute the property at point.
16408 This looks for an enclosing column format, extracts the operator and
16409 then applies it to the property in the column format's scope."
16410 (interactive)
16411 (unless (org-at-property-p)
16412 (user-error "Not at a property"))
16413 (let ((prop (org-match-string-no-properties 2)))
16414 (org-columns-get-format-and-top-level)
16415 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16416 (user-error "No operator defined for property %s" prop))
16417 (org-columns-compute prop)))
16419 (defvar org-property-allowed-value-functions nil
16420 "Hook for functions supplying allowed values for a specific property.
16421 The functions must take a single argument, the name of the property, and
16422 return a flat list of allowed values. If \":ETC\" is one of
16423 the values, this means that these values are intended as defaults for
16424 completion, but that other values should be allowed too.
16425 The functions must return nil if they are not responsible for this
16426 property.")
16428 (defun org-property-get-allowed-values (pom property &optional table)
16429 "Get allowed values for the property PROPERTY.
16430 When TABLE is non-nil, return an alist that can directly be used for
16431 completion."
16432 (let (vals)
16433 (cond
16434 ((equal property "TODO")
16435 (setq vals (org-with-point-at pom
16436 (append org-todo-keywords-1 '("")))))
16437 ((equal property "PRIORITY")
16438 (let ((n org-lowest-priority))
16439 (while (>= n org-highest-priority)
16440 (push (char-to-string n) vals)
16441 (setq n (1- n)))))
16442 ((equal property "CATEGORY"))
16443 ((member property org-special-properties))
16444 ((setq vals (run-hook-with-args-until-success
16445 'org-property-allowed-value-functions property)))
16447 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16448 (when (and vals (string-match "\\S-" vals))
16449 (setq vals (car (read-from-string (concat "(" vals ")"))))
16450 (setq vals (mapcar (lambda (x)
16451 (cond ((stringp x) x)
16452 ((numberp x) (number-to-string x))
16453 ((symbolp x) (symbol-name x))
16454 (t "???")))
16455 vals)))))
16456 (when (member ":ETC" vals)
16457 (setq vals (remove ":ETC" vals))
16458 (org-add-props (car vals) '(org-unrestricted t)))
16459 (if table (mapcar 'list vals) vals)))
16461 (defun org-property-previous-allowed-value (&optional _previous)
16462 "Switch to the next allowed value for this property."
16463 (interactive)
16464 (org-property-next-allowed-value t))
16466 (defun org-property-next-allowed-value (&optional previous)
16467 "Switch to the next allowed value for this property."
16468 (interactive)
16469 (unless (org-at-property-p)
16470 (user-error "Not at a property"))
16471 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16472 (key (match-string 2))
16473 (value (match-string 3))
16474 (allowed (or (org-property-get-allowed-values (point) key)
16475 (and (member value '("[ ]" "[-]" "[X]"))
16476 '("[ ]" "[X]"))))
16477 (heading (save-match-data (nth 4 (org-heading-components))))
16478 nval)
16479 (unless allowed
16480 (user-error "Allowed values for this property have not been defined"))
16481 (when previous (setq allowed (reverse allowed)))
16482 (when (member value allowed)
16483 (setq nval (car (cdr (member value allowed)))))
16484 (setq nval (or nval (car allowed)))
16485 (when (equal nval value)
16486 (user-error "Only one allowed value for this property"))
16487 (org-at-property-p)
16488 (replace-match (concat " :" key ": " nval) t t)
16489 (org-indent-line)
16490 (beginning-of-line 1)
16491 (skip-chars-forward " \t")
16492 (when (equal prop org-effort-property)
16493 (org-refresh-property
16494 '((effort . identity)
16495 (effort-minutes . org-duration-string-to-minutes))
16496 nval)
16497 (when (string= org-clock-current-task heading)
16498 (setq org-clock-effort nval)
16499 (org-clock-update-mode-line)))
16500 (run-hook-with-args 'org-property-changed-functions key nval)))
16502 (defun org-find-olp (path &optional this-buffer)
16503 "Return a marker pointing to the entry at outline path OLP.
16504 If anything goes wrong, throw an error.
16505 You can wrap this call to catch the error like this:
16507 \(condition-case msg
16508 \(org-mobile-locate-entry (match-string 4))
16509 \(error (nth 1 msg)))
16511 The return value will then be either a string with the error message,
16512 or a marker if everything is OK.
16514 If THIS-BUFFER is set, the outline path does not contain a file,
16515 only headings."
16516 (let* ((file (if this-buffer buffer-file-name (pop path)))
16517 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16518 (level 1)
16519 (lmin 1)
16520 (lmax 1)
16521 end found flevel)
16522 (unless buffer (error "File not found :%s" file))
16523 (with-current-buffer buffer
16524 (org-with-wide-buffer
16525 (goto-char (point-min))
16526 (dolist (heading path)
16527 (let ((re (format org-complex-heading-regexp-format
16528 (regexp-quote heading)))
16529 (cnt 0))
16530 (while (re-search-forward re end t)
16531 (setq level (- (match-end 1) (match-beginning 1)))
16532 (when (and (>= level lmin) (<= level lmax))
16533 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16534 (when (= cnt 0)
16535 (error "Heading not found on level %d: %s" lmax heading))
16536 (when (> cnt 1)
16537 (error "Heading not unique on level %d: %s" lmax heading))
16538 (goto-char found)
16539 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16540 (setq end (save-excursion (org-end-of-subtree t t)))))
16541 (when (org-at-heading-p)
16542 (point-marker))))))
16544 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16545 "Find node HEADING in BUFFER.
16546 Return a marker to the heading if it was found, or nil if not.
16547 If POS-ONLY is set, return just the position instead of a marker.
16549 The heading text must match exact, but it may have a TODO keyword,
16550 a priority cookie and tags in the standard locations."
16551 (with-current-buffer (or buffer (current-buffer))
16552 (save-excursion
16553 (save-restriction
16554 (widen)
16555 (goto-char (point-min))
16556 (let (case-fold-search)
16557 (when (re-search-forward
16558 (format org-complex-heading-regexp-format
16559 (regexp-quote heading)) nil t)
16560 (if pos-only
16561 (match-beginning 0)
16562 (move-marker (make-marker) (match-beginning 0)))))))))
16564 (defun org-find-exact-heading-in-directory (heading &optional dir)
16565 "Find Org node headline HEADING in all .org files in directory DIR.
16566 When the target headline is found, return a marker to this location."
16567 (let ((files (directory-files (or dir default-directory)
16568 t "\\`[^.#].*\\.org\\'"))
16569 visiting m buffer)
16570 (catch 'found
16571 (dolist (file files)
16572 (message "trying %s" file)
16573 (setq visiting (org-find-base-buffer-visiting file))
16574 (setq buffer (or visiting (find-file-noselect file)))
16575 (setq m (org-find-exact-headline-in-buffer
16576 heading buffer))
16577 (when (and (not m) (not visiting)) (kill-buffer buffer))
16578 (and m (throw 'found m))))))
16580 (defun org-find-entry-with-id (ident)
16581 "Locate the entry that contains the ID property with exact value IDENT.
16582 IDENT can be a string, a symbol or a number, this function will search for
16583 the string representation of it.
16584 Return the position where this entry starts, or nil if there is no such entry."
16585 (interactive "sID: ")
16586 (let ((id (cond
16587 ((stringp ident) ident)
16588 ((symbolp ident) (symbol-name ident))
16589 ((numberp ident) (number-to-string ident))
16590 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16591 (org-with-wide-buffer (org-find-property "ID" id))))
16593 ;;;; Timestamps
16595 (defvar org-last-changed-timestamp nil)
16596 (defvar org-last-inserted-timestamp nil
16597 "The last time stamp inserted with `org-insert-time-stamp'.")
16598 (defvar org-ts-what) ; dynamically scoped parameter
16600 (defun org-time-stamp (arg &optional inactive)
16601 "Prompt for a date/time and insert a time stamp.
16603 If the user specifies a time like HH:MM or if this command is
16604 called with at least one prefix argument, the time stamp contains
16605 the date and the time. Otherwise, only the date is included.
16607 All parts of a date not specified by the user are filled in from
16608 the timestamp at point, if any, or the current date/time
16609 otherwise.
16611 If there is already a timestamp at the cursor, it is replaced.
16613 With two universal prefix arguments, insert an active timestamp
16614 with the current time without prompting the user.
16616 When called from lisp, the timestamp is inactive if INACTIVE is
16617 non-nil."
16618 (interactive "P")
16619 (let* ((ts (cond
16620 ((org-at-date-range-p t)
16621 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16622 ((org-at-timestamp-p t) (match-string 0))))
16623 ;; Default time is either the timestamp at point or today.
16624 ;; When entering a range, only the range start is considered.
16625 (default-time (if (not ts) (current-time)
16626 (apply #'encode-time (org-parse-time-string ts))))
16627 (default-input (and ts (org-get-compact-tod ts)))
16628 (repeater (and ts
16629 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16630 (match-string 0 ts)))
16631 org-time-was-given
16632 org-end-time-was-given
16633 (time
16634 (and (if (equal arg '(16)) (current-time)
16635 ;; Preserve `this-command' and `last-command'.
16636 (let ((this-command this-command)
16637 (last-command last-command))
16638 (org-read-date
16639 arg 'totime nil nil default-time default-input
16640 inactive))))))
16641 (cond
16642 ((and ts
16643 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16644 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16645 (insert "--")
16646 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16648 ;; Make sure we're on a timestamp. When in the middle of a date
16649 ;; range, move arbitrarily to range end.
16650 (unless (org-at-timestamp-p t)
16651 (skip-chars-forward "-")
16652 (org-at-timestamp-p t))
16653 (replace-match "")
16654 (setq org-last-changed-timestamp
16655 (org-insert-time-stamp
16656 time (or org-time-was-given arg)
16657 inactive nil nil (list org-end-time-was-given)))
16658 (when repeater
16659 (backward-char)
16660 (insert " " repeater)
16661 (setq org-last-changed-timestamp
16662 (concat (substring org-last-inserted-timestamp 0 -1)
16663 " " repeater ">")))
16664 (message "Timestamp updated"))
16665 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16666 (t (org-insert-time-stamp
16667 time (or org-time-was-given arg) inactive nil nil
16668 (list org-end-time-was-given))))))
16670 ;; FIXME: can we use this for something else, like computing time differences?
16671 (defun org-get-compact-tod (s)
16672 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16673 (let* ((t1 (match-string 1 s))
16674 (h1 (string-to-number (match-string 2 s)))
16675 (m1 (string-to-number (match-string 3 s)))
16676 (t2 (and (match-end 4) (match-string 5 s)))
16677 (h2 (and t2 (string-to-number (match-string 6 s))))
16678 (m2 (and t2 (string-to-number (match-string 7 s))))
16679 dh dm)
16680 (if (not t2)
16682 (setq dh (- h2 h1) dm (- m2 m1))
16683 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16684 (concat t1 "+" (number-to-string dh)
16685 (and (/= 0 dm) (format ":%02d" dm)))))))
16687 (defun org-time-stamp-inactive (&optional arg)
16688 "Insert an inactive time stamp.
16689 An inactive time stamp is enclosed in square brackets instead of angle
16690 brackets. It is inactive in the sense that it does not trigger agenda entries,
16691 does not link to the calendar and cannot be changed with the S-cursor keys.
16692 So these are more for recording a certain time/date."
16693 (interactive "P")
16694 (org-time-stamp arg 'inactive))
16696 (defvar org-date-ovl (make-overlay 1 1))
16697 (overlay-put org-date-ovl 'face 'org-date-selected)
16698 (org-detach-overlay org-date-ovl)
16700 (defvar org-ans1) ; dynamically scoped parameter
16701 (defvar org-ans2) ; dynamically scoped parameter
16703 (defvar org-plain-time-of-day-regexp) ; defined below
16705 (defvar org-overriding-default-time nil) ; dynamically scoped
16706 (defvar org-read-date-overlay nil)
16707 (defvar org-dcst nil) ; dynamically scoped
16708 (defvar org-read-date-history nil)
16709 (defvar org-read-date-final-answer nil)
16710 (defvar org-read-date-analyze-futurep nil)
16711 (defvar org-read-date-analyze-forced-year nil)
16712 (defvar org-read-date-inactive)
16714 (defvar org-read-date-minibuffer-local-map
16715 (let* ((map (make-sparse-keymap)))
16716 (set-keymap-parent map minibuffer-local-map)
16717 (org-defkey map (kbd ".")
16718 (lambda () (interactive)
16719 ;; Are we at the beginning of the prompt?
16720 (if (org-looking-back "^[^:]+: "
16721 (let ((inhibit-field-text-motion t))
16722 (line-beginning-position)))
16723 (org-eval-in-calendar '(calendar-goto-today))
16724 (insert "."))))
16725 (org-defkey map (kbd "C-.")
16726 (lambda () (interactive)
16727 (org-eval-in-calendar '(calendar-goto-today))))
16728 (org-defkey map [(meta shift left)]
16729 (lambda () (interactive)
16730 (org-eval-in-calendar '(calendar-backward-month 1))))
16731 (org-defkey map [(meta shift right)]
16732 (lambda () (interactive)
16733 (org-eval-in-calendar '(calendar-forward-month 1))))
16734 (org-defkey map [(meta shift up)]
16735 (lambda () (interactive)
16736 (org-eval-in-calendar '(calendar-backward-year 1))))
16737 (org-defkey map [(meta shift down)]
16738 (lambda () (interactive)
16739 (org-eval-in-calendar '(calendar-forward-year 1))))
16740 (org-defkey map [?\e (shift left)]
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-backward-month 1))))
16743 (org-defkey map [?\e (shift right)]
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-forward-month 1))))
16746 (org-defkey map [?\e (shift up)]
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(calendar-backward-year 1))))
16749 (org-defkey map [?\e (shift down)]
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-forward-year 1))))
16752 (org-defkey map [(shift up)]
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-backward-week 1))))
16755 (org-defkey map [(shift down)]
16756 (lambda () (interactive)
16757 (org-eval-in-calendar '(calendar-forward-week 1))))
16758 (org-defkey map [(shift left)]
16759 (lambda () (interactive)
16760 (org-eval-in-calendar '(calendar-backward-day 1))))
16761 (org-defkey map [(shift right)]
16762 (lambda () (interactive)
16763 (org-eval-in-calendar '(calendar-forward-day 1))))
16764 (org-defkey map "!"
16765 (lambda () (interactive)
16766 (org-eval-in-calendar '(diary-view-entries))
16767 (message "")))
16768 (org-defkey map ">"
16769 (lambda () (interactive)
16770 (org-eval-in-calendar '(calendar-scroll-left 1))))
16771 (org-defkey map "<"
16772 (lambda () (interactive)
16773 (org-eval-in-calendar '(calendar-scroll-right 1))))
16774 (org-defkey map "\C-v"
16775 (lambda () (interactive)
16776 (org-eval-in-calendar
16777 '(calendar-scroll-left-three-months 1))))
16778 (org-defkey map "\M-v"
16779 (lambda () (interactive)
16780 (org-eval-in-calendar
16781 '(calendar-scroll-right-three-months 1))))
16782 map)
16783 "Keymap for minibuffer commands when using `org-read-date'.")
16785 (defvar org-def)
16786 (defvar org-defdecode)
16787 (defvar org-with-time)
16789 (defvar calendar-setup) ; Dynamically scoped.
16790 (defun org-read-date (&optional with-time to-time from-string prompt
16791 default-time default-input inactive)
16792 "Read a date, possibly a time, and make things smooth for the user.
16793 The prompt will suggest to enter an ISO date, but you can also enter anything
16794 which will at least partially be understood by `parse-time-string'.
16795 Unrecognized parts of the date will default to the current day, month, year,
16796 hour and minute. If this command is called to replace a timestamp at point,
16797 or to enter the second timestamp of a range, the default time is taken
16798 from the existing stamp. Furthermore, the command prefers the future,
16799 so if you are giving a date where the year is not given, and the day-month
16800 combination is already past in the current year, it will assume you
16801 mean next year. For details, see the manual. A few examples:
16803 3-2-5 --> 2003-02-05
16804 feb 15 --> currentyear-02-15
16805 2/15 --> currentyear-02-15
16806 sep 12 9 --> 2009-09-12
16807 12:45 --> today 12:45
16808 22 sept 0:34 --> currentyear-09-22 0:34
16809 12 --> currentyear-currentmonth-12
16810 Fri --> nearest Friday after today
16811 -Tue --> last Tuesday
16812 etc.
16814 Furthermore you can specify a relative date by giving, as the *first* thing
16815 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16816 change in days weeks, months, years.
16817 With a single plus or minus, the date is relative to today. With a double
16818 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16819 +4d --> four days from today
16820 +4 --> same as above
16821 +2w --> two weeks from today
16822 ++5 --> five days from default date
16824 The function understands only English month and weekday abbreviations.
16826 While prompting, a calendar is popped up - you can also select the
16827 date with the mouse (button 1). The calendar shows a period of three
16828 months. To scroll it to other months, use the keys `>' and `<'.
16829 If you don't like the calendar, turn it off with
16830 (setq org-read-date-popup-calendar nil)
16832 With optional argument TO-TIME, the date will immediately be converted
16833 to an internal time.
16834 With an optional argument WITH-TIME, the prompt will suggest to
16835 also insert a time. Note that when WITH-TIME is not set, you can
16836 still enter a time, and this function will inform the calling routine
16837 about this change. The calling routine may then choose to change the
16838 format used to insert the time stamp into the buffer to include the time.
16839 With optional argument FROM-STRING, read from this string instead from
16840 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16841 the time/date that is used for everything that is not specified by the
16842 user."
16843 (require 'parse-time)
16844 (let* ((org-with-time with-time)
16845 (org-time-stamp-rounding-minutes
16846 (if (equal org-with-time '(16))
16847 '(0 0)
16848 org-time-stamp-rounding-minutes))
16849 (org-dcst org-display-custom-times)
16850 (ct (org-current-time))
16851 (org-def (or org-overriding-default-time default-time ct))
16852 (org-defdecode (decode-time org-def))
16853 (cur-frame (selected-frame))
16854 (mouse-autoselect-window nil) ; Don't let the mouse jump
16855 (calendar-setup
16856 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16857 (calendar-move-hook nil)
16858 (calendar-view-diary-initially-flag nil)
16859 (calendar-view-holidays-initially-flag nil)
16860 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16861 ;; Rationalize `org-def' and `org-defdecode', if required.
16862 (when (< (nth 2 org-defdecode) org-extend-today-until)
16863 (setf (nth 2 org-defdecode) -1)
16864 (setf (nth 1 org-defdecode) 59)
16865 (setq org-def (apply #'encode-time org-defdecode))
16866 (setq org-defdecode (decode-time org-def)))
16867 (let* ((timestr (format-time-string
16868 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16869 org-def))
16870 (prompt (concat (if prompt (concat prompt " ") "")
16871 (format "Date+time [%s]: " timestr))))
16872 (cond
16873 (from-string (setq ans from-string))
16874 (org-read-date-popup-calendar
16875 (save-excursion
16876 (save-window-excursion
16877 (calendar)
16878 (when (eq calendar-setup 'calendar-only)
16879 (setq cal-frame
16880 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16881 (select-frame cal-frame))
16882 (org-eval-in-calendar '(setq cursor-type nil) t)
16883 (unwind-protect
16884 (progn
16885 (calendar-forward-day (- (time-to-days org-def)
16886 (calendar-absolute-from-gregorian
16887 (calendar-current-date))))
16888 (org-eval-in-calendar nil t)
16889 (let* ((old-map (current-local-map))
16890 (map (copy-keymap calendar-mode-map))
16891 (minibuffer-local-map
16892 (copy-keymap org-read-date-minibuffer-local-map)))
16893 (org-defkey map (kbd "RET") 'org-calendar-select)
16894 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16895 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16896 (unwind-protect
16897 (progn
16898 (use-local-map map)
16899 (setq org-read-date-inactive inactive)
16900 (add-hook 'post-command-hook 'org-read-date-display)
16901 (setq org-ans0
16902 (read-string prompt
16903 default-input
16904 'org-read-date-history
16905 nil))
16906 ;; org-ans0: from prompt
16907 ;; org-ans1: from mouse click
16908 ;; org-ans2: from calendar motion
16909 (setq ans
16910 (concat org-ans0 " " (or org-ans1 org-ans2))))
16911 (remove-hook 'post-command-hook 'org-read-date-display)
16912 (use-local-map old-map)
16913 (when org-read-date-overlay
16914 (delete-overlay org-read-date-overlay)
16915 (setq org-read-date-overlay nil)))))
16916 (bury-buffer "*Calendar*")
16917 (when cal-frame
16918 (delete-frame cal-frame)
16919 (select-frame-set-input-focus cur-frame))))))
16921 (t ; Naked prompt only
16922 (unwind-protect
16923 (setq ans (read-string prompt default-input
16924 'org-read-date-history timestr))
16925 (when org-read-date-overlay
16926 (delete-overlay org-read-date-overlay)
16927 (setq org-read-date-overlay nil))))))
16929 (setq final (org-read-date-analyze ans org-def org-defdecode))
16931 (when org-read-date-analyze-forced-year
16932 (message "Year was forced into %s"
16933 (if org-read-date-force-compatible-dates
16934 "compatible range (1970-2037)"
16935 "range representable on this machine"))
16936 (ding))
16938 ;; One round trip to get rid of 34th of August and stuff like that....
16939 (setq final (decode-time (apply 'encode-time final)))
16941 (setq org-read-date-final-answer ans)
16943 (if to-time
16944 (apply 'encode-time final)
16945 (if (and (boundp 'org-time-was-given) org-time-was-given)
16946 (format "%04d-%02d-%02d %02d:%02d"
16947 (nth 5 final) (nth 4 final) (nth 3 final)
16948 (nth 2 final) (nth 1 final))
16949 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16951 (defun org-read-date-display ()
16952 "Display the current date prompt interpretation in the minibuffer."
16953 (when org-read-date-display-live
16954 (when org-read-date-overlay
16955 (delete-overlay org-read-date-overlay))
16956 (when (minibufferp (current-buffer))
16957 (save-excursion
16958 (end-of-line 1)
16959 (while (not (equal (buffer-substring
16960 (max (point-min) (- (point) 4)) (point))
16961 " "))
16962 (insert " ")))
16963 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16964 " " (or org-ans1 org-ans2)))
16965 (org-end-time-was-given nil)
16966 (f (org-read-date-analyze ans org-def org-defdecode))
16967 (fmts (if org-dcst
16968 org-time-stamp-custom-formats
16969 org-time-stamp-formats))
16970 (fmt (if (or org-with-time
16971 (and (boundp 'org-time-was-given) org-time-was-given))
16972 (cdr fmts)
16973 (car fmts)))
16974 (txt (format-time-string fmt (apply 'encode-time f)))
16975 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16976 (txt (concat "=> " txt)))
16977 (when (and org-end-time-was-given
16978 (string-match org-plain-time-of-day-regexp txt))
16979 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16980 org-end-time-was-given
16981 (substring txt (match-end 0)))))
16982 (when org-read-date-analyze-futurep
16983 (setq txt (concat txt " (=>F)")))
16984 (setq org-read-date-overlay
16985 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16986 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16988 (defun org-read-date-analyze (ans def defdecode)
16989 "Analyze the combined answer of the date prompt."
16990 ;; FIXME: cleanup and comment
16991 ;; Pass `current-time' result to `decode-time' (instead of calling
16992 ;; without arguments) so that only `current-time' has to be
16993 ;; overriden in tests.
16994 (let ((org-def def)
16995 (org-defdecode defdecode)
16996 (nowdecode (decode-time (current-time)))
16997 delta deltan deltaw deltadef year month day
16998 hour minute second wday pm h2 m2 tl wday1
16999 iso-year iso-weekday iso-week iso-date futurep kill-year)
17000 (setq org-read-date-analyze-futurep nil
17001 org-read-date-analyze-forced-year nil)
17002 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17003 (setq ans "+0"))
17005 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17006 (setq ans (replace-match "" t t ans)
17007 deltan (car delta)
17008 deltaw (nth 1 delta)
17009 deltadef (nth 2 delta)))
17011 ;; Check if there is an iso week date in there. If yes, store the
17012 ;; info and postpone interpreting it until the rest of the parsing
17013 ;; is done.
17014 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17015 (setq iso-year (when (match-end 1)
17016 (org-small-year-to-year
17017 (string-to-number (match-string 1 ans))))
17018 iso-weekday (when (match-end 3)
17019 (string-to-number (match-string 3 ans)))
17020 iso-week (string-to-number (match-string 2 ans)))
17021 (setq ans (replace-match "" t t ans)))
17023 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17024 (when (string-match
17025 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17026 (setq year (if (match-end 2)
17027 (string-to-number (match-string 2 ans))
17028 (progn (setq kill-year t)
17029 (string-to-number (format-time-string "%Y"))))
17030 month (string-to-number (match-string 3 ans))
17031 day (string-to-number (match-string 4 ans)))
17032 (when (< year 100) (setq year (+ 2000 year)))
17033 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17034 t nil ans)))
17036 ;; Help matching dotted european dates
17037 (when (string-match
17038 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17039 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17040 (setq kill-year t)
17041 (string-to-number (format-time-string "%Y")))
17042 day (string-to-number (match-string 1 ans))
17043 month (string-to-number (match-string 2 ans))
17044 ans (replace-match (format "%04d-%02d-%02d" year month day)
17045 t nil ans)))
17047 ;; Help matching american dates, like 5/30 or 5/30/7
17048 (when (string-match
17049 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17050 (setq year (if (match-end 4)
17051 (string-to-number (match-string 4 ans))
17052 (progn (setq kill-year t)
17053 (string-to-number (format-time-string "%Y"))))
17054 month (string-to-number (match-string 1 ans))
17055 day (string-to-number (match-string 2 ans)))
17056 (when (< year 100) (setq year (+ 2000 year)))
17057 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17058 t nil ans)))
17059 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17060 ;; If there is a time with am/pm, and *no* time without it, we convert
17061 ;; so that matching will be successful.
17062 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17063 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17064 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17065 (setq hour (string-to-number (match-string 1 ans))
17066 minute (if (match-end 3)
17067 (string-to-number (match-string 3 ans))
17069 pm (equal ?p
17070 (string-to-char (downcase (match-string 4 ans)))))
17071 (if (and (= hour 12) (not pm))
17072 (setq hour 0)
17073 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17074 (setq ans (replace-match (format "%02d:%02d" hour minute)
17075 t t ans))))
17077 ;; Check if a time range is given as a duration
17078 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17079 (setq hour (string-to-number (match-string 1 ans))
17080 h2 (+ hour (string-to-number (match-string 3 ans)))
17081 minute (string-to-number (match-string 2 ans))
17082 m2 (+ minute (if (match-end 5) (string-to-number
17083 (match-string 5 ans))0)))
17084 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17085 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17086 t t ans)))
17088 ;; Check if there is a time range
17089 (when (boundp 'org-end-time-was-given)
17090 (setq org-time-was-given nil)
17091 (when (and (string-match org-plain-time-of-day-regexp ans)
17092 (match-end 8))
17093 (setq org-end-time-was-given (match-string 8 ans))
17094 (setq ans (concat (substring ans 0 (match-beginning 7))
17095 (substring ans (match-end 7))))))
17097 (setq tl (parse-time-string ans)
17098 day (or (nth 3 tl) (nth 3 org-defdecode))
17099 month
17100 (cond ((nth 4 tl))
17101 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17102 ;; Day was specified. Make sure DAY+MONTH
17103 ;; combination happens in the future.
17104 ((nth 3 tl)
17105 (setq futurep t)
17106 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17107 (nth 4 nowdecode)))
17108 (t (nth 4 org-defdecode)))
17109 year
17110 (cond ((and (not kill-year) (nth 5 tl)))
17111 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17112 ;; Month was guessed in the future and is at least
17113 ;; equal to NOWDECODE's. Fix year accordingly.
17114 (futurep
17115 (if (or (> month (nth 4 nowdecode))
17116 (>= day (nth 3 nowdecode)))
17117 (nth 5 nowdecode)
17118 (1+ (nth 5 nowdecode))))
17119 ;; Month was specified. Make sure MONTH+YEAR
17120 ;; combination happens in the future.
17121 ((nth 4 tl)
17122 (setq futurep t)
17123 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17124 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17125 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17126 (t (nth 5 nowdecode))))
17127 (t (nth 5 org-defdecode)))
17128 hour (or (nth 2 tl) (nth 2 org-defdecode))
17129 minute (or (nth 1 tl) (nth 1 org-defdecode))
17130 second (or (nth 0 tl) 0)
17131 wday (nth 6 tl))
17133 (when (and (eq org-read-date-prefer-future 'time)
17134 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17135 (equal day (nth 3 nowdecode))
17136 (equal month (nth 4 nowdecode))
17137 (equal year (nth 5 nowdecode))
17138 (nth 2 tl)
17139 (or (< (nth 2 tl) (nth 2 nowdecode))
17140 (and (= (nth 2 tl) (nth 2 nowdecode))
17141 (nth 1 tl)
17142 (< (nth 1 tl) (nth 1 nowdecode)))))
17143 (setq day (1+ day)
17144 futurep t))
17146 ;; Special date definitions below
17147 (cond
17148 (iso-week
17149 ;; There was an iso week
17150 (require 'cal-iso)
17151 (setq futurep nil)
17152 (setq year (or iso-year year)
17153 day (or iso-weekday wday 1)
17154 wday nil ; to make sure that the trigger below does not match
17155 iso-date (calendar-gregorian-from-absolute
17156 (calendar-iso-to-absolute
17157 (list iso-week day year))))
17158 ; FIXME: Should we also push ISO weeks into the future?
17159 ; (when (and org-read-date-prefer-future
17160 ; (not iso-year)
17161 ; (< (calendar-absolute-from-gregorian iso-date)
17162 ; (time-to-days (current-time))))
17163 ; (setq year (1+ year)
17164 ; iso-date (calendar-gregorian-from-absolute
17165 ; (calendar-iso-to-absolute
17166 ; (list iso-week day year)))))
17167 (setq month (car iso-date)
17168 year (nth 2 iso-date)
17169 day (nth 1 iso-date)))
17170 (deltan
17171 (setq futurep nil)
17172 (unless deltadef
17173 ;; Pass `current-time' result to `decode-time' (instead of
17174 ;; calling without arguments) so that only `current-time' has
17175 ;; to be overriden in tests.
17176 (let ((now (decode-time (current-time))))
17177 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17178 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17179 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17180 ((equal deltaw "m") (setq month (+ month deltan)))
17181 ((equal deltaw "y") (setq year (+ year deltan)))))
17182 ((and wday (not (nth 3 tl)))
17183 ;; Weekday was given, but no day, so pick that day in the week
17184 ;; on or after the derived date.
17185 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17186 (unless (equal wday wday1)
17187 (setq day (+ day (% (- wday wday1 -7) 7))))))
17188 (when (and (boundp 'org-time-was-given)
17189 (nth 2 tl))
17190 (setq org-time-was-given t))
17191 (when (< year 100) (setq year (+ 2000 year)))
17192 ;; Check of the date is representable
17193 (if org-read-date-force-compatible-dates
17194 (progn
17195 (when (< year 1970)
17196 (setq year 1970 org-read-date-analyze-forced-year t))
17197 (when (> year 2037)
17198 (setq year 2037 org-read-date-analyze-forced-year t)))
17199 (condition-case nil
17200 (ignore (encode-time second minute hour day month year))
17201 (error
17202 (setq year (nth 5 org-defdecode))
17203 (setq org-read-date-analyze-forced-year t))))
17204 (setq org-read-date-analyze-futurep futurep)
17205 (list second minute hour day month year)))
17207 (defvar parse-time-weekdays)
17208 (defun org-read-date-get-relative (s today default)
17209 "Check string S for special relative date string.
17210 TODAY and DEFAULT are internal times, for today and for a default.
17211 Return shift list (N what def-flag)
17212 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17213 N is the number of WHATs to shift.
17214 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17215 the DEFAULT date rather than TODAY."
17216 (require 'parse-time)
17217 (when (and
17218 (string-match
17219 (concat
17220 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17221 "\\([0-9]+\\)?"
17222 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17223 "\\([ \t]\\|$\\)") s)
17224 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17225 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17226 (string-to-char (substring (match-string 1 s) -1))
17227 ?+))
17228 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17229 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17230 (what (if (match-end 3) (match-string 3 s) "d"))
17231 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17232 (date (if rel default today))
17233 (wday (nth 6 (decode-time date)))
17234 delta)
17235 (if wday1
17236 (progn
17237 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17238 (when (= delta 0) (setq delta 7))
17239 (when (= dir ?-)
17240 (setq delta (- delta 7))
17241 (when (= delta 0) (setq delta -7)))
17242 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17243 (list delta "d" rel))
17244 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17246 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17247 "Turn a user-specified date into the internal representation.
17248 The internal representation needed by the calendar is (month day year).
17249 This is a wrapper to handle the brain-dead convention in calendar that
17250 user function argument order change dependent on argument order."
17251 (if (boundp 'calendar-date-style)
17252 (cond
17253 ((eq calendar-date-style 'american)
17254 (list arg1 arg2 arg3))
17255 ((eq calendar-date-style 'european)
17256 (list arg2 arg1 arg3))
17257 ((eq calendar-date-style 'iso)
17258 (list arg2 arg3 arg1)))
17259 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17260 (if (org-bound-and-true-p european-calendar-style)
17261 (list arg2 arg1 arg3)
17262 (list arg1 arg2 arg3)))))
17264 (defun org-eval-in-calendar (form &optional keepdate)
17265 "Eval FORM in the calendar window and return to current window.
17266 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17267 otherwise stick to the current value of `org-ans2'."
17268 (let ((sf (selected-frame))
17269 (sw (selected-window)))
17270 (select-window (get-buffer-window "*Calendar*" t))
17271 (eval form)
17272 (when (and (not keepdate) (calendar-cursor-to-date))
17273 (let* ((date (calendar-cursor-to-date))
17274 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17275 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17276 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17277 (select-window sw)
17278 (org-select-frame-set-input-focus sf)))
17280 (defun org-calendar-select ()
17281 "Return to `org-read-date' with the date currently selected.
17282 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17283 (interactive)
17284 (when (calendar-cursor-to-date)
17285 (let* ((date (calendar-cursor-to-date))
17286 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17287 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17288 (when (active-minibuffer-window) (exit-minibuffer))))
17290 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17291 "Insert a date stamp for the date given by the internal TIME.
17292 See `format-time-string' for the format of TIME.
17293 WITH-HM means use the stamp format that includes the time of the day.
17294 INACTIVE means use square brackets instead of angular ones, so that the
17295 stamp will not contribute to the agenda.
17296 PRE and POST are optional strings to be inserted before and after the
17297 stamp.
17298 The command returns the inserted time stamp."
17299 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17300 stamp)
17301 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17302 (insert-before-markers (or pre ""))
17303 (when (listp extra)
17304 (setq extra (car extra))
17305 (if (and (stringp extra)
17306 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17307 (setq extra (format "-%02d:%02d"
17308 (string-to-number (match-string 1 extra))
17309 (string-to-number (match-string 2 extra))))
17310 (setq extra nil)))
17311 (when extra
17312 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17313 (insert-before-markers (setq stamp (format-time-string fmt time)))
17314 (insert-before-markers (or post ""))
17315 (setq org-last-inserted-timestamp stamp)))
17317 (defun org-toggle-time-stamp-overlays ()
17318 "Toggle the use of custom time stamp formats."
17319 (interactive)
17320 (setq org-display-custom-times (not org-display-custom-times))
17321 (unless org-display-custom-times
17322 (let ((p (point-min)) (bmp (buffer-modified-p)))
17323 (while (setq p (next-single-property-change p 'display))
17324 (when (and (get-text-property p 'display)
17325 (eq (get-text-property p 'face) 'org-date))
17326 (remove-text-properties
17327 p (setq p (next-single-property-change p 'display))
17328 '(display t))))
17329 (set-buffer-modified-p bmp)))
17330 (when (featurep 'xemacs)
17331 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17332 (org-restart-font-lock)
17333 (setq org-table-may-need-update t)
17334 (if org-display-custom-times
17335 (message "Time stamps are overlaid with custom format")
17336 (message "Time stamp overlays removed")))
17338 (defun org-display-custom-time (beg end)
17339 "Overlay modified time stamp format over timestamp between BEG and END."
17340 (let* ((ts (buffer-substring beg end))
17341 t1 w1 with-hm tf time str w2 (off 0))
17342 (save-match-data
17343 (setq t1 (org-parse-time-string ts t))
17344 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17345 (setq off (- (match-end 0) (match-beginning 0)))))
17346 (setq end (- end off))
17347 (setq w1 (- end beg)
17348 with-hm (and (nth 1 t1) (nth 2 t1))
17349 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17350 time (org-fix-decoded-time t1)
17351 str (org-add-props
17352 (format-time-string
17353 (substring tf 1 -1) (apply 'encode-time time))
17354 nil 'mouse-face 'highlight)
17355 w2 (length str))
17356 (unless (= w2 w1)
17357 (add-text-properties (1+ beg) (+ 2 beg)
17358 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17359 (if (featurep 'xemacs)
17360 (progn
17361 (put-text-property beg end 'invisible t)
17362 (put-text-property beg end 'end-glyph (make-glyph str)))
17363 (put-text-property beg end 'display str))))
17365 (defun org-fix-decoded-time (time)
17366 "Set 0 instead of nil for the first 6 elements of time.
17367 Don't touch the rest."
17368 (let ((n 0))
17369 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17371 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17373 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17374 "Difference between TIMESTAMP-STRING and now in days.
17375 If SECONDS is non-nil, return the difference in seconds."
17376 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17377 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17378 (funcall fdiff (current-time)))))
17380 (defun org-deadline-close (timestamp-string &optional ndays)
17381 "Is the time in TIMESTAMP-STRING close to the current date?"
17382 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17383 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17384 (not (org-entry-is-done-p))))
17386 (defun org-get-wdays (ts &optional delay zero-delay)
17387 "Get the deadline lead time appropriate for timestring TS.
17388 When DELAY is non-nil, get the delay time for scheduled items
17389 instead of the deadline lead time. When ZERO-DELAY is non-nil
17390 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17391 don't try to find the delay cookie in the scheduled timestamp."
17392 (let ((tv (if delay org-scheduled-delay-days
17393 org-deadline-warning-days)))
17394 (cond
17395 ((or (and delay (< tv 0))
17396 (and delay zero-delay (<= tv 0))
17397 (and (not delay) (<= tv 0)))
17398 ;; Enforce this value no matter what
17399 (- tv))
17400 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17401 ;; lead time is specified.
17402 (floor (* (string-to-number (match-string 1 ts))
17403 (cdr (assoc (match-string 2 ts)
17404 '(("d" . 1) ("w" . 7)
17405 ("m" . 30.4) ("y" . 365.25)
17406 ("h" . 0.041667)))))))
17407 ;; go for the default.
17408 (t tv))))
17410 (defun org-calendar-select-mouse (ev)
17411 "Return to `org-read-date' with the date currently selected.
17412 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17413 (interactive "e")
17414 (mouse-set-point ev)
17415 (when (calendar-cursor-to-date)
17416 (let* ((date (calendar-cursor-to-date))
17417 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17418 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17419 (when (active-minibuffer-window) (exit-minibuffer))))
17421 (defun org-check-deadlines (ndays)
17422 "Check if there are any deadlines due or past due.
17423 A deadline is considered due if it happens within `org-deadline-warning-days'
17424 days from today's date. If the deadline appears in an entry marked DONE,
17425 it is not shown. The prefix arg NDAYS can be used to test that many
17426 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17427 (interactive "P")
17428 (let* ((org-warn-days
17429 (cond
17430 ((equal ndays '(4)) 100000)
17431 (ndays (prefix-numeric-value ndays))
17432 (t (abs org-deadline-warning-days))))
17433 (case-fold-search nil)
17434 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17435 (callback
17436 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17437 (message "%d deadlines past-due or due within %d days"
17438 (org-occur regexp nil callback)
17439 org-warn-days)))
17441 (defsubst org-re-timestamp (type)
17442 "Return a regexp for timestamp TYPE.
17443 Allowed values for TYPE are:
17445 all: all timestamps
17446 active: only active timestamps (<...>)
17447 inactive: only inactive timestamps ([...])
17448 scheduled: only scheduled timestamps
17449 deadline: only deadline timestamps
17450 closed: only closed time-stamps
17452 When TYPE is nil, fall back on returning a regexp that matches
17453 both scheduled and deadline timestamps."
17454 (cl-case type
17455 (all org-ts-regexp-both)
17456 (active org-ts-regexp)
17457 (inactive org-ts-regexp-inactive)
17458 (scheduled org-scheduled-time-regexp)
17459 (deadline org-deadline-time-regexp)
17460 (closed org-closed-time-regexp)
17461 (otherwise
17462 (concat "\\<"
17463 (regexp-opt (list org-deadline-string org-scheduled-string))
17464 " *<\\([^>]+\\)>"))))
17466 (defun org-check-before-date (d)
17467 "Check if there are deadlines or scheduled entries before date D."
17468 (interactive (list (org-read-date)))
17469 (let ((case-fold-search nil)
17470 (regexp (org-re-timestamp org-ts-type))
17471 (callback
17472 `(lambda ()
17473 (let ((match (match-string 1)))
17474 (and ,(if (memq org-ts-type '(active inactive all))
17475 '(eq (org-element-type (org-element-context)) 'timestamp)
17476 '(org-at-planning-p))
17477 (time-less-p
17478 (org-time-string-to-time match)
17479 (org-time-string-to-time d)))))))
17480 (message "%d entries before %s"
17481 (org-occur regexp nil callback)
17482 d)))
17484 (defun org-check-after-date (d)
17485 "Check if there are deadlines or scheduled entries after date D."
17486 (interactive (list (org-read-date)))
17487 (let ((case-fold-search nil)
17488 (regexp (org-re-timestamp org-ts-type))
17489 (callback
17490 `(lambda ()
17491 (let ((match (match-string 1)))
17492 (and ,(if (memq org-ts-type '(active inactive all))
17493 '(eq (org-element-type (org-element-context)) 'timestamp)
17494 '(org-at-planning-p))
17495 (not (time-less-p
17496 (org-time-string-to-time match)
17497 (org-time-string-to-time d))))))))
17498 (message "%d entries after %s"
17499 (org-occur regexp nil callback)
17500 d)))
17502 (defun org-check-dates-range (start-date end-date)
17503 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17504 (interactive (list (org-read-date nil nil nil "Range starts")
17505 (org-read-date nil nil nil "Range end")))
17506 (let ((case-fold-search nil)
17507 (regexp (org-re-timestamp org-ts-type))
17508 (callback
17509 `(lambda ()
17510 (let ((match (match-string 1)))
17511 (and
17512 ,(if (memq org-ts-type '(active inactive all))
17513 '(eq (org-element-type (org-element-context)) 'timestamp)
17514 '(org-at-planning-p))
17515 (not (time-less-p
17516 (org-time-string-to-time match)
17517 (org-time-string-to-time start-date)))
17518 (time-less-p
17519 (org-time-string-to-time match)
17520 (org-time-string-to-time end-date)))))))
17521 (message "%d entries between %s and %s"
17522 (org-occur regexp nil callback) start-date end-date)))
17524 (defun org-evaluate-time-range (&optional to-buffer)
17525 "Evaluate a time range by computing the difference between start and end.
17526 Normally the result is just printed in the echo area, but with prefix arg
17527 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17528 If the time range is actually in a table, the result is inserted into the
17529 next column.
17530 For time difference computation, a year is assumed to be exactly 365
17531 days in order to avoid rounding problems."
17532 (interactive "P")
17534 (org-clock-update-time-maybe)
17535 (save-excursion
17536 (unless (org-at-date-range-p t)
17537 (goto-char (point-at-bol))
17538 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17539 (unless (org-at-date-range-p t)
17540 (user-error "Not at a time-stamp range, and none found in current line")))
17541 (let* ((ts1 (match-string 1))
17542 (ts2 (match-string 2))
17543 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17544 (match-end (match-end 0))
17545 (time1 (org-time-string-to-time ts1))
17546 (time2 (org-time-string-to-time ts2))
17547 (t1 (org-float-time time1))
17548 (t2 (org-float-time time2))
17549 (diff (abs (- t2 t1)))
17550 (negative (< (- t2 t1) 0))
17551 ;; (ys (floor (* 365 24 60 60)))
17552 (ds (* 24 60 60))
17553 (hs (* 60 60))
17554 (fy "%dy %dd %02d:%02d")
17555 (fy1 "%dy %dd")
17556 (fd "%dd %02d:%02d")
17557 (fd1 "%dd")
17558 (fh "%02d:%02d")
17559 y d h m align)
17560 (if havetime
17561 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17563 d (floor (/ diff ds)) diff (mod diff ds)
17564 h (floor (/ diff hs)) diff (mod diff hs)
17565 m (floor (/ diff 60)))
17566 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17568 d (floor (+ (/ diff ds) 0.5))
17569 h 0 m 0))
17570 (if (not to-buffer)
17571 (message "%s" (org-make-tdiff-string y d h m))
17572 (if (org-at-table-p)
17573 (progn
17574 (goto-char match-end)
17575 (setq align t)
17576 (and (looking-at " *|") (goto-char (match-end 0))))
17577 (goto-char match-end))
17578 (when (looking-at
17579 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17580 (replace-match ""))
17581 (when negative (insert " -"))
17582 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17583 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17584 (insert " " (format fh h m))))
17585 (when align (org-table-align))
17586 (message "Time difference inserted")))))
17588 (defun org-make-tdiff-string (y d h m)
17589 (let ((fmt "")
17590 (l nil))
17591 (when (> y 0)
17592 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17593 (push y l))
17594 (when (> d 0)
17595 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17596 (push d l))
17597 (when (> h 0)
17598 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17599 (push h l))
17600 (when (> m 0)
17601 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17602 (push m l))
17603 (apply 'format fmt (nreverse l))))
17605 (defun org-time-string-to-time (s &optional buffer pos)
17606 "Convert a timestamp string into internal time."
17607 (condition-case errdata
17608 (apply 'encode-time (org-parse-time-string s))
17609 (error (error "Bad timestamp `%s'%s\nError was: %s"
17610 s (if (not (and buffer pos))
17612 (format-message " at %d in buffer `%s'" pos buffer))
17613 (cdr errdata)))))
17615 (defun org-time-string-to-seconds (s)
17616 "Convert a timestamp string to a number of seconds."
17617 (org-float-time (org-time-string-to-time s)))
17619 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17621 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17622 "Convert time stamp S to an absolute day number.
17624 If DAYNR in non-nil, and there is a specifier for a cyclic time
17625 stamp, get the closest date to DAYNR. If PREFER is
17626 `past' (respectively `future') return a date past (respectively
17627 after) or equal to DAYNR.
17629 POS is the location of time stamp S, as a buffer position in
17630 BUFFER.
17632 Diary sexp timestamps are matched against DAYNR, when non-nil.
17633 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17634 signalled."
17635 (cond
17636 ((string-match "\\`%%\\((.*)\\)" s)
17637 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17638 ;; only able to match individual dates. If it fails, raise an
17639 ;; error.
17640 (if (and daynr
17641 (org-diary-sexp-entry
17642 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17643 daynr
17644 (signal 'org-diary-sexp-no-match (list s))))
17645 ((and daynr show-all) (org-closest-date s daynr prefer))
17646 (t (time-to-days
17647 (condition-case errdata
17648 (apply #'encode-time (org-parse-time-string s))
17649 (error (error "Bad timestamp `%s'%s\nError was: %s"
17651 (if (not (and buffer pos)) ""
17652 (format-message " at %d in buffer `%s'" pos buffer))
17653 (cdr errdata))))))))
17655 (defun org-days-to-iso-week (days)
17656 "Return the iso week number."
17657 (require 'cal-iso)
17658 (car (calendar-iso-from-absolute days)))
17660 (defun org-small-year-to-year (year)
17661 "Convert 2-digit years into 4-digit years.
17662 YEAR is expanded into one of the 30 next years, if possible, or
17663 into a past one. Any year larger than 99 is returned unchanged."
17664 (if (>= year 100) year
17665 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17666 (century (/ current 100))
17667 (offset (- year (% current 100))))
17668 (cond ((> offset 30) (+ (* (1- century) 100) year))
17669 ((> offset -70) (+ (* century 100) year))
17670 (t (+ (* (1+ century) 100) year))))))
17672 (defun org-time-from-absolute (d)
17673 "Return the time corresponding to date D.
17674 D may be an absolute day number, or a calendar-type list (month day year)."
17675 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17676 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17678 (defun org-calendar-holiday ()
17679 "List of holidays, for Diary display in Org mode."
17680 (declare (special date))
17681 (require 'holidays)
17682 (let ((hl (calendar-check-holidays date)))
17683 (and hl (mapconcat #'identity hl "; "))))
17685 (defun org-diary-sexp-entry (sexp entry d)
17686 "Process a SEXP diary ENTRY for date D."
17687 (require 'diary-lib)
17688 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17689 ;; dynamically.
17690 (let* ((sexp `(let ((entry ,entry)
17691 (date ',d))
17692 ,(car (read-from-string sexp))))
17693 (result (if calendar-debug-sexp (eval sexp)
17694 (condition-case nil
17695 (eval sexp)
17696 (error
17697 (beep)
17698 (message "Bad sexp at line %d in %s: %s"
17699 (org-current-line)
17700 (buffer-file-name) sexp)
17701 (sleep-for 2))))))
17702 (cond ((stringp result) (split-string result "; "))
17703 ((and (consp result)
17704 (not (consp (cdr result)))
17705 (stringp (cdr result))) (cdr result))
17706 ((and (consp result)
17707 (stringp (car result))) result)
17708 (result entry))))
17710 (defun org-diary-to-ical-string (frombuf)
17711 "Get iCalendar entries from diary entries in buffer FROMBUF.
17712 This uses the icalendar.el library."
17713 (let* ((tmpdir (if (featurep 'xemacs)
17714 (temp-directory)
17715 temporary-file-directory))
17716 (tmpfile (make-temp-name
17717 (expand-file-name "orgics" tmpdir)))
17718 buf rtn b e)
17719 (with-current-buffer frombuf
17720 (icalendar-export-region (point-min) (point-max) tmpfile)
17721 (setq buf (find-buffer-visiting tmpfile))
17722 (set-buffer buf)
17723 (goto-char (point-min))
17724 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17725 (setq b (match-beginning 0)))
17726 (goto-char (point-max))
17727 (when (re-search-backward "^END:VEVENT" nil t)
17728 (setq e (match-end 0)))
17729 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17730 (kill-buffer buf)
17731 (delete-file tmpfile)
17732 rtn))
17734 (defun org-closest-date (start current prefer)
17735 "Return closest date to CURRENT starting from START.
17737 CURRENT and START are both time stamps.
17739 When PREFER is `past', return a date that is either CURRENT or
17740 past. When PREFER is `future', return a date that is either
17741 CURRENT or future.
17743 Only time stamps with a repeater are modified. Any other time
17744 stamp stay unchanged. In any case, return value is an absolute
17745 day number."
17746 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17747 ;; No repeater. Do not shift time stamp.
17748 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17749 (let ((value (string-to-number (match-string 1 start)))
17750 (type (match-string 2 start)))
17751 (if (= 0 value)
17752 ;; Repeater with a 0-value is considered as void.
17753 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17754 (let* ((base (org-date-to-gregorian start))
17755 (target (org-date-to-gregorian current))
17756 (sday (calendar-absolute-from-gregorian base))
17757 (cday (calendar-absolute-from-gregorian target))
17758 n1 n2)
17759 ;; If START is already past CURRENT, just return START.
17760 (if (<= cday sday) sday
17761 ;; Compute closest date before (N1) and closest date past
17762 ;; (N2) CURRENT.
17763 (pcase type
17764 ("h"
17765 (let ((missing-hours
17766 (mod (+ (- (* 24 (- cday sday))
17767 (nth 2 (org-parse-time-string start)))
17768 org-extend-today-until)
17769 value)))
17770 (setf n1 (if (= missing-hours 0) cday
17771 (- cday (1+ (/ missing-hours 24)))))
17772 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17773 ((or "d" "w")
17774 (let ((value (if (equal type "w") (* 7 value) value)))
17775 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17776 (setf n2 (+ n1 value))))
17777 ("m"
17778 (let* ((add-months
17779 (lambda (d n)
17780 ;; Add N months to gregorian date D, i.e.,
17781 ;; a list (MONTH DAY YEAR). Return a valid
17782 ;; gregorian date.
17783 (let ((m (+ (nth 0 d) n)))
17784 (list (mod m 12)
17785 (nth 1 d)
17786 (+ (/ m 12) (nth 2 d))))))
17787 (months ; Complete months to TARGET.
17788 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17789 (- (nth 0 target) (nth 0 base))
17790 ;; If START's day is greater than
17791 ;; TARGET's, remove incomplete month.
17792 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17793 value)
17794 value))
17795 (before (funcall add-months base months)))
17796 (setf n1 (calendar-absolute-from-gregorian before))
17797 (setf n2
17798 (calendar-absolute-from-gregorian
17799 (funcall add-months before value)))))
17801 (let* ((d (nth 1 base))
17802 (m (nth 0 base))
17803 (y (nth 2 base))
17804 (years ; Complete years to TARGET.
17805 (* (/ (- (nth 2 target)
17807 ;; If START's month and day are
17808 ;; greater than TARGET's, remove
17809 ;; incomplete year.
17810 (if (or (> (nth 0 target) m)
17811 (and (= (nth 0 target) m)
17812 (> (nth 1 target) d)))
17815 value)
17816 value))
17817 (before (list m d (+ y years))))
17818 (setf n1 (calendar-absolute-from-gregorian before))
17819 (setf n2 (calendar-absolute-from-gregorian
17820 (list m d (+ (nth 2 before) value)))))))
17821 ;; Handle PREFER parameter, if any.
17822 (cond
17823 ((eq prefer 'past) (if (= cday n2) n2 n1))
17824 ((eq prefer 'future) (if (= cday n1) n1 n2))
17825 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17827 (defun org-date-to-gregorian (d)
17828 "Turn any specification of date D into a Gregorian date for the calendar."
17829 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17830 ((and (listp d) (= (length d) 3)) d)
17831 ((stringp d)
17832 (let ((d (org-parse-time-string d)))
17833 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17834 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17836 (defun org-parse-time-string (s &optional nodefault)
17837 "Parse the standard Org-mode time string.
17838 This should be a lot faster than the normal `parse-time-string'.
17839 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17840 hour and minute fields will be nil if not given."
17841 (cond ((string-match org-ts-regexp0 s)
17842 (list 0
17843 (when (or (match-beginning 8) (not nodefault))
17844 (string-to-number (or (match-string 8 s) "0")))
17845 (when (or (match-beginning 7) (not nodefault))
17846 (string-to-number (or (match-string 7 s) "0")))
17847 (string-to-number (match-string 4 s))
17848 (string-to-number (match-string 3 s))
17849 (string-to-number (match-string 2 s))
17850 nil nil nil))
17851 ((string-match "^<[^>]+>$" s)
17852 (decode-time (seconds-to-time (org-matcher-time s))))
17853 (t (error "Not a standard Org-mode time string: %s" s))))
17855 (defun org-timestamp-up (&optional arg)
17856 "Increase the date item at the cursor by one.
17857 If the cursor is on the year, change the year. If it is on the month,
17858 the day or the time, change that.
17859 With prefix ARG, change by that many units."
17860 (interactive "p")
17861 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17863 (defun org-timestamp-down (&optional arg)
17864 "Decrease the date item at the cursor by one.
17865 If the cursor is on the year, change the year. If it is on the month,
17866 the day or the time, change that.
17867 With prefix ARG, change by that many units."
17868 (interactive "p")
17869 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17871 (defun org-timestamp-up-day (&optional arg)
17872 "Increase the date in the time stamp by one day.
17873 With prefix ARG, change that many days."
17874 (interactive "p")
17875 (if (and (not (org-at-timestamp-p t))
17876 (org-at-heading-p))
17877 (org-todo 'up)
17878 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17880 (defun org-timestamp-down-day (&optional arg)
17881 "Decrease the date in the time stamp by one day.
17882 With prefix ARG, change that many days."
17883 (interactive "p")
17884 (if (and (not (org-at-timestamp-p t))
17885 (org-at-heading-p))
17886 (org-todo 'down)
17887 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17889 (defun org-at-timestamp-p (&optional inactive-ok)
17890 "Non-nil if point is inside a timestamp.
17892 When optional argument INACTIVE-OK is non-nil, also consider
17893 inactive timestamps.
17895 When this function returns a non-nil value, match data is set
17896 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17897 INACTIVE-OK."
17898 (interactive)
17899 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17900 (pos (point))
17901 (ans (or (looking-at tsr)
17902 (save-excursion
17903 (skip-chars-backward "^[<\n\r\t")
17904 (when (> (point) (point-min)) (backward-char 1))
17905 (and (looking-at tsr)
17906 (> (- (match-end 0) pos) -1))))))
17907 (and ans
17908 (boundp 'org-ts-what)
17909 (setq org-ts-what
17910 (cond
17911 ((= pos (match-beginning 0)) 'bracket)
17912 ;; Point is considered to be "on the bracket" whether
17913 ;; it's really on it or right after it.
17914 ((= pos (1- (match-end 0))) 'bracket)
17915 ((= pos (match-end 0)) 'after)
17916 ((org-pos-in-match-range pos 2) 'year)
17917 ((org-pos-in-match-range pos 3) 'month)
17918 ((org-pos-in-match-range pos 7) 'hour)
17919 ((org-pos-in-match-range pos 8) 'minute)
17920 ((or (org-pos-in-match-range pos 4)
17921 (org-pos-in-match-range pos 5)) 'day)
17922 ((and (> pos (or (match-end 8) (match-end 5)))
17923 (< pos (match-end 0)))
17924 (- pos (or (match-end 8) (match-end 5))))
17925 (t 'day))))
17926 ans))
17928 (defun org-toggle-timestamp-type ()
17929 "Toggle the type (<active> or [inactive]) of a time stamp."
17930 (interactive)
17931 (when (org-at-timestamp-p t)
17932 (let ((beg (match-beginning 0)) (end (match-end 0))
17933 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17934 (save-excursion
17935 (goto-char beg)
17936 (while (re-search-forward "[][<>]" end t)
17937 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17938 t t)))
17939 (message "Timestamp is now %sactive"
17940 (if (equal (char-after beg) ?<) "" "in")))))
17942 (defun org-at-clock-log-p nil
17943 "Is the cursor on the clock log line?"
17944 (save-excursion
17945 (move-beginning-of-line 1)
17946 (looking-at org-clock-line-re)))
17948 (defvar org-clock-history) ; defined in org-clock.el
17949 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17950 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17951 "Change the date in the time stamp at point.
17952 The date will be changed by N times WHAT. WHAT can be `day', `month',
17953 `year', `minute', `second'. If WHAT is not given, the cursor position
17954 in the timestamp determines what will be changed.
17955 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17956 (let ((origin (point)) origin-cat
17957 with-hm inactive
17958 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17959 org-ts-what
17960 extra rem
17961 ts time time0 fixnext clrgx)
17962 (unless (org-at-timestamp-p t)
17963 (user-error "Not at a timestamp"))
17964 (if (and (not what) (eq org-ts-what 'bracket))
17965 (org-toggle-timestamp-type)
17966 ;; Point isn't on brackets. Remember the part of the time-stamp
17967 ;; the point was in. Indeed, size of time-stamps may change,
17968 ;; but point must be kept in the same category nonetheless.
17969 (setq origin-cat org-ts-what)
17970 (when (and (not what) (not (eq org-ts-what 'day))
17971 org-display-custom-times
17972 (get-text-property (point) 'display)
17973 (not (get-text-property (1- (point)) 'display)))
17974 (setq org-ts-what 'day))
17975 (setq org-ts-what (or what org-ts-what)
17976 inactive (= (char-after (match-beginning 0)) ?\[)
17977 ts (match-string 0))
17978 (replace-match "")
17979 (when (string-match
17980 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17982 (setq extra (match-string 1 ts))
17983 (when suppress-tmp-delay
17984 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17985 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17986 (setq with-hm t))
17987 (setq time0 (org-parse-time-string ts))
17988 (when (and updown
17989 (eq org-ts-what 'minute)
17990 (not current-prefix-arg))
17991 ;; This looks like s-up and s-down. Change by one rounding step.
17992 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17993 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17994 (setcar (cdr time0) (+ (nth 1 time0)
17995 (if (> n 0) (- rem) (- dm rem))))))
17996 (setq time
17997 (encode-time (or (car time0) 0)
17998 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17999 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18000 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18001 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18002 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18003 (nthcdr 6 time0)))
18004 (when (and (member org-ts-what '(hour minute))
18005 extra
18006 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18007 (setq extra (org-modify-ts-extra
18008 extra
18009 (if (eq org-ts-what 'hour) 2 5)
18010 n dm)))
18011 (when (integerp org-ts-what)
18012 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18013 (when (eq what 'calendar)
18014 (let ((cal-date (org-get-date-from-calendar)))
18015 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18016 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18017 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18018 (setcar time0 (or (car time0) 0))
18019 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18020 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18021 (setq time (apply 'encode-time time0))))
18022 ;; Insert the new time-stamp, and ensure point stays in the same
18023 ;; category as before (i.e. not after the last position in that
18024 ;; category).
18025 (let ((pos (point)))
18026 ;; Stay before inserted string. `save-excursion' is of no use.
18027 (setq org-last-changed-timestamp
18028 (org-insert-time-stamp time with-hm inactive nil nil extra))
18029 (goto-char pos))
18030 (save-match-data
18031 (looking-at org-ts-regexp3)
18032 (goto-char (cond
18033 ;; `day' category ends before `hour' if any, or at
18034 ;; the end of the day name.
18035 ((eq origin-cat 'day)
18036 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18037 ((eq origin-cat 'hour) (min (match-end 7) origin))
18038 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18039 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18040 ;; `year' and `month' have both fixed size: point
18041 ;; couldn't have moved into another part.
18042 (t origin))))
18043 ;; Update clock if on a CLOCK line.
18044 (org-clock-update-time-maybe)
18045 ;; Maybe adjust the closest clock in `org-clock-history'
18046 (when org-clock-adjust-closest
18047 (if (not (and (org-at-clock-log-p)
18048 (< 1 (length (delq nil (mapcar 'marker-position
18049 org-clock-history))))))
18050 (message "No clock to adjust")
18051 (cond ((save-excursion ; fix previous clock?
18052 (re-search-backward org-ts-regexp0 nil t)
18053 (org-looking-back (concat org-clock-string " \\[")
18054 (line-beginning-position)))
18055 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18056 ((save-excursion ; fix next clock?
18057 (re-search-backward org-ts-regexp0 nil t)
18058 (looking-at (concat org-ts-regexp0 "\\] =>")))
18059 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18060 (save-window-excursion
18061 ;; Find closest clock to point, adjust the previous/next one in history
18062 (let* ((p (save-excursion (org-back-to-heading t)))
18063 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18064 (clfixnth
18065 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18066 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18067 (if (not clfixpos)
18068 (message "No clock to adjust")
18069 (save-excursion
18070 (org-goto-marker-or-bmk clfixpos)
18071 (org-show-subtree)
18072 (when (re-search-forward clrgx nil t)
18073 (goto-char (match-beginning 1))
18074 (let (org-clock-adjust-closest)
18075 (org-timestamp-change n org-ts-what updown))
18076 (message "Clock adjusted in %s for heading: %s"
18077 (file-name-nondirectory (buffer-file-name))
18078 (org-get-heading t t)))))))))
18079 ;; Try to recenter the calendar window, if any.
18080 (when (and org-calendar-follow-timestamp-change
18081 (get-buffer-window "*Calendar*" t)
18082 (memq org-ts-what '(day month year)))
18083 (org-recenter-calendar (time-to-days time))))))
18085 (defun org-modify-ts-extra (s pos n dm)
18086 "Change the different parts of the lead-time and repeat fields in timestamp."
18087 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18088 ng h m new rem)
18089 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18090 (cond
18091 ((or (org-pos-in-match-range pos 2)
18092 (org-pos-in-match-range pos 3))
18093 (setq m (string-to-number (match-string 3 s))
18094 h (string-to-number (match-string 2 s)))
18095 (if (org-pos-in-match-range pos 2)
18096 (setq h (+ h n))
18097 (setq n (* dm (org-no-warnings (signum n))))
18098 (unless (= 0 (setq rem (% m dm)))
18099 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18100 (setq m (+ m n)))
18101 (when (< m 0) (setq m (+ m 60) h (1- h)))
18102 (when (> m 59) (setq m (- m 60) h (1+ h)))
18103 (setq h (mod h 24))
18104 (setq ng 1 new (format "-%02d:%02d" h m)))
18105 ((org-pos-in-match-range pos 6)
18106 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18107 ((org-pos-in-match-range pos 5)
18108 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18110 ((org-pos-in-match-range pos 9)
18111 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18112 ((org-pos-in-match-range pos 8)
18113 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18115 (when ng
18116 (setq s (concat
18117 (substring s 0 (match-beginning ng))
18119 (substring s (match-end ng))))))
18122 (defun org-recenter-calendar (d)
18123 "If the calendar is visible, recenter it to date D."
18124 (let ((cwin (get-buffer-window "*Calendar*" t)))
18125 (when cwin
18126 (let ((calendar-move-hook nil))
18127 (with-selected-window cwin
18128 (calendar-goto-date
18129 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18131 (defun org-goto-calendar (&optional arg)
18132 "Go to the Emacs calendar at the current date.
18133 If there is a time stamp in the current line, go to that date.
18134 A prefix ARG can be used to force the current date."
18135 (interactive "P")
18136 (let ((tsr org-ts-regexp) diff
18137 (calendar-move-hook nil)
18138 (calendar-view-holidays-initially-flag nil)
18139 (calendar-view-diary-initially-flag nil))
18140 (when (or (org-at-timestamp-p)
18141 (save-excursion
18142 (beginning-of-line 1)
18143 (looking-at (concat ".*" tsr))))
18144 (let ((d1 (time-to-days (current-time)))
18145 (d2 (time-to-days
18146 (org-time-string-to-time (match-string 1)))))
18147 (setq diff (- d2 d1))))
18148 (calendar)
18149 (calendar-goto-today)
18150 (when (and diff (not arg)) (calendar-forward-day diff))))
18152 (defun org-get-date-from-calendar ()
18153 "Return a list (month day year) of date at point in calendar."
18154 (with-current-buffer "*Calendar*"
18155 (save-match-data
18156 (calendar-cursor-to-date))))
18158 (defun org-date-from-calendar ()
18159 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18160 If there is already a time stamp at the cursor position, update it."
18161 (interactive)
18162 (if (org-at-timestamp-p t)
18163 (org-timestamp-change 0 'calendar)
18164 (let ((cal-date (org-get-date-from-calendar)))
18165 (org-insert-time-stamp
18166 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18168 (defcustom org-effort-durations
18169 `(("min" . 1)
18170 ("h" . 60)
18171 ("d" . ,(* 60 8))
18172 ("w" . ,(* 60 8 5))
18173 ("m" . ,(* 60 8 5 4))
18174 ("y" . ,(* 60 8 5 40)))
18175 "Conversion factor to minutes for an effort modifier.
18177 Each entry has the form (MODIFIER . MINUTES).
18179 In an effort string, a number followed by MODIFIER is multiplied
18180 by the specified number of MINUTES to obtain an effort in
18181 minutes.
18183 For example, if the value of this variable is ((\"hours\" . 60)), then an
18184 effort string \"2hours\" is equivalent to 120 minutes."
18185 :group 'org-agenda
18186 :version "25.1"
18187 :package-version '(Org . "8.3")
18188 :type '(alist :key-type (string :tag "Modifier")
18189 :value-type (number :tag "Minutes")))
18191 (defun org-minutes-to-clocksum-string (m)
18192 "Format number of minutes as a clocksum string.
18193 The format is determined by `org-time-clocksum-format',
18194 `org-time-clocksum-use-fractional' and
18195 `org-time-clocksum-fractional-format' and
18196 `org-time-clocksum-use-effort-durations'."
18197 (let ((clocksum "")
18198 (m (round m)) ; Don't allow fractions of minutes
18199 h d w mo y fmt n)
18200 (setq h (if org-time-clocksum-use-effort-durations
18201 (cdr (assoc "h" org-effort-durations)) 60)
18202 d (if org-time-clocksum-use-effort-durations
18203 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18204 w (if org-time-clocksum-use-effort-durations
18205 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18206 mo (if org-time-clocksum-use-effort-durations
18207 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18208 y (if org-time-clocksum-use-effort-durations
18209 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18210 ;; fractional format
18211 (if org-time-clocksum-use-fractional
18212 (cond
18213 ;; single format string
18214 ((stringp org-time-clocksum-fractional-format)
18215 (format org-time-clocksum-fractional-format (/ m (float h))))
18216 ;; choice of fractional formats for different time units
18217 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18218 (> (/ (truncate m) (* y d h)) 0))
18219 (format fmt (/ m (* y d (float h)))))
18220 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18221 (> (/ (truncate m) (* mo d h)) 0))
18222 (format fmt (/ m (* mo d (float h)))))
18223 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18224 (> (/ (truncate m) (* w d h)) 0))
18225 (format fmt (/ m (* w d (float h)))))
18226 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18227 (> (/ (truncate m) (* d h)) 0))
18228 (format fmt (/ m (* d (float h)))))
18229 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18230 (> (/ (truncate m) h) 0))
18231 (format fmt (/ m (float h))))
18232 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18233 (format fmt m))
18234 ;; fall back to smallest time unit with a format
18235 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18236 (format fmt (/ m (float h))))
18237 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18238 (format fmt (/ m (* d (float h)))))
18239 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18240 (format fmt (/ m (* w d (float h)))))
18241 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18242 (format fmt (/ m (* mo d (float h)))))
18243 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18244 (format fmt (/ m (* y d (float h))))))
18245 ;; standard (non-fractional) format, with single format string
18246 (if (stringp org-time-clocksum-format)
18247 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18248 ;; separate formats components
18249 (and (setq fmt (plist-get org-time-clocksum-format :years))
18250 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18251 (plist-get org-time-clocksum-format :require-years))
18252 (setq clocksum (concat clocksum (format fmt n))
18253 m (- m (* n y d h))))
18254 (and (setq fmt (plist-get org-time-clocksum-format :months))
18255 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18256 (plist-get org-time-clocksum-format :require-months))
18257 (setq clocksum (concat clocksum (format fmt n))
18258 m (- m (* n mo d h))))
18259 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18260 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18261 (plist-get org-time-clocksum-format :require-weeks))
18262 (setq clocksum (concat clocksum (format fmt n))
18263 m (- m (* n w d h))))
18264 (and (setq fmt (plist-get org-time-clocksum-format :days))
18265 (or (> (setq n (/ (truncate m) (* d h))) 0)
18266 (plist-get org-time-clocksum-format :require-days))
18267 (setq clocksum (concat clocksum (format fmt n))
18268 m (- m (* n d h))))
18269 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18270 (or (> (setq n (/ (truncate m) h)) 0)
18271 (plist-get org-time-clocksum-format :require-hours))
18272 (setq clocksum (concat clocksum (format fmt n))
18273 m (- m (* n h))))
18274 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18275 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18276 (setq clocksum (concat clocksum (format fmt m))))
18277 ;; return formatted time duration
18278 clocksum))))
18280 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18281 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18282 "Org mode version 8.0")
18284 (defun org-hours-to-clocksum-string (n)
18285 (org-minutes-to-clocksum-string (* n 60)))
18287 (defun org-hh:mm-string-to-minutes (s)
18288 "Convert a string H:MM to a number of minutes.
18289 If the string is just a number, interpret it as minutes.
18290 In fact, the first hh:mm or number in the string will be taken,
18291 there can be extra stuff in the string.
18292 If no number is found, the return value is 0."
18293 (cond
18294 ((integerp s) s)
18295 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18296 (+ (* (string-to-number (match-string 1 s)) 60)
18297 (string-to-number (match-string 2 s))))
18298 ((string-match "\\([0-9]+\\)" s)
18299 (string-to-number (match-string 1 s)))
18300 (t 0)))
18302 (defcustom org-image-actual-width t
18303 "Should we use the actual width of images when inlining them?
18305 When set to t, always use the image width.
18307 When set to a number, use imagemagick (when available) to set
18308 the image's width to this value.
18310 When set to a number in a list, try to get the width from any
18311 #+ATTR.* keyword if it matches a width specification like
18313 #+ATTR_HTML: :width 300px
18315 and fall back on that number if none is found.
18317 When set to nil, try to get the width from an #+ATTR.* keyword
18318 and fall back on the original width if none is found.
18320 This requires Emacs >= 24.1, build with imagemagick support."
18321 :group 'org-appearance
18322 :version "24.4"
18323 :package-version '(Org . "8.0")
18324 :type '(choice
18325 (const :tag "Use the image width" t)
18326 (integer :tag "Use a number of pixels")
18327 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18328 (const :tag "Use #+ATTR* or don't resize" nil)))
18330 (defcustom org-agenda-inhibit-startup nil
18331 "Inhibit startup when preparing agenda buffers.
18332 When this variable is t, the initialization of the Org agenda
18333 buffers is inhibited: e.g. the visibility state is not set, the
18334 tables are not re-aligned, etc."
18335 :type 'boolean
18336 :version "24.3"
18337 :group 'org-agenda)
18339 (define-obsolete-variable-alias
18340 'org-agenda-ignore-drawer-properties
18341 'org-agenda-ignore-properties "25.1")
18343 (defcustom org-agenda-ignore-properties nil
18344 "Avoid updating text properties when building the agenda.
18345 Properties are used to prepare buffers for effort estimates,
18346 appointments, statistics and subtree-local categories.
18347 If you don't use these in the agenda, you can add them to this
18348 list and agenda building will be a bit faster.
18349 The value is a list, with zero or more of the symbols `effort', `appt',
18350 `stats' or `category'."
18351 :type '(set :greedy t
18352 (const effort)
18353 (const appt)
18354 (const stats)
18355 (const category))
18356 :version "25.1"
18357 :package-version '(Org . "8.3")
18358 :group 'org-agenda)
18360 (defun org-duration-string-to-minutes (s &optional output-to-string)
18361 "Convert a duration string S to minutes.
18363 A bare number is interpreted as minutes, modifiers can be set by
18364 customizing `org-effort-durations' (which see).
18366 Entries containing a colon are interpreted as H:MM by
18367 `org-hh:mm-string-to-minutes'."
18368 (let ((result 0)
18369 (re (concat "\\([0-9.]+\\) *\\("
18370 (regexp-opt (mapcar 'car org-effort-durations))
18371 "\\)")))
18372 (while (string-match re s)
18373 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18374 (string-to-number (match-string 1 s))))
18375 (setq s (replace-match "" nil t s)))
18376 (setq result (floor result))
18377 (cl-incf result (org-hh:mm-string-to-minutes s))
18378 (if output-to-string (number-to-string result) result)))
18380 ;;;; Files
18382 (defun org-save-all-org-buffers ()
18383 "Save all Org-mode buffers without user confirmation."
18384 (interactive)
18385 (message "Saving all Org-mode buffers...")
18386 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18387 (when (featurep 'org-id) (org-id-locations-save))
18388 (message "Saving all Org-mode buffers... done"))
18390 (defun org-revert-all-org-buffers ()
18391 "Revert all Org-mode buffers.
18392 Prompt for confirmation when there are unsaved changes.
18393 Be sure you know what you are doing before letting this function
18394 overwrite your changes.
18396 This function is useful in a setup where one tracks org files
18397 with a version control system, to revert on one machine after pulling
18398 changes from another. I believe the procedure must be like this:
18400 1. M-x org-save-all-org-buffers
18401 2. Pull changes from the other machine, resolve conflicts
18402 3. M-x org-revert-all-org-buffers"
18403 (interactive)
18404 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18405 (user-error "Abort"))
18406 (save-excursion
18407 (save-window-excursion
18408 (dolist (b (buffer-list))
18409 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18410 (with-current-buffer b buffer-file-name))
18411 (org-pop-to-buffer-same-window b)
18412 (revert-buffer t 'no-confirm)))
18413 (when (and (featurep 'org-id) org-id-track-globally)
18414 (org-id-locations-load)))))
18416 ;;;; Agenda files
18418 ;;;###autoload
18419 (defun org-switchb (&optional arg)
18420 "Switch between Org buffers.
18421 With one prefix argument, restrict available buffers to files.
18422 With two prefix arguments, restrict available buffers to agenda files.
18424 Defaults to `iswitchb' for buffer name completion.
18425 Set `org-completion-use-ido' to make it use ido instead."
18426 (interactive "P")
18427 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18428 ((equal arg '(16)) (org-buffer-list 'agenda))
18429 (t (org-buffer-list))))
18430 (org-completion-use-iswitchb org-completion-use-iswitchb)
18431 (org-completion-use-ido org-completion-use-ido))
18432 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18433 (setq org-completion-use-iswitchb t))
18434 (org-pop-to-buffer-same-window
18435 (completing-read "Org buffer: "
18436 (mapcar #'list (mapcar #'buffer-name blist))
18437 nil t))))
18439 ;;; Define some older names previously used for this functionality
18440 ;;;###autoload
18441 (defalias 'org-ido-switchb 'org-switchb)
18442 ;;;###autoload
18443 (defalias 'org-iswitchb 'org-switchb)
18445 (defun org-buffer-list (&optional predicate exclude-tmp)
18446 "Return a list of Org buffers.
18447 PREDICATE can be `export', `files' or `agenda'.
18449 export restrict the list to Export buffers.
18450 files restrict the list to buffers visiting Org files.
18451 agenda restrict the list to buffers visiting agenda files.
18453 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18454 (let* ((bfn nil)
18455 (agenda-files (and (eq predicate 'agenda)
18456 (mapcar 'file-truename (org-agenda-files t))))
18457 (filter
18458 (cond
18459 ((eq predicate 'files)
18460 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18461 ((eq predicate 'export)
18462 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18463 ((eq predicate 'agenda)
18464 (lambda (b)
18465 (with-current-buffer b
18466 (and (derived-mode-p 'org-mode)
18467 (setq bfn (buffer-file-name b))
18468 (member (file-truename bfn) agenda-files)))))
18469 (t (lambda (b) (with-current-buffer b
18470 (or (derived-mode-p 'org-mode)
18471 (string-match "\\*Org .*Export"
18472 (buffer-name b)))))))))
18473 (delq nil
18474 (mapcar
18475 (lambda(b)
18476 (if (and (funcall filter b)
18477 (or (not exclude-tmp)
18478 (not (string-match "tmp" (buffer-name b)))))
18480 nil))
18481 (buffer-list)))))
18483 (defun org-agenda-files (&optional unrestricted archives)
18484 "Get the list of agenda files.
18485 Optional UNRESTRICTED means return the full list even if a restriction
18486 is currently in place.
18487 When ARCHIVES is t, include all archive files that are really being
18488 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18489 `org-agenda-archives-mode' is t."
18490 (let ((files
18491 (cond
18492 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18493 ((stringp org-agenda-files) (org-read-agenda-file-list))
18494 ((listp org-agenda-files) org-agenda-files)
18495 (t (error "Invalid value of `org-agenda-files'")))))
18496 (setq files (apply 'append
18497 (mapcar (lambda (f)
18498 (if (file-directory-p f)
18499 (directory-files
18500 f t org-agenda-file-regexp)
18501 (list f)))
18502 files)))
18503 (when org-agenda-skip-unavailable-files
18504 (setq files (delq nil
18505 (mapcar (function
18506 (lambda (file)
18507 (and (file-readable-p file) file)))
18508 files))))
18509 (when (or (eq archives t)
18510 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18511 (setq files (org-add-archive-files files)))
18512 files))
18514 (defun org-agenda-file-p (&optional file)
18515 "Return non-nil, if FILE is an agenda file.
18516 If FILE is omitted, use the file associated with the current
18517 buffer."
18518 (let ((fname (or file (buffer-file-name))))
18519 (and fname
18520 (member (file-truename fname)
18521 (mapcar #'file-truename (org-agenda-files t))))))
18523 (defun org-edit-agenda-file-list ()
18524 "Edit the list of agenda files.
18525 Depending on setup, this either uses customize to edit the variable
18526 `org-agenda-files', or it visits the file that is holding the list. In the
18527 latter case, the buffer is set up in a way that saving it automatically kills
18528 the buffer and restores the previous window configuration."
18529 (interactive)
18530 (if (stringp org-agenda-files)
18531 (let ((cw (current-window-configuration)))
18532 (find-file org-agenda-files)
18533 (setq-local org-window-configuration cw)
18534 (org-add-hook 'after-save-hook
18535 (lambda ()
18536 (set-window-configuration
18537 (prog1 org-window-configuration
18538 (kill-buffer (current-buffer))))
18539 (org-install-agenda-files-menu)
18540 (message "New agenda file list installed"))
18541 nil 'local)
18542 (message "%s" (substitute-command-keys
18543 "Edit list and finish with \\[save-buffer]")))
18544 (customize-variable 'org-agenda-files)))
18546 (defun org-store-new-agenda-file-list (list)
18547 "Set new value for the agenda file list and save it correctly."
18548 (if (stringp org-agenda-files)
18549 (let ((fe (org-read-agenda-file-list t)) b u)
18550 (while (setq b (find-buffer-visiting org-agenda-files))
18551 (kill-buffer b))
18552 (with-temp-file org-agenda-files
18553 (insert
18554 (mapconcat
18555 (lambda (f) ;; Keep un-expanded entries.
18556 (if (setq u (assoc f fe))
18557 (cdr u)
18559 list "\n")
18560 "\n")))
18561 (let ((org-mode-hook nil) (org-inhibit-startup t)
18562 (org-insert-mode-line-in-empty-file nil))
18563 (setq org-agenda-files list)
18564 (customize-save-variable 'org-agenda-files org-agenda-files))))
18566 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18567 "Read the list of agenda files from a file.
18568 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18569 filenames, used by `org-store-new-agenda-file-list' to write back
18570 un-expanded file names."
18571 (when (file-directory-p org-agenda-files)
18572 (error "`org-agenda-files' cannot be a single directory"))
18573 (when (stringp org-agenda-files)
18574 (with-temp-buffer
18575 (insert-file-contents org-agenda-files)
18576 (mapcar
18577 (lambda (f)
18578 (let ((e (expand-file-name (substitute-in-file-name f)
18579 org-directory)))
18580 (if pair-with-expansion
18581 (cons e f)
18582 e)))
18583 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18585 ;;;###autoload
18586 (defun org-cycle-agenda-files ()
18587 "Cycle through the files in `org-agenda-files'.
18588 If the current buffer visits an agenda file, find the next one in the list.
18589 If the current buffer does not, find the first agenda file."
18590 (interactive)
18591 (let* ((fs (or (org-agenda-files t)
18592 (user-error "No agenda files")))
18593 (files (copy-sequence fs))
18594 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18595 file)
18596 (when tcf
18597 (while (and (setq file (pop files))
18598 (not (equal (file-truename file) tcf)))))
18599 (find-file (car (or files fs)))
18600 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18602 (defun org-agenda-file-to-front (&optional to-end)
18603 "Move/add the current file to the top of the agenda file list.
18604 If the file is not present in the list, it is added to the front. If it is
18605 present, it is moved there. With optional argument TO-END, add/move to the
18606 end of the list."
18607 (interactive "P")
18608 (let ((org-agenda-skip-unavailable-files nil)
18609 (file-alist (mapcar (lambda (x)
18610 (cons (file-truename x) x))
18611 (org-agenda-files t)))
18612 (ctf (file-truename
18613 (or buffer-file-name
18614 (user-error "Please save the current buffer to a file"))))
18615 x had)
18616 (setq x (assoc ctf file-alist) had x)
18618 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18619 (if to-end
18620 (setq file-alist (append (delq x file-alist) (list x)))
18621 (setq file-alist (cons x (delq x file-alist))))
18622 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18623 (org-install-agenda-files-menu)
18624 (message "File %s to %s of agenda file list"
18625 (if had "moved" "added") (if to-end "end" "front"))))
18627 (defun org-remove-file (&optional file)
18628 "Remove current file from the list of files in variable `org-agenda-files'.
18629 These are the files which are being checked for agenda entries.
18630 Optional argument FILE means use this file instead of the current."
18631 (interactive)
18632 (let* ((org-agenda-skip-unavailable-files nil)
18633 (file (or file buffer-file-name
18634 (user-error "Current buffer does not visit a file")))
18635 (true-file (file-truename file))
18636 (afile (abbreviate-file-name file))
18637 (files (delq nil (mapcar
18638 (lambda (x)
18639 (unless (equal true-file
18640 (file-truename x))
18642 (org-agenda-files t)))))
18643 (if (not (= (length files) (length (org-agenda-files t))))
18644 (progn
18645 (org-store-new-agenda-file-list files)
18646 (org-install-agenda-files-menu)
18647 (message "Removed from Org Agenda list: %s" afile))
18648 (message "File was not in list: %s (not removed)" afile))))
18650 (defun org-file-menu-entry (file)
18651 (vector file (list 'find-file file) t))
18653 (defun org-check-agenda-file (file)
18654 "Make sure FILE exists. If not, ask user what to do."
18655 (unless (file-exists-p file)
18656 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18657 (abbreviate-file-name file))
18658 (let ((r (downcase (read-char-exclusive))))
18659 (cond
18660 ((equal r ?r)
18661 (org-remove-file file)
18662 (throw 'nextfile t))
18663 (t (user-error "Abort"))))))
18665 (defun org-get-agenda-file-buffer (file)
18666 "Get an agenda buffer visiting FILE.
18667 If the buffer needs to be created, add it to the list of buffers
18668 which might be released later."
18669 (let ((buf (org-find-base-buffer-visiting file)))
18670 (if buf
18671 buf ; just return it
18672 ;; Make a new buffer and remember it
18673 (setq buf (find-file-noselect file))
18674 (when buf (push buf org-agenda-new-buffers))
18675 buf)))
18677 (defun org-release-buffers (blist)
18678 "Release all buffers in list, asking the user for confirmation when needed.
18679 When a buffer is unmodified, it is just killed. When modified, it is saved
18680 \(if the user agrees) and then killed."
18681 (let (file)
18682 (dolist (buf blist)
18683 (setq file (buffer-file-name buf))
18684 (when (and (buffer-modified-p buf)
18685 file
18686 (y-or-n-p (format "Save file %s? " file)))
18687 (with-current-buffer buf (save-buffer)))
18688 (kill-buffer buf))))
18690 (defun org-agenda-prepare-buffers (files)
18691 "Create buffers for all agenda files, protect archived trees and comments."
18692 (interactive)
18693 (let ((pa '(:org-archived t))
18694 (pc '(:org-comment t))
18695 (pall '(:org-archived t :org-comment t))
18696 (inhibit-read-only t)
18697 (org-inhibit-startup org-agenda-inhibit-startup)
18698 (rea (concat ":" org-archive-tag ":"))
18699 re pos)
18700 (setq org-tag-alist-for-agenda nil
18701 org-tag-groups-alist-for-agenda nil)
18702 (save-excursion
18703 (save-restriction
18704 (dolist (file files)
18705 (catch 'nextfile
18706 (if (bufferp file)
18707 (set-buffer file)
18708 (org-check-agenda-file file)
18709 (set-buffer (org-get-agenda-file-buffer file)))
18710 (widen)
18711 (org-set-regexps-and-options 'tags-only)
18712 (setq pos (point))
18713 (or (memq 'category org-agenda-ignore-properties)
18714 (org-refresh-category-properties))
18715 (or (memq 'stats org-agenda-ignore-properties)
18716 (org-refresh-stats-properties))
18717 (or (memq 'effort org-agenda-ignore-properties)
18718 (org-refresh-effort-properties))
18719 (or (memq 'appt org-agenda-ignore-properties)
18720 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18721 (setq org-todo-keywords-for-agenda
18722 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18723 (setq org-done-keywords-for-agenda
18724 (append org-done-keywords-for-agenda org-done-keywords))
18725 (setq org-todo-keyword-alist-for-agenda
18726 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18727 (setq org-tag-alist-for-agenda
18728 (org-uniquify
18729 (append org-tag-alist-for-agenda
18730 org-tag-alist
18731 org-tag-persistent-alist)))
18732 ;; Merge current file's tag groups into global
18733 ;; `org-tag-groups-alist-for-agenda'.
18734 (when org-group-tags
18735 (dolist (alist org-tag-groups-alist)
18736 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18737 (if old
18738 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18739 (push alist org-tag-groups-alist-for-agenda)))))
18740 (org-with-silent-modifications
18741 (save-excursion
18742 (remove-text-properties (point-min) (point-max) pall)
18743 (when org-agenda-skip-archived-trees
18744 (goto-char (point-min))
18745 (while (re-search-forward rea nil t)
18746 (when (org-at-heading-p t)
18747 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18748 (goto-char (point-min))
18749 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18750 (while (re-search-forward re nil t)
18751 (when (save-match-data (org-in-commented-heading-p t))
18752 (add-text-properties
18753 (match-beginning 0) (org-end-of-subtree t) pc)))))
18754 (goto-char pos)))))
18755 (setq org-todo-keywords-for-agenda
18756 (org-uniquify org-todo-keywords-for-agenda))
18757 (setq org-todo-keyword-alist-for-agenda
18758 (org-uniquify org-todo-keyword-alist-for-agenda))))
18761 ;;;; CDLaTeX minor mode
18763 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18764 "Keymap for the minor `org-cdlatex-mode'.")
18766 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18767 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18768 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18769 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18770 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18772 (defvar org-cdlatex-texmathp-advice-is-done nil
18773 "Flag remembering if we have applied the advice to texmathp already.")
18775 (define-minor-mode org-cdlatex-mode
18776 "Toggle the minor `org-cdlatex-mode'.
18777 This mode supports entering LaTeX environment and math in LaTeX fragments
18778 in Org-mode.
18779 \\{org-cdlatex-mode-map}"
18780 nil " OCDL" nil
18781 (when org-cdlatex-mode
18782 (require 'cdlatex)
18783 (run-hooks 'cdlatex-mode-hook)
18784 (cdlatex-compute-tables))
18785 (unless org-cdlatex-texmathp-advice-is-done
18786 (setq org-cdlatex-texmathp-advice-is-done t)
18787 (defadvice texmathp (around org-math-always-on activate)
18788 "Always return t in org-mode buffers.
18789 This is because we want to insert math symbols without dollars even outside
18790 the LaTeX math segments. If Orgmode thinks that point is actually inside
18791 an embedded LaTeX fragment, let texmathp do its job.
18792 \\[org-cdlatex-mode-map]"
18793 (interactive)
18794 (let (p)
18795 (cond
18796 ((not (derived-mode-p 'org-mode)) ad-do-it)
18797 ((eq this-command 'cdlatex-math-symbol)
18798 (setq ad-return-value t
18799 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18801 (let ((p (org-inside-LaTeX-fragment-p)))
18802 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18803 (setq ad-return-value t
18804 texmathp-why '("Org-mode embedded math" . 0))
18805 (when p ad-do-it)))))))))
18807 (defun turn-on-org-cdlatex ()
18808 "Unconditionally turn on `org-cdlatex-mode'."
18809 (org-cdlatex-mode 1))
18811 (defun org-try-cdlatex-tab ()
18812 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18813 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18814 - inside a LaTeX fragment, or
18815 - after the first word in a line, where an abbreviation expansion could
18816 insert a LaTeX environment."
18817 (when org-cdlatex-mode
18818 (cond
18819 ;; Before any word on the line: No expansion possible.
18820 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18821 ;; Just after first word on the line: Expand it. Make sure it
18822 ;; cannot happen on headlines, though.
18823 ((save-excursion
18824 (skip-chars-backward "a-zA-Z0-9*")
18825 (skip-chars-backward " \t")
18826 (and (bolp) (not (org-at-heading-p))))
18827 (cdlatex-tab) t)
18828 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18830 (defun org-cdlatex-underscore-caret (&optional _arg)
18831 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18832 Revert to the normal definition outside of these fragments."
18833 (interactive "P")
18834 (if (org-inside-LaTeX-fragment-p)
18835 (call-interactively 'cdlatex-sub-superscript)
18836 (let (org-cdlatex-mode)
18837 (call-interactively (key-binding (vector last-input-event))))))
18839 (defun org-cdlatex-math-modify (&optional _arg)
18840 "Execute `cdlatex-math-modify' in LaTeX fragments.
18841 Revert to the normal definition outside of these fragments."
18842 (interactive "P")
18843 (if (org-inside-LaTeX-fragment-p)
18844 (call-interactively 'cdlatex-math-modify)
18845 (let (org-cdlatex-mode)
18846 (call-interactively (key-binding (vector last-input-event))))))
18848 (defun org-cdlatex-environment-indent (&optional environment item)
18849 "Execute `cdlatex-environment' and indent the inserted environment.
18851 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18853 The inserted environment is indented to current indentation
18854 unless point is at the beginning of the line, in which the
18855 environment remains unintended."
18856 (interactive)
18857 ;; cdlatex-environment always return nil. Therefore, capture output
18858 ;; first and determine if an environment was selected.
18859 (let* ((beg (point-marker))
18860 (end (copy-marker (point) t))
18861 (inserted (progn
18862 (ignore-errors (cdlatex-environment environment item))
18863 (< beg end)))
18864 ;; Figure out how many lines to move forward after the
18865 ;; environment has been inserted.
18866 (lines (when inserted
18867 (save-excursion
18868 (- (cl-loop while (< beg (point))
18869 with x = 0
18870 do (forward-line -1)
18871 (cl-incf x)
18872 finally return x)
18873 (if (progn (goto-char beg)
18874 (and (progn (skip-chars-forward " \t") (eolp))
18875 (progn (skip-chars-backward " \t") (bolp))))
18876 1 0)))))
18877 (env (org-trim (delete-and-extract-region beg end))))
18878 (when inserted
18879 ;; Get indentation of next line unless at column 0.
18880 (let ((ind (if (bolp) 0
18881 (save-excursion
18882 (org-return-indent)
18883 (prog1 (org-get-indentation)
18884 (when (progn (skip-chars-forward " \t") (eolp))
18885 (delete-region beg (point)))))))
18886 (bol (progn (skip-chars-backward " \t") (bolp))))
18887 ;; Insert a newline before environment unless at column zero
18888 ;; to "escape" the current line. Insert a newline if
18889 ;; something is one the same line as \end{ENVIRONMENT}.
18890 (insert
18891 (concat (unless bol "\n") env
18892 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18893 (unless (zerop ind)
18894 (save-excursion
18895 (goto-char beg)
18896 (while (< (point) end)
18897 (unless (eolp) (org-indent-line-to ind))
18898 (forward-line))))
18899 (goto-char beg)
18900 (forward-line lines)
18901 (org-indent-line-to ind)))
18902 (set-marker beg nil)
18903 (set-marker end nil)))
18906 ;;;; LaTeX fragments
18908 (defun org-inside-LaTeX-fragment-p ()
18909 "Test if point is inside a LaTeX fragment.
18910 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18911 sequence appearing also before point.
18912 Even though the matchers for math are configurable, this function assumes
18913 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18914 delimiters are skipped when they have been removed by customization.
18915 The return value is nil, or a cons cell with the delimiter and the
18916 position of this delimiter.
18918 This function does a reasonably good job, but can locally be fooled by
18919 for example currency specifications. For example it will assume being in
18920 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18921 fragments that are properly closed, but during editing, we have to live
18922 with the uncertainty caused by missing closing delimiters. This function
18923 looks only before point, not after."
18924 (catch 'exit
18925 (let ((pos (point))
18926 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18927 (lim (progn
18928 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18929 (point)))
18930 dd-on str (start 0) m re)
18931 (goto-char pos)
18932 (when dodollar
18933 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18934 re (nth 1 (assoc "$" org-latex-regexps)))
18935 (while (string-match re str start)
18936 (cond
18937 ((= (match-end 0) (length str))
18938 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18939 ((= (match-end 0) (- (length str) 5))
18940 (throw 'exit nil))
18941 (t (setq start (match-end 0))))))
18942 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18943 (goto-char pos)
18944 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18945 (and (match-beginning 2) (throw 'exit nil))
18946 ;; count $$
18947 (while (re-search-backward "\\$\\$" lim t)
18948 (setq dd-on (not dd-on)))
18949 (goto-char pos)
18950 (when dd-on (cons "$$" m))))))
18952 (defun org-inside-latex-macro-p ()
18953 "Is point inside a LaTeX macro or its arguments?"
18954 (save-match-data
18955 (org-in-regexp
18956 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18958 (defvar-local org-latex-fragment-image-overlays nil
18959 "List of overlays carrying the images of latex fragments.")
18961 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18962 "Remove all overlays with LaTeX fragment images in current buffer.
18963 When optional arguments BEG and END are non-nil, remove all
18964 overlays between them instead. Return t when some overlays were
18965 removed, nil otherwise."
18966 (let (removedp)
18967 (setq org-latex-fragment-image-overlays
18968 (let ((beg (or beg (point-min)))
18969 (end (or end (point-max))))
18970 (cl-remove-if
18971 (lambda (o)
18972 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18973 ((and (>= (overlay-start o) beg)
18974 (<= (overlay-end o) end))
18975 (delete-overlay o)
18976 (unless removedp (setq removedp t)))
18977 (t nil)))
18978 org-latex-fragment-image-overlays)))
18979 removedp))
18981 (define-obsolete-function-alias
18982 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18983 (defun org-toggle-latex-fragment (&optional arg)
18984 "Preview the LaTeX fragment at point, or all locally or globally.
18986 If the cursor is on a LaTeX fragment, create the image and overlay
18987 it over the source code, if there is none. Remove it otherwise.
18988 If there is no fragment at point, display all fragments in the
18989 current section.
18991 With prefix ARG, preview or clear image for all fragments in the
18992 current subtree or in the whole buffer when used before the first
18993 headline. With a double prefix ARG \\[universal-argument] \
18994 \\[universal-argument] preview or clear images
18995 for all fragments in the buffer."
18996 (interactive "P")
18997 (unless (buffer-file-name (buffer-base-buffer))
18998 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18999 (when (display-graphic-p)
19000 (catch 'exit
19001 (save-excursion
19002 (let ((window-start (window-start)) msg)
19003 (save-restriction
19004 (cond
19005 ((or (equal arg '(16))
19006 (and (equal arg '(4))
19007 (org-with-limited-levels (org-before-first-heading-p))))
19008 (if (org-remove-latex-fragment-image-overlays)
19009 (progn (message "LaTeX fragments images removed from buffer")
19010 (throw 'exit nil))
19011 (setq msg "Creating images for buffer...")))
19012 ((equal arg '(4))
19013 (org-with-limited-levels (org-back-to-heading t))
19014 (let ((beg (point))
19015 (end (progn (org-end-of-subtree t) (point))))
19016 (if (org-remove-latex-fragment-image-overlays beg end)
19017 (progn
19018 (message "LaTeX fragment images removed from subtree")
19019 (throw 'exit nil))
19020 (setq msg "Creating images for subtree...")
19021 (narrow-to-region beg end))))
19022 ((let ((datum (org-element-context)))
19023 (when (memq (org-element-type datum)
19024 '(latex-environment latex-fragment))
19025 (let* ((beg (org-element-property :begin datum))
19026 (end (org-element-property :end datum)))
19027 (if (org-remove-latex-fragment-image-overlays beg end)
19028 (progn (message "LaTeX fragment image removed")
19029 (throw 'exit nil))
19030 (narrow-to-region beg end)
19031 (setq msg "Creating image..."))))))
19033 (org-with-limited-levels
19034 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19035 (outline-previous-heading)
19036 (point)))
19037 (end (progn (outline-next-heading) (point))))
19038 (if (org-remove-latex-fragment-image-overlays beg end)
19039 (progn
19040 (message "LaTeX fragment images removed from section")
19041 (throw 'exit nil))
19042 (setq msg "Creating images for section...")
19043 (narrow-to-region beg end))))))
19044 (let ((file (buffer-file-name (buffer-base-buffer))))
19045 (org-format-latex
19046 (concat org-latex-preview-ltxpng-directory
19047 (file-name-sans-extension (file-name-nondirectory file)))
19048 ;; Emacs cannot overlay images from remote hosts.
19049 ;; Create it in `temporary-file-directory' instead.
19050 (if (file-remote-p file) temporary-file-directory
19051 default-directory)
19052 'overlays msg 'forbuffer
19053 org-latex-create-formula-image-program)))
19054 ;; Work around a bug that doesn't restore window's start
19055 ;; when widening back the buffer.
19056 (set-window-start nil window-start)
19057 (message (concat msg "done")))))))
19059 (defun org-format-latex
19060 (prefix &optional dir overlays msg forbuffer processing-type)
19061 "Replace LaTeX fragments with links to an image, and produce images.
19063 When optional argument OVERLAYS is non-nil, display the image on
19064 top of the fragment instead of replacing it.
19066 PROCESSING-TYPE is the conversion method to use, as a symbol.
19068 Some of the options can be changed using the variable
19069 `org-format-latex-options', which see."
19070 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19071 (unless (eq processing-type 'verbatim)
19072 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19073 (cnt 0)
19074 checkdir-flag)
19075 (goto-char (point-min))
19076 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19077 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19078 (overlay-recenter (point-max)))
19079 (while (re-search-forward math-regexp nil t)
19080 (unless (and overlays
19081 (eq (get-char-property (point) 'org-overlay-type)
19082 'org-latex-overlay))
19083 (let* ((context (org-element-context))
19084 (type (org-element-type context)))
19085 (when (memq type '(latex-environment latex-fragment))
19086 (let ((block-type (eq type 'latex-environment))
19087 (value (org-element-property :value context))
19088 (beg (org-element-property :begin context))
19089 (end (save-excursion
19090 (goto-char (org-element-property :end context))
19091 (skip-chars-backward " \r\t\n")
19092 (point))))
19093 (cl-case processing-type
19094 (mathjax
19095 ;; Prepare for MathJax processing.
19096 (if (eq (char-after beg) ?$)
19097 (save-excursion
19098 (delete-region beg end)
19099 (insert "\\(" (substring value 1 -1) "\\)"))
19100 (goto-char end)))
19101 ((dvipng imagemagick)
19102 ;; Process to an image.
19103 (cl-incf cnt)
19104 (goto-char beg)
19105 (let* ((face (face-at-point))
19106 ;; Get the colors from the face at point.
19108 (let ((color (plist-get org-format-latex-options
19109 :foreground)))
19110 (if (and forbuffer (eq color 'auto))
19111 (face-attribute face :foreground nil 'default)
19112 color)))
19114 (let ((color (plist-get org-format-latex-options
19115 :background)))
19116 (if (and forbuffer (eq color 'auto))
19117 (face-attribute face :background nil 'default)
19118 color)))
19119 (hash (sha1 (prin1-to-string
19120 (list org-format-latex-header
19121 org-latex-default-packages-alist
19122 org-latex-packages-alist
19123 org-format-latex-options
19124 forbuffer value fg bg))))
19125 (absprefix (expand-file-name prefix dir))
19126 (linkfile (format "%s_%s.png" prefix hash))
19127 (movefile (format "%s_%s.png" absprefix hash))
19128 (sep (and block-type "\n\n"))
19129 (link (concat sep "[[file:" linkfile "]]" sep))
19130 (options
19131 (org-combine-plists
19132 org-format-latex-options
19133 `(:foreground ,fg :background ,bg))))
19134 (when msg (message msg cnt))
19135 (unless checkdir-flag ; Ensure the directory exists.
19136 (setq checkdir-flag t)
19137 (let ((todir (file-name-directory absprefix)))
19138 (unless (file-directory-p todir)
19139 (make-directory todir t))))
19140 (unless (file-exists-p movefile)
19141 (org-create-formula-image
19142 value movefile options forbuffer processing-type))
19143 (if overlays
19144 (progn
19145 (dolist (o (overlays-in beg end))
19146 (when (eq (overlay-get o 'org-overlay-type)
19147 'org-latex-overlay)
19148 (delete-overlay o)))
19149 (let ((ov (make-overlay beg end)))
19150 (overlay-put ov
19151 'org-overlay-type
19152 'org-latex-overlay)
19153 (overlay-put ov 'evaporate t)
19154 (if (featurep 'xemacs)
19155 (progn
19156 (overlay-put ov 'invisible t)
19157 (overlay-put
19158 ov 'end-glyph
19159 (make-glyph
19160 (vector 'png :file movefile))))
19161 (overlay-put
19162 ov 'display
19163 (list 'image
19164 :type 'png
19165 :file movefile
19166 :ascent 'center)))
19167 (push ov org-latex-fragment-image-overlays))
19168 (goto-char end))
19169 (delete-region beg end)
19170 (insert
19171 (org-add-props link
19172 (list 'org-latex-src
19173 (replace-regexp-in-string "\"" "" value)
19174 'org-latex-src-embed-type
19175 (if block-type 'paragraph 'character)))))))
19176 (mathml
19177 ;; Process to MathML.
19178 (unless (org-format-latex-mathml-available-p)
19179 (user-error "LaTeX to MathML converter not configured"))
19180 (cl-incf cnt)
19181 (when msg (message msg cnt))
19182 (goto-char beg)
19183 (delete-region beg end)
19184 (insert (org-format-latex-as-mathml
19185 value block-type prefix dir)))
19186 (otherwise
19187 (error "Unknown conversion type %s for LaTeX fragments"
19188 processing-type)))))))))))
19190 (defun org-create-math-formula (latex-frag &optional mathml-file)
19191 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19192 Use `org-latex-to-mathml-convert-command'. If the conversion is
19193 sucessful, return the portion between \"<math...> </math>\"
19194 elements otherwise return nil. When MATHML-FILE is specified,
19195 write the results in to that file. When invoked as an
19196 interactive command, prompt for LATEX-FRAG, with initial value
19197 set to the current active region and echo the results for user
19198 inspection."
19199 (interactive (list (let ((frag (when (org-region-active-p)
19200 (buffer-substring-no-properties
19201 (region-beginning) (region-end)))))
19202 (read-string "LaTeX Fragment: " frag nil frag))))
19203 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19204 (let* ((tmp-in-file
19205 (let ((file (file-relative-name
19206 (make-temp-name (expand-file-name "ltxmathml-in")))))
19207 (write-region latex-frag nil file)
19208 file))
19209 (tmp-out-file (file-relative-name
19210 (make-temp-name (expand-file-name "ltxmathml-out"))))
19211 (cmd (format-spec
19212 org-latex-to-mathml-convert-command
19213 `((?j . ,(and org-latex-to-mathml-jar-file
19214 (shell-quote-argument
19215 (expand-file-name
19216 org-latex-to-mathml-jar-file))))
19217 (?I . ,(shell-quote-argument tmp-in-file))
19218 (?i . ,latex-frag)
19219 (?o . ,(shell-quote-argument tmp-out-file)))))
19220 mathml shell-command-output)
19221 (when (org-called-interactively-p 'any)
19222 (unless (org-format-latex-mathml-available-p)
19223 (user-error "LaTeX to MathML converter not configured")))
19224 (message "Running %s" cmd)
19225 (setq shell-command-output (shell-command-to-string cmd))
19226 (setq mathml
19227 (when (file-readable-p tmp-out-file)
19228 (with-current-buffer (find-file-noselect tmp-out-file t)
19229 (goto-char (point-min))
19230 (when (re-search-forward
19231 (concat
19232 (regexp-quote
19233 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19234 "[^>]*?>"
19235 "\\(.\\|\n\\)*"
19236 "</math>")
19237 nil t)
19238 (prog1 (match-string 0) (kill-buffer))))))
19239 (cond
19240 (mathml
19241 (setq mathml
19242 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19243 (when mathml-file
19244 (write-region mathml nil mathml-file))
19245 (when (org-called-interactively-p 'any)
19246 (message mathml)))
19247 ((message "LaTeX to MathML conversion failed")
19248 (message shell-command-output)))
19249 (delete-file tmp-in-file)
19250 (when (file-exists-p tmp-out-file)
19251 (delete-file tmp-out-file))
19252 mathml))
19254 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19255 prefix &optional dir)
19256 "Use `org-create-math-formula' but check local cache first."
19257 (let* ((absprefix (expand-file-name prefix dir))
19258 (print-length nil) (print-level nil)
19259 (formula-id (concat
19260 "formula-"
19261 (sha1
19262 (prin1-to-string
19263 (list latex-frag
19264 org-latex-to-mathml-convert-command)))))
19265 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19266 (formula-cache-dir (file-name-directory formula-cache)))
19268 (unless (file-directory-p formula-cache-dir)
19269 (make-directory formula-cache-dir t))
19271 (unless (file-exists-p formula-cache)
19272 (org-create-math-formula latex-frag formula-cache))
19274 (if (file-exists-p formula-cache)
19275 ;; Successful conversion. Return the link to MathML file.
19276 (org-add-props
19277 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19278 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19279 'org-latex-src-embed-type (if latex-frag-type
19280 'paragraph 'character)))
19281 ;; Failed conversion. Return the LaTeX fragment verbatim
19282 latex-frag)))
19284 (defun org-create-formula-image (string tofile options buffer &optional type)
19285 "Create an image from LaTeX source using dvipng or convert.
19286 This function calls either `org-create-formula-image-with-dvipng'
19287 or `org-create-formula-image-with-imagemagick' depending on the
19288 value of `org-latex-create-formula-image-program' or on the value
19289 of the optional TYPE variable.
19291 Note: ultimately these two function should be combined as they
19292 share a good deal of logic."
19293 (org-check-external-command
19294 "latex" "needed to convert LaTeX fragments to images")
19295 (funcall
19296 (cl-case (or type org-latex-create-formula-image-program)
19297 (dvipng
19298 (org-check-external-command
19299 "dvipng" "needed to convert LaTeX fragments to images")
19300 #'org-create-formula-image-with-dvipng)
19301 (imagemagick
19302 (org-check-external-command
19303 "convert" "you need to install imagemagick")
19304 #'org-create-formula-image-with-imagemagick)
19305 (t (error
19306 "Invalid value of `org-latex-create-formula-image-program'")))
19307 string tofile options buffer))
19309 (declare-function org-export-get-backend "ox" (name))
19310 (declare-function org-export--get-global-options "ox" (&optional backend))
19311 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19312 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19313 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19314 (defun org-create-formula--latex-header ()
19315 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19316 (let ((info (org-combine-plists (org-export--get-global-options
19317 (org-export-get-backend 'latex))
19318 (org-export--get-inbuffer-options
19319 (org-export-get-backend 'latex)))))
19320 (org-latex-guess-babel-language
19321 (org-latex-guess-inputenc
19322 (org-splice-latex-header
19323 org-format-latex-header
19324 org-latex-default-packages-alist
19325 org-latex-packages-alist t
19326 (plist-get info :latex-header)))
19327 info)))
19329 (defun org--get-display-dpi ()
19330 "Get the DPI of the display.
19332 Assumes that the display has the same pixel width in the
19333 horizontal and vertical directions."
19334 (if (display-graphic-p)
19335 (round (/ (display-pixel-height)
19336 (/ (display-mm-height) 25.4)))
19337 (error "Attempt to calculate the dpi of a non-graphic display")))
19339 ;; This function borrows from Ganesh Swami's latex2png.el
19340 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19341 "This calls dvipng."
19342 (require 'ox-latex)
19343 (let* ((tmpdir (if (featurep 'xemacs)
19344 (temp-directory)
19345 temporary-file-directory))
19346 (texfilebase (make-temp-name
19347 (expand-file-name "orgtex" tmpdir)))
19348 (texfile (concat texfilebase ".tex"))
19349 (dvifile (concat texfilebase ".dvi"))
19350 (pngfile (concat texfilebase ".png"))
19351 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19352 ;; This assumes that the display has the same pixel width in
19353 ;; the horizontal and vertical directions
19354 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19355 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19356 "Black"))
19357 (bg (or (plist-get options (if buffer :background :html-background))
19358 "Transparent")))
19359 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19360 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19361 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19362 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19363 (let ((latex-header (org-create-formula--latex-header)))
19364 (with-temp-file texfile
19365 (insert latex-header)
19366 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19367 (let ((dir default-directory))
19368 (ignore-errors
19369 (cd tmpdir)
19370 (call-process "latex" nil nil nil texfile))
19371 (cd dir))
19372 (if (not (file-exists-p dvifile))
19373 (progn (message "Failed to create dvi file from %s" texfile) nil)
19374 (ignore-errors
19375 (if (featurep 'xemacs)
19376 (call-process "dvipng" nil nil nil
19377 "-fg" fg "-bg" bg
19378 "-T" "tight"
19379 "-o" pngfile
19380 dvifile)
19381 (call-process "dvipng" nil nil nil
19382 "-fg" fg "-bg" bg
19383 "-D" dpi
19384 ;;"-x" scale "-y" scale
19385 "-T" "tight"
19386 "-o" pngfile
19387 dvifile)))
19388 (if (not (file-exists-p pngfile))
19389 (if org-format-latex-signal-error
19390 (error "Failed to create png file from %s" texfile)
19391 (message "Failed to create png file from %s" texfile)
19392 nil)
19393 ;; Use the requested file name and clean up
19394 (copy-file pngfile tofile 'replace)
19395 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19396 (when (file-exists-p (concat texfilebase e))
19397 (delete-file (concat texfilebase e))))
19398 pngfile))))
19400 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19401 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19402 "This calls convert, which is included into imagemagick."
19403 (require 'ox-latex)
19404 (let* ((tmpdir (if (featurep 'xemacs)
19405 (temp-directory)
19406 temporary-file-directory))
19407 (texfilebase (make-temp-name
19408 (expand-file-name "orgtex" tmpdir)))
19409 (texfile (concat texfilebase ".tex"))
19410 (pdffile (concat texfilebase ".pdf"))
19411 (pngfile (concat texfilebase ".png"))
19412 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19413 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19414 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19415 "black"))
19416 (bg (or (plist-get options (if buffer :background :html-background))
19417 "white")))
19418 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19419 (setq fg (org-latex-color-format fg)))
19420 (if (eq bg 'default) (setq bg (org-latex-color :background))
19421 (setq bg (org-latex-color-format
19422 (if (string= bg "Transparent") "white" bg))))
19423 (let ((latex-header (org-create-formula--latex-header)))
19424 (with-temp-file texfile
19425 (insert latex-header)
19426 (insert "\n\\begin{document}\n"
19427 "\\definecolor{fg}{rgb}{" fg "}\n"
19428 "\\definecolor{bg}{rgb}{" bg "}\n"
19429 "\n\\pagecolor{bg}\n"
19430 "\n{\\color{fg}\n"
19431 string
19432 "\n}\n"
19433 "\n\\end{document}\n")))
19434 (org-latex-compile texfile t)
19435 (if (not (file-exists-p pdffile))
19436 (progn (message "Failed to create pdf file from %s" texfile) nil)
19437 (ignore-errors
19438 (if (featurep 'xemacs)
19439 (call-process "convert" nil nil nil
19440 "-density" "96"
19441 "-trim"
19442 "-antialias"
19443 pdffile
19444 "-quality" "100"
19445 ;; "-sharpen" "0x1.0"
19446 pngfile)
19447 (call-process "convert" nil nil nil
19448 "-density" dpi
19449 "-trim"
19450 "-antialias"
19451 pdffile
19452 "-quality" "100"
19453 ;; "-sharpen" "0x1.0"
19454 pngfile)))
19455 (if (not (file-exists-p pngfile))
19456 (if org-format-latex-signal-error
19457 (error "Failed to create png file from %s" texfile)
19458 (message "Failed to create png file from %s" texfile)
19459 nil)
19460 ;; Use the requested file name and clean up
19461 (copy-file pngfile tofile 'replace)
19462 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19463 (when (file-exists-p (concat texfilebase e))
19464 (delete-file (concat texfilebase e))))
19465 pngfile))))
19467 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19468 "Fill a LaTeX header template TPL.
19469 In the template, the following place holders will be recognized:
19471 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19472 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19473 [PACKAGES] \\usepackage statements for PKG
19474 [NO-PACKAGES] do not include PKG
19475 [EXTRA] the string EXTRA
19476 [NO-EXTRA] do not include EXTRA
19478 For backward compatibility, if both the positive and the negative place
19479 holder is missing, the positive one (without the \"NO-\") will be
19480 assumed to be present at the end of the template.
19481 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19482 EXTRA is a string.
19483 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19484 (let (rpl (end ""))
19485 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19486 (setq rpl (if (or (match-end 1) (not def-pkg))
19487 "" (org-latex-packages-to-string def-pkg snippets-p t))
19488 tpl (replace-match rpl t t tpl))
19489 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19491 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19492 (setq rpl (if (or (match-end 1) (not pkg))
19493 "" (org-latex-packages-to-string pkg snippets-p t))
19494 tpl (replace-match rpl t t tpl))
19495 (when pkg (setq end
19496 (concat end "\n"
19497 (org-latex-packages-to-string pkg snippets-p)))))
19499 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19500 (setq rpl (if (or (match-end 1) (not extra))
19501 "" (concat extra "\n"))
19502 tpl (replace-match rpl t t tpl))
19503 (when (and extra (string-match "\\S-" extra))
19504 (setq end (concat end "\n" extra))))
19506 (if (string-match "\\S-" end)
19507 (concat tpl "\n" end)
19508 tpl)))
19510 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19511 "Turn an alist of packages into a string with the \\usepackage macros."
19512 (setq pkg (mapconcat (lambda(p)
19513 (cond
19514 ((stringp p) p)
19515 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19516 (format "%% Package %s omitted" (cadr p)))
19517 ((equal "" (car p))
19518 (format "\\usepackage{%s}" (cadr p)))
19520 (format "\\usepackage[%s]{%s}"
19521 (car p) (cadr p)))))
19523 "\n"))
19524 (if newline (concat pkg "\n") pkg))
19526 (defun org-dvipng-color (attr)
19527 "Return a RGB color specification for dvipng."
19528 (apply 'format "rgb %s %s %s"
19529 (mapcar 'org-normalize-color
19530 (if (featurep 'xemacs)
19531 (color-rgb-components
19532 (face-property 'default
19533 (cond ((eq attr :foreground) 'foreground)
19534 ((eq attr :background) 'background))))
19535 (color-values (face-attribute 'default attr nil))))))
19537 (defun org-dvipng-color-format (color-name)
19538 "Convert COLOR-NAME to a RGB color value for dvipng."
19539 (apply 'format "rgb %s %s %s"
19540 (mapcar 'org-normalize-color
19541 (color-values color-name))))
19543 (defun org-latex-color (attr)
19544 "Return a RGB color for the LaTeX color package."
19545 (apply 'format "%s,%s,%s"
19546 (mapcar 'org-normalize-color
19547 (if (featurep 'xemacs)
19548 (color-rgb-components
19549 (face-property 'default
19550 (cond ((eq attr :foreground) 'foreground)
19551 ((eq attr :background) 'background))))
19552 (color-values (face-attribute 'default attr nil))))))
19554 (defun org-latex-color-format (color-name)
19555 "Convert COLOR-NAME to a RGB color value."
19556 (apply 'format "%s,%s,%s"
19557 (mapcar 'org-normalize-color
19558 (color-values color-name))))
19560 (defun org-normalize-color (value)
19561 "Return string to be used as color value for an RGB component."
19562 (format "%g" (/ value 65535.0)))
19566 ;; Image display
19568 (defvar-local org-inline-image-overlays nil)
19570 (defun org-toggle-inline-images (&optional include-linked)
19571 "Toggle the display of inline images.
19572 INCLUDE-LINKED is passed to `org-display-inline-images'."
19573 (interactive "P")
19574 (if org-inline-image-overlays
19575 (progn
19576 (org-remove-inline-images)
19577 (when (org-called-interactively-p 'interactive)
19578 (message "Inline image display turned off")))
19579 (org-display-inline-images include-linked)
19580 (when (org-called-interactively-p 'interactive)
19581 (message (if org-inline-image-overlays
19582 (format "%d images displayed inline"
19583 (length org-inline-image-overlays))
19584 "No images to display inline")))))
19586 (defun org-redisplay-inline-images ()
19587 "Refresh the display of inline images."
19588 (interactive)
19589 (if (not org-inline-image-overlays)
19590 (org-toggle-inline-images)
19591 (org-toggle-inline-images)
19592 (org-toggle-inline-images)))
19594 (defun org-display-inline-images (&optional include-linked refresh beg end)
19595 "Display inline images.
19597 An inline image is a link which follows either of these
19598 conventions:
19600 1. Its path is a file with an extension matching return value
19601 from `image-file-name-regexp' and it has no contents.
19603 2. Its description consists in a single link of the previous
19604 type.
19606 When optional argument INCLUDE-LINKED is non-nil, also links with
19607 a text description part will be inlined. This can be nice for
19608 a quick look at those images, but it does not reflect what
19609 exported files will look like.
19611 When optional argument REFRESH is non-nil, refresh existing
19612 images between BEG and END. This will create new image displays
19613 only if necessary. BEG and END default to the buffer
19614 boundaries."
19615 (interactive "P")
19616 (when (display-graphic-p)
19617 (unless refresh
19618 (org-remove-inline-images)
19619 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19620 (org-with-wide-buffer
19621 (goto-char (or beg (point-min)))
19622 (let ((case-fold-search t)
19623 (file-extension-re (image-file-name-regexp)))
19624 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19625 (let ((link (save-match-data (org-element-context))))
19626 ;; Check if we're at an inline image.
19627 (when (and (equal (org-element-property :type link) "file")
19628 (or include-linked
19629 (not (org-element-property :contents-begin link)))
19630 (let ((parent (org-element-property :parent link)))
19631 (or (not (eq (org-element-type parent) 'link))
19632 (not (cdr (org-element-contents parent)))))
19633 (org-string-match-p file-extension-re
19634 (org-element-property :path link)))
19635 (let ((file (expand-file-name
19636 (org-link-unescape
19637 (org-element-property :path link)))))
19638 (when (file-exists-p file)
19639 (let ((width
19640 ;; Apply `org-image-actual-width' specifications.
19641 (cond
19642 ((not (image-type-available-p 'imagemagick)) nil)
19643 ((eq org-image-actual-width t) nil)
19644 ((listp org-image-actual-width)
19646 ;; First try to find a width among
19647 ;; attributes associated to the paragraph
19648 ;; containing link.
19649 (let ((paragraph
19650 (let ((e link))
19651 (while (and (setq e (org-element-property
19652 :parent e))
19653 (not (eq (org-element-type e)
19654 'paragraph))))
19655 e)))
19656 (when paragraph
19657 (save-excursion
19658 (goto-char (org-element-property :begin paragraph))
19659 (when
19660 (re-search-forward
19661 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19662 (org-element-property
19663 :post-affiliated paragraph)
19665 (string-to-number (match-string 1))))))
19666 ;; Otherwise, fall-back to provided number.
19667 (car org-image-actual-width)))
19668 ((numberp org-image-actual-width)
19669 org-image-actual-width)))
19670 (old (get-char-property-and-overlay
19671 (org-element-property :begin link)
19672 'org-image-overlay)))
19673 (if (and (car-safe old) refresh)
19674 (image-refresh (overlay-get (cdr old) 'display))
19675 (let ((image (create-image file
19676 (and width 'imagemagick)
19678 :width width)))
19679 (when image
19680 (let* ((link
19681 ;; If inline image is the description
19682 ;; of another link, be sure to
19683 ;; consider the latter as the one to
19684 ;; apply the overlay on.
19685 (let ((parent
19686 (org-element-property :parent link)))
19687 (if (eq (org-element-type parent) 'link)
19688 parent
19689 link)))
19690 (ov (make-overlay
19691 (org-element-property :begin link)
19692 (progn
19693 (goto-char
19694 (org-element-property :end link))
19695 (skip-chars-backward " \t")
19696 (point)))))
19697 (overlay-put ov 'display image)
19698 (overlay-put ov 'face 'default)
19699 (overlay-put ov 'org-image-overlay t)
19700 (overlay-put
19701 ov 'modification-hooks
19702 (list 'org-display-inline-remove-overlay))
19703 (push ov org-inline-image-overlays)))))))))))))))
19705 (define-obsolete-function-alias
19706 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19708 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19709 "Remove inline-display overlay if a corresponding region is modified."
19710 (let ((inhibit-modification-hooks t))
19711 (when (and ov after)
19712 (delete ov org-inline-image-overlays)
19713 (delete-overlay ov))))
19715 (defun org-remove-inline-images ()
19716 "Remove inline display of images."
19717 (interactive)
19718 (mapc #'delete-overlay org-inline-image-overlays)
19719 (setq org-inline-image-overlays nil))
19721 ;;;; Key bindings
19723 ;; Outline functions from `outline-mode-prefix-map'
19724 ;; that can be remapped in Org:
19725 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19726 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19727 (define-key org-mode-map [remap outline-forward-same-level]
19728 'org-forward-heading-same-level)
19729 (define-key org-mode-map [remap outline-backward-same-level]
19730 'org-backward-heading-same-level)
19731 (define-key org-mode-map [remap outline-show-branches]
19732 'org-kill-note-or-show-branches)
19733 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19734 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19735 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19736 (define-key org-mode-map [remap outline-next-visible-heading]
19737 'org-next-visible-heading)
19738 (define-key org-mode-map [remap outline-previous-visible-heading]
19739 'org-previous-visible-heading)
19740 (define-key org-mode-map [remap show-children] 'org-show-children)
19742 ;; Outline functions from `outline-mode-prefix-map' that can not
19743 ;; be remapped in Org:
19745 ;; - the column "key binding" shows whether the Outline function is still
19746 ;; available in Org mode on the same key that it has been bound to in
19747 ;; Outline mode:
19748 ;; - "overridden": key used for a different functionality in Org mode
19749 ;; - else: key still bound to the same Outline function in Org mode
19751 ;; | Outline function | key binding | Org replacement |
19752 ;; |------------------------------------+-------------+--------------------------|
19753 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19754 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19755 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19756 ;; | `show-entry' | overridden | no replacement |
19757 ;; | `show-branches' | `C-c C-k' | still same function |
19758 ;; | `show-subtree' | overridden | visibility cycling |
19759 ;; | `show-all' | overridden | no replacement |
19760 ;; | `hide-subtree' | overridden | visibility cycling |
19761 ;; | `hide-body' | overridden | no replacement |
19762 ;; | `hide-entry' | overridden | visibility cycling |
19763 ;; | `hide-leaves' | overridden | no replacement |
19764 ;; | `hide-sublevels' | overridden | no replacement |
19765 ;; | `hide-other' | overridden | no replacement |
19767 ;; Make `C-c C-x' a prefix key
19768 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19770 ;; TAB key with modifiers
19771 (org-defkey org-mode-map "\C-i" 'org-cycle)
19772 (org-defkey org-mode-map [(tab)] 'org-cycle)
19773 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19774 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19775 ;; The following line is necessary under Suse GNU/Linux
19776 (unless (featurep 'xemacs)
19777 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19778 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19779 (define-key org-mode-map [backtab] 'org-shifttab)
19781 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19782 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19783 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19785 ;; Cursor keys with modifiers
19786 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19787 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19788 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19789 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19791 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19792 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19793 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19794 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19795 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19796 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19798 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19799 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19800 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19801 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19803 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19804 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19805 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19806 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19808 ;; Babel keys
19809 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19810 (dolist (pair org-babel-key-bindings)
19811 (define-key org-babel-map (car pair) (cdr pair)))
19813 ;;; Extra keys for tty access.
19814 ;; We only set them when really needed because otherwise the
19815 ;; menus don't show the simple keys
19817 (when (or org-use-extra-keys
19818 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19819 (not window-system))
19820 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19821 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19822 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19823 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19824 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19825 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19826 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19827 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19828 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19829 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19830 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19831 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19832 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19833 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19834 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19835 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19836 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19837 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19838 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19839 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19840 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19841 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19842 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19843 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19844 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19845 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19846 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19847 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19849 ;; All the other keys
19851 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19852 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19853 (if (boundp 'narrow-map)
19854 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19855 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19856 (if (boundp 'narrow-map)
19857 (org-defkey narrow-map "b" 'org-narrow-to-block)
19858 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19859 (if (boundp 'narrow-map)
19860 (org-defkey narrow-map "e" 'org-narrow-to-element)
19861 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19862 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19863 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19864 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19865 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19866 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19867 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19868 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19869 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19870 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19871 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19872 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19873 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19874 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19875 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19876 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19877 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19878 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19879 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19880 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19881 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19882 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19883 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19884 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19885 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19886 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19887 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19888 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19889 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19890 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19891 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19892 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19893 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19894 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19895 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19896 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19897 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19898 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19899 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19900 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19901 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19902 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19903 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19904 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19905 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19906 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19907 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19908 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19909 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19910 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19911 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19912 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19913 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19914 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19915 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19916 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19917 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19918 (org-defkey org-mode-map "\C-c^" 'org-sort)
19919 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19920 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19921 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19922 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19923 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19924 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19925 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19926 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19927 (org-defkey org-mode-map "\C-m" 'org-return)
19928 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19929 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19930 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19931 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19932 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19933 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19934 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19935 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19936 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19937 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19938 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19939 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19940 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19941 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19942 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19943 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19944 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19945 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19946 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19947 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19948 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19949 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19950 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19951 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19952 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19954 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19955 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19956 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19958 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19959 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19960 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19961 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19962 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19963 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19964 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19965 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19966 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19967 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19968 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19969 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19970 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19971 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19972 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19973 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19974 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19975 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19976 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19977 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19978 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19979 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19981 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19982 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19983 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19984 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19985 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19987 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19989 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19991 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19992 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19994 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19997 (when (featurep 'xemacs)
19998 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20001 (defconst org-speed-commands-default
20003 ("Outline Navigation")
20004 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20005 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20006 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20007 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20008 ("F" . org-next-block)
20009 ("B" . org-previous-block)
20010 ("u" . (org-speed-move-safe 'outline-up-heading))
20011 ("j" . org-goto)
20012 ("g" . (org-refile t))
20013 ("Outline Visibility")
20014 ("c" . org-cycle)
20015 ("C" . org-shifttab)
20016 (" " . org-display-outline-path)
20017 ("s" . org-narrow-to-subtree)
20018 ("=" . org-columns)
20019 ("Outline Structure Editing")
20020 ("U" . org-metaup)
20021 ("D" . org-metadown)
20022 ("r" . org-metaright)
20023 ("l" . org-metaleft)
20024 ("R" . org-shiftmetaright)
20025 ("L" . org-shiftmetaleft)
20026 ("i" . (progn (forward-char 1) (call-interactively
20027 'org-insert-heading-respect-content)))
20028 ("^" . org-sort)
20029 ("w" . org-refile)
20030 ("a" . org-archive-subtree-default-with-confirmation)
20031 ("@" . org-mark-subtree)
20032 ("#" . org-toggle-comment)
20033 ("Clock Commands")
20034 ("I" . org-clock-in)
20035 ("O" . org-clock-out)
20036 ("Meta Data Editing")
20037 ("t" . org-todo)
20038 ("," . (org-priority))
20039 ("0" . (org-priority ?\ ))
20040 ("1" . (org-priority ?A))
20041 ("2" . (org-priority ?B))
20042 ("3" . (org-priority ?C))
20043 (":" . org-set-tags-command)
20044 ("e" . org-set-effort)
20045 ("E" . org-inc-effort)
20046 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20047 (org-entry-put (point) "APPT_WARNTIME" m)))
20048 ("Agenda Views etc")
20049 ("v" . org-agenda)
20050 ("/" . org-sparse-tree)
20051 ("Misc")
20052 ("o" . org-open-at-point)
20053 ("?" . org-speed-command-help)
20054 ("<" . (org-agenda-set-restriction-lock 'subtree))
20055 (">" . (org-agenda-remove-restriction-lock))
20057 "The default speed commands.")
20059 (defun org-print-speed-command (e)
20060 (if (> (length (car e)) 1)
20061 (progn
20062 (princ "\n")
20063 (princ (car e))
20064 (princ "\n")
20065 (princ (make-string (length (car e)) ?-))
20066 (princ "\n"))
20067 (princ (car e))
20068 (princ " ")
20069 (if (symbolp (cdr e))
20070 (princ (symbol-name (cdr e)))
20071 (prin1 (cdr e)))
20072 (princ "\n")))
20074 (defun org-speed-command-help ()
20075 "Show the available speed commands."
20076 (interactive)
20077 (if (not org-use-speed-commands)
20078 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20079 (with-output-to-temp-buffer "*Help*"
20080 (princ "User-defined Speed commands\n===========================\n")
20081 (mapc #'org-print-speed-command org-speed-commands-user)
20082 (princ "\n")
20083 (princ "Built-in Speed commands\n=======================\n")
20084 (mapc #'org-print-speed-command org-speed-commands-default))
20085 (with-current-buffer "*Help*"
20086 (setq truncate-lines t))))
20088 (defun org-speed-move-safe (cmd)
20089 "Execute CMD, but make sure that the cursor always ends up in a headline.
20090 If not, return to the original position and throw an error."
20091 (interactive)
20092 (let ((pos (point)))
20093 (call-interactively cmd)
20094 (unless (and (bolp) (org-at-heading-p))
20095 (goto-char pos)
20096 (error "Boundary reached while executing %s" cmd))))
20098 (defvar org-self-insert-command-undo-counter 0)
20100 (defvar org-table-auto-blank-field) ; defined in org-table.el
20101 (defvar org-speed-command nil)
20103 (define-obsolete-function-alias
20104 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20106 (defun org-speed-command-activate (keys)
20107 "Hook for activating single-letter speed commands.
20108 `org-speed-commands-default' specifies a minimal command set.
20109 Use `org-speed-commands-user' for further customization."
20110 (when (or (and (bolp) (looking-at org-outline-regexp))
20111 (and (functionp org-use-speed-commands)
20112 (funcall org-use-speed-commands)))
20113 (cdr (assoc keys (append org-speed-commands-user
20114 org-speed-commands-default)))))
20116 (define-obsolete-function-alias
20117 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20119 (defun org-babel-speed-command-activate (keys)
20120 "Hook for activating single-letter code block commands."
20121 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20122 (cdr (assoc keys org-babel-key-bindings))))
20124 (defcustom org-speed-command-hook
20125 '(org-speed-command-default-hook org-babel-speed-command-hook)
20126 "Hook for activating speed commands at strategic locations.
20127 Hook functions are called in sequence until a valid handler is
20128 found.
20130 Each hook takes a single argument, a user-pressed command key
20131 which is also a `self-insert-command' from the global map.
20133 Within the hook, examine the cursor position and the command key
20134 and return nil or a valid handler as appropriate. Handler could
20135 be one of an interactive command, a function, or a form.
20137 Set `org-use-speed-commands' to non-nil value to enable this
20138 hook. The default setting is `org-speed-command-activate'."
20139 :group 'org-structure
20140 :version "24.1"
20141 :type 'hook)
20143 (defun org-self-insert-command (N)
20144 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20145 If the cursor is in a table looking at whitespace, the whitespace is
20146 overwritten, and the table is not marked as requiring realignment."
20147 (interactive "p")
20148 (org-check-before-invisible-edit 'insert)
20149 (cond
20150 ((and org-use-speed-commands
20151 (let ((kv (this-command-keys-vector)))
20152 (setq org-speed-command
20153 (run-hook-with-args-until-success
20154 'org-speed-command-hook
20155 (make-string 1 (aref kv (1- (length kv))))))))
20156 (cond
20157 ((commandp org-speed-command)
20158 (setq this-command org-speed-command)
20159 (call-interactively org-speed-command))
20160 ((functionp org-speed-command)
20161 (funcall org-speed-command))
20162 ((and org-speed-command (listp org-speed-command))
20163 (eval org-speed-command))
20164 (t (let (org-use-speed-commands)
20165 (call-interactively 'org-self-insert-command)))))
20166 ((and
20167 (org-at-table-p)
20168 (progn
20169 ;; Check if we blank the field, and if that triggers align.
20170 (and (featurep 'org-table) org-table-auto-blank-field
20171 (memq last-command
20172 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20173 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20174 ;; Got extra space, this field does not determine
20175 ;; column width.
20176 (let (org-table-may-need-update) (org-table-blank-field))
20177 ;; No extra space, this field may determine column
20178 ;; width.
20179 (org-table-blank-field)))
20181 (eq N 1)
20182 (looking-at "[^|\n]* \\( \\)|"))
20183 ;; There is room for insertion without re-aligning the table.
20184 (delete-region (match-beginning 1) (match-end 1))
20185 (self-insert-command N))
20187 (setq org-table-may-need-update t)
20188 (self-insert-command N)
20189 (org-fix-tags-on-the-fly)
20190 (when org-self-insert-cluster-for-undo
20191 (if (not (eq last-command 'org-self-insert-command))
20192 (setq org-self-insert-command-undo-counter 1)
20193 (if (>= org-self-insert-command-undo-counter 20)
20194 (setq org-self-insert-command-undo-counter 1)
20195 (and (> org-self-insert-command-undo-counter 0)
20196 buffer-undo-list (listp buffer-undo-list)
20197 (not (cadr buffer-undo-list)) ; remove nil entry
20198 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20199 (setq org-self-insert-command-undo-counter
20200 (1+ org-self-insert-command-undo-counter))))))))
20202 (defun org-check-before-invisible-edit (kind)
20203 "Check is editing if kind KIND would be dangerous with invisible text around.
20204 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20205 ;; First, try to get out of here as quickly as possible, to reduce overhead
20206 (when (and org-catch-invisible-edits
20207 (or (not (boundp 'visible-mode)) (not visible-mode))
20208 (or (get-char-property (point) 'invisible)
20209 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20210 ;; OK, we need to take a closer look
20211 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20212 (invisible-before-point (unless (bobp) (get-char-property
20213 (1- (point)) 'invisible)))
20214 (border-and-ok-direction
20216 ;; Check if we are acting predictably before invisible text
20217 (and invisible-at-point (not invisible-before-point)
20218 (memq kind '(insert delete-backward)))
20219 ;; Check if we are acting predictably after invisible text
20220 ;; This works not well, and I have turned it off. It seems
20221 ;; better to always show and stop after invisible text.
20222 ;; (and (not invisible-at-point) invisible-before-point
20223 ;; (memq kind '(insert delete)))
20225 (when (or (memq invisible-at-point '(outline org-hide-block t))
20226 (memq invisible-before-point '(outline org-hide-block t)))
20227 (when (eq org-catch-invisible-edits 'error)
20228 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20229 (if (and org-custom-properties-overlays
20230 (y-or-n-p "Display invisible properties in this buffer? "))
20231 (org-toggle-custom-properties-visibility)
20232 ;; Make the area visible
20233 (save-excursion
20234 (when invisible-before-point
20235 (goto-char (previous-single-char-property-change
20236 (point) 'invisible)))
20237 (outline-show-subtree))
20238 (cond
20239 ((eq org-catch-invisible-edits 'show)
20240 ;; That's it, we do the edit after showing
20241 (message
20242 "Unfolding invisible region around point before editing")
20243 (sit-for 1))
20244 ((and (eq org-catch-invisible-edits 'smart)
20245 border-and-ok-direction)
20246 (message "Unfolding invisible region around point before editing"))
20248 ;; Don't do the edit, make the user repeat it in full visibility
20249 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20251 (defun org-fix-tags-on-the-fly ()
20252 (when (and (equal (char-after (point-at-bol)) ?*)
20253 (org-at-heading-p))
20254 (org-align-tags-here org-tags-column)))
20256 (defun org-delete-backward-char (N)
20257 "Like `delete-backward-char', insert whitespace at field end in tables.
20258 When deleting backwards, in tables this function will insert whitespace in
20259 front of the next \"|\" separator, to keep the table aligned. The table will
20260 still be marked for re-alignment if the field did fill the entire column,
20261 because, in this case the deletion might narrow the column."
20262 (interactive "p")
20263 (save-match-data
20264 (org-check-before-invisible-edit 'delete-backward)
20265 (if (and (org-at-table-p)
20266 (eq N 1)
20267 (string-match "|" (buffer-substring (point-at-bol) (point)))
20268 (looking-at ".*?|"))
20269 (let ((pos (point))
20270 (noalign (looking-at "[^|\n\r]* |"))
20271 (c org-table-may-need-update))
20272 (backward-delete-char N)
20273 (unless overwrite-mode
20274 (skip-chars-forward "^|")
20275 (insert " ")
20276 (goto-char (1- pos)))
20277 ;; noalign: if there were two spaces at the end, this field
20278 ;; does not determine the width of the column.
20279 (when noalign (setq org-table-may-need-update c)))
20280 (backward-delete-char N)
20281 (org-fix-tags-on-the-fly))))
20283 (defun org-delete-char (N)
20284 "Like `delete-char', but insert whitespace at field end in tables.
20285 When deleting characters, in tables this function will insert whitespace in
20286 front of the next \"|\" separator, to keep the table aligned. The table will
20287 still be marked for re-alignment if the field did fill the entire column,
20288 because, in this case the deletion might narrow the column."
20289 (interactive "p")
20290 (save-match-data
20291 (org-check-before-invisible-edit 'delete)
20292 (if (and (org-at-table-p)
20293 (not (bolp))
20294 (not (= (char-after) ?|))
20295 (eq N 1))
20296 (if (looking-at ".*?|")
20297 (let ((pos (point))
20298 (noalign (looking-at "[^|\n\r]* |"))
20299 (c org-table-may-need-update))
20300 (replace-match
20301 (concat (substring (match-string 0) 1 -1) " |") nil t)
20302 (goto-char pos)
20303 ;; noalign: if there were two spaces at the end, this field
20304 ;; does not determine the width of the column.
20305 (when noalign (setq org-table-may-need-update c)))
20306 (delete-char N))
20307 (delete-char N)
20308 (org-fix-tags-on-the-fly))))
20310 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20311 (put 'org-self-insert-command 'delete-selection
20312 (lambda ()
20313 (not (run-hook-with-args-until-success
20314 'self-insert-uses-region-functions))))
20315 (put 'orgtbl-self-insert-command 'delete-selection
20316 (lambda ()
20317 (not (run-hook-with-args-until-success
20318 'self-insert-uses-region-functions))))
20319 (put 'org-delete-char 'delete-selection 'supersede)
20320 (put 'org-delete-backward-char 'delete-selection 'supersede)
20321 (put 'org-yank 'delete-selection 'yank)
20323 ;; Make `flyspell-mode' delay after some commands
20324 (put 'org-self-insert-command 'flyspell-delayed t)
20325 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20326 (put 'org-delete-char 'flyspell-delayed t)
20327 (put 'org-delete-backward-char 'flyspell-delayed t)
20329 ;; Make pabbrev-mode expand after org-mode commands
20330 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20331 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20333 (defun org-remap (map &rest commands)
20334 "In MAP, remap the functions given in COMMANDS.
20335 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20336 (let (new old)
20337 (while commands
20338 (setq old (pop commands) new (pop commands))
20339 (if (fboundp 'command-remapping)
20340 (org-defkey map (vector 'remap old) new)
20341 (substitute-key-definition old new map global-map)))))
20343 (defun org-transpose-words ()
20344 "Transpose words for Org.
20345 This uses the `org-mode-transpose-word-syntax-table' syntax
20346 table, which interprets characters in `org-emphasis-alist' as
20347 word constituents."
20348 (interactive)
20349 (with-syntax-table org-mode-transpose-word-syntax-table
20350 (call-interactively 'transpose-words)))
20351 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20353 (when (eq org-enable-table-editor 'optimized)
20354 ;; If the user wants maximum table support, we need to hijack
20355 ;; some standard editing functions
20356 (org-remap org-mode-map
20357 'self-insert-command 'org-self-insert-command
20358 'delete-char 'org-delete-char
20359 'delete-backward-char 'org-delete-backward-char)
20360 (org-defkey org-mode-map "|" 'org-force-self-insert))
20362 (defvar org-ctrl-c-ctrl-c-hook nil
20363 "Hook for functions attaching themselves to `C-c C-c'.
20365 This can be used to add additional functionality to the C-c C-c
20366 key which executes context-dependent commands. This hook is run
20367 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20368 run after the last test.
20370 Each function will be called with no arguments. The function
20371 must check if the context is appropriate for it to act. If yes,
20372 it should do its thing and then return a non-nil value. If the
20373 context is wrong, just do nothing and return nil.")
20375 (defvar org-ctrl-c-ctrl-c-final-hook nil
20376 "Hook for functions attaching themselves to `C-c C-c'.
20378 This can be used to add additional functionality to the C-c C-c
20379 key which executes context-dependent commands. This hook is run
20380 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20381 before the first test.
20383 Each function will be called with no arguments. The function
20384 must check if the context is appropriate for it to act. If yes,
20385 it should do its thing and then return a non-nil value. If the
20386 context is wrong, just do nothing and return nil.")
20388 (defvar org-tab-first-hook nil
20389 "Hook for functions to attach themselves to TAB.
20390 See `org-ctrl-c-ctrl-c-hook' for more information.
20391 This hook runs as the first action when TAB is pressed, even before
20392 `org-cycle' messes around with the `outline-regexp' to cater for
20393 inline tasks and plain list item folding.
20394 If any function in this hook returns t, any other actions that
20395 would have been caused by TAB (such as table field motion or visibility
20396 cycling) will not occur.")
20398 (defvar org-tab-after-check-for-table-hook nil
20399 "Hook for functions to attach themselves to TAB.
20400 See `org-ctrl-c-ctrl-c-hook' for more information.
20401 This hook runs after it has been established that the cursor is not in a
20402 table, but before checking if the cursor is in a headline or if global cycling
20403 should be done.
20404 If any function in this hook returns t, not other actions like visibility
20405 cycling will be done.")
20407 (defvar org-tab-after-check-for-cycling-hook nil
20408 "Hook for functions to attach themselves to TAB.
20409 See `org-ctrl-c-ctrl-c-hook' for more information.
20410 This hook runs after it has been established that not table field motion and
20411 not visibility should be done because of current context. This is probably
20412 the place where a package like yasnippets can hook in.")
20414 (defvar org-tab-before-tab-emulation-hook nil
20415 "Hook for functions to attach themselves to TAB.
20416 See `org-ctrl-c-ctrl-c-hook' for more information.
20417 This hook runs after every other options for TAB have been exhausted, but
20418 before indentation and \t insertion takes place.")
20420 (defvar org-metaleft-hook nil
20421 "Hook for functions attaching themselves to `M-left'.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.")
20423 (defvar org-metaright-hook nil
20424 "Hook for functions attaching themselves to `M-right'.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20426 (defvar org-metaup-hook nil
20427 "Hook for functions attaching themselves to `M-up'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-metadown-hook nil
20430 "Hook for functions attaching themselves to `M-down'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-shiftmetaleft-hook nil
20433 "Hook for functions attaching themselves to `M-S-left'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftmetaright-hook nil
20436 "Hook for functions attaching themselves to `M-S-right'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftmetaup-hook nil
20439 "Hook for functions attaching themselves to `M-S-up'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftmetadown-hook nil
20442 "Hook for functions attaching themselves to `M-S-down'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-metareturn-hook nil
20445 "Hook for functions attaching themselves to `M-RET'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftup-hook nil
20448 "Hook for functions attaching themselves to `S-up'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-shiftup-final-hook nil
20451 "Hook for functions attaching themselves to `S-up'.
20452 This one runs after all other options except shift-select have been excluded.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftdown-hook nil
20455 "Hook for functions attaching themselves to `S-down'.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-shiftdown-final-hook nil
20458 "Hook for functions attaching themselves to `S-down'.
20459 This one runs after all other options except shift-select have been excluded.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftleft-hook nil
20462 "Hook for functions attaching themselves to `S-left'.
20463 See `org-ctrl-c-ctrl-c-hook' for more information.")
20464 (defvar org-shiftleft-final-hook nil
20465 "Hook for functions attaching themselves to `S-left'.
20466 This one runs after all other options except shift-select have been excluded.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftright-hook nil
20469 "Hook for functions attaching themselves to `S-right'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-shiftright-final-hook nil
20472 "Hook for functions attaching themselves to `S-right'.
20473 This one runs after all other options except shift-select have been excluded.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20476 (defun org-modifier-cursor-error ()
20477 "Throw an error, a modified cursor command was applied in wrong context."
20478 (user-error "This command is active in special context like tables, headlines or items"))
20480 (defun org-shiftselect-error ()
20481 "Throw an error because Shift-Cursor command was applied in wrong context."
20482 (if (and (boundp 'shift-select-mode) shift-select-mode)
20483 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20484 (user-error "This command works only in special context like headlines or timestamps")))
20486 (defun org-call-for-shift-select (cmd)
20487 (let ((this-command-keys-shift-translated t))
20488 (call-interactively cmd)))
20490 (defun org-shifttab (&optional arg)
20491 "Global visibility cycling or move to previous table field.
20492 Call `org-table-previous-field' within a table.
20493 When ARG is nil, cycle globally through visibility states.
20494 When ARG is a numeric prefix, show contents of this level."
20495 (interactive "P")
20496 (cond
20497 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20498 ((integerp arg)
20499 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20500 (message "Content view to level: %d" arg)
20501 (org-content (prefix-numeric-value arg2))
20502 (org-cycle-show-empty-lines t)
20503 (setq org-cycle-global-status 'overview)))
20504 (t (call-interactively 'org-global-cycle))))
20506 (defun org-shiftmetaleft ()
20507 "Promote subtree or delete table column.
20508 Calls `org-promote-subtree', `org-outdent-item-tree', or
20509 `org-table-delete-column', depending on context. See the
20510 individual commands for more information."
20511 (interactive)
20512 (cond
20513 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20514 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20515 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20516 ((if (not (org-region-active-p)) (org-at-item-p)
20517 (save-excursion (goto-char (region-beginning))
20518 (org-at-item-p)))
20519 (call-interactively 'org-outdent-item-tree))
20520 (t (org-modifier-cursor-error))))
20522 (defun org-shiftmetaright ()
20523 "Demote subtree or insert table column.
20524 Calls `org-demote-subtree', `org-indent-item-tree', or
20525 `org-table-insert-column', depending on context. See the
20526 individual commands for more information."
20527 (interactive)
20528 (cond
20529 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20530 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20531 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20532 ((if (not (org-region-active-p)) (org-at-item-p)
20533 (save-excursion (goto-char (region-beginning))
20534 (org-at-item-p)))
20535 (call-interactively 'org-indent-item-tree))
20536 (t (org-modifier-cursor-error))))
20538 (defun org-shiftmetaup (&optional _arg)
20539 "Drag the line at point up.
20540 In a table, kill the current row.
20541 On a clock timestamp, update the value of the timestamp like `S-<up>'
20542 but also adjust the previous clocked item in the clock history.
20543 Everywhere else, drag the line at point up."
20544 (interactive "P")
20545 (cond
20546 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20547 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20548 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20549 (call-interactively 'org-timestamp-up)))
20550 (t (call-interactively 'org-drag-line-backward))))
20552 (defun org-shiftmetadown (&optional _arg)
20553 "Drag the line at point down.
20554 In a table, insert an empty row at the current line.
20555 On a clock timestamp, update the value of the timestamp like `S-<down>'
20556 but also adjust the previous clocked item in the clock history.
20557 Everywhere else, drag the line at point down."
20558 (interactive "P")
20559 (cond
20560 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20561 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20562 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20563 (call-interactively 'org-timestamp-down)))
20564 (t (call-interactively 'org-drag-line-forward))))
20566 (defsubst org-hidden-tree-error ()
20567 (user-error
20568 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20570 (defun org-metaleft (&optional _arg)
20571 "Promote heading, list item at point or move table column left.
20573 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20574 depending on context. With no specific context, calls the Emacs
20575 default `backward-word'. See the individual commands for more
20576 information.
20578 This function runs the hook `org-metaleft-hook' as a first step,
20579 and returns at first non-nil value."
20580 (interactive "P")
20581 (cond
20582 ((run-hook-with-args-until-success 'org-metaleft-hook))
20583 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20584 ((org-with-limited-levels
20585 (or (org-at-heading-p)
20586 (and (org-region-active-p)
20587 (save-excursion
20588 (goto-char (region-beginning))
20589 (org-at-heading-p)))))
20590 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20591 (call-interactively 'org-do-promote))
20592 ;; At an inline task.
20593 ((org-at-heading-p)
20594 (call-interactively 'org-inlinetask-promote))
20595 ((or (org-at-item-p)
20596 (and (org-region-active-p)
20597 (save-excursion
20598 (goto-char (region-beginning))
20599 (org-at-item-p))))
20600 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20601 (call-interactively 'org-outdent-item))
20602 (t (call-interactively 'backward-word))))
20604 (defun org-metaright (&optional _arg)
20605 "Demote heading, list item at point or move table column right.
20607 In front of a drawer or a block keyword, indent it correctly.
20609 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20610 `org-indnet-drawer' or `org-indent-block' depending on context.
20611 With no specific context, calls the Emacs default `forward-word'.
20612 See the individual commands for more information.
20614 This function runs the hook `org-metaright-hook' as a first step,
20615 and returns at first non-nil value."
20616 (interactive "P")
20617 (cond
20618 ((run-hook-with-args-until-success 'org-metaright-hook))
20619 ((org-at-table-p) (call-interactively 'org-table-move-column))
20620 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20621 ((org-at-block-p) (call-interactively 'org-indent-block))
20622 ((org-with-limited-levels
20623 (or (org-at-heading-p)
20624 (and (org-region-active-p)
20625 (save-excursion
20626 (goto-char (region-beginning))
20627 (org-at-heading-p)))))
20628 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20629 (call-interactively 'org-do-demote))
20630 ;; At an inline task.
20631 ((org-at-heading-p)
20632 (call-interactively 'org-inlinetask-demote))
20633 ((or (org-at-item-p)
20634 (and (org-region-active-p)
20635 (save-excursion
20636 (goto-char (region-beginning))
20637 (org-at-item-p))))
20638 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20639 (call-interactively 'org-indent-item))
20640 (t (call-interactively 'forward-word))))
20642 (defun org-check-for-hidden (what)
20643 "Check if there are hidden headlines/items in the current visual line.
20644 WHAT can be either `headlines' or `items'. If the current line is
20645 an outline or item heading and it has a folded subtree below it,
20646 this function returns t, nil otherwise."
20647 (let ((re (cond
20648 ((eq what 'headlines) org-outline-regexp-bol)
20649 ((eq what 'items) (org-item-beginning-re))
20650 (t (error "This should not happen"))))
20651 beg end)
20652 (save-excursion
20653 (catch 'exit
20654 (unless (org-region-active-p)
20655 (setq beg (point-at-bol))
20656 (beginning-of-line 2)
20657 (while (and (not (eobp)) ;; this is like `next-line'
20658 (get-char-property (1- (point)) 'invisible))
20659 (beginning-of-line 2))
20660 (setq end (point))
20661 (goto-char beg)
20662 (goto-char (point-at-eol))
20663 (setq end (max end (point)))
20664 (while (re-search-forward re end t)
20665 (when (get-char-property (match-beginning 0) 'invisible)
20666 (throw 'exit t))))
20667 nil))))
20669 (defun org-metaup (&optional _arg)
20670 "Move subtree up or move table row up.
20671 Calls `org-move-subtree-up' or `org-table-move-row' or
20672 `org-move-item-up', depending on context. See the individual commands
20673 for more information."
20674 (interactive "P")
20675 (cond
20676 ((run-hook-with-args-until-success 'org-metaup-hook))
20677 ((org-region-active-p)
20678 (let* ((a (min (region-beginning) (region-end)))
20679 (b (1- (max (region-beginning) (region-end))))
20680 (c (save-excursion (goto-char a)
20681 (move-beginning-of-line 0)))
20682 (d (save-excursion (goto-char a)
20683 (move-end-of-line 0) (point))))
20684 (transpose-regions a b c d)
20685 (goto-char c)))
20686 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20687 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20688 ((org-at-item-p) (call-interactively 'org-move-item-up))
20689 (t (org-drag-element-backward))))
20691 (defun org-metadown (&optional _arg)
20692 "Move subtree down or move table row down.
20693 Calls `org-move-subtree-down' or `org-table-move-row' or
20694 `org-move-item-down', depending on context. See the individual
20695 commands for more information."
20696 (interactive "P")
20697 (cond
20698 ((run-hook-with-args-until-success 'org-metadown-hook))
20699 ((org-region-active-p)
20700 (let* ((a (min (region-beginning) (region-end)))
20701 (b (max (region-beginning) (region-end)))
20702 (c (save-excursion (goto-char b)
20703 (move-beginning-of-line 1)))
20704 (d (save-excursion (goto-char b)
20705 (move-end-of-line 1) (1+ (point)))))
20706 (transpose-regions a b c d)
20707 (goto-char d)))
20708 ((org-at-table-p) (call-interactively 'org-table-move-row))
20709 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20710 ((org-at-item-p) (call-interactively 'org-move-item-down))
20711 (t (org-drag-element-forward))))
20713 (defun org-shiftup (&optional arg)
20714 "Increase item in timestamp or increase priority of current headline.
20715 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20716 depending on context. See the individual commands for more information."
20717 (interactive "P")
20718 (cond
20719 ((run-hook-with-args-until-success 'org-shiftup-hook))
20720 ((and org-support-shift-select (org-region-active-p))
20721 (org-call-for-shift-select 'previous-line))
20722 ((org-at-timestamp-p t)
20723 (call-interactively (if org-edit-timestamp-down-means-later
20724 'org-timestamp-down 'org-timestamp-up)))
20725 ((and (not (eq org-support-shift-select 'always))
20726 org-enable-priority-commands
20727 (org-at-heading-p))
20728 (call-interactively 'org-priority-up))
20729 ((and (not org-support-shift-select) (org-at-item-p))
20730 (call-interactively 'org-previous-item))
20731 ((org-clocktable-try-shift 'up arg))
20732 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20733 (org-support-shift-select
20734 (org-call-for-shift-select 'previous-line))
20735 (t (org-shiftselect-error))))
20737 (defun org-shiftdown (&optional arg)
20738 "Decrease item in timestamp or decrease priority of current headline.
20739 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20740 depending on context. See the individual commands for more information."
20741 (interactive "P")
20742 (cond
20743 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20744 ((and org-support-shift-select (org-region-active-p))
20745 (org-call-for-shift-select 'next-line))
20746 ((org-at-timestamp-p t)
20747 (call-interactively (if org-edit-timestamp-down-means-later
20748 'org-timestamp-up 'org-timestamp-down)))
20749 ((and (not (eq org-support-shift-select 'always))
20750 org-enable-priority-commands
20751 (org-at-heading-p))
20752 (call-interactively 'org-priority-down))
20753 ((and (not org-support-shift-select) (org-at-item-p))
20754 (call-interactively 'org-next-item))
20755 ((org-clocktable-try-shift 'down arg))
20756 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20757 (org-support-shift-select
20758 (org-call-for-shift-select 'next-line))
20759 (t (org-shiftselect-error))))
20761 (defun org-shiftright (&optional arg)
20762 "Cycle the thing at point or in the current line, depending on context.
20763 Depending on context, this does one of the following:
20765 - switch a timestamp at point one day into the future
20766 - on a headline, switch to the next TODO keyword.
20767 - on an item, switch entire list to the next bullet type
20768 - on a property line, switch to the next allowed value
20769 - on a clocktable definition line, move time block into the future"
20770 (interactive "P")
20771 (cond
20772 ((run-hook-with-args-until-success 'org-shiftright-hook))
20773 ((and org-support-shift-select (org-region-active-p))
20774 (org-call-for-shift-select 'forward-char))
20775 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20776 ((and (not (eq org-support-shift-select 'always))
20777 (org-at-heading-p))
20778 (let ((org-inhibit-logging
20779 (not org-treat-S-cursor-todo-selection-as-state-change))
20780 (org-inhibit-blocking
20781 (not org-treat-S-cursor-todo-selection-as-state-change)))
20782 (org-call-with-arg 'org-todo 'right)))
20783 ((or (and org-support-shift-select
20784 (not (eq org-support-shift-select 'always))
20785 (org-at-item-bullet-p))
20786 (and (not org-support-shift-select) (org-at-item-p)))
20787 (org-call-with-arg 'org-cycle-list-bullet nil))
20788 ((and (not (eq org-support-shift-select 'always))
20789 (org-at-property-p))
20790 (call-interactively 'org-property-next-allowed-value))
20791 ((org-clocktable-try-shift 'right arg))
20792 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20793 (org-support-shift-select
20794 (org-call-for-shift-select 'forward-char))
20795 (t (org-shiftselect-error))))
20797 (defun org-shiftleft (&optional arg)
20798 "Cycle the thing at point or in the current line, depending on context.
20799 Depending on context, this does one of the following:
20801 - switch a timestamp at point one day into the past
20802 - on a headline, switch to the previous TODO keyword.
20803 - on an item, switch entire list to the previous bullet type
20804 - on a property line, switch to the previous allowed value
20805 - on a clocktable definition line, move time block into the past"
20806 (interactive "P")
20807 (cond
20808 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20809 ((and org-support-shift-select (org-region-active-p))
20810 (org-call-for-shift-select 'backward-char))
20811 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20812 ((and (not (eq org-support-shift-select 'always))
20813 (org-at-heading-p))
20814 (let ((org-inhibit-logging
20815 (not org-treat-S-cursor-todo-selection-as-state-change))
20816 (org-inhibit-blocking
20817 (not org-treat-S-cursor-todo-selection-as-state-change)))
20818 (org-call-with-arg 'org-todo 'left)))
20819 ((or (and org-support-shift-select
20820 (not (eq org-support-shift-select 'always))
20821 (org-at-item-bullet-p))
20822 (and (not org-support-shift-select) (org-at-item-p)))
20823 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20824 ((and (not (eq org-support-shift-select 'always))
20825 (org-at-property-p))
20826 (call-interactively 'org-property-previous-allowed-value))
20827 ((org-clocktable-try-shift 'left arg))
20828 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20829 (org-support-shift-select
20830 (org-call-for-shift-select 'backward-char))
20831 (t (org-shiftselect-error))))
20833 (defun org-shiftcontrolright ()
20834 "Switch to next TODO set."
20835 (interactive)
20836 (cond
20837 ((and org-support-shift-select (org-region-active-p))
20838 (org-call-for-shift-select 'forward-word))
20839 ((and (not (eq org-support-shift-select 'always))
20840 (org-at-heading-p))
20841 (org-call-with-arg 'org-todo 'nextset))
20842 (org-support-shift-select
20843 (org-call-for-shift-select 'forward-word))
20844 (t (org-shiftselect-error))))
20846 (defun org-shiftcontrolleft ()
20847 "Switch to previous TODO set."
20848 (interactive)
20849 (cond
20850 ((and org-support-shift-select (org-region-active-p))
20851 (org-call-for-shift-select 'backward-word))
20852 ((and (not (eq org-support-shift-select 'always))
20853 (org-at-heading-p))
20854 (org-call-with-arg 'org-todo 'previousset))
20855 (org-support-shift-select
20856 (org-call-for-shift-select 'backward-word))
20857 (t (org-shiftselect-error))))
20859 (defun org-shiftcontrolup (&optional n)
20860 "Change timestamps synchronously up in CLOCK log lines.
20861 Optional argument N tells to change by that many units."
20862 (interactive "P")
20863 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20864 (let (org-support-shift-select)
20865 (org-clock-timestamps-up n))
20866 (user-error "Not at a clock log")))
20868 (defun org-shiftcontroldown (&optional n)
20869 "Change timestamps synchronously down in CLOCK log lines.
20870 Optional argument N tells to change by that many units."
20871 (interactive "P")
20872 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20873 (let (org-support-shift-select)
20874 (org-clock-timestamps-down n))
20875 (user-error "Not at a clock log")))
20877 (defun org-increase-number-at-point (&optional inc)
20878 "Increment the number at point.
20879 With an optional prefix numeric argument INC, increment using
20880 this numeric value."
20881 (interactive "p")
20882 (if (not (number-at-point))
20883 (user-error "Not on a number")
20884 (unless inc (setq inc 1))
20885 (let ((pos (point))
20886 (beg (skip-chars-backward "-+^/*0-9eE."))
20887 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20888 (setq nap (buffer-substring-no-properties
20889 (+ pos beg) (+ pos beg end)))
20890 (delete-region (+ pos beg) (+ pos beg end))
20891 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20892 (when (org-at-table-p)
20893 (org-table-align)
20894 (org-table-end-of-field 1))))
20896 (defun org-decrease-number-at-point (&optional inc)
20897 "Decrement the number at point.
20898 With an optional prefix numeric argument INC, decrement using
20899 this numeric value."
20900 (interactive "p")
20901 (org-increase-number-at-point (- (or inc 1))))
20903 (defun org-ctrl-c-ret ()
20904 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20905 (interactive)
20906 (cond
20907 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20908 (t (call-interactively 'org-insert-heading))))
20910 (defun org-find-visible ()
20911 (let ((s (point)))
20912 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20913 (get-char-property s 'invisible)))
20915 (defun org-find-invisible ()
20916 (let ((s (point)))
20917 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20918 (not (get-char-property s 'invisible))))
20921 (defun org-copy-visible (beg end)
20922 "Copy the visible parts of the region."
20923 (interactive "r")
20924 (let (snippets s)
20925 (save-excursion
20926 (save-restriction
20927 (narrow-to-region beg end)
20928 (setq s (goto-char (point-min)))
20929 (while (not (= (point) (point-max)))
20930 (goto-char (org-find-invisible))
20931 (push (buffer-substring s (point)) snippets)
20932 (setq s (goto-char (org-find-visible))))))
20933 (kill-new (apply 'concat (nreverse snippets)))))
20935 (defun org-copy-special ()
20936 "Copy region in table or copy current subtree.
20937 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20938 See the individual commands for more information."
20939 (interactive)
20940 (call-interactively
20941 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20943 (defun org-cut-special ()
20944 "Cut region in table or cut current subtree.
20945 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20946 See the individual commands for more information."
20947 (interactive)
20948 (call-interactively
20949 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20951 (defun org-paste-special (arg)
20952 "Paste rectangular region into table, or past subtree relative to level.
20953 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20954 See the individual commands for more information."
20955 (interactive "P")
20956 (if (org-at-table-p)
20957 (org-table-paste-rectangle)
20958 (org-paste-subtree arg)))
20960 (defsubst org-in-fixed-width-region-p ()
20961 "Is point in a fixed-width region?"
20962 (save-match-data
20963 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20965 (defun org-edit-special (&optional arg)
20966 "Call a special editor for the element at point.
20967 When at a table, call the formula editor with `org-table-edit-formulas'.
20968 When in a source code block, call `org-edit-src-code'.
20969 When in a fixed-width region, call `org-edit-fixed-width-region'.
20970 When in an export block, call `org-edit-export-block'.
20971 When at an #+INCLUDE keyword, visit the included file.
20972 When at a footnote reference, call `org-edit-footnote-reference'
20973 On a link, call `ffap' to visit the link at point.
20974 Otherwise, return a user error."
20975 (interactive "P")
20976 (let ((element (org-element-at-point)))
20977 (cl-assert (not buffer-read-only) nil
20978 "Buffer is read-only: %s" (buffer-name))
20979 (pcase (org-element-type element)
20980 (`src-block
20981 (if (not arg) (org-edit-src-code)
20982 (let* ((info (org-babel-get-src-block-info))
20983 (lang (nth 0 info))
20984 (params (nth 2 info))
20985 (session (cdr (assq :session params))))
20986 (if (not session) (org-edit-src-code)
20987 ;; At a src-block with a session and function called with
20988 ;; an ARG: switch to the buffer related to the inferior
20989 ;; process.
20990 (switch-to-buffer
20991 (funcall (intern (concat "org-babel-prep-session:" lang))
20992 session params))))))
20993 (`keyword
20994 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20995 (org-open-link-from-string
20996 (format "[[%s]]"
20997 (expand-file-name
20998 (let ((value (org-element-property :value element)))
20999 (cond ((not (org-string-nw-p value))
21000 (user-error "No file to edit"))
21001 ((string-match "\\`\"\\(.*?\\)\"" value)
21002 (match-string 1 value))
21003 ((string-match "\\`[^ \t\"]\\S-*" value)
21004 (match-string 0 value))
21005 (t (user-error "No valid file specified")))))))
21006 (user-error "No special environment to edit here")))
21007 (`table
21008 (if (eq (org-element-property :type element) 'table.el)
21009 (org-edit-table.el)
21010 (call-interactively 'org-table-edit-formulas)))
21011 ;; Only Org tables contain `table-row' type elements.
21012 (`table-row (call-interactively 'org-table-edit-formulas))
21013 (`example-block (org-edit-src-code))
21014 (`export-block (org-edit-export-block))
21015 (`fixed-width (org-edit-fixed-width-region))
21017 ;; No notable element at point. Though, we may be at a link or
21018 ;; a footnote reference, which are objects. Thus, scan deeper.
21019 (let ((context (org-element-context element)))
21020 (pcase (org-element-type context)
21021 (`footnote-reference (org-edit-footnote-reference))
21022 (`inline-src-block (org-edit-inline-src-code))
21023 (`link (call-interactively #'ffap))
21024 (_ (user-error "No special environment to edit here"))))))))
21026 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21027 (defun org-ctrl-c-ctrl-c (&optional arg)
21028 "Set tags in headline, or update according to changed information at point.
21030 This command does many different things, depending on context:
21032 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21033 this is what we do.
21035 - If the cursor is on a statistics cookie, update it.
21037 - If the cursor is in a headline, prompt for tags and insert them
21038 into the current line, aligned to `org-tags-column'. When called
21039 with prefix arg, realign all tags in the current buffer.
21041 - If the cursor is in one of the special #+KEYWORD lines, this
21042 triggers scanning the buffer for these lines and updating the
21043 information.
21045 - If the cursor is inside a table, realign the table. This command
21046 works even if the automatic table editor has been turned off.
21048 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21049 the entire table.
21051 - If the cursor is at a footnote reference or definition, jump to
21052 the corresponding definition or references, respectively.
21054 - If the cursor is a the beginning of a dynamic block, update it.
21056 - If the current buffer is a capture buffer, close note and file it.
21058 - If the cursor is on a <<<target>>>, update radio targets and
21059 corresponding links in this buffer.
21061 - If the cursor is on a numbered item in a plain list, renumber the
21062 ordered list.
21064 - If the cursor is on a checkbox, toggle it.
21066 - If the cursor is on a code block, evaluate it. The variable
21067 `org-confirm-babel-evaluate' can be used to control prompting
21068 before code block evaluation, by default every code block
21069 evaluation requires confirmation. Code block evaluation can be
21070 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21071 (interactive "P")
21072 (cond
21073 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21074 org-occur-highlights)
21075 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21076 (org-remove-occur-highlights)
21077 (message "Temporary highlights/overlays removed from current buffer"))
21078 ((and (local-variable-p 'org-finish-function (current-buffer))
21079 (fboundp org-finish-function))
21080 (funcall org-finish-function))
21081 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21083 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21084 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21085 (user-error "C-c C-c can do nothing useful at this location"))
21086 (let* ((context (org-element-context))
21087 (type (org-element-type context)))
21088 (cl-case type
21089 ;; When at a link, act according to the parent instead.
21090 (link (setq context (org-element-property :parent context))
21091 (setq type (org-element-type context)))
21092 ;; Unsupported object types: refer to the first supported
21093 ;; element or object containing it.
21094 ((bold code entity export-snippet inline-babel-call inline-src-block
21095 italic latex-fragment line-break macro strike-through subscript
21096 superscript underline verbatim)
21097 (setq context
21098 (org-element-lineage
21099 context '(radio-target paragraph verse-block table-cell)))))
21100 ;; For convenience: at the first line of a paragraph on the
21101 ;; same line as an item, apply function on that item instead.
21102 (when (eq type 'paragraph)
21103 (let ((parent (org-element-property :parent context)))
21104 (when (and (eq (org-element-type parent) 'item)
21105 (= (line-beginning-position)
21106 (org-element-property :begin parent)))
21107 (setq context parent type 'item))))
21108 ;; Act according to type of element or object at point.
21109 (cl-case type
21110 (clock (org-clock-update-time-maybe))
21111 (dynamic-block
21112 (save-excursion
21113 (goto-char (org-element-property :post-affiliated context))
21114 (org-update-dblock)))
21115 (footnote-definition
21116 (goto-char (org-element-property :post-affiliated context))
21117 (call-interactively 'org-footnote-action))
21118 (footnote-reference (call-interactively 'org-footnote-action))
21119 ((headline inlinetask)
21120 (save-excursion (goto-char (org-element-property :begin context))
21121 (call-interactively 'org-set-tags)))
21122 (item
21123 ;; At an item: a double C-u set checkbox to "[-]"
21124 ;; unconditionally, whereas a single one will toggle its
21125 ;; presence. Without a universal argument, if the item
21126 ;; has a checkbox, toggle it. Otherwise repair the list.
21127 (let* ((box (org-element-property :checkbox context))
21128 (struct (org-element-property :structure context))
21129 (old-struct (copy-tree struct))
21130 (parents (org-list-parents-alist struct))
21131 (prevs (org-list-prevs-alist struct))
21132 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21133 (org-list-set-checkbox
21134 (org-element-property :begin context) struct
21135 (cond ((equal arg '(16)) "[-]")
21136 ((and (not box) (equal arg '(4))) "[ ]")
21137 ((or (not box) (equal arg '(4))) nil)
21138 ((eq box 'on) "[ ]")
21139 (t "[X]")))
21140 ;; Mimic `org-list-write-struct' but with grabbing
21141 ;; a return value from `org-list-struct-fix-box'.
21142 (org-list-struct-fix-ind struct parents 2)
21143 (org-list-struct-fix-item-end struct)
21144 (org-list-struct-fix-bul struct prevs)
21145 (org-list-struct-fix-ind struct parents)
21146 (let ((block-item
21147 (org-list-struct-fix-box struct parents prevs orderedp)))
21148 (if (and box (equal struct old-struct))
21149 (if (equal arg '(16))
21150 (message "Checkboxes already reset")
21151 (user-error "Cannot toggle this checkbox: %s"
21152 (if (eq box 'on)
21153 "all subitems checked"
21154 "unchecked subitems")))
21155 (org-list-struct-apply-struct struct old-struct)
21156 (org-update-checkbox-count-maybe))
21157 (when block-item
21158 (message "Checkboxes were removed due to empty box at line %d"
21159 (org-current-line block-item))))))
21160 (keyword
21161 (let ((org-inhibit-startup-visibility-stuff t)
21162 (org-startup-align-all-tables nil))
21163 (when (boundp 'org-table-coordinate-overlays)
21164 (mapc #'delete-overlay org-table-coordinate-overlays)
21165 (setq org-table-coordinate-overlays nil))
21166 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21167 (message "Local setup has been refreshed"))
21168 (plain-list
21169 ;; At a plain list, with a double C-u argument, set
21170 ;; checkboxes of each item to "[-]", whereas a single one
21171 ;; will toggle their presence according to the state of the
21172 ;; first item in the list. Without an argument, repair the
21173 ;; list.
21174 (let* ((begin (org-element-property :contents-begin context))
21175 (beginm (move-marker (make-marker) begin))
21176 (struct (org-element-property :structure context))
21177 (old-struct (copy-tree struct))
21178 (first-box (save-excursion
21179 (goto-char begin)
21180 (looking-at org-list-full-item-re)
21181 (match-string-no-properties 3)))
21182 (new-box (cond ((equal arg '(16)) "[-]")
21183 ((equal arg '(4)) (unless first-box "[ ]"))
21184 ((equal first-box "[X]") "[ ]")
21185 (t "[X]"))))
21186 (cond
21187 (arg
21188 (dolist (pos
21189 (org-list-get-all-items
21190 begin struct (org-list-prevs-alist struct)))
21191 (org-list-set-checkbox pos struct new-box)))
21192 ((and first-box (eq (point) begin))
21193 ;; For convenience, when point is at bol on the first
21194 ;; item of the list and no argument is provided, simply
21195 ;; toggle checkbox of that item, if any.
21196 (org-list-set-checkbox begin struct new-box)))
21197 (org-list-write-struct
21198 struct (org-list-parents-alist struct) old-struct)
21199 (org-update-checkbox-count-maybe)
21200 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21201 ((property-drawer node-property)
21202 (call-interactively 'org-property-action))
21203 ((radio-target target)
21204 (call-interactively 'org-update-radio-target-regexp))
21205 (statistics-cookie
21206 (call-interactively 'org-update-statistics-cookies))
21207 ((table table-cell table-row)
21208 ;; At a table, recalculate every field and align it. Also
21209 ;; send the table if necessary. If the table has
21210 ;; a `table.el' type, just give up. At a table row or
21211 ;; cell, maybe recalculate line but always align table.
21212 (if (eq (org-element-property :type context) 'table.el)
21213 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21214 Use \\[org-edit-special] to edit table.el tables"))
21215 (let ((org-enable-table-editor t))
21216 (if (or (eq type 'table)
21217 ;; Check if point is at a TBLFM line.
21218 (and (eq type 'table-row)
21219 (= (point) (org-element-property :end context))))
21220 (save-excursion
21221 (if (org-at-TBLFM-p)
21222 (progn (require 'org-table)
21223 (org-table-calc-current-TBLFM))
21224 (goto-char (org-element-property :contents-begin context))
21225 (org-call-with-arg 'org-table-recalculate (or arg t))
21226 (orgtbl-send-table 'maybe)))
21227 (org-table-maybe-eval-formula)
21228 (cond (arg (call-interactively 'org-table-recalculate))
21229 ((org-table-maybe-recalculate-line))
21230 (t (org-table-align)))))))
21231 (timestamp (org-timestamp-change 0 'day))
21232 (otherwise
21233 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21234 (user-error
21235 "C-c C-c can do nothing useful at this location")))))))))
21237 (defun org-mode-restart ()
21238 (interactive)
21239 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21240 (funcall major-mode)
21241 (hack-local-variables)
21242 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21243 (org-indent-mode -1)))
21244 (message "%s restarted" major-mode))
21246 (defun org-kill-note-or-show-branches ()
21247 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21248 (interactive)
21249 (if (not org-finish-function)
21250 (progn
21251 (outline-hide-subtree)
21252 (call-interactively 'outline-show-branches))
21253 (let ((org-note-abort t))
21254 (funcall org-finish-function))))
21256 (defun org-delete-indentation (&optional ARG)
21257 "Join current line to previous and fix whitespace at join.
21259 If previous line is a headline add to headline title. Otherwise
21260 the function calls `delete-indentation'.
21262 With argument, join this line to following line."
21263 (interactive "*P")
21264 (if (save-excursion
21265 (if ARG (beginning-of-line)
21266 (forward-line -1))
21267 (looking-at org-complex-heading-regexp))
21268 ;; At headline.
21269 (let ((tags-column (when (match-beginning 5)
21270 (save-excursion (goto-char (match-beginning 5))
21271 (current-column))))
21272 (string (concat " " (progn (when ARG (forward-line 1))
21273 (org-trim (delete-and-extract-region
21274 (line-beginning-position)
21275 (line-end-position)))))))
21276 (unless (bobp) (delete-region (point) (1- (point))))
21277 (goto-char (or (match-end 4)
21278 (match-beginning 5)
21279 (match-end 0)))
21280 (skip-chars-backward " \t")
21281 (save-excursion (insert string))
21282 ;; Adjust alignment of tags.
21283 (when tags-column
21284 (org-align-tags-here (if org-auto-align-tags
21285 org-tags-column
21286 tags-column))))
21287 (delete-indentation ARG)))
21289 (defun org-open-line (n)
21290 "Insert a new row in tables, call `open-line' elsewhere.
21291 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21292 (interactive "*p")
21293 (cond
21294 ((not org-special-ctrl-o)
21295 (open-line n))
21296 ((org-at-table-p)
21297 (org-table-insert-row))
21299 (open-line n))))
21301 (defun org-return (&optional indent)
21302 "Goto next table row or insert a newline.
21304 Calls `org-table-next-row' or `newline', depending on context.
21306 When optional INDENT argument is non-nil, call
21307 `newline-and-indent' instead of `newline'.
21309 When `org-return-follows-link' is non-nil and point is on
21310 a timestamp or a link, call `org-open-at-point'. However, it
21311 will not happen if point is in a table or on a \"dead\"
21312 object (e.g., within a comment). In these case, you need to use
21313 `org-open-at-point' directly."
21314 (interactive)
21315 (let ((context (if org-return-follows-link (org-element-context)
21316 (org-element-at-point))))
21317 (cond
21318 ;; In a table, call `org-table-next-row'.
21319 ((or (and (eq (org-element-type context) 'table)
21320 (>= (point) (org-element-property :contents-begin context))
21321 (< (point) (org-element-property :contents-end context)))
21322 (org-element-lineage context '(table-row table-cell) t))
21323 (org-table-justify-field-maybe)
21324 (call-interactively #'org-table-next-row))
21325 ;; On a link or a timestamp, call `org-open-at-point' if
21326 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21327 ;; locations, e.g., in a comment, as `org-open-at-point'.
21328 ((and org-return-follows-link
21329 (or (org-in-regexp org-ts-regexp-both nil t)
21330 (org-in-regexp org-tsr-regexp-both nil t)
21331 (org-in-regexp org-any-link-re nil t)))
21332 (call-interactively #'org-open-at-point))
21333 ;; Insert newline in heading, but preserve tags.
21334 ((and (not (bolp))
21335 (save-excursion (beginning-of-line)
21336 (looking-at org-complex-heading-regexp)))
21337 ;; At headline. Split line. However, if point is on keyword,
21338 ;; priority cookie or tags, do not break any of them: add
21339 ;; a newline after the headline instead.
21340 (let ((tags-column (and (match-beginning 5)
21341 (save-excursion (goto-char (match-beginning 5))
21342 (current-column))))
21343 (string
21344 (when (and (match-end 4)
21345 (>= (point)
21346 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21347 (<= (point) (match-end 4)))
21348 (delete-and-extract-region (point) (match-end 4)))))
21349 (when (and tags-column string) ; Adjust tag alignment.
21350 (org-align-tags-here
21351 (if org-auto-align-tags org-tags-column tags-column)))
21352 (end-of-line)
21353 (org-show-entry)
21354 (if indent (newline-and-indent) (newline))
21355 (when string (save-excursion (insert (org-trim string))))))
21356 ;; In a list, make sure indenting keeps trailing text within.
21357 ((and indent
21358 (not (eolp))
21359 (org-element-lineage context '(item)))
21360 (let ((trailing-data
21361 (delete-and-extract-region (point) (line-end-position))))
21362 (newline-and-indent)
21363 (save-excursion (insert trailing-data))))
21364 (t (if indent (newline-and-indent) (newline))))))
21366 (defun org-return-indent ()
21367 "Goto next table row or insert a newline and indent.
21368 Calls `org-table-next-row' or `newline-and-indent', depending on
21369 context. See the individual commands for more information."
21370 (interactive)
21371 (org-return t))
21373 (defun org-ctrl-c-star ()
21374 "Compute table, or change heading status of lines.
21375 Calls `org-table-recalculate' or `org-toggle-heading',
21376 depending on context."
21377 (interactive)
21378 (cond
21379 ((org-at-table-p)
21380 (call-interactively 'org-table-recalculate))
21382 ;; Convert all lines in region to list items
21383 (call-interactively 'org-toggle-heading))))
21385 (defun org-ctrl-c-minus ()
21386 "Insert separator line in table or modify bullet status of line.
21387 Also turns a plain line or a region of lines into list items.
21388 Calls `org-table-insert-hline', `org-toggle-item', or
21389 `org-cycle-list-bullet', depending on context."
21390 (interactive)
21391 (cond
21392 ((org-at-table-p)
21393 (call-interactively 'org-table-insert-hline))
21394 ((org-region-active-p)
21395 (call-interactively 'org-toggle-item))
21396 ((org-in-item-p)
21397 (call-interactively 'org-cycle-list-bullet))
21399 (call-interactively 'org-toggle-item))))
21401 (defun org-toggle-item (arg)
21402 "Convert headings or normal lines to items, items to normal lines.
21403 If there is no active region, only the current line is considered.
21405 If the first non blank line in the region is a headline, convert
21406 all headlines to items, shifting text accordingly.
21408 If it is an item, convert all items to normal lines.
21410 If it is normal text, change region into a list of items.
21411 With a prefix argument ARG, change the region in a single item."
21412 (interactive "P")
21413 (let ((shift-text
21414 (function
21415 ;; Shift text in current section to IND, from point to END.
21416 ;; The function leaves point to END line.
21417 (lambda (ind end)
21418 (let ((min-i 1000) (end (copy-marker end)))
21419 ;; First determine the minimum indentation (MIN-I) of
21420 ;; the text.
21421 (save-excursion
21422 (catch 'exit
21423 (while (< (point) end)
21424 (let ((i (org-get-indentation)))
21425 (cond
21426 ;; Skip blank lines and inline tasks.
21427 ((looking-at "^[ \t]*$"))
21428 ((looking-at org-outline-regexp-bol))
21429 ;; We can't find less than 0 indentation.
21430 ((zerop i) (throw 'exit (setq min-i 0)))
21431 ((< i min-i) (setq min-i i))))
21432 (forward-line))))
21433 ;; Then indent each line so that a line indented to
21434 ;; MIN-I becomes indented to IND. Ignore blank lines
21435 ;; and inline tasks in the process.
21436 (let ((delta (- ind min-i)))
21437 (while (< (point) end)
21438 (unless (or (looking-at "^[ \t]*$")
21439 (looking-at org-outline-regexp-bol))
21440 (org-indent-line-to (+ (org-get-indentation) delta)))
21441 (forward-line)))))))
21442 (skip-blanks
21443 (function
21444 ;; Return beginning of first non-blank line, starting from
21445 ;; line at POS.
21446 (lambda (pos)
21447 (save-excursion
21448 (goto-char pos)
21449 (skip-chars-forward " \r\t\n")
21450 (point-at-bol)))))
21451 beg end)
21452 ;; Determine boundaries of changes.
21453 (if (org-region-active-p)
21454 (setq beg (funcall skip-blanks (region-beginning))
21455 end (copy-marker (region-end)))
21456 (setq beg (funcall skip-blanks (point-at-bol))
21457 end (copy-marker (point-at-eol))))
21458 ;; Depending on the starting line, choose an action on the text
21459 ;; between BEG and END.
21460 (org-with-limited-levels
21461 (save-excursion
21462 (goto-char beg)
21463 (cond
21464 ;; Case 1. Start at an item: de-itemize. Note that it only
21465 ;; happens when a region is active: `org-ctrl-c-minus'
21466 ;; would call `org-cycle-list-bullet' otherwise.
21467 ((org-at-item-p)
21468 (while (< (point) end)
21469 (when (org-at-item-p)
21470 (skip-chars-forward " \t")
21471 (delete-region (point) (match-end 0)))
21472 (forward-line)))
21473 ;; Case 2. Start at an heading: convert to items.
21474 ((org-at-heading-p)
21475 (let* ((bul (org-list-bullet-string "-"))
21476 (bul-len (length bul))
21477 (done (org-entry-is-done-p))
21478 (todo (org-entry-is-todo-p))
21479 ;; Indentation of the first heading. It should be
21480 ;; relative to the indentation of its parent, if any.
21481 (start-ind (save-excursion
21482 (cond
21483 ((not org-adapt-indentation) 0)
21484 ((not (outline-previous-heading)) 0)
21485 (t (length (match-string 0))))))
21486 ;; Level of first heading. Further headings will be
21487 ;; compared to it to determine hierarchy in the list.
21488 (ref-level (org-reduced-level (org-outline-level))))
21489 (when (or done todo) (org-todo ""))
21490 (while (< (point) end)
21491 (let* ((level (org-reduced-level (org-outline-level)))
21492 (delta (max 0 (- level ref-level))))
21493 ;; If current headline is less indented than the first
21494 ;; one, set it as reference, in order to preserve
21495 ;; subtrees.
21496 (when (< level ref-level) (setq ref-level level))
21497 (replace-match bul t t)
21498 (org-indent-line-to (+ start-ind (* delta bul-len)))
21499 (when (or done todo)
21500 (let* ((struct (org-list-struct))
21501 (old (copy-tree struct)))
21502 (org-list-set-checkbox (line-beginning-position)
21503 struct
21504 (if done "[X]" "[ ]"))
21505 (org-list-write-struct struct
21506 (org-list-parents-alist struct)
21507 old)))
21508 ;; Ensure all text down to END (or SECTION-END) belongs
21509 ;; to the newly created item.
21510 (let ((section-end (save-excursion
21511 (or (outline-next-heading) (point)))))
21512 (forward-line)
21513 (funcall shift-text
21514 (+ start-ind (* (1+ delta) bul-len))
21515 (min end section-end)))))))
21516 ;; Case 3. Normal line with ARG: make the first line of region
21517 ;; an item, and shift indentation of others lines to
21518 ;; set them as item's body.
21519 (arg (let* ((bul (org-list-bullet-string "-"))
21520 (bul-len (length bul))
21521 (ref-ind (org-get-indentation)))
21522 (skip-chars-forward " \t")
21523 (insert bul)
21524 (forward-line)
21525 (while (< (point) end)
21526 ;; Ensure that lines less indented than first one
21527 ;; still get included in item body.
21528 (funcall shift-text
21529 (+ ref-ind bul-len)
21530 (min end (save-excursion (or (outline-next-heading)
21531 (point)))))
21532 (forward-line))))
21533 ;; Case 4. Normal line without ARG: turn each non-item line
21534 ;; into an item.
21536 (while (< (point) end)
21537 (unless (or (org-at-heading-p) (org-at-item-p))
21538 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21539 (replace-match
21540 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21541 (forward-line))))))))
21543 (defun org-toggle-heading (&optional nstars)
21544 "Convert headings to normal text, or items or text to headings.
21545 If there is no active region, only convert the current line.
21547 With a \\[universal-argument] prefix, convert the whole list at
21548 point into heading.
21550 In a region:
21552 - If the first non blank line is a headline, remove the stars
21553 from all headlines in the region.
21555 - If it is a normal line, turn each and every normal line (i.e.,
21556 not an heading or an item) in the region into headings. If you
21557 want to convert only the first line of this region, use one
21558 universal prefix argument.
21560 - If it is a plain list item, turn all plain list items into headings.
21562 When converting a line into a heading, the number of stars is chosen
21563 such that the lines become children of the current entry. However,
21564 when a numeric prefix argument is given, its value determines the
21565 number of stars to add."
21566 (interactive "P")
21567 (let ((skip-blanks
21568 (function
21569 ;; Return beginning of first non-blank line, starting from
21570 ;; line at POS.
21571 (lambda (pos)
21572 (save-excursion
21573 (goto-char pos)
21574 (while (org-at-comment-p) (forward-line))
21575 (skip-chars-forward " \r\t\n")
21576 (point-at-bol)))))
21577 beg end toggled)
21578 ;; Determine boundaries of changes. If a universal prefix has
21579 ;; been given, put the list in a region. If region ends at a bol,
21580 ;; do not consider the last line to be in the region.
21582 (when (and current-prefix-arg (org-at-item-p))
21583 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21584 (org-mark-element))
21586 (if (org-region-active-p)
21587 (setq beg (funcall skip-blanks (region-beginning))
21588 end (copy-marker (save-excursion
21589 (goto-char (region-end))
21590 (if (bolp) (point) (point-at-eol)))))
21591 (setq beg (funcall skip-blanks (point-at-bol))
21592 end (copy-marker (point-at-eol))))
21593 ;; Ensure inline tasks don't count as headings.
21594 (org-with-limited-levels
21595 (save-excursion
21596 (goto-char beg)
21597 (cond
21598 ;; Case 1. Started at an heading: de-star headings.
21599 ((org-at-heading-p)
21600 (while (< (point) end)
21601 (when (org-at-heading-p t)
21602 (looking-at org-outline-regexp) (replace-match "")
21603 (setq toggled t))
21604 (forward-line)))
21605 ;; Case 2. Started at an item: change items into headlines.
21606 ;; One star will be added by `org-list-to-subtree'.
21607 ((org-at-item-p)
21608 (while (< (point) end)
21609 (when (org-at-item-p)
21610 ;; Pay attention to cases when region ends before list.
21611 (let* ((struct (org-list-struct))
21612 (list-end
21613 (min (org-list-get-bottom-point struct) (1+ end))))
21614 (save-restriction
21615 (narrow-to-region (point) list-end)
21616 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21617 (setq toggled t))
21618 (forward-line)))
21619 ;; Case 3. Started at normal text: make every line an heading,
21620 ;; skipping headlines and items.
21621 (t (let* ((stars
21622 (make-string
21623 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21624 (add-stars
21625 (cond (nstars "") ; stars from prefix only
21626 ((equal stars "") "*") ; before first heading
21627 (org-odd-levels-only "**") ; inside heading, odd
21628 (t "*"))) ; inside heading, oddeven
21629 (rpl (concat stars add-stars " "))
21630 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21631 (while (< (point) (if (equal nstars '(4)) lend end))
21632 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21633 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21634 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21635 (forward-line)))))))
21636 (unless toggled (message "Cannot toggle heading from here"))))
21638 (defun org-meta-return (&optional _arg)
21639 "Insert a new heading or wrap a region in a table.
21640 Calls `org-insert-heading' or `org-table-wrap-region', depending
21641 on context. See the individual commands for more information."
21642 (interactive)
21643 (org-check-before-invisible-edit 'insert)
21644 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21645 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21646 #'org-insert-heading))))
21648 ;;; Menu entries
21650 (defsubst org-in-subtree-not-table-p ()
21651 "Are we in a subtree and not in a table?"
21652 (and (not (org-before-first-heading-p))
21653 (not (org-at-table-p))))
21655 ;; Define the Org-mode menus
21656 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21657 '("Tbl"
21658 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21659 ["Next Field" org-cycle (org-at-table-p)]
21660 ["Previous Field" org-shifttab (org-at-table-p)]
21661 ["Next Row" org-return (org-at-table-p)]
21662 "--"
21663 ["Blank Field" org-table-blank-field (org-at-table-p)]
21664 ["Edit Field" org-table-edit-field (org-at-table-p)]
21665 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21666 "--"
21667 ("Column"
21668 ["Move Column Left" org-metaleft (org-at-table-p)]
21669 ["Move Column Right" org-metaright (org-at-table-p)]
21670 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21671 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21672 ("Row"
21673 ["Move Row Up" org-metaup (org-at-table-p)]
21674 ["Move Row Down" org-metadown (org-at-table-p)]
21675 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21676 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21677 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21678 "--"
21679 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21680 ("Rectangle"
21681 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21682 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21683 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21684 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21685 "--"
21686 ("Calculate"
21687 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21688 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21689 ["Edit Formulas" org-edit-special (org-at-table-p)]
21690 "--"
21691 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21692 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21693 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21694 "--"
21695 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21696 "--"
21697 ["Sum Column/Rectangle" org-table-sum
21698 (or (org-at-table-p) (org-region-active-p))]
21699 ["Which Column?" org-table-current-column (org-at-table-p)])
21700 ["Debug Formulas"
21701 org-table-toggle-formula-debugger
21702 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21703 ["Show Col/Row Numbers"
21704 org-table-toggle-coordinate-overlays
21705 :style toggle
21706 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21707 "--"
21708 ["Create" org-table-create (and (not (org-at-table-p))
21709 org-enable-table-editor)]
21710 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21711 ["Import from File" org-table-import (not (org-at-table-p))]
21712 ["Export to File" org-table-export (org-at-table-p)]
21713 "--"
21714 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21715 "--"
21716 ("Plot"
21717 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21718 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21720 (easy-menu-define org-org-menu org-mode-map "Org menu"
21721 '("Org"
21722 ("Show/Hide"
21723 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21724 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21725 ["Sparse Tree..." org-sparse-tree t]
21726 ["Reveal Context" org-reveal t]
21727 ["Show All" outline-show-all t]
21728 "--"
21729 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21730 "--"
21731 ["New Heading" org-insert-heading t]
21732 ("Navigate Headings"
21733 ["Up" outline-up-heading t]
21734 ["Next" outline-next-visible-heading t]
21735 ["Previous" outline-previous-visible-heading t]
21736 ["Next Same Level" outline-forward-same-level t]
21737 ["Previous Same Level" outline-backward-same-level t]
21738 "--"
21739 ["Jump" org-goto t])
21740 ("Edit Structure"
21741 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21742 "--"
21743 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21744 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21745 "--"
21746 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21747 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21748 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21749 "--"
21750 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21751 "--"
21752 ["Copy visible text" org-copy-visible t]
21753 "--"
21754 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21755 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21756 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21757 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21758 "--"
21759 ["Sort Region/Children" org-sort t]
21760 "--"
21761 ["Convert to odd levels" org-convert-to-odd-levels t]
21762 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21763 ("Editing"
21764 ["Emphasis..." org-emphasize t]
21765 ["Edit Source Example" org-edit-special t]
21766 "--"
21767 ["Footnote new/jump" org-footnote-action t]
21768 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21769 ("Archive"
21770 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21771 "--"
21772 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21773 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21774 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21776 "--"
21777 ("Hyperlinks"
21778 ["Store Link (Global)" org-store-link t]
21779 ["Find existing link to here" org-occur-link-in-agenda-files t]
21780 ["Insert Link" org-insert-link t]
21781 ["Follow Link" org-open-at-point t]
21782 "--"
21783 ["Next link" org-next-link t]
21784 ["Previous link" org-previous-link t]
21785 "--"
21786 ["Descriptive Links"
21787 org-toggle-link-display
21788 :style radio
21789 :selected org-descriptive-links
21791 ["Literal Links"
21792 org-toggle-link-display
21793 :style radio
21794 :selected (not org-descriptive-links)])
21795 "--"
21796 ("TODO Lists"
21797 ["TODO/DONE/-" org-todo t]
21798 ("Select keyword"
21799 ["Next keyword" org-shiftright (org-at-heading-p)]
21800 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21801 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21802 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21803 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21804 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21805 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21806 "--"
21807 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21808 :selected org-enforce-todo-dependencies :style toggle :active t]
21809 "Settings for tree at point"
21810 ["Do Children sequentially" org-toggle-ordered-property :style radio
21811 :selected (org-entry-get nil "ORDERED")
21812 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21813 ["Do Children parallel" org-toggle-ordered-property :style radio
21814 :selected (not (org-entry-get nil "ORDERED"))
21815 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21816 "--"
21817 ["Set Priority" org-priority t]
21818 ["Priority Up" org-shiftup t]
21819 ["Priority Down" org-shiftdown t]
21820 "--"
21821 ["Get news from all feeds" org-feed-update-all t]
21822 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21823 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21824 ("TAGS and Properties"
21825 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21826 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21827 "--"
21828 ["Set property" org-set-property (not (org-before-first-heading-p))]
21829 ["Column view of properties" org-columns t]
21830 ["Insert Column View DBlock" org-insert-columns-dblock t])
21831 ("Dates and Scheduling"
21832 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21833 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21834 ("Change Date"
21835 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21836 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21837 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21838 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21839 ["Compute Time Range" org-evaluate-time-range t]
21840 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21841 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21842 "--"
21843 ["Custom time format" org-toggle-time-stamp-overlays
21844 :style radio :selected org-display-custom-times]
21845 "--"
21846 ["Goto Calendar" org-goto-calendar t]
21847 ["Date from Calendar" org-date-from-calendar t]
21848 "--"
21849 ["Start/Restart Timer" org-timer-start t]
21850 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21851 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21852 ["Insert Timer String" org-timer t]
21853 ["Insert Timer Item" org-timer-item t])
21854 ("Logging work"
21855 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21856 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21857 ["Clock out" org-clock-out t]
21858 ["Clock cancel" org-clock-cancel t]
21859 "--"
21860 ["Mark as default task" org-clock-mark-default-task t]
21861 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21862 ["Goto running clock" org-clock-goto t]
21863 "--"
21864 ["Display times" org-clock-display t]
21865 ["Create clock table" org-clock-report t]
21866 "--"
21867 ["Record DONE time"
21868 (progn (setq org-log-done (not org-log-done))
21869 (message "Switching to %s will %s record a timestamp"
21870 (car org-done-keywords)
21871 (if org-log-done "automatically" "not")))
21872 :style toggle :selected org-log-done])
21873 "--"
21874 ["Agenda Command..." org-agenda t]
21875 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21876 ("File List for Agenda")
21877 ("Special views current file"
21878 ["TODO Tree" org-show-todo-tree t]
21879 ["Check Deadlines" org-check-deadlines t]
21880 ["Timeline" org-timeline t]
21881 ["Tags/Property tree" org-match-sparse-tree t])
21882 "--"
21883 ["Export/Publish..." org-export-dispatch t]
21884 ("LaTeX"
21885 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21886 :selected org-cdlatex-mode]
21887 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21888 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21889 ["Modify math symbol" org-cdlatex-math-modify
21890 (org-inside-LaTeX-fragment-p)]
21891 ["Insert citation" org-reftex-citation t]
21892 "--"
21893 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21894 "--"
21895 ("MobileOrg"
21896 ["Push Files and Views" org-mobile-push t]
21897 ["Get Captured and Flagged" org-mobile-pull t]
21898 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21899 "--"
21900 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21901 "--"
21902 ("Documentation"
21903 ["Show Version" org-version t]
21904 ["Info Documentation" org-info t])
21905 ("Customize"
21906 ["Browse Org Group" org-customize t]
21907 "--"
21908 ["Expand This Menu" org-create-customize-menu
21909 (fboundp 'customize-menu-create)])
21910 ["Send bug report" org-submit-bug-report t]
21911 "--"
21912 ("Refresh/Reload"
21913 ["Refresh setup current buffer" org-mode-restart t]
21914 ["Reload Org (after update)" org-reload t]
21915 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21918 (defun org-info (&optional node)
21919 "Read documentation for Org-mode in the info system.
21920 With optional NODE, go directly to that node."
21921 (interactive)
21922 (info (format "(org)%s" (or node ""))))
21924 ;;;###autoload
21925 (defun org-submit-bug-report ()
21926 "Submit a bug report on Org-mode via mail.
21928 Don't hesitate to report any problems or inaccurate documentation.
21930 If you don't have setup sending mail from (X)Emacs, please copy the
21931 output buffer into your mail program, as it gives us important
21932 information about your Org-mode version and configuration."
21933 (interactive)
21934 (require 'reporter)
21935 (defvar reporter-prompt-for-summary-p)
21936 (org-load-modules-maybe)
21937 (org-require-autoloaded-modules)
21938 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21939 (reporter-submit-bug-report
21940 "emacs-orgmode@gnu.org"
21941 (org-version nil 'full)
21942 (let (list)
21943 (save-window-excursion
21944 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21945 (delete-other-windows)
21946 (erase-buffer)
21947 (insert "You are about to submit a bug report to the Org-mode mailing list.
21949 We would like to add your full Org-mode and Outline configuration to the
21950 bug report. This greatly simplifies the work of the maintainer and
21951 other experts on the mailing list.
21953 HOWEVER, some variables you have customized may contain private
21954 information. The names of customers, colleagues, or friends, might
21955 appear in the form of file names, tags, todo states, or search strings.
21956 If you answer yes to the prompt, you might want to check and remove
21957 such private information before sending the email.")
21958 (add-text-properties (point-min) (point-max) '(face org-warning))
21959 (when (yes-or-no-p "Include your Org-mode configuration ")
21960 (mapatoms
21961 (lambda (v)
21962 (and (boundp v)
21963 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21964 (or (and (symbol-value v)
21965 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21966 (and
21967 (get v 'custom-type) (get v 'standard-value)
21968 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21969 (push v list)))))
21970 (kill-buffer (get-buffer "*Warn about privacy*"))
21971 list))
21972 nil nil
21973 "Remember to cover the basics, that is, what you expected to happen and
21974 what in fact did happen. You don't know how to make a good report? See
21976 http://orgmode.org/manual/Feedback.html#Feedback
21978 Your bug report will be posted to the Org-mode mailing list.
21979 ------------------------------------------------------------------------")
21980 (save-excursion
21981 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21982 (replace-match "\\1Bug: \\3 [\\2]")))))
21985 (defun org-install-agenda-files-menu ()
21986 (let ((bl (buffer-list)))
21987 (save-excursion
21988 (while bl
21989 (set-buffer (pop bl))
21990 (when (derived-mode-p 'org-mode) (setq bl nil)))
21991 (when (derived-mode-p 'org-mode)
21992 (easy-menu-change
21993 '("Org") "File List for Agenda"
21994 (append
21995 (list
21996 ["Edit File List" (org-edit-agenda-file-list) t]
21997 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21998 ["Remove Current File from List" org-remove-file t]
21999 ["Cycle through agenda files" org-cycle-agenda-files t]
22000 ["Occur in all agenda files" org-occur-in-agenda-files t]
22001 "--")
22002 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22004 ;;;; Documentation
22006 (defun org-require-autoloaded-modules ()
22007 (interactive)
22008 (mapc #'require
22009 '(org-agenda org-archive org-attach org-clock org-colview org-id
22010 org-table org-timer)))
22012 ;;;###autoload
22013 (defun org-reload (&optional uncompiled)
22014 "Reload all org lisp files.
22015 With prefix arg UNCOMPILED, load the uncompiled versions."
22016 (interactive "P")
22017 (require 'loadhist)
22018 (let* ((org-dir (org-find-library-dir "org"))
22019 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22020 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22021 (remove-re (mapconcat 'identity
22022 (mapcar (lambda (f) (concat "^" f "$"))
22023 (list (if (featurep 'xemacs)
22024 "org-colview"
22025 "org-colview-xemacs")
22026 "org" "org-loaddefs" "org-version"))
22027 "\\|"))
22028 (feats (delete-dups
22029 (mapcar 'file-name-sans-extension
22030 (mapcar 'file-name-nondirectory
22031 (delq nil
22032 (mapcar 'feature-file
22033 features))))))
22034 (lfeat (append
22035 (sort
22036 (setq feats
22037 (delq nil (mapcar
22038 (lambda (f)
22039 (if (and (string-match feature-re f)
22040 (not (string-match remove-re f)))
22041 f nil))
22042 feats)))
22043 'string-lessp)
22044 (list "org-version" "org")))
22045 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22046 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22047 load-uncore load-misses)
22048 (setq load-misses
22049 (delq 't
22050 (mapcar (lambda (f)
22051 (or (org-load-noerror-mustsuffix (concat org-dir f))
22052 (and (string= org-dir contrib-dir)
22053 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22054 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22055 (add-to-list 'load-uncore f 'append)
22058 lfeat)))
22059 (when load-uncore
22060 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22061 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22062 (if load-misses
22063 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22064 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22065 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22067 ;;;###autoload
22068 (defun org-customize ()
22069 "Call the customize function with org as argument."
22070 (interactive)
22071 (org-load-modules-maybe)
22072 (org-require-autoloaded-modules)
22073 (customize-browse 'org))
22075 (defun org-create-customize-menu ()
22076 "Create a full customization menu for Org-mode, insert it into the menu."
22077 (interactive)
22078 (org-load-modules-maybe)
22079 (org-require-autoloaded-modules)
22080 (if (fboundp 'customize-menu-create)
22081 (progn
22082 (easy-menu-change
22083 '("Org") "Customize"
22084 `(["Browse Org group" org-customize t]
22085 "--"
22086 ,(customize-menu-create 'org)
22087 ["Set" Custom-set t]
22088 ["Save" Custom-save t]
22089 ["Reset to Current" Custom-reset-current t]
22090 ["Reset to Saved" Custom-reset-saved t]
22091 ["Reset to Standard Settings" Custom-reset-standard t]))
22092 (message "\"Org\"-menu now contains full customization menu"))
22093 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22095 ;;;; Miscellaneous stuff
22097 ;;; Generally useful functions
22099 (defun org-get-at-eol (property n)
22100 "Get text property PROPERTY at the end of line less N characters."
22101 (get-text-property (- (point-at-eol) n) property))
22103 (defun org-find-text-property-in-string (prop s)
22104 "Return the first non-nil value of property PROP in string S."
22105 (or (get-text-property 0 prop s)
22106 (get-text-property (or (next-single-property-change 0 prop s) 0)
22107 prop s)))
22109 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22110 "Display the given MESSAGE as a warning."
22111 (if (fboundp 'display-warning)
22112 (display-warning 'org message
22113 (if (featurep 'xemacs) 'warning :warning))
22114 (let ((buf (get-buffer-create "*Org warnings*")))
22115 (with-current-buffer buf
22116 (goto-char (point-max))
22117 (insert "Warning (Org): " message)
22118 (unless (bolp)
22119 (newline)))
22120 (display-buffer buf)
22121 (sit-for 0))))
22123 (defun org-eval (form)
22124 "Eval FORM and return result."
22125 (condition-case error
22126 (eval form)
22127 (error (format "%%![Error: %s]" error))))
22129 (defun org-in-clocktable-p ()
22130 "Check if the cursor is in a clocktable."
22131 (let ((pos (point)) start)
22132 (save-excursion
22133 (end-of-line 1)
22134 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22135 (setq start (match-beginning 0))
22136 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22137 (>= (match-end 0) pos)
22138 start))))
22140 (defun org-in-verbatim-emphasis ()
22141 (save-match-data
22142 (and (org-in-regexp org-emph-re 2)
22143 (>= (point) (match-beginning 3))
22144 (<= (point) (match-end 4))
22145 (member (match-string 3) '("=" "~")))))
22147 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22148 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22149 (if (and marker (marker-buffer marker)
22150 (buffer-live-p (marker-buffer marker)))
22151 (progn
22152 (org-pop-to-buffer-same-window (marker-buffer marker))
22153 (when (or (> marker (point-max)) (< marker (point-min)))
22154 (widen))
22155 (goto-char marker)
22156 (org-show-context 'org-goto))
22157 (if bookmark
22158 (bookmark-jump bookmark)
22159 (error "Cannot find location"))))
22161 (defun org-quote-csv-field (s)
22162 "Quote field for inclusion in CSV material."
22163 (if (string-match "[\",]" s)
22164 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22167 (defun org-force-self-insert (N)
22168 "Needed to enforce self-insert under remapping."
22169 (interactive "p")
22170 (self-insert-command N))
22172 (defun org-string-width (s)
22173 "Compute width of string, ignoring invisible characters.
22174 This ignores character with invisibility property `org-link', and also
22175 characters with property `org-cwidth', because these will become invisible
22176 upon the next fontification round."
22177 (let (b l)
22178 (when (or (eq t buffer-invisibility-spec)
22179 (assq 'org-link buffer-invisibility-spec))
22180 (while (setq b (text-property-any 0 (length s)
22181 'invisible 'org-link s))
22182 (setq s (concat (substring s 0 b)
22183 (substring s (or (next-single-property-change
22184 b 'invisible s)
22185 (length s)))))))
22186 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22187 (setq s (concat (substring s 0 b)
22188 (substring s (or (next-single-property-change
22189 b 'org-cwidth s)
22190 (length s))))))
22191 (setq l (string-width s) b -1)
22192 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22193 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22196 (defun org-shorten-string (s maxlength)
22197 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22198 If the string is shorter or has length MAXLENGTH, just return the
22199 original string. If it is longer, the functions finds a space in the
22200 string, breaks this string off at that locations and adds three dots
22201 as ellipsis. Including the ellipsis, the string will not be longer
22202 than MAXLENGTH. If finding a good breaking point in the string does
22203 not work, the string is just chopped off in the middle of a word
22204 if necessary."
22205 (if (<= (length s) maxlength)
22207 (let* ((n (max (- maxlength 4) 1))
22208 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22209 (if (string-match re s)
22210 (concat (match-string 1 s) "...")
22211 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22213 (defun org-get-indentation (&optional line)
22214 "Get the indentation of the current line, interpreting tabs.
22215 When LINE is given, assume it represents a line and compute its indentation."
22216 (if line
22217 (when (string-match "^ *" (org-remove-tabs line))
22218 (match-end 0))
22219 (save-excursion
22220 (beginning-of-line 1)
22221 (skip-chars-forward " \t")
22222 (current-column))))
22224 (defun org-get-string-indentation (s)
22225 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22226 (let ((n -1) (i 0) (w tab-width) c)
22227 (catch 'exit
22228 (while (< (setq n (1+ n)) (length s))
22229 (setq c (aref s n))
22230 (cond ((= c ?\ ) (setq i (1+ i)))
22231 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22232 (t (throw 'exit t)))))
22235 (defun org-remove-tabs (s &optional width)
22236 "Replace tabulators in S with spaces.
22237 Assumes that s is a single line, starting in column 0."
22238 (setq width (or width tab-width))
22239 (while (string-match "\t" s)
22240 (setq s (replace-match
22241 (make-string
22242 (- (* width (/ (+ (match-beginning 0) width) width))
22243 (match-beginning 0)) ?\ )
22244 t t s)))
22247 (defun org-fix-indentation (line ind)
22248 "Fix indentation in LINE.
22249 IND is a cons cell with target and minimum indentation.
22250 If the current indentation in LINE is smaller than the minimum,
22251 leave it alone. If it is larger than ind, set it to the target."
22252 (let* ((l (org-remove-tabs line))
22253 (i (org-get-indentation l))
22254 (i1 (car ind)) (i2 (cdr ind)))
22255 (when (>= i i2) (setq l (substring line i2)))
22256 (if (> i1 0)
22257 (concat (make-string i1 ?\ ) l)
22258 l)))
22260 (defun org-remove-indentation (code &optional n)
22261 "Remove maximum common indentation in string CODE and return it.
22262 N may optionally be the number of columns to remove. Return CODE
22263 as-is if removal failed."
22264 (with-temp-buffer
22265 (insert code)
22266 (if (org-do-remove-indentation n) (buffer-string) code)))
22268 (defun org-do-remove-indentation (&optional n)
22269 "Remove the maximum common indentation from the buffer.
22270 When optional argument N is a positive integer, remove exactly
22271 that much characters from indentation, if possible. Return nil
22272 if it fails."
22273 (catch :exit
22274 (goto-char (point-min))
22275 ;; Find maximum common indentation, if not specified.
22276 (let ((n (or n
22277 (let ((min-ind (point-max)))
22278 (save-excursion
22279 (while (re-search-forward "^[ \t]*\\S-" nil t)
22280 (let ((ind (1- (current-column))))
22281 (if (zerop ind) (throw :exit nil)
22282 (setq min-ind (min min-ind ind))))))
22283 min-ind))))
22284 (if (zerop n) (throw :exit nil)
22285 ;; Remove exactly N indentation, but give up if not possible.
22286 (while (not (eobp))
22287 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22288 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22289 ((< ind n) (throw :exit nil))
22290 (t (org-indent-line-to (- ind n))))
22291 (forward-line)))
22292 ;; Signal success.
22293 t))))
22295 (defun org-fill-template (template alist)
22296 "Find each %key of ALIST in TEMPLATE and replace it."
22297 (let ((case-fold-search nil))
22298 (dolist (entry (sort (copy-sequence alist)
22299 (lambda (a b) (< (length (car a)) (length (car b))))))
22300 (setq template
22301 (replace-regexp-in-string
22302 (concat "%" (regexp-quote (car entry)))
22303 (or (cdr entry) "") template t t)))
22304 template))
22306 (defun org-base-buffer (buffer)
22307 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22308 (if (not buffer)
22309 buffer
22310 (or (buffer-base-buffer buffer)
22311 buffer)))
22313 (defun org-wrap (string &optional width lines)
22314 "Wrap string to either a number of lines, or a width in characters.
22315 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22316 that costs. If there is a word longer than WIDTH, the text is actually
22317 wrapped to the length of that word.
22318 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22319 many lines, whatever width that takes.
22320 The return value is a list of lines, without newlines at the end."
22321 (let* ((words (org-split-string string "[ \t\n]+"))
22322 (maxword (apply 'max (mapcar 'org-string-width words)))
22323 w ll)
22324 (cond (width
22325 (org-do-wrap words (max maxword width)))
22326 (lines
22327 (setq w maxword)
22328 (setq ll (org-do-wrap words maxword))
22329 (if (<= (length ll) lines)
22331 (setq ll words)
22332 (while (> (length ll) lines)
22333 (setq w (1+ w))
22334 (setq ll (org-do-wrap words w)))
22335 ll))
22336 (t (error "Cannot wrap this")))))
22338 (defun org-do-wrap (words width)
22339 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22340 (let (lines line)
22341 (while words
22342 (setq line (pop words))
22343 (while (and words (< (+ (length line) (length (car words))) width))
22344 (setq line (concat line " " (pop words))))
22345 (setq lines (push line lines)))
22346 (nreverse lines)))
22348 (defun org-split-string (string &optional separators)
22349 "Splits STRING into substrings at SEPARATORS.
22350 SEPARATORS is a regular expression.
22351 No empty strings are returned if there are matches at the beginning
22352 and end of string."
22353 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22354 (let ((start 0) notfirst list)
22355 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22356 (if (and notfirst
22357 (= start (match-beginning 0))
22358 (< start (length string)))
22359 (1+ start) start))
22360 (< (match-beginning 0) (length string)))
22361 (setq notfirst t)
22362 (or (eq (match-beginning 0) 0)
22363 (and (eq (match-beginning 0) (match-end 0))
22364 (eq (match-beginning 0) start))
22365 (push (substring string start (match-beginning 0)) list))
22366 (setq start (match-end 0)))
22367 (or (eq start (length string))
22368 (push (substring string start) list))
22369 (nreverse list)))
22371 (defun org-quote-vert (s)
22372 "Replace \"|\" with \"\\vert\"."
22373 (while (string-match "|" s)
22374 (setq s (replace-match "\\vert" t t s)))
22377 (defun org-uuidgen-p (s)
22378 "Is S an ID created by UUIDGEN?"
22379 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22381 (defun org-in-src-block-p (&optional inside)
22382 "Whether point is in a code source block.
22383 When INSIDE is non-nil, don't consider we are within a src block
22384 when point is at #+BEGIN_SRC or #+END_SRC."
22385 (let ((case-fold-search t))
22386 (or (and (eq (get-char-property (point) 'src-block) t))
22387 (and (not inside)
22388 (save-match-data
22389 (save-excursion
22390 (beginning-of-line)
22391 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22393 (defun org-context ()
22394 "Return a list of contexts of the current cursor position.
22395 If several contexts apply, all are returned.
22396 Each context entry is a list with a symbol naming the context, and
22397 two positions indicating start and end of the context. Possible
22398 contexts are:
22400 :headline anywhere in a headline
22401 :headline-stars on the leading stars in a headline
22402 :todo-keyword on a TODO keyword (including DONE) in a headline
22403 :tags on the TAGS in a headline
22404 :priority on the priority cookie in a headline
22405 :item on the first line of a plain list item
22406 :item-bullet on the bullet/number of a plain list item
22407 :checkbox on the checkbox in a plain list item
22408 :table in an org-mode table
22409 :table-special on a special filed in a table
22410 :table-table in a table.el table
22411 :clocktable in a clocktable
22412 :src-block in a source block
22413 :link on a hyperlink
22414 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22415 :target on a <<target>>
22416 :radio-target on a <<<radio-target>>>
22417 :latex-fragment on a LaTeX fragment
22418 :latex-preview on a LaTeX fragment with overlaid preview image
22420 This function expects the position to be visible because it uses font-lock
22421 faces as a help to recognize the following contexts: :table-special, :link,
22422 and :keyword."
22423 (let* ((f (get-text-property (point) 'face))
22424 (faces (if (listp f) f (list f)))
22425 (case-fold-search t)
22426 (p (point)) clist o)
22427 ;; First the large context
22428 (cond
22429 ((org-at-heading-p t)
22430 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22431 (when (progn
22432 (beginning-of-line 1)
22433 (looking-at org-todo-line-tags-regexp))
22434 (push (org-point-in-group p 1 :headline-stars) clist)
22435 (push (org-point-in-group p 2 :todo-keyword) clist)
22436 (push (org-point-in-group p 4 :tags) clist))
22437 (goto-char p)
22438 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22439 (when (looking-at "\\[#[A-Z0-9]\\]")
22440 (push (org-point-in-group p 0 :priority) clist)))
22442 ((org-at-item-p)
22443 (push (org-point-in-group p 2 :item-bullet) clist)
22444 (push (list :item (point-at-bol)
22445 (save-excursion (org-end-of-item) (point)))
22446 clist)
22447 (and (org-at-item-checkbox-p)
22448 (push (org-point-in-group p 0 :checkbox) clist)))
22450 ((org-at-table-p)
22451 (push (list :table (org-table-begin) (org-table-end)) clist)
22452 (when (memq 'org-formula faces)
22453 (push (list :table-special
22454 (previous-single-property-change p 'face)
22455 (next-single-property-change p 'face)) clist)))
22456 ((org-at-table-p 'any)
22457 (push (list :table-table) clist)))
22458 (goto-char p)
22460 (let ((case-fold-search t))
22461 ;; New the "medium" contexts: clocktables, source blocks
22462 (cond ((org-in-clocktable-p)
22463 (push (list :clocktable
22464 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22465 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22466 (match-beginning 1))
22467 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22468 (match-end 0))) clist))
22469 ((org-in-src-block-p)
22470 (push (list :src-block
22471 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22472 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22473 (match-beginning 1))
22474 (and (search-forward "#+END_SRC" nil t)
22475 (match-beginning 0))) clist))))
22476 (goto-char p)
22478 ;; Now the small context
22479 (cond
22480 ((org-at-timestamp-p)
22481 (push (org-point-in-group p 0 :timestamp) clist))
22482 ((memq 'org-link faces)
22483 (push (list :link
22484 (previous-single-property-change p 'face)
22485 (next-single-property-change p 'face)) clist))
22486 ((memq 'org-special-keyword faces)
22487 (push (list :keyword
22488 (previous-single-property-change p 'face)
22489 (next-single-property-change p 'face)) clist))
22490 ((org-at-target-p)
22491 (push (org-point-in-group p 0 :target) clist)
22492 (goto-char (1- (match-beginning 0)))
22493 (when (looking-at org-radio-target-regexp)
22494 (push (org-point-in-group p 0 :radio-target) clist))
22495 (goto-char p))
22496 ((setq o (car (delq nil
22497 (mapcar
22498 (lambda (x)
22499 (when (memq x org-latex-fragment-image-overlays) x))
22500 (overlays-at (point))))))
22501 (push (list :latex-fragment
22502 (overlay-start o) (overlay-end o)) clist)
22503 (push (list :latex-preview
22504 (overlay-start o) (overlay-end o)) clist))
22505 ((org-inside-LaTeX-fragment-p)
22506 ;; FIXME: positions wrong.
22507 (push (list :latex-fragment (point) (point)) clist)))
22509 (setq clist (nreverse (delq nil clist)))
22510 clist))
22512 (defun org-in-regexp (regexp &optional nlines visually)
22513 "Check if point is inside a match of REGEXP.
22515 Normally only the current line is checked, but you can include
22516 NLINES extra lines around point into the search. If VISUALLY is
22517 set, require that the cursor is not after the match but really
22518 on, so that the block visually is on the match.
22520 Return nil or a cons cell (BEG . END) where BEG and END are,
22521 respectively, the positions at the beginning and the end of the
22522 match."
22523 (catch :exit
22524 (let ((pos (point))
22525 (eol (line-end-position (if nlines (1+ nlines) 1))))
22526 (save-excursion
22527 (beginning-of-line (- 1 (or nlines 0)))
22528 (while (and (re-search-forward regexp eol t)
22529 (<= (match-beginning 0) pos))
22530 (let ((end (match-end 0)))
22531 (when (or (> end pos) (and (= end pos) (not visually)))
22532 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22533 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22534 "Org mode 8.3")
22536 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22537 "Non-nil when point is between matches of START-RE and END-RE.
22539 Also return a non-nil value when point is on one of the matches.
22541 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22542 buffer positions. Default values are the positions of headlines
22543 surrounding the point.
22545 The functions returns a cons cell whose car (resp. cdr) is the
22546 position before START-RE (resp. after END-RE)."
22547 (save-match-data
22548 (let ((pos (point))
22549 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22550 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22551 beg end)
22552 (save-excursion
22553 ;; Point is on a block when on START-RE or if START-RE can be
22554 ;; found before it...
22555 (and (or (org-in-regexp start-re)
22556 (re-search-backward start-re limit-up t))
22557 (setq beg (match-beginning 0))
22558 ;; ... and END-RE after it...
22559 (goto-char (match-end 0))
22560 (re-search-forward end-re limit-down t)
22561 (> (setq end (match-end 0)) pos)
22562 ;; ... without another START-RE in-between.
22563 (goto-char (match-beginning 0))
22564 (not (re-search-backward start-re (1+ beg) t))
22565 ;; Return value.
22566 (cons beg end))))))
22568 (defun org-in-block-p (names)
22569 "Non-nil when point belongs to a block whose name belongs to NAMES.
22571 NAMES is a list of strings containing names of blocks.
22573 Return first block name matched, or nil. Beware that in case of
22574 nested blocks, the returned name may not belong to the closest
22575 block from point."
22576 (save-match-data
22577 (catch 'exit
22578 (let ((case-fold-search t)
22579 (lim-up (save-excursion (outline-previous-heading)))
22580 (lim-down (save-excursion (outline-next-heading))))
22581 (dolist (name names)
22582 (let ((n (regexp-quote name)))
22583 (when (org-between-regexps-p
22584 (concat "^[ \t]*#\\+begin_" n)
22585 (concat "^[ \t]*#\\+end_" n)
22586 lim-up lim-down)
22587 (throw 'exit n)))))
22588 nil)))
22590 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22591 "Call `multi-occur' with buffers for all agenda files."
22592 (interactive "sOrg-files matching: ")
22593 (let* ((files (org-agenda-files))
22594 (tnames (mapcar #'file-truename files))
22595 (extra org-agenda-text-search-extra-files))
22596 (when (eq (car extra) 'agenda-archives)
22597 (setq extra (cdr extra))
22598 (setq files (org-add-archive-files files)))
22599 (dolist (f extra)
22600 (unless (member (file-truename f) tnames)
22601 (unless (member f files) (setq files (append files (list f))))
22602 (setq tnames (append tnames (list (file-truename f))))))
22603 (multi-occur
22604 (mapcar (lambda (x)
22605 (with-current-buffer
22606 ;; FIXME: Why not just (find-file-noselect x)?
22607 ;; Is it to avoid the "revert buffer" prompt?
22608 (or (get-file-buffer x) (find-file-noselect x))
22609 (widen)
22610 (current-buffer)))
22611 files)
22612 regexp)))
22614 (if (boundp 'occur-mode-find-occurrence-hook)
22615 ;; Emacs 23
22616 (add-hook 'occur-mode-find-occurrence-hook
22617 (lambda ()
22618 (when (derived-mode-p 'org-mode)
22619 (org-reveal))))
22620 ;; Emacs 22
22621 (defadvice occur-mode-goto-occurrence
22622 (after org-occur-reveal activate)
22623 (and (derived-mode-p 'org-mode) (org-reveal)))
22624 (defadvice occur-mode-goto-occurrence-other-window
22625 (after org-occur-reveal activate)
22626 (and (derived-mode-p 'org-mode) (org-reveal)))
22627 (defadvice occur-mode-display-occurrence
22628 (after org-occur-reveal activate)
22629 (when (derived-mode-p 'org-mode)
22630 (let ((pos (occur-mode-find-occurrence)))
22631 (with-current-buffer (marker-buffer pos)
22632 (save-excursion
22633 (goto-char pos)
22634 (org-reveal)))))))
22636 (defun org-occur-link-in-agenda-files ()
22637 "Create a link and search for it in the agendas.
22638 The link is not stored in `org-stored-links', it is just created
22639 for the search purpose."
22640 (interactive)
22641 (let ((link (condition-case nil
22642 (org-store-link nil)
22643 (error "Unable to create a link to here"))))
22644 (org-occur-in-agenda-files (regexp-quote link))))
22646 (defun org-reverse-string (string)
22647 "Return the reverse of STRING."
22648 (apply 'string (reverse (string-to-list string))))
22650 ;; defsubst org-uniquify must be defined before first use
22652 (defun org-uniquify-alist (alist)
22653 "Merge elements of ALIST with the same key.
22655 For example, in this alist:
22657 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22658 => \\='((a 1 3) (b 2))
22660 merge (a 1) and (a 3) into (a 1 3).
22662 The function returns the new ALIST."
22663 (let (rtn)
22664 (dolist (e alist rtn)
22665 (let (n)
22666 (if (not (assoc (car e) rtn))
22667 (push e rtn)
22668 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22669 (setq rtn (assq-delete-all (car e) rtn))
22670 (push n rtn))))))
22672 (defun org-delete-all (elts list)
22673 "Remove all elements in ELTS from LIST."
22674 (while elts
22675 (setq list (delete (pop elts) list)))
22676 list)
22678 (defun org-back-over-empty-lines ()
22679 "Move backwards over whitespace, to the beginning of the first empty line.
22680 Returns the number of empty lines passed."
22681 (let ((pos (point)))
22682 (if (cdr (assoc 'heading org-blank-before-new-entry))
22683 (skip-chars-backward " \t\n\r")
22684 (unless (eobp)
22685 (forward-line -1)))
22686 (beginning-of-line 2)
22687 (goto-char (min (point) pos))
22688 (count-lines (point) pos)))
22690 (defun org-skip-whitespace ()
22691 (skip-chars-forward " \t\n\r"))
22693 (defun org-point-in-group (point group &optional context)
22694 "Check if POINT is in match-group GROUP.
22695 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22696 match. If the match group does not exist or point is not inside it,
22697 return nil."
22698 (and (match-beginning group)
22699 (>= point (match-beginning group))
22700 (<= point (match-end group))
22701 (if context
22702 (list context (match-beginning group) (match-end group))
22703 t)))
22705 (defun org-switch-to-buffer-other-window (&rest args)
22706 "Switch to buffer in a second window on the current frame.
22707 In particular, do not allow pop-up frames.
22708 Returns the newly created buffer."
22709 (org-no-popups
22710 (apply 'switch-to-buffer-other-window args)))
22712 (defun org-combine-plists (&rest plists)
22713 "Create a single property list from all plists in PLISTS.
22714 The process starts by copying the first list, and then setting properties
22715 from the other lists. Settings in the last list are the most significant
22716 ones and overrule settings in the other lists."
22717 (let ((rtn (copy-sequence (pop plists)))
22718 p v ls)
22719 (while plists
22720 (setq ls (pop plists))
22721 (while ls
22722 (setq p (pop ls) v (pop ls))
22723 (setq rtn (plist-put rtn p v))))
22724 rtn))
22726 (defun org-replace-escapes (string table)
22727 "Replace %-escapes in STRING with values in TABLE.
22728 TABLE is an association list with keys like \"%a\" and string values.
22729 The sequences in STRING may contain normal field width and padding information,
22730 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22731 so values can contain further %-escapes if they are define later in TABLE."
22732 (let ((tbl (copy-alist table))
22733 (case-fold-search nil)
22734 (pchg 0)
22735 re rpl)
22736 (dolist (e tbl)
22737 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22738 (when (and (cdr e) (string-match re (cdr e)))
22739 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22740 (safe "SREF"))
22741 (add-text-properties 0 3 (list 'sref sref) safe)
22742 (setcdr e (replace-match safe t t (cdr e)))))
22743 (while (string-match re string)
22744 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22745 (cdr e)))
22746 (setq string (replace-match rpl t t string))))
22747 (while (setq pchg (next-property-change pchg string))
22748 (let ((sref (get-text-property pchg 'sref string)))
22749 (when (and sref (string-match "SREF" string pchg))
22750 (setq string (replace-match sref t t string)))))
22751 string))
22753 (defun org-sublist (list start end)
22754 "Return a section of LIST, from START to END.
22756 Counting starts at 1."
22757 (cl-subseq list (1- start) end))
22758 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22760 (defun org-find-base-buffer-visiting (file)
22761 "Like `find-buffer-visiting' but always return the base buffer and
22762 not an indirect buffer."
22763 (let ((buf (or (get-file-buffer file)
22764 (find-buffer-visiting file))))
22765 (if buf
22766 (or (buffer-base-buffer buf) buf)
22767 nil)))
22769 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22770 "Org 9.0")
22772 ;;; TODO: Only called once, from ox-odt which should probably use
22773 ;;; org-export-inline-image-p or something.
22774 (defun org-file-image-p (file)
22775 "Return non-nil if FILE is an image."
22776 (save-match-data
22777 (string-match (image-file-name-regexp) file)))
22779 (defun org-get-cursor-date (&optional with-time)
22780 "Return the date at cursor in as a time.
22781 This works in the calendar and in the agenda, anywhere else it just
22782 returns the current time.
22783 If WITH-TIME is non-nil, returns the time of the event at point (in
22784 the agenda) or the current time of the day."
22785 (let (date day defd tp hod mod)
22786 (when with-time
22787 (setq tp (get-text-property (point) 'time))
22788 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22789 (setq hod (string-to-number (match-string 1 tp))
22790 mod (string-to-number (match-string 2 tp))))
22791 (or tp (let ((now (decode-time)))
22792 (setq hod (nth 2 now)
22793 mod (nth 1 now)))))
22794 (cond
22795 ((eq major-mode 'calendar-mode)
22796 (setq date (calendar-cursor-to-date)
22797 defd (encode-time 0 (or mod 0) (or hod 0)
22798 (nth 1 date) (nth 0 date) (nth 2 date))))
22799 ((eq major-mode 'org-agenda-mode)
22800 (setq day (get-text-property (point) 'day))
22801 (when day
22802 (setq date (calendar-gregorian-from-absolute day)
22803 defd (encode-time 0 (or mod 0) (or hod 0)
22804 (nth 1 date) (nth 0 date) (nth 2 date))))))
22805 (or defd (current-time))))
22807 (defun org-mark-subtree (&optional up)
22808 "Mark the current subtree.
22809 This puts point at the start of the current subtree, and mark at
22810 the end. If a numeric prefix UP is given, move up into the
22811 hierarchy of headlines by UP levels before marking the subtree."
22812 (interactive "P")
22813 (org-with-limited-levels
22814 (cond ((org-at-heading-p) (beginning-of-line))
22815 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22816 (t (outline-previous-visible-heading 1))))
22817 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22818 (if (org-called-interactively-p 'any)
22819 (call-interactively 'org-mark-element)
22820 (org-mark-element)))
22823 ;;; Indentation
22825 (defun org--get-expected-indentation (element contentsp)
22826 "Expected indentation column for current line, according to ELEMENT.
22827 ELEMENT is an element containing point. CONTENTSP is non-nil
22828 when indentation is to be computed according to contents of
22829 ELEMENT."
22830 (let ((type (org-element-type element))
22831 (start (org-element-property :begin element))
22832 (post-affiliated (org-element-property :post-affiliated element)))
22833 (org-with-wide-buffer
22834 (cond
22835 (contentsp
22836 (cl-case type
22837 ((diary-sexp footnote-definition) 0)
22838 ((headline inlinetask nil)
22839 (if (not org-adapt-indentation) 0
22840 (let ((level (org-current-level)))
22841 (if level (1+ level) 0))))
22842 ((item plain-list) (org-list-item-body-column post-affiliated))
22844 (goto-char start)
22845 (org-get-indentation))))
22846 ((memq type '(headline inlinetask nil))
22847 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22848 (org--get-expected-indentation element t)
22850 ((memq type '(diary-sexp footnote-definition)) 0)
22851 ;; First paragraph of a footnote definition or an item.
22852 ;; Indent like parent.
22853 ((< (line-beginning-position) start)
22854 (org--get-expected-indentation
22855 (org-element-property :parent element) t))
22856 ;; At first line: indent according to previous sibling, if any,
22857 ;; ignoring footnote definitions and inline tasks, or parent's
22858 ;; contents.
22859 ((= (line-beginning-position) start)
22860 (catch 'exit
22861 (while t
22862 (if (= (point-min) start) (throw 'exit 0)
22863 (goto-char (1- start))
22864 (let* ((previous (org-element-at-point))
22865 (parent previous))
22866 (while (and parent (<= (org-element-property :end parent) start))
22867 (setq previous parent
22868 parent (org-element-property :parent parent)))
22869 (cond
22870 ((not previous) (throw 'exit 0))
22871 ((> (org-element-property :end previous) start)
22872 (throw 'exit (org--get-expected-indentation previous t)))
22873 ((memq (org-element-type previous)
22874 '(footnote-definition inlinetask))
22875 (setq start (org-element-property :begin previous)))
22876 (t (goto-char (org-element-property :begin previous))
22877 (throw 'exit
22878 (if (bolp) (org-get-indentation)
22879 ;; At first paragraph in an item or
22880 ;; a footnote definition.
22881 (org--get-expected-indentation
22882 (org-element-property :parent previous) t))))))))))
22883 ;; Otherwise, move to the first non-blank line above.
22885 (beginning-of-line)
22886 (let ((pos (point)))
22887 (skip-chars-backward " \r\t\n")
22888 (cond
22889 ;; Two blank lines end a footnote definition or a plain
22890 ;; list. When we indent an empty line after them, the
22891 ;; containing list or footnote definition is over, so it
22892 ;; qualifies as a previous sibling. Therefore, we indent
22893 ;; like its first line.
22894 ((and (memq type '(footnote-definition plain-list))
22895 (> (count-lines (point) pos) 2))
22896 (goto-char start)
22897 (org-get-indentation))
22898 ;; Line above is the first one of a paragraph at the
22899 ;; beginning of an item or a footnote definition. Indent
22900 ;; like parent.
22901 ((< (line-beginning-position) start)
22902 (org--get-expected-indentation
22903 (org-element-property :parent element) t))
22904 ;; Line above is the beginning of an element, i.e., point
22905 ;; was originally on the blank lines between element's start
22906 ;; and contents.
22907 ((= (line-beginning-position) post-affiliated)
22908 (org--get-expected-indentation element t))
22909 ;; POS is after contents in a greater element. Indent like
22910 ;; the beginning of the element.
22912 ;; As a special case, if point is at the end of a footnote
22913 ;; definition or an item, indent like the very last element
22914 ;; within.
22915 ((and (not (eq type 'paragraph))
22916 (let ((cend (org-element-property :contents-end element)))
22917 (and cend (<= cend pos))))
22918 (if (memq type '(footnote-definition item plain-list))
22919 (let ((last (org-element-at-point)))
22920 (org--get-expected-indentation
22921 last
22922 (memq (org-element-type last)
22923 '(footnote-definition item plain-list))))
22924 (goto-char start)
22925 (org-get-indentation)))
22926 ;; In any other case, indent like the current line.
22927 (t (org-get-indentation)))))))))
22929 (defun org--align-node-property ()
22930 "Align node property at point.
22931 Alignment is done according to `org-property-format', which see."
22932 (when (save-excursion
22933 (beginning-of-line)
22934 (looking-at org-property-re))
22935 (replace-match
22936 (concat (match-string 4)
22937 (org-trim
22938 (format org-property-format (match-string 1) (match-string 3))))
22939 t t)))
22941 (defun org-indent-line ()
22942 "Indent line depending on context.
22944 Indentation is done according to the following rules:
22946 - Footnote definitions, diary sexps, headlines and inline tasks
22947 have to start at column 0.
22949 - On the very first line of an element, consider, in order, the
22950 next rules until one matches:
22952 1. If there's a sibling element before, ignoring footnote
22953 definitions and inline tasks, indent like its first line.
22955 2. If element has a parent, indent like its contents. More
22956 precisely, if parent is an item, indent after the
22957 description part, if any, or the bullet (see
22958 `org-list-description-max-indent'). Else, indent like
22959 parent's first line.
22961 3. Otherwise, indent relatively to current level, if
22962 `org-adapt-indentation' is non-nil, or to left margin.
22964 - On a blank line at the end of an element, indent according to
22965 the type of the element. More precisely
22967 1. If element is a plain list, an item, or a footnote
22968 definition, indent like the very last element within.
22970 2. If element is a paragraph, indent like its last non blank
22971 line.
22973 3. Otherwise, indent like its very first line.
22975 - In the code part of a source block, use language major mode
22976 to indent current line if `org-src-tab-acts-natively' is
22977 non-nil. If it is nil, do nothing.
22979 - Otherwise, indent like the first non-blank line above.
22981 The function doesn't indent an item as it could break the whole
22982 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22983 \\[org-shiftmetaright].
22985 Also align node properties according to `org-property-format'."
22986 (interactive)
22987 (cond
22988 (orgstruct-is-++
22989 (let ((indent-line-function
22990 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22991 (indent-according-to-mode)))
22992 ((org-at-heading-p) 'noindent)
22994 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22995 (type (org-element-type element)))
22996 (cond ((and (memq type '(plain-list item))
22997 (= (line-beginning-position)
22998 (org-element-property :post-affiliated element)))
22999 'noindent)
23000 ((and (eq type 'src-block)
23001 org-src-tab-acts-natively
23002 (> (line-beginning-position)
23003 (org-element-property :post-affiliated element))
23004 (< (line-beginning-position)
23005 (org-with-wide-buffer
23006 (goto-char (org-element-property :end element))
23007 (skip-chars-backward " \r\t\n")
23008 (line-beginning-position))))
23009 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23011 (let ((column (org--get-expected-indentation element nil)))
23012 ;; Preserve current column.
23013 (if (<= (current-column) (current-indentation))
23014 (org-indent-line-to column)
23015 (save-excursion (org-indent-line-to column))))
23016 ;; Align node property. Also preserve current column.
23017 (when (eq type 'node-property)
23018 (let ((column (current-column)))
23019 (org--align-node-property)
23020 (org-move-to-column column)))))))))
23022 (defun org-indent-region (start end)
23023 "Indent each non-blank line in the region.
23024 Called from a program, START and END specify the region to
23025 indent. The function will not indent contents of example blocks,
23026 verse blocks and export blocks as leading white spaces are
23027 assumed to be significant there."
23028 (interactive "r")
23029 (save-excursion
23030 (goto-char start)
23031 (skip-chars-forward " \r\t\n")
23032 (unless (eobp) (beginning-of-line))
23033 (let ((indent-to
23034 (lambda (ind pos)
23035 ;; Set IND as indentation for all lines between point and
23036 ;; POS. Blank lines are ignored. Leave point after POS
23037 ;; once done.
23038 (let ((limit (copy-marker pos)))
23039 (while (< (point) limit)
23040 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23041 (forward-line))
23042 (set-marker limit nil))))
23043 (end (copy-marker end)))
23044 (while (< (point) end)
23045 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23046 (let* ((element (org-element-at-point))
23047 (type (org-element-type element))
23048 (element-end (copy-marker (org-element-property :end element)))
23049 (ind (org--get-expected-indentation element nil)))
23050 (cond
23051 ((or (memq type '(paragraph table table-row))
23052 (not (or (org-element-property :contents-begin element)
23053 (memq type
23054 '(example-block export-block src-block)))))
23055 ;; Elements here are indented as a single block. Also
23056 ;; align node properties.
23057 (when (eq type 'node-property)
23058 (org--align-node-property)
23059 (beginning-of-line))
23060 (funcall indent-to ind (min element-end end)))
23062 ;; Elements in this category consist of three parts:
23063 ;; before the contents, the contents, and after the
23064 ;; contents. The contents are treated specially,
23065 ;; according to the element type, or not indented at
23066 ;; all. Other parts are indented as a single block.
23067 (let* ((post (copy-marker
23068 (org-element-property :post-affiliated element)))
23069 (cbeg
23070 (copy-marker
23071 (cond
23072 ((not (org-element-property :contents-begin element))
23073 ;; Fake contents for source blocks.
23074 (org-with-wide-buffer
23075 (goto-char post)
23076 (forward-line)
23077 (point)))
23078 ((memq type '(footnote-definition item plain-list))
23079 ;; Contents in these elements could start on
23080 ;; the same line as the beginning of the
23081 ;; element. Make sure we start indenting
23082 ;; from the second line.
23083 (org-with-wide-buffer
23084 (goto-char post)
23085 (end-of-line)
23086 (skip-chars-forward " \r\t\n")
23087 (if (eobp) (point) (line-beginning-position))))
23088 (t (org-element-property :contents-begin element)))))
23089 (cend (copy-marker
23090 (or (org-element-property :contents-end element)
23091 ;; Fake contents for source blocks.
23092 (org-with-wide-buffer
23093 (goto-char element-end)
23094 (skip-chars-backward " \r\t\n")
23095 (line-beginning-position)))
23096 t)))
23097 ;; Do not change items indentation individually as it
23098 ;; might break the list as a whole. On the other
23099 ;; hand, when at a plain list, indent it as a whole.
23100 (cond ((eq type 'plain-list)
23101 (let ((offset (- ind (org-get-indentation))))
23102 (unless (zerop offset)
23103 (indent-rigidly (org-element-property :begin element)
23104 (org-element-property :end element)
23105 offset))
23106 (goto-char cbeg)))
23107 ((eq type 'item) (goto-char cbeg))
23108 (t (funcall indent-to ind (min cbeg end))))
23109 (when (< (point) end)
23110 (cl-case type
23111 ((example-block export-block verse-block))
23112 (src-block
23113 ;; In a source block, indent source code
23114 ;; according to language major mode, but only if
23115 ;; `org-src-tab-acts-natively' is non-nil.
23116 (when (and (< (point) end) org-src-tab-acts-natively)
23117 (ignore-errors
23118 (org-babel-do-in-edit-buffer
23119 (indent-region (point-min) (point-max))))))
23120 (t (org-indent-region (point) (min cend end))))
23121 (goto-char (min cend end))
23122 (when (< (point) end)
23123 (funcall indent-to ind (min element-end end))))
23124 (set-marker post nil)
23125 (set-marker cbeg nil)
23126 (set-marker cend nil))))
23127 (set-marker element-end nil))))
23128 (set-marker end nil))))
23130 (defun org-indent-drawer ()
23131 "Indent the drawer at point."
23132 (interactive)
23133 (unless (save-excursion
23134 (beginning-of-line)
23135 (org-looking-at-p org-drawer-regexp))
23136 (user-error "Not at a drawer"))
23137 (let ((element (org-element-at-point)))
23138 (unless (memq (org-element-type element) '(drawer property-drawer))
23139 (user-error "Not at a drawer"))
23140 (org-with-wide-buffer
23141 (org-indent-region (org-element-property :begin element)
23142 (org-element-property :end element))))
23143 (message "Drawer at point indented"))
23145 (defun org-indent-block ()
23146 "Indent the block at point."
23147 (interactive)
23148 (unless (save-excursion
23149 (beginning-of-line)
23150 (let ((case-fold-search t))
23151 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23152 (user-error "Not at a block"))
23153 (let ((element (org-element-at-point)))
23154 (unless (memq (org-element-type element)
23155 '(comment-block center-block dynamic-block example-block
23156 export-block quote-block special-block
23157 src-block verse-block))
23158 (user-error "Not at a block"))
23159 (org-with-wide-buffer
23160 (org-indent-region (org-element-property :begin element)
23161 (org-element-property :end element))))
23162 (message "Block at point indented"))
23165 ;;; Filling
23167 ;; We use our own fill-paragraph and auto-fill functions.
23169 ;; `org-fill-paragraph' relies on adaptive filling and context
23170 ;; checking. Appropriate `fill-prefix' is computed with
23171 ;; `org-adaptive-fill-function'.
23173 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23174 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23175 ;; `org-adaptive-fill-function' value. Internally,
23176 ;; `org-comment-line-break-function' breaks the line.
23178 ;; `org-setup-filling' installs filling and auto-filling related
23179 ;; variables during `org-mode' initialization.
23181 (defvar org-element-paragraph-separate) ; org-element.el
23182 (defun org-setup-filling ()
23183 (require 'org-element)
23184 ;; Prevent auto-fill from inserting unwanted new items.
23185 (when (boundp 'fill-nobreak-predicate)
23186 (setq-local
23187 fill-nobreak-predicate
23188 (org-uniquify
23189 (append fill-nobreak-predicate
23190 '(org-fill-line-break-nobreak-p
23191 org-fill-paragraph-with-timestamp-nobreak-p)))))
23192 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23193 (setq-local paragraph-start paragraph-ending)
23194 (setq-local paragraph-separate paragraph-ending))
23195 (setq-local fill-paragraph-function 'org-fill-paragraph)
23196 (setq-local auto-fill-inhibit-regexp nil)
23197 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23198 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23199 (setq-local comment-line-break-function 'org-comment-line-break-function))
23201 (defun org-fill-line-break-nobreak-p ()
23202 "Non-nil when a new line at point would create an Org line break."
23203 (save-excursion
23204 (skip-chars-backward "[ \t]")
23205 (skip-chars-backward "\\\\")
23206 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23208 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23209 "Non-nil when a new line at point would split a timestamp."
23210 (and (org-at-timestamp-p t)
23211 (not (looking-at org-ts-regexp-both))))
23213 (declare-function message-in-body-p "message" ())
23214 (defvar orgtbl-line-start-regexp) ; From org-table.el
23215 (defun org-adaptive-fill-function ()
23216 "Compute a fill prefix for the current line.
23217 Return fill prefix, as a string, or nil if current line isn't
23218 meant to be filled. For convenience, if `adaptive-fill-regexp'
23219 matches in paragraphs or comments, use it."
23220 (catch 'exit
23221 (when (derived-mode-p 'message-mode)
23222 (save-excursion
23223 (beginning-of-line)
23224 (cond ((not (message-in-body-p)) (throw 'exit nil))
23225 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23226 ((looking-at message-cite-prefix-regexp)
23227 (throw 'exit (match-string-no-properties 0)))
23228 ((looking-at org-outline-regexp)
23229 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23230 (org-with-wide-buffer
23231 (unless (org-at-heading-p)
23232 (let* ((p (line-beginning-position))
23233 (element (save-excursion
23234 (beginning-of-line)
23235 (org-element-at-point)))
23236 (type (org-element-type element))
23237 (post-affiliated (org-element-property :post-affiliated element)))
23238 (unless (< p post-affiliated)
23239 (cl-case type
23240 (comment
23241 (save-excursion
23242 (beginning-of-line)
23243 (looking-at "[ \t]*")
23244 (concat (match-string 0) "# ")))
23245 (footnote-definition "")
23246 ((item plain-list)
23247 (make-string (org-list-item-body-column post-affiliated) ?\s))
23248 (paragraph
23249 ;; Fill prefix is usually the same as the current line,
23250 ;; unless the paragraph is at the beginning of an item.
23251 (let ((parent (org-element-property :parent element)))
23252 (save-excursion
23253 (beginning-of-line)
23254 (cond ((eq (org-element-type parent) 'item)
23255 (make-string (org-list-item-body-column
23256 (org-element-property :begin parent))
23257 ?\s))
23258 ((and adaptive-fill-regexp
23259 ;; Locally disable
23260 ;; `adaptive-fill-function' to let
23261 ;; `fill-context-prefix' handle
23262 ;; `adaptive-fill-regexp' variable.
23263 (let (adaptive-fill-function)
23264 (fill-context-prefix
23265 post-affiliated
23266 (org-element-property :end element)))))
23267 ((looking-at "[ \t]+") (match-string 0))
23268 (t "")))))
23269 (comment-block
23270 ;; Only fill contents if P is within block boundaries.
23271 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23272 (forward-line)
23273 (point)))
23274 (cend (save-excursion
23275 (goto-char (org-element-property :end element))
23276 (skip-chars-backward " \r\t\n")
23277 (line-beginning-position))))
23278 (when (and (>= p cbeg) (< p cend))
23279 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23280 (match-string 0)
23281 "")))))))))))
23283 (declare-function message-goto-body "message" ())
23284 (defvar message-cite-prefix-regexp) ; From message.el
23285 (defun org-fill-paragraph (&optional justify)
23286 "Fill element at point, when applicable.
23288 This function only applies to comment blocks, comments, example
23289 blocks and paragraphs. Also, as a special case, re-align table
23290 when point is at one.
23292 If JUSTIFY is non-nil (interactively, with prefix argument),
23293 justify as well. If `sentence-end-double-space' is non-nil, then
23294 period followed by one space does not end a sentence, so don't
23295 break a line there. The variable `fill-column' controls the
23296 width for filling.
23298 For convenience, when point is at a plain list, an item or
23299 a footnote definition, try to fill the first paragraph within."
23300 (interactive)
23301 (if (and (derived-mode-p 'message-mode)
23302 (or (not (message-in-body-p))
23303 (save-excursion (move-beginning-of-line 1)
23304 (looking-at message-cite-prefix-regexp))))
23305 ;; First ensure filling is correct in message-mode.
23306 (let ((fill-paragraph-function
23307 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23308 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23309 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23310 (paragraph-separate
23311 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23312 (fill-paragraph nil))
23313 (with-syntax-table org-mode-transpose-word-syntax-table
23314 ;; Move to end of line in order to get the first paragraph
23315 ;; within a plain list or a footnote definition.
23316 (let ((element (save-excursion
23317 (end-of-line)
23318 (or (ignore-errors (org-element-at-point))
23319 (user-error "An element cannot be parsed line %d"
23320 (line-number-at-pos (point)))))))
23321 ;; First check if point is in a blank line at the beginning of
23322 ;; the buffer. In that case, ignore filling.
23323 (cl-case (org-element-type element)
23324 ;; Use major mode filling function is src blocks.
23325 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23326 ;; Align Org tables, leave table.el tables as-is.
23327 (table-row (org-table-align) t)
23328 (table
23329 (when (eq (org-element-property :type element) 'org)
23330 (save-excursion
23331 (goto-char (org-element-property :post-affiliated element))
23332 (org-table-align)))
23334 (paragraph
23335 ;; Paragraphs may contain `line-break' type objects.
23336 (let ((beg (max (point-min)
23337 (org-element-property :contents-begin element)))
23338 (end (min (point-max)
23339 (org-element-property :contents-end element))))
23340 ;; Do nothing if point is at an affiliated keyword.
23341 (if (< (line-end-position) beg) t
23342 (when (derived-mode-p 'message-mode)
23343 ;; In `message-mode', do not fill following citation
23344 ;; in current paragraph nor text before message body.
23345 (let ((body-start (save-excursion (message-goto-body))))
23346 (when body-start (setq beg (max body-start beg))))
23347 (when (save-excursion
23348 (re-search-forward
23349 (concat "^" message-cite-prefix-regexp) end t))
23350 (setq end (match-beginning 0))))
23351 ;; Fill paragraph, taking line breaks into account.
23352 (save-excursion
23353 (goto-char beg)
23354 (let ((cuts (list beg)))
23355 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23356 (when (eq 'line-break
23357 (org-element-type
23358 (save-excursion (backward-char)
23359 (org-element-context))))
23360 (push (point) cuts)))
23361 (dolist (c (delq end cuts))
23362 (fill-region-as-paragraph c end justify)
23363 (setq end c))))
23364 t)))
23365 ;; Contents of `comment-block' type elements should be
23366 ;; filled as plain text, but only if point is within block
23367 ;; markers.
23368 (comment-block
23369 (let* ((case-fold-search t)
23370 (beg (save-excursion
23371 (goto-char (org-element-property :begin element))
23372 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23373 (forward-line)
23374 (point)))
23375 (end (save-excursion
23376 (goto-char (org-element-property :end element))
23377 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23378 (line-beginning-position))))
23379 (if (or (< (point) beg) (> (point) end)) t
23380 (fill-region-as-paragraph
23381 (save-excursion (end-of-line)
23382 (re-search-backward "^[ \t]*$" beg 'move)
23383 (line-beginning-position))
23384 (save-excursion (beginning-of-line)
23385 (re-search-forward "^[ \t]*$" end 'move)
23386 (line-beginning-position))
23387 justify))))
23388 ;; Fill comments.
23389 (comment
23390 (let ((begin (org-element-property :post-affiliated element))
23391 (end (org-element-property :end element)))
23392 (when (and (>= (point) begin) (<= (point) end))
23393 (let ((begin (save-excursion
23394 (end-of-line)
23395 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23396 (progn (forward-line) (point))
23397 begin)))
23398 (end (save-excursion
23399 (end-of-line)
23400 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23401 (1- (line-beginning-position))
23402 (skip-chars-backward " \r\t\n")
23403 (line-end-position)))))
23404 ;; Do not fill comments when at a blank line.
23405 (when (> end begin)
23406 (let ((fill-prefix
23407 (save-excursion
23408 (beginning-of-line)
23409 (looking-at "[ \t]*#")
23410 (let ((comment-prefix (match-string 0)))
23411 (goto-char (match-end 0))
23412 (if (looking-at adaptive-fill-regexp)
23413 (concat comment-prefix (match-string 0))
23414 (concat comment-prefix " "))))))
23415 (save-excursion
23416 (fill-region-as-paragraph begin end justify))))))
23418 ;; Ignore every other element.
23419 (otherwise t))))))
23421 (defun org-auto-fill-function ()
23422 "Auto-fill function."
23423 ;; Check if auto-filling is meaningful.
23424 (let ((fc (current-fill-column)))
23425 (when (and fc (> (current-column) fc))
23426 (let* ((fill-prefix (org-adaptive-fill-function))
23427 ;; Enforce empty fill prefix, if required. Otherwise, it
23428 ;; will be computed again.
23429 (adaptive-fill-mode (not (equal fill-prefix ""))))
23430 (when fill-prefix (do-auto-fill))))))
23432 (defun org-comment-line-break-function (&optional soft)
23433 "Break line at point and indent, continuing comment if within one.
23434 The inserted newline is marked hard if variable
23435 `use-hard-newlines' is true, unless optional argument SOFT is
23436 non-nil."
23437 (if soft (insert-and-inherit ?\n) (newline 1))
23438 (save-excursion (forward-char -1) (delete-horizontal-space))
23439 (delete-horizontal-space)
23440 (indent-to-left-margin)
23441 (insert-before-markers-and-inherit fill-prefix))
23444 ;;; Fixed Width Areas
23446 (defun org-toggle-fixed-width ()
23447 "Toggle fixed-width markup.
23449 Add or remove fixed-width markup on current line, whenever it
23450 makes sense. Return an error otherwise.
23452 If a region is active and if it contains only fixed-width areas
23453 or blank lines, remove all fixed-width markup in it. If the
23454 region contains anything else, convert all non-fixed-width lines
23455 to fixed-width ones.
23457 Blank lines at the end of the region are ignored unless the
23458 region only contains such lines."
23459 (interactive)
23460 (if (not (org-region-active-p))
23461 ;; No region:
23463 ;; Remove fixed width marker only in a fixed-with element.
23465 ;; Add fixed width maker in paragraphs, in blank lines after
23466 ;; elements or at the beginning of a headline or an inlinetask,
23467 ;; and before any one-line elements (e.g., a clock).
23468 (progn
23469 (beginning-of-line)
23470 (let* ((element (org-element-at-point))
23471 (type (org-element-type element)))
23472 (cond
23473 ((and (eq type 'fixed-width)
23474 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23475 (replace-match
23476 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23477 ((and (memq type '(babel-call clock comment diary-sexp headline
23478 horizontal-rule keyword paragraph
23479 planning))
23480 (<= (org-element-property :post-affiliated element) (point)))
23481 (skip-chars-forward " \t")
23482 (insert ": "))
23483 ((and (org-looking-at-p "[ \t]*$")
23484 (or (eq type 'inlinetask)
23485 (save-excursion
23486 (skip-chars-forward " \r\t\n")
23487 (<= (org-element-property :end element) (point)))))
23488 (delete-region (point) (line-end-position))
23489 (org-indent-line)
23490 (insert ": "))
23491 (t (user-error "Cannot insert a fixed-width line here")))))
23492 ;; Region active.
23493 (let* ((begin (save-excursion
23494 (goto-char (region-beginning))
23495 (line-beginning-position)))
23496 (end (copy-marker
23497 (save-excursion
23498 (goto-char (region-end))
23499 (unless (eolp) (beginning-of-line))
23500 (if (save-excursion (re-search-backward "\\S-" begin t))
23501 (progn (skip-chars-backward " \r\t\n") (point))
23502 (point)))))
23503 (all-fixed-width-p
23504 (catch 'not-all-p
23505 (save-excursion
23506 (goto-char begin)
23507 (skip-chars-forward " \r\t\n")
23508 (when (eobp) (throw 'not-all-p nil))
23509 (while (< (point) end)
23510 (let ((element (org-element-at-point)))
23511 (if (eq (org-element-type element) 'fixed-width)
23512 (goto-char (org-element-property :end element))
23513 (throw 'not-all-p nil))))
23514 t))))
23515 (if all-fixed-width-p
23516 (save-excursion
23517 (goto-char begin)
23518 (while (< (point) end)
23519 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23520 (replace-match
23521 "" nil nil nil
23522 (if (= (line-end-position) (match-end 0)) 0 1)))
23523 (forward-line)))
23524 (let ((min-ind (point-max)))
23525 ;; Find minimum indentation across all lines.
23526 (save-excursion
23527 (goto-char begin)
23528 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23529 (setq min-ind 0)
23530 (catch 'zerop
23531 (while (< (point) end)
23532 (unless (org-looking-at-p "[ \t]*$")
23533 (let ((ind (org-get-indentation)))
23534 (setq min-ind (min min-ind ind))
23535 (when (zerop ind) (throw 'zerop t))))
23536 (forward-line)))))
23537 ;; Loop over all lines and add fixed-width markup everywhere
23538 ;; but in fixed-width lines.
23539 (save-excursion
23540 (goto-char begin)
23541 (while (< (point) end)
23542 (cond
23543 ((org-at-heading-p)
23544 (insert ": ")
23545 (forward-line)
23546 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23547 (insert ":")
23548 (forward-line)))
23549 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23550 (let* ((element (org-element-at-point))
23551 (element-end (org-element-property :end element)))
23552 (if (eq (org-element-type element) 'fixed-width)
23553 (progn (goto-char element-end)
23554 (skip-chars-backward " \r\t\n")
23555 (forward-line))
23556 (let ((limit (min end element-end)))
23557 (while (< (point) limit)
23558 (org-move-to-column min-ind t)
23559 (insert ": ")
23560 (forward-line))))))
23562 (org-move-to-column min-ind t)
23563 (insert ": ")
23564 (forward-line)))))))
23565 (set-marker end nil))))
23568 ;;; Comments
23570 ;; Org comments syntax is quite complex. It requires the entire line
23571 ;; to be just a comment. Also, even with the right syntax at the
23572 ;; beginning of line, some some elements (i.e. verse-block or
23573 ;; example-block) don't accept comments. Usual Emacs comment commands
23574 ;; cannot cope with those requirements. Therefore, Org replaces them.
23576 ;; Org still relies on `comment-dwim', but cannot trust
23577 ;; `comment-only-p'. So, `comment-region-function' and
23578 ;; `uncomment-region-function' both point
23579 ;; to`org-comment-or-uncomment-region'. Eventually,
23580 ;; `org-insert-comment' takes care of insertion of comments at the
23581 ;; beginning of line.
23583 ;; `org-setup-comments-handling' install comments related variables
23584 ;; during `org-mode' initialization.
23586 (defun org-setup-comments-handling ()
23587 (interactive)
23588 (setq-local comment-use-syntax nil)
23589 (setq-local comment-start "# ")
23590 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23591 (setq-local comment-insert-comment-function 'org-insert-comment)
23592 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23593 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23595 (defun org-insert-comment ()
23596 "Insert an empty comment above current line.
23597 If the line is empty, insert comment at its beginning. When
23598 point is within a source block, comment according to the related
23599 major mode."
23600 (if (let ((element (org-element-at-point)))
23601 (and (eq (org-element-type element) 'src-block)
23602 (< (save-excursion
23603 (goto-char (org-element-property :post-affiliated element))
23604 (line-end-position))
23605 (point))
23606 (> (save-excursion
23607 (goto-char (org-element-property :end element))
23608 (skip-chars-backward " \r\t\n")
23609 (line-beginning-position))
23610 (point))))
23611 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23612 (beginning-of-line)
23613 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23614 (open-line 1))
23615 (org-indent-line)
23616 (insert "# ")))
23618 (defvar comment-empty-lines) ; From newcomment.el.
23619 (defun org-comment-or-uncomment-region (beg end &rest _)
23620 "Comment or uncomment each non-blank line in the region.
23621 Uncomment each non-blank line between BEG and END if it only
23622 contains commented lines. Otherwise, comment them. If region is
23623 strictly within a source block, use appropriate comment syntax."
23624 (if (let ((element (org-element-at-point)))
23625 (and (eq (org-element-type element) 'src-block)
23626 (< (save-excursion
23627 (goto-char (org-element-property :post-affiliated element))
23628 (line-end-position))
23629 beg)
23630 (>= (save-excursion
23631 (goto-char (org-element-property :end element))
23632 (skip-chars-backward " \r\t\n")
23633 (line-beginning-position))
23634 end)))
23635 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23636 (save-restriction
23637 ;; Restrict region
23638 (narrow-to-region (save-excursion (goto-char beg)
23639 (skip-chars-forward " \r\t\n" end)
23640 (line-beginning-position))
23641 (save-excursion (goto-char end)
23642 (skip-chars-backward " \r\t\n" beg)
23643 (line-end-position)))
23644 (let ((uncommentp
23645 ;; UNCOMMENTP is non-nil when every non blank line between
23646 ;; BEG and END is a comment.
23647 (save-excursion
23648 (goto-char (point-min))
23649 (while (and (not (eobp))
23650 (let ((element (org-element-at-point)))
23651 (and (eq (org-element-type element) 'comment)
23652 (goto-char (min (point-max)
23653 (org-element-property
23654 :end element)))))))
23655 (eobp))))
23656 (if uncommentp
23657 ;; Only blank lines and comments in region: uncomment it.
23658 (save-excursion
23659 (goto-char (point-min))
23660 (while (not (eobp))
23661 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23662 (replace-match "" nil nil nil 1))
23663 (forward-line)))
23664 ;; Comment each line in region.
23665 (let ((min-indent (point-max)))
23666 ;; First find the minimum indentation across all lines.
23667 (save-excursion
23668 (goto-char (point-min))
23669 (while (and (not (eobp)) (not (zerop min-indent)))
23670 (unless (looking-at "[ \t]*$")
23671 (setq min-indent (min min-indent (current-indentation))))
23672 (forward-line)))
23673 ;; Then loop over all lines.
23674 (save-excursion
23675 (goto-char (point-min))
23676 (while (not (eobp))
23677 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23678 ;; Don't get fooled by invisible text (e.g. link path)
23679 ;; when moving to column MIN-INDENT.
23680 (let ((buffer-invisibility-spec nil))
23681 (org-move-to-column min-indent t))
23682 (insert comment-start))
23683 (forward-line)))))))))
23685 (defun org-comment-dwim (_arg)
23686 "Call `comment-dwim' within a source edit buffer if needed."
23687 (interactive "*P")
23688 (if (org-in-src-block-p)
23689 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23690 (call-interactively 'comment-dwim)))
23693 ;;; Timestamps API
23695 ;; This section contains tools to operate on timestamp objects, as
23696 ;; returned by, e.g. `org-element-context'.
23698 (defun org-timestamp--to-internal-time (timestamp &optional end)
23699 "Encode TIMESTAMP object into Emacs internal time.
23700 Use end of date range or time range when END is non-nil."
23701 (apply #'encode-time
23702 (cons 0
23703 (mapcar
23704 (lambda (prop) (or (org-element-property prop timestamp) 0))
23705 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23706 '(:minute-start :hour-start :day-start :month-start
23707 :year-start))))))
23709 (defun org-timestamp-has-time-p (timestamp)
23710 "Non-nil when TIMESTAMP has a time specified."
23711 (org-element-property :hour-start timestamp))
23713 (defun org-timestamp-format (timestamp format &optional end utc)
23714 "Format a TIMESTAMP object into a string.
23716 FORMAT is a format specifier to be passed to
23717 `format-time-string'.
23719 When optional argument END is non-nil, use end of date-range or
23720 time-range, if possible.
23722 When optional argument UTC is non-nil, time will be expressed as
23723 Universal Time."
23724 (format-time-string
23725 format (org-timestamp--to-internal-time timestamp end) utc))
23727 (defun org-timestamp-split-range (timestamp &optional end)
23728 "Extract a TIMESTAMP object from a date or time range.
23730 END, when non-nil, means extract the end of the range.
23731 Otherwise, extract its start.
23733 Return a new timestamp object."
23734 (let ((type (org-element-property :type timestamp)))
23735 (if (memq type '(active inactive diary)) timestamp
23736 (let ((split-ts (org-element-copy timestamp)))
23737 ;; Set new type.
23738 (org-element-put-property
23739 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23740 ;; Copy start properties over end properties if END is
23741 ;; non-nil. Otherwise, copy end properties over `start' ones.
23742 (let ((p-alist '((:minute-start . :minute-end)
23743 (:hour-start . :hour-end)
23744 (:day-start . :day-end)
23745 (:month-start . :month-end)
23746 (:year-start . :year-end))))
23747 (dolist (p-cell p-alist)
23748 (org-element-put-property
23749 split-ts
23750 (funcall (if end #'car #'cdr) p-cell)
23751 (org-element-property
23752 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23753 ;; Eventually refresh `:raw-value'.
23754 (org-element-put-property split-ts :raw-value nil)
23755 (org-element-put-property
23756 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23758 (defun org-timestamp-translate (timestamp &optional boundary)
23759 "Translate TIMESTAMP object to custom format.
23761 Format string is defined in `org-time-stamp-custom-formats',
23762 which see.
23764 When optional argument BOUNDARY is non-nil, it is either the
23765 symbol `start' or `end'. In this case, only translate the
23766 starting or ending part of TIMESTAMP if it is a date or time
23767 range. Otherwise, translate both parts.
23769 Return timestamp as-is if `org-display-custom-times' is nil or if
23770 it has a `diary' type."
23771 (let ((type (org-element-property :type timestamp)))
23772 (if (or (not org-display-custom-times) (eq type 'diary))
23773 (org-element-interpret-data timestamp)
23774 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23775 org-time-stamp-custom-formats)))
23776 (if (and (not boundary) (memq type '(active-range inactive-range)))
23777 (concat (org-timestamp-format timestamp fmt)
23778 "--"
23779 (org-timestamp-format timestamp fmt t))
23780 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23784 ;;; Other stuff.
23786 (defvar reftex-docstruct-symbol)
23787 (defvar reftex-cite-format)
23788 (defvar org--rds)
23790 (defun org-reftex-citation ()
23791 "Use reftex-citation to insert a citation into the buffer.
23792 This looks for a line like
23794 #+BIBLIOGRAPHY: foo plain option:-d
23796 and derives from it that foo.bib is the bibliography file relevant
23797 for this document. It then installs the necessary environment for RefTeX
23798 to work in this buffer and calls `reftex-citation' to insert a citation
23799 into the buffer.
23801 Export of such citations to both LaTeX and HTML is handled by the contributed
23802 package ox-bibtex by Taru Karttunen."
23803 (interactive)
23804 (let ((reftex-docstruct-symbol 'org--rds)
23805 (reftex-cite-format "\\cite{%l}")
23806 org--rds bib)
23807 (save-excursion
23808 (save-restriction
23809 (widen)
23810 (let ((case-fold-search t)
23811 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23812 (if (not (save-excursion
23813 (or (re-search-forward re nil t)
23814 (re-search-backward re nil t))))
23815 (user-error "No bibliography defined in file")
23816 (setq bib (concat (match-string 1) ".bib")
23817 org--rds (list (list 'bib bib)))))))
23818 (call-interactively 'reftex-citation)))
23820 ;;;; Functions extending outline functionality
23822 (defun org-beginning-of-line (&optional arg)
23823 "Go to the beginning of the current line. If that is invisible, continue
23824 to a visible line beginning. This makes the function of C-a more intuitive.
23825 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23826 first attempt, and only move to after the tags when the cursor is already
23827 beyond the end of the headline."
23828 (interactive "P")
23829 (let ((pos (point))
23830 (special (if (consp org-special-ctrl-a/e)
23831 (car org-special-ctrl-a/e)
23832 org-special-ctrl-a/e))
23833 deactivate-mark refpos)
23834 (if (org-bound-and-true-p visual-line-mode)
23835 (beginning-of-visual-line 1)
23836 (beginning-of-line 1))
23837 (if (and arg (fboundp 'move-beginning-of-line))
23838 (call-interactively 'move-beginning-of-line)
23839 (unless (bobp)
23840 (backward-char 1)
23841 (if (org-truely-invisible-p)
23842 (while (and (not (bobp)) (org-truely-invisible-p))
23843 (backward-char 1)
23844 (beginning-of-line 1))
23845 (forward-char 1))))
23846 (when special
23847 (cond
23848 ((and (looking-at org-complex-heading-regexp)
23849 (eq (char-after (match-end 1)) ?\s))
23850 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23851 (point-at-eol)))
23852 (goto-char
23853 (if (eq special t)
23854 (cond ((> pos refpos) refpos)
23855 ((= pos (point)) refpos)
23856 (t (point)))
23857 (cond ((> pos (point)) (point))
23858 ((not (eq last-command this-command)) (point))
23859 (t refpos)))))
23860 ((org-at-item-p)
23861 ;; Being at an item and not looking at an the item means point
23862 ;; was previously moved to beginning of a visual line, which
23863 ;; doesn't contain the item. Therefore, do nothing special,
23864 ;; just stay here.
23865 (when (looking-at org-list-full-item-re)
23866 ;; Set special position at first white space character after
23867 ;; bullet, and check-box, if any.
23868 (let ((after-bullet
23869 (let ((box (match-end 3)))
23870 (if (not box) (match-end 1)
23871 (let ((after (char-after box)))
23872 (if (and after (= after ? )) (1+ box) box))))))
23873 ;; Special case: Move point to special position when
23874 ;; currently after it or at beginning of line.
23875 (if (eq special t)
23876 (when (or (> pos after-bullet) (= (point) pos))
23877 (goto-char after-bullet))
23878 ;; Reversed case: Move point to special position when
23879 ;; point was already at beginning of line and command is
23880 ;; repeated.
23881 (when (and (= (point) pos) (eq last-command this-command))
23882 (goto-char after-bullet))))))))
23883 (org-no-warnings
23884 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23885 (setq disable-point-adjustment
23886 (or (not (invisible-p (point)))
23887 (not (invisible-p (max (point-min) (1- (point))))))))
23889 (defun org-end-of-line (&optional arg)
23890 "Go to the end of the line.
23891 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23892 tags on the first attempt, and only move to after the tags when
23893 the cursor is already beyond the end of the headline."
23894 (interactive "P")
23895 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23896 org-special-ctrl-a/e))
23897 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23898 'end-of-visual-line)
23899 ((fboundp 'move-end-of-line) 'move-end-of-line)
23900 (t 'end-of-line)))
23901 deactivate-mark)
23902 (if (or (not special) arg) (call-interactively move-fun)
23903 (let* ((element (save-excursion (beginning-of-line)
23904 (org-element-at-point)))
23905 (type (org-element-type element)))
23906 (cond
23907 ((memq type '(headline inlinetask))
23908 (let ((pos (point)))
23909 (beginning-of-line 1)
23910 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23911 (if (eq special t)
23912 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23913 (goto-char (match-beginning 1))
23914 (goto-char (match-end 0)))
23915 (if (or (< pos (match-end 0))
23916 (not (eq this-command last-command)))
23917 (goto-char (match-end 0))
23918 (goto-char (match-beginning 1))))
23919 (call-interactively move-fun))))
23920 ((outline-invisible-p (line-end-position))
23921 ;; If element is hidden, `move-end-of-line' would put point
23922 ;; after it. Use `end-of-line' to stay on current line.
23923 (call-interactively 'end-of-line))
23924 (t (call-interactively move-fun)))))
23925 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23926 (setq disable-point-adjustment
23927 (or (not (invisible-p (point)))
23928 (not (invisible-p (max (point-min) (1- (point))))))))
23930 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23931 (define-key org-mode-map "\C-e" 'org-end-of-line)
23933 (defun org-backward-sentence (&optional _arg)
23934 "Go to beginning of sentence, or beginning of table field.
23935 This will call `backward-sentence' or `org-table-beginning-of-field',
23936 depending on context."
23937 (interactive)
23938 (let* ((element (org-element-at-point))
23939 (contents-begin (org-element-property :contents-begin element))
23940 (table (org-element-lineage element '(table) t)))
23941 (if (and table
23942 (> (point) contents-begin)
23943 (<= (point) (org-element-property :contents-end table)))
23944 (call-interactively #'org-table-beginning-of-field)
23945 (save-restriction
23946 (when (and contents-begin
23947 (< (point-min) contents-begin)
23948 (> (point) contents-begin))
23949 (narrow-to-region contents-begin
23950 (org-element-property :contents-end element)))
23951 (call-interactively #'backward-sentence)))))
23953 (defun org-forward-sentence (&optional _arg)
23954 "Go to end of sentence, or end of table field.
23955 This will call `forward-sentence' or `org-table-end-of-field',
23956 depending on context."
23957 (interactive)
23958 (let* ((element (org-element-at-point))
23959 (contents-end (org-element-property :contents-end element))
23960 (table (org-element-lineage element '(table) t)))
23961 (if (and table
23962 (>= (point) (org-element-property :contents-begin table))
23963 (< (point) contents-end))
23964 (call-interactively #'org-table-end-of-field)
23965 (save-restriction
23966 (when (and contents-end
23967 (> (point-max) contents-end)
23968 ;; Skip blank lines between elements.
23969 (< (org-element-property :end element)
23970 (save-excursion (goto-char contents-end)
23971 (skip-chars-forward " \r\t\n"))))
23972 (narrow-to-region (org-element-property :contents-begin element)
23973 contents-end))
23974 (call-interactively #'forward-sentence)))))
23976 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23977 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23979 (defun org-kill-line (&optional _arg)
23980 "Kill line, to tags or end of line."
23981 (interactive)
23982 (cond
23983 ((or (not org-special-ctrl-k)
23984 (bolp)
23985 (not (org-at-heading-p)))
23986 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23987 org-ctrl-k-protect-subtree
23988 (or (eq org-ctrl-k-protect-subtree 'error)
23989 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23990 (user-error "C-k aborted as it would kill a hidden subtree"))
23991 (call-interactively
23992 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23993 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23994 (kill-region (point) (match-beginning 1))
23995 (org-set-tags nil t))
23996 (t (kill-region (point) (point-at-eol)))))
23998 (define-key org-mode-map "\C-k" 'org-kill-line)
24000 (defun org-yank (&optional arg)
24001 "Yank. If the kill is a subtree, treat it specially.
24002 This command will look at the current kill and check if is a single
24003 subtree, or a series of subtrees[1]. If it passes the test, and if the
24004 cursor is at the beginning of a line or after the stars of a currently
24005 empty headline, then the yank is handled specially. How exactly depends
24006 on the value of the following variables, both set by default.
24008 `org-yank-folded-subtrees'
24009 When set, the subtree(s) will be folded after insertion, but only
24010 if doing so would now swallow text after the yanked text.
24012 `org-yank-adjusted-subtrees'
24013 When set, the subtree will be promoted or demoted in order to
24014 fit into the local outline tree structure, which means that the
24015 level will be adjusted so that it becomes the smaller one of the
24016 two *visible* surrounding headings.
24018 Any prefix to this command will cause `yank' to be called directly with
24019 no special treatment. In particular, a simple \\[universal-argument] prefix \
24020 will just
24021 plainly yank the text as it is.
24023 \[1] The test checks if the first non-white line is a heading
24024 and if there are no other headings with fewer stars."
24025 (interactive "P")
24026 (org-yank-generic 'yank arg))
24028 (defun org-yank-generic (command arg)
24029 "Perform some yank-like command.
24031 This function implements the behavior described in the `org-yank'
24032 documentation. However, it has been generalized to work for any
24033 interactive command with similar behavior."
24035 ;; pretend to be command COMMAND
24036 (setq this-command command)
24038 (if arg
24039 (call-interactively command)
24041 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24042 (and (org-kill-is-subtree-p)
24043 (or (bolp)
24044 (and (looking-at "[ \t]*$")
24045 (string-match
24046 "\\`\\*+\\'"
24047 (buffer-substring (point-at-bol) (point)))))))
24048 swallowp)
24049 (cond
24050 ((and subtreep org-yank-folded-subtrees)
24051 (let ((beg (point))
24052 end)
24053 (if (and subtreep org-yank-adjusted-subtrees)
24054 (org-paste-subtree nil nil 'for-yank)
24055 (call-interactively command))
24057 (setq end (point))
24058 (goto-char beg)
24059 (when (and (bolp) subtreep
24060 (not (setq swallowp
24061 (org-yank-folding-would-swallow-text beg end))))
24062 (org-with-limited-levels
24063 (or (looking-at org-outline-regexp)
24064 (re-search-forward org-outline-regexp-bol end t))
24065 (while (and (< (point) end) (looking-at org-outline-regexp))
24066 (outline-hide-subtree)
24067 (org-cycle-show-empty-lines 'folded)
24068 (condition-case nil
24069 (outline-forward-same-level 1)
24070 (error (goto-char end))))))
24071 (when swallowp
24072 (message
24073 "Inserted text not folded because that would swallow text"))
24075 (goto-char end)
24076 (skip-chars-forward " \t\n\r")
24077 (beginning-of-line 1)
24078 (push-mark beg 'nomsg)))
24079 ((and subtreep org-yank-adjusted-subtrees)
24080 (let ((beg (point-at-bol)))
24081 (org-paste-subtree nil nil 'for-yank)
24082 (push-mark beg 'nomsg)))
24084 (call-interactively command))))))
24086 (defun org-yank-folding-would-swallow-text (beg end)
24087 "Would hide-subtree at BEG swallow any text after END?"
24088 (let (level)
24089 (org-with-limited-levels
24090 (save-excursion
24091 (goto-char beg)
24092 (when (or (looking-at org-outline-regexp)
24093 (re-search-forward org-outline-regexp-bol end t))
24094 (setq level (org-outline-level)))
24095 (goto-char end)
24096 (skip-chars-forward " \t\r\n\v\f")
24097 (not (or (eobp)
24098 (and (bolp) (looking-at-p org-outline-regexp)
24099 (<= (org-outline-level) level))))))))
24101 (define-key org-mode-map "\C-y" 'org-yank)
24103 (defun org-truely-invisible-p ()
24104 "Check if point is at a character currently not visible.
24105 This version does not only check the character property, but also
24106 `visible-mode'."
24107 ;; Early versions of noutline don't have `outline-invisible-p'.
24108 (unless (org-bound-and-true-p visible-mode)
24109 (outline-invisible-p)))
24111 (defun org-invisible-p2 ()
24112 "Check if point is at a character currently not visible."
24113 (save-excursion
24114 (when (and (eolp) (not (bobp))) (backward-char 1))
24115 ;; Early versions of noutline don't have `outline-invisible-p'.
24116 (outline-invisible-p)))
24118 (defun org-back-to-heading (&optional invisible-ok)
24119 "Call `outline-back-to-heading', but provide a better error message."
24120 (condition-case nil
24121 (outline-back-to-heading invisible-ok)
24122 (error (error "Before first headline at position %d in buffer %s"
24123 (point) (current-buffer)))))
24125 (defun org-before-first-heading-p ()
24126 "Before first heading?"
24127 (save-excursion
24128 (end-of-line)
24129 (null (re-search-backward org-outline-regexp-bol nil t))))
24131 (defun org-at-heading-p (&optional ignored)
24132 (outline-on-heading-p t))
24133 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24134 ;;; warning was only added in Org 9.0, which should be taken into
24135 ;;; account when deciding when to remove the alias.
24136 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24138 (defun org-in-commented-heading-p (&optional no-inheritance)
24139 "Non-nil if point is under a commented heading.
24140 This function also checks ancestors of the current headline,
24141 unless optional argument NO-INHERITANCE is non-nil."
24142 (cond
24143 ((org-before-first-heading-p) nil)
24144 ((let ((headline (nth 4 (org-heading-components))))
24145 (and headline
24146 (let ((case-fold-search nil))
24147 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24148 headline)))))
24149 (no-inheritance nil)
24151 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24153 (defun org-at-comment-p nil
24154 "Is cursor in a commented line?"
24155 (save-excursion
24156 (save-match-data
24157 (beginning-of-line)
24158 (looking-at "^[ \t]*# "))))
24160 (defun org-at-drawer-p nil
24161 "Is cursor at a drawer keyword?"
24162 (save-excursion
24163 (move-beginning-of-line 1)
24164 (looking-at org-drawer-regexp)))
24166 (defun org-at-block-p nil
24167 "Is cursor at a block keyword?"
24168 (save-excursion
24169 (move-beginning-of-line 1)
24170 (looking-at org-block-regexp)))
24172 (defun org-point-at-end-of-empty-headline ()
24173 "If point is at the end of an empty headline, return t, else nil.
24174 If the heading only contains a TODO keyword, it is still still considered
24175 empty."
24176 (and (looking-at "[ \t]*$")
24177 (when org-todo-line-regexp
24178 (save-excursion
24179 (beginning-of-line 1)
24180 (let ((case-fold-search nil))
24181 (looking-at org-todo-line-regexp)
24182 (string= (match-string 3) ""))))))
24184 (defun org-at-heading-or-item-p ()
24185 (or (org-at-heading-p) (org-at-item-p)))
24187 (defun org-at-target-p ()
24188 (or (org-in-regexp org-radio-target-regexp)
24189 (org-in-regexp org-target-regexp)))
24190 ;; Compatibility alias with Org versions < 7.8.03
24191 (defalias 'org-on-target-p 'org-at-target-p)
24193 (defun org-up-heading-all (arg)
24194 "Move to the heading line of which the present line is a subheading.
24195 This function considers both visible and invisible heading lines.
24196 With argument, move up ARG levels."
24197 (if (fboundp 'outline-up-heading-all)
24198 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24199 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24201 (defun org-up-heading-safe ()
24202 "Move to the heading line of which the present line is a subheading.
24203 This version will not throw an error. It will return the level of the
24204 headline found, or nil if no higher level is found.
24206 Also, this function will be a lot faster than `outline-up-heading',
24207 because it relies on stars being the outline starters. This can really
24208 make a significant difference in outlines with very many siblings."
24209 (when (ignore-errors (org-back-to-heading t))
24210 (let ((level-up (1- (funcall outline-level))))
24211 (and (> level-up 0)
24212 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24213 (funcall outline-level)))))
24215 (defun org-first-sibling-p ()
24216 "Is this heading the first child of its parents?"
24217 (interactive)
24218 (let ((re org-outline-regexp-bol)
24219 level l)
24220 (unless (org-at-heading-p t)
24221 (user-error "Not at a heading"))
24222 (setq level (funcall outline-level))
24223 (save-excursion
24224 (if (not (re-search-backward re nil t))
24226 (setq l (funcall outline-level))
24227 (< l level)))))
24229 (defun org-goto-sibling (&optional previous)
24230 "Goto the next sibling, even if it is invisible.
24231 When PREVIOUS is set, go to the previous sibling instead. Returns t
24232 when a sibling was found. When none is found, return nil and don't
24233 move point."
24234 (let ((fun (if previous 're-search-backward 're-search-forward))
24235 (pos (point))
24236 (re org-outline-regexp-bol)
24237 level l)
24238 (when (ignore-errors (org-back-to-heading t))
24239 (setq level (funcall outline-level))
24240 (catch 'exit
24241 (or previous (forward-char 1))
24242 (while (funcall fun re nil t)
24243 (setq l (funcall outline-level))
24244 (when (< l level) (goto-char pos) (throw 'exit nil))
24245 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24246 (goto-char pos)
24247 nil))))
24249 (defun org-show-siblings ()
24250 "Show all siblings of the current headline."
24251 (save-excursion
24252 (while (org-goto-sibling) (org-flag-heading nil)))
24253 (save-excursion
24254 (while (org-goto-sibling 'previous)
24255 (org-flag-heading nil))))
24257 (defun org-goto-first-child ()
24258 "Goto the first child, even if it is invisible.
24259 Return t when a child was found. Otherwise don't move point and
24260 return nil."
24261 (let (level (pos (point)) (re org-outline-regexp-bol))
24262 (when (ignore-errors (org-back-to-heading t))
24263 (setq level (outline-level))
24264 (forward-char 1)
24265 (if (and (re-search-forward re nil t) (> (outline-level) level))
24266 (progn (goto-char (match-beginning 0)) t)
24267 (goto-char pos) nil))))
24269 (defun org-show-hidden-entry ()
24270 "Show an entry where even the heading is hidden."
24271 (save-excursion
24272 (org-show-entry)))
24274 (defun org-flag-heading (flag &optional entry)
24275 "Flag the current heading. FLAG non-nil means make invisible.
24276 When ENTRY is non-nil, show the entire entry."
24277 (save-excursion
24278 (org-back-to-heading t)
24279 ;; Check if we should show the entire entry
24280 (if entry
24281 (progn
24282 (org-show-entry)
24283 (save-excursion
24284 (and (outline-next-heading)
24285 (org-flag-heading nil))))
24286 (outline-flag-region (max (point-min) (1- (point)))
24287 (save-excursion (outline-end-of-heading) (point))
24288 flag))))
24290 (defun org-get-next-sibling ()
24291 "Move to next heading of the same level, and return point.
24292 If there is no such heading, return nil.
24293 This is like outline-next-sibling, but invisible headings are ok."
24294 (let ((level (funcall outline-level)))
24295 (outline-next-heading)
24296 (while (and (not (eobp)) (> (funcall outline-level) level))
24297 (outline-next-heading))
24298 (unless (or (eobp) (< (funcall outline-level) level))
24299 (point))))
24301 (defun org-get-last-sibling ()
24302 "Move to previous heading of the same level, and return point.
24303 If there is no such heading, return nil."
24304 (let ((opoint (point))
24305 (level (funcall outline-level)))
24306 (outline-previous-heading)
24307 (when (and (/= (point) opoint) (outline-on-heading-p t))
24308 (while (and (> (funcall outline-level) level)
24309 (not (bobp)))
24310 (outline-previous-heading))
24311 (unless (< (funcall outline-level) level)
24312 (point)))))
24314 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24315 "Goto to the end of a subtree."
24316 ;; This contains an exact copy of the original function, but it uses
24317 ;; `org-back-to-heading', to make it work also in invisible
24318 ;; trees. And is uses an invisible-ok argument.
24319 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24320 ;; Furthermore, when used inside Org, finding the end of a large subtree
24321 ;; with many children and grandchildren etc, this can be much faster
24322 ;; than the outline version.
24323 (org-back-to-heading invisible-ok)
24324 (let ((first t)
24325 (level (funcall outline-level)))
24326 (if (and (derived-mode-p 'org-mode) (< level 1000))
24327 ;; A true heading (not a plain list item), in Org-mode
24328 ;; This means we can easily find the end by looking
24329 ;; only for the right number of stars. Using a regexp to do
24330 ;; this is so much faster than using a Lisp loop.
24331 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24332 (forward-char 1)
24333 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24334 ;; something else, do it the slow way
24335 (while (and (not (eobp))
24336 (or first (> (funcall outline-level) level)))
24337 (setq first nil)
24338 (outline-next-heading)))
24339 (unless to-heading
24340 (when (memq (preceding-char) '(?\n ?\^M))
24341 ;; Go to end of line before heading
24342 (forward-char -1)
24343 (when (memq (preceding-char) '(?\n ?\^M))
24344 ;; leave blank line before heading
24345 (forward-char -1)))))
24346 (point))
24348 (defun org-end-of-meta-data (&optional full)
24349 "Skip planning line and properties drawer in current entry.
24350 When optional argument FULL is non-nil, also skip empty lines,
24351 clocking lines and regular drawers at the beginning of the
24352 entry."
24353 (org-back-to-heading t)
24354 (forward-line)
24355 (when (org-looking-at-p org-planning-line-re) (forward-line))
24356 (when (looking-at org-property-drawer-re)
24357 (goto-char (match-end 0))
24358 (forward-line))
24359 (when (and full (not (org-at-heading-p)))
24360 (catch 'exit
24361 (let ((end (save-excursion (outline-next-heading) (point)))
24362 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24363 (while (not (eobp))
24364 (cond ((org-looking-at-p org-drawer-regexp)
24365 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24366 (forward-line)
24367 (throw 'exit t)))
24368 ((org-looking-at-p re) (forward-line))
24369 (t (throw 'exit t))))))))
24371 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24372 "Move forward to the ARG'th subheading at same level as this one.
24373 Stop at the first and last subheadings of a superior heading.
24374 Normally this only looks at visible headings, but when INVISIBLE-OK is
24375 non-nil it will also look at invisible ones."
24376 (interactive "p")
24377 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24378 (if (and arg (< arg 0))
24379 (goto-char (point-min))
24380 (outline-next-heading))
24381 (org-at-heading-p)
24382 (let ((level (- (match-end 0) (match-beginning 0) 1))
24383 (f (if (and arg (< arg 0))
24384 're-search-backward
24385 're-search-forward))
24386 (count (if arg (abs arg) 1))
24387 (result (point)))
24388 (while (and (prog1 (> count 0)
24389 (forward-char (if (and arg (< arg 0)) -1 1)))
24390 (funcall f org-outline-regexp-bol nil 'move))
24391 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24392 (cond ((< l level) (setq count 0))
24393 ((and (= l level)
24394 (or invisible-ok
24395 (progn
24396 (goto-char (line-beginning-position))
24397 (not (outline-invisible-p)))))
24398 (setq count (1- count))
24399 (when (eq l level)
24400 (setq result (point)))))))
24401 (goto-char result))
24402 (beginning-of-line 1)))
24404 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24405 "Move backward to the ARG'th subheading at same level as this one.
24406 Stop at the first and last subheadings of a superior heading."
24407 (interactive "p")
24408 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24410 (defun org-next-visible-heading (arg)
24411 "Move to the next visible heading.
24413 This function wraps `outline-next-visible-heading' with
24414 `org-with-limited-levels' in order to skip over inline tasks and
24415 respect customization of `org-odd-levels-only'."
24416 (interactive "p")
24417 (org-with-limited-levels
24418 (outline-next-visible-heading arg)))
24420 (defun org-previous-visible-heading (arg)
24421 "Move to the next visible heading.
24423 This function wraps `outline-previous-visible-heading' with
24424 `org-with-limited-levels' in order to skip over inline tasks and
24425 respect customization of `org-odd-levels-only'."
24426 (interactive "p")
24427 (org-with-limited-levels
24428 (outline-previous-visible-heading arg)))
24430 (defun org-next-block (arg &optional backward block-regexp)
24431 "Jump to the next block.
24433 With a prefix argument ARG, jump forward ARG many blocks.
24435 When BACKWARD is non-nil, jump to the previous block.
24437 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24438 Match data is set according to this regexp when the function
24439 returns.
24441 Return point at beginning of the opening line of found block.
24442 Throw an error if no block is found."
24443 (interactive "p")
24444 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24445 (case-fold-search t)
24446 (search-fn (if backward #'re-search-backward #'re-search-forward))
24447 (count (or arg 1))
24448 (origin (point))
24449 last-element)
24450 (if backward (beginning-of-line) (end-of-line))
24451 (while (and (> count 0) (funcall search-fn re nil t))
24452 (let ((element (save-excursion
24453 (goto-char (match-beginning 0))
24454 (save-match-data (org-element-at-point)))))
24455 (when (and (memq (org-element-type element)
24456 '(center-block comment-block dynamic-block
24457 example-block export-block quote-block
24458 special-block src-block verse-block))
24459 (<= (match-beginning 0)
24460 (org-element-property :post-affiliated element)))
24461 (setq last-element element)
24462 (cl-decf count))))
24463 (if (= count 0)
24464 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24465 (save-match-data (org-show-context)))
24466 (goto-char origin)
24467 (user-error "No %s code blocks" (if backward "previous" "further")))))
24469 (defun org-previous-block (arg &optional block-regexp)
24470 "Jump to the previous block.
24471 With a prefix argument ARG, jump backward ARG many source blocks.
24472 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24473 (interactive "p")
24474 (org-next-block arg t block-regexp))
24476 (defun org-forward-paragraph ()
24477 "Move forward to beginning of next paragraph or equivalent.
24479 The function moves point to the beginning of the next visible
24480 structural element, which can be a paragraph, a table, a list
24481 item, etc. It also provides some special moves for convenience:
24483 - On an affiliated keyword, jump to the beginning of the
24484 relative element.
24485 - On an item or a footnote definition, move to the second
24486 element inside, if any.
24487 - On a table or a property drawer, jump after it.
24488 - On a verse or source block, stop after blank lines."
24489 (interactive)
24490 (when (eobp) (user-error "Cannot move further down"))
24491 (let* ((deactivate-mark nil)
24492 (element (org-element-at-point))
24493 (type (org-element-type element))
24494 (post-affiliated (org-element-property :post-affiliated element))
24495 (contents-begin (org-element-property :contents-begin element))
24496 (contents-end (org-element-property :contents-end element))
24497 (end (let ((end (org-element-property :end element)) (parent element))
24498 (while (and (setq parent (org-element-property :parent parent))
24499 (= (org-element-property :contents-end parent) end))
24500 (setq end (org-element-property :end parent)))
24501 end)))
24502 (cond ((not element)
24503 (skip-chars-forward " \r\t\n")
24504 (or (eobp) (beginning-of-line)))
24505 ;; On affiliated keywords, move to element's beginning.
24506 ((< (point) post-affiliated)
24507 (goto-char post-affiliated))
24508 ;; At a table row, move to the end of the table. Similarly,
24509 ;; at a node property, move to the end of the property
24510 ;; drawer.
24511 ((memq type '(node-property table-row))
24512 (goto-char (org-element-property
24513 :end (org-element-property :parent element))))
24514 ((memq type '(property-drawer table)) (goto-char end))
24515 ;; Consider blank lines as separators in verse and source
24516 ;; blocks to ease editing.
24517 ((memq type '(src-block verse-block))
24518 (when (eq type 'src-block)
24519 (setq contents-end
24520 (save-excursion (goto-char end)
24521 (skip-chars-backward " \r\t\n")
24522 (line-beginning-position))))
24523 (beginning-of-line)
24524 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24525 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24526 (goto-char end)
24527 (skip-chars-forward " \r\t\n")
24528 (if (= (point) contents-end) (goto-char end)
24529 (beginning-of-line))))
24530 ;; With no contents, just skip element.
24531 ((not contents-begin) (goto-char end))
24532 ;; If contents are invisible, skip the element altogether.
24533 ((outline-invisible-p (line-end-position))
24534 (cl-case type
24535 (headline
24536 (org-with-limited-levels (outline-next-visible-heading 1)))
24537 ;; At a plain list, make sure we move to the next item
24538 ;; instead of skipping the whole list.
24539 (plain-list (forward-char)
24540 (org-forward-paragraph))
24541 (otherwise (goto-char end))))
24542 ((>= (point) contents-end) (goto-char end))
24543 ((>= (point) contents-begin)
24544 ;; This can only happen on paragraphs and plain lists.
24545 (cl-case type
24546 (paragraph (goto-char end))
24547 ;; At a plain list, try to move to second element in
24548 ;; first item, if possible.
24549 (plain-list (end-of-line)
24550 (org-forward-paragraph))))
24551 ;; When contents start on the middle of a line (e.g. in
24552 ;; items and footnote definitions), try to reach first
24553 ;; element starting after current line.
24554 ((> (line-end-position) contents-begin)
24555 (end-of-line)
24556 (org-forward-paragraph))
24557 (t (goto-char contents-begin)))))
24559 (defun org-backward-paragraph ()
24560 "Move backward to start of previous paragraph or equivalent.
24562 The function moves point to the beginning of the current
24563 structural element, which can be a paragraph, a table, a list
24564 item, etc., or to the beginning of the previous visible one if
24565 point is already there. It also provides some special moves for
24566 convenience:
24568 - On an affiliated keyword, jump to the first one.
24569 - On a table or a property drawer, move to its beginning.
24570 - On a verse or source block, stop before blank lines."
24571 (interactive)
24572 (when (bobp) (user-error "Cannot move further up"))
24573 (let* ((deactivate-mark nil)
24574 (element (org-element-at-point))
24575 (type (org-element-type element))
24576 (contents-begin (org-element-property :contents-begin element))
24577 (contents-end (org-element-property :contents-end element))
24578 (post-affiliated (org-element-property :post-affiliated element))
24579 (begin (org-element-property :begin element)))
24580 (cond
24581 ((not element) (goto-char (point-min)))
24582 ((= (point) begin)
24583 (backward-char)
24584 (org-backward-paragraph))
24585 ((<= (point) post-affiliated) (goto-char begin))
24586 ((memq type '(node-property table-row))
24587 (goto-char (org-element-property
24588 :post-affiliated (org-element-property :parent element))))
24589 ((memq type '(property-drawer table)) (goto-char begin))
24590 ((memq type '(src-block verse-block))
24591 (when (eq type 'src-block)
24592 (setq contents-begin
24593 (save-excursion (goto-char begin) (forward-line) (point))))
24594 (if (= (point) contents-begin) (goto-char post-affiliated)
24595 ;; Inside a verse block, see blank lines as paragraph
24596 ;; separators.
24597 (let ((origin (point)))
24598 (skip-chars-backward " \r\t\n" contents-begin)
24599 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24600 (skip-chars-forward " \r\t\n" origin)
24601 (if (= (point) origin) (goto-char contents-begin)
24602 (beginning-of-line))))))
24603 ((not contents-begin) (goto-char (or post-affiliated begin)))
24604 ((eq type 'paragraph)
24605 (goto-char contents-begin)
24606 ;; When at first paragraph in an item or a footnote definition,
24607 ;; move directly to beginning of line.
24608 (let ((parent-contents
24609 (org-element-property
24610 :contents-begin (org-element-property :parent element))))
24611 (when (and parent-contents (= parent-contents contents-begin))
24612 (beginning-of-line))))
24613 ;; At the end of a greater element, move to the beginning of the
24614 ;; last element within.
24615 ((>= (point) contents-end)
24616 (goto-char (1- contents-end))
24617 (org-backward-paragraph))
24618 (t (goto-char (or post-affiliated begin))))
24619 ;; Ensure we never leave point invisible.
24620 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24622 (defun org-forward-element ()
24623 "Move forward by one element.
24624 Move to the next element at the same level, when possible."
24625 (interactive)
24626 (cond ((eobp) (user-error "Cannot move further down"))
24627 ((org-with-limited-levels (org-at-heading-p))
24628 (let ((origin (point)))
24629 (goto-char (org-end-of-subtree nil t))
24630 (unless (org-with-limited-levels (org-at-heading-p))
24631 (goto-char origin)
24632 (user-error "Cannot move further down"))))
24634 (let* ((elem (org-element-at-point))
24635 (end (org-element-property :end elem))
24636 (parent (org-element-property :parent elem)))
24637 (cond ((and parent (= (org-element-property :contents-end parent) end))
24638 (goto-char (org-element-property :end parent)))
24639 ((integer-or-marker-p end) (goto-char end))
24640 (t (message "No element at point")))))))
24642 (defun org-backward-element ()
24643 "Move backward by one element.
24644 Move to the previous element at the same level, when possible."
24645 (interactive)
24646 (cond ((bobp) (user-error "Cannot move further up"))
24647 ((org-with-limited-levels (org-at-heading-p))
24648 ;; At a headline, move to the previous one, if any, or stay
24649 ;; here.
24650 (let ((origin (point)))
24651 (org-with-limited-levels (org-backward-heading-same-level 1))
24652 ;; When current headline has no sibling above, move to its
24653 ;; parent.
24654 (when (= (point) origin)
24655 (or (org-with-limited-levels (org-up-heading-safe))
24656 (progn (goto-char origin)
24657 (user-error "Cannot move further up"))))))
24659 (let* ((elem (org-element-at-point))
24660 (beg (org-element-property :begin elem)))
24661 (cond
24662 ;; Move to beginning of current element if point isn't
24663 ;; there already.
24664 ((null beg) (message "No element at point"))
24665 ((/= (point) beg) (goto-char beg))
24666 (t (goto-char beg)
24667 (skip-chars-backward " \r\t\n")
24668 (unless (bobp)
24669 (let ((prev (org-element-at-point)))
24670 (goto-char (org-element-property :begin prev))
24671 (while (and (setq prev (org-element-property :parent prev))
24672 (<= (org-element-property :end prev) beg))
24673 (goto-char (org-element-property :begin prev)))))))))))
24675 (defun org-up-element ()
24676 "Move to upper element."
24677 (interactive)
24678 (if (org-with-limited-levels (org-at-heading-p))
24679 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24680 (let* ((elem (org-element-at-point))
24681 (parent (org-element-property :parent elem)))
24682 (if parent (goto-char (org-element-property :begin parent))
24683 (if (org-with-limited-levels (org-before-first-heading-p))
24684 (user-error "No surrounding element")
24685 (org-with-limited-levels (org-back-to-heading)))))))
24687 (defvar org-element-greater-elements)
24688 (defun org-down-element ()
24689 "Move to inner element."
24690 (interactive)
24691 (let ((element (org-element-at-point)))
24692 (cond
24693 ((memq (org-element-type element) '(plain-list table))
24694 (goto-char (org-element-property :contents-begin element))
24695 (forward-char))
24696 ((memq (org-element-type element) org-element-greater-elements)
24697 ;; If contents are hidden, first disclose them.
24698 (when (outline-invisible-p (line-end-position)) (org-cycle))
24699 (goto-char (or (org-element-property :contents-begin element)
24700 (user-error "No content for this element"))))
24701 (t (user-error "No inner element")))))
24703 (defun org-drag-element-backward ()
24704 "Move backward element at point."
24705 (interactive)
24706 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24707 (let* ((elem (org-element-at-point))
24708 (prev-elem
24709 (save-excursion
24710 (goto-char (org-element-property :begin elem))
24711 (skip-chars-backward " \r\t\n")
24712 (unless (bobp)
24713 (let* ((beg (org-element-property :begin elem))
24714 (prev (org-element-at-point))
24715 (up prev))
24716 (while (and (setq up (org-element-property :parent up))
24717 (<= (org-element-property :end up) beg))
24718 (setq prev up))
24719 prev)))))
24720 ;; Error out if no previous element or previous element is
24721 ;; a parent of the current one.
24722 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24723 (user-error "Cannot drag element backward")
24724 (let ((pos (point)))
24725 (org-element-swap-A-B prev-elem elem)
24726 (goto-char (+ (org-element-property :begin prev-elem)
24727 (- pos (org-element-property :begin elem)))))))))
24729 (defun org-drag-element-forward ()
24730 "Move forward element at point."
24731 (interactive)
24732 (let* ((pos (point))
24733 (elem (org-element-at-point)))
24734 (when (= (point-max) (org-element-property :end elem))
24735 (user-error "Cannot drag element forward"))
24736 (goto-char (org-element-property :end elem))
24737 (let ((next-elem (org-element-at-point)))
24738 (when (or (org-element-nested-p elem next-elem)
24739 (and (eq (org-element-type next-elem) 'headline)
24740 (not (eq (org-element-type elem) 'headline))))
24741 (goto-char pos)
24742 (user-error "Cannot drag element forward"))
24743 ;; Compute new position of point: it's shifted by NEXT-ELEM
24744 ;; body's length (without final blanks) and by the length of
24745 ;; blanks between ELEM and NEXT-ELEM.
24746 (let ((size-next (- (save-excursion
24747 (goto-char (org-element-property :end next-elem))
24748 (skip-chars-backward " \r\t\n")
24749 (forward-line)
24750 ;; Small correction if buffer doesn't end
24751 ;; with a newline character.
24752 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24753 (org-element-property :begin next-elem)))
24754 (size-blank (- (org-element-property :end elem)
24755 (save-excursion
24756 (goto-char (org-element-property :end elem))
24757 (skip-chars-backward " \r\t\n")
24758 (forward-line)
24759 (point)))))
24760 (org-element-swap-A-B elem next-elem)
24761 (goto-char (+ pos size-next size-blank))))))
24763 (defun org-drag-line-forward (arg)
24764 "Drag the line at point ARG lines forward."
24765 (interactive "p")
24766 (dotimes (_ (abs arg))
24767 (let ((c (current-column)))
24768 (if (< 0 arg)
24769 (progn
24770 (beginning-of-line 2)
24771 (transpose-lines 1)
24772 (beginning-of-line 0))
24773 (transpose-lines 1)
24774 (beginning-of-line -1))
24775 (org-move-to-column c))))
24777 (defun org-drag-line-backward (arg)
24778 "Drag the line at point ARG lines backward."
24779 (interactive "p")
24780 (org-drag-line-forward (- arg)))
24782 (defun org-mark-element ()
24783 "Put point at beginning of this element, mark at end.
24785 Interactively, if this command is repeated or (in Transient Mark
24786 mode) if the mark is active, it marks the next element after the
24787 ones already marked."
24788 (interactive)
24789 (let (deactivate-mark)
24790 (if (and (org-called-interactively-p 'any)
24791 (or (and (eq last-command this-command) (mark t))
24792 (and transient-mark-mode mark-active)))
24793 (set-mark
24794 (save-excursion
24795 (goto-char (mark))
24796 (goto-char (org-element-property :end (org-element-at-point)))))
24797 (let ((element (org-element-at-point)))
24798 (end-of-line)
24799 (push-mark (org-element-property :end element) t t)
24800 (goto-char (org-element-property :begin element))))))
24802 (defun org-narrow-to-element ()
24803 "Narrow buffer to current element."
24804 (interactive)
24805 (let ((elem (org-element-at-point)))
24806 (cond
24807 ((eq (car elem) 'headline)
24808 (narrow-to-region
24809 (org-element-property :begin elem)
24810 (org-element-property :end elem)))
24811 ((memq (car elem) org-element-greater-elements)
24812 (narrow-to-region
24813 (org-element-property :contents-begin elem)
24814 (org-element-property :contents-end elem)))
24816 (narrow-to-region
24817 (org-element-property :begin elem)
24818 (org-element-property :end elem))))))
24820 (defun org-transpose-element ()
24821 "Transpose current and previous elements, keeping blank lines between.
24822 Point is moved after both elements."
24823 (interactive)
24824 (org-skip-whitespace)
24825 (let ((end (org-element-property :end (org-element-at-point))))
24826 (org-drag-element-backward)
24827 (goto-char end)))
24829 (defun org-unindent-buffer ()
24830 "Un-indent the visible part of the buffer.
24831 Relative indentation (between items, inside blocks, etc.) isn't
24832 modified."
24833 (interactive)
24834 (unless (eq major-mode 'org-mode)
24835 (user-error "Cannot un-indent a buffer not in Org mode"))
24836 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24837 (unindent-tree
24838 (lambda (contents)
24839 (dolist (element (reverse contents))
24840 (if (memq (org-element-type element) '(headline section))
24841 (funcall unindent-tree (org-element-contents element))
24842 (save-excursion
24843 (save-restriction
24844 (narrow-to-region
24845 (org-element-property :begin element)
24846 (org-element-property :end element))
24847 (org-do-remove-indentation))))))))
24848 (funcall unindent-tree (org-element-contents parse-tree))))
24850 (defun org-show-children (&optional level)
24851 "Show all direct subheadings of this heading.
24852 Prefix arg LEVEL is how many levels below the current level
24853 should be shown. Default is enough to cause the following
24854 heading to appear."
24855 (interactive "p")
24856 ;; If `orgstruct-mode' is active, use the slower version.
24857 (if orgstruct-mode (call-interactively #'outline-show-children)
24858 (save-excursion
24859 (org-back-to-heading t)
24860 (let* ((current-level (funcall outline-level))
24861 (max-level (org-get-valid-level
24862 current-level
24863 (if level (prefix-numeric-value level) 1)))
24864 (end (save-excursion (org-end-of-subtree t t)))
24865 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24866 (past-first-child nil)
24867 ;; Make sure to skip inlinetasks.
24868 (re (format regexp-fmt
24869 current-level
24870 (cond
24871 ((not (featurep 'org-inlinetask)) "")
24872 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24874 (t (1- org-inlinetask-min-level))))))
24875 ;; Display parent heading.
24876 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24877 (forward-line)
24878 ;; Display children. First child may be deeper than expected
24879 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24880 ;; MAX-LEVEL accordingly.
24881 (while (re-search-forward re end t)
24882 (unless past-first-child
24883 (setq re (format regexp-fmt
24884 current-level
24885 (max (funcall outline-level) max-level)))
24886 (setq past-first-child t))
24887 (outline-flag-region
24888 (line-end-position 0) (line-end-position) nil))))))
24890 (defun org-show-subtree ()
24891 "Show everything after this heading at deeper levels."
24892 (interactive)
24893 (outline-flag-region
24894 (point)
24895 (save-excursion
24896 (org-end-of-subtree t t))
24897 nil))
24899 (defun org-show-entry ()
24900 "Show the body directly following this heading.
24901 Show the heading too, if it is currently invisible."
24902 (interactive)
24903 (save-excursion
24904 (ignore-errors
24905 (org-back-to-heading t)
24906 (outline-flag-region
24907 (max (point-min) (1- (point)))
24908 (save-excursion
24909 (if (re-search-forward
24910 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24911 (match-beginning 1)
24912 (point-max)))
24913 nil)
24914 (org-cycle-hide-drawers 'children))))
24916 (defun org-make-options-regexp (kwds &optional extra)
24917 "Make a regular expression for keyword lines.
24918 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24919 when non-nil, is a regexp matching keywords names."
24920 (concat "^[ \t]*#\\+\\("
24921 (regexp-opt kwds)
24922 (and extra (concat (and kwds "\\|") extra))
24923 "\\):[ \t]*\\(.*\\)"))
24925 ;;;; Integration with and fixes for other packages
24927 ;;; Imenu support
24929 (defvar-local org-imenu-markers nil
24930 "All markers currently used by Imenu.")
24932 (defun org-imenu-new-marker (&optional pos)
24933 "Return a new marker for use by Imenu, and remember the marker."
24934 (let ((m (make-marker)))
24935 (move-marker m (or pos (point)))
24936 (push m org-imenu-markers)
24939 (defun org-imenu-get-tree ()
24940 "Produce the index for Imenu."
24941 (dolist (x org-imenu-markers) (move-marker x nil))
24942 (setq org-imenu-markers nil)
24943 (let* ((n org-imenu-depth)
24944 (re (concat "^" (org-get-limited-outline-regexp)))
24945 (subs (make-vector (1+ n) nil))
24946 (last-level 0)
24947 m level head0 head)
24948 (save-excursion
24949 (save-restriction
24950 (widen)
24951 (goto-char (point-max))
24952 (while (re-search-backward re nil t)
24953 (setq level (org-reduced-level (funcall outline-level)))
24954 (when (and (<= level n)
24955 (looking-at org-complex-heading-regexp)
24956 (setq head0 (org-match-string-no-properties 4)))
24957 (setq head (org-link-display-format head0)
24958 m (org-imenu-new-marker))
24959 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24960 (if (>= level last-level)
24961 (push (cons head m) (aref subs level))
24962 (push (cons head (aref subs (1+ level))) (aref subs level))
24963 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24964 (setq last-level level)))))
24965 (aref subs 1)))
24967 (eval-after-load "imenu"
24968 '(progn
24969 (add-hook 'imenu-after-jump-hook
24970 (lambda ()
24971 (when (derived-mode-p 'org-mode)
24972 (org-show-context 'org-goto))))))
24974 (defun org-link-display-format (link)
24975 "Replace a link with its the description.
24976 If there is no description, use the link target."
24977 (save-match-data
24978 (if (string-match org-bracket-link-analytic-regexp link)
24979 (replace-match (if (match-end 5)
24980 (match-string 5 link)
24981 (concat (match-string 1 link)
24982 (match-string 3 link)))
24983 nil t link)
24984 link)))
24986 (defun org-toggle-link-display ()
24987 "Toggle the literal or descriptive display of links."
24988 (interactive)
24989 (if org-descriptive-links
24990 (progn (org-remove-from-invisibility-spec '(org-link))
24991 (org-restart-font-lock)
24992 (setq org-descriptive-links nil))
24993 (progn (add-to-invisibility-spec '(org-link))
24994 (org-restart-font-lock)
24995 (setq org-descriptive-links t))))
24997 ;; Speedbar support
24999 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25000 "Overlay marking the agenda restriction line in speedbar.")
25001 (overlay-put org-speedbar-restriction-lock-overlay
25002 'face 'org-agenda-restriction-lock)
25003 (overlay-put org-speedbar-restriction-lock-overlay
25004 'help-echo "Agendas are currently limited to this item.")
25005 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25007 (defun org-speedbar-set-agenda-restriction ()
25008 "Restrict future agenda commands to the location at point in speedbar.
25009 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25010 (interactive)
25011 (require 'org-agenda)
25012 (let (p m tp np dir txt)
25013 (cond
25014 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25015 'org-imenu t))
25016 (setq m (get-text-property p 'org-imenu-marker))
25017 (with-current-buffer (marker-buffer m)
25018 (goto-char m)
25019 (org-agenda-set-restriction-lock 'subtree)))
25020 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25021 'speedbar-function 'speedbar-find-file))
25022 (setq tp (previous-single-property-change
25023 (1+ p) 'speedbar-function)
25024 np (next-single-property-change
25025 tp 'speedbar-function)
25026 dir (speedbar-line-directory)
25027 txt (buffer-substring-no-properties (or tp (point-min))
25028 (or np (point-max))))
25029 (with-current-buffer (find-file-noselect
25030 (let ((default-directory dir))
25031 (expand-file-name txt)))
25032 (unless (derived-mode-p 'org-mode)
25033 (user-error "Cannot restrict to non-Org-mode file"))
25034 (org-agenda-set-restriction-lock 'file)))
25035 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25036 (move-overlay org-speedbar-restriction-lock-overlay
25037 (point-at-bol) (point-at-eol))
25038 (setq current-prefix-arg nil)
25039 (org-agenda-maybe-redo)))
25041 (defvar speedbar-file-key-map)
25042 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25043 (eval-after-load "speedbar"
25044 '(progn
25045 (speedbar-add-supported-extension ".org")
25046 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25047 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25048 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25049 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25050 (add-hook 'speedbar-visiting-tag-hook
25051 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25053 ;;; Fixes and Hacks for problems with other packages
25055 (defun org--flyspell-object-check-p (element)
25056 "Non-nil when Flyspell can check object at point.
25057 ELEMENT is the element at point."
25058 (let ((object (save-excursion
25059 (when (org-looking-at-p "\\>") (backward-char))
25060 (org-element-context element))))
25061 (cl-case (org-element-type object)
25062 ;; Prevent checks in links due to keybinding conflict with
25063 ;; Flyspell.
25064 ((code entity export-snippet inline-babel-call
25065 inline-src-block line-break latex-fragment link macro
25066 statistics-cookie target timestamp verbatim)
25067 nil)
25068 (footnote-reference
25069 ;; Only in inline footnotes, within the definition.
25070 (and (eq (org-element-property :type object) 'inline)
25071 (< (save-excursion
25072 (goto-char (org-element-property :begin object))
25073 (search-forward ":" nil t 2))
25074 (point))))
25075 (otherwise t))))
25077 (defun org-mode-flyspell-verify ()
25078 "Function used for `flyspell-generic-check-word-predicate'."
25079 (if (org-at-heading-p)
25080 ;; At a headline or an inlinetask, check title only. This is
25081 ;; faster than relying on `org-element-at-point'.
25082 (and (save-excursion (beginning-of-line)
25083 (and (let ((case-fold-search t))
25084 (not (looking-at "\\*+ END[ \t]*$")))
25085 (looking-at org-complex-heading-regexp)))
25086 (match-beginning 4)
25087 (>= (point) (match-beginning 4))
25088 (or (not (match-beginning 5))
25089 (< (point) (match-beginning 5))))
25090 (let* ((element (org-element-at-point))
25091 (post-affiliated (org-element-property :post-affiliated element)))
25092 (cond
25093 ;; Ignore checks in all affiliated keywords but captions.
25094 ((< (point) post-affiliated)
25095 (and (save-excursion
25096 (beginning-of-line)
25097 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25098 (> (point) (match-end 0))
25099 (org--flyspell-object-check-p element)))
25100 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25101 ((let ((log (org-log-into-drawer)))
25102 (and log
25103 (let ((drawer (org-element-lineage element '(drawer))))
25104 (and drawer
25105 (eq (compare-strings
25106 log nil nil
25107 (org-element-property :drawer-name drawer) nil nil t)
25108 t)))))
25109 nil)
25111 (cl-case (org-element-type element)
25112 ((comment quote-section) t)
25113 (comment-block
25114 ;; Allow checks between block markers, not on them.
25115 (and (> (line-beginning-position) post-affiliated)
25116 (save-excursion
25117 (end-of-line)
25118 (skip-chars-forward " \r\t\n")
25119 (< (point) (org-element-property :end element)))))
25120 ;; Arbitrary list of keywords where checks are meaningful.
25121 ;; Make sure point is on the value part of the element.
25122 (keyword
25123 (and (member (org-element-property :key element)
25124 '("DESCRIPTION" "TITLE"))
25125 (save-excursion
25126 (search-backward ":" (line-beginning-position) t))))
25127 ;; Check is globally allowed in paragraphs verse blocks and
25128 ;; table rows (after affiliated keywords) but some objects
25129 ;; must not be affected.
25130 ((paragraph table-row verse-block)
25131 (let ((cbeg (org-element-property :contents-begin element))
25132 (cend (org-element-property :contents-end element)))
25133 (and cbeg (>= (point) cbeg) (< (point) cend)
25134 (org--flyspell-object-check-p element))))))))))
25135 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25137 (defun org-remove-flyspell-overlays-in (beg end)
25138 "Remove flyspell overlays in region."
25139 (and (org-bound-and-true-p flyspell-mode)
25140 (fboundp 'flyspell-delete-region-overlays)
25141 (flyspell-delete-region-overlays beg end)))
25143 (defvar flyspell-delayed-commands)
25144 (eval-after-load "flyspell"
25145 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25147 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25148 (eval-after-load "bookmark"
25149 '(if (boundp 'bookmark-after-jump-hook)
25150 ;; We can use the hook
25151 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25152 ;; Hook not available, use advice
25153 (defadvice bookmark-jump (after org-make-visible activate)
25154 "Make the position visible."
25155 (org-bookmark-jump-unhide))))
25157 ;; Make sure saveplace shows the location if it was hidden
25158 (eval-after-load "saveplace"
25159 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25160 "Make the position visible."
25161 (org-bookmark-jump-unhide)))
25163 ;; Make sure ecb shows the location if it was hidden
25164 (eval-after-load "ecb"
25165 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25166 "Make hierarchy visible when jumping into location from ECB tree buffer."
25167 (when (derived-mode-p 'org-mode)
25168 (org-show-context))))
25170 (defun org-bookmark-jump-unhide ()
25171 "Unhide the current position, to show the bookmark location."
25172 (and (derived-mode-p 'org-mode)
25173 (or (outline-invisible-p)
25174 (save-excursion (goto-char (max (point-min) (1- (point))))
25175 (outline-invisible-p)))
25176 (org-show-context 'bookmark-jump)))
25178 (defun org-mark-jump-unhide ()
25179 "Make the point visible with `org-show-context' after jumping to the mark."
25180 (when (and (derived-mode-p 'org-mode)
25181 (outline-invisible-p))
25182 (org-show-context 'mark-goto)))
25184 (eval-after-load "simple"
25185 '(defadvice pop-to-mark-command (after org-make-visible activate)
25186 "Make the point visible with `org-show-context'."
25187 (org-mark-jump-unhide)))
25189 (eval-after-load "simple"
25190 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25191 "Make the point visible with `org-show-context'."
25192 (org-mark-jump-unhide)))
25194 (eval-after-load "simple"
25195 '(defadvice pop-global-mark (after org-make-visible activate)
25196 "Make the point visible with `org-show-context'."
25197 (org-mark-jump-unhide)))
25199 ;; Make session.el ignore our circular variable
25200 (defvar session-globals-exclude)
25201 (eval-after-load "session"
25202 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25204 ;;;; Finish up
25206 (provide 'org)
25208 (run-hooks 'org-load-hook)
25210 ;;; org.el ends here