org.el: Use `dolist' instead of `mapc' + `lambda'
[org-mode/org-tableheadings.git] / lisp / org.el
blob8ee89f44c39162519d6baf2fb6c67ee6f095b3b7
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 cdlatex-environment "ext:cdlatex" (environment item))
113 (declare-function org-add-archive-files "org-archive" (files))
114 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
115 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
116 (declare-function org-agenda-redo "org-agenda" (&optional all))
117 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
118 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
119 (declare-function org-beamer-mode "ox-beamer" ())
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
122 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
123 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
126 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
127 (declare-function org-clock-update-time-maybe "org-clock" ())
128 (declare-function org-clocktable-shift "org-clock" (dir n))
129 (declare-function org-element-at-point "org-element" ())
130 (declare-function org-element-cache-refresh "org-element" (pos))
131 (declare-function org-element-cache-reset "org-element" (&optional all))
132 (declare-function org-element-contents "org-element" (element))
133 (declare-function org-element-context "org-element" (&optional element))
134 (declare-function org-element-copy "org-element" (datum))
135 (declare-function org-element-interpret-data "org-element" (data &optional parent))
136 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
137 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
138 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
139 (declare-function org-element-property "org-element" (property element))
140 (declare-function org-element-put-property "org-element" (element property value))
141 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-update-syntax "org-element" ())
144 (declare-function org-id-find-id-file "org-id" (id))
145 (declare-function org-id-get-create "org-id" (&optional force))
146 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
147 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
148 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
149 (declare-function org-plot/gnuplot "org-plot" (&optional params))
150 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
151 (declare-function org-table-align "org-table" ())
152 (declare-function org-table-begin "org-table" (&optional table-type))
153 (declare-function org-table-beginning-of-field "org-table" (&optional n))
154 (declare-function org-table-blank-field "org-table" ())
155 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
156 (declare-function org-table-edit-field "org-table" (arg))
157 (declare-function org-table-end "org-table" (&optional table-type))
158 (declare-function org-table-end-of-field "org-table" (&optional n))
159 (declare-function org-table-insert-row "org-table" (&optional arg))
160 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
161 (declare-function org-table-maybe-eval-formula "org-table" ())
162 (declare-function org-table-maybe-recalculate-line "org-table" ())
163 (declare-function org-table-next-row "org-table" ())
164 (declare-function org-table-paste-rectangle "org-table" ())
165 (declare-function org-table-wrap-region "org-table" (arg))
166 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
167 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
168 (declare-function orgtbl-mode "org-table" (&optional arg))
170 (defsubst org-uniquify (list)
171 "Non-destructively remove duplicate elements from LIST."
172 (let ((res (copy-sequence list))) (delete-dups res)))
174 (defsubst org-get-at-bol (property)
175 "Get text property PROPERTY at the beginning of line."
176 (get-text-property (point-at-bol) property))
178 (defsubst org-trim (s)
179 "Remove whitespace at the beginning and the end of string S."
180 (replace-regexp-in-string
181 "\\`[ \t\n\r]+" ""
182 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
184 ;; load languages based on value of `org-babel-load-languages'
185 (defvar org-babel-load-languages)
187 ;;;###autoload
188 (defun org-babel-do-load-languages (sym value)
189 "Load the languages defined in `org-babel-load-languages'."
190 (set-default sym value)
191 (dolist (pair org-babel-load-languages)
192 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
193 (if active
194 (require (intern (concat "ob-" lang)))
195 (funcall 'fmakunbound
196 (intern (concat "org-babel-execute:" lang)))
197 (funcall 'fmakunbound
198 (intern (concat "org-babel-expand-body:" lang)))))))
200 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
201 ;;;###autoload
202 (defun org-babel-load-file (file &optional compile)
203 "Load Emacs Lisp source code blocks in the Org-mode FILE.
204 This function exports the source code using `org-babel-tangle'
205 and then loads the resulting file using `load-file'. With prefix
206 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
207 file to byte-code before it is loaded."
208 (interactive "fFile to load: \nP")
209 (let* ((age (lambda (file)
210 (float-time
211 (time-subtract (current-time)
212 (nth 5 (or (file-attributes (file-truename file))
213 (file-attributes file)))))))
214 (base-name (file-name-sans-extension file))
215 (exported-file (concat base-name ".el")))
216 ;; tangle if the org-mode file is newer than the elisp file
217 (unless (and (file-exists-p exported-file)
218 (> (funcall age file) (funcall age exported-file)))
219 ;; Tangle-file traversal returns reversed list of tangled files
220 ;; and we want to evaluate the first target.
221 (setq exported-file
222 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
223 (message "%s %s"
224 (if compile
225 (progn (byte-compile-file exported-file 'load)
226 "Compiled and loaded")
227 (progn (load-file exported-file) "Loaded"))
228 exported-file)))
230 (defcustom org-babel-load-languages '((emacs-lisp . t))
231 "Languages which can be evaluated in Org-mode buffers.
232 This list can be used to load support for any of the languages
233 below, note that each language will depend on a different set of
234 system executables and/or Emacs modes. When a language is
235 \"loaded\", then code blocks in that language can be evaluated
236 with `org-babel-execute-src-block' bound by default to C-c
237 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
238 be set to remove code block evaluation from the C-c C-c
239 keybinding. By default only Emacs Lisp (which has no
240 requirements) is loaded."
241 :group 'org-babel
242 :set 'org-babel-do-load-languages
243 :version "24.1"
244 :type '(alist :tag "Babel Languages"
245 :key-type
246 (choice
247 (const :tag "Awk" awk)
248 (const :tag "C" C)
249 (const :tag "R" R)
250 (const :tag "Asymptote" asymptote)
251 (const :tag "Calc" calc)
252 (const :tag "Clojure" clojure)
253 (const :tag "CSS" css)
254 (const :tag "Ditaa" ditaa)
255 (const :tag "Dot" dot)
256 (const :tag "Emacs Lisp" emacs-lisp)
257 (const :tag "Forth" forth)
258 (const :tag "Fortran" fortran)
259 (const :tag "Gnuplot" gnuplot)
260 (const :tag "Haskell" haskell)
261 (const :tag "IO" io)
262 (const :tag "J" J)
263 (const :tag "Java" java)
264 (const :tag "Javascript" js)
265 (const :tag "LaTeX" latex)
266 (const :tag "Ledger" ledger)
267 (const :tag "Lilypond" lilypond)
268 (const :tag "Lisp" lisp)
269 (const :tag "Makefile" makefile)
270 (const :tag "Maxima" maxima)
271 (const :tag "Matlab" matlab)
272 (const :tag "Mscgen" mscgen)
273 (const :tag "Ocaml" ocaml)
274 (const :tag "Octave" octave)
275 (const :tag "Org" org)
276 (const :tag "Perl" perl)
277 (const :tag "Pico Lisp" picolisp)
278 (const :tag "PlantUML" plantuml)
279 (const :tag "Python" python)
280 (const :tag "Ruby" ruby)
281 (const :tag "Sass" sass)
282 (const :tag "Scala" scala)
283 (const :tag "Scheme" scheme)
284 (const :tag "Screen" screen)
285 (const :tag "Shell Script" shell)
286 (const :tag "Shen" shen)
287 (const :tag "Sql" sql)
288 (const :tag "Sqlite" sqlite)
289 (const :tag "Stan" stan)
290 (const :tag "ebnf2ps" ebnf2ps))
291 :value-type (boolean :tag "Activate" :value t)))
293 ;;;; Customization variables
294 (defcustom org-clone-delete-id nil
295 "Remove ID property of clones of a subtree.
296 When non-nil, clones of a subtree don't inherit the ID property.
297 Otherwise they inherit the ID property with a new unique
298 identifier."
299 :type 'boolean
300 :version "24.1"
301 :group 'org-id)
303 ;;; Version
304 (org-check-version)
306 ;;;###autoload
307 (defun org-version (&optional here full message)
308 "Show the org-mode version.
309 Interactively, or when MESSAGE is non-nil, show it in echo area.
310 With prefix argument, or when HERE is non-nil, insert it at point.
311 In non-interactive uses, a reduced version string is output unless
312 FULL is given."
313 (interactive (list current-prefix-arg t (not current-prefix-arg)))
314 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
315 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
316 (load-suffixes (list ".el"))
317 (org-install-dir
318 (ignore-errors (org-find-library-dir "org-loaddefs"))))
319 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
320 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
321 (let* ((load-suffixes save-load-suffixes)
322 (org-version (org-release))
323 (git-version (org-git-version))
324 (version (format "Org-mode version %s (%s @ %s)"
325 org-version
326 git-version
327 (if org-install-dir
328 (if (string= org-dir org-install-dir)
329 org-install-dir
330 (concat "mixed installation! " org-install-dir " and " org-dir))
331 "org-loaddefs.el can not be found!")))
332 (version1 (if full version org-version)))
333 (when here (insert version1))
334 (when message (message "%s" version1))
335 version1)))
337 (defconst org-version (org-version))
340 ;;; Syntax Constants
342 ;;;; Block
344 (defconst org-block-regexp
345 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
346 "Regular expression for hiding blocks.")
348 (defconst org-dblock-start-re
349 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
350 "Matches the start line of a dynamic block, with parameters.")
352 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
353 "Matches the end of a dynamic block.")
355 ;;;; Clock and Planning
357 (defconst org-clock-string "CLOCK:"
358 "String used as prefix for timestamps clocking work hours on an item.")
360 (defvar org-closed-string "CLOSED:"
361 "String used as the prefix for timestamps logging closing a TODO entry.")
363 (defvar org-deadline-string "DEADLINE:"
364 "String to mark deadline entries.
365 A deadline is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-deadline].")
369 (defvar org-scheduled-string "SCHEDULED:"
370 "String to mark scheduled TODO entries.
371 A schedule is this string, followed by a time stamp. Should be a word,
372 terminated by a colon. You can insert a schedule keyword and
373 a timestamp with \\[org-schedule].")
375 (defconst org-ds-keyword-length
376 (+ 2
377 (apply #'max
378 (mapcar #'length
379 (list org-deadline-string org-scheduled-string
380 org-clock-string org-closed-string))))
381 "Maximum length of the DEADLINE and SCHEDULED keywords.")
383 (defconst org-planning-line-re
384 (concat "^[ \t]*"
385 (regexp-opt
386 (list org-closed-string org-deadline-string org-scheduled-string)
388 "Matches a line with planning info.
389 Matched keyword is in group 1.")
391 (defconst org-clock-line-re
392 (concat "^[ \t]*" org-clock-string)
393 "Matches a line with clock info.")
395 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
396 "Matches the DEADLINE keyword.")
398 (defconst org-deadline-time-regexp
399 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
400 "Matches the DEADLINE keyword together with a time stamp.")
402 (defconst org-deadline-time-hour-regexp
403 (concat "\\<" org-deadline-string
404 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
405 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
407 (defconst org-deadline-line-regexp
408 (concat "\\<\\(" org-deadline-string "\\).*")
409 "Matches the DEADLINE keyword and the rest of the line.")
411 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
412 "Matches the SCHEDULED keyword.")
414 (defconst org-scheduled-time-regexp
415 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
416 "Matches the SCHEDULED keyword together with a time stamp.")
418 (defconst org-scheduled-time-hour-regexp
419 (concat "\\<" org-scheduled-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
423 (defconst org-closed-time-regexp
424 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
425 "Matches the CLOSED keyword together with a time stamp.")
427 (defconst org-keyword-time-regexp
428 (concat "\\<"
429 (regexp-opt
430 (list org-scheduled-string org-deadline-string org-closed-string
431 org-clock-string)
433 " *[[<]\\([^]>]+\\)[]>]")
434 "Matches any of the 4 keywords, together with the time stamp.")
436 (defconst org-keyword-time-not-clock-regexp
437 (concat
438 "\\<"
439 (regexp-opt
440 (list org-scheduled-string org-deadline-string org-closed-string) t)
441 " *[[<]\\([^]>]+\\)[]>]")
442 "Matches any of the 3 keywords, together with the time stamp.")
444 (defconst org-maybe-keyword-time-regexp
445 (concat "\\(\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string
448 org-clock-string)
450 "\\)?"
451 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
452 "\\|"
453 "<%%([^\r\n>]*>\\)")
454 "Matches a timestamp, possibly preceded by a keyword.")
456 (defconst org-all-time-keywords
457 (mapcar (lambda (w) (substring w 0 -1))
458 (list org-scheduled-string org-deadline-string
459 org-clock-string org-closed-string))
460 "List of time keywords.")
462 ;;;; Drawer
464 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
465 "Matches first or last line of a hidden block.
466 Group 1 contains drawer's name or \"END\".")
468 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
469 "Regular expression matching the first line of a property drawer.")
471 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
472 "Regular expression matching the last line of a property drawer.")
474 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
475 "Regular expression matching the first line of a clock drawer.")
477 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
478 "Regular expression matching the last line of a clock drawer.")
480 (defconst org-property-drawer-re
481 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
482 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
483 "[ \t]*:END:[ \t]*$")
484 "Matches an entire property drawer.")
486 (defconst org-clock-drawer-re
487 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
488 org-clock-drawer-end-re "\\)\n?")
489 "Matches an entire clock drawer.")
491 ;;;; Headline
493 (defconst org-heading-keyword-regexp-format
494 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
495 "Printf format for a regexp matching a headline with some keyword.
496 This regexp will match the headline of any node which has the
497 exact keyword that is put into the format. The keyword isn't in
498 any group by default, but the stars and the body are.")
500 (defconst org-heading-keyword-maybe-regexp-format
501 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
502 "Printf format for a regexp matching a headline, possibly with some keyword.
503 This regexp can match any headline with the specified keyword, or
504 without a keyword. The keyword isn't in any group by default,
505 but the stars and the body are.")
507 (defconst org-archive-tag "ARCHIVE"
508 "The tag that marks a subtree as archived.
509 An archived subtree does not open during visibility cycling, and does
510 not contribute to the agenda listings.")
512 (defconst org-comment-string "COMMENT"
513 "Entries starting with this keyword will never be exported.
514 An entry can be toggled between COMMENT and normal with
515 \\[org-toggle-comment].")
518 ;;;; LaTeX Environments and Fragments
520 (defconst org-latex-regexps
521 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
522 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
523 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
524 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
525 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
526 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
527 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
528 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
529 "Regular expressions for matching embedded LaTeX.")
531 ;;;; Node Property
533 (defconst org-effort-property "Effort"
534 "The property that is being used to keep track of effort estimates.
535 Effort estimates given in this property need to have the format H:MM.")
537 ;;;; Table
539 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
540 "Detect an org-type or table-type table.")
542 (defconst org-table-line-regexp "^[ \t]*|"
543 "Detect an org-type table line.")
545 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
546 "Detect an org-type table line.")
548 (defconst org-table-hline-regexp "^[ \t]*|-"
549 "Detect an org-type table hline.")
551 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
552 "Detect a table-type table hline.")
554 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
555 "Detect the first line outside a table when searching from within it.
556 This works for both table types.")
558 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
559 "Detect a #+TBLFM line.")
561 ;;;; Timestamp
563 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
564 "Regular expression for fast time stamp matching.")
566 (defconst org-ts-regexp-inactive
567 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
568 "Regular expression for fast inactive time stamp matching.")
570 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
571 "Regular expression for fast time stamp matching.")
573 (defconst org-ts-regexp0
574 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
575 "Regular expression matching time strings for analysis.
576 This one does not require the space after the date, so it can be used
577 on a string that terminates immediately after the date.")
579 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
580 "Regular expression matching time strings for analysis.")
582 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
583 "Regular expression matching time stamps, with groups.")
585 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
586 "Regular expression matching time stamps (also [..]), with groups.")
588 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
589 "Regular expression matching a time stamp range.")
591 (defconst org-tr-regexp-both
592 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
596 org-ts-regexp "\\)?")
597 "Regular expression matching a time stamp or time stamp range.")
599 (defconst org-tsr-regexp-both
600 (concat org-ts-regexp-both "\\(--?-?"
601 org-ts-regexp-both "\\)?")
602 "Regular expression matching a time stamp or time stamp range.
603 The time stamps may be either active or inactive.")
605 (defconst org-repeat-re
606 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
607 "Regular expression for specifying repeated events.
608 After a match, group 1 contains the repeat expression.")
610 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
611 "Formats for `format-time-string' which are used for time stamps.")
614 ;;; The custom variables
616 (defgroup org nil
617 "Outline-based notes management and organizer."
618 :tag "Org"
619 :group 'outlines
620 :group 'calendar)
622 (defcustom org-mode-hook nil
623 "Mode hook for Org-mode, run after the mode was turned on."
624 :group 'org
625 :type 'hook)
627 (defcustom org-load-hook nil
628 "Hook that is run after org.el has been loaded."
629 :group 'org
630 :type 'hook)
632 (defcustom org-log-buffer-setup-hook nil
633 "Hook that is run after an Org log buffer is created."
634 :group 'org
635 :version "24.1"
636 :type 'hook)
638 (defvar org-modules) ; defined below
639 (defvar org-modules-loaded nil
640 "Have the modules been loaded already?")
642 (defun org-load-modules-maybe (&optional force)
643 "Load all extensions listed in `org-modules'."
644 (when (or force (not org-modules-loaded))
645 (dolist (ext org-modules)
646 (condition-case nil (require ext)
647 (error (message "Problems while trying to load feature `%s'" ext))))
648 (setq org-modules-loaded t)))
650 (defun org-set-modules (var value)
651 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
652 (set var value)
653 (when (featurep 'org)
654 (org-load-modules-maybe 'force)
655 (org-element-cache-reset 'all)))
657 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
658 "Modules that should always be loaded together with org.el.
660 If a description starts with <C>, the file is not part of Emacs
661 and loading it will require that you have downloaded and properly
662 installed the Org mode distribution.
664 You can also use this system to load external packages (i.e. neither Org
665 core modules, nor modules from the CONTRIB directory). Just add symbols
666 to the end of the list. If the package is called org-xyz.el, then you need
667 to add the symbol `xyz', and the package must have a call to:
669 (provide \\='org-xyz)
671 For export specific modules, see also `org-export-backends'."
672 :group 'org
673 :set 'org-set-modules
674 :version "24.4"
675 :package-version '(Org . "8.0")
676 :type
677 '(set :greedy t
678 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
679 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
680 (const :tag " crypt: Encryption of subtrees" org-crypt)
681 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
682 (const :tag " docview: Links to doc-view buffers" org-docview)
683 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
684 (const :tag " habit: Track your consistency with habits" org-habit)
685 (const :tag " id: Global IDs for identifying entries" org-id)
686 (const :tag " info: Links to Info nodes" org-info)
687 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
688 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
689 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
690 (const :tag " mouse: Additional mouse support" org-mouse)
691 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
692 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
693 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
695 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
696 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
697 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
698 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
699 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
700 (const :tag "C collector: Collect properties into tables" org-collector)
701 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
702 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
703 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
704 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
705 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
706 (const :tag "C eval: Include command output as text" org-eval)
707 (const :tag "C eww: Store link to url of eww" org-eww)
708 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
709 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
710 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
711 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
712 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
713 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
714 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
715 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
716 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
717 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
718 (const :tag "C mew: Links to Mew folders/messages" org-mew)
719 (const :tag "C mtags: Support for muse-like tags" org-mtags)
720 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
721 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
722 (const :tag "C registry: A registry for Org-mode links" org-registry)
723 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
724 (const :tag "C secretary: Team management with org-mode" org-secretary)
725 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
726 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
727 (const :tag "C track: Keep up with Org-mode development" org-track)
728 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
729 (const :tag "C vm: Links to VM folders/messages" org-vm)
730 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
731 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
732 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
734 (defvar org-export-registered-backends) ; From ox.el.
735 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
736 (declare-function org-export-backend-name "ox" (backend))
737 (defcustom org-export-backends '(ascii html icalendar latex)
738 "List of export back-ends that should be always available.
740 If a description starts with <C>, the file is not part of Emacs
741 and loading it will require that you have downloaded and properly
742 installed the Org mode distribution.
744 Unlike to `org-modules', libraries in this list will not be
745 loaded along with Org, but only once the export framework is
746 needed.
748 This variable needs to be set before org.el is loaded. If you
749 need to make a change while Emacs is running, use the customize
750 interface or run the following code, where VAL stands for the new
751 value of the variable, after updating it:
753 (progn
754 (setq org-export-registered-backends
755 (cl-remove-if-not
756 (lambda (backend)
757 (let ((name (org-export-backend-name backend)))
758 (or (memq name val)
759 (catch \\='parentp
760 (dolist (b val)
761 (and (org-export-derived-backend-p b name)
762 (throw \\='parentp t)))))))
763 org-export-registered-backends))
764 (let ((new-list (mapcar #\\='org-export-backend-name
765 org-export-registered-backends)))
766 (dolist (backend val)
767 (cond
768 ((not (load (format \"ox-%s\" backend) t t))
769 (message \"Problems while trying to load export back-end \\=`%s\\='\"
770 backend))
771 ((not (memq backend new-list)) (push backend new-list))))
772 (set-default \\='org-export-backends new-list)))
774 Adding a back-end to this list will also pull the back-end it
775 depends on, if any."
776 :group 'org
777 :group 'org-export
778 :version "24.4"
779 :package-version '(Org . "8.0")
780 :initialize 'custom-initialize-set
781 :set (lambda (var val)
782 (if (not (featurep 'ox)) (set-default var val)
783 ;; Any back-end not required anymore (not present in VAL and not
784 ;; a parent of any back-end in the new value) is removed from the
785 ;; list of registered back-ends.
786 (setq org-export-registered-backends
787 (cl-remove-if-not
788 (lambda (backend)
789 (let ((name (org-export-backend-name backend)))
790 (or (memq name val)
791 (catch 'parentp
792 (dolist (b val)
793 (and (org-export-derived-backend-p b name)
794 (throw 'parentp t)))))))
795 org-export-registered-backends))
796 ;; Now build NEW-LIST of both new back-ends and required
797 ;; parents.
798 (let ((new-list (mapcar #'org-export-backend-name
799 org-export-registered-backends)))
800 (dolist (backend val)
801 (cond
802 ((not (load (format "ox-%s" backend) t t))
803 (message "Problems while trying to load export back-end `%s'"
804 backend))
805 ((not (memq backend new-list)) (push backend new-list))))
806 ;; Set VAR to that list with fixed dependencies.
807 (set-default var new-list))))
808 :type '(set :greedy t
809 (const :tag " ascii Export buffer to ASCII format" ascii)
810 (const :tag " beamer Export buffer to Beamer presentation" beamer)
811 (const :tag " html Export buffer to HTML format" html)
812 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
813 (const :tag " latex Export buffer to LaTeX format" latex)
814 (const :tag " man Export buffer to MAN format" man)
815 (const :tag " md Export buffer to Markdown format" md)
816 (const :tag " odt Export buffer to ODT format" odt)
817 (const :tag " org Export buffer to Org format" org)
818 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
819 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
820 (const :tag "C deck Export buffer to deck.js presentations" deck)
821 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
822 (const :tag "C groff Export buffer to Groff format" groff)
823 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
824 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
825 (const :tag "C s5 Export buffer to s5 presentations" s5)
826 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
828 (eval-after-load 'ox
829 '(dolist (backend org-export-backends)
830 (condition-case nil (require (intern (format "ox-%s" backend)))
831 (error (message "Problems while trying to load export back-end `%s'"
832 backend)))))
834 (defcustom org-support-shift-select nil
835 "Non-nil means make shift-cursor commands select text when possible.
836 \\<org-mode-map>\
838 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
839 start selecting a region, or enlarge regions started in this way.
840 In Org-mode, in special contexts, these same keys are used for
841 other purposes, important enough to compete with shift selection.
842 Org tries to balance these needs by supporting `shift-select-mode'
843 outside these special contexts, under control of this variable.
845 The default of this variable is nil, to avoid confusing behavior. Shifted
846 cursor keys will then execute Org commands in the following contexts:
847 - on a headline, changing TODO state (left/right) and priority (up/down)
848 - on a time stamp, changing the time
849 - in a plain list item, changing the bullet type
850 - in a property definition line, switching between allowed values
851 - in the BEGIN line of a clock table (changing the time block).
852 Outside these contexts, the commands will throw an error.
854 When this variable is t and the cursor is not in a special
855 context, Org-mode will support shift-selection for making and
856 enlarging regions. To make this more effective, the bullet
857 cycling will no longer happen anywhere in an item line, but only
858 if the cursor is exactly on the bullet.
860 If you set this variable to the symbol `always', then the keys
861 will not be special in headlines, property lines, and item lines,
862 to make shift selection work there as well. If this is what you
863 want, you can use the following alternative commands:
864 `\\[org-todo]' and `\\[org-priority]' \
865 to change TODO state and priority,
866 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
867 can be used to switch TODO sets,
868 `\\[org-ctrl-c-minus]' to cycle item bullet types,
869 and properties can be edited by hand or in column view.
871 However, when the cursor is on a timestamp, shift-cursor commands
872 will still edit the time stamp - this is just too good to give up.
874 XEmacs user should have this variable set to nil, because
875 `shift-select-mode' is in Emacs 23 or later only."
876 :group 'org
877 :type '(choice
878 (const :tag "Never" nil)
879 (const :tag "When outside special context" t)
880 (const :tag "Everywhere except timestamps" always)))
882 (defcustom org-loop-over-headlines-in-active-region nil
883 "Shall some commands act upon headlines in the active region?
885 When set to t, some commands will be performed in all headlines
886 within the active region.
888 When set to `start-level', some commands will be performed in all
889 headlines within the active region, provided that these headlines
890 are of the same level than the first one.
892 When set to a string, those commands will be performed on the
893 matching headlines within the active region. Such string must be
894 a tags/property/todo match as it is used in the agenda tags view.
896 The list of commands is: `org-schedule', `org-deadline',
897 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
898 `org-archive-to-archive-sibling'. The archiving commands skip
899 already archived entries."
900 :type '(choice (const :tag "Don't loop" nil)
901 (const :tag "All headlines in active region" t)
902 (const :tag "In active region, headlines at the same level than the first one" start-level)
903 (string :tag "Tags/Property/Todo matcher"))
904 :version "24.1"
905 :group 'org-todo
906 :group 'org-archive)
908 (defgroup org-startup nil
909 "Options concerning startup of Org-mode."
910 :tag "Org Startup"
911 :group 'org)
913 (defcustom org-startup-folded t
914 "Non-nil means entering Org-mode will switch to OVERVIEW.
915 This can also be configured on a per-file basis by adding one of
916 the following lines anywhere in the buffer:
918 #+STARTUP: fold (or `overview', this is equivalent)
919 #+STARTUP: nofold (or `showall', this is equivalent)
920 #+STARTUP: content
921 #+STARTUP: showeverything
923 By default, this option is ignored when Org opens agenda files
924 for the first time. If you want the agenda to honor the startup
925 option, set `org-agenda-inhibit-startup' to nil."
926 :group 'org-startup
927 :type '(choice
928 (const :tag "nofold: show all" nil)
929 (const :tag "fold: overview" t)
930 (const :tag "content: all headlines" content)
931 (const :tag "show everything, even drawers" showeverything)))
933 (defcustom org-startup-truncated t
934 "Non-nil means entering Org-mode will set `truncate-lines'.
935 This is useful since some lines containing links can be very long and
936 uninteresting. Also tables look terrible when wrapped."
937 :group 'org-startup
938 :type 'boolean)
940 (defcustom org-startup-indented nil
941 "Non-nil means turn on `org-indent-mode' on startup.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
945 #+STARTUP: indent
946 #+STARTUP: noindent"
947 :group 'org-structure
948 :type '(choice
949 (const :tag "Not" nil)
950 (const :tag "Globally (slow on startup in large files)" t)))
952 (defcustom org-use-sub-superscripts t
953 "Non-nil means interpret \"_\" and \"^\" for display.
955 If you want to control how Org exports those characters, see
956 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
957 used to be an alias for `org-export-with-sub-superscripts' in
958 Org <8.0, it is not anymore.
960 When this option is turned on, you can use TeX-like syntax for
961 sub- and superscripts within the buffer. Several characters after
962 \"_\" or \"^\" will be considered as a single item - so grouping
963 with {} is normally not needed. For example, the following things
964 will be parsed as single sub- or superscripts:
966 10^24 or 10^tau several digits will be considered 1 item.
967 10^-12 or 10^-tau a leading sign with digits or a word
968 x^2-y^3 will be read as x^2 - y^3, because items are
969 terminated by almost any nonword/nondigit char.
970 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
972 Still, ambiguity is possible. So when in doubt, use {} to enclose
973 the sub/superscript. If you set this variable to the symbol `{}',
974 the braces are *required* in order to trigger interpretations as
975 sub/superscript. This can be helpful in documents that need \"_\"
976 frequently in plain text."
977 :group 'org-startup
978 :version "24.4"
979 :package-version '(Org . "8.0")
980 :type '(choice
981 (const :tag "Always interpret" t)
982 (const :tag "Only with braces" {})
983 (const :tag "Never interpret" nil)))
985 (defcustom org-startup-with-beamer-mode nil
986 "Non-nil means turn on `org-beamer-mode' on startup.
987 This can also be configured on a per-file basis by adding one of
988 the following lines anywhere in the buffer:
990 #+STARTUP: beamer"
991 :group 'org-startup
992 :version "24.1"
993 :type 'boolean)
995 (defcustom org-startup-align-all-tables nil
996 "Non-nil means align all tables when visiting a file.
997 This is useful when the column width in tables is forced with <N> cookies
998 in table fields. Such tables will look correct only after the first re-align.
999 This can also be configured on a per-file basis by adding one of
1000 the following lines anywhere in the buffer:
1001 #+STARTUP: align
1002 #+STARTUP: noalign"
1003 :group 'org-startup
1004 :type 'boolean)
1006 (defcustom org-startup-with-inline-images nil
1007 "Non-nil means show inline images when loading a new Org file.
1008 This can also be configured on a per-file basis by adding one of
1009 the following lines anywhere in the buffer:
1010 #+STARTUP: inlineimages
1011 #+STARTUP: noinlineimages"
1012 :group 'org-startup
1013 :version "24.1"
1014 :type 'boolean)
1016 (defcustom org-startup-with-latex-preview nil
1017 "Non-nil means preview LaTeX fragments when loading a new Org file.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1021 #+STARTUP: latexpreview
1022 #+STARTUP: nolatexpreview"
1023 :group 'org-startup
1024 :version "24.4"
1025 :package-version '(Org . "8.0")
1026 :type 'boolean)
1028 (defcustom org-insert-mode-line-in-empty-file nil
1029 "Non-nil means insert the first line setting Org-mode in empty files.
1030 When the function `org-mode' is called interactively in an empty file, this
1031 normally means that the file name does not automatically trigger Org-mode.
1032 To ensure that the file will always be in Org-mode in the future, a
1033 line enforcing Org-mode will be inserted into the buffer, if this option
1034 has been set."
1035 :group 'org-startup
1036 :type 'boolean)
1038 (defcustom org-replace-disputed-keys nil
1039 "Non-nil means use alternative key bindings for some keys.
1040 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1041 These keys are also used by other packages like shift-selection-mode'
1042 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1043 If you want to use Org-mode together with one of these other modes,
1044 or more generally if you would like to move some Org-mode commands to
1045 other keys, set this variable and configure the keys with the variable
1046 `org-disputed-keys'.
1048 This option is only relevant at load-time of Org-mode, and must be set
1049 *before* org.el is loaded. Changing it requires a restart of Emacs to
1050 become effective."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-use-extra-keys nil
1055 "Non-nil means use extra key sequence definitions for certain commands.
1056 This happens automatically if you run XEmacs or if `window-system'
1057 is nil. This variable lets you do the same manually. You must
1058 set it before loading org.
1060 Example: on Carbon Emacs 22 running graphically, with an external
1061 keyboard on a Powerbook, the default way of setting M-left might
1062 not work for either Alt or ESC. Setting this variable will make
1063 it work for ESC."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1069 (defcustom org-disputed-keys
1070 '(([(shift up)] . [(meta p)])
1071 ([(shift down)] . [(meta n)])
1072 ([(shift left)] . [(meta -)])
1073 ([(shift right)] . [(meta +)])
1074 ([(control shift right)] . [(meta shift +)])
1075 ([(control shift left)] . [(meta shift -)]))
1076 "Keys for which Org-mode and other modes compete.
1077 This is an alist, cars are the default keys, second element specifies
1078 the alternative to use when `org-replace-disputed-keys' is t.
1080 Keys can be specified in any syntax supported by `define-key'.
1081 The value of this option takes effect only at Org-mode's startup,
1082 therefore you'll have to restart Emacs to apply it after changing."
1083 :group 'org-startup
1084 :type 'alist)
1086 (defun org-key (key)
1087 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1088 Or return the original if not disputed.
1089 Also apply the translations defined in `org-xemacs-key-equivalents'."
1090 (when org-replace-disputed-keys
1091 (let* ((nkey (key-description key))
1092 (x (org-find-if (lambda (x)
1093 (equal (key-description (car x)) nkey))
1094 org-disputed-keys)))
1095 (setq key (if x (cdr x) key))))
1096 (when (featurep 'xemacs)
1097 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1098 key)
1100 (defun org-find-if (predicate seq)
1101 (catch 'exit
1102 (while seq
1103 (if (funcall predicate (car seq))
1104 (throw 'exit (car seq))
1105 (pop seq)))))
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org-mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org-mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org-mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org-mode files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((isearch . lineage)
1151 (bookmark-jump . lineage)
1152 (default . ancestors))
1153 "Alist between context and visibility span when revealing a location.
1155 \\<org-mode-map>Some actions may move point into invisible
1156 locations. As a consequence, Org always expose a neighborhood
1157 around point. How much is shown depends on the initial action,
1158 or context. Valid contexts are
1160 agenda when exposing an entry from the agenda
1161 org-goto when using the command `org-goto' (\\[org-goto])
1162 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1163 tags-tree when constructing a sparse tree based on tags matches
1164 link-search when exposing search matches associated with a link
1165 mark-goto when exposing the jump goal of a mark
1166 bookmark-jump when exposing a bookmark location
1167 isearch when exiting from an incremental search
1168 default default for all contexts not set explicitly
1170 Allowed visibility spans are
1172 minimal show current headline; if point is not on headline,
1173 also show entry
1175 local show current headline, entry and next headline
1177 ancestors show current headline and its direct ancestors; if
1178 point is not on headline, also show entry
1180 lineage show current headline, its direct ancestors and all
1181 their children; if point is not on headline, also show
1182 entry and first child
1184 tree show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and all children
1188 canonical show current headline, its direct ancestors along with
1189 their entries and children; if point is not located on
1190 the headline, also show current entry and all children
1192 As special cases, a nil or t value means show all contexts in
1193 `minimal' or `canonical' view, respectively.
1195 Some views can make displayed information very compact, but also
1196 make it harder to edit the location of the match. In such
1197 a case, use the command `org-reveal' (\\[org-reveal]) to show
1198 more context."
1199 :group 'org-reveal-location
1200 :version "25.1"
1201 :package-version '(Org . "8.3")
1202 :type '(choice
1203 (const :tag "Canonical" t)
1204 (const :tag "Minimal" nil)
1205 (repeat :greedy t :tag "Individual contexts"
1206 (cons
1207 (choice :tag "Context"
1208 (const agenda)
1209 (const org-goto)
1210 (const occur-tree)
1211 (const tags-tree)
1212 (const link-search)
1213 (const mark-goto)
1214 (const bookmark-jump)
1215 (const isearch)
1216 (const default))
1217 (choice :tag "Detail level"
1218 (const minimal)
1219 (const local)
1220 (const ancestors)
1221 (const lineage)
1222 (const tree)
1223 (const canonical))))))
1225 (defcustom org-indirect-buffer-display 'other-window
1226 "How should indirect tree buffers be displayed?
1227 This applies to indirect buffers created with the commands
1228 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1229 Valid values are:
1230 current-window Display in the current window
1231 other-window Just display in another window.
1232 dedicated-frame Create one new frame, and re-use it each time.
1233 new-frame Make a new frame each time. Note that in this case
1234 previously-made indirect buffers are kept, and you need to
1235 kill these buffers yourself."
1236 :group 'org-structure
1237 :group 'org-agenda-windows
1238 :type '(choice
1239 (const :tag "In current window" current-window)
1240 (const :tag "In current frame, other window" other-window)
1241 (const :tag "Each time a new frame" new-frame)
1242 (const :tag "One dedicated frame" dedicated-frame)))
1244 (defcustom org-use-speed-commands nil
1245 "Non-nil means activate single letter commands at beginning of a headline.
1246 This may also be a function to test for appropriate locations where speed
1247 commands should be active.
1249 For example, to activate speed commands when the point is on any
1250 star at the beginning of the headline, you can do this:
1252 (setq org-use-speed-commands
1253 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1254 :group 'org-structure
1255 :type '(choice
1256 (const :tag "Never" nil)
1257 (const :tag "At beginning of headline stars" t)
1258 (function)))
1260 (defcustom org-speed-commands-user nil
1261 "Alist of additional speed commands.
1262 This list will be checked before `org-speed-commands-default'
1263 when the variable `org-use-speed-commands' is non-nil
1264 and when the cursor is at the beginning of a headline.
1265 The car if each entry is a string with a single letter, which must
1266 be assigned to `self-insert-command' in the global map.
1267 The cdr is either a command to be called interactively, a function
1268 to be called, or a form to be evaluated.
1269 An entry that is just a list with a single string will be interpreted
1270 as a descriptive headline that will be added when listing the speed
1271 commands in the Help buffer using the `?' speed command."
1272 :group 'org-structure
1273 :type '(repeat :value ("k" . ignore)
1274 (choice :value ("k" . ignore)
1275 (list :tag "Descriptive Headline" (string :tag "Headline"))
1276 (cons :tag "Letter and Command"
1277 (string :tag "Command letter")
1278 (choice
1279 (function)
1280 (sexp))))))
1282 (defcustom org-bookmark-names-plist
1283 '(:last-capture "org-capture-last-stored"
1284 :last-refile "org-refile-last-stored"
1285 :last-capture-marker "org-capture-last-stored-marker")
1286 "Names for bookmarks automatically set by some Org commands.
1287 This can provide strings as names for a number of bookmarks Org sets
1288 automatically. The following keys are currently implemented:
1289 :last-capture
1290 :last-capture-marker
1291 :last-refile
1292 When a key does not show up in the property list, the corresponding bookmark
1293 is not set."
1294 :group 'org-structure
1295 :type 'plist)
1297 (defgroup org-cycle nil
1298 "Options concerning visibility cycling in Org-mode."
1299 :tag "Org Cycle"
1300 :group 'org-structure)
1302 (defcustom org-cycle-skip-children-state-if-no-children t
1303 "Non-nil means skip CHILDREN state in entries that don't have any."
1304 :group 'org-cycle
1305 :type 'boolean)
1307 (defcustom org-cycle-max-level nil
1308 "Maximum level which should still be subject to visibility cycling.
1309 Levels higher than this will, for cycling, be treated as text, not a headline.
1310 When `org-odd-levels-only' is set, a value of N in this variable actually
1311 means 2N-1 stars as the limiting headline.
1312 When nil, cycle all levels.
1313 Note that the limiting level of cycling is also influenced by
1314 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1315 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1316 than its value."
1317 :group 'org-cycle
1318 :type '(choice
1319 (const :tag "No limit" nil)
1320 (integer :tag "Maximum level")))
1322 (defcustom org-hide-block-startup nil
1323 "Non-nil means entering Org-mode will fold all blocks.
1324 This can also be set in on a per-file basis with
1326 #+STARTUP: hideblocks
1327 #+STARTUP: showblocks"
1328 :group 'org-startup
1329 :group 'org-cycle
1330 :type 'boolean)
1332 (defcustom org-cycle-global-at-bob nil
1333 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1334 This makes it possible to do global cycling without having to use S-TAB or
1335 \\[universal-argument] TAB. For this special case to work, the first line
1336 of the buffer must not be a headline -- it may be empty or some other text.
1337 When used in this way, `org-cycle-hook' is disabled temporarily to make
1338 sure the cursor stays at the beginning of the buffer. When this option is
1339 nil, don't do anything special at the beginning of the buffer."
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-level-after-item/entry-creation t
1344 "Non-nil means cycle entry level or item indentation in new empty entries.
1346 When the cursor is at the end of an empty headline, i.e., with only stars
1347 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1348 and then all possible ancestor states, before returning to the original state.
1349 This makes data entry extremely fast: M-RET to create a new headline,
1350 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1352 When the cursor is at the end of an empty plain list item, one TAB will
1353 make it a subitem, two or more tabs will back up to make this an item
1354 higher up in the item hierarchy."
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-emulate-tab t
1359 "Where should `org-cycle' emulate TAB.
1360 nil Never
1361 white Only in completely white lines
1362 whitestart Only at the beginning of lines, before the first non-white char
1363 t Everywhere except in headlines
1364 exc-hl-bol Everywhere except at the start of a headline
1365 If TAB is used in a place where it does not emulate TAB, the current subtree
1366 visibility is cycled."
1367 :group 'org-cycle
1368 :type '(choice (const :tag "Never" nil)
1369 (const :tag "Only in completely white lines" white)
1370 (const :tag "Before first char in a line" whitestart)
1371 (const :tag "Everywhere except in headlines" t)
1372 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1374 (defcustom org-cycle-separator-lines 2
1375 "Number of empty lines needed to keep an empty line between collapsed trees.
1376 If you leave an empty line between the end of a subtree and the following
1377 headline, this empty line is hidden when the subtree is folded.
1378 Org-mode will leave (exactly) one empty line visible if the number of
1379 empty lines is equal or larger to the number given in this variable.
1380 So the default 2 means at least 2 empty lines after the end of a subtree
1381 are needed to produce free space between a collapsed subtree and the
1382 following headline.
1384 If the number is negative, and the number of empty lines is at least -N,
1385 all empty lines are shown.
1387 Special case: when 0, never leave empty lines in collapsed view."
1388 :group 'org-cycle
1389 :type 'integer)
1390 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1392 (defcustom org-pre-cycle-hook nil
1393 "Hook that is run before visibility cycling is happening.
1394 The function(s) in this hook must accept a single argument which indicates
1395 the new state that will be set right after running this hook. The
1396 argument is a symbol. Before a global state change, it can have the values
1397 `overview', `content', or `all'. Before a local state change, it can have
1398 the values `folded', `children', or `subtree'."
1399 :group 'org-cycle
1400 :type 'hook)
1402 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1403 org-cycle-hide-drawers
1404 org-cycle-show-empty-lines
1405 org-optimize-window-after-visibility-change)
1406 "Hook that is run after `org-cycle' has changed the buffer visibility.
1407 The function(s) in this hook must accept a single argument which indicates
1408 the new state that was set by the most recent `org-cycle' command. The
1409 argument is a symbol. After a global state change, it can have the values
1410 `overview', `contents', or `all'. After a local state change, it can have
1411 the values `folded', `children', or `subtree'."
1412 :group 'org-cycle
1413 :type 'hook
1414 :version "25.1"
1415 :package-version '(Org . "8.3"))
1417 (defgroup org-edit-structure nil
1418 "Options concerning structure editing in Org-mode."
1419 :tag "Org Edit Structure"
1420 :group 'org-structure)
1422 (defcustom org-odd-levels-only nil
1423 "Non-nil means skip even levels and only use odd levels for the outline.
1424 This has the effect that two stars are being added/taken away in
1425 promotion/demotion commands. It also influences how levels are
1426 handled by the exporters.
1427 Changing it requires restart of `font-lock-mode' to become effective
1428 for fontification also in regions already fontified.
1429 You may also set this on a per-file basis by adding one of the following
1430 lines to the buffer:
1432 #+STARTUP: odd
1433 #+STARTUP: oddeven"
1434 :group 'org-edit-structure
1435 :group 'org-appearance
1436 :type 'boolean)
1438 (defcustom org-adapt-indentation t
1439 "Non-nil means adapt indentation to outline node level.
1441 When this variable is set, Org assumes that you write outlines by
1442 indenting text in each node to align with the headline (after the
1443 stars). The following issues are influenced by this variable:
1445 - The indentation is increased by one space in a demotion
1446 command, and decreased by one in a promotion command. However,
1447 in the latter case, if shifting some line in the entry body
1448 would alter document structure (e.g., insert a new headline),
1449 indentation is not changed at all.
1451 - Property drawers and planning information is inserted indented
1452 when this variable is set. When nil, they will not be indented.
1454 - TAB indents a line relative to current level. The lines below
1455 a headline will be indented when this variable is set.
1457 Note that this is all about true indentation, by adding and
1458 removing space characters. See also `org-indent.el' which does
1459 level-dependent indentation in a virtual way, i.e. at display
1460 time in Emacs."
1461 :group 'org-edit-structure
1462 :type 'boolean)
1464 (defcustom org-special-ctrl-a/e nil
1465 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1467 When t, `C-a' will bring back the cursor to the beginning of the
1468 headline text, i.e. after the stars and after a possible TODO
1469 keyword. In an item, this will be the position after bullet and
1470 check-box, if any. When the cursor is already at that position,
1471 another `C-a' will bring it to the beginning of the line.
1473 `C-e' will jump to the end of the headline, ignoring the presence
1474 of tags in the headline. A second `C-e' will then jump to the
1475 true end of the line, after any tags. This also means that, when
1476 this variable is non-nil, `C-e' also will never jump beyond the
1477 end of the heading of a folded section, i.e. not after the
1478 ellipses.
1480 When set to the symbol `reversed', the first `C-a' or `C-e' works
1481 normally, going to the true line boundary first. Only a directly
1482 following, identical keypress will bring the cursor to the
1483 special positions.
1485 This may also be a cons cell where the behavior for `C-a' and
1486 `C-e' is set separately."
1487 :group 'org-edit-structure
1488 :type '(choice
1489 (const :tag "off" nil)
1490 (const :tag "on: after stars/bullet and before tags first" t)
1491 (const :tag "reversed: true line boundary first" reversed)
1492 (cons :tag "Set C-a and C-e separately"
1493 (choice :tag "Special C-a"
1494 (const :tag "off" nil)
1495 (const :tag "on: after stars/bullet first" t)
1496 (const :tag "reversed: before stars/bullet first" reversed))
1497 (choice :tag "Special C-e"
1498 (const :tag "off" nil)
1499 (const :tag "on: before tags first" t)
1500 (const :tag "reversed: after tags first" reversed)))))
1501 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1503 (defcustom org-special-ctrl-k nil
1504 "Non-nil means `C-k' will behave specially in headlines.
1505 When nil, `C-k' will call the default `kill-line' command.
1506 When t, the following will happen while the cursor is in the headline:
1508 - When the cursor is at the beginning of a headline, kill the entire
1509 line and possible the folded subtree below the line.
1510 - When in the middle of the headline text, kill the headline up to the tags.
1511 - When after the headline text, kill the tags."
1512 :group 'org-edit-structure
1513 :type 'boolean)
1515 (defcustom org-ctrl-k-protect-subtree nil
1516 "Non-nil means, do not delete a hidden subtree with C-k.
1517 When set to the symbol `error', simply throw an error when C-k is
1518 used to kill (part-of) a headline that has hidden text behind it.
1519 Any other non-nil value will result in a query to the user, if it is
1520 OK to kill that hidden subtree. When nil, kill without remorse."
1521 :group 'org-edit-structure
1522 :version "24.1"
1523 :type '(choice
1524 (const :tag "Do not protect hidden subtrees" nil)
1525 (const :tag "Protect hidden subtrees with a security query" t)
1526 (const :tag "Never kill a hidden subtree with C-k" error)))
1528 (defcustom org-special-ctrl-o t
1529 "Non-nil means, make `C-o' insert a row in tables."
1530 :group 'org-edit-structure
1531 :type 'boolean)
1533 (defcustom org-catch-invisible-edits nil
1534 "Check if in invisible region before inserting or deleting a character.
1535 Valid values are:
1537 nil Do not check, so just do invisible edits.
1538 error Throw an error and do nothing.
1539 show Make point visible, and do the requested edit.
1540 show-and-error Make point visible, then throw an error and abort the edit.
1541 smart Make point visible, and do insertion/deletion if it is
1542 adjacent to visible text and the change feels predictable.
1543 Never delete a previously invisible character or add in the
1544 middle or right after an invisible region. Basically, this
1545 allows insertion and backward-delete right before ellipses.
1546 FIXME: maybe in this case we should not even show?"
1547 :group 'org-edit-structure
1548 :version "24.1"
1549 :type '(choice
1550 (const :tag "Do not check" nil)
1551 (const :tag "Throw error when trying to edit" error)
1552 (const :tag "Unhide, but do not do the edit" show-and-error)
1553 (const :tag "Show invisible part and do the edit" show)
1554 (const :tag "Be smart and do the right thing" smart)))
1556 (defcustom org-yank-folded-subtrees t
1557 "Non-nil means when yanking subtrees, fold them.
1558 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1559 it starts with a heading and all other headings in it are either children
1560 or siblings, then fold all the subtrees. However, do this only if no
1561 text after the yank would be swallowed into a folded tree by this action."
1562 :group 'org-edit-structure
1563 :type 'boolean)
1565 (defcustom org-yank-adjusted-subtrees nil
1566 "Non-nil means when yanking subtrees, adjust the level.
1567 With this setting, `org-paste-subtree' is used to insert the subtree, see
1568 this function for details."
1569 :group 'org-edit-structure
1570 :type 'boolean)
1572 (defcustom org-M-RET-may-split-line '((default . t))
1573 "Non-nil means M-RET will split the line at the cursor position.
1574 When nil, it will go to the end of the line before making a
1575 new line.
1576 You may also set this option in a different way for different
1577 contexts. Valid contexts are:
1579 headline when creating a new headline
1580 item when creating a new item
1581 table in a table field
1582 default the value to be used for all contexts not explicitly
1583 customized"
1584 :group 'org-structure
1585 :group 'org-table
1586 :type '(choice
1587 (const :tag "Always" t)
1588 (const :tag "Never" nil)
1589 (repeat :greedy t :tag "Individual contexts"
1590 (cons
1591 (choice :tag "Context"
1592 (const headline)
1593 (const item)
1594 (const table)
1595 (const default))
1596 (boolean)))))
1599 (defcustom org-insert-heading-respect-content nil
1600 "Non-nil means insert new headings after the current subtree.
1601 When nil, the new heading is created directly after the current line.
1602 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1603 this variable on for the duration of the command."
1604 :group 'org-structure
1605 :type 'boolean)
1607 (defcustom org-blank-before-new-entry '((heading . auto)
1608 (plain-list-item . auto))
1609 "Should `org-insert-heading' leave a blank line before new heading/item?
1610 The value is an alist, with `heading' and `plain-list-item' as CAR,
1611 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1612 which case Org will look at the surrounding headings/items and try to
1613 make an intelligent decision whether to insert a blank line or not."
1614 :group 'org-edit-structure
1615 :type '(list
1616 (cons (const heading)
1617 (choice (const :tag "Never" nil)
1618 (const :tag "Always" t)
1619 (const :tag "Auto" auto)))
1620 (cons (const plain-list-item)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))))
1625 (defcustom org-insert-heading-hook nil
1626 "Hook being run after inserting a new heading."
1627 :group 'org-edit-structure
1628 :type 'hook)
1630 (defcustom org-enable-fixed-width-editor t
1631 "Non-nil means lines starting with \":\" are treated as fixed-width.
1632 This currently only means they are never auto-wrapped.
1633 When nil, such lines will be treated like ordinary lines."
1634 :group 'org-edit-structure
1635 :type 'boolean)
1637 (defcustom org-goto-auto-isearch t
1638 "Non-nil means typing characters in `org-goto' starts incremental search.
1639 When nil, you can use these keybindings to navigate the buffer:
1641 q Quit the org-goto interface
1642 n Go to the next visible heading
1643 p Go to the previous visible heading
1644 f Go one heading forward on same level
1645 b Go one heading backward on same level
1646 u Go one heading up"
1647 :group 'org-edit-structure
1648 :type 'boolean)
1650 (defgroup org-sparse-trees nil
1651 "Options concerning sparse trees in Org-mode."
1652 :tag "Org Sparse Trees"
1653 :group 'org-structure)
1655 (defcustom org-highlight-sparse-tree-matches t
1656 "Non-nil means highlight all matches that define a sparse tree.
1657 The highlights will automatically disappear the next time the buffer is
1658 changed by an edit command."
1659 :group 'org-sparse-trees
1660 :type 'boolean)
1662 (defcustom org-remove-highlights-with-change t
1663 "Non-nil means any change to the buffer will remove temporary highlights.
1664 \\<org-mode-map>\
1665 Such highlights are created by `org-occur' and `org-clock-display'.
1666 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1667 to get rid of the highlights.
1668 The highlights created by `org-toggle-latex-fragment' always need
1669 `\\[org-toggle-latex-fragment]' to be removed."
1670 :group 'org-sparse-trees
1671 :group 'org-time
1672 :type 'boolean)
1675 (defcustom org-occur-hook '(org-first-headline-recenter)
1676 "Hook that is run after `org-occur' has constructed a sparse tree.
1677 This can be used to recenter the window to show as much of the structure
1678 as possible."
1679 :group 'org-sparse-trees
1680 :type 'hook)
1682 (defgroup org-imenu-and-speedbar nil
1683 "Options concerning imenu and speedbar in Org-mode."
1684 :tag "Org Imenu and Speedbar"
1685 :group 'org-structure)
1687 (defcustom org-imenu-depth 2
1688 "The maximum level for Imenu access to Org-mode headlines.
1689 This also applied for speedbar access."
1690 :group 'org-imenu-and-speedbar
1691 :type 'integer)
1693 (defgroup org-table nil
1694 "Options concerning tables in Org-mode."
1695 :tag "Org Table"
1696 :group 'org)
1698 (defcustom org-enable-table-editor 'optimized
1699 "Non-nil means lines starting with \"|\" are handled by the table editor.
1700 When nil, such lines will be treated like ordinary lines.
1702 When equal to the symbol `optimized', the table editor will be optimized to
1703 do the following:
1704 - Automatic overwrite mode in front of whitespace in table fields.
1705 This makes the structure of the table stay in tact as long as the edited
1706 field does not exceed the column width.
1707 - Minimize the number of realigns. Normally, the table is aligned each time
1708 TAB or RET are pressed to move to another field. With optimization this
1709 happens only if changes to a field might have changed the column width.
1710 Optimization requires replacing the functions `self-insert-command',
1711 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1712 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1713 very good at guessing when a re-align will be necessary, but you can always
1714 force one with \\[org-ctrl-c-ctrl-c].
1716 If you would like to use the optimized version in Org-mode, but the
1717 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1719 This variable can be used to turn on and off the table editor during a session,
1720 but in order to toggle optimization, a restart is required.
1722 See also the variable `org-table-auto-blank-field'."
1723 :group 'org-table
1724 :type '(choice
1725 (const :tag "off" nil)
1726 (const :tag "on" t)
1727 (const :tag "on, optimized" optimized)))
1729 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1730 (version<= emacs-version "24.1"))
1731 "Non-nil means cluster self-insert commands for undo when possible.
1732 If this is set, then, like in the Emacs command loop, 20 consecutive
1733 characters will be undone together.
1734 This is configurable, because there is some impact on typing performance."
1735 :group 'org-table
1736 :type 'boolean)
1738 (defcustom org-table-tab-recognizes-table.el t
1739 "Non-nil means TAB will automatically notice a table.el table.
1740 When it sees such a table, it moves point into it and - if necessary -
1741 calls `table-recognize-table'."
1742 :group 'org-table-editing
1743 :type 'boolean)
1745 (defgroup org-link nil
1746 "Options concerning links in Org-mode."
1747 :tag "Org Link"
1748 :group 'org)
1750 (defvar-local org-link-abbrev-alist-local nil
1751 "Buffer-local version of `org-link-abbrev-alist', which see.
1752 The value of this is taken from the #+LINK lines.")
1754 (defcustom org-link-abbrev-alist nil
1755 "Alist of link abbreviations.
1756 The car of each element is a string, to be replaced at the start of a link.
1757 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1758 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1760 [[linkkey:tag][description]]
1762 The `linkkey' must be a word word, starting with a letter, followed
1763 by letters, numbers, `-' or `_'.
1765 If REPLACE is a string, the tag will simply be appended to create the link.
1766 If the string contains \"%s\", the tag will be inserted there. If the string
1767 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1768 at that point (see the function `url-hexify-string'). If the string contains
1769 the specifier \"%(my-function)\", then the custom function `my-function' will
1770 be invoked: this function takes the tag as its only argument and must return
1771 a string.
1773 REPLACE may also be a function that will be called with the tag as the
1774 only argument to create the link, which should be returned as a string.
1776 See the manual for examples."
1777 :group 'org-link
1778 :type '(repeat
1779 (cons
1780 (string :tag "Protocol")
1781 (choice
1782 (string :tag "Format")
1783 (function)))))
1785 (defcustom org-descriptive-links t
1786 "Non-nil means Org will display descriptive links.
1787 E.g. [[http://orgmode.org][Org website]] will be displayed as
1788 \"Org Website\", hiding the link itself and just displaying its
1789 description. When set to nil, Org will display the full links
1790 literally.
1792 You can interactively set the value of this variable by calling
1793 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1794 :group 'org-link
1795 :type 'boolean)
1797 (defcustom org-link-file-path-type 'adaptive
1798 "How the path name in file links should be stored.
1799 Valid values are:
1801 relative Relative to the current directory, i.e. the directory of the file
1802 into which the link is being inserted.
1803 absolute Absolute path, if possible with ~ for home directory.
1804 noabbrev Absolute path, no abbreviation of home directory.
1805 adaptive Use relative path for files in the current directory and sub-
1806 directories of it. For other files, use an absolute path."
1807 :group 'org-link
1808 :type '(choice
1809 (const relative)
1810 (const absolute)
1811 (const noabbrev)
1812 (const adaptive)))
1814 (defvaralias 'org-activate-links 'org-highlight-links)
1815 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1816 "Types of links that should be highlighted in Org-mode files.
1818 This is a list of symbols, each one of them leading to the
1819 highlighting of a certain link type.
1821 You can still open links that are not highlighted.
1823 In principle, it does not hurt to turn on highlighting for all
1824 link types. There may be a small gain when turning off unused
1825 link types. The types are:
1827 bracket The recommended [[link][description]] or [[link]] links with hiding.
1828 angle Links in angular brackets that may contain whitespace like
1829 <bbdb:Carsten Dominik>.
1830 plain Plain links in normal text, no whitespace, like http://google.com.
1831 radio Text that is matched by a radio target, see manual for details.
1832 tag Tag settings in a headline (link to tag search).
1833 date Time stamps (link to calendar).
1834 footnote Footnote labels.
1836 If you set this variable during an Emacs session, use `org-mode-restart'
1837 in the Org buffer so that the change takes effect."
1838 :group 'org-link
1839 :group 'org-appearance
1840 :type '(set :greedy t
1841 (const :tag "Double bracket links" bracket)
1842 (const :tag "Angular bracket links" angle)
1843 (const :tag "Plain text links" plain)
1844 (const :tag "Radio target matches" radio)
1845 (const :tag "Tags" tag)
1846 (const :tag "Timestamps" date)
1847 (const :tag "Footnotes" footnote)))
1849 (defcustom org-make-link-description-function nil
1850 "Function to use for generating link descriptions from links.
1851 When nil, the link location will be used. This function must take
1852 two parameters: the first one is the link, the second one is the
1853 description generated by `org-insert-link'. The function should
1854 return the description to use."
1855 :group 'org-link
1856 :type '(choice (const nil) (function)))
1858 (defgroup org-link-store nil
1859 "Options concerning storing links in Org-mode."
1860 :tag "Org Store Link"
1861 :group 'org-link)
1863 (defcustom org-url-hexify-p t
1864 "When non-nil, hexify URL when creating a link."
1865 :type 'boolean
1866 :version "24.3"
1867 :group 'org-link-store)
1869 (defcustom org-email-link-description-format "Email %c: %.30s"
1870 "Format of the description part of a link to an email or usenet message.
1871 The following %-escapes will be replaced by corresponding information:
1873 %F full \"From\" field
1874 %f name, taken from \"From\" field, address if no name
1875 %T full \"To\" field
1876 %t first name in \"To\" field, address if no name
1877 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1878 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1879 %s subject
1880 %d date
1881 %m message-id.
1883 You may use normal field width specification between the % and the letter.
1884 This is for example useful to limit the length of the subject.
1886 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1887 :group 'org-link-store
1888 :type 'string)
1890 (defcustom org-from-is-user-regexp
1891 (let (r1 r2)
1892 (when (and user-mail-address (not (string= user-mail-address "")))
1893 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1894 (when (and user-full-name (not (string= user-full-name "")))
1895 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1896 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1897 "Regexp matched against the \"From:\" header of an email or usenet message.
1898 It should match if the message is from the user him/herself."
1899 :group 'org-link-store
1900 :type 'regexp)
1902 (defcustom org-context-in-file-links t
1903 "Non-nil means file links from `org-store-link' contain context.
1904 A search string will be added to the file name with :: as separator and
1905 used to find the context when the link is activated by the command
1906 `org-open-at-point'. When this option is t, the entire active region
1907 will be placed in the search string of the file link. If set to a
1908 positive integer, only the first n lines of context will be stored.
1910 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1911 negates this setting for the duration of the command."
1912 :group 'org-link-store
1913 :type '(choice boolean integer))
1915 (defcustom org-keep-stored-link-after-insertion nil
1916 "Non-nil means keep link in list for entire session.
1918 The command `org-store-link' adds a link pointing to the current
1919 location to an internal list. These links accumulate during a session.
1920 The command `org-insert-link' can be used to insert links into any
1921 Org-mode file (offering completion for all stored links). When this
1922 option is nil, every link which has been inserted once using \\[org-insert-link]
1923 will be removed from the list, to make completing the unused links
1924 more efficient."
1925 :group 'org-link-store
1926 :type 'boolean)
1928 (defgroup org-link-follow nil
1929 "Options concerning following links in Org-mode."
1930 :tag "Org Follow Link"
1931 :group 'org-link)
1933 (defcustom org-link-translation-function nil
1934 "Function to translate links with different syntax to Org syntax.
1935 This can be used to translate links created for example by the Planner
1936 or emacs-wiki packages to Org syntax.
1937 The function must accept two parameters, a TYPE containing the link
1938 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1939 which is everything after the link protocol. It should return a cons
1940 with possibly modified values of type and path.
1941 Org contains a function for this, so if you set this variable to
1942 `org-translate-link-from-planner', you should be able follow many
1943 links created by planner."
1944 :group 'org-link-follow
1945 :type '(choice (const nil) (function)))
1947 (defcustom org-follow-link-hook nil
1948 "Hook that is run after a link has been followed."
1949 :group 'org-link-follow
1950 :type 'hook)
1952 (defcustom org-tab-follows-link nil
1953 "Non-nil means on links TAB will follow the link.
1954 Needs to be set before org.el is loaded.
1955 This really should not be used, it does not make sense, and the
1956 implementation is bad."
1957 :group 'org-link-follow
1958 :type 'boolean)
1960 (defcustom org-return-follows-link nil
1961 "Non-nil means on links RET will follow the link.
1962 In tables, the special behavior of RET has precedence."
1963 :group 'org-link-follow
1964 :type 'boolean)
1966 (defcustom org-mouse-1-follows-link
1967 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1968 "Non-nil means mouse-1 on a link will follow the link.
1969 A longer mouse click will still set point. Does not work on XEmacs.
1970 Needs to be set before org.el is loaded."
1971 :group 'org-link-follow
1972 :version "24.4"
1973 :package-version '(Org . "8.3")
1974 :type '(choice
1975 (const :tag "A double click follows the link" double)
1976 (const :tag "Unconditionally follow the link with mouse-1" t)
1977 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1979 (defcustom org-mark-ring-length 4
1980 "Number of different positions to be recorded in the ring.
1981 Changing this requires a restart of Emacs to work correctly."
1982 :group 'org-link-follow
1983 :type 'integer)
1985 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1986 "Non-nil means internal links in Org files must exactly match a headline.
1987 When nil, the link search tries to match a phrase with all words
1988 in the search text."
1989 :group 'org-link-follow
1990 :version "24.1"
1991 :type '(choice
1992 (const :tag "Use fuzzy text search" nil)
1993 (const :tag "Match only exact headline" t)
1994 (const :tag "Match exact headline or query to create it"
1995 query-to-create)))
1997 (defcustom org-link-frame-setup
1998 '((vm . vm-visit-folder-other-frame)
1999 (vm-imap . vm-visit-imap-folder-other-frame)
2000 (gnus . org-gnus-no-new-news)
2001 (file . find-file-other-window)
2002 (wl . wl-other-frame))
2003 "Setup the frame configuration for following links.
2004 When following a link with Emacs, it may often be useful to display
2005 this link in another window or frame. This variable can be used to
2006 set this up for the different types of links.
2007 For VM, use any of
2008 `vm-visit-folder'
2009 `vm-visit-folder-other-window'
2010 `vm-visit-folder-other-frame'
2011 For Gnus, use any of
2012 `gnus'
2013 `gnus-other-frame'
2014 `org-gnus-no-new-news'
2015 For FILE, use any of
2016 `find-file'
2017 `find-file-other-window'
2018 `find-file-other-frame'
2019 For Wanderlust use any of
2020 `wl'
2021 `wl-other-frame'
2022 For the calendar, use the variable `calendar-setup'.
2023 For BBDB, it is currently only possible to display the matches in
2024 another window."
2025 :group 'org-link-follow
2026 :type '(list
2027 (cons (const vm)
2028 (choice
2029 (const vm-visit-folder)
2030 (const vm-visit-folder-other-window)
2031 (const vm-visit-folder-other-frame)))
2032 (cons (const vm-imap)
2033 (choice
2034 (const vm-visit-imap-folder)
2035 (const vm-visit-imap-folder-other-window)
2036 (const vm-visit-imap-folder-other-frame)))
2037 (cons (const gnus)
2038 (choice
2039 (const gnus)
2040 (const gnus-other-frame)
2041 (const org-gnus-no-new-news)))
2042 (cons (const file)
2043 (choice
2044 (const find-file)
2045 (const find-file-other-window)
2046 (const find-file-other-frame)))
2047 (cons (const wl)
2048 (choice
2049 (const wl)
2050 (const wl-other-frame)))))
2052 (defcustom org-display-internal-link-with-indirect-buffer nil
2053 "Non-nil means use indirect buffer to display infile links.
2054 Activating internal links (from one location in a file to another location
2055 in the same file) normally just jumps to the location. When the link is
2056 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2057 is displayed in
2058 another window. When this option is set, the other window actually displays
2059 an indirect buffer clone of the current buffer, to avoid any visibility
2060 changes to the current buffer."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-open-non-existing-files nil
2065 "Non-nil means `org-open-file' will open non-existing files.
2066 When nil, an error will be generated.
2067 This variable applies only to external applications because they
2068 might choke on non-existing files. If the link is to a file that
2069 will be opened in Emacs, the variable is ignored."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-open-directory-means-index-dot-org nil
2074 "Non-nil means a link to a directory really means to index.org.
2075 When nil, following a directory link will run dired or open a finder/explorer
2076 window on that directory."
2077 :group 'org-link-follow
2078 :type 'boolean)
2080 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2081 "Non-nil means ask for confirmation before executing shell links.
2082 Shell links can be dangerous: just think about a link
2084 [[shell:rm -rf ~/*][Google Search]]
2086 This link would show up in your Org-mode document as \"Google Search\",
2087 but really it would remove your entire home directory.
2088 Therefore we advise against setting this variable to nil.
2089 Just change it to `y-or-n-p' if you want to confirm with a
2090 single keystroke rather than having to type \"yes\"."
2091 :group 'org-link-follow
2092 :type '(choice
2093 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2094 (const :tag "with y-or-n (faster)" y-or-n-p)
2095 (const :tag "no confirmation (dangerous)" nil)))
2096 (put 'org-confirm-shell-link-function
2097 'safe-local-variable
2098 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2100 (defcustom org-confirm-shell-link-not-regexp ""
2101 "A regexp to skip confirmation for shell links."
2102 :group 'org-link-follow
2103 :version "24.1"
2104 :type 'regexp)
2106 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2107 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2108 Elisp links can be dangerous: just think about a link
2110 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2112 This link would show up in your Org-mode document as \"Google Search\",
2113 but really it would remove your entire home directory.
2114 Therefore we advise against setting this variable to nil.
2115 Just change it to `y-or-n-p' if you want to confirm with a
2116 single keystroke rather than having to type \"yes\"."
2117 :group 'org-link-follow
2118 :type '(choice
2119 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2120 (const :tag "with y-or-n (faster)" y-or-n-p)
2121 (const :tag "no confirmation (dangerous)" nil)))
2122 (put 'org-confirm-shell-link-function
2123 'safe-local-variable
2124 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2126 (defcustom org-confirm-elisp-link-not-regexp ""
2127 "A regexp to skip confirmation for Elisp links."
2128 :group 'org-link-follow
2129 :version "24.1"
2130 :type 'regexp)
2132 (defconst org-file-apps-defaults-gnu
2133 '((remote . emacs)
2134 (system . mailcap)
2135 (t . mailcap))
2136 "Default file applications on a UNIX or GNU/Linux system.
2137 See `org-file-apps'.")
2139 (defconst org-file-apps-defaults-macosx
2140 '((remote . emacs)
2141 (t . "open %s")
2142 (system . "open %s")
2143 ("ps.gz" . "gv %s")
2144 ("eps.gz" . "gv %s")
2145 ("dvi" . "xdvi %s")
2146 ("fig" . "xfig %s"))
2147 "Default file applications on a MacOS X system.
2148 The system \"open\" is known as a default, but we use X11 applications
2149 for some files for which the OS does not have a good default.
2150 See `org-file-apps'.")
2152 (defconst org-file-apps-defaults-windowsnt
2153 (list
2154 '(remote . emacs)
2155 (cons t
2156 (list (if (featurep 'xemacs)
2157 'mswindows-shell-execute
2158 'w32-shell-execute)
2159 "open" 'file))
2160 (cons 'system
2161 (list (if (featurep 'xemacs)
2162 'mswindows-shell-execute
2163 'w32-shell-execute)
2164 "open" 'file)))
2165 "Default file applications on a Windows NT system.
2166 The system \"open\" is used for most files.
2167 See `org-file-apps'.")
2169 (defcustom org-file-apps
2170 '((auto-mode . emacs)
2171 ("\\.mm\\'" . default)
2172 ("\\.x?html?\\'" . default)
2173 ("\\.pdf\\'" . default))
2174 "External applications for opening `file:path' items in a document.
2175 Org-mode uses system defaults for different file types, but
2176 you can use this variable to set the application for a given file
2177 extension. The entries in this list are cons cells where the car identifies
2178 files and the cdr the corresponding command. Possible values for the
2179 file identifier are
2180 \"string\" A string as a file identifier can be interpreted in different
2181 ways, depending on its contents:
2183 - Alphanumeric characters only:
2184 Match links with this file extension.
2185 Example: (\"pdf\" . \"evince %s\")
2186 to open PDFs with evince.
2188 - Regular expression: Match links where the
2189 filename matches the regexp. If you want to
2190 use groups here, use shy groups.
2192 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2193 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2194 to open *.html and *.xhtml with firefox.
2196 - Regular expression which contains (non-shy) groups:
2197 Match links where the whole link, including \"::\", and
2198 anything after that, matches the regexp.
2199 In a custom command string, %1, %2, etc. are replaced with
2200 the parts of the link that were matched by the groups.
2201 For backwards compatibility, if a command string is given
2202 that does not use any of the group matches, this case is
2203 handled identically to the second one (i.e. match against
2204 file name only).
2205 In a custom lisp form, you can access the group matches with
2206 (match-string n link).
2208 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2209 to open [[file:document.pdf::5]] with evince at page 5.
2211 `directory' Matches a directory
2212 `remote' Matches a remote file, accessible through tramp or efs.
2213 Remote files most likely should be visited through Emacs
2214 because external applications cannot handle such paths.
2215 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2216 so all files Emacs knows how to handle. Using this with
2217 command `emacs' will open most files in Emacs. Beware that this
2218 will also open html files inside Emacs, unless you add
2219 (\"html\" . default) to the list as well.
2220 t Default for files not matched by any of the other options.
2221 `system' The system command to open files, like `open' on Windows
2222 and Mac OS X, and mailcap under GNU/Linux. This is the command
2223 that will be selected if you call `C-c C-o' with a double
2224 \\[universal-argument] \\[universal-argument] prefix.
2226 Possible values for the command are:
2227 `emacs' The file will be visited by the current Emacs process.
2228 `default' Use the default application for this file type, which is the
2229 association for t in the list, most likely in the system-specific
2230 part.
2231 This can be used to overrule an unwanted setting in the
2232 system-specific variable.
2233 `system' Use the system command for opening files, like \"open\".
2234 This command is specified by the entry whose car is `system'.
2235 Most likely, the system-specific version of this variable
2236 does define this command, but you can overrule/replace it
2237 here.
2238 string A command to be executed by a shell; %s will be replaced
2239 by the path to the file.
2240 sexp A Lisp form which will be evaluated. The file path will
2241 be available in the Lisp variable `file'.
2242 For more examples, see the system specific constants
2243 `org-file-apps-defaults-macosx'
2244 `org-file-apps-defaults-windowsnt'
2245 `org-file-apps-defaults-gnu'."
2246 :group 'org-link-follow
2247 :type '(repeat
2248 (cons (choice :value ""
2249 (string :tag "Extension")
2250 (const :tag "System command to open files" system)
2251 (const :tag "Default for unrecognized files" t)
2252 (const :tag "Remote file" remote)
2253 (const :tag "Links to a directory" directory)
2254 (const :tag "Any files that have Emacs modes"
2255 auto-mode))
2256 (choice :value ""
2257 (const :tag "Visit with Emacs" emacs)
2258 (const :tag "Use default" default)
2259 (const :tag "Use the system command" system)
2260 (string :tag "Command")
2261 (sexp :tag "Lisp form")))))
2263 (defcustom org-doi-server-url "http://dx.doi.org/"
2264 "The URL of the DOI server."
2265 :type 'string
2266 :version "24.3"
2267 :group 'org-link-follow)
2269 (defgroup org-refile nil
2270 "Options concerning refiling entries in Org-mode."
2271 :tag "Org Refile"
2272 :group 'org)
2274 (defcustom org-directory "~/org"
2275 "Directory with org files.
2276 This is just a default location to look for Org files. There is no need
2277 at all to put your files into this directory. It is only used in the
2278 following situations:
2280 1. When a capture template specifies a target file that is not an
2281 absolute path. The path will then be interpreted relative to
2282 `org-directory'
2283 2. When a capture note is filed away in an interactive way (when exiting the
2284 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2285 with `org-directory' as the default path."
2286 :group 'org-refile
2287 :group 'org-capture
2288 :type 'directory)
2290 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2291 "Default target for storing notes.
2292 Used as a fall back file for org-capture.el, for templates that
2293 do not specify a target file."
2294 :group 'org-refile
2295 :group 'org-capture
2296 :type 'file)
2298 (defcustom org-goto-interface 'outline
2299 "The default interface to be used for `org-goto'.
2300 Allowed values are:
2301 outline The interface shows an outline of the relevant file
2302 and the correct heading is found by moving through
2303 the outline or by searching with incremental search.
2304 outline-path-completion Headlines in the current buffer are offered via
2305 completion. This is the interface also used by
2306 the refile command."
2307 :group 'org-refile
2308 :type '(choice
2309 (const :tag "Outline" outline)
2310 (const :tag "Outline-path-completion" outline-path-completion)))
2312 (defcustom org-goto-max-level 5
2313 "Maximum target level when running `org-goto' with refile interface."
2314 :group 'org-refile
2315 :type 'integer)
2317 (defcustom org-reverse-note-order nil
2318 "Non-nil means store new notes at the beginning of a file or entry.
2319 When nil, new notes will be filed to the end of a file or entry.
2320 This can also be a list with cons cells of regular expressions that
2321 are matched against file names, and values."
2322 :group 'org-capture
2323 :group 'org-refile
2324 :type '(choice
2325 (const :tag "Reverse always" t)
2326 (const :tag "Reverse never" nil)
2327 (repeat :tag "By file name regexp"
2328 (cons regexp boolean))))
2330 (defcustom org-log-refile nil
2331 "Information to record when a task is refiled.
2333 Possible values are:
2335 nil Don't add anything
2336 time Add a time stamp to the task
2337 note Prompt for a note and add it with template `org-log-note-headings'
2339 This option can also be set with on a per-file-basis with
2341 #+STARTUP: nologrefile
2342 #+STARTUP: logrefile
2343 #+STARTUP: lognoterefile
2345 You can have local logging settings for a subtree by setting the LOGGING
2346 property to one or more of these keywords.
2348 When bulk-refiling from the agenda, the value `note' is forbidden and
2349 will temporarily be changed to `time'."
2350 :group 'org-refile
2351 :group 'org-progress
2352 :version "24.1"
2353 :type '(choice
2354 (const :tag "No logging" nil)
2355 (const :tag "Record timestamp" time)
2356 (const :tag "Record timestamp with note." note)))
2358 (defcustom org-refile-targets nil
2359 "Targets for refiling entries with \\[org-refile].
2360 This is a list of cons cells. Each cell contains:
2361 - a specification of the files to be considered, either a list of files,
2362 or a symbol whose function or variable value will be used to retrieve
2363 a file name or a list of file names. If you use `org-agenda-files' for
2364 that, all agenda files will be scanned for targets. Nil means consider
2365 headings in the current buffer.
2366 - A specification of how to find candidate refile targets. This may be
2367 any of:
2368 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2369 This tag has to be present in all target headlines, inheritance will
2370 not be considered.
2371 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2372 todo keyword.
2373 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2374 headlines that are refiling targets.
2375 - a cons cell (:level . N). Any headline of level N is considered a target.
2376 Note that, when `org-odd-levels-only' is set, level corresponds to
2377 order in hierarchy, not to the number of stars.
2378 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2379 Note that, when `org-odd-levels-only' is set, level corresponds to
2380 order in hierarchy, not to the number of stars.
2382 Each element of this list generates a set of possible targets.
2383 The union of these sets is presented (with completion) to
2384 the user by `org-refile'.
2386 You can set the variable `org-refile-target-verify-function' to a function
2387 to verify each headline found by the simple criteria above.
2389 When this variable is nil, all top-level headlines in the current buffer
2390 are used, equivalent to the value `((nil . (:level . 1))'."
2391 :group 'org-refile
2392 :type '(repeat
2393 (cons
2394 (choice :value org-agenda-files
2395 (const :tag "All agenda files" org-agenda-files)
2396 (const :tag "Current buffer" nil)
2397 (function) (variable) (file))
2398 (choice :tag "Identify target headline by"
2399 (cons :tag "Specific tag" (const :value :tag) (string))
2400 (cons :tag "TODO keyword" (const :value :todo) (string))
2401 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2402 (cons :tag "Level number" (const :value :level) (integer))
2403 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2405 (defcustom org-refile-target-verify-function nil
2406 "Function to verify if the headline at point should be a refile target.
2407 The function will be called without arguments, with point at the
2408 beginning of the headline. It should return t and leave point
2409 where it is if the headline is a valid target for refiling.
2411 If the target should not be selected, the function must return nil.
2412 In addition to this, it may move point to a place from where the search
2413 should be continued. For example, the function may decide that the entire
2414 subtree of the current entry should be excluded and move point to the end
2415 of the subtree."
2416 :group 'org-refile
2417 :type '(choice
2418 (const nil)
2419 (function)))
2421 (defcustom org-refile-use-cache nil
2422 "Non-nil means cache refile targets to speed up the process.
2423 \\<org-mode-map>\
2424 The cache for a particular file will be updated automatically when
2425 the buffer has been killed, or when any of the marker used for flagging
2426 refile targets no longer points at a live buffer.
2427 If you have added new entries to a buffer that might themselves be targets,
2428 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2429 if you find that easier, \
2430 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2431 \\[org-refile]'."
2432 :group 'org-refile
2433 :version "24.1"
2434 :type 'boolean)
2436 (defcustom org-refile-use-outline-path nil
2437 "Non-nil means provide refile targets as paths.
2438 So a level 3 headline will be available as level1/level2/level3.
2440 When the value is `file', also include the file name (without directory)
2441 into the path. In this case, you can also stop the completion after
2442 the file name, to get entries inserted as top level in the file.
2444 When `full-file-path', include the full file path."
2445 :group 'org-refile
2446 :type '(choice
2447 (const :tag "Not" nil)
2448 (const :tag "Yes" t)
2449 (const :tag "Start with file name" file)
2450 (const :tag "Start with full file path" full-file-path)))
2452 (defcustom org-outline-path-complete-in-steps t
2453 "Non-nil means complete the outline path in hierarchical steps.
2454 When Org-mode uses the refile interface to select an outline path
2455 \(see variable `org-refile-use-outline-path'), the completion of
2456 the path can be done in a single go, or it can be done in steps down
2457 the headline hierarchy. Going in steps is probably the best if you
2458 do not use a special completion package like `ido' or `icicles'.
2459 However, when using these packages, going in one step can be very
2460 fast, while still showing the whole path to the entry."
2461 :group 'org-refile
2462 :type 'boolean)
2464 (defcustom org-refile-allow-creating-parent-nodes nil
2465 "Non-nil means allow to create new nodes as refile targets.
2466 New nodes are then created by adding \"/new node name\" to the completion
2467 of an existing node. When the value of this variable is `confirm',
2468 new node creation must be confirmed by the user (recommended).
2469 When nil, the completion must match an existing entry.
2471 Note that, if the new heading is not seen by the criteria
2472 listed in `org-refile-targets', multiple instances of the same
2473 heading would be created by trying again to file under the new
2474 heading."
2475 :group 'org-refile
2476 :type '(choice
2477 (const :tag "Never" nil)
2478 (const :tag "Always" t)
2479 (const :tag "Prompt for confirmation" confirm)))
2481 (defcustom org-refile-active-region-within-subtree nil
2482 "Non-nil means also refile active region within a subtree.
2484 By default `org-refile' doesn't allow refiling regions if they
2485 don't contain a set of subtrees, but it might be convenient to
2486 do so sometimes: in that case, the first line of the region is
2487 converted to a headline before refiling."
2488 :group 'org-refile
2489 :version "24.1"
2490 :type 'boolean)
2492 (defgroup org-todo nil
2493 "Options concerning TODO items in Org-mode."
2494 :tag "Org TODO"
2495 :group 'org)
2497 (defgroup org-progress nil
2498 "Options concerning Progress logging in Org-mode."
2499 :tag "Org Progress"
2500 :group 'org-time)
2502 (defvar org-todo-interpretation-widgets
2503 '((:tag "Sequence (cycling hits every state)" sequence)
2504 (:tag "Type (cycling directly to DONE)" type))
2505 "The available interpretation symbols for customizing `org-todo-keywords'.
2506 Interested libraries should add to this list.")
2508 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2509 "List of TODO entry keyword sequences and their interpretation.
2510 \\<org-mode-map>This is a list of sequences.
2512 Each sequence starts with a symbol, either `sequence' or `type',
2513 indicating if the keywords should be interpreted as a sequence of
2514 action steps, or as different types of TODO items. The first
2515 keywords are states requiring action - these states will select a headline
2516 for inclusion into the global TODO list Org-mode produces. If one of
2517 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2518 signify that no further action is necessary. If \"|\" is not found,
2519 the last keyword is treated as the only DONE state of the sequence.
2521 The command \\[org-todo] cycles an entry through these states, and one
2522 additional state where no keyword is present. For details about this
2523 cycling, see the manual.
2525 TODO keywords and interpretation can also be set on a per-file basis with
2526 the special #+SEQ_TODO and #+TYP_TODO lines.
2528 Each keyword can optionally specify a character for fast state selection
2529 \(in combination with the variable `org-use-fast-todo-selection')
2530 and specifiers for state change logging, using the same syntax that
2531 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2532 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2533 indicates to record a time stamp each time this state is selected.
2535 Each keyword may also specify if a timestamp or a note should be
2536 recorded when entering or leaving the state, by adding additional
2537 characters in the parenthesis after the keyword. This looks like this:
2538 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2539 record only the time of the state change. With X and Y being either
2540 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2541 Y when leaving the state if and only if the *target* state does not
2542 define X. You may omit any of the fast-selection key or X or /Y,
2543 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2545 For backward compatibility, this variable may also be just a list
2546 of keywords. In this case the interpretation (sequence or type) will be
2547 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2548 :group 'org-todo
2549 :group 'org-keywords
2550 :type '(choice
2551 (repeat :tag "Old syntax, just keywords"
2552 (string :tag "Keyword"))
2553 (repeat :tag "New syntax"
2554 (cons
2555 (choice
2556 :tag "Interpretation"
2557 ;;Quick and dirty way to see
2558 ;;`org-todo-interpretations'. This takes the
2559 ;;place of item arguments
2560 :convert-widget
2561 (lambda (widget)
2562 (widget-put widget
2563 :args (mapcar
2564 (lambda (x)
2565 (widget-convert
2566 (cons 'const x)))
2567 org-todo-interpretation-widgets))
2568 widget))
2569 (repeat
2570 (string :tag "Keyword"))))))
2572 (defvar-local org-todo-keywords-1 nil
2573 "All TODO and DONE keywords active in a buffer.")
2574 (defvar org-todo-keywords-for-agenda nil)
2575 (defvar org-done-keywords-for-agenda nil)
2576 (defvar org-todo-keyword-alist-for-agenda nil)
2577 (defvar org-tag-alist-for-agenda nil
2578 "Alist of all tags from all agenda files.")
2579 (defvar org-tag-groups-alist-for-agenda nil
2580 "Alist of all groups tags from all current agenda files.")
2581 (defvar-local org-tag-groups-alist nil)
2582 (defvar org-agenda-contributing-files nil)
2583 (defvar-local org-not-done-keywords nil)
2584 (defvar-local org-done-keywords nil)
2585 (defvar-local org-todo-heads nil)
2586 (defvar-local org-todo-sets nil)
2587 (defvar-local org-todo-log-states nil)
2588 (defvar-local org-todo-kwd-alist nil)
2589 (defvar-local org-todo-key-alist nil)
2590 (defvar-local org-todo-key-trigger nil)
2592 (defcustom org-todo-interpretation 'sequence
2593 "Controls how TODO keywords are interpreted.
2594 This variable is in principle obsolete and is only used for
2595 backward compatibility, if the interpretation of todo keywords is
2596 not given already in `org-todo-keywords'. See that variable for
2597 more information."
2598 :group 'org-todo
2599 :group 'org-keywords
2600 :type '(choice (const sequence)
2601 (const type)))
2603 (defcustom org-use-fast-todo-selection t
2604 "\\<org-mode-map>\
2605 Non-nil means use the fast todo selection scheme with \\[org-todo].
2606 This variable describes if and under what circumstances the cycling
2607 mechanism for TODO keywords will be replaced by a single-key, direct
2608 selection scheme.
2610 When nil, fast selection is never used.
2612 When the symbol `prefix', it will be used when `org-todo' is called
2613 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2614 in an Org-mode buffer, and
2615 `\\[universal-argument] t' in an agenda buffer.
2617 When t, fast selection is used by default. In this case, the prefix
2618 argument forces cycling instead.
2620 In all cases, the special interface is only used if access keys have
2621 actually been assigned by the user, i.e. if keywords in the configuration
2622 are followed by a letter in parenthesis, like TODO(t)."
2623 :group 'org-todo
2624 :type '(choice
2625 (const :tag "Never" nil)
2626 (const :tag "By default" t)
2627 (const :tag "Only with C-u C-c C-t" prefix)))
2629 (defcustom org-provide-todo-statistics t
2630 "Non-nil means update todo statistics after insert and toggle.
2631 ALL-HEADLINES means update todo statistics by including headlines
2632 with no TODO keyword as well, counting them as not done.
2633 A list of TODO keywords means the same, but skip keywords that are
2634 not in this list.
2635 When set to a list of two lists, the first list contains keywords
2636 to consider as TODO keywords, the second list contains keywords
2637 to consider as DONE keywords.
2639 When this is set, todo statistics is updated in the parent of the
2640 current entry each time a todo state is changed."
2641 :group 'org-todo
2642 :type '(choice
2643 (const :tag "Yes, only for TODO entries" t)
2644 (const :tag "Yes, including all entries" all-headlines)
2645 (repeat :tag "Yes, for TODOs in this list"
2646 (string :tag "TODO keyword"))
2647 (list :tag "Yes, for TODOs and DONEs in these lists"
2648 (repeat (string :tag "TODO keyword"))
2649 (repeat (string :tag "DONE keyword")))
2650 (other :tag "No TODO statistics" nil)))
2652 (defcustom org-hierarchical-todo-statistics t
2653 "Non-nil means TODO statistics covers just direct children.
2654 When nil, all entries in the subtree are considered.
2655 This has only an effect if `org-provide-todo-statistics' is set.
2656 To set this to nil for only a single subtree, use a COOKIE_DATA
2657 property and include the word \"recursive\" into the value."
2658 :group 'org-todo
2659 :type 'boolean)
2661 (defcustom org-after-todo-state-change-hook nil
2662 "Hook which is run after the state of a TODO item was changed.
2663 The new state (a string with a TODO keyword, or nil) is available in the
2664 Lisp variable `org-state'."
2665 :group 'org-todo
2666 :type 'hook)
2668 (defvar org-blocker-hook nil
2669 "Hook for functions that are allowed to block a state change.
2671 Functions in this hook should not modify the buffer.
2672 Each function gets as its single argument a property list,
2673 see `org-trigger-hook' for more information about this list.
2675 If any of the functions in this hook returns nil, the state change
2676 is blocked.")
2678 (defvar org-trigger-hook nil
2679 "Hook for functions that are triggered by a state change.
2681 Each function gets as its single argument a property list with at
2682 least the following elements:
2684 (:type type-of-change :position pos-at-entry-start
2685 :from old-state :to new-state)
2687 Depending on the type, more properties may be present.
2689 This mechanism is currently implemented for:
2691 TODO state changes
2692 ------------------
2693 :type todo-state-change
2694 :from previous state (keyword as a string), or nil, or a symbol
2695 `todo' or `done', to indicate the general type of state.
2696 :to new state, like in :from")
2698 (defcustom org-enforce-todo-dependencies nil
2699 "Non-nil means undone TODO entries will block switching the parent to DONE.
2700 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2701 be blocked if any prior sibling is not yet done.
2702 Finally, if the parent is blocked because of ordered siblings of its own,
2703 the child will also be blocked."
2704 :set (lambda (var val)
2705 (set var val)
2706 (if val
2707 (add-hook 'org-blocker-hook
2708 'org-block-todo-from-children-or-siblings-or-parent)
2709 (remove-hook 'org-blocker-hook
2710 'org-block-todo-from-children-or-siblings-or-parent)))
2711 :group 'org-todo
2712 :type 'boolean)
2714 (defcustom org-enforce-todo-checkbox-dependencies nil
2715 "Non-nil means unchecked boxes will block switching the parent to DONE.
2716 When this is nil, checkboxes have no influence on switching TODO states.
2717 When non-nil, you first need to check off all check boxes before the TODO
2718 entry can be switched to DONE.
2719 This variable needs to be set before org.el is loaded, and you need to
2720 restart Emacs after a change to make the change effective. The only way
2721 to change is while Emacs is running is through the customize interface."
2722 :set (lambda (var val)
2723 (set var val)
2724 (if val
2725 (add-hook 'org-blocker-hook
2726 'org-block-todo-from-checkboxes)
2727 (remove-hook 'org-blocker-hook
2728 'org-block-todo-from-checkboxes)))
2729 :group 'org-todo
2730 :type 'boolean)
2732 (defcustom org-treat-insert-todo-heading-as-state-change nil
2733 "Non-nil means inserting a TODO heading is treated as state change.
2734 So when the command \\[org-insert-todo-heading] is used, state change
2735 logging will apply if appropriate. When nil, the new TODO item will
2736 be inserted directly, and no logging will take place."
2737 :group 'org-todo
2738 :type 'boolean)
2740 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2741 "Non-nil means switching TODO states with S-cursor counts as state change.
2742 This is the default behavior. However, setting this to nil allows a
2743 convenient way to select a TODO state and bypass any logging associated
2744 with that."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-todo-state-tags-triggers nil
2749 "Tag changes that should be triggered by TODO state changes.
2750 This is a list. Each entry is
2752 (state-change (tag . flag) .......)
2754 State-change can be a string with a state, and empty string to indicate the
2755 state that has no TODO keyword, or it can be one of the symbols `todo'
2756 or `done', meaning any not-done or done state, respectively."
2757 :group 'org-todo
2758 :group 'org-tags
2759 :type '(repeat
2760 (cons (choice :tag "When changing to"
2761 (const :tag "Not-done state" todo)
2762 (const :tag "Done state" done)
2763 (string :tag "State"))
2764 (repeat
2765 (cons :tag "Tag action"
2766 (string :tag "Tag")
2767 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2769 (defcustom org-log-done nil
2770 "Information to record when a task moves to the DONE state.
2772 Possible values are:
2774 nil Don't add anything, just change the keyword
2775 time Add a time stamp to the task
2776 note Prompt for a note and add it with template `org-log-note-headings'
2778 This option can also be set with on a per-file-basis with
2780 #+STARTUP: nologdone
2781 #+STARTUP: logdone
2782 #+STARTUP: lognotedone
2784 You can have local logging settings for a subtree by setting the LOGGING
2785 property to one or more of these keywords."
2786 :group 'org-todo
2787 :group 'org-progress
2788 :type '(choice
2789 (const :tag "No logging" nil)
2790 (const :tag "Record CLOSED timestamp" time)
2791 (const :tag "Record CLOSED timestamp with note." note)))
2793 ;; Normalize old uses of org-log-done.
2794 (cond
2795 ((eq org-log-done t) (setq org-log-done 'time))
2796 ((and (listp org-log-done) (memq 'done org-log-done))
2797 (setq org-log-done 'note)))
2799 (defcustom org-log-reschedule nil
2800 "Information to record when the scheduling date of a tasks is modified.
2802 Possible values are:
2804 nil Don't add anything, just change the date
2805 time Add a time stamp to the task
2806 note Prompt for a note and add it with template `org-log-note-headings'
2808 This option can also be set with on a per-file-basis with
2810 #+STARTUP: nologreschedule
2811 #+STARTUP: logreschedule
2812 #+STARTUP: lognotereschedule"
2813 :group 'org-todo
2814 :group 'org-progress
2815 :type '(choice
2816 (const :tag "No logging" nil)
2817 (const :tag "Record timestamp" time)
2818 (const :tag "Record timestamp with note." note)))
2820 (defcustom org-log-redeadline nil
2821 "Information to record when the deadline date of a tasks is modified.
2823 Possible values are:
2825 nil Don't add anything, just change the date
2826 time Add a time stamp to the task
2827 note Prompt for a note and add it with template `org-log-note-headings'
2829 This option can also be set with on a per-file-basis with
2831 #+STARTUP: nologredeadline
2832 #+STARTUP: logredeadline
2833 #+STARTUP: lognoteredeadline
2835 You can have local logging settings for a subtree by setting the LOGGING
2836 property to one or more of these keywords."
2837 :group 'org-todo
2838 :group 'org-progress
2839 :type '(choice
2840 (const :tag "No logging" nil)
2841 (const :tag "Record timestamp" time)
2842 (const :tag "Record timestamp with note." note)))
2844 (defcustom org-log-note-clock-out nil
2845 "Non-nil means record a note when clocking out of an item.
2846 This can also be configured on a per-file basis by adding one of
2847 the following lines anywhere in the buffer:
2849 #+STARTUP: lognoteclock-out
2850 #+STARTUP: nolognoteclock-out"
2851 :group 'org-todo
2852 :group 'org-progress
2853 :type 'boolean)
2855 (defcustom org-log-done-with-time t
2856 "Non-nil means the CLOSED time stamp will contain date and time.
2857 When nil, only the date will be recorded."
2858 :group 'org-progress
2859 :type 'boolean)
2861 (defcustom org-log-note-headings
2862 '((done . "CLOSING NOTE %t")
2863 (state . "State %-12s from %-12S %t")
2864 (note . "Note taken on %t")
2865 (reschedule . "Rescheduled from %S on %t")
2866 (delschedule . "Not scheduled, was %S on %t")
2867 (redeadline . "New deadline from %S on %t")
2868 (deldeadline . "Removed deadline, was %S on %t")
2869 (refile . "Refiled on %t")
2870 (clock-out . ""))
2871 "Headings for notes added to entries.
2873 The value is an alist, with the car being a symbol indicating the
2874 note context, and the cdr is the heading to be used. The heading
2875 may also be the empty string. The following placeholders can be
2876 used:
2878 %t a time stamp.
2879 %T an active time stamp instead the default inactive one
2880 %d a short-format time stamp.
2881 %D an active short-format time stamp.
2882 %s the new TODO state or time stamp (inactive), in double quotes.
2883 %S the old TODO state or time stamp (inactive), in double quotes.
2884 %u the user name.
2885 %U full user name.
2887 In fact, it is not a good idea to change the `state' entry,
2888 because Agenda Log mode depends on the format of these entries."
2889 :group 'org-todo
2890 :group 'org-progress
2891 :type '(list :greedy t
2892 (cons (const :tag "Heading when closing an item" done) string)
2893 (cons (const :tag
2894 "Heading when changing todo state (todo sequence only)"
2895 state) string)
2896 (cons (const :tag "Heading when just taking a note" note) string)
2897 (cons (const :tag "Heading when rescheduling" reschedule) string)
2898 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2899 (cons (const :tag "Heading when changing deadline" redeadline) string)
2900 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2901 (cons (const :tag "Heading when refiling" refile) string)
2902 (cons (const :tag "Heading when clocking out" clock-out) string)))
2904 (unless (assq 'note org-log-note-headings)
2905 (push '(note . "%t") org-log-note-headings))
2907 (defcustom org-log-into-drawer nil
2908 "Non-nil means insert state change notes and time stamps into a drawer.
2909 When nil, state changes notes will be inserted after the headline and
2910 any scheduling and clock lines, but not inside a drawer.
2912 The value of this variable should be the name of the drawer to use.
2913 LOGBOOK is proposed as the default drawer for this purpose, you can
2914 also set this to a string to define the drawer of your choice.
2916 A value of t is also allowed, representing \"LOGBOOK\".
2918 A value of t or nil can also be set with on a per-file-basis with
2920 #+STARTUP: logdrawer
2921 #+STARTUP: nologdrawer
2923 If this variable is set, `org-log-state-notes-insert-after-drawers'
2924 will be ignored.
2926 You can set the property LOG_INTO_DRAWER to overrule this setting for
2927 a subtree.
2929 Do not check directly this variable in a Lisp program. Call
2930 function `org-log-into-drawer' instead."
2931 :group 'org-todo
2932 :group 'org-progress
2933 :type '(choice
2934 (const :tag "Not into a drawer" nil)
2935 (const :tag "LOGBOOK" t)
2936 (string :tag "Other")))
2938 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2940 (defun org-log-into-drawer ()
2941 "Name of the log drawer, as a string, or nil.
2942 This is the value of `org-log-into-drawer'. However, if the
2943 current entry has or inherits a LOG_INTO_DRAWER property, it will
2944 be used instead of the default value."
2945 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2946 (cond ((equal p "nil") nil)
2947 ((equal p "t") "LOGBOOK")
2948 ((stringp p) p)
2949 (p "LOGBOOK")
2950 ((stringp org-log-into-drawer) org-log-into-drawer)
2951 (org-log-into-drawer "LOGBOOK"))))
2953 (defcustom org-log-state-notes-insert-after-drawers nil
2954 "Non-nil means insert state change notes after any drawers in entry.
2955 Only the drawers that *immediately* follow the headline and the
2956 deadline/scheduled line are skipped.
2957 When nil, insert notes right after the heading and perhaps the line
2958 with deadline/scheduling if present.
2960 This variable will have no effect if `org-log-into-drawer' is
2961 set."
2962 :group 'org-todo
2963 :group 'org-progress
2964 :type 'boolean)
2966 (defcustom org-log-states-order-reversed t
2967 "Non-nil means the latest state note will be directly after heading.
2968 When nil, the state change notes will be ordered according to time.
2970 This option can also be set with on a per-file-basis with
2972 #+STARTUP: logstatesreversed
2973 #+STARTUP: nologstatesreversed"
2974 :group 'org-todo
2975 :group 'org-progress
2976 :type 'boolean)
2978 (defcustom org-todo-repeat-to-state nil
2979 "The TODO state to which a repeater should return the repeating task.
2980 By default this is the first task in a TODO sequence, or the previous state
2981 in a TODO_TYP set. But you can specify another task here.
2982 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2983 :group 'org-todo
2984 :version "24.1"
2985 :type '(choice (const :tag "Head of sequence" nil)
2986 (string :tag "Specific state")))
2988 (defcustom org-log-repeat 'time
2989 "Non-nil means record moving through the DONE state when triggering repeat.
2990 An auto-repeating task is immediately switched back to TODO when
2991 marked DONE. If you are not logging state changes (by adding \"@\"
2992 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2993 record a closing note, there will be no record of the task moving
2994 through DONE. This variable forces taking a note anyway.
2996 nil Don't force a record
2997 time Record a time stamp
2998 note Prompt for a note and add it with template `org-log-note-headings'
3000 This option can also be set with on a per-file-basis with
3002 #+STARTUP: nologrepeat
3003 #+STARTUP: logrepeat
3004 #+STARTUP: lognoterepeat
3006 You can have local logging settings for a subtree by setting the LOGGING
3007 property to one or more of these keywords."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type '(choice
3011 (const :tag "Don't force a record" nil)
3012 (const :tag "Force recording the DONE state" time)
3013 (const :tag "Force recording a note with the DONE state" note)))
3016 (defgroup org-priorities nil
3017 "Priorities in Org-mode."
3018 :tag "Org Priorities"
3019 :group 'org-todo)
3021 (defcustom org-enable-priority-commands t
3022 "Non-nil means priority commands are active.
3023 When nil, these commands will be disabled, so that you never accidentally
3024 set a priority."
3025 :group 'org-priorities
3026 :type 'boolean)
3028 (defcustom org-highest-priority ?A
3029 "The highest priority of TODO items. A character like ?A, ?B etc.
3030 Must have a smaller ASCII number than `org-lowest-priority'."
3031 :group 'org-priorities
3032 :type 'character)
3034 (defcustom org-lowest-priority ?C
3035 "The lowest priority of TODO items. A character like ?A, ?B etc.
3036 Must have a larger ASCII number than `org-highest-priority'."
3037 :group 'org-priorities
3038 :type 'character)
3040 (defcustom org-default-priority ?B
3041 "The default priority of TODO items.
3042 This is the priority an item gets if no explicit priority is given.
3043 When starting to cycle on an empty priority the first step in the cycle
3044 depends on `org-priority-start-cycle-with-default'. The resulting first
3045 step priority must not exceed the range from `org-highest-priority' to
3046 `org-lowest-priority' which means that `org-default-priority' has to be
3047 in this range exclusive or inclusive the range boundaries. Else the
3048 first step refuses to set the default and the second will fall back
3049 to (depending on the command used) the highest or lowest priority."
3050 :group 'org-priorities
3051 :type 'character)
3053 (defcustom org-priority-start-cycle-with-default t
3054 "Non-nil means start with default priority when starting to cycle.
3055 When this is nil, the first step in the cycle will be (depending on the
3056 command used) one higher or lower than the default priority.
3057 See also `org-default-priority'."
3058 :group 'org-priorities
3059 :type 'boolean)
3061 (defcustom org-get-priority-function nil
3062 "Function to extract the priority from a string.
3063 The string is normally the headline. If this is nil Org computes the
3064 priority from the priority cookie like [#A] in the headline. It returns
3065 an integer, increasing by 1000 for each priority level.
3066 The user can set a different function here, which should take a string
3067 as an argument and return the numeric priority."
3068 :group 'org-priorities
3069 :version "24.1"
3070 :type '(choice
3071 (const nil)
3072 (function)))
3074 (defgroup org-time nil
3075 "Options concerning time stamps and deadlines in Org-mode."
3076 :tag "Org Time"
3077 :group 'org)
3079 (defcustom org-time-stamp-rounding-minutes '(0 5)
3080 "Number of minutes to round time stamps to.
3081 \\<org-mode-map>\
3082 These are two values, the first applies when first creating a time stamp.
3083 The second applies when changing it with the commands `S-up' and `S-down'.
3084 When changing the time stamp, this means that it will change in steps
3085 of N minutes, as given by the second value.
3087 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3088 numbers should be factors of 60, so for example 5, 10, 15.
3090 When this is larger than 1, you can still force an exact time stamp by using
3091 a double prefix argument to a time stamp command like \
3092 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3093 and by using a prefix arg to `S-up/down' to specify the exact number
3094 of minutes to shift."
3095 :group 'org-time
3096 :get (lambda (var) ; Make sure both elements are there
3097 (if (integerp (default-value var))
3098 (list (default-value var) 5)
3099 (default-value var)))
3100 :type '(list
3101 (integer :tag "when inserting times")
3102 (integer :tag "when modifying times")))
3104 ;; Normalize old customizations of this variable.
3105 (when (integerp org-time-stamp-rounding-minutes)
3106 (setq org-time-stamp-rounding-minutes
3107 (list org-time-stamp-rounding-minutes
3108 org-time-stamp-rounding-minutes)))
3110 (defcustom org-display-custom-times nil
3111 "Non-nil means overlay custom formats over all time stamps.
3112 The formats are defined through the variable `org-time-stamp-custom-formats'.
3113 To turn this on on a per-file basis, insert anywhere in the file:
3114 #+STARTUP: customtime"
3115 :group 'org-time
3116 :set 'set-default
3117 :type 'sexp)
3118 (make-variable-buffer-local 'org-display-custom-times)
3120 (defcustom org-time-stamp-custom-formats
3121 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3122 "Custom formats for time stamps. See `format-time-string' for the syntax.
3123 These are overlaid over the default ISO format if the variable
3124 `org-display-custom-times' is set. Time like %H:%M should be at the
3125 end of the second format. The custom formats are also honored by export
3126 commands, if custom time display is turned on at the time of export."
3127 :group 'org-time
3128 :type 'sexp)
3130 (defun org-time-stamp-format (&optional long inactive)
3131 "Get the right format for a time string."
3132 (let ((f (if long (cdr org-time-stamp-formats)
3133 (car org-time-stamp-formats))))
3134 (if inactive
3135 (concat "[" (substring f 1 -1) "]")
3136 f)))
3138 (defcustom org-time-clocksum-format
3139 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3140 "The format string used when creating CLOCKSUM lines.
3141 This is also used when Org mode generates a time duration.
3143 The value can be a single format string containing two
3144 %-sequences, which will be filled with the number of hours and
3145 minutes in that order.
3147 Alternatively, the value can be a plist associating any of the
3148 keys :years, :months, :weeks, :days, :hours or :minutes with
3149 format strings. The time duration is formatted using only the
3150 time components that are needed and concatenating the results.
3151 If a time unit in absent, it falls back to the next smallest
3152 unit.
3154 The keys :require-years, :require-months, :require-days,
3155 :require-weeks, :require-hours, :require-minutes are also
3156 meaningful. A non-nil value for these keys indicates that the
3157 corresponding time component should always be included, even if
3158 its value is 0.
3161 For example,
3163 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3164 :require-minutes t)
3166 means durations longer than a day will be expressed in days,
3167 hours and minutes, and durations less than a day will always be
3168 expressed in hours and minutes (even for durations less than an
3169 hour).
3171 The value
3173 (:days \"%dd\" :minutes \"%dm\")
3175 means durations longer than a day will be expressed in days and
3176 minutes, and durations less than a day will be expressed entirely
3177 in minutes (even for durations longer than an hour)."
3178 :group 'org-time
3179 :group 'org-clock
3180 :version "24.4"
3181 :package-version '(Org . "8.0")
3182 :type '(choice (string :tag "Format string")
3183 (set :tag "Plist"
3184 (group :inline t (const :tag "Years" :years)
3185 (string :tag "Format string"))
3186 (group :inline t
3187 (const :tag "Always show years" :require-years)
3188 (const t))
3189 (group :inline t (const :tag "Months" :months)
3190 (string :tag "Format string"))
3191 (group :inline t
3192 (const :tag "Always show months" :require-months)
3193 (const t))
3194 (group :inline t (const :tag "Weeks" :weeks)
3195 (string :tag "Format string"))
3196 (group :inline t
3197 (const :tag "Always show weeks" :require-weeks)
3198 (const t))
3199 (group :inline t (const :tag "Days" :days)
3200 (string :tag "Format string"))
3201 (group :inline t
3202 (const :tag "Always show days" :require-days)
3203 (const t))
3204 (group :inline t (const :tag "Hours" :hours)
3205 (string :tag "Format string"))
3206 (group :inline t
3207 (const :tag "Always show hours" :require-hours)
3208 (const t))
3209 (group :inline t (const :tag "Minutes" :minutes)
3210 (string :tag "Format string"))
3211 (group :inline t
3212 (const :tag "Always show minutes" :require-minutes)
3213 (const t)))))
3215 (defcustom org-time-clocksum-use-fractional nil
3216 "When non-nil, \\[org-clock-display] uses fractional times.
3217 See `org-time-clocksum-format' for more on time clock formats."
3218 :group 'org-time
3219 :group 'org-clock
3220 :version "24.3"
3221 :type 'boolean)
3223 (defcustom org-time-clocksum-use-effort-durations nil
3224 "When non-nil, \\[org-clock-display] uses effort durations.
3225 E.g. by default, one day is considered to be a 8 hours effort,
3226 so a task that has been clocked for 16 hours will be displayed
3227 as during 2 days in the clock display or in the clocktable.
3229 See `org-effort-durations' on how to set effort durations
3230 and `org-time-clocksum-format' for more on time clock formats."
3231 :group 'org-time
3232 :group 'org-clock
3233 :version "24.4"
3234 :package-version '(Org . "8.0")
3235 :type 'boolean)
3237 (defcustom org-time-clocksum-fractional-format "%.2f"
3238 "The format string used when creating CLOCKSUM lines,
3239 or when Org mode generates a time duration, if
3240 `org-time-clocksum-use-fractional' is enabled.
3242 The value can be a single format string containing one
3243 %-sequence, which will be filled with the number of hours as
3244 a float.
3246 Alternatively, the value can be a plist associating any of the
3247 keys :years, :months, :weeks, :days, :hours or :minutes with
3248 a format string. The time duration is formatted using the
3249 largest time unit which gives a non-zero integer part. If all
3250 specified formats have zero integer part, the smallest time unit
3251 is used."
3252 :group 'org-time
3253 :type '(choice (string :tag "Format string")
3254 (set (group :inline t (const :tag "Years" :years)
3255 (string :tag "Format string"))
3256 (group :inline t (const :tag "Months" :months)
3257 (string :tag "Format string"))
3258 (group :inline t (const :tag "Weeks" :weeks)
3259 (string :tag "Format string"))
3260 (group :inline t (const :tag "Days" :days)
3261 (string :tag "Format string"))
3262 (group :inline t (const :tag "Hours" :hours)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Minutes" :minutes)
3265 (string :tag "Format string")))))
3267 (defcustom org-deadline-warning-days 14
3268 "Number of days before expiration during which a deadline becomes active.
3269 This variable governs the display in sparse trees and in the agenda.
3270 When 0 or negative, it means use this number (the absolute value of it)
3271 even if a deadline has a different individual lead time specified.
3273 Custom commands can set this variable in the options section."
3274 :group 'org-time
3275 :group 'org-agenda-daily/weekly
3276 :type 'integer)
3278 (defcustom org-scheduled-delay-days 0
3279 "Number of days before a scheduled item becomes active.
3280 This variable governs the display in sparse trees and in the agenda.
3281 The default value (i.e. 0) means: don't delay scheduled item.
3282 When negative, it means use this number (the absolute value of it)
3283 even if a scheduled item has a different individual delay time
3284 specified.
3286 Custom commands can set this variable in the options section."
3287 :group 'org-time
3288 :group 'org-agenda-daily/weekly
3289 :version "24.4"
3290 :package-version '(Org . "8.0")
3291 :type 'integer)
3293 (defcustom org-read-date-prefer-future t
3294 "Non-nil means assume future for incomplete date input from user.
3295 This affects the following situations:
3296 1. The user gives a month but not a year.
3297 For example, if it is April and you enter \"feb 2\", this will be read
3298 as Feb 2, *next* year. \"May 5\", however, will be this year.
3299 2. The user gives a day, but no month.
3300 For example, if today is the 15th, and you enter \"3\", Org-mode will
3301 read this as the third of *next* month. However, if you enter \"17\",
3302 it will be considered as *this* month.
3304 If you set this variable to the symbol `time', then also the following
3305 will work:
3307 3. If the user gives a time.
3308 If the time is before now, it will be interpreted as tomorrow.
3310 Currently none of this works for ISO week specifications.
3312 When this option is nil, the current day, month and year will always be
3313 used as defaults.
3315 See also `org-agenda-jump-prefer-future'."
3316 :group 'org-time
3317 :type '(choice
3318 (const :tag "Never" nil)
3319 (const :tag "Check month and day" t)
3320 (const :tag "Check month, day, and time" time)))
3322 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3323 "Should the agenda jump command prefer the future for incomplete dates?
3324 The default is to do the same as configured in `org-read-date-prefer-future'.
3325 But you can also set a deviating value here.
3326 This may t or nil, or the symbol `org-read-date-prefer-future'."
3327 :group 'org-agenda
3328 :group 'org-time
3329 :version "24.1"
3330 :type '(choice
3331 (const :tag "Use org-read-date-prefer-future"
3332 org-read-date-prefer-future)
3333 (const :tag "Never" nil)
3334 (const :tag "Always" t)))
3336 (defcustom org-read-date-force-compatible-dates t
3337 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3339 Depending on the system Emacs is running on, certain dates cannot
3340 be represented with the type used internally to represent time.
3341 Dates between 1970-1-1 and 2038-1-1 can always be represented
3342 correctly. Some systems allow for earlier dates, some for later,
3343 some for both. One way to find out it to insert any date into an
3344 Org buffer, putting the cursor on the year and hitting S-up and
3345 S-down to test the range.
3347 When this variable is set to t, the date/time prompt will not let
3348 you specify dates outside the 1970-2037 range, so it is certain that
3349 these dates will work in whatever version of Emacs you are
3350 running, and also that you can move a file from one Emacs implementation
3351 to another. WHenever Org is forcing the year for you, it will display
3352 a message and beep.
3354 When this variable is nil, Org will check if the date is
3355 representable in the specific Emacs implementation you are using.
3356 If not, it will force a year, usually the current year, and beep
3357 to remind you. Currently this setting is not recommended because
3358 the likelihood that you will open your Org files in an Emacs that
3359 has limited date range is not negligible.
3361 A workaround for this problem is to use diary sexp dates for time
3362 stamps outside of this range."
3363 :group 'org-time
3364 :version "24.1"
3365 :type 'boolean)
3367 (defcustom org-read-date-display-live t
3368 "Non-nil means display current interpretation of date prompt live.
3369 This display will be in an overlay, in the minibuffer."
3370 :group 'org-time
3371 :type 'boolean)
3373 (defcustom org-read-date-popup-calendar t
3374 "Non-nil means pop up a calendar when prompting for a date.
3375 In the calendar, the date can be selected with mouse-1. However, the
3376 minibuffer will also be active, and you can simply enter the date as well.
3377 When nil, only the minibuffer will be available."
3378 :group 'org-time
3379 :type 'boolean)
3380 (org-defvaralias 'org-popup-calendar-for-date-prompt
3381 'org-read-date-popup-calendar)
3383 (make-obsolete-variable
3384 'org-read-date-minibuffer-setup-hook
3385 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3386 (defcustom org-read-date-minibuffer-setup-hook nil
3387 "Hook to be used to set up keys for the date/time interface.
3388 Add key definitions to `minibuffer-local-map', which will be a
3389 temporary copy.
3391 WARNING: This option is obsolete, you should use
3392 `org-read-date-minibuffer-local-map' to set up keys."
3393 :group 'org-time
3394 :type 'hook)
3396 (defcustom org-extend-today-until 0
3397 "The hour when your day really ends. Must be an integer.
3398 This has influence for the following applications:
3399 - When switching the agenda to \"today\". It it is still earlier than
3400 the time given here, the day recognized as TODAY is actually yesterday.
3401 - When a date is read from the user and it is still before the time given
3402 here, the current date and time will be assumed to be yesterday, 23:59.
3403 Also, timestamps inserted in capture templates follow this rule.
3405 IMPORTANT: This is a feature whose implementation is and likely will
3406 remain incomplete. Really, it is only here because past midnight seems to
3407 be the favorite working time of John Wiegley :-)"
3408 :group 'org-time
3409 :type 'integer)
3411 (defcustom org-use-effective-time nil
3412 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3413 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3414 \"effective time\" of any timestamps between midnight and 8am will be
3415 23:59 of the previous day."
3416 :group 'org-time
3417 :version "24.1"
3418 :type 'boolean)
3420 (defcustom org-use-last-clock-out-time-as-effective-time nil
3421 "When non-nil, use the last clock out time for `org-todo'.
3422 Note that this option has precedence over the combined use of
3423 `org-use-effective-time' and `org-extend-today-until'."
3424 :group 'org-time
3425 :version "24.4"
3426 :package-version '(Org . "8.0")
3427 :type 'boolean)
3429 (defcustom org-edit-timestamp-down-means-later nil
3430 "Non-nil means S-down will increase the time in a time stamp.
3431 When nil, S-up will increase."
3432 :group 'org-time
3433 :type 'boolean)
3435 (defcustom org-calendar-follow-timestamp-change t
3436 "Non-nil means make the calendar window follow timestamp changes.
3437 When a timestamp is modified and the calendar window is visible, it will be
3438 moved to the new date."
3439 :group 'org-time
3440 :type 'boolean)
3442 (defgroup org-tags nil
3443 "Options concerning tags in Org-mode."
3444 :tag "Org Tags"
3445 :group 'org)
3447 (defcustom org-tag-alist nil
3448 "List of tags allowed in Org-mode files.
3449 When this list is nil, Org-mode will base TAG input on what is already in the
3450 buffer.
3451 The value of this variable is an alist, the car of each entry must be a
3452 keyword as a string, the cdr may be a character that is used to select
3453 that tag through the fast-tag-selection interface.
3454 See the manual for details."
3455 :group 'org-tags
3456 :type '(repeat
3457 (choice
3458 (cons (string :tag "Tag name")
3459 (character :tag "Access char"))
3460 (list :tag "Start radio group"
3461 (const :startgroup)
3462 (option (string :tag "Group description")))
3463 (list :tag "Start tag group, non distinct"
3464 (const :startgrouptag)
3465 (option (string :tag "Group description")))
3466 (list :tag "Group tags delimiter"
3467 (const :grouptags))
3468 (list :tag "End radio group"
3469 (const :endgroup)
3470 (option (string :tag "Group description")))
3471 (list :tag "End tag group, non distinct"
3472 (const :endgrouptag)
3473 (option (string :tag "Group description")))
3474 (const :tag "New line" (:newline)))))
3476 (defcustom org-tag-persistent-alist nil
3477 "List of tags that will always appear in all Org-mode files.
3478 This is in addition to any in buffer settings or customizations
3479 of `org-tag-alist'.
3480 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3481 The value of this variable is an alist, the car of each entry must be a
3482 keyword as a string, the cdr may be a character that is used to select
3483 that tag through the fast-tag-selection interface.
3484 See the manual for details.
3485 To disable these tags on a per-file basis, insert anywhere in the file:
3486 #+STARTUP: noptag"
3487 :group 'org-tags
3488 :type '(repeat
3489 (choice
3490 (cons (string :tag "Tag name")
3491 (character :tag "Access char"))
3492 (const :tag "Start radio group" (:startgroup))
3493 (const :tag "Group tags delimiter" (:grouptags))
3494 (const :tag "End radio group" (:endgroup))
3495 (const :tag "New line" (:newline)))))
3497 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3498 "If non-nil, always offer completion for all tags of all agenda files.
3499 Instead of customizing this variable directly, you might want to
3500 set it locally for capture buffers, because there no list of
3501 tags in that file can be created dynamically (there are none).
3503 (add-hook \\='org-capture-mode-hook
3504 (lambda ()
3505 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3506 :group 'org-tags
3507 :version "24.1"
3508 :type 'boolean)
3510 (defvar org-file-tags nil
3511 "List of tags that can be inherited by all entries in the file.
3512 The tags will be inherited if the variable `org-use-tag-inheritance'
3513 says they should be.
3514 This variable is populated from #+FILETAGS lines.")
3516 (defcustom org-use-fast-tag-selection 'auto
3517 "Non-nil means use fast tag selection scheme.
3518 This is a special interface to select and deselect tags with single keys.
3519 When nil, fast selection is never used.
3520 When the symbol `auto', fast selection is used if and only if selection
3521 characters for tags have been configured, either through the variable
3522 `org-tag-alist' or through a #+TAGS line in the buffer.
3523 When t, fast selection is always used and selection keys are assigned
3524 automatically if necessary."
3525 :group 'org-tags
3526 :type '(choice
3527 (const :tag "Always" t)
3528 (const :tag "Never" nil)
3529 (const :tag "When selection characters are configured" auto)))
3531 (defcustom org-fast-tag-selection-single-key nil
3532 "Non-nil means fast tag selection exits after first change.
3533 When nil, you have to press RET to exit it.
3534 During fast tag selection, you can toggle this flag with `C-c'.
3535 This variable can also have the value `expert'. In this case, the window
3536 displaying the tags menu is not even shown, until you press C-c again."
3537 :group 'org-tags
3538 :type '(choice
3539 (const :tag "No" nil)
3540 (const :tag "Yes" t)
3541 (const :tag "Expert" expert)))
3543 (defvar org-fast-tag-selection-include-todo nil
3544 "Non-nil means fast tags selection interface will also offer TODO states.
3545 This is an undocumented feature, you should not rely on it.")
3547 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3548 "The column to which tags should be indented in a headline.
3549 If this number is positive, it specifies the column. If it is negative,
3550 it means that the tags should be flushright to that column. For example,
3551 -80 works well for a normal 80 character screen.
3552 When 0, place tags directly after headline text, with only one space in
3553 between."
3554 :group 'org-tags
3555 :type 'integer)
3557 (defcustom org-auto-align-tags t
3558 "Non-nil keeps tags aligned when modifying headlines.
3559 Some operations (i.e. demoting) change the length of a headline and
3560 therefore shift the tags around. With this option turned on, after
3561 each such operation the tags are again aligned to `org-tags-column'."
3562 :group 'org-tags
3563 :type 'boolean)
3565 (defcustom org-use-tag-inheritance t
3566 "Non-nil means tags in levels apply also for sublevels.
3567 When nil, only the tags directly given in a specific line apply there.
3568 This may also be a list of tags that should be inherited, or a regexp that
3569 matches tags that should be inherited. Additional control is possible
3570 with the variable `org-tags-exclude-from-inheritance' which gives an
3571 explicit list of tags to be excluded from inheritance, even if the value of
3572 `org-use-tag-inheritance' would select it for inheritance.
3574 If this option is t, a match early-on in a tree can lead to a large
3575 number of matches in the subtree when constructing the agenda or creating
3576 a sparse tree. If you only want to see the first match in a tree during
3577 a search, check out the variable `org-tags-match-list-sublevels'."
3578 :group 'org-tags
3579 :type '(choice
3580 (const :tag "Not" nil)
3581 (const :tag "Always" t)
3582 (repeat :tag "Specific tags" (string :tag "Tag"))
3583 (regexp :tag "Tags matched by regexp")))
3585 (defcustom org-tags-exclude-from-inheritance nil
3586 "List of tags that should never be inherited.
3587 This is a way to exclude a few tags from inheritance. For way to do
3588 the opposite, to actively allow inheritance for selected tags,
3589 see the variable `org-use-tag-inheritance'."
3590 :group 'org-tags
3591 :type '(repeat (string :tag "Tag")))
3593 (defun org-tag-inherit-p (tag)
3594 "Check if TAG is one that should be inherited."
3595 (cond
3596 ((member tag org-tags-exclude-from-inheritance) nil)
3597 ((eq org-use-tag-inheritance t) t)
3598 ((not org-use-tag-inheritance) nil)
3599 ((stringp org-use-tag-inheritance)
3600 (string-match org-use-tag-inheritance tag))
3601 ((listp org-use-tag-inheritance)
3602 (member tag org-use-tag-inheritance))
3603 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3605 (defcustom org-tags-match-list-sublevels t
3606 "Non-nil means list also sublevels of headlines matching a search.
3607 This variable applies to tags/property searches, and also to stuck
3608 projects because this search is based on a tags match as well.
3610 When set to the symbol `indented', sublevels are indented with
3611 leading dots.
3613 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3614 the sublevels of a headline matching a tag search often also match
3615 the same search. Listing all of them can create very long lists.
3616 Setting this variable to nil causes subtrees of a match to be skipped.
3618 This variable is semi-obsolete and probably should always be true. It
3619 is better to limit inheritance to certain tags using the variables
3620 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3621 :group 'org-tags
3622 :type '(choice
3623 (const :tag "No, don't list them" nil)
3624 (const :tag "Yes, do list them" t)
3625 (const :tag "List them, indented with leading dots" indented)))
3627 (defcustom org-tags-sort-function nil
3628 "When set, tags are sorted using this function as a comparator."
3629 :group 'org-tags
3630 :type '(choice
3631 (const :tag "No sorting" nil)
3632 (const :tag "Alphabetical" string<)
3633 (const :tag "Reverse alphabetical" string>)
3634 (function :tag "Custom function" nil)))
3636 (defvar org-tags-history nil
3637 "History of minibuffer reads for tags.")
3638 (defvar org-last-tags-completion-table nil
3639 "The last used completion table for tags.")
3640 (defvar org-after-tags-change-hook nil
3641 "Hook that is run after the tags in a line have changed.")
3643 (defgroup org-properties nil
3644 "Options concerning properties in Org-mode."
3645 :tag "Org Properties"
3646 :group 'org)
3648 (defcustom org-property-format "%-10s %s"
3649 "How property key/value pairs should be formatted by `indent-line'.
3650 When `indent-line' hits a property definition, it will format the line
3651 according to this format, mainly to make sure that the values are
3652 lined-up with respect to each other."
3653 :group 'org-properties
3654 :type 'string)
3656 (defcustom org-properties-postprocess-alist nil
3657 "Alist of properties and functions to adjust inserted values.
3658 Elements of this alist must be of the form
3660 ([string] [function])
3662 where [string] must be a property name and [function] must be a
3663 lambda expression: this lambda expression must take one argument,
3664 the value to adjust, and return the new value as a string.
3666 For example, this element will allow the property \"Remaining\"
3667 to be updated wrt the relation between the \"Effort\" property
3668 and the clock summary:
3670 ((\"Remaining\" (lambda(value)
3671 (let ((clocksum (org-clock-sum-current-item))
3672 (effort (org-duration-string-to-minutes
3673 (org-entry-get (point) \"Effort\"))))
3674 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3675 :group 'org-properties
3676 :version "24.1"
3677 :type '(alist :key-type (string :tag "Property")
3678 :value-type (function :tag "Function")))
3680 (defcustom org-use-property-inheritance nil
3681 "Non-nil means properties apply also for sublevels.
3683 This setting is chiefly used during property searches. Turning it on can
3684 cause significant overhead when doing a search, which is why it is not
3685 on by default.
3687 When nil, only the properties directly given in the current entry count.
3688 When t, every property is inherited. The value may also be a list of
3689 properties that should have inheritance, or a regular expression matching
3690 properties that should be inherited.
3692 However, note that some special properties use inheritance under special
3693 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3694 and the properties ending in \"_ALL\" when they are used as descriptor
3695 for valid values of a property.
3697 Note for programmers:
3698 When querying an entry with `org-entry-get', you can control if inheritance
3699 should be used. By default, `org-entry-get' looks only at the local
3700 properties. You can request inheritance by setting the inherit argument
3701 to t (to force inheritance) or to `selective' (to respect the setting
3702 in this variable)."
3703 :group 'org-properties
3704 :type '(choice
3705 (const :tag "Not" nil)
3706 (const :tag "Always" t)
3707 (repeat :tag "Specific properties" (string :tag "Property"))
3708 (regexp :tag "Properties matched by regexp")))
3710 (defun org-property-inherit-p (property)
3711 "Check if PROPERTY is one that should be inherited."
3712 (cond
3713 ((eq org-use-property-inheritance t) t)
3714 ((not org-use-property-inheritance) nil)
3715 ((stringp org-use-property-inheritance)
3716 (string-match org-use-property-inheritance property))
3717 ((listp org-use-property-inheritance)
3718 (member property org-use-property-inheritance))
3719 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3721 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3722 "The default column format, if no other format has been defined.
3723 This variable can be set on the per-file basis by inserting a line
3725 #+COLUMNS: %25ITEM ....."
3726 :group 'org-properties
3727 :type 'string)
3729 (defcustom org-columns-ellipses ".."
3730 "The ellipses to be used when a field in column view is truncated.
3731 When this is the empty string, as many characters as possible are shown,
3732 but then there will be no visual indication that the field has been truncated.
3733 When this is a string of length N, the last N characters of a truncated
3734 field are replaced by this string. If the column is narrower than the
3735 ellipses string, only part of the ellipses string will be shown."
3736 :group 'org-properties
3737 :type 'string)
3739 (defcustom org-columns-modify-value-for-display-function nil
3740 "Function that modifies values for display in column view.
3741 For example, it can be used to cut out a certain part from a time stamp.
3742 The function must take 2 arguments:
3744 column-title The title of the column (*not* the property name)
3745 value The value that should be modified.
3747 The function should return the value that should be displayed,
3748 or nil if the normal value should be used."
3749 :group 'org-properties
3750 :type '(choice (const nil) (function)))
3752 (defconst org-global-properties-fixed
3753 '(("VISIBILITY_ALL" . "folded children content all")
3754 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3755 "List of property/value pairs that can be inherited by any entry.
3757 These are fixed values, for the preset properties. The user variable
3758 that can be used to add to this list is `org-global-properties'.
3760 The entries in this list are cons cells where the car is a property
3761 name and cdr is a string with the value. If the value represents
3762 multiple items like an \"_ALL\" property, separate the items by
3763 spaces.")
3765 (defcustom org-global-properties nil
3766 "List of property/value pairs that can be inherited by any entry.
3768 This list will be combined with the constant `org-global-properties-fixed'.
3770 The entries in this list are cons cells where the car is a property
3771 name and cdr is a string with the value.
3773 You can set buffer-local values for the same purpose in the variable
3774 `org-file-properties' this by adding lines like
3776 #+PROPERTY: NAME VALUE"
3777 :group 'org-properties
3778 :type '(repeat
3779 (cons (string :tag "Property")
3780 (string :tag "Value"))))
3782 (defvar-local org-file-properties nil
3783 "List of property/value pairs that can be inherited by any entry.
3784 Valid for the current buffer.
3785 This variable is populated from #+PROPERTY lines.")
3787 (defgroup org-agenda nil
3788 "Options concerning agenda views in Org-mode."
3789 :tag "Org Agenda"
3790 :group 'org)
3792 (defvar-local org-category nil
3793 "Variable used by org files to set a category for agenda display.
3794 Such files should use a file variable to set it, for example
3796 # -*- mode: org; org-category: \"ELisp\"
3798 or contain a special line
3800 #+CATEGORY: ELisp
3802 If the file does not specify a category, then file's base name
3803 is used instead.")
3804 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3806 (defcustom org-agenda-files nil
3807 "The files to be used for agenda display.
3808 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3809 \\[org-remove-file]. You can also use customize to edit the list.
3811 If an entry is a directory, all files in that directory that are matched by
3812 `org-agenda-file-regexp' will be part of the file list.
3814 If the value of the variable is not a list but a single file name, then
3815 the list of agenda files is actually stored and maintained in that file, one
3816 agenda file per line. In this file paths can be given relative to
3817 `org-directory'. Tilde expansion and environment variable substitution
3818 are also made."
3819 :group 'org-agenda
3820 :type '(choice
3821 (repeat :tag "List of files and directories" file)
3822 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3824 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3825 "Regular expression to match files for `org-agenda-files'.
3826 If any element in the list in that variable contains a directory instead
3827 of a normal file, all files in that directory that are matched by this
3828 regular expression will be included."
3829 :group 'org-agenda
3830 :type 'regexp)
3832 (defcustom org-agenda-text-search-extra-files nil
3833 "List of extra files to be searched by text search commands.
3834 These files will be searched in addition to the agenda files by the
3835 commands `org-search-view' (`\\[org-agenda] s') \
3836 and `org-occur-in-agenda-files'.
3837 Note that these files will only be searched for text search commands,
3838 not for the other agenda views like todo lists, tag searches or the weekly
3839 agenda. This variable is intended to list notes and possibly archive files
3840 that should also be searched by these two commands.
3841 In fact, if the first element in the list is the symbol `agenda-archives',
3842 then all archive files of all agenda files will be added to the search
3843 scope."
3844 :group 'org-agenda
3845 :type '(set :greedy t
3846 (const :tag "Agenda Archives" agenda-archives)
3847 (repeat :inline t (file))))
3849 (org-defvaralias 'org-agenda-multi-occur-extra-files
3850 'org-agenda-text-search-extra-files)
3852 (defcustom org-agenda-skip-unavailable-files nil
3853 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3854 A nil value means to remove them, after a query, from the list."
3855 :group 'org-agenda
3856 :type 'boolean)
3858 (defcustom org-calendar-to-agenda-key [?c]
3859 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3860 The command `org-calendar-goto-agenda' will be bound to this key. The
3861 default is the character `c' because then `c' can be used to switch back and
3862 forth between agenda and calendar."
3863 :group 'org-agenda
3864 :type 'sexp)
3866 (defcustom org-calendar-insert-diary-entry-key [?i]
3867 "The key to be installed in `calendar-mode-map' for adding diary entries.
3868 This option is irrelevant until `org-agenda-diary-file' has been configured
3869 to point to an Org-mode file. When that is the case, the command
3870 `org-agenda-diary-entry' will be bound to the key given here, by default
3871 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3872 if you want to continue doing this, you need to change this to a different
3873 key."
3874 :group 'org-agenda
3875 :type 'sexp)
3877 (defcustom org-agenda-diary-file 'diary-file
3878 "File to which to add new entries with the `i' key in agenda and calendar.
3879 When this is the symbol `diary-file', the functionality in the Emacs
3880 calendar will be used to add entries to the `diary-file'. But when this
3881 points to a file, `org-agenda-diary-entry' will be used instead."
3882 :group 'org-agenda
3883 :type '(choice
3884 (const :tag "The standard Emacs diary file" diary-file)
3885 (file :tag "Special Org file diary entries")))
3887 (eval-after-load "calendar"
3888 '(progn
3889 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3890 'org-calendar-goto-agenda)
3891 (add-hook 'calendar-mode-hook
3892 (lambda ()
3893 (unless (eq org-agenda-diary-file 'diary-file)
3894 (define-key calendar-mode-map
3895 org-calendar-insert-diary-entry-key
3896 'org-agenda-diary-entry))))))
3898 (defgroup org-latex nil
3899 "Options for embedding LaTeX code into Org-mode."
3900 :tag "Org LaTeX"
3901 :group 'org)
3903 (defcustom org-format-latex-options
3904 '(:foreground default :background default :scale 1.0
3905 :html-foreground "Black" :html-background "Transparent"
3906 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3907 "Options for creating images from LaTeX fragments.
3908 This is a property list with the following properties:
3909 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3910 `default' means use the foreground of the default face.
3911 `auto' means use the foreground from the text face.
3912 :background the background color, or \"Transparent\".
3913 `default' means use the background of the default face.
3914 `auto' means use the background from the text face.
3915 :scale a scaling factor for the size of the images, to get more pixels
3916 :html-foreground, :html-background, :html-scale
3917 the same numbers for HTML export.
3918 :matchers a list indicating which matchers should be used to
3919 find LaTeX fragments. Valid members of this list are:
3920 \"begin\" find environments
3921 \"$1\" find single characters surrounded by $.$
3922 \"$\" find math expressions surrounded by $...$
3923 \"$$\" find math expressions surrounded by $$....$$
3924 \"\\(\" find math expressions surrounded by \\(...\\)
3925 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3926 :group 'org-latex
3927 :type 'plist)
3929 (defcustom org-format-latex-signal-error t
3930 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3931 When nil, just push out a message."
3932 :group 'org-latex
3933 :version "24.1"
3934 :type 'boolean)
3936 (defcustom org-latex-to-mathml-jar-file nil
3937 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3938 Use this to specify additional executable file say a jar file.
3940 When using MathToWeb as the converter, specify the full-path to
3941 your mathtoweb.jar file."
3942 :group 'org-latex
3943 :version "24.1"
3944 :type '(choice
3945 (const :tag "None" nil)
3946 (file :tag "JAR file" :must-match t)))
3948 (defcustom org-latex-to-mathml-convert-command nil
3949 "Command to convert LaTeX fragments to MathML.
3950 Replace format-specifiers in the command as noted below and use
3951 `shell-command' to convert LaTeX to MathML.
3952 %j: Executable file in fully expanded form as specified by
3953 `org-latex-to-mathml-jar-file'.
3954 %I: Input LaTeX file in fully expanded form.
3955 %i: The latex fragment to be converted.
3956 %o: Output MathML file.
3958 This command is used by `org-create-math-formula'.
3960 When using MathToWeb as the converter, set this option to
3961 \"java -jar %j -unicode -force -df %o %I\".
3963 When using LaTeXML set this option to
3964 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3965 :group 'org-latex
3966 :version "24.1"
3967 :type '(choice
3968 (const :tag "None" nil)
3969 (string :tag "\nShell command")))
3971 (defcustom org-latex-create-formula-image-program 'dvipng
3972 "Program to convert LaTeX fragments with.
3974 dvipng Process the LaTeX fragments to dvi file, then convert
3975 dvi files to png files using dvipng.
3976 This will also include processing of non-math environments.
3977 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3978 to convert pdf files to png files"
3979 :group 'org-latex
3980 :version "24.1"
3981 :type '(choice
3982 (const :tag "dvipng" dvipng)
3983 (const :tag "imagemagick" imagemagick)))
3985 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3986 "Path to store latex preview images.
3987 A relative path here creates many directories relative to the
3988 processed org files paths. An absolute path puts all preview
3989 images at the same place."
3990 :group 'org-latex
3991 :version "24.3"
3992 :type 'string)
3994 (defun org-format-latex-mathml-available-p ()
3995 "Return t if `org-latex-to-mathml-convert-command' is usable."
3996 (save-match-data
3997 (when (and (boundp 'org-latex-to-mathml-convert-command)
3998 org-latex-to-mathml-convert-command)
3999 (let ((executable (car (split-string
4000 org-latex-to-mathml-convert-command))))
4001 (when (executable-find executable)
4002 (if (string-match
4003 "%j" org-latex-to-mathml-convert-command)
4004 (file-readable-p org-latex-to-mathml-jar-file)
4005 t))))))
4007 (defcustom org-format-latex-header "\\documentclass{article}
4008 \\usepackage[usenames]{color}
4009 \[PACKAGES]
4010 \[DEFAULT-PACKAGES]
4011 \\pagestyle{empty} % do not remove
4012 % The settings below are copied from fullpage.sty
4013 \\setlength{\\textwidth}{\\paperwidth}
4014 \\addtolength{\\textwidth}{-3cm}
4015 \\setlength{\\oddsidemargin}{1.5cm}
4016 \\addtolength{\\oddsidemargin}{-2.54cm}
4017 \\setlength{\\evensidemargin}{\\oddsidemargin}
4018 \\setlength{\\textheight}{\\paperheight}
4019 \\addtolength{\\textheight}{-\\headheight}
4020 \\addtolength{\\textheight}{-\\headsep}
4021 \\addtolength{\\textheight}{-\\footskip}
4022 \\addtolength{\\textheight}{-3cm}
4023 \\setlength{\\topmargin}{1.5cm}
4024 \\addtolength{\\topmargin}{-2.54cm}"
4025 "The document header used for processing LaTeX fragments.
4026 It is imperative that this header make sure that no page number
4027 appears on the page. The package defined in the variables
4028 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4029 will either replace the placeholder \"[PACKAGES]\" in this
4030 header, or they will be appended."
4031 :group 'org-latex
4032 :type 'string)
4034 (defun org-set-packages-alist (var val)
4035 "Set the packages alist and make sure it has 3 elements per entry."
4036 (set var (mapcar (lambda (x)
4037 (if (and (consp x) (= (length x) 2))
4038 (list (car x) (nth 1 x) t)
4040 val)))
4042 (defun org-get-packages-alist (var)
4043 "Get the packages alist and make sure it has 3 elements per entry."
4044 (mapcar (lambda (x)
4045 (if (and (consp x) (= (length x) 2))
4046 (list (car x) (nth 1 x) t)
4048 (default-value var)))
4050 (defcustom org-latex-default-packages-alist
4051 '(("AUTO" "inputenc" t ("pdflatex"))
4052 ("T1" "fontenc" t ("pdflatex"))
4053 ("" "graphicx" t)
4054 ("" "grffile" t)
4055 ("" "longtable" nil)
4056 ("" "wrapfig" nil)
4057 ("" "rotating" nil)
4058 ("normalem" "ulem" t)
4059 ("" "amsmath" t)
4060 ("" "textcomp" t)
4061 ("" "amssymb" t)
4062 ("" "capt-of" nil)
4063 ("" "hyperref" nil))
4064 "Alist of default packages to be inserted in the header.
4066 Change this only if one of the packages here causes an
4067 incompatibility with another package you are using.
4069 The packages in this list are needed by one part or another of
4070 Org mode to function properly:
4072 - inputenc, fontenc: for basic font and character selection
4073 - graphicx: for including images
4074 - grffile: allow periods and spaces in graphics file names
4075 - longtable: For multipage tables
4076 - wrapfig: for figure placement
4077 - rotating: for sideways figures and tables
4078 - ulem: for underline and strike-through
4079 - amsmath: for subscript and superscript and math environments
4080 - textcomp, amssymb: for various symbols used
4081 for interpreting the entities in `org-entities'. You can skip
4082 some of these packages if you don't use any of their symbols.
4083 - capt-of: for captions outside of floats
4084 - hyperref: for cross references
4086 Therefore you should not modify this variable unless you know
4087 what you are doing. The one reason to change it anyway is that
4088 you might be loading some other package that conflicts with one
4089 of the default packages. Each element is either a cell or
4090 a string.
4092 A cell is of the format
4094 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4096 If SNIPPET-FLAG is non-nil, the package also needs to be included
4097 when compiling LaTeX snippets into images for inclusion into
4098 non-LaTeX output. COMPILERS is a list of compilers that should
4099 include the package, see `org-latex-compiler'. If the document
4100 compiler is not in the list, and the list is non-nil, the package
4101 will not be inserted in the final document.
4103 A string will be inserted as-is in the header of the document."
4104 :group 'org-latex
4105 :group 'org-export-latex
4106 :set 'org-set-packages-alist
4107 :get 'org-get-packages-alist
4108 :version "25.1"
4109 :package-version '(Org . "8.3")
4110 :type '(repeat
4111 (choice
4112 (list :tag "options/package pair"
4113 (string :tag "options")
4114 (string :tag "package")
4115 (boolean :tag "Snippet"))
4116 (string :tag "A line of LaTeX"))))
4118 (defcustom org-latex-packages-alist nil
4119 "Alist of packages to be inserted in every LaTeX header.
4121 These will be inserted after `org-latex-default-packages-alist'.
4122 Each element is either a cell or a string.
4124 A cell is of the format:
4126 (\"options\" \"package\" SNIPPET-FLAG)
4128 SNIPPET-FLAG, when non-nil, indicates that this package is also
4129 needed when turning LaTeX snippets into images for inclusion into
4130 non-LaTeX output.
4132 A string will be inserted as-is in the header of the document.
4134 Make sure that you only list packages here which:
4136 - you want in every file;
4137 - do not conflict with the setup in `org-format-latex-header';
4138 - do not conflict with the default packages in
4139 `org-latex-default-packages-alist'."
4140 :group 'org-latex
4141 :group 'org-export-latex
4142 :set 'org-set-packages-alist
4143 :get 'org-get-packages-alist
4144 :type '(repeat
4145 (choice
4146 (list :tag "options/package pair"
4147 (string :tag "options")
4148 (string :tag "package")
4149 (boolean :tag "Snippet"))
4150 (string :tag "A line of LaTeX"))))
4152 (defgroup org-appearance nil
4153 "Settings for Org-mode appearance."
4154 :tag "Org Appearance"
4155 :group 'org)
4157 (defcustom org-level-color-stars-only nil
4158 "Non-nil means fontify only the stars in each headline.
4159 When nil, the entire headline is fontified.
4160 Changing it requires restart of `font-lock-mode' to become effective
4161 also in regions already fontified."
4162 :group 'org-appearance
4163 :type 'boolean)
4165 (defcustom org-hide-leading-stars nil
4166 "Non-nil means hide the first N-1 stars in a headline.
4167 This works by using the face `org-hide' for these stars. This
4168 face is white for a light background, and black for a dark
4169 background. You may have to customize the face `org-hide' to
4170 make this work.
4171 Changing it requires restart of `font-lock-mode' to become effective
4172 also in regions already fontified.
4173 You may also set this on a per-file basis by adding one of the following
4174 lines to the buffer:
4176 #+STARTUP: hidestars
4177 #+STARTUP: showstars"
4178 :group 'org-appearance
4179 :type 'boolean)
4181 (defcustom org-hidden-keywords nil
4182 "List of symbols corresponding to keywords to be hidden the org buffer.
4183 For example, a value \\='(title) for this list will make the document's title
4184 appear in the buffer without the initial #+TITLE: keyword."
4185 :group 'org-appearance
4186 :version "24.1"
4187 :type '(set (const :tag "#+AUTHOR" author)
4188 (const :tag "#+DATE" date)
4189 (const :tag "#+EMAIL" email)
4190 (const :tag "#+TITLE" title)))
4192 (defcustom org-custom-properties nil
4193 "List of properties (as strings) with a special meaning.
4194 The default use of these custom properties is to let the user
4195 hide them with `org-toggle-custom-properties-visibility'."
4196 :group 'org-properties
4197 :group 'org-appearance
4198 :version "24.3"
4199 :type '(repeat (string :tag "Property Name")))
4201 (defcustom org-fontify-done-headline nil
4202 "Non-nil means change the face of a headline if it is marked DONE.
4203 Normally, only the TODO/DONE keyword indicates the state of a headline.
4204 When this is non-nil, the headline after the keyword is set to the
4205 `org-headline-done' as an additional indication."
4206 :group 'org-appearance
4207 :type 'boolean)
4209 (defcustom org-fontify-emphasized-text t
4210 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4211 Changing this variable requires a restart of Emacs to take effect."
4212 :group 'org-appearance
4213 :type 'boolean)
4215 (defcustom org-fontify-whole-heading-line nil
4216 "Non-nil means fontify the whole line for headings.
4217 This is useful when setting a background color for the
4218 org-level-* faces."
4219 :group 'org-appearance
4220 :type 'boolean)
4222 (defcustom org-highlight-latex-and-related nil
4223 "Non-nil means highlight LaTeX related syntax in the buffer.
4224 When non nil, the value should be a list containing any of the
4225 following symbols:
4226 `latex' Highlight LaTeX snippets and environments.
4227 `script' Highlight subscript and superscript.
4228 `entities' Highlight entities."
4229 :group 'org-appearance
4230 :version "24.4"
4231 :package-version '(Org . "8.0")
4232 :type '(choice
4233 (const :tag "No highlighting" nil)
4234 (set :greedy t :tag "Highlight"
4235 (const :tag "LaTeX snippets and environments" latex)
4236 (const :tag "Subscript and superscript" script)
4237 (const :tag "Entities" entities))))
4239 (defcustom org-hide-emphasis-markers nil
4240 "Non-nil mean font-lock should hide the emphasis marker characters."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hide-macro-markers nil
4245 "Non-nil mean font-lock should hide the brackets marking macro calls."
4246 :group 'org-appearance
4247 :type 'boolean)
4249 (defcustom org-pretty-entities nil
4250 "Non-nil means show entities as UTF8 characters.
4251 When nil, the \\name form remains in the buffer."
4252 :group 'org-appearance
4253 :version "24.1"
4254 :type 'boolean)
4256 (defcustom org-pretty-entities-include-sub-superscripts t
4257 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4258 :group 'org-appearance
4259 :version "24.1"
4260 :type 'boolean)
4262 (defvar org-emph-re nil
4263 "Regular expression for matching emphasis.
4264 After a match, the match groups contain these elements:
4265 0 The match of the full regular expression, including the characters
4266 before and after the proper match
4267 1 The character before the proper match, or empty at beginning of line
4268 2 The proper match, including the leading and trailing markers
4269 3 The leading marker like * or /, indicating the type of highlighting
4270 4 The text between the emphasis markers, not including the markers
4271 5 The character after the match, empty at the end of a line")
4272 (defvar org-verbatim-re nil
4273 "Regular expression for matching verbatim text.")
4274 (defvar org-emphasis-regexp-components) ; defined just below
4275 (defvar org-emphasis-alist) ; defined just below
4276 (defun org-set-emph-re (var val)
4277 "Set variable and compute the emphasis regular expression."
4278 (set var val)
4279 (when (and (boundp 'org-emphasis-alist)
4280 (boundp 'org-emphasis-regexp-components)
4281 org-emphasis-alist org-emphasis-regexp-components)
4282 (let* ((e org-emphasis-regexp-components)
4283 (pre (car e))
4284 (post (nth 1 e))
4285 (border (nth 2 e))
4286 (body (nth 3 e))
4287 (nl (nth 4 e))
4288 (body1 (concat body "*?"))
4289 (markers (mapconcat 'car org-emphasis-alist ""))
4290 (vmarkers (mapconcat
4291 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4292 org-emphasis-alist "")))
4293 ;; make sure special characters appear at the right position in the class
4294 (if (string-match "\\^" markers)
4295 (setq markers (concat (replace-match "" t t markers) "^")))
4296 (if (string-match "-" markers)
4297 (setq markers (concat (replace-match "" t t markers) "-")))
4298 (if (string-match "\\^" vmarkers)
4299 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4300 (if (string-match "-" vmarkers)
4301 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4302 (if (> nl 0)
4303 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4304 (int-to-string nl) "\\}")))
4305 ;; Make the regexp
4306 (setq org-emph-re
4307 (concat "\\([" pre "]\\|^\\)"
4308 "\\("
4309 "\\([" markers "]\\)"
4310 "\\("
4311 "[^" border "]\\|"
4312 "[^" border "]"
4313 body1
4314 "[^" border "]"
4315 "\\)"
4316 "\\3\\)"
4317 "\\([" post "]\\|$\\)"))
4318 (setq org-verbatim-re
4319 (concat "\\([" pre "]\\|^\\)"
4320 "\\("
4321 "\\([" vmarkers "]\\)"
4322 "\\("
4323 "[^" border "]\\|"
4324 "[^" border "]"
4325 body1
4326 "[^" border "]"
4327 "\\)"
4328 "\\3\\)"
4329 "\\([" post "]\\|$\\)")))))
4331 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4332 ;; set this option proved cumbersome. See this message/thread:
4333 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4334 (defvar org-emphasis-regexp-components
4335 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4336 "Components used to build the regular expression for emphasis.
4337 This is a list with five entries. Terminology: In an emphasis string
4338 like \" *strong word* \", we call the initial space PREMATCH, the final
4339 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4340 and \"trong wor\" is the body. The different components in this variable
4341 specify what is allowed/forbidden in each part:
4343 pre Chars allowed as prematch. Beginning of line will be allowed too.
4344 post Chars allowed as postmatch. End of line will be allowed too.
4345 border The chars *forbidden* as border characters.
4346 body-regexp A regexp like \".\" to match a body character. Don't use
4347 non-shy groups here, and don't allow newline here.
4348 newline The maximum number of newlines allowed in an emphasis exp.
4350 You need to reload Org or to restart Emacs after customizing this.")
4352 (defcustom org-emphasis-alist
4353 `(("*" bold)
4354 ("/" italic)
4355 ("_" underline)
4356 ("=" org-verbatim verbatim)
4357 ("~" org-code verbatim)
4358 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4359 "Alist of characters and faces to emphasize text.
4360 Text starting and ending with a special character will be emphasized,
4361 for example *bold*, _underlined_ and /italic/. This variable sets the
4362 marker characters and the face to be used by font-lock for highlighting
4363 in Org-mode Emacs buffers.
4365 You need to reload Org or to restart Emacs after customizing this."
4366 :group 'org-appearance
4367 :set 'org-set-emph-re
4368 :version "24.4"
4369 :package-version '(Org . "8.0")
4370 :type '(repeat
4371 (list
4372 (string :tag "Marker character")
4373 (choice
4374 (face :tag "Font-lock-face")
4375 (plist :tag "Face property list"))
4376 (option (const verbatim)))))
4378 (defvar org-protecting-blocks '("src" "example" "export")
4379 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4380 This is needed for font-lock setup.")
4382 ;;; Miscellaneous options
4384 (defgroup org-completion nil
4385 "Completion in Org-mode."
4386 :tag "Org Completion"
4387 :group 'org)
4389 (defcustom org-completion-use-ido nil
4390 "Non-nil means use ido completion wherever possible.
4391 Note that `ido-mode' must be active for this variable to be relevant.
4392 If you decide to turn this variable on, you might well want to turn off
4393 `org-outline-path-complete-in-steps'.
4394 See also `org-completion-use-iswitchb'."
4395 :group 'org-completion
4396 :type 'boolean)
4398 (defcustom org-completion-use-iswitchb nil
4399 "Non-nil means use iswitchb completion wherever possible.
4400 Note that `iswitchb-mode' must be active for this variable to be relevant.
4401 If you decide to turn this variable on, you might well want to turn off
4402 `org-outline-path-complete-in-steps'.
4403 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4404 :group 'org-completion
4405 :type 'boolean)
4407 (defcustom org-completion-fallback-command 'hippie-expand
4408 "The expansion command called by \\[pcomplete] in normal context.
4409 Normal means, no org-mode-specific context."
4410 :group 'org-completion
4411 :type 'function)
4413 ;;; Functions and variables from their packages
4414 ;; Declared here to avoid compiler warnings
4416 ;; XEmacs only
4417 (defvar outline-mode-menu-heading)
4418 (defvar outline-mode-menu-show)
4419 (defvar outline-mode-menu-hide)
4420 (defvar zmacs-regions) ; XEmacs regions
4422 ;; Emacs only
4423 (defvar mark-active)
4425 ;; Various packages
4426 (declare-function calc-eval "calc" (str &optional separator &rest args))
4427 (declare-function calendar-forward-day "cal-move" (arg))
4428 (declare-function calendar-goto-date "cal-move" (date))
4429 (declare-function calendar-goto-today "cal-move" ())
4430 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4431 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4432 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4433 (declare-function cdlatex-tab "ext:cdlatex" ())
4434 (declare-function dired-get-filename
4435 "dired"
4436 (&optional localp no-error-if-not-filep))
4437 (declare-function iswitchb-read-buffer
4438 "iswitchb"
4439 (prompt &optional default require-match start matches-set))
4440 (declare-function org-agenda-change-all-lines
4441 "org-agenda"
4442 (newhead hdmarker &optional fixface just-this))
4443 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4444 "org-agenda"
4445 (&optional end))
4446 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4447 (declare-function org-agenda-format-item
4448 "org-agenda"
4449 (extra txt &optional level category tags dotime noprefix
4450 remove-re habitp))
4451 (declare-function org-agenda-maybe-redo "org-agenda" ())
4452 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4453 (declare-function org-agenda-save-markers-for-cut-and-paste
4454 "org-agenda"
4455 (beg end))
4456 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4457 (declare-function org-agenda-skip "org-agenda" ())
4458 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4459 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4460 (declare-function org-indent-mode "org-indent" (&optional arg))
4461 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4462 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4463 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4464 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4465 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4466 (declare-function parse-time-string "parse-time" (string))
4467 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4468 (declare-function table--at-cell-p
4469 "table"
4470 (position &optional object at-column))
4472 (defvar align-mode-rules-list)
4473 (defvar calc-embedded-close-formula)
4474 (defvar calc-embedded-open-formula)
4475 (defvar calc-embedded-open-mode)
4476 (defvar font-lock-unfontify-region-function)
4477 (defvar iswitchb-temp-buflist)
4478 (defvar org-agenda-tags-todo-honor-ignore-options)
4479 (defvar remember-data-file)
4480 (defvar texmathp-why)
4482 ;;;###autoload
4483 (defun turn-on-orgtbl ()
4484 "Unconditionally turn on `orgtbl-mode'."
4485 (require 'org-table)
4486 (orgtbl-mode 1))
4488 (defun org-at-table-p (&optional table-type)
4489 "Non-nil if the cursor is inside an Org table.
4490 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4491 If `org-enable-table-editor' is nil, return nil unconditionally."
4492 (and
4493 org-enable-table-editor
4494 (save-excursion
4495 (beginning-of-line)
4496 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4497 (or (not (derived-mode-p 'org-mode))
4498 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4499 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4500 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4502 (defun org-at-table.el-p ()
4503 "Non-nil when point is at a table.el table."
4504 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4505 (let ((element (org-element-at-point)))
4506 (and (eq (org-element-type element) 'table)
4507 (eq (org-element-property :type element) 'table.el)))))
4509 (defun org-table-recognize-table.el ()
4510 "If there is a table.el table nearby, recognize it and move into it."
4511 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4512 (beginning-of-line)
4513 (unless (or (looking-at org-table-dataline-regexp)
4514 (not (looking-at org-table1-hline-regexp)))
4515 (forward-line)
4516 (when (looking-at org-table-any-border-regexp)
4517 (forward-line -2)))
4518 (if (re-search-forward "|" (org-table-end t) t)
4519 (progn
4520 (require 'table)
4521 (if (table--at-cell-p (point)) t
4522 (message "recognizing table.el table...")
4523 (table-recognize-table)
4524 (message "recognizing table.el table...done")))
4525 (error "This should not happen"))))
4526 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4527 (make-obsolete 'org-table-recognize-table.el
4528 "please notify the org mailing list if you use this function."
4529 "Org 9.0")
4531 (defun org-at-table-hline-p ()
4532 "Non-nil when point is inside a hline in a table.
4533 Assume point is already in a table. If `org-enable-table-editor'
4534 is nil, return nil unconditionally."
4535 (and org-enable-table-editor
4536 (save-excursion
4537 (beginning-of-line)
4538 (looking-at org-table-hline-regexp))))
4540 (defun org-table-map-tables (function &optional quietly)
4541 "Apply FUNCTION to the start of all tables in the buffer."
4542 (save-excursion
4543 (save-restriction
4544 (widen)
4545 (goto-char (point-min))
4546 (while (re-search-forward org-table-any-line-regexp nil t)
4547 (unless quietly
4548 (message "Mapping tables: %d%%"
4549 (floor (* 100.0 (point)) (buffer-size))))
4550 (beginning-of-line 1)
4551 (when (and (looking-at org-table-line-regexp)
4552 ;; Exclude tables in src/example/verbatim/clocktable blocks
4553 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4554 (save-excursion (funcall function))
4555 (or (looking-at org-table-line-regexp)
4556 (forward-char 1)))
4557 (re-search-forward org-table-any-border-regexp nil 1))))
4558 (unless quietly (message "Mapping tables: done")))
4560 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4561 (declare-function org-clock-update-mode-line "org-clock" ())
4562 (declare-function org-resolve-clocks "org-clock"
4563 (&optional also-non-dangling-p prompt last-valid))
4565 (defun org-at-TBLFM-p (&optional pos)
4566 "Non-nil when point (or POS) is in #+TBLFM line."
4567 (save-excursion
4568 (goto-char (or pos (point)))
4569 (beginning-of-line)
4570 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4571 (eq (org-element-type (org-element-at-point)) 'table))))
4573 (defvar org-clock-start-time)
4574 (defvar org-clock-marker (make-marker)
4575 "Marker recording the last clock-in.")
4576 (defvar org-clock-hd-marker (make-marker)
4577 "Marker recording the last clock-in, but the headline position.")
4578 (defvar org-clock-heading ""
4579 "The heading of the current clock entry.")
4580 (defun org-clock-is-active ()
4581 "Return the buffer where the clock is currently running.
4582 Return nil if no clock is running."
4583 (marker-buffer org-clock-marker))
4585 (defun org-check-running-clock ()
4586 "Check if the current buffer contains the running clock.
4587 If yes, offer to stop it and to save the buffer with the changes."
4588 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4589 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4590 (buffer-name))))
4591 (org-clock-out)
4592 (when (y-or-n-p "Save changed buffer?")
4593 (save-buffer))))
4595 (defun org-clocktable-try-shift (dir n)
4596 "Check if this line starts a clock table, if yes, shift the time block."
4597 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4598 (org-clocktable-shift dir n)))
4600 ;;;###autoload
4601 (defun org-clock-persistence-insinuate ()
4602 "Set up hooks for clock persistence."
4603 (require 'org-clock)
4604 (add-hook 'org-mode-hook 'org-clock-load)
4605 (add-hook 'kill-emacs-hook 'org-clock-save))
4607 (defgroup org-archive nil
4608 "Options concerning archiving in Org-mode."
4609 :tag "Org Archive"
4610 :group 'org-structure)
4612 (defcustom org-archive-location "%s_archive::"
4613 "The location where subtrees should be archived.
4615 The value of this variable is a string, consisting of two parts,
4616 separated by a double-colon. The first part is a filename and
4617 the second part is a headline.
4619 When the filename is omitted, archiving happens in the same file.
4620 %s in the filename will be replaced by the current file
4621 name (without the directory part). Archiving to a different file
4622 is useful to keep archived entries from contributing to the
4623 Org-mode Agenda.
4625 The archived entries will be filed as subtrees of the specified
4626 headline. When the headline is omitted, the subtrees are simply
4627 filed away at the end of the file, as top-level entries. Also in
4628 the heading you can use %s to represent the file name, this can be
4629 useful when using the same archive for a number of different files.
4631 Here are a few examples:
4632 \"%s_archive::\"
4633 If the current file is Projects.org, archive in file
4634 Projects.org_archive, as top-level trees. This is the default.
4636 \"::* Archived Tasks\"
4637 Archive in the current file, under the top-level headline
4638 \"* Archived Tasks\".
4640 \"~/org/archive.org::\"
4641 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4643 \"~/org/archive.org::* From %s\"
4644 Archive in file ~/org/archive.org (absolute path), under headlines
4645 \"From FILENAME\" where file name is the current file name.
4647 \"~/org/datetree.org::datetree/* Finished Tasks\"
4648 The \"datetree/\" string is special, signifying to archive
4649 items to the datetree. Items are placed in either the CLOSED
4650 date of the item, or the current date if there is no CLOSED date.
4651 The heading will be a subentry to the current date. There doesn't
4652 need to be a heading, but there always needs to be a slash after
4653 datetree. For example, to store archived items directly in the
4654 datetree, use \"~/org/datetree.org::datetree/\".
4656 \"basement::** Finished Tasks\"
4657 Archive in file ./basement (relative path), as level 3 trees
4658 below the level 2 heading \"** Finished Tasks\".
4660 You may set this option on a per-file basis by adding to the buffer a
4661 line like
4663 #+ARCHIVE: basement::** Finished Tasks
4665 You may also define it locally for a subtree by setting an ARCHIVE property
4666 in the entry. If such a property is found in an entry, or anywhere up
4667 the hierarchy, it will be used."
4668 :group 'org-archive
4669 :type 'string)
4671 (defcustom org-agenda-skip-archived-trees t
4672 "Non-nil means the agenda will skip any items located in archived trees.
4673 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4674 variable is no longer recommended, you should leave it at the value t.
4675 Instead, use the key `v' to cycle the archives-mode in the agenda."
4676 :group 'org-archive
4677 :group 'org-agenda-skip
4678 :type 'boolean)
4680 (defcustom org-columns-skip-archived-trees t
4681 "Non-nil means ignore archived trees when creating column view."
4682 :group 'org-archive
4683 :group 'org-properties
4684 :type 'boolean)
4686 (defcustom org-cycle-open-archived-trees nil
4687 "Non-nil means `org-cycle' will open archived trees.
4688 An archived tree is a tree marked with the tag ARCHIVE.
4689 When nil, archived trees will stay folded. You can still open them with
4690 normal outline commands like `show-all', but not with the cycling commands."
4691 :group 'org-archive
4692 :group 'org-cycle
4693 :type 'boolean)
4695 (defcustom org-sparse-tree-open-archived-trees nil
4696 "Non-nil means sparse tree construction shows matches in archived trees.
4697 When nil, matches in these trees are highlighted, but the trees are kept in
4698 collapsed state."
4699 :group 'org-archive
4700 :group 'org-sparse-trees
4701 :type 'boolean)
4703 (defcustom org-sparse-tree-default-date-type nil
4704 "The default date type when building a sparse tree.
4705 When this is nil, a date is a scheduled or a deadline timestamp.
4706 Otherwise, these types are allowed:
4708 all: all timestamps
4709 active: only active timestamps (<...>)
4710 inactive: only inactive timestamps ([...])
4711 scheduled: only scheduled timestamps
4712 deadline: only deadline timestamps"
4713 :type '(choice (const :tag "Scheduled or deadline" nil)
4714 (const :tag "All timestamps" all)
4715 (const :tag "Only active timestamps" active)
4716 (const :tag "Only inactive timestamps" inactive)
4717 (const :tag "Only scheduled timestamps" scheduled)
4718 (const :tag "Only deadline timestamps" deadline)
4719 (const :tag "Only closed timestamps" closed))
4720 :version "25.1"
4721 :package-version '(Org . "8.3")
4722 :group 'org-sparse-trees)
4724 (defun org-cycle-hide-archived-subtrees (state)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (when (and (not org-cycle-open-archived-trees)
4727 (not (memq state '(overview folded))))
4728 (save-excursion
4729 (let* ((globalp (memq state '(contents all)))
4730 (beg (if globalp (point-min) (point)))
4731 (end (if globalp (point-max) (org-end-of-subtree t))))
4732 (org-hide-archived-subtrees beg end)
4733 (goto-char beg)
4734 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4735 (message "%s" (substitute-command-keys
4736 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4738 (defun org-force-cycle-archived ()
4739 "Cycle subtree even if it is archived."
4740 (interactive)
4741 (setq this-command 'org-cycle)
4742 (let ((org-cycle-open-archived-trees t))
4743 (call-interactively 'org-cycle)))
4745 (defun org-hide-archived-subtrees (beg end)
4746 "Re-hide all archived subtrees after a visibility state change."
4747 (org-with-wide-buffer
4748 (let ((case-fold-search nil)
4749 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4750 (goto-char beg)
4751 ;; Include headline point is currently on.
4752 (beginning-of-line)
4753 (while (and (< (point) end) (re-search-forward re end t))
4754 (when (member org-archive-tag (org-get-tags))
4755 (org-flag-subtree t)
4756 (org-end-of-subtree t))))))
4758 (declare-function outline-end-of-heading "outline" ())
4759 (declare-function outline-flag-region "outline" (from to flag))
4760 (defun org-flag-subtree (flag)
4761 (save-excursion
4762 (org-back-to-heading t)
4763 (outline-end-of-heading)
4764 (outline-flag-region (point)
4765 (progn (org-end-of-subtree t) (point))
4766 flag)))
4768 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4770 ;; Declare Column View Code
4772 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4773 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4774 (declare-function org-columns-compute "org-colview" (property))
4776 ;; Declare ID code
4778 (declare-function org-id-store-link "org-id")
4779 (declare-function org-id-locations-load "org-id")
4780 (declare-function org-id-locations-save "org-id")
4781 (defvar org-id-track-globally)
4783 ;;; Variables for pre-computed regular expressions, all buffer local
4785 (defvar-local org-todo-regexp nil
4786 "Matches any of the TODO state keywords.")
4787 (defvar-local org-not-done-regexp nil
4788 "Matches any of the TODO state keywords except the last one.")
4789 (defvar-local org-not-done-heading-regexp nil
4790 "Matches a TODO headline that is not done.")
4791 (defvar-local org-todo-line-regexp nil
4792 "Matches a headline and puts TODO state into group 2 if present.")
4793 (defvar-local org-complex-heading-regexp nil
4794 "Matches a headline and puts everything into groups:
4795 group 1: the stars
4796 group 2: The todo keyword, maybe
4797 group 3: Priority cookie
4798 group 4: True headline
4799 group 5: Tags")
4800 (defvar-local org-complex-heading-regexp-format nil
4801 "Printf format to make regexp to match an exact headline.
4802 This regexp will match the headline of any node which has the
4803 exact headline text that is put into the format, but may have any
4804 TODO state, priority and tags.")
4805 (defvar-local org-todo-line-tags-regexp nil
4806 "Matches a headline and puts TODO state into group 2 if present.
4807 Also put tags into group 4 if tags are present.")
4809 (defconst org-plain-time-of-day-regexp
4810 (concat
4811 "\\(\\<[012]?[0-9]"
4812 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4813 "\\(--?"
4814 "\\(\\<[012]?[0-9]"
4815 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4816 "\\)?")
4817 "Regular expression to match a plain time or time range.
4818 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4819 groups carry important information:
4820 0 the full match
4821 1 the first time, range or not
4822 8 the second time, if it is a range.")
4824 (defconst org-plain-time-extension-regexp
4825 (concat
4826 "\\(\\<[012]?[0-9]"
4827 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4828 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4829 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4830 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4831 groups carry important information:
4832 0 the full match
4833 7 hours of duration
4834 9 minutes of duration")
4836 (defconst org-stamp-time-of-day-regexp
4837 (concat
4838 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4839 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4840 "\\(--?"
4841 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4842 "Regular expression to match a timestamp time or time range.
4843 After a match, the following groups carry important information:
4844 0 the full match
4845 1 date plus weekday, for back referencing to make sure both times are on the same day
4846 2 the first time, range or not
4847 4 the second time, if it is a range.")
4849 (defconst org-startup-options
4850 '(("fold" org-startup-folded t)
4851 ("overview" org-startup-folded t)
4852 ("nofold" org-startup-folded nil)
4853 ("showall" org-startup-folded nil)
4854 ("showeverything" org-startup-folded showeverything)
4855 ("content" org-startup-folded content)
4856 ("indent" org-startup-indented t)
4857 ("noindent" org-startup-indented nil)
4858 ("hidestars" org-hide-leading-stars t)
4859 ("showstars" org-hide-leading-stars nil)
4860 ("odd" org-odd-levels-only t)
4861 ("oddeven" org-odd-levels-only nil)
4862 ("align" org-startup-align-all-tables t)
4863 ("noalign" org-startup-align-all-tables nil)
4864 ("inlineimages" org-startup-with-inline-images t)
4865 ("noinlineimages" org-startup-with-inline-images nil)
4866 ("latexpreview" org-startup-with-latex-preview t)
4867 ("nolatexpreview" org-startup-with-latex-preview nil)
4868 ("customtime" org-display-custom-times t)
4869 ("logdone" org-log-done time)
4870 ("lognotedone" org-log-done note)
4871 ("nologdone" org-log-done nil)
4872 ("lognoteclock-out" org-log-note-clock-out t)
4873 ("nolognoteclock-out" org-log-note-clock-out nil)
4874 ("logrepeat" org-log-repeat state)
4875 ("lognoterepeat" org-log-repeat note)
4876 ("logdrawer" org-log-into-drawer t)
4877 ("nologdrawer" org-log-into-drawer nil)
4878 ("logstatesreversed" org-log-states-order-reversed t)
4879 ("nologstatesreversed" org-log-states-order-reversed nil)
4880 ("nologrepeat" org-log-repeat nil)
4881 ("logreschedule" org-log-reschedule time)
4882 ("lognotereschedule" org-log-reschedule note)
4883 ("nologreschedule" org-log-reschedule nil)
4884 ("logredeadline" org-log-redeadline time)
4885 ("lognoteredeadline" org-log-redeadline note)
4886 ("nologredeadline" org-log-redeadline nil)
4887 ("logrefile" org-log-refile time)
4888 ("lognoterefile" org-log-refile note)
4889 ("nologrefile" org-log-refile nil)
4890 ("fninline" org-footnote-define-inline t)
4891 ("nofninline" org-footnote-define-inline nil)
4892 ("fnlocal" org-footnote-section nil)
4893 ("fnauto" org-footnote-auto-label t)
4894 ("fnprompt" org-footnote-auto-label nil)
4895 ("fnconfirm" org-footnote-auto-label confirm)
4896 ("fnplain" org-footnote-auto-label plain)
4897 ("fnadjust" org-footnote-auto-adjust t)
4898 ("nofnadjust" org-footnote-auto-adjust nil)
4899 ("constcgs" constants-unit-system cgs)
4900 ("constSI" constants-unit-system SI)
4901 ("noptag" org-tag-persistent-alist nil)
4902 ("hideblocks" org-hide-block-startup t)
4903 ("nohideblocks" org-hide-block-startup nil)
4904 ("beamer" org-startup-with-beamer-mode t)
4905 ("entitiespretty" org-pretty-entities t)
4906 ("entitiesplain" org-pretty-entities nil))
4907 "Variable associated with STARTUP options for org-mode.
4908 Each element is a list of three items: the startup options (as written
4909 in the #+STARTUP line), the corresponding variable, and the value to set
4910 this variable to if the option is found. An optional forth element PUSH
4911 means to push this value onto the list in the variable.")
4913 (defcustom org-group-tags t
4914 "When non-nil (the default), use group tags.
4915 This can be turned on/off through `org-toggle-tags-groups'."
4916 :group 'org-tags
4917 :group 'org-startup
4918 :type 'boolean)
4920 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4922 (defun org-toggle-tags-groups ()
4923 "Toggle support for group tags.
4924 Support for group tags is controlled by the option
4925 `org-group-tags', which is non-nil by default."
4926 (interactive)
4927 (setq org-group-tags (not org-group-tags))
4928 (cond ((and (derived-mode-p 'org-agenda-mode)
4929 org-group-tags)
4930 (org-agenda-redo))
4931 ((derived-mode-p 'org-mode)
4932 (let ((org-inhibit-startup t)) (org-mode))))
4933 (message "Groups tags support has been turned %s"
4934 (if org-group-tags "on" "off")))
4936 (defun org-set-regexps-and-options (&optional tags-only)
4937 "Precompute regular expressions used in the current buffer.
4938 When optional argument TAGS-ONLY is non-nil, only compute tags
4939 related expressions."
4940 (when (derived-mode-p 'org-mode)
4941 (let ((alist (org--setup-collect-keywords
4942 (org-make-options-regexp
4943 (append '("FILETAGS" "TAGS" "SETUPFILE")
4944 (and (not tags-only)
4945 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4946 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4947 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4948 (org--setup-process-tags
4949 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4950 (unless tags-only
4951 ;; File properties.
4952 (setq-local org-file-properties (cdr (assq 'property alist)))
4953 ;; Archive location.
4954 (let ((archive (cdr (assq 'archive alist))))
4955 (when archive (setq-local org-archive-location archive)))
4956 ;; Category.
4957 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4958 (when cat
4959 (setq-local org-category (intern cat))
4960 (setq-local org-file-properties
4961 (org--update-property-plist
4962 "CATEGORY" cat org-file-properties))))
4963 ;; Columns.
4964 (let ((column (cdr (assq 'columns alist))))
4965 (when column (setq-local org-columns-default-format column)))
4966 ;; Constants.
4967 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4968 ;; Link abbreviations.
4969 (let ((links (cdr (assq 'link alist))))
4970 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4971 ;; Priorities.
4972 (let ((priorities (cdr (assq 'priorities alist))))
4973 (when priorities
4974 (setq-local org-highest-priority (nth 0 priorities))
4975 (setq-local org-lowest-priority (nth 1 priorities))
4976 (setq-local org-default-priority (nth 2 priorities))))
4977 ;; Scripts.
4978 (let ((scripts (assq 'scripts alist)))
4979 (when scripts
4980 (setq-local org-use-sub-superscripts (cdr scripts))))
4981 ;; Startup options.
4982 (let ((startup (cdr (assq 'startup alist))))
4983 (dolist (option startup)
4984 (let ((entry (assoc-string option org-startup-options t)))
4985 (when entry
4986 (let ((var (nth 1 entry))
4987 (val (nth 2 entry)))
4988 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4989 (unless (listp (symbol-value var))
4990 (set (make-local-variable var) nil))
4991 (add-to-list var val)))))))
4992 ;; TODO keywords.
4993 (setq-local org-todo-kwd-alist nil)
4994 (setq-local org-todo-key-alist nil)
4995 (setq-local org-todo-key-trigger nil)
4996 (setq-local org-todo-keywords-1 nil)
4997 (setq-local org-done-keywords nil)
4998 (setq-local org-todo-heads nil)
4999 (setq-local org-todo-sets nil)
5000 (setq-local org-todo-log-states nil)
5001 (let ((todo-sequences
5002 (or (nreverse (cdr (assq 'todo alist)))
5003 (let ((d (default-value 'org-todo-keywords)))
5004 (if (not (stringp (car d))) d
5005 ;; XXX: Backward compatibility code.
5006 (list (cons org-todo-interpretation d)))))))
5007 (dolist (sequence todo-sequences)
5008 (let* ((sequence (or (run-hook-with-args-until-success
5009 'org-todo-setup-filter-hook sequence)
5010 sequence))
5011 (sequence-type (car sequence))
5012 (keywords (cdr sequence))
5013 (sep (member "|" keywords))
5014 names alist)
5015 (dolist (k (remove "|" keywords))
5016 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5018 (error "Invalid TODO keyword %s" k))
5019 (let ((name (match-string 1 k))
5020 (key (match-string 2 k))
5021 (log (org-extract-log-state-settings k)))
5022 (push name names)
5023 (push (cons name (and key (string-to-char key))) alist)
5024 (when log (push log org-todo-log-states))))
5025 (let* ((names (nreverse names))
5026 (done (if sep (org-remove-keyword-keys (cdr sep))
5027 (last names)))
5028 (head (car names))
5029 (tail (list sequence-type head (car done) (org-last done))))
5030 (add-to-list 'org-todo-heads head 'append)
5031 (push names org-todo-sets)
5032 (setq org-done-keywords (append org-done-keywords done nil))
5033 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5034 (setq org-todo-key-alist
5035 (append org-todo-key-alist
5036 (and alist
5037 (append '((:startgroup))
5038 (nreverse alist)
5039 '((:endgroup))))))
5040 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5041 (setq org-todo-sets (nreverse org-todo-sets)
5042 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5043 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5044 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5045 ;; Compute the regular expressions and other local variables.
5046 ;; Using `org-outline-regexp-bol' would complicate them much,
5047 ;; because of the fixed white space at the end of that string.
5048 (unless org-done-keywords
5049 (setq org-done-keywords
5050 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5051 (setq org-not-done-keywords
5052 (org-delete-all org-done-keywords
5053 (copy-sequence org-todo-keywords-1))
5054 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5055 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5056 org-not-done-heading-regexp
5057 (format org-heading-keyword-regexp-format org-not-done-regexp)
5058 org-todo-line-regexp
5059 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5060 org-complex-heading-regexp
5061 (concat "^\\(\\*+\\)"
5062 "\\(?: +" org-todo-regexp "\\)?"
5063 "\\(?: +\\(\\[#.\\]\\)\\)?"
5064 "\\(?: +\\(.*?\\)\\)??"
5065 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5066 "[ \t]*$")
5067 org-complex-heading-regexp-format
5068 (concat "^\\(\\*+\\)"
5069 "\\(?: +" org-todo-regexp "\\)?"
5070 "\\(?: +\\(\\[#.\\]\\)\\)?"
5071 "\\(?: +"
5072 ;; Stats cookies can be stuck to body.
5073 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5074 "\\(%s\\)"
5075 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5076 "\\)"
5077 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5078 "[ \t]*$")
5079 org-todo-line-tags-regexp
5080 (concat "^\\(\\*+\\)"
5081 "\\(?: +" org-todo-regexp "\\)?"
5082 "\\(?: +\\(.*?\\)\\)??"
5083 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5084 "[ \t]*$"))
5085 (org-compute-latex-and-related-regexp)))))
5087 (defun org--setup-collect-keywords (regexp &optional files alist)
5088 "Return setup keywords values as an alist.
5090 REGEXP matches a subset of setup keywords. FILES is a list of
5091 file names already visited. It is used to avoid circular setup
5092 files. ALIST, when non-nil, is the alist computed so far.
5094 Return value contains the following keys: `archive', `category',
5095 `columns', `constants', `filetags', `link', `priorities',
5096 `property', `scripts', `startup', `tags' and `todo'."
5097 (org-with-wide-buffer
5098 (goto-char (point-min))
5099 (let ((case-fold-search t))
5100 (while (re-search-forward regexp nil t)
5101 (let ((element (org-element-at-point)))
5102 (when (eq (org-element-type element) 'keyword)
5103 (let ((key (org-element-property :key element))
5104 (value (org-element-property :value element)))
5105 (cond
5106 ((equal key "ARCHIVE")
5107 (when (org-string-nw-p value)
5108 (push (cons 'archive value) alist)))
5109 ((equal key "CATEGORY") (push (cons 'category value) alist))
5110 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5111 ((equal key "CONSTANTS")
5112 (let* ((constants (assq 'constants alist))
5113 (store (cdr constants)))
5114 (dolist (pair (org-split-string value))
5115 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5116 pair)
5117 (let* ((name (match-string 1 pair))
5118 (value (match-string 2 pair))
5119 (old (assoc name store)))
5120 (if old (setcdr old value)
5121 (push (cons name value) store)))))
5122 (if constants (setcdr constants store)
5123 (push (cons 'constants store) alist))))
5124 ((equal key "FILETAGS")
5125 (when (org-string-nw-p value)
5126 (let ((old (assq 'filetags alist))
5127 (new (apply #'nconc
5128 (mapcar (lambda (x) (org-split-string x ":"))
5129 (org-split-string value)))))
5130 (if old (setcdr old (append new (cdr old)))
5131 (push (cons 'filetags new) alist)))))
5132 ((equal key "LINK")
5133 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5134 (let ((links (assq 'link alist))
5135 (pair (cons (org-match-string-no-properties 1 value)
5136 (org-match-string-no-properties 2 value))))
5137 (if links (push pair (cdr links))
5138 (push (list 'link pair) alist)))))
5139 ((equal key "OPTIONS")
5140 (when (and (org-string-nw-p value)
5141 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5142 (push (cons 'scripts (read (match-string 1 value))) alist)))
5143 ((equal key "PRIORITIES")
5144 (push (cons 'priorities
5145 (let ((prio (org-split-string value)))
5146 (if (< (length prio) 3) '(?A ?C ?B)
5147 (mapcar #'string-to-char prio))))
5148 alist))
5149 ((equal key "PROPERTY")
5150 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5151 (let* ((property (assq 'property alist))
5152 (value (org--update-property-plist
5153 (org-match-string-no-properties 1 value)
5154 (org-match-string-no-properties 2 value)
5155 (cdr property))))
5156 (if property (setcdr property value)
5157 (push (cons 'property value) alist)))))
5158 ((equal key "STARTUP")
5159 (let ((startup (assq 'startup alist)))
5160 (if startup
5161 (setcdr startup
5162 (append (cdr startup) (org-split-string value)))
5163 (push (cons 'startup (org-split-string value)) alist))))
5164 ((equal key "TAGS")
5165 (let ((tag-cell (assq 'tags alist)))
5166 (if tag-cell
5167 (setcdr tag-cell
5168 (append (cdr tag-cell)
5169 '("\\n")
5170 (org-split-string value)))
5171 (push (cons 'tags (org-split-string value)) alist))))
5172 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5173 (let ((todo (assq 'todo alist))
5174 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5175 (org-split-string value))))
5176 (if todo (push value (cdr todo))
5177 (push (list 'todo value) alist))))
5178 ((equal key "SETUPFILE")
5179 (unless buffer-read-only ; Do not check in Gnus messages.
5180 (let ((f (and (org-string-nw-p value)
5181 (expand-file-name
5182 (org-remove-double-quotes value)))))
5183 (when (and f (file-readable-p f) (not (member f files)))
5184 (with-temp-buffer
5185 (setq default-directory (file-name-directory f))
5186 (insert-file-contents f)
5187 (setq alist
5188 ;; Fake Org mode to benefit from cache
5189 ;; without recurring needlessly.
5190 (let ((major-mode 'org-mode))
5191 (org--setup-collect-keywords
5192 regexp (cons f files) alist)))))))))))))))
5193 alist)
5195 (defun org--setup-process-tags (tags filetags)
5196 "Precompute variables used for tags.
5197 TAGS is a list of tags and tag group symbols, as strings.
5198 FILETAGS is a list of tags, as strings."
5199 ;; Process the file tags.
5200 (setq-local org-file-tags
5201 (mapcar #'org-add-prop-inherited filetags))
5202 ;; Provide default tags if no local tags are found.
5203 (when (and (not tags) org-tag-alist)
5204 (setq tags
5205 (mapcar (lambda (tag)
5206 (case (car tag)
5207 (:startgroup "{")
5208 (:endgroup "}")
5209 (:startgrouptag "[")
5210 (:endgrouptag "]")
5211 (:grouptags ":")
5212 (:newline "\\n")
5213 (otherwise (concat (car tag)
5214 (and (characterp (cdr tag))
5215 (format "(%c)" (cdr tag)))))))
5216 org-tag-alist)))
5217 ;; Process the tags.
5218 (setq-local org-tag-groups-alist nil)
5219 (setq-local org-tag-alist nil)
5220 (let (group-flag)
5221 (while tags
5222 (let ((e (car tags)))
5223 (setq tags (cdr tags))
5224 (cond
5225 ((equal e "{")
5226 (push '(:startgroup) org-tag-alist)
5227 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5228 ((equal e "}")
5229 (push '(:endgroup) org-tag-alist)
5230 (setq group-flag nil))
5231 ((equal e "[")
5232 (push '(:startgrouptag) org-tag-alist)
5233 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5234 ((equal e "]")
5235 (push '(:endgrouptag) org-tag-alist)
5236 (setq group-flag nil))
5237 ((equal e ":")
5238 (push '(:grouptags) org-tag-alist)
5239 (setq group-flag 'append))
5240 ((equal e "\\n") (push '(:newline) org-tag-alist))
5241 ((string-match
5242 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5243 "\\|{.+?}\\)" ; regular expression
5244 "\\(?:(\\(.\\))\\)?\\'")) e)
5245 (let ((tag (match-string 1 e))
5246 (key (and (match-beginning 2)
5247 (string-to-char (match-string 2 e)))))
5248 (cond ((eq group-flag 'append)
5249 (setcar org-tag-groups-alist
5250 (append (car org-tag-groups-alist) (list tag))))
5251 (group-flag (push (list tag) org-tag-groups-alist)))
5252 ;; Push all tags in groups, no matter if they already exist.
5253 (unless (and (not group-flag) (assoc tag org-tag-alist))
5254 (push (cons tag key) org-tag-alist))))))))
5255 (setq org-tag-alist (nreverse org-tag-alist)))
5257 (defun org-file-contents (file &optional noerror)
5258 "Return the contents of FILE, as a string."
5259 (if (and file (file-readable-p file))
5260 (with-temp-buffer
5261 (insert-file-contents file)
5262 (buffer-string))
5263 (funcall (if noerror 'message 'error)
5264 "Cannot read file \"%s\"%s"
5265 file
5266 (let ((from (buffer-file-name (buffer-base-buffer))))
5267 (if from (concat " (referenced in file \"" from "\")") "")))))
5269 (defun org-extract-log-state-settings (x)
5270 "Extract the log state setting from a TODO keyword string.
5271 This will extract info from a string like \"WAIT(w@/!)\"."
5272 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5273 (let ((kw (match-string 1 x))
5274 (log1 (and (match-end 3) (match-string 3 x)))
5275 (log2 (and (match-end 4) (match-string 4 x))))
5276 (and (or log1 log2)
5277 (list kw
5278 (and log1 (if (equal log1 "!") 'time 'note))
5279 (and log2 (if (equal log2 "!") 'time 'note)))))))
5281 (defun org-remove-keyword-keys (list)
5282 "Remove a pair of parenthesis at the end of each string in LIST."
5283 (mapcar (lambda (x)
5284 (if (string-match "(.*)$" x)
5285 (substring x 0 (match-beginning 0))
5287 list))
5289 (defun org-assign-fast-keys (alist)
5290 "Assign fast keys to a keyword-key alist.
5291 Respect keys that are already there."
5292 (let (new e (alt ?0))
5293 (while (setq e (pop alist))
5294 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5295 (cdr e)) ;; Key already assigned.
5296 (push e new)
5297 (let ((clist (string-to-list (downcase (car e))))
5298 (used (append new alist)))
5299 (when (= (car clist) ?@)
5300 (pop clist))
5301 (while (and clist (rassoc (car clist) used))
5302 (pop clist))
5303 (unless clist
5304 (while (rassoc alt used)
5305 (incf alt)))
5306 (push (cons (car e) (or (car clist) alt)) new))))
5307 (nreverse new)))
5309 ;;; Some variables used in various places
5311 (defvar org-window-configuration nil
5312 "Used in various places to store a window configuration.")
5313 (defvar org-selected-window nil
5314 "Used in various places to store a window configuration.")
5315 (defvar org-finish-function nil
5316 "Function to be called when `C-c C-c' is used.
5317 This is for getting out of special buffers like capture.")
5318 (defvar org-last-state)
5320 ;; Defined somewhere in this file, but used before definition.
5321 (defvar org-entities) ;; defined in org-entities.el
5322 (defvar org-struct-menu)
5323 (defvar org-org-menu)
5324 (defvar org-tbl-menu)
5326 ;;;; Define the Org-mode
5328 ;; We use a before-change function to check if a table might need
5329 ;; an update.
5330 (defvar org-table-may-need-update t
5331 "Indicates that a table might need an update.
5332 This variable is set by `org-before-change-function'.
5333 `org-table-align' sets it back to nil.")
5334 (defun org-before-change-function (_beg _end)
5335 "Every change indicates that a table might need an update."
5336 (setq org-table-may-need-update t))
5337 (defvar org-mode-map)
5338 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5339 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5340 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5341 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5342 (defvar org-table-buffer-is-an nil)
5344 (defvar bidi-paragraph-direction)
5345 (defvar buffer-face-mode-face)
5347 (require 'outline)
5348 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5349 (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"))
5350 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5352 ;; Other stuff we need.
5353 (require 'time-date)
5354 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5355 (require 'easymenu)
5356 (autoload 'easy-menu-add "easymenu")
5357 (require 'overlay)
5359 ;; (require 'org-macs) moved higher up in the file before it is first used
5360 (require 'org-entities)
5361 ;; (require 'org-compat) moved higher up in the file before it is first used
5362 (require 'org-faces)
5363 (require 'org-list)
5364 (require 'org-pcomplete)
5365 (require 'org-src)
5366 (require 'org-footnote)
5367 (require 'org-macro)
5369 ;; babel
5370 (require 'ob)
5372 ;;;###autoload
5373 (define-derived-mode org-mode outline-mode "Org"
5374 "Outline-based notes management and organizer, alias
5375 \"Carsten's outline-mode for keeping track of everything.\"
5377 Org-mode develops organizational tasks around a NOTES file which
5378 contains information about projects as plain text. Org-mode is
5379 implemented on top of outline-mode, which is ideal to keep the content
5380 of large files well structured. It supports ToDo items, deadlines and
5381 time stamps, which magically appear in the diary listing of the Emacs
5382 calendar. Tables are easily created with a built-in table editor.
5383 Plain text URL-like links connect to websites, emails (VM), Usenet
5384 messages (Gnus), BBDB entries, and any files related to the project.
5385 For printing and sharing of notes, an Org-mode file (or a part of it)
5386 can be exported as a structured ASCII or HTML file.
5388 The following commands are available:
5390 \\{org-mode-map}"
5392 ;; Get rid of Outline menus, they are not needed
5393 ;; Need to do this here because define-derived-mode sets up
5394 ;; the keymap so late. Still, it is a waste to call this each time
5395 ;; we switch another buffer into org-mode.
5396 (if (featurep 'xemacs)
5397 (when (boundp 'outline-mode-menu-heading)
5398 ;; Assume this is Greg's port, it uses easymenu
5399 (easy-menu-remove outline-mode-menu-heading)
5400 (easy-menu-remove outline-mode-menu-show)
5401 (easy-menu-remove outline-mode-menu-hide))
5402 (define-key org-mode-map [menu-bar headings] 'undefined)
5403 (define-key org-mode-map [menu-bar hide] 'undefined)
5404 (define-key org-mode-map [menu-bar show] 'undefined))
5406 (org-load-modules-maybe)
5407 (when (featurep 'xemacs)
5408 (easy-menu-add org-org-menu)
5409 (easy-menu-add org-tbl-menu))
5410 (org-install-agenda-files-menu)
5411 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5412 (add-to-invisibility-spec '(org-cwidth))
5413 (add-to-invisibility-spec '(org-hide-block . t))
5414 (when (featurep 'xemacs)
5415 (setq-local line-move-ignore-invisible t))
5416 (setq-local outline-regexp org-outline-regexp)
5417 (setq-local outline-level 'org-outline-level)
5418 (setq bidi-paragraph-direction 'left-to-right)
5419 (when (and org-ellipsis
5420 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5421 (fboundp 'make-glyph-code))
5422 (unless org-display-table
5423 (setq org-display-table (make-display-table)))
5424 (set-display-table-slot
5425 org-display-table 4
5426 (vconcat (mapcar
5427 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5428 org-ellipsis)))
5429 (if (stringp org-ellipsis) org-ellipsis "..."))))
5430 (setq buffer-display-table org-display-table))
5431 (org-set-regexps-and-options)
5432 (org-set-font-lock-defaults)
5433 (when (and org-tag-faces (not org-tags-special-faces-re))
5434 ;; tag faces set outside customize.... force initialization.
5435 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5436 ;; Calc embedded
5437 (setq-local calc-embedded-open-mode "# ")
5438 ;; Modify a few syntax entries
5439 (modify-syntax-entry ?@ "w")
5440 (modify-syntax-entry ?\" "\"")
5441 (modify-syntax-entry ?\\ "_")
5442 (modify-syntax-entry ?~ "_")
5443 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5444 ;; Activate before-change-function
5445 (setq-local org-table-may-need-update t)
5446 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5447 ;; Check for running clock before killing a buffer
5448 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5449 ;; Initialize macros templates.
5450 (org-macro-initialize-templates)
5451 ;; Initialize radio targets.
5452 (org-update-radio-target-regexp)
5453 ;; Indentation.
5454 (setq-local indent-line-function 'org-indent-line)
5455 (setq-local indent-region-function 'org-indent-region)
5456 ;; Filling and auto-filling.
5457 (org-setup-filling)
5458 ;; Comments.
5459 (org-setup-comments-handling)
5460 ;; Initialize cache.
5461 (org-element-cache-reset)
5462 ;; Beginning/end of defun
5463 (setq-local beginning-of-defun-function 'org-backward-element)
5464 (setq-local end-of-defun-function
5465 (lambda ()
5466 (if (not (org-at-heading-p))
5467 (org-forward-element)
5468 (org-forward-element)
5469 (forward-char -1))))
5470 ;; Next error for sparse trees
5471 (setq-local next-error-function 'org-occur-next-match)
5472 ;; Make sure dependence stuff works reliably, even for users who set it
5473 ;; too late :-(
5474 (if org-enforce-todo-dependencies
5475 (add-hook 'org-blocker-hook
5476 'org-block-todo-from-children-or-siblings-or-parent)
5477 (remove-hook 'org-blocker-hook
5478 'org-block-todo-from-children-or-siblings-or-parent))
5479 (if org-enforce-todo-checkbox-dependencies
5480 (add-hook 'org-blocker-hook
5481 'org-block-todo-from-checkboxes)
5482 (remove-hook 'org-blocker-hook
5483 'org-block-todo-from-checkboxes))
5485 ;; Align options lines
5486 (setq-local
5487 align-mode-rules-list
5488 '((org-in-buffer-settings
5489 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5490 (modes . '(org-mode)))))
5492 ;; Imenu
5493 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5495 ;; Make isearch reveal context
5496 (if (or (featurep 'xemacs)
5497 (not (boundp 'outline-isearch-open-invisible-function)))
5498 ;; Emacs 21 and XEmacs make use of the hook
5499 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5500 ;; Emacs 22 deals with this through a special variable
5501 (setq-local outline-isearch-open-invisible-function
5502 (lambda (&rest _) (org-show-context 'isearch))))
5504 ;; Setup the pcomplete hooks
5505 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5506 (setq-local pcomplete-command-name-function 'org-command-at-point)
5507 (setq-local pcomplete-default-completion-function 'ignore)
5508 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5509 (setq-local pcomplete-termination-string "")
5510 (setq-local buffer-face-mode-face 'org-default)
5512 ;; If empty file that did not turn on Org mode automatically, make
5513 ;; it to.
5514 (when (and org-insert-mode-line-in-empty-file
5515 (org-called-interactively-p 'any)
5516 (= (point-min) (point-max)))
5517 (insert "# -*- mode: org -*-\n\n"))
5518 (unless org-inhibit-startup
5519 (org-unmodified
5520 (when org-startup-with-beamer-mode (org-beamer-mode))
5521 (when org-startup-align-all-tables
5522 (org-table-map-tables #'org-table-align t))
5523 (when org-startup-with-inline-images (org-display-inline-images))
5524 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5525 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5526 (when org-startup-truncated (setq truncate-lines t))
5527 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5528 (org-refresh-effort-properties)))
5529 ;; Try to set `org-hide' face correctly.
5530 (let ((foreground (org-find-invisible-foreground)))
5531 (when foreground
5532 (set-face-foreground 'org-hide foreground))))
5534 ;; Update `customize-package-emacs-version-alist'
5535 (add-to-list 'customize-package-emacs-version-alist
5536 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5537 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5538 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5540 (defvar org-mode-transpose-word-syntax-table
5541 (let ((st (make-syntax-table text-mode-syntax-table)))
5542 (dolist (c org-emphasis-alist st)
5543 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5545 (when (fboundp 'abbrev-table-put)
5546 (abbrev-table-put org-mode-abbrev-table
5547 :parents (list text-mode-abbrev-table)))
5549 (defun org-find-invisible-foreground ()
5550 (let ((candidates (remove
5551 "unspecified-bg"
5552 (nconc
5553 (list (face-background 'default)
5554 (face-background 'org-default))
5555 (mapcar
5556 (lambda (alist)
5557 (when (boundp alist)
5558 (cdr (assoc 'background-color (symbol-value alist)))))
5559 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5560 (list (face-foreground 'org-hide))))))
5561 (car (remove nil candidates))))
5563 (defun org-current-time (&optional rounding-minutes past)
5564 "Current time, possibly rounded to ROUNDING-MINUTES.
5565 When ROUNDING-MINUTES is not an integer, fall back on the car of
5566 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5567 the rounding returns a past time."
5568 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5569 (car org-time-stamp-rounding-minutes)))
5570 (time (decode-time)) res)
5571 (if (< r 1)
5572 (current-time)
5573 (setq res
5574 (apply 'encode-time
5575 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5576 (nthcdr 2 time))))
5577 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5578 (seconds-to-time (- (org-float-time res) (* r 60)))
5579 res))))
5581 (defun org-today ()
5582 "Return today date, considering `org-extend-today-until'."
5583 (time-to-days
5584 (time-subtract (current-time)
5585 (list 0 (* 3600 org-extend-today-until) 0))))
5587 ;;;; Font-Lock stuff, including the activators
5589 (defvar org-mouse-map (make-sparse-keymap))
5590 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5591 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5592 (when org-mouse-1-follows-link
5593 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5594 (when org-tab-follows-link
5595 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5596 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5598 (require 'font-lock)
5600 (defconst org-non-link-chars "]\t\n\r<>")
5601 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5602 "file+sys" "news" "shell" "elisp" "doi" "message"
5603 "help"))
5604 (defvar org-link-types-re nil
5605 "Matches a link that has a url-like prefix like \"http:\"")
5606 (defvar org-link-re-with-space nil
5607 "Matches a link with spaces, optional angular brackets around it.")
5608 (defvar org-link-re-with-space2 nil
5609 "Matches a link with spaces, optional angular brackets around it.")
5610 (defvar org-link-re-with-space3 nil
5611 "Matches a link with spaces, only for internal part in bracket links.")
5612 (defvar org-angle-link-re nil
5613 "Matches link with angular brackets, spaces are allowed.")
5614 (defvar org-plain-link-re nil
5615 "Matches plain link, without spaces.")
5616 (defvar org-bracket-link-regexp nil
5617 "Matches a link in double brackets.")
5618 (defvar org-bracket-link-analytic-regexp nil
5619 "Regular expression used to analyze links.
5620 Here is what the match groups contain after a match:
5621 1: http:
5622 2: http
5623 3: path
5624 4: [desc]
5625 5: desc")
5626 (defvar org-bracket-link-analytic-regexp++ nil
5627 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5628 (defvar org-any-link-re nil
5629 "Regular expression matching any link.")
5631 (defconst org-match-sexp-depth 3
5632 "Number of stacked braces for sub/superscript matching.")
5634 (defun org-create-multibrace-regexp (left right n)
5635 "Create a regular expression which will match a balanced sexp.
5636 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5637 as single character strings.
5638 The regexp returned will match the entire expression including the
5639 delimiters. It will also define a single group which contains the
5640 match except for the outermost delimiters. The maximum depth of
5641 stacked delimiters is N. Escaping delimiters is not possible."
5642 (let* ((nothing (concat "[^" left right "]*?"))
5643 (or "\\|")
5644 (re nothing)
5645 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5646 (while (> n 1)
5647 (setq n (1- n)
5648 re (concat re or next)
5649 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5650 (concat left "\\(" re "\\)" right)))
5652 (defconst org-match-substring-regexp
5653 (concat
5654 "\\(\\S-\\)\\([_^]\\)\\("
5655 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5656 "\\|"
5657 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5658 "\\|"
5659 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5660 "The regular expression matching a sub- or superscript.")
5662 (defconst org-match-substring-with-braces-regexp
5663 (concat
5664 "\\(\\S-\\)\\([_^]\\)"
5665 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5666 "The regular expression matching a sub- or superscript, forcing braces.")
5668 (defun org-make-link-regexps ()
5669 "Update the link regular expressions.
5670 This should be called after the variable `org-link-types' has changed."
5671 (let ((types-re (regexp-opt org-link-types t)))
5672 (setq org-link-types-re
5673 (concat "\\`" types-re ":")
5674 org-link-re-with-space
5675 (concat "<?" types-re ":"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^" org-non-link-chars "]*"
5678 "[^" org-non-link-chars " ]\\)>?")
5679 org-link-re-with-space2
5680 (concat "<?" types-re ":"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^\t\n\r]*"
5683 "[^" org-non-link-chars " ]\\)>?")
5684 org-link-re-with-space3
5685 (concat "<?" types-re ":"
5686 "\\([^" org-non-link-chars " ]"
5687 "[^\t\n\r]*\\)")
5688 org-angle-link-re
5689 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5690 types-re)
5691 org-plain-link-re
5692 (concat
5693 "\\<" types-re ":"
5694 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5695 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5696 org-bracket-link-regexp
5697 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5698 org-bracket-link-analytic-regexp
5699 (concat
5700 "\\[\\["
5701 "\\(" types-re ":\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-bracket-link-analytic-regexp++
5707 (concat
5708 "\\[\\["
5709 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5710 "\\([^]]+\\)"
5711 "\\]"
5712 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5713 "\\]")
5714 org-any-link-re
5715 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5716 org-angle-link-re "\\)\\|\\("
5717 org-plain-link-re "\\)"))))
5719 (org-make-link-regexps)
5721 (defvar org-emph-face nil)
5723 (defun org-do-emphasis-faces (limit)
5724 "Run through the buffer and emphasize strings."
5725 (let (rtn a)
5726 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5727 (let* ((border (char-after (match-beginning 3)))
5728 (bre (regexp-quote (char-to-string border))))
5729 (when (and (not (= border (char-after (match-beginning 4))))
5730 (not (string-match-p (concat bre ".*" bre)
5731 (replace-regexp-in-string
5732 "\n" " "
5733 (substring (match-string 2) 1 -1)))))
5734 (setq rtn t)
5735 (setq a (assoc (match-string 3) org-emphasis-alist))
5736 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5737 'face
5738 (nth 1 a))
5739 (and (nth 2 a)
5740 (org-remove-flyspell-overlays-in
5741 (match-beginning 0) (match-end 0)))
5742 (add-text-properties (match-beginning 2) (match-end 2)
5743 '(font-lock-multiline t org-emphasis t))
5744 (when org-hide-emphasis-markers
5745 (add-text-properties (match-end 4) (match-beginning 5)
5746 '(invisible org-link))
5747 (add-text-properties (match-beginning 3) (match-end 3)
5748 '(invisible org-link)))))
5749 (goto-char (1+ (match-beginning 0))))
5750 rtn))
5752 (defun org-emphasize (&optional char)
5753 "Insert or change an emphasis, i.e. a font like bold or italic.
5754 If there is an active region, change that region to a new emphasis.
5755 If there is no region, just insert the marker characters and position
5756 the cursor between them.
5757 CHAR should be the marker character. If it is a space, it means to
5758 remove the emphasis of the selected region.
5759 If CHAR is not given (for example in an interactive call) it will be
5760 prompted for."
5761 (interactive)
5762 (let ((erc org-emphasis-regexp-components)
5763 (string "") beg end move s)
5764 (if (org-region-active-p)
5765 (setq beg (region-beginning)
5766 end (region-end)
5767 string (buffer-substring beg end))
5768 (setq move t))
5770 (unless char
5771 (message "Emphasis marker or tag: [%s]"
5772 (mapconcat #'car org-emphasis-alist ""))
5773 (setq char (read-char-exclusive)))
5774 (if (equal char ?\s)
5775 (setq s ""
5776 move nil)
5777 (unless (assoc (char-to-string char) org-emphasis-alist)
5778 (user-error "No such emphasis marker: \"%c\"" char))
5779 (setq s (char-to-string char)))
5780 (while (and (> (length string) 1)
5781 (equal (substring string 0 1) (substring string -1))
5782 (assoc (substring string 0 1) org-emphasis-alist))
5783 (setq string (substring string 1 -1)))
5784 (setq string (concat s string s))
5785 (when beg (delete-region beg end))
5786 (unless (or (bolp)
5787 (string-match (concat "[" (nth 0 erc) "\n]")
5788 (char-to-string (char-before (point)))))
5789 (insert " "))
5790 (unless (or (eobp)
5791 (string-match (concat "[" (nth 1 erc) "\n]")
5792 (char-to-string (char-after (point)))))
5793 (insert " ") (backward-char 1))
5794 (insert string)
5795 (and move (backward-char 1))))
5797 (defconst org-nonsticky-props
5798 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5800 (defsubst org-rear-nonsticky-at (pos)
5801 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5803 (defun org-activate-plain-links (limit)
5804 "Add link properties for plain links."
5805 (let (f hl)
5806 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5807 (not (member 'org-tag
5808 (get-text-property (1- (match-beginning 0)) 'face)))
5809 (not (org-in-src-block-p)))
5810 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5811 (setq f (get-text-property (match-beginning 0) 'face))
5812 (setq hl (org-match-string-no-properties 0))
5813 (unless (or (eq f 'org-tag)
5814 (and (listp f) (memq 'org-tag f)))
5815 (add-text-properties (match-beginning 0) (match-end 0)
5816 (list 'mouse-face 'highlight
5817 'face 'org-link
5818 'htmlize-link `(:uri ,hl)
5819 'keymap org-mouse-map))
5820 (org-rear-nonsticky-at (match-end 0)))
5821 t)))
5823 (defun org-activate-code (limit)
5824 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5825 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5826 (remove-text-properties (match-beginning 0) (match-end 0)
5827 '(display t invisible t intangible t))
5830 (defcustom org-src-fontify-natively t
5831 "When non-nil, fontify code in code blocks."
5832 :type 'boolean
5833 :version "24.4"
5834 :package-version '(Org . "8.3")
5835 :group 'org-appearance
5836 :group 'org-babel)
5838 (defcustom org-allow-promoting-top-level-subtree nil
5839 "When non-nil, allow promoting a top level subtree.
5840 The leading star of the top level headline will be replaced
5841 by a #."
5842 :type 'boolean
5843 :version "24.1"
5844 :group 'org-appearance)
5846 (defun org-fontify-meta-lines-and-blocks (limit)
5847 (condition-case nil
5848 (org-fontify-meta-lines-and-blocks-1 limit)
5849 (error (message "org-mode fontification error"))))
5851 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5852 "Fontify #+ lines and blocks."
5853 (let ((case-fold-search t))
5854 (when (re-search-forward
5855 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5856 limit t)
5857 (let ((beg (match-beginning 0))
5858 (block-start (match-end 0))
5859 (block-end nil)
5860 (lang (match-string 7))
5861 (beg1 (line-beginning-position 2))
5862 (dc1 (downcase (match-string 2)))
5863 (dc3 (downcase (match-string 3)))
5864 end end1 quoting block-type)
5865 (cond
5866 ((and (match-end 4) (equal dc3 "+begin"))
5867 ;; Truly a block
5868 (setq block-type (downcase (match-string 5))
5869 quoting (member block-type org-protecting-blocks))
5870 (when (re-search-forward
5871 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5872 nil t) ;; on purpose, we look further than LIMIT
5873 (setq end (min (point-max) (match-end 0))
5874 end1 (min (point-max) (1- (match-beginning 0))))
5875 (setq block-end (match-beginning 0))
5876 (when quoting
5877 (org-remove-flyspell-overlays-in beg1 end1)
5878 (remove-text-properties beg end
5879 '(display t invisible t intangible t)))
5880 (add-text-properties
5881 beg end '(font-lock-fontified t font-lock-multiline t))
5882 (add-text-properties beg beg1 '(face org-meta-line))
5883 (org-remove-flyspell-overlays-in beg beg1)
5884 (add-text-properties ; For end_src
5885 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5886 (org-remove-flyspell-overlays-in end1 end)
5887 (cond
5888 ((and lang (not (string= lang "")) org-src-fontify-natively)
5889 (org-src-font-lock-fontify-block lang block-start block-end)
5890 (add-text-properties beg1 block-end '(src-block t)))
5891 (quoting
5892 (add-text-properties beg1 (min (point-max) (1+ end1))
5893 '(face org-block))) ; end of source block
5894 ((not org-fontify-quote-and-verse-blocks))
5895 ((string= block-type "quote")
5896 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5897 ((string= block-type "verse")
5898 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5899 (add-text-properties beg beg1 '(face org-block-begin-line))
5900 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5901 '(face org-block-end-line))
5903 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5904 (org-remove-flyspell-overlays-in
5905 (match-beginning 0)
5906 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5907 (add-text-properties
5908 beg (match-end 3)
5909 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5910 '(font-lock-fontified t invisible t)
5911 '(font-lock-fontified t face org-document-info-keyword)))
5912 (add-text-properties
5913 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5914 (if (string-equal dc1 "+title:")
5915 '(font-lock-fontified t face org-document-title)
5916 '(font-lock-fontified t face org-document-info))))
5917 ((equal dc1 "+caption:")
5918 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5919 (remove-text-properties (match-beginning 0) (match-end 0)
5920 '(display t invisible t intangible t))
5921 (add-text-properties (match-beginning 1) (match-end 3)
5922 '(font-lock-fontified t face org-meta-line))
5923 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5924 '(font-lock-fontified t face org-block))
5926 ((member dc3 '(" " ""))
5927 (org-remove-flyspell-overlays-in beg (match-end 0))
5928 (add-text-properties
5929 beg (match-end 0)
5930 '(font-lock-fontified t face font-lock-comment-face)))
5931 (t ;; just any other in-buffer setting, but not indented
5932 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5933 (remove-text-properties (match-beginning 0) (match-end 0)
5934 '(display t invisible t intangible t))
5935 (add-text-properties beg (match-end 0)
5936 '(font-lock-fontified t face org-meta-line))
5937 t))))))
5939 (defun org-fontify-drawers (limit)
5940 "Fontify drawers."
5941 (when (re-search-forward org-drawer-regexp limit t)
5942 (add-text-properties
5943 (match-beginning 0) (match-end 0)
5944 '(font-lock-fontified t face org-special-keyword))
5945 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5948 (defun org-fontify-macros (limit)
5949 "Fontify macros."
5950 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5951 (add-text-properties
5952 (match-beginning 0) (match-end 0)
5953 '(font-lock-fontified t face org-macro))
5954 (when org-hide-macro-markers
5955 (add-text-properties (match-end 2) (match-beginning 2)
5956 '(invisible t))
5957 (add-text-properties (match-beginning 1) (match-end 1)
5958 '(invisible t)))
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (defun org-activate-angle-links (limit)
5963 "Add text properties for angle links."
5964 (when (and (re-search-forward org-angle-link-re limit t)
5965 (not (org-in-src-block-p)))
5966 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5967 (add-text-properties (match-beginning 0) (match-end 0)
5968 (list 'mouse-face 'highlight
5969 'keymap org-mouse-map
5970 'font-lock-multiline t))
5971 (org-rear-nonsticky-at (match-end 0))
5974 (defun org-activate-footnote-links (limit)
5975 "Add text properties for footnotes."
5976 (let ((fn (org-footnote-next-reference-or-definition limit)))
5977 (when fn
5978 (let* ((beg (nth 1 fn))
5979 (end (nth 2 fn))
5980 (label (car fn))
5981 (referencep (/= (line-beginning-position) beg)))
5982 (when (and referencep (nth 3 fn))
5983 (save-excursion
5984 (goto-char beg)
5985 (search-forward (or label "fn:"))
5986 (org-remove-flyspell-overlays-in beg (match-end 0))))
5987 (add-text-properties beg end
5988 (list 'mouse-face 'highlight
5989 'keymap org-mouse-map
5990 'help-echo
5991 (if referencep "Footnote reference"
5992 "Footnote definition")
5993 'font-lock-fontified t
5994 'font-lock-multiline t
5995 'face 'org-footnote))))))
5997 (defun org-activate-bracket-links (limit)
5998 "Add text properties for bracketed links."
5999 (when (and (re-search-forward org-bracket-link-regexp limit t)
6000 (not (org-in-src-block-p)))
6001 (let* ((hl (org-match-string-no-properties 1))
6002 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6003 (ip (org-maybe-intangible
6004 (list 'invisible 'org-link
6005 'keymap org-mouse-map 'mouse-face 'highlight
6006 'font-lock-multiline t 'help-echo help
6007 'htmlize-link `(:uri ,hl))))
6008 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6009 'font-lock-multiline t 'help-echo help
6010 'htmlize-link `(:uri ,hl))))
6011 ;; We need to remove the invisible property here. Table narrowing
6012 ;; may have made some of this invisible.
6013 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6014 (remove-text-properties (match-beginning 0) (match-end 0)
6015 '(invisible nil))
6016 (if (match-end 3)
6017 (progn
6018 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6019 (org-rear-nonsticky-at (match-beginning 3))
6020 (add-text-properties (match-beginning 3) (match-end 3) vp)
6021 (org-rear-nonsticky-at (match-end 3))
6022 (add-text-properties (match-end 3) (match-end 0) ip)
6023 (org-rear-nonsticky-at (match-end 0)))
6024 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6025 (org-rear-nonsticky-at (match-beginning 1))
6026 (add-text-properties (match-beginning 1) (match-end 1) vp)
6027 (org-rear-nonsticky-at (match-end 1))
6028 (add-text-properties (match-end 1) (match-end 0) ip)
6029 (org-rear-nonsticky-at (match-end 0)))
6030 t)))
6032 (defun org-activate-dates (limit)
6033 "Add text properties for dates."
6034 (when (and (re-search-forward org-tsr-regexp-both limit t)
6035 (not (equal (char-before (match-beginning 0)) 91)))
6036 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6037 (add-text-properties (match-beginning 0) (match-end 0)
6038 (list 'mouse-face 'highlight
6039 'keymap org-mouse-map))
6040 (org-rear-nonsticky-at (match-end 0))
6041 (when org-display-custom-times
6042 (if (match-end 3)
6043 (org-display-custom-time (match-beginning 3) (match-end 3))
6044 (org-display-custom-time (match-beginning 1) (match-end 1))))
6047 (defvar-local org-target-link-regexp nil
6048 "Regular expression matching radio targets in plain text.")
6050 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6051 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6052 border border border))
6053 "Regular expression matching a link target.")
6055 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6056 "Regular expression matching a radio target.")
6058 (defconst org-any-target-regexp
6059 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6060 "Regular expression matching any target.")
6062 (defun org-activate-target-links (limit)
6063 "Add text properties for target matches."
6064 (when org-target-link-regexp
6065 (let ((case-fold-search t))
6066 (when (re-search-forward org-target-link-regexp limit t)
6067 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6068 (add-text-properties (match-beginning 1) (match-end 1)
6069 (list 'mouse-face 'highlight
6070 'keymap org-mouse-map
6071 'help-echo "Radio target link"
6072 'org-linked-text t))
6073 (org-rear-nonsticky-at (match-end 1))
6074 t))))
6076 (defun org-update-radio-target-regexp ()
6077 "Find all radio targets in this file and update the regular expression.
6078 Also refresh fontification if needed."
6079 (interactive)
6080 (let ((old-regexp org-target-link-regexp)
6081 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6082 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6083 (targets
6084 (org-with-wide-buffer
6085 (goto-char (point-min))
6086 (let (rtn)
6087 (while (re-search-forward org-radio-target-regexp nil t)
6088 ;; Make sure point is really within the object.
6089 (backward-char)
6090 (let ((obj (org-element-context)))
6091 (when (eq (org-element-type obj) 'radio-target)
6092 (cl-pushnew (org-element-property :value obj) rtn
6093 :test #'equal))))
6094 rtn))))
6095 (setq org-target-link-regexp
6096 (and targets
6097 (concat before-re
6098 (mapconcat
6099 (lambda (x)
6100 (replace-regexp-in-string
6101 " +" "\\s-+" (regexp-quote x) t t))
6102 targets
6103 "\\|")
6104 after-re)))
6105 (unless (equal old-regexp org-target-link-regexp)
6106 ;; Clean-up cache.
6107 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6108 ((not org-target-link-regexp) old-regexp)
6110 (concat before-re
6111 (mapconcat
6112 (lambda (re)
6113 (substring re (length before-re)
6114 (- (length after-re))))
6115 (list old-regexp org-target-link-regexp)
6116 "\\|")
6117 after-re)))))
6118 (org-with-wide-buffer
6119 (goto-char (point-min))
6120 (while (re-search-forward regexp nil t)
6121 (org-element-cache-refresh (match-beginning 1)))))
6122 ;; Re fontify buffer.
6123 (when (memq 'radio org-highlight-links)
6124 (org-restart-font-lock)))))
6126 (defun org-hide-wide-columns (limit)
6127 (let (s e)
6128 (setq s (text-property-any (point) (or limit (point-max))
6129 'org-cwidth t))
6130 (when s
6131 (setq e (next-single-property-change s 'org-cwidth))
6132 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6133 (goto-char e)
6134 t)))
6136 (defvar org-latex-and-related-regexp nil
6137 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6139 (defun org-compute-latex-and-related-regexp ()
6140 "Compute regular expression for LaTeX, entities and sub/superscript.
6141 Result depends on variable `org-highlight-latex-and-related'."
6142 (setq-local
6143 org-latex-and-related-regexp
6144 (let* ((re-sub
6145 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6146 ((eq org-use-sub-superscripts '{})
6147 (list org-match-substring-with-braces-regexp))
6148 (org-use-sub-superscripts (list org-match-substring-regexp))))
6149 (re-latex
6150 (when (memq 'latex org-highlight-latex-and-related)
6151 (let ((matchers (plist-get org-format-latex-options :matchers)))
6152 (delq nil
6153 (mapcar (lambda (x)
6154 (and (member (car x) matchers) (nth 1 x)))
6155 org-latex-regexps)))))
6156 (re-entities
6157 (when (memq 'entities org-highlight-latex-and-related)
6158 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6159 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6161 (defun org-do-latex-and-related (limit)
6162 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6163 LIMIT bounds the search for syntax to highlight. Stop at first
6164 highlighted object, if any. Return t if some highlighting was
6165 done, nil otherwise."
6166 (when (org-string-nw-p org-latex-and-related-regexp)
6167 (catch 'found
6168 (while (re-search-forward org-latex-and-related-regexp limit t)
6169 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6170 'face))
6171 '(org-code org-verbatim underline))
6172 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6173 '(?_ ?^))
6175 0)))
6176 (font-lock-prepend-text-property
6177 (+ offset (match-beginning 0)) (match-end 0)
6178 'face 'org-latex-and-related)
6179 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6180 '(font-lock-multiline t)))
6181 (throw 'found t)))
6182 nil)))
6184 (defun org-restart-font-lock ()
6185 "Restart `font-lock-mode', to force refontification."
6186 (when (and (boundp 'font-lock-mode) font-lock-mode)
6187 (font-lock-mode -1)
6188 (font-lock-mode 1)))
6190 (defun org-activate-tags (limit)
6191 (when (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6192 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6193 (add-text-properties (match-beginning 1) (match-end 1)
6194 (list 'mouse-face 'highlight
6195 'keymap org-mouse-map))
6196 (org-rear-nonsticky-at (match-end 1))
6199 (defun org-outline-level ()
6200 "Compute the outline level of the heading at point.
6202 If this is called at a normal headline, the level is the number
6203 of stars. Use `org-reduced-level' to remove the effect of
6204 `org-odd-levels'. Unlike to `org-current-level', this function
6205 takes into consideration inlinetasks."
6206 (org-with-wide-buffer
6207 (end-of-line)
6208 (if (re-search-backward org-outline-regexp-bol nil t)
6209 (1- (- (match-end 0) (match-beginning 0)))
6210 0)))
6212 (defvar org-font-lock-keywords nil)
6214 (defsubst org-re-property (property &optional literal allow-null value)
6215 "Return a regexp matching a PROPERTY line.
6217 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6218 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6219 non-nil, match properties even without a value.
6221 Match group 3 is set to the value when it exists. If there is no
6222 value and ALLOW-NULL is non-nil, it is set to the empty string.
6224 With optional argument VALUE, match only property lines with
6225 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6226 unless LITERAL is non-nil."
6227 (concat
6228 "^\\(?4:[ \t]*\\)"
6229 (format "\\(?1::\\(?2:%s\\):\\)"
6230 (if literal property (regexp-quote property)))
6231 (cond (value
6232 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6233 (if literal value (regexp-quote value))))
6234 (allow-null
6235 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6237 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6239 (defconst org-property-re
6240 (org-re-property "\\S-+" 'literal t)
6241 "Regular expression matching a property line.
6242 There are four matching groups:
6243 1: :PROPKEY: including the leading and trailing colon,
6244 2: PROPKEY without the leading and trailing colon,
6245 3: PROPVAL without leading or trailing spaces,
6246 4: the indentation of the current line,
6247 5: trailing whitespace.")
6249 (defvar org-font-lock-hook nil
6250 "Functions to be called for special font lock stuff.")
6252 (defvar org-font-lock-set-keywords-hook nil
6253 "Functions that can manipulate `org-font-lock-extra-keywords'.
6254 This is called after `org-font-lock-extra-keywords' is defined, but before
6255 it is installed to be used by font lock. This can be useful if something
6256 needs to be inserted at a specific position in the font-lock sequence.")
6258 (defun org-font-lock-hook (limit)
6259 "Run `org-font-lock-hook' within LIMIT."
6260 (run-hook-with-args 'org-font-lock-hook limit))
6262 (defun org-set-font-lock-defaults ()
6263 "Set font lock defaults for the current buffer."
6264 (let* ((em org-fontify-emphasized-text)
6265 (lk org-highlight-links)
6266 (org-font-lock-extra-keywords
6267 (list
6268 ;; Call the hook
6269 '(org-font-lock-hook)
6270 ;; Headlines
6271 `(,(if org-fontify-whole-heading-line
6272 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6273 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6274 (1 (org-get-level-face 1))
6275 (2 (org-get-level-face 2))
6276 (3 (org-get-level-face 3)))
6277 ;; Table lines
6278 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6279 (1 'org-table t))
6280 ;; Table internals
6281 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6282 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6283 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6284 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6285 ;; Drawers
6286 '(org-fontify-drawers)
6287 ;; Properties
6288 (list org-property-re
6289 '(1 'org-special-keyword t)
6290 '(3 'org-property-value t))
6291 ;; Links
6292 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6293 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6294 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6295 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6296 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6297 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6298 (when (memq 'footnote lk) '(org-activate-footnote-links))
6299 ;; Targets.
6300 (list org-any-target-regexp '(0 'org-target t))
6301 ;; Diary sexps.
6302 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6303 ;; Macro
6304 '(org-fontify-macros)
6305 '(org-hide-wide-columns (0 nil append))
6306 ;; TODO keyword
6307 (list (format org-heading-keyword-regexp-format
6308 org-todo-regexp)
6309 '(2 (org-get-todo-face 2) t))
6310 ;; DONE
6311 (if org-fontify-done-headline
6312 (list (format org-heading-keyword-regexp-format
6313 (concat
6314 "\\(?:"
6315 (mapconcat 'regexp-quote org-done-keywords "\\|")
6316 "\\)"))
6317 '(2 'org-headline-done t))
6318 nil)
6319 ;; Priorities
6320 '(org-font-lock-add-priority-faces)
6321 ;; Tags
6322 '(org-font-lock-add-tag-faces)
6323 ;; Tags groups
6324 (when (and org-group-tags org-tag-groups-alist)
6325 (list (concat org-outline-regexp-bol ".+\\(:"
6326 (regexp-opt (mapcar 'car org-tag-groups-alist))
6327 ":\\).*$")
6328 '(1 'org-tag-group prepend)))
6329 ;; Special keywords
6330 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6331 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6332 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6333 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6334 ;; Emphasis
6335 (when em
6336 (if (featurep 'xemacs)
6337 '(org-do-emphasis-faces (0 nil append))
6338 '(org-do-emphasis-faces)))
6339 ;; Checkboxes
6340 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6341 1 'org-checkbox prepend)
6342 (when (cdr (assq 'checkbox org-list-automatic-rules))
6343 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6344 (0 (org-get-checkbox-statistics-face) t)))
6345 ;; Description list items
6346 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6347 1 'org-list-dt prepend)
6348 ;; ARCHIVEd headings
6349 (list (concat
6350 org-outline-regexp-bol
6351 "\\(.*:" org-archive-tag ":.*\\)")
6352 '(1 'org-archived prepend))
6353 ;; Specials
6354 '(org-do-latex-and-related)
6355 '(org-fontify-entities)
6356 '(org-raise-scripts)
6357 ;; Code
6358 '(org-activate-code (1 'org-code t))
6359 ;; COMMENT
6360 (list (format
6361 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6362 org-todo-regexp
6363 org-comment-string)
6364 '(9 'org-special-keyword t))
6365 ;; Blocks and meta lines
6366 '(org-fontify-meta-lines-and-blocks))))
6367 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6368 (run-hooks 'org-font-lock-set-keywords-hook)
6369 ;; Now set the full font-lock-keywords
6370 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6371 (setq-local font-lock-defaults
6372 '(org-font-lock-keywords t nil nil backward-paragraph))
6373 (kill-local-variable 'font-lock-keywords) nil))
6375 (defun org-toggle-pretty-entities ()
6376 "Toggle the composition display of entities as UTF8 characters."
6377 (interactive)
6378 (setq-local org-pretty-entities (not org-pretty-entities))
6379 (org-restart-font-lock)
6380 (if org-pretty-entities
6381 (message "Entities are now displayed as UTF8 characters")
6382 (save-restriction
6383 (widen)
6384 (org-decompose-region (point-min) (point-max))
6385 (message "Entities are now displayed as plain text"))))
6387 (defvar-local org-custom-properties-overlays nil
6388 "List of overlays used for custom properties.")
6390 (defun org-toggle-custom-properties-visibility ()
6391 "Display or hide properties in `org-custom-properties'."
6392 (interactive)
6393 (if org-custom-properties-overlays
6394 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6395 (setq org-custom-properties-overlays nil))
6396 (when org-custom-properties
6397 (org-with-wide-buffer
6398 (goto-char (point-min))
6399 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6400 (while (re-search-forward regexp nil t)
6401 (let ((end (cdr (save-match-data (org-get-property-block)))))
6402 (when (and end (< (point) end))
6403 ;; Hide first custom property in current drawer.
6404 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6405 (overlay-put o 'invisible t)
6406 (overlay-put o 'org-custom-property t)
6407 (push o org-custom-properties-overlays))
6408 ;; Hide additional custom properties in the same drawer.
6409 (while (re-search-forward regexp end t)
6410 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6411 (overlay-put o 'invisible t)
6412 (overlay-put o 'org-custom-property t)
6413 (push o org-custom-properties-overlays)))))
6414 ;; Each entry is limited to a single property drawer.
6415 (outline-next-heading)))))))
6417 (defun org-fontify-entities (limit)
6418 "Find an entity to fontify."
6419 (let (ee)
6420 (when org-pretty-entities
6421 (catch 'match
6422 ;; "\_ "-family is left out on purpose. Only the first one,
6423 ;; i.e., "\_ ", could be fontified anyway, and it would be
6424 ;; confusing when adding a second white space character.
6425 (while (re-search-forward
6426 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6427 limit t)
6428 (when (and (not (org-at-comment-p))
6429 (setq ee (org-entity-get (match-string 1)))
6430 (= (length (nth 6 ee)) 1))
6431 (let* ((end (if (equal (match-string 2) "{}")
6432 (match-end 2)
6433 (match-end 1))))
6434 (add-text-properties
6435 (match-beginning 0) end
6436 (list 'font-lock-fontified t))
6437 (compose-region (match-beginning 0) end
6438 (nth 6 ee) nil)
6439 (backward-char 1)
6440 (throw 'match t))))
6441 nil))))
6443 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6444 "Fontify string S like in Org-mode."
6445 (with-temp-buffer
6446 (insert s)
6447 (let ((org-odd-levels-only odd-levels))
6448 (org-mode)
6449 (font-lock-ensure)
6450 (buffer-string))))
6452 (defvar org-m nil)
6453 (defvar org-l nil)
6454 (defvar org-f nil)
6455 (defun org-get-level-face (n)
6456 "Get the right face for match N in font-lock matching of headlines."
6457 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6458 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6459 (if org-cycle-level-faces
6460 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6461 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6462 (cond
6463 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6464 ((eq n 2) org-f)
6465 (t (unless org-level-color-stars-only org-f))))
6467 (defun org-face-from-face-or-color (context inherit face-or-color)
6468 "Create a face list that inherits INHERIT, but sets the foreground color.
6469 When FACE-OR-COLOR is not a string, just return it."
6470 (if (stringp face-or-color)
6471 (list :inherit inherit
6472 (cdr (assoc context org-faces-easy-properties))
6473 face-or-color)
6474 face-or-color))
6476 (defun org-get-todo-face (kwd)
6477 "Get the right face for a TODO keyword KWD.
6478 If KWD is a number, get the corresponding match group."
6479 (when (numberp kwd) (setq kwd (match-string kwd)))
6480 (or (org-face-from-face-or-color
6481 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6482 (and (member kwd org-done-keywords) 'org-done)
6483 'org-todo))
6485 (defun org-get-priority-face (priority)
6486 "Get the right face for PRIORITY.
6487 PRIORITY is a character."
6488 (or (org-face-from-face-or-color
6489 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6490 'org-priority))
6492 (defun org-get-tag-face (tag)
6493 "Get the right face for TAG.
6494 If TAG is a number, get the corresponding match group."
6495 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6496 (or (org-face-from-face-or-color
6497 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6498 'org-tag)))
6500 (defun org-font-lock-add-priority-faces (limit)
6501 "Add the special priority faces."
6502 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6503 (add-text-properties
6504 (match-beginning 1) (match-end 1)
6505 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6506 'font-lock-fontified t))))
6508 (defun org-font-lock-add-tag-faces (limit)
6509 "Add the special tag faces."
6510 (when (and org-tag-faces org-tags-special-faces-re)
6511 (while (re-search-forward org-tags-special-faces-re limit t)
6512 (add-text-properties (match-beginning 1) (match-end 1)
6513 (list 'face (org-get-tag-face 1)
6514 'font-lock-fontified t))
6515 (backward-char 1))))
6517 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6518 "Remove fontification and activation overlays from links."
6519 (font-lock-default-unfontify-region beg end)
6520 (let* ((buffer-undo-list t)
6521 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6522 (inhibit-modification-hooks t)
6523 deactivate-mark buffer-file-name buffer-file-truename)
6524 (org-decompose-region beg end)
6525 (remove-text-properties beg end
6526 '(mouse-face t keymap t org-linked-text t
6527 invisible t intangible t
6528 org-emphasis t))
6529 (org-remove-font-lock-display-properties beg end)))
6531 (defconst org-script-display '(((raise -0.3) (height 0.7))
6532 ((raise 0.3) (height 0.7))
6533 ((raise -0.5))
6534 ((raise 0.5)))
6535 "Display properties for showing superscripts and subscripts.")
6537 (defun org-remove-font-lock-display-properties (beg end)
6538 "Remove specific display properties that have been added by font lock.
6539 The will remove the raise properties that are used to show superscripts
6540 and subscripts."
6541 (let (next prop)
6542 (while (< beg end)
6543 (setq next (next-single-property-change beg 'display nil end)
6544 prop (get-text-property beg 'display))
6545 (when (member prop org-script-display)
6546 (put-text-property beg next 'display nil))
6547 (setq beg next))))
6549 (defun org-raise-scripts (limit)
6550 "Add raise properties to sub/superscripts."
6551 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6552 (re-search-forward
6553 (if (eq org-use-sub-superscripts t)
6554 org-match-substring-regexp
6555 org-match-substring-with-braces-regexp)
6556 limit t))
6557 (let* ((pos (point)) table-p comment-p
6558 (mpos (match-beginning 3))
6559 (emph-p (get-text-property mpos 'org-emphasis))
6560 (link-p (get-text-property mpos 'mouse-face))
6561 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6562 (goto-char (point-at-bol))
6563 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6564 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6565 (goto-char pos)
6566 ;; Handle a_b^c
6567 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6568 (unless (or comment-p emph-p link-p keyw-p)
6569 (put-text-property (match-beginning 3) (match-end 0)
6570 'display
6571 (if (equal (char-after (match-beginning 2)) ?^)
6572 (nth (if table-p 3 1) org-script-display)
6573 (nth (if table-p 2 0) org-script-display)))
6574 (add-text-properties (match-beginning 2) (match-end 2)
6575 (list 'invisible t
6576 'org-dwidth t 'org-dwidth-n 1))
6577 (if (and (eq (char-after (match-beginning 3)) ?{)
6578 (eq (char-before (match-end 3)) ?}))
6579 (progn
6580 (add-text-properties
6581 (match-beginning 3) (1+ (match-beginning 3))
6582 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6583 (add-text-properties
6584 (1- (match-end 3)) (match-end 3)
6585 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6586 t)))
6588 ;;;; Visibility cycling, including org-goto and indirect buffer
6590 ;;; Cycling
6592 (defvar-local org-cycle-global-status nil)
6593 (put 'org-cycle-global-status 'org-state t)
6594 (defvar-local org-cycle-subtree-status nil)
6595 (put 'org-cycle-subtree-status 'org-state t)
6597 (defvar org-inlinetask-min-level)
6599 (defun org-unlogged-message (&rest args)
6600 "Display a message, but avoid logging it in the *Messages* buffer."
6601 (let ((message-log-max nil))
6602 (apply 'message args)))
6604 ;;;###autoload
6605 (defun org-cycle (&optional arg)
6606 "TAB-action and visibility cycling for Org-mode.
6608 This is the command invoked in Org-mode by the TAB key. Its main purpose
6609 is outline visibility cycling, but it also invokes other actions
6610 in special contexts.
6612 - When this function is called with a prefix argument, rotate the entire
6613 buffer through 3 states (global cycling)
6614 1. OVERVIEW: Show only top-level headlines.
6615 2. CONTENTS: Show all headlines of all levels, but no body text.
6616 3. SHOW ALL: Show everything.
6617 With a double \\[universal-argument] prefix argument, \
6618 switch to the startup visibility,
6619 determined by the variable `org-startup-folded', and by any VISIBILITY
6620 properties in the buffer.
6621 With a triple \\[universal-argument] prefix argument, \
6622 show the entire buffer, including any drawers.
6624 - When inside a table, re-align the table and move to the next field.
6626 - When point is at the beginning of a headline, rotate the subtree started
6627 by this line through 3 different states (local cycling)
6628 1. FOLDED: Only the main headline is shown.
6629 2. CHILDREN: The main headline and the direct children are shown.
6630 From this state, you can move to one of the children
6631 and zoom in further.
6632 3. SUBTREE: Show the entire subtree, including body text.
6633 If there is no subtree, switch directly from CHILDREN to FOLDED.
6635 - When point is at the beginning of an empty headline and the variable
6636 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6637 of the headline by demoting and promoting it to likely levels. This
6638 speeds up creation document structure by pressing TAB once or several
6639 times right after creating a new headline.
6641 - When there is a numeric prefix, go up to a heading with level ARG, do
6642 a `show-subtree' and return to the previous cursor position. If ARG
6643 is negative, go up that many levels.
6645 - When point is not at the beginning of a headline, execute the global
6646 binding for TAB, which is re-indenting the line. See the option
6647 `org-cycle-emulate-tab' for details.
6649 - Special case: if point is at the beginning of the buffer and there is
6650 no headline in line 1, this function will act as if called with prefix arg
6651 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6652 But only if also the variable `org-cycle-global-at-bob' is t."
6653 (interactive "P")
6654 (org-load-modules-maybe)
6655 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6656 (and org-cycle-level-after-item/entry-creation
6657 (or (org-cycle-level)
6658 (org-cycle-item-indentation))))
6659 (let* ((limit-level
6660 (or org-cycle-max-level
6661 (and (boundp 'org-inlinetask-min-level)
6662 org-inlinetask-min-level
6663 (1- org-inlinetask-min-level))))
6664 (nstars (and limit-level
6665 (if org-odd-levels-only
6666 (and limit-level (1- (* limit-level 2)))
6667 limit-level)))
6668 (org-outline-regexp
6669 (if (not (derived-mode-p 'org-mode))
6670 outline-regexp
6671 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6672 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6673 (not (looking-at org-outline-regexp))))
6674 (org-cycle-hook
6675 (if bob-special
6676 (delq 'org-optimize-window-after-visibility-change
6677 (copy-sequence org-cycle-hook))
6678 org-cycle-hook))
6679 (pos (point)))
6681 (when (or bob-special (equal arg '(4)))
6682 ;; special case: use global cycling
6683 (setq arg t))
6685 (cond
6687 ((equal arg '(16))
6688 (setq last-command 'dummy)
6689 (org-set-startup-visibility)
6690 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6692 ((equal arg '(64))
6693 (outline-show-all)
6694 (org-unlogged-message "Entire buffer visible, including drawers"))
6696 ;; Try cdlatex TAB completion
6697 ((org-try-cdlatex-tab))
6699 ;; Table: enter it or move to the next field.
6700 ((org-at-table-p 'any)
6701 (if (org-at-table.el-p)
6702 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6703 Use \\[org-edit-special] to edit table.el tables"))
6704 (if arg (org-table-edit-field t)
6705 (org-table-justify-field-maybe)
6706 (call-interactively 'org-table-next-field))))
6708 ((run-hook-with-args-until-success
6709 'org-tab-after-check-for-table-hook))
6711 ;; Global cycling: delegate to `org-cycle-internal-global'.
6712 ((eq arg t) (org-cycle-internal-global))
6714 ;; Drawers: delegate to `org-flag-drawer'.
6715 ((save-excursion
6716 (beginning-of-line 1)
6717 (looking-at org-drawer-regexp))
6718 (org-flag-drawer ; toggle block visibility
6719 (not (get-char-property (match-end 0) 'invisible))))
6721 ;; Show-subtree, ARG levels up from here.
6722 ((integerp arg)
6723 (save-excursion
6724 (org-back-to-heading)
6725 (outline-up-heading (if (< arg 0) (- arg)
6726 (- (funcall outline-level) arg)))
6727 (org-show-subtree)))
6729 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6730 ((and (featurep 'org-inlinetask)
6731 (org-inlinetask-at-task-p)
6732 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6733 (org-inlinetask-toggle-visibility))
6735 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6736 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6737 (save-excursion (move-beginning-of-line 1)
6738 (looking-at org-outline-regexp)))
6739 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6740 (org-cycle-internal-local))
6742 ;; From there: TAB emulation and template completion.
6743 (buffer-read-only (org-back-to-heading))
6745 ((run-hook-with-args-until-success
6746 'org-tab-after-check-for-cycling-hook))
6748 ((org-try-structure-completion))
6750 ((run-hook-with-args-until-success
6751 'org-tab-before-tab-emulation-hook))
6753 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6754 (or (not (bolp))
6755 (not (looking-at org-outline-regexp))))
6756 (call-interactively (global-key-binding "\t")))
6758 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6759 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6760 (or (and (eq org-cycle-emulate-tab 'white)
6761 (= (match-end 0) (point-at-eol)))
6762 (and (eq org-cycle-emulate-tab 'whitestart)
6763 (>= (match-end 0) pos))))
6765 (eq org-cycle-emulate-tab t))
6766 (call-interactively (global-key-binding "\t")))
6768 (t (save-excursion
6769 (org-back-to-heading)
6770 (org-cycle)))))))
6772 (defun org-cycle-internal-global ()
6773 "Do the global cycling action."
6774 ;; Hack to avoid display of messages for .org attachments in Gnus
6775 (let ((ga (string-match "\\*fontification" (buffer-name))))
6776 (cond
6777 ((and (eq last-command this-command)
6778 (eq org-cycle-global-status 'overview))
6779 ;; We just created the overview - now do table of contents
6780 ;; This can be slow in very large buffers, so indicate action
6781 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6782 (unless ga (org-unlogged-message "CONTENTS..."))
6783 (org-content)
6784 (unless ga (org-unlogged-message "CONTENTS...done"))
6785 (setq org-cycle-global-status 'contents)
6786 (run-hook-with-args 'org-cycle-hook 'contents))
6788 ((and (eq last-command this-command)
6789 (eq org-cycle-global-status 'contents))
6790 ;; We just showed the table of contents - now show everything
6791 (run-hook-with-args 'org-pre-cycle-hook 'all)
6792 (outline-show-all)
6793 (unless ga (org-unlogged-message "SHOW ALL"))
6794 (setq org-cycle-global-status 'all)
6795 (run-hook-with-args 'org-cycle-hook 'all))
6798 ;; Default action: go to overview
6799 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6800 (org-overview)
6801 (unless ga (org-unlogged-message "OVERVIEW"))
6802 (setq org-cycle-global-status 'overview)
6803 (run-hook-with-args 'org-cycle-hook 'overview)))))
6805 (defvar org-called-with-limited-levels nil
6806 "Non-nil when `org-with-limited-levels' is currently active.")
6808 (defun org-cycle-internal-local ()
6809 "Do the local cycling action."
6810 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6811 ;; First, determine end of headline (EOH), end of subtree or item
6812 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6813 (save-excursion
6814 (if (org-at-item-p)
6815 (progn
6816 (beginning-of-line)
6817 (setq struct (org-list-struct))
6818 (setq eoh (point-at-eol))
6819 (setq eos (org-list-get-item-end-before-blank (point) struct))
6820 (setq has-children (org-list-has-child-p (point) struct)))
6821 (org-back-to-heading)
6822 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6823 (setq eos (save-excursion (org-end-of-subtree t t)
6824 (when (bolp) (backward-char)) (point)))
6825 (setq has-children
6826 (or (save-excursion
6827 (let ((level (funcall outline-level)))
6828 (outline-next-heading)
6829 (and (org-at-heading-p t)
6830 (> (funcall outline-level) level))))
6831 (save-excursion
6832 (org-list-search-forward (org-item-beginning-re) eos t)))))
6833 ;; Determine end invisible part of buffer (EOL)
6834 (beginning-of-line 2)
6835 ;; XEmacs doesn't have `next-single-char-property-change'
6836 (if (featurep 'xemacs)
6837 (while (and (not (eobp)) ;; this is like `next-line'
6838 (get-char-property (1- (point)) 'invisible))
6839 (beginning-of-line 2))
6840 (while (and (not (eobp)) ;; this is like `next-line'
6841 (get-char-property (1- (point)) 'invisible))
6842 (goto-char (next-single-char-property-change (point) 'invisible))
6843 (and (eolp) (beginning-of-line 2))))
6844 (setq eol (point)))
6845 ;; Find out what to do next and set `this-command'
6846 (cond
6847 ((= eos eoh)
6848 ;; Nothing is hidden behind this heading
6849 (unless (org-before-first-heading-p)
6850 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6851 (org-unlogged-message "EMPTY ENTRY")
6852 (setq org-cycle-subtree-status nil)
6853 (save-excursion
6854 (goto-char eos)
6855 (outline-next-heading)
6856 (when (outline-invisible-p) (org-flag-heading nil))))
6857 ((and (or (>= eol eos)
6858 (not (string-match "\\S-" (buffer-substring eol eos))))
6859 (or has-children
6860 (not (setq children-skipped
6861 org-cycle-skip-children-state-if-no-children))))
6862 ;; Entire subtree is hidden in one line: children view
6863 (unless (org-before-first-heading-p)
6864 (run-hook-with-args 'org-pre-cycle-hook 'children))
6865 (if (org-at-item-p)
6866 (org-list-set-item-visibility (point-at-bol) struct 'children)
6867 (org-show-entry)
6868 (org-with-limited-levels (org-show-children))
6869 ;; FIXME: This slows down the func way too much.
6870 ;; How keep drawers hidden in subtree anyway?
6871 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6872 ;; (org-cycle-hide-drawers 'subtree))
6874 ;; Fold every list in subtree to top-level items.
6875 (when (eq org-cycle-include-plain-lists 'integrate)
6876 (save-excursion
6877 (org-back-to-heading)
6878 (while (org-list-search-forward (org-item-beginning-re) eos t)
6879 (beginning-of-line 1)
6880 (let* ((struct (org-list-struct))
6881 (prevs (org-list-prevs-alist struct))
6882 (end (org-list-get-bottom-point struct)))
6883 (dolist (e (org-list-get-all-items (point) struct prevs))
6884 (org-list-set-item-visibility e struct 'folded))
6885 (goto-char (if (< end eos) end eos)))))))
6886 (org-unlogged-message "CHILDREN")
6887 (save-excursion
6888 (goto-char eos)
6889 (outline-next-heading)
6890 (when (outline-invisible-p) (org-flag-heading nil)))
6891 (setq org-cycle-subtree-status 'children)
6892 (unless (org-before-first-heading-p)
6893 (run-hook-with-args 'org-cycle-hook 'children)))
6894 ((or children-skipped
6895 (and (eq last-command this-command)
6896 (eq org-cycle-subtree-status 'children)))
6897 ;; We just showed the children, or no children are there,
6898 ;; now show everything.
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6901 (outline-flag-region eoh eos nil)
6902 (org-unlogged-message
6903 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6904 (setq org-cycle-subtree-status 'subtree)
6905 (unless (org-before-first-heading-p)
6906 (run-hook-with-args 'org-cycle-hook 'subtree)))
6908 ;; Default action: hide the subtree.
6909 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6910 (outline-flag-region eoh eos t)
6911 (org-unlogged-message "FOLDED")
6912 (setq org-cycle-subtree-status 'folded)
6913 (unless (org-before-first-heading-p)
6914 (run-hook-with-args 'org-cycle-hook 'folded))))))
6916 ;;;###autoload
6917 (defun org-global-cycle (&optional arg)
6918 "Cycle the global visibility. For details see `org-cycle'.
6919 With \\[universal-argument] prefix arg, switch to startup visibility.
6920 With a numeric prefix, show all headlines up to that level."
6921 (interactive "P")
6922 (let ((org-cycle-include-plain-lists
6923 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6924 (cond
6925 ((integerp arg)
6926 (outline-show-all)
6927 (outline-hide-sublevels arg)
6928 (setq org-cycle-global-status 'contents))
6929 ((equal arg '(4))
6930 (org-set-startup-visibility)
6931 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6933 (org-cycle '(4))))))
6935 (defun org-set-startup-visibility ()
6936 "Set the visibility required by startup options and properties."
6937 (cond
6938 ((eq org-startup-folded t)
6939 (org-overview))
6940 ((eq org-startup-folded 'content)
6941 (org-content))
6942 ((or (eq org-startup-folded 'showeverything)
6943 (eq org-startup-folded nil))
6944 (outline-show-all)))
6945 (unless (eq org-startup-folded 'showeverything)
6946 (when org-hide-block-startup (org-hide-block-all))
6947 (org-set-visibility-according-to-property 'no-cleanup)
6948 (org-cycle-hide-archived-subtrees 'all)
6949 (org-cycle-hide-drawers 'all)
6950 (org-cycle-show-empty-lines t)))
6952 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6953 "Switch subtree visibilities according to :VISIBILITY: property."
6954 (interactive)
6955 (org-with-wide-buffer
6956 (goto-char (point-min))
6957 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6958 (if (not (org-at-property-p)) (outline-next-heading)
6959 (let ((state (match-string 3)))
6960 (save-excursion
6961 (org-back-to-heading t)
6962 (outline-hide-subtree)
6963 (org-reveal)
6964 (cond
6965 ((equal state "folded")
6966 (outline-hide-subtree))
6967 ((equal state "children")
6968 (org-show-hidden-entry)
6969 (org-show-children))
6970 ((equal state "content")
6971 (save-excursion
6972 (save-restriction
6973 (org-narrow-to-subtree)
6974 (org-content))))
6975 ((member state '("all" "showall"))
6976 (outline-show-subtree)))))))
6977 (unless no-cleanup
6978 (org-cycle-hide-archived-subtrees 'all)
6979 (org-cycle-hide-drawers 'all)
6980 (org-cycle-show-empty-lines 'all))))
6982 ;; This function uses outline-regexp instead of the more fundamental
6983 ;; org-outline-regexp so that org-cycle-global works outside of Org
6984 ;; buffers, where outline-regexp is needed.
6985 (defun org-overview ()
6986 "Switch to overview mode, showing only top-level headlines.
6987 This shows all headlines with a level equal or greater than the level
6988 of the first headline in the buffer. This is important, because if the
6989 first headline is not level one, then (hide-sublevels 1) gives confusing
6990 results."
6991 (interactive)
6992 (save-excursion
6993 (let ((level
6994 (save-excursion
6995 (goto-char (point-min))
6996 (when (re-search-forward (concat "^" outline-regexp) nil t)
6997 (goto-char (match-beginning 0))
6998 (funcall outline-level)))))
6999 (and level (outline-hide-sublevels level)))))
7001 (defun org-content (&optional arg)
7002 "Show all headlines in the buffer, like a table of contents.
7003 With numerical argument N, show content up to level N."
7004 (interactive "P")
7005 (org-overview)
7006 (save-excursion
7007 ;; Visit all headings and show their offspring
7008 (and (integerp arg) (org-overview))
7009 (goto-char (point-max))
7010 (catch 'exit
7011 (while (and (progn (condition-case nil
7012 (outline-previous-visible-heading 1)
7013 (error (goto-char (point-min))))
7015 (looking-at org-outline-regexp))
7016 (if (integerp arg)
7017 (org-show-children (1- arg))
7018 (outline-show-branches))
7019 (when (bobp) (throw 'exit nil))))))
7021 (defun org-optimize-window-after-visibility-change (state)
7022 "Adjust the window after a change in outline visibility.
7023 This function is the default value of the hook `org-cycle-hook'."
7024 (when (get-buffer-window (current-buffer))
7025 (cond
7026 ((eq state 'content) nil)
7027 ((eq state 'all) nil)
7028 ((eq state 'folded) nil)
7029 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7030 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7032 (defun org-remove-empty-overlays-at (pos)
7033 "Remove outline overlays that do not contain non-white stuff."
7034 (dolist (o (overlays-at pos))
7035 (and (eq 'outline (overlay-get o 'invisible))
7036 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7037 (overlay-end o))))
7038 (delete-overlay o))))
7040 (defun org-clean-visibility-after-subtree-move ()
7041 "Fix visibility issues after moving a subtree."
7042 ;; First, find a reasonable region to look at:
7043 ;; Start two siblings above, end three below
7044 (let* ((beg (save-excursion
7045 (and (org-get-last-sibling)
7046 (org-get-last-sibling))
7047 (point)))
7048 (end (save-excursion
7049 (and (org-get-next-sibling)
7050 (org-get-next-sibling)
7051 (org-get-next-sibling))
7052 (if (org-at-heading-p)
7053 (point-at-eol)
7054 (point))))
7055 (level (looking-at "\\*+"))
7056 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7057 (save-excursion
7058 (save-restriction
7059 (narrow-to-region beg end)
7060 (when re
7061 ;; Properly fold already folded siblings
7062 (goto-char (point-min))
7063 (while (re-search-forward re nil t)
7064 (when (and (not (outline-invisible-p))
7065 (save-excursion
7066 (goto-char (point-at-eol)) (outline-invisible-p)))
7067 (outline-hide-entry))))
7068 (org-cycle-show-empty-lines 'overview)
7069 (org-cycle-hide-drawers 'overview)))))
7071 (defun org-cycle-show-empty-lines (state)
7072 "Show empty lines above all visible headlines.
7073 The region to be covered depends on STATE when called through
7074 `org-cycle-hook'. Lisp program can use t for STATE to get the
7075 entire buffer covered. Note that an empty line is only shown if there
7076 are at least `org-cycle-separator-lines' empty lines before the headline."
7077 (when (/= org-cycle-separator-lines 0)
7078 (save-excursion
7079 (let* ((n (abs org-cycle-separator-lines))
7080 (re (cond
7081 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7082 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7083 (t (let ((ns (number-to-string (- n 2))))
7084 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7085 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7086 beg end)
7087 (cond
7088 ((memq state '(overview contents t))
7089 (setq beg (point-min) end (point-max)))
7090 ((memq state '(children folded))
7091 (setq beg (point)
7092 end (progn (org-end-of-subtree t t)
7093 (line-beginning-position 2)))))
7094 (when beg
7095 (goto-char beg)
7096 (while (re-search-forward re end t)
7097 (unless (get-char-property (match-end 1) 'invisible)
7098 (let ((e (match-end 1))
7099 (b (if (>= org-cycle-separator-lines 0)
7100 (match-beginning 1)
7101 (save-excursion
7102 (goto-char (match-beginning 0))
7103 (skip-chars-backward " \t\n")
7104 (line-end-position)))))
7105 (outline-flag-region b e nil))))))))
7106 ;; Never hide empty lines at the end of the file.
7107 (save-excursion
7108 (goto-char (point-max))
7109 (outline-previous-heading)
7110 (outline-end-of-heading)
7111 (when (and (looking-at "[ \t\n]+")
7112 (= (match-end 0) (point-max)))
7113 (outline-flag-region (point) (match-end 0) nil))))
7115 (defun org-show-empty-lines-in-parent ()
7116 "Move to the parent and re-show empty lines before visible headlines."
7117 (save-excursion
7118 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7119 (org-cycle-show-empty-lines context))))
7121 (defun org-files-list ()
7122 "Return `org-agenda-files' list, plus all open org-mode files.
7123 This is useful for operations that need to scan all of a user's
7124 open and agenda-wise Org files."
7125 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7126 (dolist (buf (buffer-list))
7127 (with-current-buffer buf
7128 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7129 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7130 files))
7132 (defsubst org-entry-beginning-position ()
7133 "Return the beginning position of the current entry."
7134 (save-excursion (outline-back-to-heading t) (point)))
7136 (defsubst org-entry-end-position ()
7137 "Return the end position of the current entry."
7138 (save-excursion (outline-next-heading) (point)))
7140 (defun org-cycle-hide-drawers (state &optional exceptions)
7141 "Re-hide all drawers after a visibility state change.
7142 When non-nil, optional argument EXCEPTIONS is a list of strings
7143 specifying which drawers should not be hidden."
7144 (when (and (derived-mode-p 'org-mode)
7145 (not (memq state '(overview folded contents))))
7146 (save-excursion
7147 (let* ((globalp (memq state '(contents all)))
7148 (beg (if globalp (point-min) (point)))
7149 (end (if globalp (point-max)
7150 (if (eq state 'children)
7151 (save-excursion (outline-next-heading) (point))
7152 (org-end-of-subtree t)))))
7153 (goto-char beg)
7154 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7155 (unless (member-ignore-case (match-string 1) exceptions)
7156 (let ((drawer (org-element-at-point)))
7157 (when (memq (org-element-type drawer) '(drawer property-drawer))
7158 (org-flag-drawer t drawer)
7159 ;; Make sure to skip drawer entirely or we might flag
7160 ;; it another time when matching its ending line with
7161 ;; `org-drawer-regexp'.
7162 (goto-char (org-element-property :end drawer))))))))))
7164 (defun org-flag-drawer (flag &optional element)
7165 "When FLAG is non-nil, hide the drawer we are at.
7166 Otherwise make it visible. When optional argument ELEMENT is
7167 a parsed drawer, as returned by `org-element-at-point', hide or
7168 show that drawer instead."
7169 (when (save-excursion
7170 (beginning-of-line)
7171 (org-looking-at-p org-drawer-regexp))
7172 (let ((drawer (or element (org-element-at-point))))
7173 (when (memq (org-element-type drawer) '(drawer property-drawer))
7174 (let ((post (org-element-property :post-affiliated drawer)))
7175 (save-excursion
7176 (outline-flag-region
7177 (progn (goto-char post) (line-end-position))
7178 (progn (goto-char (org-element-property :end drawer))
7179 (skip-chars-backward " \r\t\n")
7180 (line-end-position))
7181 flag))
7182 ;; When the drawer is hidden away, make sure point lies in
7183 ;; a visible part of the buffer.
7184 (when (and flag (> (line-beginning-position) post))
7185 (goto-char post)))))))
7187 (defun org-subtree-end-visible-p ()
7188 "Is the end of the current subtree visible?"
7189 (pos-visible-in-window-p
7190 (save-excursion (org-end-of-subtree t) (point))))
7192 (defun org-first-headline-recenter ()
7193 "Move cursor to the first headline and recenter the headline."
7194 (goto-char (point-min))
7195 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7196 (set-window-start (selected-window) (point-at-bol))))
7198 ;;; Saving and restoring visibility
7200 (defun org-outline-overlay-data (&optional use-markers)
7201 "Return a list of the locations of all outline overlays.
7202 These are overlays with the `invisible' property value `outline'.
7203 The return value is a list of cons cells, with start and stop
7204 positions for each overlay.
7205 If USE-MARKERS is set, return the positions as markers."
7206 (let (beg end)
7207 (save-excursion
7208 (save-restriction
7209 (widen)
7210 (delq nil
7211 (mapcar (lambda (o)
7212 (when (eq (overlay-get o 'invisible) 'outline)
7213 (setq beg (overlay-start o)
7214 end (overlay-end o))
7215 (and beg end (> end beg)
7216 (if use-markers
7217 (cons (copy-marker beg)
7218 (copy-marker end t))
7219 (cons beg end)))))
7220 (overlays-in (point-min) (point-max))))))))
7222 (defun org-set-outline-overlay-data (data)
7223 "Create visibility overlays for all positions in DATA.
7224 DATA should have been made by `org-outline-overlay-data'."
7225 (org-with-wide-buffer
7226 (outline-show-all)
7227 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7229 ;;; Folding of blocks
7231 (defvar-local org-hide-block-overlays nil
7232 "Overlays hiding blocks.")
7234 (defun org-block-map (function &optional start end)
7235 "Call FUNCTION at the head of all source blocks in the current buffer.
7236 Optional arguments START and END can be used to limit the range."
7237 (let ((start (or start (point-min)))
7238 (end (or end (point-max))))
7239 (save-excursion
7240 (goto-char start)
7241 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7242 (save-excursion
7243 (save-match-data
7244 (goto-char (match-beginning 0))
7245 (funcall function)))))))
7247 (defun org-hide-block-toggle-all ()
7248 "Toggle the visibility of all blocks in the current buffer."
7249 (org-block-map 'org-hide-block-toggle))
7251 (defun org-hide-block-all ()
7252 "Fold all blocks in the current buffer."
7253 (interactive)
7254 (org-show-block-all)
7255 (org-block-map 'org-hide-block-toggle-maybe))
7257 (defun org-show-block-all ()
7258 "Unfold all blocks in the current buffer."
7259 (interactive)
7260 (mapc #'delete-overlay org-hide-block-overlays)
7261 (setq org-hide-block-overlays nil))
7263 (defun org-hide-block-toggle-maybe ()
7264 "Toggle visibility of block at point.
7265 Unlike to `org-hide-block-toggle', this function does not throw
7266 an error. Return a non-nil value when toggling is successful."
7267 (interactive)
7268 (ignore-errors (org-hide-block-toggle)))
7270 (defun org-hide-block-toggle (&optional force)
7271 "Toggle the visibility of the current block.
7272 When optional argument FORCE is `off', make block visible. If it
7273 is non-nil, hide it unconditionally. Throw an error when not at
7274 a block. Return a non-nil value when toggling is successful."
7275 (interactive)
7276 (let ((element (org-element-at-point)))
7277 (unless (memq (org-element-type element)
7278 '(center-block comment-block dynamic-block example-block
7279 export-block quote-block special-block
7280 src-block verse-block))
7281 (user-error "Not at a block"))
7282 (let* ((start (save-excursion
7283 (goto-char (org-element-property :post-affiliated element))
7284 (line-end-position)))
7285 (end (save-excursion
7286 (goto-char (org-element-property :end element))
7287 (skip-chars-backward " \r\t\n")
7288 (line-end-position)))
7289 (overlays (overlays-at start)))
7290 (cond
7291 ;; Do nothing when not before or at the block opening line or
7292 ;; at the block closing line.
7293 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7294 ((and (not (eq force 'off))
7295 (not (memq t (mapcar
7296 (lambda (o)
7297 (eq (overlay-get o 'invisible) 'org-hide-block))
7298 overlays))))
7299 (let ((ov (make-overlay start end)))
7300 (overlay-put ov 'invisible 'org-hide-block)
7301 ;; Make the block accessible to `isearch'.
7302 (overlay-put
7303 ov 'isearch-open-invisible
7304 (lambda (ov)
7305 (when (memq ov org-hide-block-overlays)
7306 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7307 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7308 (delete-overlay ov))))
7309 (push ov org-hide-block-overlays)
7310 ;; When the block is hidden away, make sure point is left in
7311 ;; a visible part of the buffer.
7312 (when (> (line-beginning-position) start)
7313 (goto-char start)
7314 (beginning-of-line))
7315 ;; Signal successful toggling.
7317 ((or (not force) (eq force 'off))
7318 (dolist (ov overlays t)
7319 (when (memq ov org-hide-block-overlays)
7320 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7321 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7322 (delete-overlay ov))))))))
7324 ;; org-tab-after-check-for-cycling-hook
7325 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7326 ;; Remove overlays when changing major mode
7327 (add-hook 'org-mode-hook
7328 (lambda () (org-add-hook 'change-major-mode-hook
7329 'org-show-block-all 'append 'local)))
7331 ;;; Org-goto
7333 (defvar org-goto-window-configuration nil)
7334 (defvar org-goto-marker nil)
7335 (defvar org-goto-map)
7336 (defun org-goto-map ()
7337 "Set the keymap `org-goto'."
7338 (setq org-goto-map
7339 (let ((map (make-sparse-keymap)))
7340 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7341 mouse-drag-region universal-argument org-occur)))
7342 (dolist (cmd cmds)
7343 (substitute-key-definition cmd cmd map global-map)))
7344 (suppress-keymap map)
7345 (org-defkey map "\C-m" 'org-goto-ret)
7346 (org-defkey map [(return)] 'org-goto-ret)
7347 (org-defkey map [(left)] 'org-goto-left)
7348 (org-defkey map [(right)] 'org-goto-right)
7349 (org-defkey map [(control ?g)] 'org-goto-quit)
7350 (org-defkey map "\C-i" 'org-cycle)
7351 (org-defkey map [(tab)] 'org-cycle)
7352 (org-defkey map [(down)] 'outline-next-visible-heading)
7353 (org-defkey map [(up)] 'outline-previous-visible-heading)
7354 (if org-goto-auto-isearch
7355 (if (fboundp 'define-key-after)
7356 (define-key-after map [t] 'org-goto-local-auto-isearch)
7357 nil)
7358 (org-defkey map "q" 'org-goto-quit)
7359 (org-defkey map "n" 'outline-next-visible-heading)
7360 (org-defkey map "p" 'outline-previous-visible-heading)
7361 (org-defkey map "f" 'outline-forward-same-level)
7362 (org-defkey map "b" 'outline-backward-same-level)
7363 (org-defkey map "u" 'outline-up-heading))
7364 (org-defkey map "/" 'org-occur)
7365 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7366 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7367 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7368 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7369 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7370 map)))
7372 (defconst org-goto-help
7373 "Browse buffer copy, to find location or copy text.%s
7374 RET=jump to location C-g=quit and return to previous location
7375 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7377 (defvar org-goto-start-pos) ; dynamically scoped parameter
7379 (defun org-goto (&optional alternative-interface)
7380 "Look up a different location in the current file, keeping current visibility.
7382 When you want look-up or go to a different location in a
7383 document, the fastest way is often to fold the entire buffer and
7384 then dive into the tree. This method has the disadvantage, that
7385 the previous location will be folded, which may not be what you
7386 want.
7388 This command works around this by showing a copy of the current
7389 buffer in an indirect buffer, in overview mode. You can dive
7390 into the tree in that copy, use org-occur and incremental search
7391 to find a location. When pressing RET or `Q', the command
7392 returns to the original buffer in which the visibility is still
7393 unchanged. After RET it will also jump to the location selected
7394 in the indirect buffer and expose the headline hierarchy above.
7396 With a prefix argument, use the alternative interface: e.g., if
7397 `org-goto-interface' is `outline' use `outline-path-completion'."
7398 (interactive "P")
7399 (org-goto-map)
7400 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7401 (org-refile-use-outline-path t)
7402 (org-refile-target-verify-function nil)
7403 (interface
7404 (if (not alternative-interface)
7405 org-goto-interface
7406 (if (eq org-goto-interface 'outline)
7407 'outline-path-completion
7408 'outline)))
7409 (org-goto-start-pos (point))
7410 (selected-point
7411 (if (eq interface 'outline)
7412 (car (org-get-location (current-buffer) org-goto-help))
7413 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7414 (org-refile-check-position pa)
7415 (nth 3 pa)))))
7416 (if selected-point
7417 (progn
7418 (org-mark-ring-push org-goto-start-pos)
7419 (goto-char selected-point)
7420 (when (or (outline-invisible-p) (org-invisible-p2))
7421 (org-show-context 'org-goto)))
7422 (message "Quit"))))
7424 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7425 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7426 (defvar org-goto-local-auto-isearch-map) ; defined below
7428 (defun org-get-location (_buf help)
7429 "Let the user select a location in current buffer.
7430 This function uses a recursive edit. It returns the selected position
7431 or nil."
7432 (org-no-popups
7433 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7434 (isearch-hide-immediately nil)
7435 (isearch-search-fun-function
7436 (lambda () 'org-goto-local-search-headings))
7437 (org-goto-selected-point org-goto-exit-command))
7438 (save-excursion
7439 (save-window-excursion
7440 (delete-other-windows)
7441 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7442 (org-pop-to-buffer-same-window
7443 (condition-case nil
7444 (make-indirect-buffer (current-buffer) "*org-goto*")
7445 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7446 (with-output-to-temp-buffer "*Org Help*"
7447 (princ (format help (if org-goto-auto-isearch
7448 " Just type for auto-isearch."
7449 " n/p/f/b/u to navigate, q to quit."))))
7450 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7451 (setq buffer-read-only nil)
7452 (let ((org-startup-truncated t)
7453 (org-startup-folded nil)
7454 (org-startup-align-all-tables nil))
7455 (org-mode)
7456 (org-overview))
7457 (setq buffer-read-only t)
7458 (if (and (boundp 'org-goto-start-pos)
7459 (integer-or-marker-p org-goto-start-pos))
7460 (progn (goto-char org-goto-start-pos)
7461 (when (outline-invisible-p)
7462 (org-show-set-visibility 'lineage)))
7463 (goto-char (point-min)))
7464 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7465 (message "Select location and press RET")
7466 (use-local-map org-goto-map)
7467 (recursive-edit)))
7468 (kill-buffer "*org-goto*")
7469 (cons org-goto-selected-point org-goto-exit-command))))
7471 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7472 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7473 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7474 (if (fboundp 'isearch-other-control-char)
7475 (progn
7476 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7477 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7478 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7479 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7480 (define-key org-goto-local-auto-isearch-map [return] nil))
7482 (defun org-goto-local-search-headings (string bound noerror)
7483 "Search and make sure that any matches are in headlines."
7484 (catch 'return
7485 (while (if isearch-forward
7486 (search-forward string bound noerror)
7487 (search-backward string bound noerror))
7488 (when (save-match-data
7489 (and (save-excursion
7490 (beginning-of-line)
7491 (looking-at org-complex-heading-regexp))
7492 (or (not (match-beginning 5))
7493 (< (point) (match-beginning 5)))))
7494 (throw 'return (point))))))
7496 (defun org-goto-local-auto-isearch ()
7497 "Start isearch."
7498 (interactive)
7499 (goto-char (point-min))
7500 (let ((keys (this-command-keys)))
7501 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7502 (isearch-mode t)
7503 (isearch-process-search-char (string-to-char keys)))))
7505 (defun org-goto-ret (&optional _arg)
7506 "Finish `org-goto' by going to the new location."
7507 (interactive "P")
7508 (setq org-goto-selected-point (point))
7509 (setq org-goto-exit-command 'return)
7510 (throw 'exit nil))
7512 (defun org-goto-left ()
7513 "Finish `org-goto' by going to the new location."
7514 (interactive)
7515 (if (org-at-heading-p)
7516 (progn
7517 (beginning-of-line 1)
7518 (setq org-goto-selected-point (point)
7519 org-goto-exit-command 'left)
7520 (throw 'exit nil))
7521 (user-error "Not on a heading")))
7523 (defun org-goto-right ()
7524 "Finish `org-goto' by going to the new location."
7525 (interactive)
7526 (if (org-at-heading-p)
7527 (progn
7528 (setq org-goto-selected-point (point)
7529 org-goto-exit-command 'right)
7530 (throw 'exit nil))
7531 (user-error "Not on a heading")))
7533 (defun org-goto-quit ()
7534 "Finish `org-goto' without cursor motion."
7535 (interactive)
7536 (setq org-goto-selected-point nil)
7537 (setq org-goto-exit-command 'quit)
7538 (throw 'exit nil))
7540 ;;; Indirect buffer display of subtrees
7542 (defvar org-indirect-dedicated-frame nil
7543 "This is the frame being used for indirect tree display.")
7544 (defvar org-last-indirect-buffer nil)
7546 (defun org-tree-to-indirect-buffer (&optional arg)
7547 "Create indirect buffer and narrow it to current subtree.
7548 With a numerical prefix ARG, go up to this level and then take that tree.
7549 If ARG is negative, go up that many levels.
7551 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7552 indirect buffer previously made with this command, to avoid proliferation of
7553 indirect buffers. However, when you call the command with a \
7554 \\[universal-argument] prefix, or
7555 when `org-indirect-buffer-display' is `new-frame', the last buffer
7556 is kept so that you can work with several indirect buffers at the same time.
7557 If `org-indirect-buffer-display' is `dedicated-frame', the \
7558 \\[universal-argument] prefix also
7559 requests that a new frame be made for the new buffer, so that the dedicated
7560 frame is not changed."
7561 (interactive "P")
7562 (let ((cbuf (current-buffer))
7563 (cwin (selected-window))
7564 (pos (point))
7565 beg end level heading ibuf)
7566 (save-excursion
7567 (org-back-to-heading t)
7568 (when (numberp arg)
7569 (setq level (org-outline-level))
7570 (when (< arg 0) (setq arg (+ level arg)))
7571 (while (> (setq level (org-outline-level)) arg)
7572 (org-up-heading-safe)))
7573 (setq beg (point)
7574 heading (org-get-heading 'no-tags))
7575 (org-end-of-subtree t t)
7576 (when (org-at-heading-p) (backward-char 1))
7577 (setq end (point)))
7578 (when (and (buffer-live-p org-last-indirect-buffer)
7579 (not (eq org-indirect-buffer-display 'new-frame))
7580 (not arg))
7581 (kill-buffer org-last-indirect-buffer))
7582 (setq ibuf (org-get-indirect-buffer cbuf heading)
7583 org-last-indirect-buffer ibuf)
7584 (cond
7585 ((or (eq org-indirect-buffer-display 'new-frame)
7586 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7587 (select-frame (make-frame))
7588 (delete-other-windows)
7589 (org-pop-to-buffer-same-window ibuf)
7590 (org-set-frame-title heading))
7591 ((eq org-indirect-buffer-display 'dedicated-frame)
7592 (raise-frame
7593 (select-frame (or (and org-indirect-dedicated-frame
7594 (frame-live-p org-indirect-dedicated-frame)
7595 org-indirect-dedicated-frame)
7596 (setq org-indirect-dedicated-frame (make-frame)))))
7597 (delete-other-windows)
7598 (org-pop-to-buffer-same-window ibuf)
7599 (org-set-frame-title (concat "Indirect: " heading)))
7600 ((eq org-indirect-buffer-display 'current-window)
7601 (org-pop-to-buffer-same-window ibuf))
7602 ((eq org-indirect-buffer-display 'other-window)
7603 (pop-to-buffer ibuf))
7604 (t (error "Invalid value")))
7605 (when (featurep 'xemacs)
7606 (save-excursion (org-mode) (turn-on-font-lock)))
7607 (narrow-to-region beg end)
7608 (outline-show-all)
7609 (goto-char pos)
7610 (run-hook-with-args 'org-cycle-hook 'all)
7611 (and (window-live-p cwin) (select-window cwin))))
7613 (defun org-get-indirect-buffer (&optional buffer heading)
7614 (setq buffer (or buffer (current-buffer)))
7615 (let ((n 1) (base (buffer-name buffer)) bname)
7616 (while (buffer-live-p
7617 (get-buffer
7618 (setq bname
7619 (concat base "-"
7620 (if heading (concat heading "-" (number-to-string n))
7621 (number-to-string n))))))
7622 (setq n (1+ n)))
7623 (condition-case nil
7624 (make-indirect-buffer buffer bname 'clone)
7625 (error (make-indirect-buffer buffer bname)))))
7627 (defun org-set-frame-title (title)
7628 "Set the title of the current frame to the string TITLE."
7629 ;; FIXME: how to name a single frame in XEmacs???
7630 (unless (featurep 'xemacs)
7631 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7633 ;;;; Structure editing
7635 ;;; Inserting headlines
7637 (defun org--line-empty-p (n)
7638 "Is the Nth next line empty?
7640 Counts the current line as N = 1 and the previous line as N = 0;
7641 see `beginning-of-line'."
7642 (save-excursion
7643 (and (not (bobp))
7644 (or (beginning-of-line n) t)
7645 (save-match-data
7646 (looking-at "[ \t]*$")))))
7648 (defun org-previous-line-empty-p ()
7649 "Is the previous line a blank line?
7650 When NEXT is non-nil, check the next line instead."
7651 (org--line-empty-p 0))
7653 (defun org-next-line-empty-p ()
7654 "Is the previous line a blank line?
7655 When NEXT is non-nil, check the next line instead."
7656 (org--line-empty-p 2))
7658 (defun org-insert-heading (&optional arg invisible-ok top)
7659 "Insert a new heading or an item with the same depth at point.
7661 If point is at the beginning of a heading or a list item, insert
7662 a new heading or a new item above the current one. If point is
7663 at the beginning of a normal line, turn the line into a heading.
7665 If point is in the middle of a headline or a list item, split the
7666 headline or the item and create a new headline/item with the text
7667 in the current line after point \(see `org-M-RET-may-split-line'
7668 on how to modify this behavior).
7670 With one universal prefix argument, set the user option
7671 `org-insert-heading-respect-content' to t for the duration of
7672 the command. This modifies the behavior described above in this
7673 ways: on list items and at the beginning of normal lines, force
7674 the insertion of a heading after the current subtree.
7676 With two universal prefix arguments, insert the heading at the
7677 end of the grandparent subtree. For example, if point is within
7678 a 2nd-level heading, then it will insert a 2nd-level heading at
7679 the end of the 1st-level parent heading.
7681 If point is at the beginning of a headline, insert a sibling
7682 before the current headline. If point is not at the beginning,
7683 split the line and create a new headline with the text in the
7684 current line after point \(see `org-M-RET-may-split-line' on how
7685 to modify this behavior).
7687 If point is at the beginning of a normal line, turn this line
7688 into a heading.
7690 When INVISIBLE-OK is set, stop at invisible headlines when going
7691 back. This is important for non-interactive uses of the
7692 command.
7694 When optional argument TOP is non-nil, insert a level 1 heading,
7695 unconditionally."
7696 (interactive "P")
7697 (when (org-called-interactively-p 'any) (org-reveal))
7698 (let ((itemp (and (not top) (org-in-item-p)))
7699 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7700 (respect-content (or org-insert-heading-respect-content
7701 (equal arg '(4))))
7702 (initial-content ""))
7704 (cond
7706 ((or (= (buffer-size) 0)
7707 (and (not (save-excursion
7708 (and (ignore-errors (org-back-to-heading invisible-ok))
7709 (org-at-heading-p))))
7710 (or arg (not itemp))))
7711 ;; At beginning of buffer or so high up that only a heading
7712 ;; makes sense.
7713 (cond ((and (bolp) (not respect-content)) (insert "* "))
7714 ((not respect-content)
7715 (unless may-split (end-of-line))
7716 (insert "\n* "))
7717 ((re-search-forward org-outline-regexp-bol nil t)
7718 (beginning-of-line)
7719 (insert "* \n")
7720 (backward-char))
7721 (t (goto-char (point-max))
7722 (insert "\n* ")))
7723 (run-hooks 'org-insert-heading-hook))
7725 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7728 ;; Maybe move at the end of the subtree
7729 (when (equal arg '(16))
7730 (org-up-heading-safe)
7731 (org-end-of-subtree t))
7732 ;; Insert a heading
7733 (save-restriction
7734 (widen)
7735 (let* ((level nil)
7736 (on-heading (org-at-heading-p))
7737 (empty-line-p (if on-heading
7738 (org-previous-line-empty-p)
7739 ;; We will decide later
7740 nil))
7741 ;; Get a level string to fall back on.
7742 (fix-level
7743 (if (org-before-first-heading-p) "*"
7744 (save-excursion
7745 (org-back-to-heading t)
7746 (when (org-previous-line-empty-p) (setq empty-line-p t))
7747 (looking-at org-outline-regexp)
7748 (make-string (1- (length (match-string 0))) ?*))))
7749 (stars
7750 (save-excursion
7751 (condition-case nil
7752 (if top "* "
7753 (org-back-to-heading invisible-ok)
7754 (when (and (not on-heading)
7755 (featurep 'org-inlinetask)
7756 (integerp org-inlinetask-min-level)
7757 (>= (length (match-string 0))
7758 org-inlinetask-min-level))
7759 ;; Find a heading level before the inline
7760 ;; task.
7761 (while (and (setq level (org-up-heading-safe))
7762 (>= level org-inlinetask-min-level)))
7763 (if (org-at-heading-p)
7764 (org-back-to-heading invisible-ok)
7765 (error "This should not happen")))
7766 (unless (and (save-excursion
7767 (save-match-data
7768 (org-backward-heading-same-level
7769 1 invisible-ok))
7770 (= (point) (match-beginning 0)))
7771 (not (org-next-line-empty-p)))
7772 (setq empty-line-p (or empty-line-p
7773 (org-previous-line-empty-p))))
7774 (match-string 0))
7775 (error (or fix-level "* ")))))
7776 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7777 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7779 ;; If we insert after content, move there and clean up
7780 ;; whitespace.
7781 (when (and respect-content
7782 (not (org-looking-at-p org-outline-regexp-bol)))
7783 (if (not (org-before-first-heading-p))
7784 (org-end-of-subtree nil t)
7785 (re-search-forward org-outline-regexp-bol)
7786 (beginning-of-line 0))
7787 (skip-chars-backward " \r\t\n")
7788 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7789 (looking-at "[ \t]+") (replace-match ""))
7790 (unless (eobp) (forward-char 1))
7791 (when (looking-at "^\\*")
7792 (unless (bobp) (backward-char 1))
7793 (insert "\n")))
7795 ;; If we are splitting, grab the text that should be moved
7796 ;; to the new headline.
7797 (when may-split
7798 (if (org-at-heading-p)
7799 ;; This is a heading: split intelligently (keeping
7800 ;; tags).
7801 (let ((pos (point)))
7802 (beginning-of-line)
7803 (unless (looking-at org-complex-heading-regexp)
7804 (error "This should not happen"))
7805 (when (and (match-beginning 4)
7806 (> pos (match-beginning 4))
7807 (< pos (match-end 4)))
7808 (setq initial-content (buffer-substring pos (match-end 4)))
7809 (goto-char pos)
7810 (delete-region (point) (match-end 4))
7811 (if (looking-at "[ \t]*$")
7812 (replace-match "")
7813 (insert (make-string (length initial-content) ?\s)))
7814 (setq initial-content (org-trim initial-content)))
7815 (goto-char pos))
7816 ;; A normal line.
7817 (setq initial-content
7818 (org-trim
7819 (delete-and-extract-region (point) (line-end-position))))))
7821 ;; If we are at the beginning of the line, insert before it.
7822 ;; Otherwise, after it.
7823 (cond
7824 ((and (bolp) (looking-at "[ \t]*$")))
7825 ((bolp) (save-excursion (insert "\n")))
7826 (t (end-of-line)
7827 (insert "\n")))
7829 ;; Insert the new heading
7830 (insert stars)
7831 (just-one-space)
7832 (insert initial-content)
7833 (unless (and blank (org-previous-line-empty-p))
7834 (org-N-empty-lines-before-current (if blank 1 0)))
7835 ;; Adjust visibility, which may be messed up if we removed
7836 ;; blank lines while previous entry was hidden.
7837 (let ((bol (line-beginning-position)))
7838 (dolist (o (overlays-at (1- bol)))
7839 (when (and (eq (overlay-get o 'invisible) 'outline)
7840 (eq (overlay-end o) bol))
7841 (move-overlay o (overlay-start o) (1- bol)))))
7842 (run-hooks 'org-insert-heading-hook)))))))
7844 (defun org-N-empty-lines-before-current (N)
7845 "Make the number of empty lines before current exactly N.
7846 So this will delete or add empty lines."
7847 (save-excursion
7848 (beginning-of-line)
7849 (let ((p (point)))
7850 (skip-chars-backward " \r\t\n")
7851 (unless (bolp) (forward-line))
7852 (delete-region (point) p))
7853 (when (> N 0) (insert (make-string N ?\n)))))
7855 (defun org-get-heading (&optional no-tags no-todo)
7856 "Return the heading of the current entry, without the stars.
7857 When NO-TAGS is non-nil, don't include tags.
7858 When NO-TODO is non-nil, don't include TODO keywords."
7859 (save-excursion
7860 (org-back-to-heading t)
7861 (cond
7862 ((and no-tags no-todo)
7863 (looking-at org-complex-heading-regexp)
7864 (match-string 4))
7865 (no-tags
7866 (looking-at (concat org-outline-regexp
7867 "\\(.*?\\)"
7868 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7869 (match-string 1))
7870 (no-todo
7871 (looking-at org-todo-line-regexp)
7872 (match-string 3))
7873 (t (looking-at org-heading-regexp)
7874 (match-string 2)))))
7876 (defvar orgstruct-mode) ; defined below
7878 (defun org-heading-components ()
7879 "Return the components of the current heading.
7880 This is a list with the following elements:
7881 - the level as an integer
7882 - the reduced level, different if `org-odd-levels-only' is set.
7883 - the TODO keyword, or nil
7884 - the priority character, like ?A, or nil if no priority is given
7885 - the headline text itself, or the tags string if no headline text
7886 - the tags string, or nil."
7887 (save-excursion
7888 (org-back-to-heading t)
7889 (when (let (case-fold-search)
7890 (looking-at
7891 (if orgstruct-mode
7892 org-heading-regexp
7893 org-complex-heading-regexp)))
7894 (if orgstruct-mode
7895 (list (length (match-string 1))
7896 (org-reduced-level (length (match-string 1)))
7899 (match-string 2)
7900 nil)
7901 (list (length (match-string 1))
7902 (org-reduced-level (length (match-string 1)))
7903 (org-match-string-no-properties 2)
7904 (and (match-end 3) (aref (match-string 3) 2))
7905 (org-match-string-no-properties 4)
7906 (org-match-string-no-properties 5))))))
7908 (defun org-get-entry ()
7909 "Get the entry text, after heading, entire subtree."
7910 (save-excursion
7911 (org-back-to-heading t)
7912 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7914 (defun org-insert-heading-after-current ()
7915 "Insert a new heading with same level as current, after current subtree."
7916 (interactive)
7917 (org-back-to-heading)
7918 (org-insert-heading)
7919 (org-move-subtree-down)
7920 (end-of-line 1))
7922 (defun org-insert-heading-respect-content (&optional invisible-ok)
7923 "Insert heading with `org-insert-heading-respect-content' set to t."
7924 (interactive)
7925 (org-insert-heading '(4) invisible-ok))
7927 (defun org-insert-todo-heading-respect-content (&optional force-state)
7928 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7929 (interactive)
7930 (org-insert-todo-heading force-state '(4)))
7932 (defun org-insert-todo-heading (arg &optional force-heading)
7933 "Insert a new heading with the same level and TODO state as current heading.
7934 If the heading has no TODO state, or if the state is DONE, use the first
7935 state (TODO by default). Also with one prefix arg, force first state. With
7936 two prefix args, force inserting at the end of the parent subtree."
7937 (interactive "P")
7938 (when (or force-heading (not (org-insert-item 'checkbox)))
7939 (org-insert-heading (or (and (equal arg '(16)) '(16))
7940 force-heading))
7941 (save-excursion
7942 (org-back-to-heading)
7943 (outline-previous-heading)
7944 (looking-at org-todo-line-regexp))
7945 (let*
7946 ((new-mark-x
7947 (if (or (equal arg '(4))
7948 (not (match-beginning 2))
7949 (member (match-string 2) org-done-keywords))
7950 (car org-todo-keywords-1)
7951 (match-string 2)))
7952 (new-mark
7954 (run-hook-with-args-until-success
7955 'org-todo-get-default-hook new-mark-x nil)
7956 new-mark-x)))
7957 (beginning-of-line 1)
7958 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7959 (if org-treat-insert-todo-heading-as-state-change
7960 (org-todo new-mark)
7961 (insert new-mark " "))))
7962 (when org-provide-todo-statistics
7963 (org-update-parent-todo-statistics))))
7965 (defun org-insert-subheading (arg)
7966 "Insert a new subheading and demote it.
7967 Works for outline headings and for plain lists alike."
7968 (interactive "P")
7969 (org-insert-heading arg)
7970 (cond
7971 ((org-at-heading-p) (org-do-demote))
7972 ((org-at-item-p) (org-indent-item))))
7974 (defun org-insert-todo-subheading (arg)
7975 "Insert a new subheading with TODO keyword or checkbox and demote it.
7976 Works for outline headings and for plain lists alike."
7977 (interactive "P")
7978 (org-insert-todo-heading arg)
7979 (cond
7980 ((org-at-heading-p) (org-do-demote))
7981 ((org-at-item-p) (org-indent-item))))
7983 ;;; Promotion and Demotion
7985 (defvar org-after-demote-entry-hook nil
7986 "Hook run after an entry has been demoted.
7987 The cursor will be at the beginning of the entry.
7988 When a subtree is being demoted, the hook will be called for each node.")
7990 (defvar org-after-promote-entry-hook nil
7991 "Hook run after an entry has been promoted.
7992 The cursor will be at the beginning of the entry.
7993 When a subtree is being promoted, the hook will be called for each node.")
7995 (defun org-promote-subtree ()
7996 "Promote the entire subtree.
7997 See also `org-promote'."
7998 (interactive)
7999 (save-excursion
8000 (org-with-limited-levels (org-map-tree 'org-promote)))
8001 (org-fix-position-after-promote))
8003 (defun org-demote-subtree ()
8004 "Demote the entire subtree.
8005 See `org-demote' and `org-promote'."
8006 (interactive)
8007 (save-excursion
8008 (org-with-limited-levels (org-map-tree 'org-demote)))
8009 (org-fix-position-after-promote))
8011 (defun org-do-promote ()
8012 "Promote the current heading higher up the tree.
8013 If the region is active in `transient-mark-mode', promote all
8014 headings in the region."
8015 (interactive)
8016 (save-excursion
8017 (if (org-region-active-p)
8018 (org-map-region 'org-promote (region-beginning) (region-end))
8019 (org-promote)))
8020 (org-fix-position-after-promote))
8022 (defun org-do-demote ()
8023 "Demote the current heading lower down the tree.
8024 If the region is active in `transient-mark-mode', demote all
8025 headings in the region."
8026 (interactive)
8027 (save-excursion
8028 (if (org-region-active-p)
8029 (org-map-region 'org-demote (region-beginning) (region-end))
8030 (org-demote)))
8031 (org-fix-position-after-promote))
8033 (defun org-fix-position-after-promote ()
8034 "Fix cursor position and indentation after demoting/promoting."
8035 (let ((pos (point)))
8036 (when (save-excursion
8037 (beginning-of-line 1)
8038 (looking-at org-todo-line-regexp)
8039 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8040 (cond ((eobp) (insert " "))
8041 ((eolp) (insert " "))
8042 ((equal (char-after) ?\ ) (forward-char 1))))))
8044 (defun org-current-level ()
8045 "Return the level of the current entry, or nil if before the first headline.
8046 The level is the number of stars at the beginning of the
8047 headline. Use `org-reduced-level' to remove the effect of
8048 `org-odd-levels'. Unlike to `org-outline-level', this function
8049 ignores inlinetasks."
8050 (let ((level (org-with-limited-levels (org-outline-level))))
8051 (and (> level 0) level)))
8053 (defun org-get-previous-line-level ()
8054 "Return the outline depth of the last headline before the current line.
8055 Returns 0 for the first headline in the buffer, and nil if before the
8056 first headline."
8057 (and (org-current-level)
8058 (or (and (/= (line-beginning-position) (point-min))
8059 (save-excursion (beginning-of-line 0) (org-current-level)))
8060 0)))
8062 (defun org-reduced-level (l)
8063 "Compute the effective level of a heading.
8064 This takes into account the setting of `org-odd-levels-only'."
8065 (cond
8066 ((zerop l) 0)
8067 (org-odd-levels-only (1+ (floor (/ l 2))))
8068 (t l)))
8070 (defun org-level-increment ()
8071 "Return the number of stars that will be added or removed at a
8072 time to headlines when structure editing, based on the value of
8073 `org-odd-levels-only'."
8074 (if org-odd-levels-only 2 1))
8076 (defun org-get-valid-level (level &optional change)
8077 "Rectify a level change under the influence of `org-odd-levels-only'
8078 LEVEL is a current level, CHANGE is by how much the level should be
8079 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8080 even level numbers will become the next higher odd number."
8081 (if org-odd-levels-only
8082 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8083 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8084 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8085 (max 1 (+ level (or change 0)))))
8086 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8088 (defun org-promote ()
8089 "Promote the current heading higher up the tree."
8090 (org-with-wide-buffer
8091 (org-back-to-heading t)
8092 (let* ((after-change-functions (remq 'flyspell-after-change-function
8093 after-change-functions))
8094 (level (save-match-data (funcall outline-level)))
8095 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8096 (diff (abs (- level (length up-head) -1))))
8097 (cond
8098 ((and (= level 1) org-allow-promoting-top-level-subtree)
8099 (replace-match "# " nil t))
8100 ((= level 1)
8101 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8102 (t (replace-match up-head nil t)))
8103 (unless (= level 1)
8104 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8105 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8106 (run-hooks 'org-after-promote-entry-hook))))
8108 (defun org-demote ()
8109 "Demote the current heading lower down the tree."
8110 (org-with-wide-buffer
8111 (org-back-to-heading t)
8112 (let* ((after-change-functions (remq 'flyspell-after-change-function
8113 after-change-functions))
8114 (level (save-match-data (funcall outline-level)))
8115 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8116 (diff (abs (- level (length down-head) -1))))
8117 (replace-match down-head nil t)
8118 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8119 (when org-adapt-indentation (org-fixup-indentation diff))
8120 (run-hooks 'org-after-demote-entry-hook))))
8122 (defun org-cycle-level ()
8123 "Cycle the level of an empty headline through possible states.
8124 This goes first to child, then to parent, level, then up the hierarchy.
8125 After top level, it switches back to sibling level."
8126 (interactive)
8127 (let ((org-adapt-indentation nil))
8128 (when (org-point-at-end-of-empty-headline)
8129 (setq this-command 'org-cycle-level) ; Only needed for caching
8130 (let ((cur-level (org-current-level))
8131 (prev-level (org-get-previous-line-level)))
8132 (cond
8133 ;; If first headline in file, promote to top-level.
8134 ((= prev-level 0)
8135 (loop repeat (/ (- cur-level 1) (org-level-increment))
8136 do (org-do-promote)))
8137 ;; If same level as prev, demote one.
8138 ((= prev-level cur-level)
8139 (org-do-demote))
8140 ;; If parent is top-level, promote to top level if not already.
8141 ((= prev-level 1)
8142 (loop repeat (/ (- cur-level 1) (org-level-increment))
8143 do (org-do-promote)))
8144 ;; If top-level, return to prev-level.
8145 ((= cur-level 1)
8146 (loop repeat (/ (- prev-level 1) (org-level-increment))
8147 do (org-do-demote)))
8148 ;; If less than prev-level, promote one.
8149 ((< cur-level prev-level)
8150 (org-do-promote))
8151 ;; If deeper than prev-level, promote until higher than
8152 ;; prev-level.
8153 ((> cur-level prev-level)
8154 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8155 do (org-do-promote))))
8156 t))))
8158 (defun org-map-tree (fun)
8159 "Call FUN for every heading underneath the current one."
8160 (org-back-to-heading)
8161 (let ((level (funcall outline-level)))
8162 (save-excursion
8163 (funcall fun)
8164 (while (and (progn
8165 (outline-next-heading)
8166 (> (funcall outline-level) level))
8167 (not (eobp)))
8168 (funcall fun)))))
8170 (defun org-map-region (fun beg end)
8171 "Call FUN for every heading between BEG and END."
8172 (let ((org-ignore-region t))
8173 (save-excursion
8174 (setq end (copy-marker end))
8175 (goto-char beg)
8176 (when (and (re-search-forward org-outline-regexp-bol nil t)
8177 (< (point) end))
8178 (funcall fun))
8179 (while (and (progn
8180 (outline-next-heading)
8181 (< (point) end))
8182 (not (eobp)))
8183 (funcall fun)))))
8185 (defun org-fixup-indentation (diff)
8186 "Change the indentation in the current entry by DIFF.
8188 DIFF is an integer. Indentation is done according to the
8189 following rules:
8191 - Planning information and property drawers are always indented
8192 according to the new level of the headline;
8194 - Footnote definitions and their contents are ignored;
8196 - Inlinetasks' boundaries are not shifted;
8198 - Empty lines are ignored;
8200 - Other lines' indentation are shifted by DIFF columns, unless
8201 it would introduce a structural change in the document, in
8202 which case no shifting is done at all.
8204 Assume point is at a heading or an inlinetask beginning."
8205 (org-with-wide-buffer
8206 (narrow-to-region (line-beginning-position)
8207 (save-excursion
8208 (if (org-with-limited-levels (org-at-heading-p))
8209 (org-with-limited-levels (outline-next-heading))
8210 (org-inlinetask-goto-end))
8211 (point)))
8212 (forward-line)
8213 ;; Indent properly planning info and property drawer.
8214 (when (org-looking-at-p org-planning-line-re)
8215 (org-indent-line)
8216 (forward-line))
8217 (when (looking-at org-property-drawer-re)
8218 (goto-char (match-end 0))
8219 (forward-line)
8220 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8221 (catch 'no-shift
8222 (when (zerop diff) (throw 'no-shift nil))
8223 ;; If DIFF is negative, first check if a shift is possible at all
8224 ;; (e.g., it doesn't break structure). This can only happen if
8225 ;; some contents are not properly indented.
8226 (let ((case-fold-search t))
8227 (when (< diff 0)
8228 (let ((diff (- diff))
8229 (forbidden-re (concat org-outline-regexp
8230 "\\|"
8231 (substring org-footnote-definition-re 1))))
8232 (save-excursion
8233 (while (not (eobp))
8234 (cond
8235 ((org-looking-at-p "[ \t]*$") (forward-line))
8236 ((and (org-looking-at-p org-footnote-definition-re)
8237 (let ((e (org-element-at-point)))
8238 (and (eq (org-element-type e) 'footnote-definition)
8239 (goto-char (org-element-property :end e))))))
8240 ((org-looking-at-p org-outline-regexp) (forward-line))
8241 ;; Give up if shifting would move before column 0 or
8242 ;; if it would introduce a headline or a footnote
8243 ;; definition.
8245 (skip-chars-forward " \t")
8246 (let ((ind (current-column)))
8247 (when (or (< ind diff)
8248 (and (= ind diff) (org-looking-at-p forbidden-re)))
8249 (throw 'no-shift nil)))
8250 ;; Ignore contents of example blocks and source
8251 ;; blocks if their indentation is meant to be
8252 ;; preserved. Jump to block's closing line.
8253 (beginning-of-line)
8254 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8255 (let ((e (org-element-at-point)))
8256 (and (memq (org-element-type e)
8257 '(example-block src-block))
8258 (or org-src-preserve-indentation
8259 (org-element-property :preserve-indent e))
8260 (goto-char (org-element-property :end e))
8261 (progn (skip-chars-backward " \r\t\n")
8262 (beginning-of-line)
8263 t))))
8264 (forward-line))))))))
8265 ;; Shift lines but footnote definitions, inlinetasks boundaries
8266 ;; by DIFF. Also skip contents of source or example blocks
8267 ;; when indentation is meant to be preserved.
8268 (while (not (eobp))
8269 (cond
8270 ((and (org-looking-at-p org-footnote-definition-re)
8271 (let ((e (org-element-at-point)))
8272 (and (eq (org-element-type e) 'footnote-definition)
8273 (goto-char (org-element-property :end e))))))
8274 ((org-looking-at-p org-outline-regexp) (forward-line))
8275 ((org-looking-at-p "[ \t]*$") (forward-line))
8277 (org-indent-line-to (+ (org-get-indentation) diff))
8278 (beginning-of-line)
8279 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8280 (let ((e (org-element-at-point)))
8281 (and (memq (org-element-type e)
8282 '(example-block src-block))
8283 (or org-src-preserve-indentation
8284 (org-element-property :preserve-indent e))
8285 (goto-char (org-element-property :end e))
8286 (progn (skip-chars-backward " \r\t\n")
8287 (beginning-of-line)
8288 t))))
8289 (forward-line)))))))))
8291 (defun org-convert-to-odd-levels ()
8292 "Convert an org-mode file with all levels allowed to one with odd levels.
8293 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8294 level 5 etc."
8295 (interactive)
8296 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8297 (let ((outline-level 'org-outline-level)
8298 (org-odd-levels-only nil) n)
8299 (save-excursion
8300 (goto-char (point-min))
8301 (while (re-search-forward "^\\*\\*+ " nil t)
8302 (setq n (- (length (match-string 0)) 2))
8303 (while (>= (setq n (1- n)) 0)
8304 (org-demote))
8305 (end-of-line 1))))))
8307 (defun org-convert-to-oddeven-levels ()
8308 "Convert an org-mode file with only odd levels to one with odd/even levels.
8309 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8310 file contains a section with an even level, conversion would
8311 destroy the structure of the file. An error is signaled in this
8312 case."
8313 (interactive)
8314 (goto-char (point-min))
8315 ;; First check if there are no even levels
8316 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8317 (org-show-set-visibility 'canonical)
8318 (error "Not all levels are odd in this file. Conversion not possible"))
8319 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8320 (let ((outline-regexp org-outline-regexp)
8321 (outline-level 'org-outline-level)
8322 (org-odd-levels-only nil) n)
8323 (save-excursion
8324 (goto-char (point-min))
8325 (while (re-search-forward "^\\*\\*+ " nil t)
8326 (setq n (/ (1- (length (match-string 0))) 2))
8327 (while (>= (setq n (1- n)) 0)
8328 (org-promote))
8329 (end-of-line 1))))))
8331 (defun org-tr-level (n)
8332 "Make N odd if required."
8333 (if org-odd-levels-only (1+ (/ n 2)) n))
8335 ;;; Vertical tree motion, cutting and pasting of subtrees
8337 (defun org-move-subtree-up (&optional arg)
8338 "Move the current subtree up past ARG headlines of the same level."
8339 (interactive "p")
8340 (org-move-subtree-down (- (prefix-numeric-value arg))))
8342 (defun org-move-subtree-down (&optional arg)
8343 "Move the current subtree down past ARG headlines of the same level."
8344 (interactive "p")
8345 (setq arg (prefix-numeric-value arg))
8346 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8347 'org-get-last-sibling))
8348 (ins-point (make-marker))
8349 (cnt (abs arg))
8350 (col (current-column))
8351 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8352 ;; Select the tree
8353 (org-back-to-heading)
8354 (setq beg0 (point))
8355 (save-excursion
8356 (setq ne-beg (org-back-over-empty-lines))
8357 (setq beg (point)))
8358 (save-match-data
8359 (save-excursion (outline-end-of-heading)
8360 (setq folded (outline-invisible-p)))
8361 (progn (org-end-of-subtree nil t)
8362 (unless (eobp) (backward-char))))
8363 (outline-next-heading)
8364 (setq ne-end (org-back-over-empty-lines))
8365 (setq end (point))
8366 (goto-char beg0)
8367 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8368 ;; include less whitespace
8369 (save-excursion
8370 (goto-char beg)
8371 (forward-line (- ne-beg ne-end))
8372 (setq beg (point))))
8373 ;; Find insertion point, with error handling
8374 (while (> cnt 0)
8375 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8376 (progn (goto-char beg0)
8377 (user-error "Cannot move past superior level or buffer limit")))
8378 (setq cnt (1- cnt)))
8379 (when (> arg 0)
8380 ;; Moving forward - still need to move over subtree
8381 (org-end-of-subtree t t)
8382 (save-excursion
8383 (org-back-over-empty-lines)
8384 (or (bolp) (newline))))
8385 (setq ne-ins (org-back-over-empty-lines))
8386 (move-marker ins-point (point))
8387 (setq txt (buffer-substring beg end))
8388 (org-save-markers-in-region beg end)
8389 (delete-region beg end)
8390 (org-remove-empty-overlays-at beg)
8391 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8392 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8393 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8394 (let ((bbb (point)))
8395 (insert-before-markers txt)
8396 (org-reinstall-markers-in-region bbb)
8397 (move-marker ins-point bbb))
8398 (or (bolp) (insert "\n"))
8399 (setq ins-end (point))
8400 (goto-char ins-point)
8401 (org-skip-whitespace)
8402 (when (and (< arg 0)
8403 (org-first-sibling-p)
8404 (> ne-ins ne-beg))
8405 ;; Move whitespace back to beginning
8406 (save-excursion
8407 (goto-char ins-end)
8408 (let ((kill-whole-line t))
8409 (kill-line (- ne-ins ne-beg)) (point)))
8410 (insert (make-string (- ne-ins ne-beg) ?\n)))
8411 (move-marker ins-point nil)
8412 (if folded
8413 (outline-hide-subtree)
8414 (org-show-entry)
8415 (org-show-children)
8416 (org-cycle-hide-drawers 'children))
8417 (org-clean-visibility-after-subtree-move)
8418 ;; move back to the initial column we were at
8419 (move-to-column col)))
8421 (defvar org-subtree-clip ""
8422 "Clipboard for cut and paste of subtrees.
8423 This is actually only a copy of the kill, because we use the normal kill
8424 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8426 (defvar org-subtree-clip-folded nil
8427 "Was the last copied subtree folded?
8428 This is used to fold the tree back after pasting.")
8430 (defun org-cut-subtree (&optional n)
8431 "Cut the current subtree into the clipboard.
8432 With prefix arg N, cut this many sequential subtrees.
8433 This is a short-hand for marking the subtree and then cutting it."
8434 (interactive "p")
8435 (org-copy-subtree n 'cut))
8437 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8438 "Copy the current subtree it in the clipboard.
8439 With prefix arg N, copy this many sequential subtrees.
8440 This is a short-hand for marking the subtree and then copying it.
8441 If CUT is non-nil, actually cut the subtree.
8442 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8443 of some markers in the region, even if CUT is non-nil. This is
8444 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8445 (interactive "p")
8446 (let (beg end folded (beg0 (point)))
8447 (if (org-called-interactively-p 'any)
8448 (org-back-to-heading nil) ; take what looks like a subtree
8449 (org-back-to-heading t)) ; take what is really there
8450 (setq beg (point))
8451 (skip-chars-forward " \t\r\n")
8452 (save-match-data
8453 (if nosubtrees
8454 (outline-next-heading)
8455 (save-excursion (outline-end-of-heading)
8456 (setq folded (outline-invisible-p)))
8457 (ignore-errors (org-forward-heading-same-level (1- n) t))
8458 (org-end-of-subtree t t)))
8459 ;; Include the end of an inlinetask
8460 (when (and (featurep 'org-inlinetask)
8461 (looking-at-p (concat (org-inlinetask-outline-regexp)
8462 "END[ \t]*$")))
8463 (end-of-line))
8464 (setq end (point))
8465 (goto-char beg0)
8466 (when (> end beg)
8467 (setq org-subtree-clip-folded folded)
8468 (when (or cut force-store-markers)
8469 (org-save-markers-in-region beg end))
8470 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8471 (setq org-subtree-clip (current-kill 0))
8472 (message "%s: Subtree(s) with %d characters"
8473 (if cut "Cut" "Copied")
8474 (length org-subtree-clip)))))
8476 (defun org-paste-subtree (&optional level tree for-yank remove)
8477 "Paste the clipboard as a subtree, with modification of headline level.
8478 The entire subtree is promoted or demoted in order to match a new headline
8479 level.
8481 If the cursor is at the beginning of a headline, the same level as
8482 that headline is used to paste the tree.
8484 If not, the new level is derived from the *visible* headings
8485 before and after the insertion point, and taken to be the inferior headline
8486 level of the two. So if the previous visible heading is level 3 and the
8487 next is level 4 (or vice versa), level 4 will be used for insertion.
8488 This makes sure that the subtree remains an independent subtree and does
8489 not swallow low level entries.
8491 You can also force a different level, either by using a numeric prefix
8492 argument, or by inserting the heading marker by hand. For example, if the
8493 cursor is after \"*****\", then the tree will be shifted to level 5.
8495 If optional TREE is given, use this text instead of the kill ring.
8497 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8498 move back over whitespace before inserting, and move point to the end of
8499 the inserted text when done.
8501 When REMOVE is non-nil, remove the subtree from the clipboard."
8502 (interactive "P")
8503 (setq tree (or tree (and kill-ring (current-kill 0))))
8504 (unless (org-kill-is-subtree-p tree)
8505 (user-error "%s"
8506 (substitute-command-keys
8507 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8508 (org-with-limited-levels
8509 (let* ((visp (not (outline-invisible-p)))
8510 (txt tree)
8511 (^re_ "\\(\\*+\\)[ \t]*")
8512 (old-level (if (string-match org-outline-regexp-bol txt)
8513 (- (match-end 0) (match-beginning 0) 1)
8514 -1))
8515 (force-level (cond (level (prefix-numeric-value level))
8516 ((and (looking-at "[ \t]*$")
8517 (string-match
8518 "^\\*+$" (buffer-substring
8519 (point-at-bol) (point))))
8520 (- (match-end 0) (match-beginning 0)))
8521 ((and (bolp)
8522 (looking-at org-outline-regexp))
8523 (- (match-end 0) (point) 1))))
8524 (previous-level (save-excursion
8525 (condition-case nil
8526 (progn
8527 (outline-previous-visible-heading 1)
8528 (if (looking-at ^re_)
8529 (- (match-end 0) (match-beginning 0) 1)
8531 (error 1))))
8532 (next-level (save-excursion
8533 (condition-case nil
8534 (progn
8535 (or (looking-at org-outline-regexp)
8536 (outline-next-visible-heading 1))
8537 (if (looking-at ^re_)
8538 (- (match-end 0) (match-beginning 0) 1)
8540 (error 1))))
8541 (new-level (or force-level (max previous-level next-level)))
8542 (shift (if (or (= old-level -1)
8543 (= new-level -1)
8544 (= old-level new-level))
8546 (- new-level old-level)))
8547 (delta (if (> shift 0) -1 1))
8548 (func (if (> shift 0) 'org-demote 'org-promote))
8549 (org-odd-levels-only nil)
8550 beg end newend)
8551 ;; Remove the forced level indicator
8552 (when force-level
8553 (delete-region (point-at-bol) (point)))
8554 ;; Paste
8555 (beginning-of-line (if (bolp) 1 2))
8556 (setq beg (point))
8557 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8558 (insert-before-markers txt)
8559 (unless (string-match "\n\\'" txt) (insert "\n"))
8560 (setq newend (point))
8561 (org-reinstall-markers-in-region beg)
8562 (setq end (point))
8563 (goto-char beg)
8564 (skip-chars-forward " \t\n\r")
8565 (setq beg (point))
8566 (when (and (outline-invisible-p) visp)
8567 (save-excursion (outline-show-heading)))
8568 ;; Shift if necessary
8569 (unless (= shift 0)
8570 (save-restriction
8571 (narrow-to-region beg end)
8572 (while (not (= shift 0))
8573 (org-map-region func (point-min) (point-max))
8574 (setq shift (+ delta shift)))
8575 (goto-char (point-min))
8576 (setq newend (point-max))))
8577 (when (or (org-called-interactively-p 'interactive) for-yank)
8578 (message "Clipboard pasted as level %d subtree" new-level))
8579 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8580 kill-ring
8581 (eq org-subtree-clip (current-kill 0))
8582 org-subtree-clip-folded)
8583 ;; The tree was folded before it was killed/copied
8584 (outline-hide-subtree))
8585 (and for-yank (goto-char newend))
8586 (and remove (setq kill-ring (cdr kill-ring))))))
8588 (defun org-kill-is-subtree-p (&optional txt)
8589 "Check if the current kill is an outline subtree, or a set of trees.
8590 Returns nil if kill does not start with a headline, or if the first
8591 headline level is not the largest headline level in the tree.
8592 So this will actually accept several entries of equal levels as well,
8593 which is OK for `org-paste-subtree'.
8594 If optional TXT is given, check this string instead of the current kill."
8595 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8596 (re (org-get-limited-outline-regexp))
8597 (^re (concat "^" re))
8598 (start-level (and kill
8599 (string-match
8600 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8601 kill)
8602 (- (match-end 2) (match-beginning 2) 1)))
8603 (start (1+ (or (match-beginning 2) -1))))
8604 (if (not start-level)
8605 (progn
8606 nil) ;; does not even start with a heading
8607 (catch 'exit
8608 (while (setq start (string-match ^re kill (1+ start)))
8609 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8610 (throw 'exit nil)))
8611 t))))
8613 (defvar org-markers-to-move nil
8614 "Markers that should be moved with a cut-and-paste operation.
8615 Those markers are stored together with their positions relative to
8616 the start of the region.")
8618 (defun org-save-markers-in-region (beg end)
8619 "Check markers in region.
8620 If these markers are between BEG and END, record their position relative
8621 to BEG, so that after moving the block of text, we can put the markers back
8622 into place.
8623 This function gets called just before an entry or tree gets cut from the
8624 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8625 called immediately, to move the markers with the entries."
8626 (setq org-markers-to-move nil)
8627 (when (featurep 'org-clock)
8628 (org-clock-save-markers-for-cut-and-paste beg end))
8629 (when (featurep 'org-agenda)
8630 (org-agenda-save-markers-for-cut-and-paste beg end)))
8632 (defun org-check-and-save-marker (marker beg end)
8633 "Check if MARKER is between BEG and END.
8634 If yes, remember the marker and the distance to BEG."
8635 (when (and (marker-buffer marker)
8636 (equal (marker-buffer marker) (current-buffer))
8637 (>= marker beg) (< marker end))
8638 (push (cons marker (- marker beg)) org-markers-to-move)))
8640 (defun org-reinstall-markers-in-region (beg)
8641 "Move all remembered markers to their position relative to BEG."
8642 (dolist (x org-markers-to-move)
8643 (move-marker (car x) (+ beg (cdr x))))
8644 (setq org-markers-to-move nil))
8646 (defun org-narrow-to-subtree ()
8647 "Narrow buffer to the current subtree."
8648 (interactive)
8649 (save-excursion
8650 (save-match-data
8651 (org-with-limited-levels
8652 (narrow-to-region
8653 (progn (org-back-to-heading t) (point))
8654 (progn (org-end-of-subtree t t)
8655 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8656 (point)))))))
8658 (defun org-narrow-to-block ()
8659 "Narrow buffer to the current block."
8660 (interactive)
8661 (let* ((case-fold-search t)
8662 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8663 "^[ \t]*#\\+end_.*")))
8664 (if blockp
8665 (narrow-to-region (car blockp) (cdr blockp))
8666 (user-error "Not in a block"))))
8668 (defun org-clone-subtree-with-time-shift (n &optional shift)
8669 "Clone the task (subtree) at point N times.
8670 The clones will be inserted as siblings.
8672 In interactive use, the user will be prompted for the number of
8673 clones to be produced. If the entry has a timestamp, the user
8674 will also be prompted for a time shift, which may be a repeater
8675 as used in time stamps, for example `+3d'. To disable this,
8676 you can call the function with a universal prefix argument.
8678 When a valid repeater is given and the entry contains any time
8679 stamps, the clones will become a sequence in time, with time
8680 stamps in the subtree shifted for each clone produced. If SHIFT
8681 is nil or the empty string, time stamps will be left alone. The
8682 ID property of the original subtree is removed.
8684 If the original subtree did contain time stamps with a repeater,
8685 the following will happen:
8686 - the repeater will be removed in each clone
8687 - an additional clone will be produced, with the current, unshifted
8688 date(s) in the entry.
8689 - the original entry will be placed *after* all the clones, with
8690 repeater intact.
8691 - the start days in the repeater in the original entry will be shifted
8692 to past the last clone.
8693 In this way you can spell out a number of instances of a repeating task,
8694 and still retain the repeater to cover future instances of the task.
8696 As described above, N+1 clones are produced when the original
8697 subtree has a repeater. Setting N to 0, then, can be used to
8698 remove the repeater from a subtree and create a shifted clone
8699 with the original repeater."
8700 (interactive "nNumber of clones to produce: ")
8701 (let ((shift
8702 (or shift
8703 (if (and (not (equal current-prefix-arg '(4)))
8704 (save-excursion
8705 (re-search-forward org-ts-regexp-both
8706 (save-excursion
8707 (org-end-of-subtree t)
8708 (point)) t)))
8709 (read-from-minibuffer
8710 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8711 ""))) ;; No time shift
8712 (n-no-remove -1)
8713 (drawer-re org-drawer-regexp)
8714 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8715 beg end template task idprop
8716 shift-n shift-what doshift nmin nmax)
8717 (unless (wholenump n)
8718 (user-error "Invalid number of replications %s" n))
8719 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8720 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8721 shift)))
8722 (user-error "Invalid shift specification %s" shift))
8723 (when doshift
8724 (setq shift-n (string-to-number (match-string 1 shift))
8725 shift-what (cdr (assoc (match-string 2 shift)
8726 '(("d" . day) ("w" . week)
8727 ("m" . month) ("y" . year))))))
8728 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8729 (setq nmin 1 nmax n)
8730 (org-back-to-heading t)
8731 (setq beg (point))
8732 (setq idprop (org-entry-get nil "ID"))
8733 (org-end-of-subtree t t)
8734 (or (bolp) (insert "\n"))
8735 (setq end (point))
8736 (setq template (buffer-substring beg end))
8737 (when (and doshift
8738 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8739 (delete-region beg end)
8740 (setq end beg)
8741 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8742 (goto-char end)
8743 (loop for n from nmin to nmax do
8744 ;; prepare clone
8745 (with-temp-buffer
8746 (insert template)
8747 (org-mode)
8748 (goto-char (point-min))
8749 (org-show-subtree)
8750 (and idprop (if org-clone-delete-id
8751 (org-entry-delete nil "ID")
8752 (org-id-get-create t)))
8753 (unless (= n 0)
8754 (while (re-search-forward org-clock-re nil t)
8755 (kill-whole-line))
8756 (goto-char (point-min))
8757 (while (re-search-forward drawer-re nil t)
8758 (org-remove-empty-drawer-at (point))))
8759 (goto-char (point-min))
8760 (when doshift
8761 (while (re-search-forward org-ts-regexp-both nil t)
8762 (org-timestamp-change (* n shift-n) shift-what))
8763 (unless (= n n-no-remove)
8764 (goto-char (point-min))
8765 (while (re-search-forward org-ts-regexp nil t)
8766 (save-excursion
8767 (goto-char (match-beginning 0))
8768 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8769 (delete-region (match-beginning 1) (match-end 1)))))))
8770 (setq task (buffer-string)))
8771 (insert task))
8772 (goto-char beg)))
8774 ;;; Outline Sorting
8776 (defun org-sort (with-case)
8777 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8778 Optional argument WITH-CASE means sort case-sensitively."
8779 (interactive "P")
8780 (cond
8781 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8782 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8784 (org-call-with-arg 'org-sort-entries with-case))))
8786 (defun org-sort-remove-invisible (s)
8787 "Remove invisible links from string S."
8788 (remove-text-properties 0 (length s) org-rm-props s)
8789 (while (string-match org-bracket-link-regexp s)
8790 (setq s (replace-match (if (match-end 2)
8791 (match-string 3 s)
8792 (match-string 1 s))
8793 t t s)))
8794 (let ((st (format " %s " s)))
8795 (while (string-match org-emph-re st)
8796 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8797 (setq s (substring st 1 -1)))
8800 (defvar org-priority-regexp) ; defined later in the file
8802 (defvar org-after-sorting-entries-or-items-hook nil
8803 "Hook that is run after a bunch of entries or items have been sorted.
8804 When children are sorted, the cursor is in the parent line when this
8805 hook gets called. When a region or a plain list is sorted, the cursor
8806 will be in the first entry of the sorted region/list.")
8808 (defun org-sort-entries
8809 (&optional with-case sorting-type getkey-func compare-func property)
8810 "Sort entries on a certain level of an outline tree.
8811 If there is an active region, the entries in the region are sorted.
8812 Else, if the cursor is before the first entry, sort the top-level items.
8813 Else, the children of the entry at point are sorted.
8815 Sorting can be alphabetically, numerically, by date/time as given by
8816 a time stamp, by a property, by priority order, or by a custom function.
8818 The command prompts for the sorting type unless it has been given to the
8819 function through the SORTING-TYPE argument, which needs to be a character,
8820 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8821 the precise meaning of each character:
8823 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8824 c By creation time, which is assumed to be the first inactive time stamp
8825 at the beginning of a line.
8826 d By deadline date/time.
8827 k By clocking time.
8828 n Numerically, by converting the beginning of the entry/item to a number.
8829 o By order of TODO keywords.
8830 p By priority according to the cookie.
8831 r By the value of a property.
8832 s By scheduled date/time.
8833 t By date/time, either the first active time stamp in the entry, or, if
8834 none exist, by the first inactive one.
8836 Capital letters will reverse the sort order.
8838 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8839 called with point at the beginning of the record. It must return either
8840 a string or a number that should serve as the sorting key for that record.
8842 Comparing entries ignores case by default. However, with an optional argument
8843 WITH-CASE, the sorting considers case as well.
8845 Sorting is done against the visible part of the headlines, it ignores hidden
8846 links.
8848 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8849 (interactive "P")
8850 (let ((case-func (if with-case 'identity 'downcase))
8851 (cmstr
8852 ;; The clock marker is lost when using `sort-subr', let's
8853 ;; store the clocking string.
8854 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8855 (save-excursion
8856 (goto-char org-clock-marker)
8857 (buffer-substring-no-properties (line-beginning-position)
8858 (point)))))
8859 start beg end stars re re2
8860 txt what tmp)
8861 ;; Find beginning and end of region to sort
8862 (cond
8863 ((org-region-active-p)
8864 ;; we will sort the region
8865 (setq end (region-end)
8866 what "region")
8867 (goto-char (region-beginning))
8868 (unless (org-at-heading-p) (outline-next-heading))
8869 (setq start (point)))
8870 ((or (org-at-heading-p)
8871 (ignore-errors (progn (org-back-to-heading) t)))
8872 ;; we will sort the children of the current headline
8873 (org-back-to-heading)
8874 (setq start (point)
8875 end (progn (org-end-of-subtree t t)
8876 (or (bolp) (insert "\n"))
8877 (when (>= (org-back-over-empty-lines) 1)
8878 (forward-line 1))
8879 (point))
8880 what "children")
8881 (goto-char start)
8882 (outline-show-subtree)
8883 (outline-next-heading))
8885 ;; we will sort the top-level entries in this file
8886 (goto-char (point-min))
8887 (or (org-at-heading-p) (outline-next-heading))
8888 (setq start (point))
8889 (goto-char (point-max))
8890 (beginning-of-line 1)
8891 (when (looking-at ".*?\\S-")
8892 ;; File ends in a non-white line
8893 (end-of-line 1)
8894 (insert "\n"))
8895 (setq end (point-max))
8896 (setq what "top-level")
8897 (goto-char start)
8898 (outline-show-all)))
8900 (setq beg (point))
8901 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8903 (looking-at "\\(\\*+\\)")
8904 (setq stars (match-string 1)
8905 re (concat "^" (regexp-quote stars) " +")
8906 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8907 txt (buffer-substring beg end))
8908 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8909 (when (and (not (equal stars "*")) (string-match re2 txt))
8910 (user-error "Region to sort contains a level above the first entry"))
8912 (unless sorting-type
8913 (message
8914 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8915 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8916 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8917 what)
8918 (setq sorting-type (read-char-exclusive))
8920 (unless getkey-func
8921 (and (= (downcase sorting-type) ?f)
8922 (setq getkey-func
8923 (completing-read "Sort using function: "
8924 obarray 'fboundp t nil nil))
8925 (setq getkey-func (intern getkey-func))))
8927 (and (= (downcase sorting-type) ?r)
8928 (not property)
8929 (setq property
8930 (completing-read "Property: "
8931 (mapcar #'list (org-buffer-property-keys t))
8932 nil t))))
8934 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8935 (message "Sorting entries...")
8937 (save-restriction
8938 (narrow-to-region start end)
8939 (let ((dcst (downcase sorting-type))
8940 (case-fold-search nil)
8941 (now (current-time)))
8942 (sort-subr
8943 (/= dcst sorting-type)
8944 ;; This function moves to the beginning character of the "record" to
8945 ;; be sorted.
8946 (lambda nil
8947 (if (re-search-forward re nil t)
8948 (goto-char (match-beginning 0))
8949 (goto-char (point-max))))
8950 ;; This function moves to the last character of the "record" being
8951 ;; sorted.
8952 (lambda nil
8953 (save-match-data
8954 (condition-case nil
8955 (outline-forward-same-level 1)
8956 (error
8957 (goto-char (point-max))))))
8958 ;; This function returns the value that gets sorted against.
8959 (lambda nil
8960 (cond
8961 ((= dcst ?n)
8962 (if (looking-at org-complex-heading-regexp)
8963 (string-to-number (org-sort-remove-invisible (match-string 4)))
8964 nil))
8965 ((= dcst ?a)
8966 (if (looking-at org-complex-heading-regexp)
8967 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8968 nil))
8969 ((= dcst ?k)
8970 (or (get-text-property (point) :org-clock-minutes) 0))
8971 ((= dcst ?t)
8972 (let ((end (save-excursion (outline-next-heading) (point))))
8973 (if (or (re-search-forward org-ts-regexp end t)
8974 (re-search-forward org-ts-regexp-both end t))
8975 (org-time-string-to-seconds (match-string 0))
8976 (org-float-time now))))
8977 ((= dcst ?c)
8978 (let ((end (save-excursion (outline-next-heading) (point))))
8979 (if (re-search-forward
8980 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8981 end t)
8982 (org-time-string-to-seconds (match-string 0))
8983 (org-float-time now))))
8984 ((= dcst ?s)
8985 (let ((end (save-excursion (outline-next-heading) (point))))
8986 (if (re-search-forward org-scheduled-time-regexp end t)
8987 (org-time-string-to-seconds (match-string 1))
8988 (org-float-time now))))
8989 ((= dcst ?d)
8990 (let ((end (save-excursion (outline-next-heading) (point))))
8991 (if (re-search-forward org-deadline-time-regexp end t)
8992 (org-time-string-to-seconds (match-string 1))
8993 (org-float-time now))))
8994 ((= dcst ?p)
8995 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8996 (string-to-char (match-string 2))
8997 org-default-priority))
8998 ((= dcst ?r)
8999 (or (org-entry-get nil property) ""))
9000 ((= dcst ?o)
9001 (when (looking-at org-complex-heading-regexp)
9002 (let* ((m (match-string 2))
9003 (s (if (member m org-done-keywords) '- '+)))
9004 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9005 ((= dcst ?f)
9006 (if getkey-func
9007 (progn
9008 (setq tmp (funcall getkey-func))
9009 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9010 tmp)
9011 (error "Invalid key function `%s'" getkey-func)))
9012 (t (error "Invalid sorting type `%c'" sorting-type))))
9014 (cond
9015 ((= dcst ?a) 'string<)
9016 ((= dcst ?f) compare-func)
9017 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9018 (run-hooks 'org-after-sorting-entries-or-items-hook)
9019 ;; Reset the clock marker if needed
9020 (when cmstr
9021 (save-excursion
9022 (goto-char start)
9023 (search-forward cmstr nil t)
9024 (move-marker org-clock-marker (point))))
9025 (message "Sorting entries...done")))
9027 ;;; The orgstruct minor mode
9029 ;; Define a minor mode which can be used in other modes in order to
9030 ;; integrate the org-mode structure editing commands.
9032 ;; This is really a hack, because the org-mode structure commands use
9033 ;; keys which normally belong to the major mode. Here is how it
9034 ;; works: The minor mode defines all the keys necessary to operate the
9035 ;; structure commands, but wraps the commands into a function which
9036 ;; tests if the cursor is currently at a headline or a plain list
9037 ;; item. If that is the case, the structure command is used,
9038 ;; temporarily setting many Org-mode variables like regular
9039 ;; expressions for filling etc. However, when any of those keys is
9040 ;; used at a different location, function uses `key-binding' to look
9041 ;; up if the key has an associated command in another currently active
9042 ;; keymap (minor modes, major mode, global), and executes that
9043 ;; command. There might be problems if any of the keys is otherwise
9044 ;; used as a prefix key.
9046 (defcustom orgstruct-heading-prefix-regexp ""
9047 "Regexp that matches the custom prefix of Org headlines in
9048 orgstruct(++)-mode."
9049 :group 'org
9050 :version "24.4"
9051 :package-version '(Org . "8.3")
9052 :type 'regexp)
9053 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9055 (defcustom orgstruct-setup-hook nil
9056 "Hook run after orgstruct-mode-map is filled."
9057 :group 'org
9058 :version "24.4"
9059 :package-version '(Org . "8.0")
9060 :type 'hook)
9062 (defvar orgstruct-initialized nil)
9064 (defvar org-local-vars nil
9065 "List of local variables, for use by `orgstruct-mode'.")
9067 ;;;###autoload
9068 (define-minor-mode orgstruct-mode
9069 "Toggle the minor mode `orgstruct-mode'.
9070 This mode is for using Org-mode structure commands in other
9071 modes. The following keys behave as if Org-mode were active, if
9072 the cursor is on a headline, or on a plain list item (both as
9073 defined by Org-mode)."
9074 nil " OrgStruct" (make-sparse-keymap)
9075 (funcall (if orgstruct-mode
9076 'add-to-invisibility-spec
9077 'remove-from-invisibility-spec)
9078 '(outline . t))
9079 (when orgstruct-mode
9080 (org-load-modules-maybe)
9081 (unless orgstruct-initialized
9082 (orgstruct-setup)
9083 (setq orgstruct-initialized t))))
9085 ;;;###autoload
9086 (defun turn-on-orgstruct ()
9087 "Unconditionally turn on `orgstruct-mode'."
9088 (orgstruct-mode 1))
9090 (defvar-local orgstruct-is-++ nil
9091 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9092 (defvar-local org-fb-vars nil)
9093 (defun orgstruct++-mode (&optional arg)
9094 "Toggle `orgstruct-mode', the enhanced version of it.
9095 In addition to setting orgstruct-mode, this also exports all
9096 indentation and autofilling variables from org-mode into the
9097 buffer. It will also recognize item context in multiline items."
9098 (interactive "P")
9099 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9100 (if (< arg 1)
9101 (progn (orgstruct-mode -1)
9102 (dolist (v org-fb-vars)
9103 (set (make-local-variable (car v))
9104 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v)))))
9105 (orgstruct-mode 1)
9106 (setq org-fb-vars nil)
9107 (unless org-local-vars
9108 (setq org-local-vars (org-get-local-variables)))
9109 (let (var val)
9110 (dolist (x org-local-vars)
9111 (when (string-match
9112 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9113 \\|fill-prefix\\|indent-\\)"
9114 (symbol-name (car x)))
9115 (setq var (car x) val (nth 1 x))
9116 (push (list var `(quote ,(eval var))) org-fb-vars)
9117 (set (make-local-variable var)
9118 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9119 (setq-local orgstruct-is-++ t))))
9121 ;;;###autoload
9122 (defun turn-on-orgstruct++ ()
9123 "Unconditionally turn on `orgstruct++-mode'."
9124 (orgstruct++-mode 1))
9126 (defun orgstruct-error ()
9127 "Error when there is no default binding for a structure key."
9128 (interactive)
9129 (funcall (if (fboundp 'user-error)
9130 'user-error
9131 'error)
9132 "This key has no function outside structure elements"))
9134 (defun orgstruct-setup ()
9135 "Setup orgstruct keymap."
9136 (dolist (cell '((org-demote . t)
9137 (org-metaleft . t)
9138 (org-metaright . t)
9139 (org-promote . t)
9140 (org-shiftmetaleft . t)
9141 (org-shiftmetaright . t)
9142 org-backward-element
9143 org-backward-heading-same-level
9144 org-ctrl-c-ret
9145 org-ctrl-c-minus
9146 org-ctrl-c-star
9147 org-cycle
9148 org-forward-heading-same-level
9149 org-insert-heading
9150 org-insert-heading-respect-content
9151 org-kill-note-or-show-branches
9152 org-mark-subtree
9153 org-meta-return
9154 org-metadown
9155 org-metaup
9156 org-narrow-to-subtree
9157 org-promote-subtree
9158 org-reveal
9159 org-shiftdown
9160 org-shiftleft
9161 org-shiftmetadown
9162 org-shiftmetaup
9163 org-shiftright
9164 org-shifttab
9165 org-shifttab
9166 org-shiftup
9167 org-show-children
9168 org-show-subtree
9169 org-sort
9170 org-up-element
9171 outline-demote
9172 outline-next-visible-heading
9173 outline-previous-visible-heading
9174 outline-promote
9175 outline-up-heading))
9176 (let ((f (or (car-safe cell) cell))
9177 (disable-when-heading-prefix (cdr-safe cell)))
9178 (when (fboundp f)
9179 (let ((new-bindings))
9180 (dolist (binding (nconc (where-is-internal f org-mode-map)
9181 (where-is-internal f outline-mode-map)))
9182 (push binding new-bindings)
9183 ;; TODO use local-function-key-map
9184 (dolist (rep '(("<tab>" . "TAB")
9185 ("<return>" . "RET")
9186 ("<escape>" . "ESC")
9187 ("<delete>" . "DEL")))
9188 (setq binding (read-kbd-macro
9189 (let ((case-fold-search))
9190 (replace-regexp-in-string
9191 (regexp-quote (cdr rep))
9192 (car rep)
9193 (key-description binding)))))
9194 (pushnew binding new-bindings :test 'equal)))
9195 (dolist (binding new-bindings)
9196 (let ((key (lookup-key orgstruct-mode-map binding)))
9197 (when (or (not key) (numberp key))
9198 (ignore-errors
9199 (org-defkey orgstruct-mode-map
9200 binding
9201 (orgstruct-make-binding
9202 f binding disable-when-heading-prefix))))))))))
9203 (run-hooks 'orgstruct-setup-hook))
9205 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9206 "Create a function for binding in the structure minor mode.
9207 FUN is the command to call inside a table. KEY is the key that
9208 should be checked in for a command to execute outside of tables.
9209 Non-nil `disable-when-heading-prefix' means to disable the command
9210 if `orgstruct-heading-prefix-regexp' is not empty."
9211 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9212 (let ((nname name)
9213 (i 0))
9214 (while (fboundp (intern nname))
9215 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9216 (setq name (intern nname)))
9217 (eval
9218 (let ((bindings '((org-heading-regexp
9219 (concat "^"
9220 orgstruct-heading-prefix-regexp
9221 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9222 (org-outline-regexp
9223 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9224 (org-outline-regexp-bol
9225 (concat "^" org-outline-regexp))
9226 (outline-regexp org-outline-regexp)
9227 (outline-heading-end-regexp "\n")
9228 (outline-level 'org-outline-level)
9229 (outline-heading-alist))))
9230 `(defun ,name (arg)
9231 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9232 "Outside of structure, run the binding of `"
9233 (key-description key) "'."
9234 (when disable-when-heading-prefix
9235 (concat
9236 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9237 "back to the default binding due to limitations of Org's implementation of\n"
9238 "`" (symbol-name fun) "'.")))
9239 (interactive "p")
9240 (let* ((disable
9241 ,(and disable-when-heading-prefix
9242 '(not (string= orgstruct-heading-prefix-regexp ""))))
9243 (fallback
9244 (or disable
9245 (not
9246 (let* ,bindings
9247 (org-context-p 'headline 'item
9248 ,(when (memq fun
9249 '(org-insert-heading
9250 org-insert-heading-respect-content
9251 org-meta-return))
9252 '(when orgstruct-is-++
9253 'item-body))))))))
9254 (if fallback
9255 (let* ((orgstruct-mode)
9256 (binding
9257 (let ((key ,key))
9258 (catch 'exit
9259 (dolist
9260 (rep
9261 '(nil
9262 ("<\\([^>]*\\)tab>" . "\\1TAB")
9263 ("<\\([^>]*\\)return>" . "\\1RET")
9264 ("<\\([^>]*\\)escape>" . "\\1ESC")
9265 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9266 nil)
9267 (when rep
9268 (setq key (read-kbd-macro
9269 (let ((case-fold-search))
9270 (replace-regexp-in-string
9271 (car rep)
9272 (cdr rep)
9273 (key-description key))))))
9274 (when (key-binding key)
9275 (throw 'exit (key-binding key))))))))
9276 (if (keymapp binding)
9277 (org-set-transient-map binding)
9278 (let ((func (or binding
9279 (unless disable
9280 'orgstruct-error))))
9281 (when func
9282 (call-interactively func)))))
9283 (org-run-like-in-org-mode
9284 (lambda ()
9285 (interactive)
9286 (let* ,bindings
9287 (call-interactively ',fun)))))))))
9288 name))
9290 (defun org-contextualize-keys (alist contexts)
9291 "Return valid elements in ALIST depending on CONTEXTS.
9293 `org-agenda-custom-commands' or `org-capture-templates' are the
9294 values used for ALIST, and `org-agenda-custom-commands-contexts'
9295 or `org-capture-templates-contexts' are the associated contexts
9296 definitions."
9297 (let ((contexts
9298 ;; normalize contexts
9299 (mapcar
9300 (lambda(c) (cond ((listp (cadr c))
9301 (list (car c) (car c) (cadr c)))
9302 ((string= "" (cadr c))
9303 (list (car c) (car c) (caddr c)))
9304 (t c)))
9305 contexts))
9306 (a alist) r s)
9307 ;; loop over all commands or templates
9308 (dolist (c a)
9309 (let (vrules repl)
9310 (cond
9311 ((not (assoc (car c) contexts))
9312 (push c r))
9313 ((and (assoc (car c) contexts)
9314 (setq vrules (org-contextualize-validate-key
9315 (car c) contexts)))
9316 (mapc (lambda (vr)
9317 (unless (equal (car vr) (cadr vr))
9318 (setq repl vr)))
9319 vrules)
9320 (if (not repl) (push c r)
9321 (push (cadr repl) s)
9322 (push
9323 (cons (car c)
9324 (cdr (or (assoc (cadr repl) alist)
9325 (error "Undefined key `%s' as contextual replacement for `%s'"
9326 (cadr repl) (car c)))))
9327 r))))))
9328 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9329 (delq
9331 (delete-dups
9332 (mapcar (lambda (x)
9333 (let ((tpl (car x)))
9334 (unless (delq
9336 (mapcar (lambda (y)
9337 (equal y tpl))
9339 x)))
9340 (reverse r))))))
9342 (defun org-contextualize-validate-key (key contexts)
9343 "Check CONTEXTS for agenda or capture KEY."
9344 (let (res)
9345 (dolist (r contexts)
9346 (dolist (rr (car (last r)))
9347 (when
9348 (and (equal key (car r))
9349 (if (functionp rr) (funcall rr)
9350 (or (and (eq (car rr) 'in-file)
9351 (buffer-file-name)
9352 (string-match (cdr rr) (buffer-file-name)))
9353 (and (eq (car rr) 'in-mode)
9354 (string-match (cdr rr) (symbol-name major-mode)))
9355 (and (eq (car rr) 'in-buffer)
9356 (string-match (cdr rr) (buffer-name)))
9357 (when (and (eq (car rr) 'not-in-file)
9358 (buffer-file-name))
9359 (not (string-match (cdr rr) (buffer-file-name))))
9360 (when (eq (car rr) 'not-in-mode)
9361 (not (string-match (cdr rr) (symbol-name major-mode))))
9362 (when (eq (car rr) 'not-in-buffer)
9363 (not (string-match (cdr rr) (buffer-name)))))))
9364 (push r res))))
9365 (delete-dups (delq nil res))))
9367 (defun org-context-p (&rest contexts)
9368 "Check if local context is any of CONTEXTS.
9369 Possible values in the list of contexts are `table', `headline', and `item'."
9370 (let ((pos (point)))
9371 (goto-char (point-at-bol))
9372 (prog1 (or (and (memq 'table contexts)
9373 (looking-at "[ \t]*|"))
9374 (and (memq 'headline contexts)
9375 (looking-at org-outline-regexp))
9376 (and (memq 'item contexts)
9377 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9378 (and (memq 'item-body contexts)
9379 (org-in-item-p)))
9380 (goto-char pos))))
9382 (defconst org-unique-local-variables
9383 '(org-element--cache
9384 org-element--cache-objects
9385 org-element--cache-sync-keys
9386 org-element--cache-sync-requests
9387 org-element--cache-sync-timer)
9388 "List of local variables that cannot be transferred to another buffer.")
9390 (defun org-get-local-variables ()
9391 "Return a list of all local variables in an Org mode buffer."
9392 (delq nil
9393 (mapcar
9394 (lambda (x)
9395 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9396 (name (car binding)))
9397 (and (not (get name 'org-state))
9398 (not (memq name org-unique-local-variables))
9399 (string-match-p
9400 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9401 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9402 (symbol-name name))
9403 binding)))
9404 (with-temp-buffer
9405 (org-mode)
9406 (buffer-local-variables)))))
9408 (defun org-clone-local-variables (from-buffer &optional regexp)
9409 "Clone local variables from FROM-BUFFER.
9410 Optional argument REGEXP selects variables to clone."
9411 (dolist (pair (buffer-local-variables from-buffer))
9412 (let ((name (car pair)))
9413 (when (and (symbolp name)
9414 (not (memq name org-unique-local-variables))
9415 (or (null regexp) (string-match regexp (symbol-name name))))
9416 (set (make-local-variable name) (cdr pair))))))
9418 ;;;###autoload
9419 (defun org-run-like-in-org-mode (cmd)
9420 "Run a command, pretending that the current buffer is in Org-mode.
9421 This will temporarily bind local variables that are typically bound in
9422 Org-mode to the values they have in Org-mode, and then interactively
9423 call CMD."
9424 (org-load-modules-maybe)
9425 (unless org-local-vars
9426 (setq org-local-vars (org-get-local-variables)))
9427 (let (binds)
9428 (dolist (var org-local-vars)
9429 (when (or (not (boundp (car var)))
9430 (eq (symbol-value (car var))
9431 (default-value (car var))))
9432 (push (list (car var) `(quote ,(cadr var))) binds)))
9433 (eval `(let ,binds
9434 (call-interactively (quote ,cmd))))))
9436 (defun org-get-category (&optional pos force-refresh)
9437 "Get the category applying to position POS."
9438 (save-match-data
9439 (when force-refresh (org-refresh-category-properties))
9440 (let ((pos (or pos (point))))
9441 (or (get-text-property pos 'org-category)
9442 (progn (org-refresh-category-properties)
9443 (get-text-property pos 'org-category))))))
9445 ;;; Refresh properties
9447 (defun org-refresh-properties (dprop tprop)
9448 "Refresh buffer text properties.
9449 DPROP is the drawer property and TPROP is either the
9450 corresponding text property to set, or an alist with each element
9451 being a text property (as a symbol) and a function to apply to
9452 the value of the drawer property."
9453 (let ((case-fold-search t)
9454 (inhibit-read-only t))
9455 (org-with-silent-modifications
9456 (save-excursion
9457 (save-restriction
9458 (widen)
9459 (goto-char (point-min))
9460 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9461 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9463 (defun org-refresh-property (tprop p)
9464 "Refresh the buffer text property TPROP from the drawer property P.
9465 The refresh happens only for the current tree (not subtree)."
9466 (unless (org-before-first-heading-p)
9467 (save-excursion
9468 (org-back-to-heading t)
9469 (if (symbolp tprop)
9470 ;; TPROP is a text property symbol
9471 (put-text-property
9472 (point) (or (outline-next-heading) (point-max)) tprop p)
9473 ;; TPROP is an alist with (properties . function) elements
9474 (dolist (al tprop)
9475 (save-excursion
9476 (put-text-property
9477 (line-beginning-position) (or (outline-next-heading) (point-max))
9478 (car al)
9479 (funcall (cdr al) p))))))))
9481 (defun org-refresh-category-properties ()
9482 "Refresh category text properties in the buffer."
9483 (let ((case-fold-search t)
9484 (inhibit-read-only t)
9485 (default-category
9486 (cond ((null org-category)
9487 (if buffer-file-name
9488 (file-name-sans-extension
9489 (file-name-nondirectory buffer-file-name))
9490 "???"))
9491 ((symbolp org-category) (symbol-name org-category))
9492 (t org-category))))
9493 (org-with-silent-modifications
9494 (org-with-wide-buffer
9495 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9496 ;; This is the default category for the buffer. If none is
9497 ;; found, fall-back to `org-category' or buffer file name.
9498 (put-text-property
9499 (point-min) (point-max)
9500 'org-category
9501 (catch 'buffer-category
9502 (goto-char (point-max))
9503 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9504 (let ((element (org-element-at-point)))
9505 (when (eq (org-element-type element) 'keyword)
9506 (throw 'buffer-category
9507 (org-element-property :value element)))))
9508 default-category))
9509 ;; Set sub-tree specific categories.
9510 (goto-char (point-min))
9511 (let ((regexp (org-re-property "CATEGORY")))
9512 (while (re-search-forward regexp nil t)
9513 (let ((value (org-match-string-no-properties 3)))
9514 (when (org-at-property-p)
9515 (put-text-property
9516 (save-excursion (org-back-to-heading t) (point))
9517 (save-excursion (org-end-of-subtree t t) (point))
9518 'org-category
9519 value)))))))))
9521 (defun org-refresh-stats-properties ()
9522 "Refresh stats text properties in the buffer."
9523 (let (stats)
9524 (org-with-silent-modifications
9525 (save-excursion
9526 (save-restriction
9527 (widen)
9528 (goto-char (point-min))
9529 (while (re-search-forward
9530 (concat org-outline-regexp-bol ".*"
9531 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9532 nil t)
9533 (setq stats (cond ((equal (match-string 3) "0") 0)
9534 ((match-string 2)
9535 (/ (* (string-to-number (match-string 2)) 100)
9536 (string-to-number (match-string 3))))
9537 (t (string-to-number (match-string 1)))))
9538 (org-back-to-heading t)
9539 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9540 'org-stats stats)))))))
9542 (defun org-refresh-effort-properties ()
9543 "Refresh effort properties"
9544 (org-refresh-properties
9545 org-effort-property
9546 '((effort . identity)
9547 (effort-minutes . org-duration-string-to-minutes))))
9549 ;;;; Link Stuff
9551 ;;; Link abbreviations
9553 (defun org-link-expand-abbrev (link)
9554 "Apply replacements as defined in `org-link-abbrev-alist'."
9555 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9556 (let* ((key (match-string 1 link))
9557 (as (or (assoc key org-link-abbrev-alist-local)
9558 (assoc key org-link-abbrev-alist)))
9559 (tag (and (match-end 2) (match-string 3 link)))
9560 rpl)
9561 (if (not as)
9562 link
9563 (setq rpl (cdr as))
9564 (cond
9565 ((symbolp rpl) (funcall rpl tag))
9566 ((string-match "%(\\([^)]+\\))" rpl)
9567 (replace-match
9568 (save-match-data
9569 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9570 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9571 ((string-match "%h" rpl)
9572 (replace-match (url-hexify-string (or tag "")) t t rpl))
9573 (t (concat rpl tag)))))
9574 link))
9576 ;;; Storing and inserting links
9578 (defvar org-insert-link-history nil
9579 "Minibuffer history for links inserted with `org-insert-link'.")
9581 (defvar org-stored-links nil
9582 "Contains the links stored with `org-store-link'.")
9584 (defvar org-store-link-plist nil
9585 "Plist with info about the most recently link created with `org-store-link'.")
9587 (defvar org-link-protocols nil
9588 "Link protocols added to Org-mode using `org-add-link-type'.")
9590 (defvar org-store-link-functions nil
9591 "List of functions that are called to create and store a link.
9592 Each function will be called in turn until one returns a non-nil
9593 value. Each function should check if it is responsible for creating
9594 this link (for example by looking at the major mode).
9595 If not, it must exit and return nil.
9596 If yes, it should return a non-nil value after a calling
9597 `org-store-link-props' with a list of properties and values.
9598 Special properties are:
9600 :type The link prefix, like \"http\". This must be given.
9601 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9602 This is obligatory as well.
9603 :description Optional default description for the second pair
9604 of brackets in an Org-mode link. The user can still change
9605 this when inserting this link into an Org-mode buffer.
9607 In addition to these, any additional properties can be specified
9608 and then used in capture templates.")
9610 (defun org-add-link-type (type &optional follow export)
9611 "Add TYPE to the list of `org-link-types'.
9612 Re-compute all regular expressions depending on `org-link-types'
9614 FOLLOW and EXPORT are two functions.
9616 FOLLOW should take the link path as the single argument and do whatever
9617 is necessary to follow the link, for example find a file or display
9618 a mail message.
9620 EXPORT should format the link path for export to one of the export formats.
9621 It should be a function accepting three arguments:
9623 path the path of the link, the text after the prefix (like \"http:\")
9624 desc the description of the link, if any
9625 format the export format, a symbol like `html' or `latex' or `ascii'.
9627 The function may use the FORMAT information to return different values
9628 depending on the format. The return value will be put literally into
9629 the exported file. If the return value is nil, this means Org should
9630 do what it normally does with links which do not have EXPORT defined.
9632 Org mode has a built-in default for exporting links. If you are happy with
9633 this default, there is no need to define an export function for the link
9634 type. For a simple example of an export function, see `org-bbdb.el'."
9635 (add-to-list 'org-link-types type t)
9636 (org-make-link-regexps)
9637 (org-element-update-syntax)
9638 (if (assoc type org-link-protocols)
9639 (setcdr (assoc type org-link-protocols) (list follow export))
9640 (push (list type follow export) org-link-protocols)))
9642 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9643 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9645 ;;;###autoload
9646 (defun org-store-link (arg)
9647 "\\<org-mode-map>Store an org-link to the current location.
9648 This link is added to `org-stored-links' and can later be inserted
9649 into an Org buffer with \\[org-insert-link].
9651 For some link types, a prefix ARG is interpreted.
9652 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9653 For file links, ARG negates `org-context-in-file-links'.
9655 A double prefix ARG force skipping storing functions that are not
9656 part of Org's core.
9658 A triple prefix ARG force storing a link for each line in the
9659 active region."
9660 (interactive "P")
9661 (org-load-modules-maybe)
9662 (if (and (equal arg '(64)) (org-region-active-p))
9663 (save-excursion
9664 (let ((end (region-end)))
9665 (goto-char (region-beginning))
9666 (set-mark (point))
9667 (while (< (point-at-eol) end)
9668 (move-end-of-line 1) (activate-mark)
9669 (let (current-prefix-arg)
9670 (call-interactively 'org-store-link))
9671 (move-beginning-of-line 2)
9672 (set-mark (point)))))
9673 (org-with-limited-levels
9674 (setq org-store-link-plist nil)
9675 (let (link cpltxt desc description search
9676 txt custom-id agenda-link sfuns sfunsn)
9677 (cond
9679 ;; Store a link using an external link type
9680 ((and (not (equal arg '(16)))
9681 (setq sfuns
9682 (delq
9683 nil (mapcar (lambda (f)
9684 (let (fs) (if (funcall f) (push f fs))))
9685 org-store-link-functions))
9686 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9687 (or (and (cdr sfuns)
9688 (funcall (intern
9689 (completing-read
9690 "Which function for creating the link? "
9691 sfunsn nil t (car sfunsn)))))
9692 (funcall (caar sfuns)))
9693 (setq link (plist-get org-store-link-plist :link)
9694 desc (or (plist-get org-store-link-plist
9695 :description)
9696 link))))
9698 ;; Store a link from a source code buffer.
9699 ((org-src-edit-buffer-p)
9700 (cond
9701 ((save-excursion
9702 (beginning-of-line)
9703 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9704 "[ \t]*$")))
9705 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9706 ((org-called-interactively-p 'any)
9707 (let (label)
9708 (while (or (not label)
9709 (org-with-wide-buffer
9710 (goto-char (point-min))
9711 (re-search-forward
9712 (regexp-quote (format org-coderef-label-format label))
9713 nil t)))
9714 (when label (message "Label exists already") (sit-for 2))
9715 (setq label (read-string "Code line label: " label)))
9716 (end-of-line)
9717 (setq link (format org-coderef-label-format label))
9718 (let ((gc (- 79 (length link))))
9719 (if (< (current-column) gc) (org-move-to-column gc t)
9720 (insert " ")))
9721 (insert link)
9722 (setq link (concat "(" label ")") desc nil)))
9723 (t (setq link nil))))
9725 ;; We are in the agenda, link to referenced location
9726 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9727 (let ((m (or (get-text-property (point) 'org-hd-marker)
9728 (get-text-property (point) 'org-marker))))
9729 (when m
9730 (org-with-point-at m
9731 (setq agenda-link
9732 (if (org-called-interactively-p 'any)
9733 (call-interactively 'org-store-link)
9734 (org-store-link nil)))))))
9736 ((eq major-mode 'calendar-mode)
9737 (let ((cd (calendar-cursor-to-date)))
9738 (setq link
9739 (format-time-string
9740 (car org-time-stamp-formats)
9741 (apply 'encode-time
9742 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9743 nil nil nil))))
9744 (org-store-link-props :type "calendar" :date cd)))
9746 ((eq major-mode 'help-mode)
9747 (setq link (concat "help:" (save-excursion
9748 (goto-char (point-min))
9749 (looking-at "^[^ ]+")
9750 (match-string 0))))
9751 (org-store-link-props :type "help"))
9753 ((eq major-mode 'w3-mode)
9754 (setq cpltxt (if (and (buffer-name)
9755 (not (string-match "Untitled" (buffer-name))))
9756 (buffer-name)
9757 (url-view-url t))
9758 link (url-view-url t))
9759 (org-store-link-props :type "w3" :url (url-view-url t)))
9761 ((eq major-mode 'image-mode)
9762 (setq cpltxt (concat "file:"
9763 (abbreviate-file-name buffer-file-name))
9764 link cpltxt)
9765 (org-store-link-props :type "image" :file buffer-file-name))
9767 ;; In dired, store a link to the file of the current line
9768 ((derived-mode-p 'dired-mode)
9769 (let ((file (dired-get-filename nil t)))
9770 (setq file (if file
9771 (abbreviate-file-name
9772 (expand-file-name (dired-get-filename nil t)))
9773 ;; otherwise, no file so use current directory.
9774 default-directory))
9775 (setq cpltxt (concat "file:" file)
9776 link cpltxt)))
9778 ((setq search (run-hook-with-args-until-success
9779 'org-create-file-search-functions))
9780 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9781 "::" search))
9782 (setq cpltxt (or description link)))
9784 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9785 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9786 (cond
9787 ;; Store a link using the target at point
9788 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9789 (setq cpltxt
9790 (concat "file:"
9791 (abbreviate-file-name
9792 (buffer-file-name (buffer-base-buffer)))
9793 "::" (match-string 1))
9794 link cpltxt))
9795 ((and (featurep 'org-id)
9796 (or (eq org-id-link-to-org-use-id t)
9797 (and (org-called-interactively-p 'any)
9798 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9799 (and (eq org-id-link-to-org-use-id
9800 'create-if-interactive-and-no-custom-id)
9801 (not custom-id))))
9802 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9803 ;; Store a link using the ID at point
9804 (setq link (condition-case nil
9805 (prog1 (org-id-store-link)
9806 (setq desc (or (plist-get org-store-link-plist
9807 :description)
9808 "")))
9809 (error
9810 ;; Probably before first headline, link only to file
9811 (concat "file:"
9812 (abbreviate-file-name
9813 (buffer-file-name (buffer-base-buffer))))))))
9815 ;; Just link to current headline
9816 (setq cpltxt (concat "file:"
9817 (abbreviate-file-name
9818 (buffer-file-name (buffer-base-buffer)))))
9819 ;; Add a context search string
9820 (when (org-xor org-context-in-file-links arg)
9821 (let* ((ee (org-element-at-point))
9822 (et (org-element-type ee))
9823 (ev (plist-get (cadr ee) :value))
9824 (ek (plist-get (cadr ee) :key))
9825 (eok (and (stringp ek) (string-match "name" ek))))
9826 (setq txt (cond
9827 ((org-at-heading-p) nil)
9828 ((and (eq et 'keyword) eok) ev)
9829 ((org-region-active-p)
9830 (buffer-substring (region-beginning) (region-end)))))
9831 (when (or (null txt) (string-match "\\S-" txt))
9832 (setq cpltxt
9833 (concat cpltxt "::"
9834 (condition-case nil
9835 (org-make-org-heading-search-string txt)
9836 (error "")))
9837 desc (or (and (eq et 'keyword) eok ev)
9838 (nth 4 (ignore-errors (org-heading-components)))
9839 "NONE")))))
9840 (when (string-match "::\\'" cpltxt)
9841 (setq cpltxt (substring cpltxt 0 -2)))
9842 (setq link cpltxt))))
9844 ((buffer-file-name (buffer-base-buffer))
9845 ;; Just link to this file here.
9846 (setq cpltxt (concat "file:"
9847 (abbreviate-file-name
9848 (buffer-file-name (buffer-base-buffer)))))
9849 ;; Add a context string.
9850 (when (org-xor org-context-in-file-links arg)
9851 (setq txt (if (org-region-active-p)
9852 (buffer-substring (region-beginning) (region-end))
9853 (buffer-substring (point-at-bol) (point-at-eol))))
9854 ;; Only use search option if there is some text.
9855 (when (string-match "\\S-" txt)
9856 (setq cpltxt
9857 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9858 desc "NONE")))
9859 (setq link cpltxt))
9861 ((org-called-interactively-p 'interactive)
9862 (user-error "No method for storing a link from this buffer"))
9864 (t (setq link nil)))
9866 ;; We're done setting link and desc, clean up
9867 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9868 (setq link (or link cpltxt)
9869 desc (or desc cpltxt))
9870 (cond ((equal desc "NONE") (setq desc nil))
9871 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9872 (let ((d0 (match-string 3 desc))
9873 (p0 (match-string 5 desc)))
9874 (setq desc
9875 (replace-regexp-in-string
9876 org-bracket-link-regexp
9877 (concat (or p0 d0)
9878 (if (equal (length (match-string 0 desc))
9879 (length desc)) "*" "")) desc)))))
9881 ;; Return the link
9882 (if (not (and (or (org-called-interactively-p 'any)
9883 executing-kbd-macro)
9884 link))
9885 (or agenda-link (and link (org-make-link-string link desc)))
9886 (push (list link desc) org-stored-links)
9887 (message "Stored: %s" (or desc link))
9888 (when custom-id
9889 (setq link (concat "file:" (abbreviate-file-name
9890 (buffer-file-name)) "::#" custom-id))
9891 (push (list link desc) org-stored-links))
9892 (car org-stored-links))))))
9894 (defun org-store-link-props (&rest plist)
9895 "Store link properties, extract names, addresses and dates."
9896 (let ((x (plist-get plist :from)))
9897 (when x
9898 (let ((adr (mail-extract-address-components x)))
9899 (setq plist (plist-put plist :fromname (car adr)))
9900 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9901 (let ((x (plist-get plist :to)))
9902 (when x
9903 (let ((adr (mail-extract-address-components x)))
9904 (setq plist (plist-put plist :toname (car adr)))
9905 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9906 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9907 (when x
9908 (setq plist (plist-put plist :date-timestamp
9909 (format-time-string
9910 (org-time-stamp-format t) x)))
9911 (setq plist (plist-put plist :date-timestamp-inactive
9912 (format-time-string
9913 (org-time-stamp-format t t) x)))))
9914 (let ((from (plist-get plist :from))
9915 (to (plist-get plist :to)))
9916 (when (and from to org-from-is-user-regexp)
9917 (setq plist
9918 (plist-put plist :fromto
9919 (if (string-match org-from-is-user-regexp from)
9920 (concat "to %t")
9921 (concat "from %f"))))))
9922 (setq org-store-link-plist plist))
9924 (defun org-add-link-props (&rest plist)
9925 "Add these properties to the link property list."
9926 (let (key value)
9927 (while plist
9928 (setq key (pop plist) value (pop plist))
9929 (setq org-store-link-plist
9930 (plist-put org-store-link-plist key value)))))
9932 (defun org-email-link-description (&optional fmt)
9933 "Return the description part of an email link.
9934 This takes information from `org-store-link-plist' and formats it
9935 according to FMT (default from `org-email-link-description-format')."
9936 (setq fmt (or fmt org-email-link-description-format))
9937 (let* ((p org-store-link-plist)
9938 (to (plist-get p :toaddress))
9939 (from (plist-get p :fromaddress))
9940 (table
9941 (list
9942 (cons "%c" (plist-get p :fromto))
9943 (cons "%F" (plist-get p :from))
9944 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9945 (cons "%T" (plist-get p :to))
9946 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9947 (cons "%s" (plist-get p :subject))
9948 (cons "%d" (plist-get p :date))
9949 (cons "%m" (plist-get p :message-id)))))
9950 (when (string-match "%c" fmt)
9951 ;; Check if the user wrote this message
9952 (if (and org-from-is-user-regexp from to
9953 (save-match-data (string-match org-from-is-user-regexp from)))
9954 (setq fmt (replace-match "to %t" t t fmt))
9955 (setq fmt (replace-match "from %f" t t fmt))))
9956 (org-replace-escapes fmt table)))
9958 (defun org-make-org-heading-search-string (&optional string)
9959 "Make search string for the current headline or STRING."
9960 (let ((s (or string
9961 (and (derived-mode-p 'org-mode)
9962 (save-excursion
9963 (org-back-to-heading t)
9964 (org-element-property :raw-value (org-element-at-point))))))
9965 (lines org-context-in-file-links))
9966 (or string (setq s (concat "*" s))) ; Add * for headlines
9967 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9968 (when (and string (integerp lines) (> lines 0))
9969 (let ((slines (org-split-string s "\n")))
9970 (when (< lines (length slines))
9971 (setq s (mapconcat
9972 'identity
9973 (reverse (nthcdr (- (length slines) lines)
9974 (reverse slines))) "\n")))))
9975 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9977 (defun org-make-link-string (link &optional description)
9978 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9979 (unless (org-string-nw-p link) (error "Empty link"))
9980 (let ((uri (cond ((string-match org-link-types-re link)
9981 (concat (match-string 1 link)
9982 (org-link-escape (substring link (match-end 1)))))
9983 ;; For readability, url-encode internal links only
9984 ;; when absolutely needed (i.e, when they contain
9985 ;; square brackets). File links however, are
9986 ;; encoded since, e.g., spaces are significant.
9987 ((or (file-name-absolute-p link)
9988 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
9989 (org-link-escape link))
9990 (t link)))
9991 (description
9992 (and (org-string-nw-p description)
9993 ;; Remove brackets from description, as they are fatal.
9994 (replace-regexp-in-string
9995 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9996 (org-trim description)))))
9997 (format "[[%s]%s]"
9999 (if description (format "[%s]" description) ""))))
10001 (defconst org-link-escape-chars
10002 ;;%20 %5B %5D %25
10003 '(?\s ?\[ ?\] ?%)
10004 "List of characters that should be escaped in a link when stored to Org.
10005 This is the list that is used for internal purposes.")
10007 (defconst org-link-escape-chars-browser
10008 ;;%20 %22
10009 '(?\s ?\")
10010 "List of characters to be escaped before handing over to the browser.
10011 If you consider using this constant then you probably want to use
10012 the function `org-link-escape-browser' instead. See there why
10013 this constant is a candidate to be removed once Org drops support
10014 for Emacs 24.1 and 24.2.")
10016 (defun org-link-escape (text &optional table merge)
10017 "Return percent escaped representation of TEXT.
10018 TEXT is a string with the text to escape.
10019 Optional argument TABLE is a list with characters that should be
10020 escaped. When nil, `org-link-escape-chars' is used.
10021 If optional argument MERGE is set, merge TABLE into
10022 `org-link-escape-chars'."
10023 (let ((characters-to-encode
10024 (cond ((null table) org-link-escape-chars)
10025 (merge (append org-link-escape-chars table))
10026 (t table))))
10027 (mapconcat
10028 (lambda (c)
10029 (if (or (memq c characters-to-encode)
10030 (and org-url-hexify-p (or (< c 32) (> c 126))))
10031 (mapconcat (lambda (e) (format "%%%.2X" e))
10032 (or (encode-coding-char c 'utf-8)
10033 (error "Unable to percent escape character: %c" c))
10035 (char-to-string c)))
10036 text "")))
10038 (defun org-link-escape-browser (text)
10039 "Escape some characters before handing over to the browser.
10040 This function is a candidate to be removed together with the
10041 constant `org-link-escape-chars-browser' once Org drops support
10042 for Emacs 24.1 and 24.2. All calls to this function will have to
10043 be replaced with `url-encode-url' which is available since Emacs
10044 24.3.1."
10045 ;; Example with the Org link
10046 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10047 ;; to open the browser with +subject:"Release 8.2" filled into the
10048 ;; query field: In this case the variable TEXT contains the
10049 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10050 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10051 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10052 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10053 (if (fboundp 'url-encode-url)
10054 (url-encode-url text)
10055 (if (org-string-match-p
10056 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10057 text)
10058 (org-link-escape text org-link-escape-chars-browser)
10059 text)))
10061 (defun org-link-unescape (str)
10062 "Unhex hexified Unicode parts in string STR.
10063 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10064 reciprocal of `org-link-escape', which see."
10065 (if (org-string-nw-p str)
10066 (replace-regexp-in-string
10067 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10068 str))
10070 (defun org-link-unescape-compound (hex)
10071 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10072 Note: this function also decodes single byte encodings like
10073 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10074 (save-match-data
10075 (let* ((bytes (cdr (split-string hex "%")))
10076 (ret "")
10077 (eat 0)
10078 (sum 0))
10079 (while bytes
10080 (let* ((val (string-to-number (pop bytes) 16))
10081 (shift-xor
10082 (if (= 0 eat)
10083 (cond
10084 ((>= val 252) (cons 6 252))
10085 ((>= val 248) (cons 5 248))
10086 ((>= val 240) (cons 4 240))
10087 ((>= val 224) (cons 3 224))
10088 ((>= val 192) (cons 2 192))
10089 (t (cons 0 0)))
10090 (cons 6 128))))
10091 (when (>= val 192) (setq eat (car shift-xor)))
10092 (setq val (logxor val (cdr shift-xor)))
10093 (setq sum (+ (lsh sum (car shift-xor)) val))
10094 (when (> eat 0) (setq eat (- eat 1)))
10095 (cond
10096 ((= 0 eat) ;multi byte
10097 (setq ret (concat ret (org-char-to-string sum)))
10098 (setq sum 0))
10099 ((not bytes) ; single byte(s)
10100 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10101 ret)))
10103 (defun org-link-unescape-single-byte-sequence (hex)
10104 "Unhexify hex-encoded single byte character sequences."
10105 (mapconcat (lambda (byte)
10106 (char-to-string (string-to-number byte 16)))
10107 (cdr (split-string hex "%")) ""))
10109 (defun org-xor (a b)
10110 "Exclusive or."
10111 (if a (not b) b))
10113 (defun org-fixup-message-id-for-http (s)
10114 "Replace special characters in a message id, so it can be used in an http query."
10115 (when (string-match "%" s)
10116 (setq s (mapconcat (lambda (c)
10117 (if (eq c ?%)
10118 "%25"
10119 (char-to-string c)))
10120 s "")))
10121 (while (string-match "<" s)
10122 (setq s (replace-match "%3C" t t s)))
10123 (while (string-match ">" s)
10124 (setq s (replace-match "%3E" t t s)))
10125 (while (string-match "@" s)
10126 (setq s (replace-match "%40" t t s)))
10129 (defun org-link-prettify (link)
10130 "Return a human-readable representation of LINK.
10131 The car of LINK must be a raw link.
10132 The cdr of LINK must be either a link description or nil."
10133 (let ((desc (or (cadr link) "<no description>")))
10134 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10135 "<" (car link) ">")))
10137 ;;;###autoload
10138 (defun org-insert-link-global ()
10139 "Insert a link like Org-mode does.
10140 This command can be called in any mode to insert a link in Org-mode syntax."
10141 (interactive)
10142 (org-load-modules-maybe)
10143 (org-run-like-in-org-mode 'org-insert-link))
10145 (defun org-insert-all-links (arg &optional pre post)
10146 "Insert all links in `org-stored-links'.
10147 When a universal prefix, do not delete the links from `org-stored-links'.
10148 When `ARG' is a number, insert the last N link(s).
10149 `PRE' and `POST' are optional arguments to define a string to
10150 prepend or to append."
10151 (interactive "P")
10152 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10153 (links (copy-seq org-stored-links))
10154 (pr (or pre "- "))
10155 (po (or post "\n"))
10156 (cnt 1) l)
10157 (if (null org-stored-links)
10158 (message "No link to insert")
10159 (while (and (or (listp arg) (>= arg cnt))
10160 (setq l (if (listp arg)
10161 (pop links)
10162 (pop org-stored-links))))
10163 (setq cnt (1+ cnt))
10164 (insert pr)
10165 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10166 (insert po)))))
10168 (defun org-insert-last-stored-link (arg)
10169 "Insert the last link stored in `org-stored-links'."
10170 (interactive "p")
10171 (org-insert-all-links arg "" "\n"))
10173 (defun org-link-fontify-links-to-this-file ()
10174 "Fontify links to the current file in `org-stored-links'."
10175 (let ((f (buffer-file-name)) a b)
10176 (setq a (mapcar (lambda(l)
10177 (let ((ll (car l)))
10178 (when (and (string-match "^file:\\(.+\\)::" ll)
10179 (equal f (expand-file-name (match-string 1 ll))))
10180 ll)))
10181 org-stored-links))
10182 (when (featurep 'org-id)
10183 (setq b (mapcar (lambda(l)
10184 (let ((ll (car l)))
10185 (when (and (string-match "^id:\\(.+\\)$" ll)
10186 (equal f (expand-file-name
10187 (or (org-id-find-id-file
10188 (match-string 1 ll)) ""))))
10189 ll)))
10190 org-stored-links)))
10191 (mapcar (lambda(l)
10192 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10193 (delq nil (append a b)))))
10195 (defvar org--links-history nil)
10196 (defun org-insert-link (&optional complete-file link-location default-description)
10197 "Insert a link. At the prompt, enter the link.
10199 Completion can be used to insert any of the link protocol prefixes like
10200 http or ftp in use.
10202 The history can be used to select a link previously stored with
10203 `org-store-link'. When the empty string is entered (i.e. if you just
10204 press RET at the prompt), the link defaults to the most recently
10205 stored link. As SPC triggers completion in the minibuffer, you need to
10206 use M-SPC or C-q SPC to force the insertion of a space character.
10208 You will also be prompted for a description, and if one is given, it will
10209 be displayed in the buffer instead of the link.
10211 If there is already a link at point, this command will allow you to edit link
10212 and description parts.
10214 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10215 be selected using completion. The path to the file will be relative to the
10216 current directory if the file is in the current directory or a subdirectory.
10217 Otherwise, the link will be the absolute path as completed in the minibuffer
10218 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10219 option `org-link-file-path-type'.
10221 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10222 the current directory or below.
10224 With three \\[universal-argument] prefixes, negate the meaning of
10225 `org-keep-stored-link-after-insertion'.
10227 If `org-make-link-description-function' is non-nil, this function will be
10228 called with the link target, and the result will be the default
10229 link description.
10231 If the LINK-LOCATION parameter is non-nil, this value will be
10232 used as the link location instead of reading one interactively.
10234 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10235 be used as the default description."
10236 (interactive "P")
10237 (let* ((wcf (current-window-configuration))
10238 (origbuf (current-buffer))
10239 (region (when (org-region-active-p)
10240 (buffer-substring (region-beginning) (region-end))))
10241 (remove (and region (list (region-beginning) (region-end))))
10242 (desc region)
10243 (link link-location)
10244 (abbrevs org-link-abbrev-alist-local)
10245 entry all-prefixes auto-desc)
10246 (cond
10247 (link-location) ; specified by arg, just use it.
10248 ((org-in-regexp org-bracket-link-regexp 1)
10249 ;; We do have a link at point, and we are going to edit it.
10250 (setq remove (list (match-beginning 0) (match-end 0)))
10251 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10252 (setq link (read-string "Link: "
10253 (org-link-unescape
10254 (org-match-string-no-properties 1)))))
10255 ((or (org-in-regexp org-angle-link-re)
10256 (org-in-regexp org-plain-link-re))
10257 ;; Convert to bracket link
10258 (setq remove (list (match-beginning 0) (match-end 0))
10259 link (read-string "Link: "
10260 (org-remove-angle-brackets (match-string 0)))))
10261 ((member complete-file '((4) (16)))
10262 ;; Completing read for file names.
10263 (setq link (org-file-complete-link complete-file)))
10265 ;; Read link, with completion for stored links.
10266 (org-link-fontify-links-to-this-file)
10267 (org-switch-to-buffer-other-window "*Org Links*")
10268 (with-current-buffer "*Org Links*"
10269 (erase-buffer)
10270 (insert "Insert a link.
10271 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10272 (when org-stored-links
10273 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10274 (insert (mapconcat 'org-link-prettify
10275 (reverse org-stored-links) "\n")))
10276 (goto-char (point-min)))
10277 (let ((cw (selected-window)))
10278 (select-window (get-buffer-window "*Org Links*" 'visible))
10279 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10280 (unless (pos-visible-in-window-p (point-max))
10281 (org-fit-window-to-buffer))
10282 (and (window-live-p cw) (select-window cw)))
10283 (setq all-prefixes (append (mapcar 'car abbrevs)
10284 (mapcar 'car org-link-abbrev-alist)
10285 org-link-types))
10286 (unwind-protect
10287 ;; Fake a link history, containing the stored links.
10288 (let ((org--links-history
10289 (append (mapcar #'car org-stored-links)
10290 org-insert-link-history)))
10291 (setq link
10292 (org-completing-read
10293 "Link: "
10294 (append
10295 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10296 (mapcar #'car org-stored-links))
10297 nil nil nil
10298 'org--links-history
10299 (caar org-stored-links)))
10300 (unless (org-string-nw-p link) (user-error "No link selected"))
10301 (dolist (l org-stored-links)
10302 (when (equal link (cadr l))
10303 (setq link (car l))
10304 (setq auto-desc t)))
10305 (when (or (member link all-prefixes)
10306 (and (equal ":" (substring link -1))
10307 (member (substring link 0 -1) all-prefixes)
10308 (setq link (substring link 0 -1))))
10309 (setq link (with-current-buffer origbuf
10310 (org-link-try-special-completion link)))))
10311 (set-window-configuration wcf)
10312 (kill-buffer "*Org Links*"))
10313 (setq entry (assoc link org-stored-links))
10314 (or entry (push link org-insert-link-history))
10315 (setq desc (or desc (nth 1 entry)))))
10317 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10318 (not org-keep-stored-link-after-insertion))
10319 (setq org-stored-links (delq (assoc link org-stored-links)
10320 org-stored-links)))
10322 (when (and (string-match org-plain-link-re link)
10323 (not (string-match org-ts-regexp link)))
10324 ;; URL-like link, normalize the use of angular brackets.
10325 (setq link (org-remove-angle-brackets link)))
10327 ;; Check if we are linking to the current file with a search
10328 ;; option If yes, simplify the link by using only the search
10329 ;; option.
10330 (when (and buffer-file-name
10331 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10332 (let* ((path (match-string 1 link))
10333 (case-fold-search nil)
10334 (search (match-string 2 link)))
10335 (save-match-data
10336 (when (equal (file-truename buffer-file-name) (file-truename path))
10337 ;; We are linking to this same file, with a search option
10338 (setq link search)))))
10340 ;; Check if we can/should use a relative path. If yes, simplify the link
10341 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10342 (let* ((type (match-string 1 link))
10343 (path (match-string 2 link))
10344 (origpath path)
10345 (case-fold-search nil))
10346 (cond
10347 ((or (eq org-link-file-path-type 'absolute)
10348 (equal complete-file '(16)))
10349 (setq path (abbreviate-file-name (expand-file-name path))))
10350 ((eq org-link-file-path-type 'noabbrev)
10351 (setq path (expand-file-name path)))
10352 ((eq org-link-file-path-type 'relative)
10353 (setq path (file-relative-name path)))
10355 (save-match-data
10356 (if (string-match (concat "^" (regexp-quote
10357 (expand-file-name
10358 (file-name-as-directory
10359 default-directory))))
10360 (expand-file-name path))
10361 ;; We are linking a file with relative path name.
10362 (setq path (substring (expand-file-name path)
10363 (match-end 0)))
10364 (setq path (abbreviate-file-name (expand-file-name path)))))))
10365 (setq link (concat type path))
10366 (when (equal desc origpath)
10367 (setq desc path))))
10369 (if org-make-link-description-function
10370 (setq desc
10371 (or (condition-case nil
10372 (funcall org-make-link-description-function link desc)
10373 (error (progn (message "Can't get link description from `%s'"
10374 (symbol-name org-make-link-description-function))
10375 (sit-for 2) nil)))
10376 (read-string "Description: " default-description)))
10377 (if default-description (setq desc default-description)
10378 (setq desc (or (and auto-desc desc)
10379 (read-string "Description: " desc)))))
10381 (unless (string-match "\\S-" desc) (setq desc nil))
10382 (when remove (apply 'delete-region remove))
10383 (insert (org-make-link-string link desc))
10384 ;; Redisplay so as the new link has proper invisible characters.
10385 (sit-for 0)))
10387 (defun org-link-try-special-completion (type)
10388 "If there is completion support for link type TYPE, offer it."
10389 (let ((fun (intern (concat "org-" type "-complete-link"))))
10390 (if (functionp fun)
10391 (funcall fun)
10392 (read-string "Link (no completion support): " (concat type ":")))))
10394 (defun org-file-complete-link (&optional arg)
10395 "Create a file link using completion."
10396 (let ((file (org-iread-file-name "File: "))
10397 (pwd (file-name-as-directory (expand-file-name ".")))
10398 (pwd1 (file-name-as-directory (abbreviate-file-name
10399 (expand-file-name ".")))))
10400 (cond ((equal arg '(16))
10401 (concat "file:"
10402 (abbreviate-file-name (expand-file-name file))))
10403 ((string-match
10404 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10405 (concat "file:" (match-string 1 file)))
10406 ((string-match
10407 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10408 (expand-file-name file))
10409 (concat "file:"
10410 (match-string 1 (expand-file-name file))))
10411 (t (concat "file:" file)))))
10413 (defvar ido-enter-matching-directory)
10414 (defun org-iread-file-name (&rest args)
10415 "Read-file-name using `ido-mode' speedup if available.
10416 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10417 See `read-file-name' for a description of parameters."
10418 (org-without-partial-completion
10419 (if (and org-completion-use-ido
10420 (fboundp 'ido-read-file-name)
10421 (org-bound-and-true-p ido-mode)
10422 (listp (nth 1 args)))
10423 (let ((ido-enter-matching-directory nil))
10424 (apply #'ido-read-file-name args))
10425 (apply #'read-file-name args))))
10427 (defun org-completing-read (&rest args)
10428 "Completing-read with SPACE being a normal character."
10429 (let ((enable-recursive-minibuffers t)
10430 (minibuffer-local-completion-map
10431 (copy-keymap minibuffer-local-completion-map)))
10432 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10433 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10434 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10435 'org-time-stamp-inactive)
10436 (apply #'completing-read args)))
10438 (define-obsolete-function-alias
10439 'org-completing-read-no-i 'completing-read "Org 9.0")
10440 (define-obsolete-function-alias
10441 'org-icompleting-read 'completing-read "Org 9.0")
10443 ;;; Opening/following a link
10445 (defvar org-link-search-failed nil)
10447 (defvar org-open-link-functions nil
10448 "Hook for functions finding a plain text link.
10449 These functions must take a single argument, the link content.
10450 They will be called for links that look like [[link text][description]]
10451 when LINK TEXT does not have a protocol like \"http:\" and does not look
10452 like a filename (e.g. \"./blue.png\").
10454 These functions will be called *before* Org attempts to resolve the
10455 link by doing text searches in the current buffer - so if you want a
10456 link \"[[target]]\" to still find \"<<target>>\", your function should
10457 handle this as a special case.
10459 When the function does handle the link, it must return a non-nil value.
10460 If it decides that it is not responsible for this link, it must return
10461 nil to indicate that that Org-mode can continue with other options
10462 like exact and fuzzy text search.")
10464 (defun org-next-link (&optional search-backward)
10465 "Move forward to the next link.
10466 If the link is in hidden text, expose it."
10467 (interactive "P")
10468 (when (and org-link-search-failed (eq this-command last-command))
10469 (goto-char (point-min))
10470 (message "Link search wrapped back to beginning of buffer"))
10471 (setq org-link-search-failed nil)
10472 (let* ((pos (point))
10473 (ct (org-context))
10474 (a (assoc :link ct))
10475 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10476 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10477 ((looking-at org-any-link-re)
10478 ;; Don't stay stuck at link without an org-link face
10479 (forward-char (if search-backward -1 1))))
10480 (if (funcall srch-fun org-any-link-re nil t)
10481 (progn
10482 (goto-char (match-beginning 0))
10483 (when (outline-invisible-p) (org-show-context)))
10484 (goto-char pos)
10485 (setq org-link-search-failed t)
10486 (message "No further link found"))))
10488 (defun org-previous-link ()
10489 "Move backward to the previous link.
10490 If the link is in hidden text, expose it."
10491 (interactive)
10492 (funcall 'org-next-link t))
10494 (defun org-translate-link (s)
10495 "Translate a link string if a translation function has been defined."
10496 (with-temp-buffer
10497 (insert (org-trim s))
10498 (org-trim (org-element-interpret-data (org-element-context)))))
10500 (defun org-translate-link-from-planner (type path)
10501 "Translate a link from Emacs Planner syntax so that Org can follow it.
10502 This is still an experimental function, your mileage may vary."
10503 (cond
10504 ((member type '("http" "https" "news" "ftp"))
10505 ;; standard Internet links are the same.
10506 nil)
10507 ((and (equal type "irc") (string-match "^//" path))
10508 ;; Planner has two / at the beginning of an irc link, we have 1.
10509 ;; We should have zero, actually....
10510 (setq path (substring path 1)))
10511 ((and (equal type "lisp") (string-match "^/" path))
10512 ;; Planner has a slash, we do not.
10513 (setq type "elisp" path (substring path 1)))
10514 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10515 ;; A typical message link. Planner has the id after the final slash,
10516 ;; we separate it with a hash mark
10517 (setq path (concat (match-string 1 path) "#"
10518 (org-remove-angle-brackets (match-string 2 path))))))
10519 (cons type path))
10521 (defun org-find-file-at-mouse (ev)
10522 "Open file link or URL at mouse."
10523 (interactive "e")
10524 (mouse-set-point ev)
10525 (org-open-at-point 'in-emacs))
10527 (defun org-open-at-mouse (ev)
10528 "Open file link or URL at mouse.
10529 See the docstring of `org-open-file' for details."
10530 (interactive "e")
10531 (mouse-set-point ev)
10532 (when (eq major-mode 'org-agenda-mode)
10533 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10534 (org-open-at-point))
10536 (defvar org-window-config-before-follow-link nil
10537 "The window configuration before following a link.
10538 This is saved in case the need arises to restore it.")
10540 ;;;###autoload
10541 (defun org-open-at-point-global ()
10542 "Follow a link like Org-mode does.
10543 This command can be called in any mode to follow a link that has
10544 Org-mode syntax."
10545 (interactive)
10546 (org-run-like-in-org-mode 'org-open-at-point))
10548 ;;;###autoload
10549 (defun org-open-link-from-string (s &optional arg reference-buffer)
10550 "Open a link in the string S, as if it was in Org-mode."
10551 (interactive "sLink: \nP")
10552 (let ((reference-buffer (or reference-buffer (current-buffer))))
10553 (with-temp-buffer
10554 (let ((org-inhibit-startup (not reference-buffer)))
10555 (org-mode)
10556 (insert s)
10557 (goto-char (point-min))
10558 (when reference-buffer
10559 (setq org-link-abbrev-alist-local
10560 (with-current-buffer reference-buffer
10561 org-link-abbrev-alist-local)))
10562 (org-open-at-point arg reference-buffer)))))
10564 (defvar org-open-at-point-functions nil
10565 "Hook that is run when following a link at point.
10567 Functions in this hook must return t if they identify and follow
10568 a link at point. If they don't find anything interesting at point,
10569 they must return nil.")
10571 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10572 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10573 (defun org-open-at-point (&optional arg reference-buffer)
10574 "Open link, timestamp, footnote or tags at point.
10576 When point is on a link, follow it. Normally, files will be
10577 opened by an appropriate application. If the optional prefix
10578 argument ARG is non-nil, Emacs will visit the file. With
10579 a double prefix argument, try to open outside of Emacs, in the
10580 application the system uses for this file type.
10582 When point is on a timestamp, open the agenda at the day
10583 specified.
10585 When point is a footnote definition, move to the first reference
10586 found. If it is on a reference, move to the associated
10587 definition.
10589 When point is on a headline, display a list of every link in the
10590 entry, so it is possible to pick one, or all, of them. If point
10591 is on a tag, call `org-tags-view' instead.
10593 When optional argument REFERENCE-BUFFER is non-nil, it should
10594 specify a buffer from where the link search should happen. This
10595 is used internally by `org-open-link-from-string'.
10597 On top of syntactically correct links, this function will open
10598 the link at point in comments or comment blocks and the first
10599 link in a property drawer line."
10600 (interactive "P")
10601 ;; On a code block, open block's results.
10602 (unless (call-interactively 'org-babel-open-src-block-result)
10603 (org-load-modules-maybe)
10604 (setq org-window-config-before-follow-link (current-window-configuration))
10605 (org-remove-occur-highlights nil nil t)
10606 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10607 (let* ((context
10608 ;; Only consider supported types, even if they are not
10609 ;; the closest one.
10610 (org-element-lineage
10611 (org-element-context)
10612 '(clock comment comment-block footnote-definition
10613 footnote-reference headline inlinetask keyword link
10614 node-property timestamp)
10616 (type (org-element-type context))
10617 (value (org-element-property :value context)))
10618 (cond
10619 ((not context) (user-error "No link found"))
10620 ;; Exception: open timestamps and links in properties
10621 ;; drawers, keywords and comments.
10622 ((memq type '(comment comment-block keyword node-property))
10623 (cond ((org-in-regexp org-any-link-re)
10624 (org-open-link-from-string (match-string-no-properties 0)))
10625 ((or (org-in-regexp org-ts-regexp-both nil t)
10626 (org-in-regexp org-tsr-regexp-both nil t))
10627 (org-follow-timestamp-link))
10628 (t (user-error "No link found"))))
10629 ;; On a headline or an inlinetask, but not on a timestamp,
10630 ;; a link, a footnote reference or on tags.
10631 ((and (memq type '(headline inlinetask))
10632 ;; Not on tags.
10633 (progn (save-excursion (beginning-of-line)
10634 (looking-at org-complex-heading-regexp))
10635 (or (not (match-beginning 5))
10636 (< (point) (match-beginning 5)))))
10637 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10638 (links (car data))
10639 (links-end (cdr data)))
10640 (if links
10641 (dolist (link (if (stringp links) (list links) links))
10642 (search-forward link nil links-end)
10643 (goto-char (match-beginning 0))
10644 (org-open-at-point))
10645 (require 'org-attach)
10646 (org-attach-reveal 'if-exists))))
10647 ;; On a clock line, make sure point is on the timestamp
10648 ;; before opening it.
10649 ((and (eq type 'clock)
10650 value
10651 (>= (point) (org-element-property :begin value))
10652 (<= (point) (org-element-property :end value)))
10653 (org-follow-timestamp-link))
10654 ;; Do nothing on white spaces after an object.
10655 ((>= (point)
10656 (save-excursion
10657 (goto-char (org-element-property :end context))
10658 (skip-chars-backward " \t")
10659 (point)))
10660 (user-error "No link found"))
10661 ((eq type 'timestamp) (org-follow-timestamp-link))
10662 ;; On tags within a headline or an inlinetask.
10663 ((and (memq type '(headline inlinetask))
10664 (progn (save-excursion (beginning-of-line)
10665 (looking-at org-complex-heading-regexp))
10666 (and (match-beginning 5)
10667 (>= (point) (match-beginning 5)))))
10668 (org-tags-view arg (substring (match-string 5) 0 -1)))
10669 ((eq type 'link)
10670 ;; When link is located within the description of another
10671 ;; link (e.g., an inline image), always open the parent
10672 ;; link.
10673 (let*((link (let ((up (org-element-property :parent context)))
10674 (if (eq (org-element-type up) 'link) up context)))
10675 (type (org-element-property :type link))
10676 (path (org-link-unescape (org-element-property :path link))))
10677 ;; Switch back to REFERENCE-BUFFER needed when called in
10678 ;; a temporary buffer through `org-open-link-from-string'.
10679 (with-current-buffer (or reference-buffer (current-buffer))
10680 (cond
10681 ((equal type "file")
10682 (if (string-match "[*?{]" (file-name-nondirectory path))
10683 (dired path)
10684 ;; Look into `org-link-protocols' in order to find
10685 ;; a DEDICATED-FUNCTION to open file. The function
10686 ;; will be applied on raw link instead of parsed
10687 ;; link due to the limitation in `org-add-link-type'
10688 ;; ("open" function called with a single argument).
10689 ;; If no such function is found, fallback to
10690 ;; `org-open-file'.
10692 ;; Note : "file+emacs" and "file+sys" types are
10693 ;; hard-coded in order to escape the previous
10694 ;; limitation.
10695 (let* ((option (org-element-property :search-option link))
10696 (app (org-element-property :application link))
10697 (dedicated-function
10698 (nth 1 (assoc app org-link-protocols))))
10699 (if dedicated-function
10700 (funcall dedicated-function
10701 (concat path
10702 (and option (concat "::" option))))
10703 (apply #'org-open-file
10704 path
10705 (cond (arg)
10706 ((equal app "emacs") 'emacs)
10707 ((equal app "sys") 'system))
10708 (cond ((not option) nil)
10709 ((org-string-match-p "\\`[0-9]+\\'" option)
10710 (list (string-to-number option)))
10711 (t (list nil
10712 (org-link-unescape option)))))))))
10713 ((assoc type org-link-protocols)
10714 (funcall (nth 1 (assoc type org-link-protocols)) path))
10715 ((equal type "help")
10716 (let ((f-or-v (intern path)))
10717 (cond ((fboundp f-or-v) (describe-function f-or-v))
10718 ((boundp f-or-v) (describe-variable f-or-v))
10719 (t (error "Not a known function or variable")))))
10720 ((member type '("http" "https" "ftp" "mailto" "news"))
10721 (browse-url (org-link-escape-browser (concat type ":" path))))
10722 ((equal type "doi")
10723 (browse-url
10724 (org-link-escape-browser (concat org-doi-server-url path))))
10725 ((equal type "message") (browse-url (concat type ":" path)))
10726 ((equal type "shell")
10727 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10728 (cmd path))
10729 (if (or (and (org-string-nw-p
10730 org-confirm-shell-link-not-regexp)
10731 (string-match
10732 org-confirm-shell-link-not-regexp cmd))
10733 (not org-confirm-shell-link-function)
10734 (funcall org-confirm-shell-link-function
10735 (format "Execute \"%s\" in shell? "
10736 (org-add-props cmd nil
10737 'face 'org-warning))))
10738 (progn
10739 (message "Executing %s" cmd)
10740 (shell-command cmd buf)
10741 (when (featurep 'midnight)
10742 (setq clean-buffer-list-kill-buffer-names
10743 (cons (buffer-name buf)
10744 clean-buffer-list-kill-buffer-names))))
10745 (user-error "Abort"))))
10746 ((equal type "elisp")
10747 (let ((cmd path))
10748 (if (or (and (org-string-nw-p
10749 org-confirm-elisp-link-not-regexp)
10750 (org-string-match-p
10751 org-confirm-elisp-link-not-regexp cmd))
10752 (not org-confirm-elisp-link-function)
10753 (funcall org-confirm-elisp-link-function
10754 (format "Execute \"%s\" as elisp? "
10755 (org-add-props cmd nil
10756 'face 'org-warning))))
10757 (message "%s => %s" cmd
10758 (if (eq (string-to-char cmd) ?\()
10759 (eval (read cmd))
10760 (call-interactively (read cmd))))
10761 (user-error "Abort"))))
10762 ((equal type "id")
10763 (require 'org-id)
10764 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10765 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10766 (unless (run-hook-with-args-until-success
10767 'org-open-link-functions path)
10768 (if (not arg) (org-mark-ring-push)
10769 (switch-to-buffer-other-window
10770 (org-get-buffer-for-internal-link (current-buffer))))
10771 (let ((destination
10772 (org-with-wide-buffer
10773 (if (equal type "radio")
10774 (org-search-radio-target
10775 (org-element-property :path link))
10776 (org-link-search
10777 (if (member type '("custom-id" "coderef"))
10778 (org-element-property :raw-link link)
10779 path)
10780 ;; Prevent fuzzy links from matching
10781 ;; themselves.
10782 (and (equal type "fuzzy")
10783 (+ 2 (org-element-property :begin link)))))
10784 (point))))
10785 (unless (and (<= (point-min) destination)
10786 (>= (point-max) destination))
10787 (widen))
10788 (goto-char destination))))
10789 (t (browse-url-at-point))))))
10790 ;; On a footnote reference or at a footnote definition's label.
10791 ((or (eq type 'footnote-reference)
10792 (and (eq type 'footnote-definition)
10793 (save-excursion
10794 ;; Do not validate action when point is on the
10795 ;; spaces right after the footnote label, in
10796 ;; order to be on par with behaviour on links.
10797 (skip-chars-forward " \t")
10798 (let ((begin
10799 (org-element-property :contents-begin context)))
10800 (if begin (< (point) begin)
10801 (= (org-element-property :post-affiliated context)
10802 (line-beginning-position)))))))
10803 (org-footnote-action))
10804 (t (user-error "No link found")))))
10805 (run-hook-with-args 'org-follow-link-hook)))
10807 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10808 "Offer links in the current entry and return the selected link.
10809 If there is only one link, return it.
10810 If NTH is an integer, return the NTH link found.
10811 If ZERO is a string, check also this string for a link, and if
10812 there is one, return it."
10813 (with-current-buffer buffer
10814 (save-excursion
10815 (save-restriction
10816 (widen)
10817 (goto-char marker)
10818 (let ((cnt ?0)
10819 have-zero end links link c)
10820 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10821 (push (match-string 0 zero) links)
10822 (setq cnt (1- cnt) have-zero t))
10823 (save-excursion
10824 (org-back-to-heading t)
10825 (setq end (save-excursion (outline-next-heading) (point)))
10826 (while (re-search-forward org-any-link-re end t)
10827 (push (match-string 0) links))
10828 (setq links (org-uniquify (reverse links))))
10829 (cond
10830 ((null links)
10831 (message "No links"))
10832 ((equal (length links) 1)
10833 (setq link (car links)))
10834 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10835 (setq link (nth (if have-zero nth (1- nth)) links)))
10836 (t ; we have to select a link
10837 (save-excursion
10838 (save-window-excursion
10839 (delete-other-windows)
10840 (with-output-to-temp-buffer "*Select Link*"
10841 (dolist (l links)
10842 (cond
10843 ((not (string-match org-bracket-link-regexp l))
10844 (princ (format "[%c] %s\n" (incf cnt)
10845 (org-remove-angle-brackets l))))
10846 ((match-end 3)
10847 (princ (format "[%c] %s (%s)\n" (incf cnt)
10848 (match-string 3 l) (match-string 1 l))))
10849 (t (princ (format "[%c] %s\n" (incf cnt)
10850 (match-string 1 l)))))))
10851 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10852 (message "Select link to open, RET to open all:")
10853 (setq c (read-char-exclusive))
10854 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10855 (when (equal c ?q) (user-error "Abort"))
10856 (if (equal c ?\C-m)
10857 (setq link links)
10858 (setq nth (- c ?0))
10859 (when have-zero (setq nth (1+ nth)))
10860 (unless (and (integerp nth) (>= (length links) nth))
10861 (user-error "Invalid link selection"))
10862 (setq link (nth (1- nth) links)))))
10863 (cons link end))))))
10865 ;; TODO: These functions are deprecated since `org-open-at-point'
10866 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10867 (defun org-open-file-with-system (path)
10868 "Open file at PATH using the system way of opening it."
10869 (org-open-file path 'system))
10870 (defun org-open-file-with-emacs (path)
10871 "Open file at PATH in Emacs."
10872 (org-open-file path 'emacs))
10875 ;;; File search
10877 (defvar org-create-file-search-functions nil
10878 "List of functions to construct the right search string for a file link.
10879 These functions are called in turn with point at the location to
10880 which the link should point.
10882 A function in the hook should first test if it would like to
10883 handle this file type, for example by checking the `major-mode'
10884 or the file extension. If it decides not to handle this file, it
10885 should just return nil to give other functions a chance. If it
10886 does handle the file, it must return the search string to be used
10887 when following the link. The search string will be part of the
10888 file link, given after a double colon, and `org-open-at-point'
10889 will automatically search for it. If special measures must be
10890 taken to make the search successful, another function should be
10891 added to the companion hook `org-execute-file-search-functions',
10892 which see.
10894 A function in this hook may also use `setq' to set the variable
10895 `description' to provide a suggestion for the descriptive text to
10896 be used for this link when it gets inserted into an Org-mode
10897 buffer with \\[org-insert-link].")
10899 (defvar org-execute-file-search-functions nil
10900 "List of functions to execute a file search triggered by a link.
10902 Functions added to this hook must accept a single argument, the
10903 search string that was part of the file link, the part after the
10904 double colon. The function must first check if it would like to
10905 handle this search, for example by checking the `major-mode' or
10906 the file extension. If it decides not to handle this search, it
10907 should just return nil to give other functions a chance. If it
10908 does handle the search, it must return a non-nil value to keep
10909 other functions from trying.
10911 Each function can access the current prefix argument through the
10912 variable `current-prefix-arg'. Note that a single prefix is used
10913 to force opening a link in Emacs, so it may be good to only use a
10914 numeric or double prefix to guide the search function.
10916 In case this is needed, a function in this hook can also restore
10917 the window configuration before `org-open-at-point' was called using:
10919 (set-window-configuration org-window-config-before-follow-link)")
10921 (defun org-search-radio-target (target)
10922 "Search a radio target matching TARGET in current buffer.
10923 White spaces are not significant."
10924 (let ((re (format "<<<%s>>>"
10925 (mapconcat #'regexp-quote
10926 (org-split-string target "[ \t\n]+")
10927 "[ \t]+\\(?:\n[ \t]*\\)?")))
10928 (origin (point)))
10929 (goto-char (point-min))
10930 (catch :radio-match
10931 (while (re-search-forward re nil t)
10932 (backward-char)
10933 (let ((object (org-element-context)))
10934 (when (eq (org-element-type object) 'radio-target)
10935 (goto-char (org-element-property :begin object))
10936 (org-show-context 'link-search)
10937 (throw :radio-match nil))))
10938 (goto-char origin)
10939 (user-error "No match for radio target: %s" target))))
10941 (defun org-link-search (s &optional avoid-pos stealth)
10942 "Search for a search string S.
10944 If S starts with \"#\", it triggers a custom ID search.
10946 If S is enclosed within parenthesis, it initiates a coderef
10947 search.
10949 If S is surrounded by forward slashes, it is interpreted as
10950 a regular expression. In Org mode files, this will create an
10951 `org-occur' sparse tree. In ordinary files, `occur' will be used
10952 to list matches. If the current buffer is in `dired-mode', grep
10953 will be used to search in all files.
10955 When AVOID-POS is given, ignore matches near that position.
10957 When optional argument STEALTH is non-nil, do not modify
10958 visibility around point, thus ignoring `org-show-context-detail'
10959 variable.
10961 Search is case-insensitive and ignores white spaces. Return type
10962 of matched result, with is either `dedicated' or `fuzzy'."
10963 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10964 (let* ((case-fold-search t)
10965 (origin (point))
10966 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10967 (words (org-split-string s "[ \t\n]+"))
10968 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10969 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10970 type)
10971 (cond
10972 ;; Check if there are any special search functions.
10973 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10974 ((eq (string-to-char s) ?#)
10975 ;; Look for a custom ID S if S starts with "#".
10976 (let* ((id (substring normalized 1))
10977 (match (org-find-property "CUSTOM_ID" id)))
10978 (if match (progn (goto-char match) (setf type 'dedicated))
10979 (error "No match for custom ID: %s" id))))
10980 ((string-match "\\`(\\(.*\\))\\'" normalized)
10981 ;; Look for coderef targets if S is enclosed within parenthesis.
10982 (let ((coderef (match-string-no-properties 1 normalized))
10983 (re (substring s-single-re 1 -1)))
10984 (goto-char (point-min))
10985 (catch :coderef-match
10986 (while (re-search-forward re nil t)
10987 (let ((element (org-element-at-point)))
10988 (when (and (memq (org-element-type element)
10989 '(example-block src-block))
10990 ;; Build proper regexp according to current
10991 ;; block's label format.
10992 (let ((label-fmt
10993 (regexp-quote
10994 (or (org-element-property :label-fmt element)
10995 org-coderef-label-format))))
10996 (save-excursion
10997 (beginning-of-line)
10998 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10999 (format label-fmt coderef))))))
11000 (setq type 'dedicated)
11001 (goto-char (match-beginning 1))
11002 (throw :coderef-match nil))))
11003 (goto-char origin)
11004 (error "No match for coderef: %s" coderef))))
11005 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11006 ;; Look for a regular expression.
11007 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11008 (match-string 1 s)))
11009 ;; Fuzzy links.
11011 (let ((starred (eq (string-to-char normalized) ?*)))
11012 (cond
11013 ;; Look for targets, only if not in a headline search.
11014 ((and (not starred)
11015 (let ((target (format "<<%s>>" s-multi-re)))
11016 (catch :target-match
11017 (goto-char (point-min))
11018 (while (re-search-forward target nil t)
11019 (backward-char)
11020 (let ((context (org-element-context)))
11021 (when (eq (org-element-type context) 'target)
11022 (setq type 'dedicated)
11023 (goto-char (org-element-property :begin context))
11024 (throw :target-match t))))
11025 nil))))
11026 ;; Look for elements named after S, only if not in a headline
11027 ;; search.
11028 ((and (not starred)
11029 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11030 (catch :name-match
11031 (goto-char (point-min))
11032 (while (re-search-forward name nil t)
11033 (let ((element (org-element-at-point)))
11034 (when (equal (org-split-string
11035 (org-element-property :name element)
11036 "[ \t]+")
11037 words)
11038 (setq type 'dedicated)
11039 (beginning-of-line)
11040 (throw :name-match t))))
11041 nil))))
11042 ;; Regular text search. Prefer headlines in Org mode
11043 ;; buffers.
11044 ((and (derived-mode-p 'org-mode)
11045 (let* ((wspace "[ \t]")
11046 (wspaceopt (concat wspace "*"))
11047 (cookie (concat "\\(?:"
11048 wspaceopt
11049 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11050 wspaceopt
11051 "\\)"))
11052 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11053 (re (concat
11054 org-outline-regexp-bol
11055 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11056 "\\(?:\\[#.\\][ \t]+\\)?"
11057 "\\(?:" org-comment-string "[ \t]+\\)?"
11058 sep "?"
11059 (let ((title (mapconcat #'regexp-quote
11060 words
11061 sep)))
11062 (if starred (substring title 1) title))
11063 sep "?"
11064 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11065 "[ \t]*$")))
11066 (goto-char (point-min))
11067 (re-search-forward re nil t)))
11068 (goto-char (match-beginning 0))
11069 (setq type 'dedicated))
11070 ;; Offer to create non-existent headline depending on
11071 ;; `org-link-search-must-match-exact-headline'.
11072 ((and (derived-mode-p 'org-mode)
11073 (not org-link-search-inhibit-query)
11074 (eq org-link-search-must-match-exact-headline 'query-to-create)
11075 (yes-or-no-p "No match - create this as a new heading? "))
11076 (goto-char (point-max))
11077 (unless (bolp) (newline))
11078 (org-insert-heading nil t t)
11079 (insert s "\n")
11080 (beginning-of-line 0))
11081 ;; Only headlines are looked after. No need to process
11082 ;; further: throw an error.
11083 ((and (derived-mode-p 'org-mode)
11084 (or starred org-link-search-must-match-exact-headline))
11085 (goto-char origin)
11086 (error "No match for fuzzy expression: %s" normalized))
11087 ;; Regular text search.
11088 ((catch :fuzzy-match
11089 (goto-char (point-min))
11090 (while (re-search-forward s-multi-re nil t)
11091 ;; Skip match if it contains AVOID-POS or it is included
11092 ;; in a link with a description but outside the
11093 ;; description.
11094 (unless (or (and avoid-pos
11095 (<= (match-beginning 0) avoid-pos)
11096 (> (match-end 0) avoid-pos))
11097 (and (save-match-data
11098 (org-in-regexp org-bracket-link-regexp))
11099 (match-beginning 3)
11100 (or (> (match-beginning 3) (point))
11101 (<= (match-end 3) (point)))
11102 (org-element-lineage
11103 (save-match-data (org-element-context))
11104 '(link) t)))
11105 (goto-char (match-beginning 0))
11106 (setq type 'fuzzy)
11107 (throw :fuzzy-match t)))
11108 nil))
11109 ;; All failed. Throw an error.
11110 (t (goto-char origin)
11111 (error "No match for fuzzy expression: %s" normalized))))))
11112 ;; Disclose surroundings of match, if appropriate.
11113 (when (and (derived-mode-p 'org-mode) (not stealth))
11114 (org-show-context 'link-search))
11115 type))
11117 (defun org-get-buffer-for-internal-link (buffer)
11118 "Return a buffer to be used for displaying the link target of internal links."
11119 (cond
11120 ((not org-display-internal-link-with-indirect-buffer)
11121 buffer)
11122 ((string-match "(Clone)$" (buffer-name buffer))
11123 (message "Buffer is already a clone, not making another one")
11124 ;; we also do not modify visibility in this case
11125 buffer)
11126 (t ; make a new indirect buffer for displaying the link
11127 (let* ((bn (buffer-name buffer))
11128 (ibn (concat bn "(Clone)"))
11129 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11130 (with-current-buffer ib (org-overview))
11131 ib))))
11133 (defun org-do-occur (regexp &optional cleanup)
11134 "Call the Emacs command `occur'.
11135 If CLEANUP is non-nil, remove the printout of the regular expression
11136 in the *Occur* buffer. This is useful if the regex is long and not useful
11137 to read."
11138 (occur regexp)
11139 (when cleanup
11140 (let ((cwin (selected-window)) win beg end)
11141 (when (setq win (get-buffer-window "*Occur*"))
11142 (select-window win))
11143 (goto-char (point-min))
11144 (when (re-search-forward "match[a-z]+" nil t)
11145 (setq beg (match-end 0))
11146 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11147 (setq end (1- (match-beginning 0)))))
11148 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11149 (goto-char (point-min))
11150 (select-window cwin))))
11152 ;;; The mark ring for links jumps
11154 (defvar org-mark-ring nil
11155 "Mark ring for positions before jumps in Org-mode.")
11156 (defvar org-mark-ring-last-goto nil
11157 "Last position in the mark ring used to go back.")
11158 ;; Fill and close the ring
11159 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11160 (loop for i from 1 to org-mark-ring-length do
11161 (push (make-marker) org-mark-ring))
11162 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11163 org-mark-ring)
11165 (defun org-mark-ring-push (&optional pos buffer)
11166 "Put the current position or POS into the mark ring and rotate it."
11167 (interactive)
11168 (setq pos (or pos (point)))
11169 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11170 (move-marker (car org-mark-ring)
11171 (or pos (point))
11172 (or buffer (current-buffer)))
11173 (message "%s"
11174 (substitute-command-keys
11175 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11177 (defun org-mark-ring-goto (&optional n)
11178 "Jump to the previous position in the mark ring.
11179 With prefix arg N, jump back that many stored positions. When
11180 called several times in succession, walk through the entire ring.
11181 Org-mode commands jumping to a different position in the current file,
11182 or to another Org-mode file, automatically push the old position
11183 onto the ring."
11184 (interactive "p")
11185 (let (p m)
11186 (if (eq last-command this-command)
11187 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11188 (setq p org-mark-ring))
11189 (setq org-mark-ring-last-goto p)
11190 (setq m (car p))
11191 (org-pop-to-buffer-same-window (marker-buffer m))
11192 (goto-char m)
11193 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11195 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11196 ;;; Emacs 24.4+
11197 (defun org-remove-angle-brackets (s)
11198 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11199 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11201 (defun org-add-angle-brackets (s)
11202 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11203 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11205 (defun org-remove-double-quotes (s)
11206 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11207 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11210 ;;; Following specific links
11212 (defun org-follow-timestamp-link ()
11213 "Open an agenda view for the time-stamp date/range at point."
11214 (cond
11215 ((org-at-date-range-p t)
11216 (let ((org-agenda-start-on-weekday)
11217 (t1 (match-string 1))
11218 (t2 (match-string 2)) tt1 tt2)
11219 (setq tt1 (time-to-days (org-time-string-to-time t1))
11220 tt2 (time-to-days (org-time-string-to-time t2)))
11221 (let ((org-agenda-buffer-tmp-name
11222 (format "*Org Agenda(a:%s)"
11223 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11224 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11225 ((org-at-timestamp-p t)
11226 (let ((org-agenda-buffer-tmp-name
11227 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11228 (org-agenda-list nil (time-to-days (org-time-string-to-time
11229 (substring (match-string 1) 0 10)))
11230 1)))
11231 (t (error "This should not happen"))))
11234 ;;; Following file links
11235 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11236 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11237 (declare-function mailcap-mime-info
11238 "mailcap" (string &optional request no-decode))
11239 (defvar org-wait nil)
11240 (defun org-open-file (path &optional in-emacs line search)
11241 "Open the file at PATH.
11242 First, this expands any special file name abbreviations. Then the
11243 configuration variable `org-file-apps' is checked if it contains an
11244 entry for this file type, and if yes, the corresponding command is launched.
11246 If no application is found, Emacs simply visits the file.
11248 With optional prefix argument IN-EMACS, Emacs will visit the file.
11249 With a double \\[universal-argument] \\[universal-argument] \
11250 prefix arg, Org tries to avoid opening in Emacs
11251 and to use an external application to visit the file.
11253 Optional LINE specifies a line to go to, optional SEARCH a string
11254 to search for. If LINE or SEARCH is given, the file will be
11255 opened in Emacs, unless an entry from org-file-apps that makes
11256 use of groups in a regexp matches.
11258 If you want to change the way frames are used when following a
11259 link, please customize `org-link-frame-setup'.
11261 If the file does not exist, an error is thrown."
11262 (let* ((file (if (equal path "")
11263 buffer-file-name
11264 (substitute-in-file-name (expand-file-name path))))
11265 (file-apps (append org-file-apps (org-default-apps)))
11266 (apps (cl-remove-if
11267 'org-file-apps-entry-match-against-dlink-p file-apps))
11268 (apps-dlink (cl-remove-if-not
11269 'org-file-apps-entry-match-against-dlink-p file-apps))
11270 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11271 (dirp (unless remp (file-directory-p file)))
11272 (file (if (and dirp org-open-directory-means-index-dot-org)
11273 (concat (file-name-as-directory file) "index.org")
11274 file))
11275 (a-m-a-p (assq 'auto-mode apps))
11276 (dfile (downcase file))
11277 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11278 (link (cond ((and (eq line nil)
11279 (eq search nil))
11280 file)
11281 (line
11282 (concat file "::" (number-to-string line)))
11283 (search
11284 (concat file "::" search))))
11285 (dlink (downcase link))
11286 (old-buffer (current-buffer))
11287 (old-pos (point))
11288 (old-mode major-mode)
11289 ext cmd link-match-data)
11290 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11291 (setq ext (match-string 1 dfile))
11292 (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11293 (setq ext (match-string 1 dfile))))
11294 (cond
11295 ((member in-emacs '((16) system))
11296 (setq cmd (cdr (assoc 'system apps))))
11297 (in-emacs (setq cmd 'emacs))
11299 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11300 (and dirp (cdr (assoc 'directory apps)))
11301 ; first, try matching against apps-dlink
11302 ; if we get a match here, store the match data for later
11303 (let ((match (assoc-default dlink apps-dlink
11304 'string-match)))
11305 (if match
11306 (progn (setq link-match-data (match-data))
11307 match)
11308 (progn (setq in-emacs (or in-emacs line search))
11309 nil))) ; if we have no match in apps-dlink,
11310 ; always open the file in emacs if line or search
11311 ; is given (for backwards compatibility)
11312 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11313 'string-match)
11314 (cdr (assoc ext apps))
11315 (cdr (assoc t apps))))))
11316 (when (eq cmd 'system)
11317 (setq cmd (cdr (assoc 'system apps))))
11318 (when (eq cmd 'default)
11319 (setq cmd (cdr (assoc t apps))))
11320 (when (eq cmd 'mailcap)
11321 (require 'mailcap)
11322 (mailcap-parse-mailcaps)
11323 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11324 (command (mailcap-mime-info mime-type)))
11325 (if (stringp command)
11326 (setq cmd command)
11327 (setq cmd 'emacs))))
11328 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11329 (not (file-exists-p file))
11330 (not org-open-non-existing-files))
11331 (user-error "No such file: %s" file))
11332 (cond
11333 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11334 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11335 (while (string-match "['\"]%s['\"]" cmd)
11336 (setq cmd (replace-match "%s" t t cmd)))
11337 (while (string-match "%s" cmd)
11338 (setq cmd (replace-match
11339 (save-match-data
11340 (shell-quote-argument
11341 (convert-standard-filename file)))
11342 t t cmd)))
11344 ;; Replace "%1", "%2" etc. in command with group matches from regex
11345 (save-match-data
11346 (let ((match-index 1)
11347 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11348 (set-match-data link-match-data)
11349 (while (<= match-index number-of-groups)
11350 (let ((regex (concat "%" (number-to-string match-index)))
11351 (replace-with (match-string match-index dlink)))
11352 (while (string-match regex cmd)
11353 (setq cmd (replace-match replace-with t t cmd))))
11354 (setq match-index (+ match-index 1)))))
11356 (save-window-excursion
11357 (message "Running %s...done" cmd)
11358 (start-process-shell-command cmd nil cmd)
11359 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11360 ((or (stringp cmd)
11361 (eq cmd 'emacs))
11362 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11363 (widen)
11364 (if line (progn (org-goto-line line)
11365 (when (derived-mode-p 'org-mode)
11366 (org-reveal)))
11367 (when search (org-link-search search))))
11368 ((consp cmd)
11369 (save-match-data
11370 (set-match-data link-match-data)
11371 (eval cmd `((file . ,(convert-standard-filename file))))))
11372 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11373 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11374 (or (not (equal old-buffer (current-buffer)))
11375 (not (equal old-pos (point))))
11376 (org-mark-ring-push old-pos old-buffer))))
11378 (defun org-file-apps-entry-match-against-dlink-p (entry)
11379 "This function returns non-nil if `entry' uses a regular
11380 expression which should be matched against the whole link by
11381 org-open-file.
11383 It assumes that is the case when the entry uses a regular
11384 expression which has at least one grouping construct and the
11385 action is either a lisp form or a command string containing
11386 `%1', i.e. using at least one subexpression match as a
11387 parameter."
11388 (let ((selector (car entry))
11389 (action (cdr entry)))
11390 (if (stringp selector)
11391 (and (> (regexp-opt-depth selector) 0)
11392 (or (and (stringp action)
11393 (string-match "%[0-9]" action))
11394 (consp action)))
11395 nil)))
11397 (defun org-default-apps ()
11398 "Return the default applications for this operating system."
11399 (cond
11400 ((eq system-type 'darwin)
11401 org-file-apps-defaults-macosx)
11402 ((eq system-type 'windows-nt)
11403 org-file-apps-defaults-windowsnt)
11404 (t org-file-apps-defaults-gnu)))
11406 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11407 "Convert extensions to regular expressions in the cars of LIST.
11408 Also, weed out any non-string entries, because the return value is used
11409 only for regexp matching.
11410 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11411 point to the symbol `emacs', indicating that the file should
11412 be opened in Emacs."
11413 (append
11414 (delq nil
11415 (mapcar (lambda (x)
11416 (unless (not (stringp (car x)))
11417 (if (string-match "\\W" (car x))
11419 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11420 list))
11421 (when add-auto-mode
11422 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11424 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11425 (defun org-file-remote-p (file)
11426 "Test whether FILE specifies a location on a remote system.
11427 Return non-nil if the location is indeed remote.
11429 For example, the filename \"/user@host:/foo\" specifies a location
11430 on the system \"/user@host:\"."
11431 (cond ((fboundp 'file-remote-p)
11432 (file-remote-p file))
11433 ((fboundp 'tramp-handle-file-remote-p)
11434 (tramp-handle-file-remote-p file))
11435 ((and (boundp 'ange-ftp-name-format)
11436 (string-match (car ange-ftp-name-format) file))
11437 t)))
11440 ;;;; Refiling
11442 (defun org-get-org-file ()
11443 "Read a filename, with default directory `org-directory'."
11444 (let ((default (or org-default-notes-file remember-data-file)))
11445 (read-file-name (format "File name [%s]: " default)
11446 (file-name-as-directory org-directory)
11447 default)))
11449 (defun org-notes-order-reversed-p ()
11450 "Check if the current file should receive notes in reversed order."
11451 (cond
11452 ((not org-reverse-note-order) nil)
11453 ((eq t org-reverse-note-order) t)
11454 ((not (listp org-reverse-note-order)) nil)
11455 (t (catch 'exit
11456 (dolist (entry org-reverse-note-order)
11457 (when (string-match (car entry) buffer-file-name)
11458 (throw 'exit (cdr entry))))))))
11460 (defvar org-refile-target-table nil
11461 "The list of refile targets, created by `org-refile'.")
11463 (defvar org-agenda-new-buffers nil
11464 "Buffers created to visit agenda files.")
11466 (defvar org-refile-cache nil
11467 "Cache for refile targets.")
11469 (defvar org-refile-markers nil
11470 "All the markers used for caching refile locations.")
11472 (defun org-refile-marker (pos)
11473 "Get a new refile marker, but only if caching is in use."
11474 (if (not org-refile-use-cache)
11476 (let ((m (make-marker)))
11477 (move-marker m pos)
11478 (push m org-refile-markers)
11479 m)))
11481 (defun org-refile-cache-clear ()
11482 "Clear the refile cache and disable all the markers."
11483 (dolist (m org-refile-markers) (move-marker m nil))
11484 (setq org-refile-markers nil)
11485 (setq org-refile-cache nil)
11486 (message "Refile cache has been cleared"))
11488 (defun org-refile-cache-check-set (set)
11489 "Check if all the markers in the cache still have live buffers."
11490 (let (marker)
11491 (catch 'exit
11492 (while (and set (setq marker (nth 3 (pop set))))
11493 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11494 (when (and marker (null (marker-buffer marker)))
11495 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11496 (sit-for 3)
11497 (throw 'exit nil)))
11498 t)))
11500 (defun org-refile-cache-put (set &rest identifiers)
11501 "Push the refile targets SET into the cache, under IDENTIFIERS."
11502 (let* ((key (sha1 (prin1-to-string identifiers)))
11503 (entry (assoc key org-refile-cache)))
11504 (if entry
11505 (setcdr entry set)
11506 (push (cons key set) org-refile-cache))))
11508 (defun org-refile-cache-get (&rest identifiers)
11509 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11510 (cond
11511 ((not org-refile-cache) nil)
11512 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11514 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11515 org-refile-cache))))
11516 (and set (org-refile-cache-check-set set) set)))))
11518 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11519 "Produce a table with refile targets."
11520 (let ((case-fold-search nil)
11521 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11522 (entries (or org-refile-targets '((nil . (:level . 1)))))
11523 targets tgs txt re files desc descre fast-path-p level pos0)
11524 (message "Getting targets...")
11525 (with-current-buffer (or default-buffer (current-buffer))
11526 (dolist (entry entries)
11527 (setq files (car entry) desc (cdr entry))
11528 (setq fast-path-p nil)
11529 (cond
11530 ((null files) (setq files (list (current-buffer))))
11531 ((eq files 'org-agenda-files)
11532 (setq files (org-agenda-files 'unrestricted)))
11533 ((and (symbolp files) (fboundp files))
11534 (setq files (funcall files)))
11535 ((and (symbolp files) (boundp files))
11536 (setq files (symbol-value files))))
11537 (when (stringp files) (setq files (list files)))
11538 (cond
11539 ((eq (car desc) :tag)
11540 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11541 ((eq (car desc) :todo)
11542 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11543 ((eq (car desc) :regexp)
11544 (setq descre (cdr desc)))
11545 ((eq (car desc) :level)
11546 (setq descre (concat "^\\*\\{" (number-to-string
11547 (if org-odd-levels-only
11548 (1- (* 2 (cdr desc)))
11549 (cdr desc)))
11550 "\\}[ \t]")))
11551 ((eq (car desc) :maxlevel)
11552 (setq fast-path-p t)
11553 (setq descre (concat "^\\*\\{1," (number-to-string
11554 (if org-odd-levels-only
11555 (1- (* 2 (cdr desc)))
11556 (cdr desc)))
11557 "\\}[ \t]")))
11558 (t (error "Bad refiling target description %s" desc)))
11559 (dolist (f files)
11560 (with-current-buffer
11561 (if (bufferp f) f (org-get-agenda-file-buffer f))
11563 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11564 (progn
11565 (when (bufferp f) (setq f (buffer-file-name
11566 (buffer-base-buffer f))))
11567 (setq f (and f (expand-file-name f)))
11568 (when (eq org-refile-use-outline-path 'file)
11569 (push (list (file-name-nondirectory f) f nil nil) tgs))
11570 (save-excursion
11571 (save-restriction
11572 (widen)
11573 (goto-char (point-min))
11574 (while (re-search-forward descre nil t)
11575 (goto-char (setq pos0 (point-at-bol)))
11576 (catch 'next
11577 (when org-refile-target-verify-function
11578 (save-match-data
11579 (or (funcall org-refile-target-verify-function)
11580 (throw 'next t))))
11581 (when (and (looking-at org-complex-heading-regexp)
11582 (not (member (match-string 4) excluded-entries))
11583 (match-string 4))
11584 (setq level (org-reduced-level
11585 (- (match-end 1) (match-beginning 1)))
11586 txt (org-link-display-format (match-string 4))
11587 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11588 re (format org-complex-heading-regexp-format
11589 (regexp-quote (match-string 4))))
11590 (when org-refile-use-outline-path
11591 (setq txt (mapconcat
11592 'org-protect-slash
11593 (append
11594 (if (eq org-refile-use-outline-path
11595 'file)
11596 (list (file-name-nondirectory
11597 (buffer-file-name
11598 (buffer-base-buffer))))
11599 (when (eq org-refile-use-outline-path
11600 'full-file-path)
11601 (list (buffer-file-name
11602 (buffer-base-buffer)))))
11603 (org-get-outline-path fast-path-p
11604 level txt)
11605 (list txt))
11606 "/")))
11607 (push (list txt f re (org-refile-marker (point)))
11608 tgs)))
11609 (when (= (point) pos0)
11610 ;; verification function has not moved point
11611 (goto-char (point-at-eol))))))))
11612 (when org-refile-use-cache
11613 (org-refile-cache-put tgs (buffer-file-name) descre))
11614 (setq targets (append tgs targets))))))
11615 (message "Getting targets...done")
11616 (nreverse targets)))
11618 (defun org-protect-slash (s)
11619 (while (string-match "/" s)
11620 (setq s (replace-match "\\" t t s)))
11623 (defvar org-olpa (make-vector 20 nil))
11625 (defun org-get-outline-path (&optional fastp level heading)
11626 "Return the outline path to the current entry, as a list.
11628 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11629 routine which makes outline path derivations for an entire file,
11630 avoiding backtracing. Refile target collection makes use of that."
11631 (if fastp
11632 (progn
11633 (when (> level 19)
11634 (error "Outline path failure, more than 19 levels"))
11635 (loop for i from level upto 19 do
11636 (aset org-olpa i nil))
11637 (prog1
11638 (delq nil (append org-olpa nil))
11639 (aset org-olpa level heading)))
11640 (let (rtn case-fold-search)
11641 (save-excursion
11642 (save-restriction
11643 (widen)
11644 (while (org-up-heading-safe)
11645 (when (looking-at org-complex-heading-regexp)
11646 (push (org-trim
11647 (replace-regexp-in-string
11648 ;; Remove statistical/checkboxes cookies
11649 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11650 (org-match-string-no-properties 4)))
11651 rtn)))
11652 rtn)))))
11654 (defun org-format-outline-path (path &optional width prefix separator)
11655 "Format the outline path PATH for display.
11656 WIDTH is the maximum number of characters that is available.
11657 PREFIX is a prefix to be included in the returned string,
11658 such as the file name.
11659 SEPARATOR is inserted between the different parts of the path,
11660 the default is \"/\"."
11661 (setq width (or width 79))
11662 (setq path (delq nil path))
11663 (unless (> width 0)
11664 (user-error "Argument `width' must be positive"))
11665 (setq separator (or separator "/"))
11666 (let* ((org-odd-levels-only nil)
11667 (fpath (concat
11668 prefix (and prefix path separator)
11669 (mapconcat
11670 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11671 (loop for head in path
11672 for n from 0
11673 collect (org-add-props
11674 head nil 'face
11675 (nth (% n org-n-level-faces) org-level-faces)))
11676 separator))))
11677 (when (> (length fpath) width)
11678 (if (< width 7)
11679 ;; It's unlikely that `width' will be this small, but don't
11680 ;; waste characters by adding ".." if it is.
11681 (setq fpath (substring fpath 0 width))
11682 (setf (substring fpath (- width 2)) "..")))
11683 fpath))
11685 (defun org-display-outline-path (&optional file current separator just-return-string)
11686 "Display the current outline path in the echo area.
11688 If FILE is non-nil, prepend the output with the file name.
11689 If CURRENT is non-nil, append the current heading to the output.
11690 SEPARATOR is passed through to `org-format-outline-path'. It separates
11691 the different parts of the path and defaults to \"/\".
11692 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11693 (interactive "P")
11694 (let* (case-fold-search
11695 (bfn (buffer-file-name (buffer-base-buffer)))
11696 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11697 res)
11698 (when current (setq path (append path
11699 (save-excursion
11700 (org-back-to-heading t)
11701 (when (looking-at org-complex-heading-regexp)
11702 (list (match-string 4)))))))
11703 (setq res
11704 (org-format-outline-path
11705 path
11706 (1- (frame-width))
11707 (and file bfn (concat (file-name-nondirectory bfn) separator))
11708 separator))
11709 (if just-return-string
11710 (org-no-properties res)
11711 (org-unlogged-message "%s" res))))
11713 (defvar org-refile-history nil
11714 "History for refiling operations.")
11716 (defvar org-after-refile-insert-hook nil
11717 "Hook run after `org-refile' has inserted its stuff at the new location.
11718 Note that this is still *before* the stuff will be removed from
11719 the *old* location.")
11721 (defvar org-capture-last-stored-marker)
11722 (defvar org-refile-keep nil
11723 "Non-nil means `org-refile' will copy instead of refile.")
11725 (defun org-copy ()
11726 "Like `org-refile', but copy."
11727 (interactive)
11728 (let ((org-refile-keep t))
11729 (funcall 'org-refile nil nil nil "Copy")))
11731 (defun org-refile (&optional arg default-buffer rfloc msg)
11732 "Move the entry or entries at point to another heading.
11733 The list of target headings is compiled using the information in
11734 `org-refile-targets', which see.
11736 At the target location, the entry is filed as a subitem of the
11737 target heading. Depending on `org-reverse-note-order', the new
11738 subitem will either be the first or the last subitem.
11740 If there is an active region, all entries in that region will be
11741 refiled. However, the region must fulfill the requirement that
11742 the first heading sets the top-level of the moved text.
11744 With prefix arg ARG, the command will only visit the target
11745 location and not actually move anything.
11747 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11748 refiling operation has put the subtree.
11750 With a numeric prefix argument of `2', refile to the running clock.
11752 With a numeric prefix argument of `3', emulate `org-refile-keep'
11753 being set to t and copy to the target location, don't move it.
11754 Beware that keeping refiled entries may result in duplicated ID
11755 properties.
11757 RFLOC can be a refile location obtained in a different way.
11759 MSG is a string to replace \"Refile\" in the default prompt with
11760 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11762 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11764 If you are using target caching (see `org-refile-use-cache'), you
11765 have to clear the target cache in order to find new targets.
11766 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11767 prefix argument (`C-u C-u C-u C-c C-w')."
11768 (interactive "P")
11769 (if (member arg '(0 (64)))
11770 (org-refile-cache-clear)
11771 (let* ((actionmsg (cond (msg msg)
11772 ((equal arg 3) "Refile (and keep)")
11773 (t "Refile")))
11774 (regionp (org-region-active-p))
11775 (region-start (and regionp (region-beginning)))
11776 (region-end (and regionp (region-end)))
11777 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11778 pos it nbuf file level reversed)
11779 (setq last-command nil)
11780 (when regionp
11781 (goto-char region-start)
11782 (or (bolp) (goto-char (point-at-bol)))
11783 (setq region-start (point))
11784 (unless (or (org-kill-is-subtree-p
11785 (buffer-substring region-start region-end))
11786 (prog1 org-refile-active-region-within-subtree
11787 (let ((s (point-at-eol)))
11788 (org-toggle-heading)
11789 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11790 (user-error "The region is not a (sequence of) subtree(s)")))
11791 (if (equal arg '(16))
11792 (org-refile-goto-last-stored)
11793 (when (or
11794 (and (equal arg 2)
11795 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11796 (prog1
11797 (setq it (list (or org-clock-heading "running clock")
11798 (buffer-file-name
11799 (marker-buffer org-clock-hd-marker))
11801 (marker-position org-clock-hd-marker)))
11802 (setq arg nil)))
11803 (setq it (or rfloc
11804 (let (heading-text)
11805 (save-excursion
11806 (unless (and arg (listp arg))
11807 (org-back-to-heading t)
11808 (setq heading-text
11809 (replace-regexp-in-string
11810 org-bracket-link-regexp
11811 "\\3"
11812 (nth 4 (org-heading-components)))))
11813 (org-refile-get-location
11814 (cond ((and arg (listp arg)) "Goto")
11815 (regionp (concat actionmsg " region to"))
11816 (t (concat actionmsg " subtree \""
11817 heading-text "\" to")))
11818 default-buffer
11819 (and (not (equal '(4) arg))
11820 org-refile-allow-creating-parent-nodes)
11821 arg))))))
11822 (setq file (nth 1 it)
11823 pos (nth 3 it))
11824 (when (and (not arg)
11826 (equal (buffer-file-name) file)
11827 (if regionp
11828 (and (>= pos region-start)
11829 (<= pos region-end))
11830 (and (>= pos (point))
11831 (< pos (save-excursion
11832 (org-end-of-subtree t t))))))
11833 (error "Cannot refile to position inside the tree or region"))
11834 (setq nbuf (or (find-buffer-visiting file)
11835 (find-file-noselect file)))
11836 (if (and arg (not (equal arg 3)))
11837 (progn
11838 (org-pop-to-buffer-same-window nbuf)
11839 (goto-char pos)
11840 (org-show-context 'org-goto))
11841 (if regionp
11842 (progn
11843 (org-kill-new (buffer-substring region-start region-end))
11844 (org-save-markers-in-region region-start region-end))
11845 (org-copy-subtree 1 nil t))
11846 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11847 (find-file-noselect file)))
11848 (setq reversed (org-notes-order-reversed-p))
11849 (save-excursion
11850 (save-restriction
11851 (widen)
11852 (if pos
11853 (progn
11854 (goto-char pos)
11855 (looking-at org-outline-regexp)
11856 (setq level (org-get-valid-level (funcall outline-level) 1))
11857 (goto-char
11858 (if reversed
11859 (or (outline-next-heading) (point-max))
11860 (or (save-excursion (org-get-next-sibling))
11861 (org-end-of-subtree t t)
11862 (point-max)))))
11863 (setq level 1)
11864 (if (not reversed)
11865 (goto-char (point-max))
11866 (goto-char (point-min))
11867 (or (outline-next-heading) (goto-char (point-max)))))
11868 (unless (bolp) (newline))
11869 (org-paste-subtree level nil nil t)
11870 (when org-log-refile
11871 (org-add-log-setup 'refile nil nil org-log-refile)
11872 (unless (eq org-log-refile 'note)
11873 (save-excursion (org-add-log-note))))
11874 (and org-auto-align-tags
11875 (let ((org-loop-over-headlines-in-active-region nil))
11876 (org-set-tags nil t)))
11877 (let ((bookmark-name (plist-get org-bookmark-names-plist
11878 :last-refile)))
11879 (when bookmark-name
11880 (with-demoted-errors
11881 (bookmark-set bookmark-name))))
11882 ;; If we are refiling for capture, make sure that the
11883 ;; last-capture pointers point here
11884 (when (org-bound-and-true-p org-capture-is-refiling)
11885 (let ((bookmark-name (plist-get org-bookmark-names-plist
11886 :last-capture-marker)))
11887 (when bookmark-name
11888 (with-demoted-errors
11889 (bookmark-set bookmark-name))))
11890 (move-marker org-capture-last-stored-marker (point)))
11891 (when (fboundp 'deactivate-mark) (deactivate-mark))
11892 (run-hooks 'org-after-refile-insert-hook))))
11893 (unless org-refile-keep
11894 (if regionp
11895 (delete-region (point) (+ (point) (- region-end region-start)))
11896 (delete-region
11897 (and (org-back-to-heading t) (point))
11898 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11899 (when (featurep 'org-inlinetask)
11900 (org-inlinetask-remove-END-maybe))
11901 (setq org-markers-to-move nil)
11902 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11904 (defun org-refile-goto-last-stored ()
11905 "Go to the location where the last refile was stored."
11906 (interactive)
11907 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11908 (message "This is the location of the last refile"))
11910 (defun org-refile--get-location (refloc tbl)
11911 "When user refile to REFLOC, find the associated target in TBL.
11912 Also check `org-refile-target-table'."
11913 (car (delq
11915 (mapcar
11916 (lambda (r) (or (assoc r tbl)
11917 (assoc r org-refile-target-table)))
11918 (list (replace-regexp-in-string "/$" "" refloc)
11919 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11921 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11922 no-exclude)
11923 "Prompt the user for a refile location, using PROMPT.
11924 PROMPT should not be suffixed with a colon and a space, because
11925 this function appends the default value from
11926 `org-refile-history' automatically, if that is not empty.
11927 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11928 this is used for the GOTO interface."
11929 (let ((org-refile-targets org-refile-targets)
11930 (org-refile-use-outline-path org-refile-use-outline-path)
11931 excluded-entries)
11932 (when (and (derived-mode-p 'org-mode)
11933 (not org-refile-use-cache)
11934 (not no-exclude))
11935 (org-map-tree
11936 (lambda()
11937 (setq excluded-entries
11938 (append excluded-entries (list (org-get-heading t t)))))))
11939 (setq org-refile-target-table
11940 (org-refile-get-targets default-buffer excluded-entries)))
11941 (unless org-refile-target-table
11942 (user-error "No refile targets"))
11943 (let* ((cbuf (current-buffer))
11944 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11945 (cfunc (if (and org-refile-use-outline-path
11946 org-outline-path-complete-in-steps)
11947 #'org-olpath-completing-read
11948 #'completing-read))
11949 (extra (if org-refile-use-outline-path "/" ""))
11950 (cbnex (concat (buffer-name) extra))
11951 (filename (and cfn (expand-file-name cfn)))
11952 (tbl (mapcar
11953 (lambda (x)
11954 (if (and (not (member org-refile-use-outline-path
11955 '(file full-file-path)))
11956 (not (equal filename (nth 1 x))))
11957 (cons (concat (car x) extra " ("
11958 (file-name-nondirectory (nth 1 x)) ")")
11959 (cdr x))
11960 (cons (concat (car x) extra) (cdr x))))
11961 org-refile-target-table))
11962 (completion-ignore-case t)
11963 cdef
11964 (prompt (concat prompt
11965 (or (and (car org-refile-history)
11966 (concat " (default " (car org-refile-history) ")"))
11967 (and (assoc cbnex tbl) (setq cdef cbnex)
11968 (concat " (default " cbnex ")"))) ": "))
11969 pa answ parent-target child parent old-hist)
11970 (setq old-hist org-refile-history)
11971 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11972 nil 'org-refile-history (or cdef (car org-refile-history))))
11973 (if (setq pa (org-refile--get-location answ tbl))
11974 (progn
11975 (org-refile-check-position pa)
11976 (when (or (not org-refile-history)
11977 (not (eq old-hist org-refile-history))
11978 (not (equal (car pa) (car org-refile-history))))
11979 (setq org-refile-history
11980 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11981 org-refile-history
11982 (cdr org-refile-history))))
11983 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11984 (pop org-refile-history)))
11986 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11987 (progn
11988 (setq parent (match-string 1 answ)
11989 child (match-string 2 answ))
11990 (setq parent-target (org-refile--get-location parent tbl))
11991 (when (and parent-target
11992 (or (eq new-nodes t)
11993 (and (eq new-nodes 'confirm)
11994 (y-or-n-p (format "Create new node \"%s\"? "
11995 child)))))
11996 (org-refile-new-child parent-target child)))
11997 (user-error "Invalid target location")))))
11999 (declare-function org-string-nw-p "org-macs" (s))
12000 (defun org-refile-check-position (refile-pointer)
12001 "Check if the refile pointer matches the headline to which it points."
12002 (let* ((file (nth 1 refile-pointer))
12003 (re (nth 2 refile-pointer))
12004 (pos (nth 3 refile-pointer))
12005 buffer)
12006 (if (and (not (markerp pos)) (not file))
12007 (user-error "Please indicate a target file in the refile path")
12008 (when (org-string-nw-p re)
12009 (setq buffer (if (markerp pos)
12010 (marker-buffer pos)
12011 (or (find-buffer-visiting file)
12012 (find-file-noselect file))))
12013 (with-current-buffer buffer
12014 (save-excursion
12015 (save-restriction
12016 (widen)
12017 (goto-char pos)
12018 (beginning-of-line 1)
12019 (unless (org-looking-at-p re)
12020 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12022 (defun org-refile-new-child (parent-target child)
12023 "Use refile target PARENT-TARGET to add new CHILD below it."
12024 (unless parent-target
12025 (error "Cannot find parent for new node"))
12026 (let ((file (nth 1 parent-target))
12027 (pos (nth 3 parent-target))
12028 level)
12029 (with-current-buffer (or (find-buffer-visiting file)
12030 (find-file-noselect file))
12031 (save-excursion
12032 (save-restriction
12033 (widen)
12034 (if pos
12035 (goto-char pos)
12036 (goto-char (point-max))
12037 (unless (bolp) (newline)))
12038 (when (looking-at org-outline-regexp)
12039 (setq level (funcall outline-level))
12040 (org-end-of-subtree t t))
12041 (org-back-over-empty-lines)
12042 (insert "\n" (make-string
12043 (if pos (org-get-valid-level level 1) 1) ?*)
12044 " " child "\n")
12045 (beginning-of-line 0)
12046 (list (concat (car parent-target) "/" child) file "" (point)))))))
12048 (defun org-olpath-completing-read (prompt collection &rest args)
12049 "Read an outline path like a file name."
12050 (let ((thetable collection))
12051 (apply #'completing-read
12052 prompt
12053 (lambda (string predicate &optional flag)
12054 (cond
12055 ((eq flag nil) (try-completion string thetable))
12056 ((eq flag t)
12057 (let ((l (length string)))
12058 (mapcar (lambda (x)
12059 (let ((r (substring x l))
12060 (f (if (string-match " ([^)]*)$" x)
12061 (match-string 0 x)
12062 "")))
12063 (if (string-match "/" r)
12064 (concat string (substring r 0 (match-end 0)) f)
12065 x)))
12066 (all-completions string thetable predicate))))
12067 ;; Exact match?
12068 ((eq flag 'lambda) (assoc string thetable))))
12069 args)))
12071 ;;;; Dynamic blocks
12073 (defun org-find-dblock (name)
12074 "Find the first dynamic block with name NAME in the buffer.
12075 If not found, stay at current position and return nil."
12076 (let ((case-fold-search t) pos)
12077 (save-excursion
12078 (goto-char (point-min))
12079 (setq pos (and (re-search-forward
12080 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12081 (match-beginning 0))))
12082 (when pos (goto-char pos))
12083 pos))
12085 (defun org-create-dblock (plist)
12086 "Create a dynamic block section, with parameters taken from PLIST.
12087 PLIST must contain a :name entry which is used as the name of the block."
12088 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12089 (end-of-line 1)
12090 (newline))
12091 (let ((col (current-column))
12092 (name (plist-get plist :name)))
12093 (insert "#+BEGIN: " name)
12094 (while plist
12095 (if (eq (car plist) :name)
12096 (setq plist (cddr plist))
12097 (insert " " (prin1-to-string (pop plist)))))
12098 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12099 (beginning-of-line -2)))
12101 (defun org-prepare-dblock ()
12102 "Prepare dynamic block for refresh.
12103 This empties the block, puts the cursor at the insert position and returns
12104 the property list including an extra property :name with the block name."
12105 (unless (looking-at org-dblock-start-re)
12106 (user-error "Not at a dynamic block"))
12107 (let* ((begdel (1+ (match-end 0)))
12108 (name (org-no-properties (match-string 1)))
12109 (params (append (list :name name)
12110 (read (concat "(" (match-string 3) ")")))))
12111 (save-excursion
12112 (beginning-of-line 1)
12113 (skip-chars-forward " \t")
12114 (setq params (plist-put params :indentation-column (current-column))))
12115 (unless (re-search-forward org-dblock-end-re nil t)
12116 (error "Dynamic block not terminated"))
12117 (setq params
12118 (append params
12119 (list :content (buffer-substring
12120 begdel (match-beginning 0)))))
12121 (delete-region begdel (match-beginning 0))
12122 (goto-char begdel)
12123 (open-line 1)
12124 params))
12126 (defun org-map-dblocks (&optional command)
12127 "Apply COMMAND to all dynamic blocks in the current buffer.
12128 If COMMAND is not given, use `org-update-dblock'."
12129 (let ((cmd (or command 'org-update-dblock)))
12130 (save-excursion
12131 (goto-char (point-min))
12132 (while (re-search-forward org-dblock-start-re nil t)
12133 (goto-char (match-beginning 0))
12134 (save-excursion
12135 (condition-case nil
12136 (funcall cmd)
12137 (error (message "Error during update of dynamic block"))))
12138 (unless (re-search-forward org-dblock-end-re nil t)
12139 (error "Dynamic block not terminated"))))))
12141 (defun org-dblock-update (&optional arg)
12142 "User command for updating dynamic blocks.
12143 Update the dynamic block at point. With prefix ARG, update all dynamic
12144 blocks in the buffer."
12145 (interactive "P")
12146 (if arg
12147 (org-update-all-dblocks)
12148 (or (looking-at org-dblock-start-re)
12149 (org-beginning-of-dblock))
12150 (org-update-dblock)))
12152 (defun org-update-dblock ()
12153 "Update the dynamic block at point.
12154 This means to empty the block, parse for parameters and then call
12155 the correct writing function."
12156 (interactive)
12157 (save-excursion
12158 (let* ((win (selected-window))
12159 (pos (point))
12160 (line (org-current-line))
12161 (params (org-prepare-dblock))
12162 (name (plist-get params :name))
12163 (indent (plist-get params :indentation-column))
12164 (cmd (intern (concat "org-dblock-write:" name))))
12165 (message "Updating dynamic block `%s' at line %d..." name line)
12166 (funcall cmd params)
12167 (message "Updating dynamic block `%s' at line %d...done" name line)
12168 (goto-char pos)
12169 (when (and indent (> indent 0))
12170 (setq indent (make-string indent ?\ ))
12171 (save-excursion
12172 (select-window win)
12173 (org-beginning-of-dblock)
12174 (forward-line 1)
12175 (while (not (looking-at org-dblock-end-re))
12176 (insert indent)
12177 (beginning-of-line 2))
12178 (when (looking-at org-dblock-end-re)
12179 (and (looking-at "[ \t]+")
12180 (replace-match ""))
12181 (insert indent)))))))
12183 (defun org-beginning-of-dblock ()
12184 "Find the beginning of the dynamic block at point.
12185 Error if there is no such block at point."
12186 (let ((pos (point))
12187 beg)
12188 (end-of-line 1)
12189 (if (and (re-search-backward org-dblock-start-re nil t)
12190 (setq beg (match-beginning 0))
12191 (re-search-forward org-dblock-end-re nil t)
12192 (> (match-end 0) pos))
12193 (goto-char beg)
12194 (goto-char pos)
12195 (error "Not in a dynamic block"))))
12197 (defun org-update-all-dblocks ()
12198 "Update all dynamic blocks in the buffer.
12199 This function can be used in a hook."
12200 (interactive)
12201 (when (derived-mode-p 'org-mode)
12202 (org-map-dblocks 'org-update-dblock)))
12205 ;;;; Completion
12207 (declare-function org-export-backend-name "org-export" (cl-x))
12208 (declare-function org-export-backend-options "org-export" (cl-x))
12209 (defun org-get-export-keywords ()
12210 "Return a list of all currently understood export keywords.
12211 Export keywords include options, block names, attributes and
12212 keywords relative to each registered export back-end."
12213 (let (keywords)
12214 (dolist (backend
12215 (org-bound-and-true-p org-export-registered-backends)
12216 (delq nil keywords))
12217 ;; Back-end name (for keywords, like #+LATEX:)
12218 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12219 (dolist (option-entry (org-export-backend-options backend))
12220 ;; Back-end options.
12221 (push (nth 1 option-entry) keywords)))))
12223 (defconst org-options-keywords
12224 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12225 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12226 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12227 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12228 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12230 (defcustom org-structure-template-alist
12231 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12232 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12233 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12234 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12235 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12236 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12237 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12238 ("L" "#+LaTeX: ")
12239 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12240 ("H" "#+HTML: ")
12241 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12242 ("A" "#+ASCII: ")
12243 ("i" "#+INDEX: ?")
12244 ("I" "#+INCLUDE: %file ?"))
12245 "Structure completion elements.
12246 This is a list of abbreviation keys and values. The value gets inserted
12247 if you type `<' followed by the key and then press the completion key,
12248 usually `TAB'. %file will be replaced by a file name after prompting
12249 for the file using completion. The cursor will be placed at the position
12250 of the `?' in the template.
12251 There are two templates for each key, the first uses the original Org syntax,
12252 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12253 the default when the /org-mtags.el/ module has been loaded. See also the
12254 variable `org-mtags-prefer-muse-templates'."
12255 :group 'org-completion
12256 :type '(repeat
12257 (list
12258 (string :tag "Key")
12259 (string :tag "Template")))
12260 :version "25.1"
12261 :package-version '(Org . "8.3"))
12263 (defun org-try-structure-completion ()
12264 "Try to complete a structure template before point.
12265 This looks for strings like \"<e\" on an otherwise empty line and
12266 expands them."
12267 (let ((l (buffer-substring (point-at-bol) (point)))
12269 (when (and (looking-at "[ \t]*$")
12270 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12271 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12272 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12273 (match-beginning 1)) a)
12274 t)))
12276 (defun org-complete-expand-structure-template (start cell)
12277 "Expand a structure template."
12278 (let ((rpl (nth 1 cell))
12279 (ind ""))
12280 (delete-region start (point))
12281 (when (string-match "\\`[ \t]*#\\+" rpl)
12282 (cond
12283 ((bolp))
12284 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12285 (setq ind (buffer-substring (point-at-bol) (point))))
12286 (t (newline))))
12287 (setq start (point))
12288 (when (string-match "%file" rpl)
12289 (setq rpl (replace-match
12290 (concat
12291 "\""
12292 (save-match-data
12293 (abbreviate-file-name (read-file-name "Include file: ")))
12294 "\"")
12295 t t rpl)))
12296 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12297 (concat "\n" ind)))
12298 (insert rpl)
12299 (when (re-search-backward "\\?" start t) (delete-char 1))))
12301 ;;;; TODO, DEADLINE, Comments
12303 (defun org-toggle-comment ()
12304 "Change the COMMENT state of an entry."
12305 (interactive)
12306 (save-excursion
12307 (org-back-to-heading)
12308 (looking-at org-complex-heading-regexp)
12309 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12310 (skip-chars-forward " \t")
12311 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12312 (if (org-in-commented-heading-p t)
12313 (delete-region (point)
12314 (progn (search-forward " " (line-end-position) 'move)
12315 (skip-chars-forward " \t")
12316 (point)))
12317 (insert org-comment-string)
12318 (unless (eolp) (insert " ")))))
12320 (defvar org-last-todo-state-is-todo nil
12321 "This is non-nil when the last TODO state change led to a TODO state.
12322 If the last change removed the TODO tag or switched to DONE, then
12323 this is nil.")
12325 (defvar org-setting-tags nil) ; dynamically skipped
12327 (defvar org-todo-setup-filter-hook nil
12328 "Hook for functions that pre-filter todo specs.
12329 Each function takes a todo spec and returns either nil or the spec
12330 transformed into canonical form." )
12332 (defvar org-todo-get-default-hook nil
12333 "Hook for functions that get a default item for todo.
12334 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12335 nil or a string to be used for the todo mark." )
12337 (defvar org-agenda-headline-snapshot-before-repeat)
12339 (defun org-current-effective-time ()
12340 "Return current time adjusted for `org-extend-today-until' variable."
12341 (let* ((ct (org-current-time))
12342 (dct (decode-time ct))
12343 (ct1
12344 (cond
12345 (org-use-last-clock-out-time-as-effective-time
12346 (or (org-clock-get-last-clock-out-time) ct))
12347 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12348 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12349 (t ct))))
12350 ct1))
12352 (defun org-todo-yesterday (&optional arg)
12353 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12354 (interactive "P")
12355 (if (eq major-mode 'org-agenda-mode)
12356 (apply 'org-agenda-todo-yesterday arg)
12357 (let* ((org-use-effective-time t)
12358 (hour (third (decode-time
12359 (org-current-time))))
12360 (org-extend-today-until (1+ hour)))
12361 (org-todo arg))))
12363 (defvar org-block-entry-blocking ""
12364 "First entry preventing the TODO state change.")
12366 (defun org-cancel-repeater ()
12367 "Cancel a repeater by setting its numeric value to zero."
12368 (interactive)
12369 (save-excursion
12370 (org-back-to-heading t)
12371 (let ((bound1 (point))
12372 (bound0 (save-excursion (outline-next-heading) (point))))
12373 (when (and (re-search-forward
12374 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12375 org-deadline-time-regexp "\\)\\|\\("
12376 org-ts-regexp "\\)")
12377 bound0 t)
12378 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12379 bound1 t))
12380 (replace-match "0" t nil nil 1)))))
12382 (defun org-todo (&optional arg)
12383 "Change the TODO state of an item.
12384 The state of an item is given by a keyword at the start of the heading,
12385 like
12386 *** TODO Write paper
12387 *** DONE Call mom
12389 The different keywords are specified in the variable `org-todo-keywords'.
12390 By default the available states are \"TODO\" and \"DONE\".
12391 So for this example: when the item starts with TODO, it is changed to DONE.
12392 When it starts with DONE, the DONE is removed. And when neither TODO nor
12393 DONE are present, add TODO at the beginning of the heading.
12395 With \\[universal-argument] prefix arg, use completion to determine the new \
12396 state.
12397 With numeric prefix arg, switch to that state.
12398 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12399 keywords (nextset).
12400 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12401 With a numeric prefix arg of 0, inhibit note taking for the change.
12402 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12404 When called through ELisp, arg is also interpreted in the following way:
12405 `none' -> empty state
12406 \"\"(empty string) -> switch to empty state
12407 `done' -> switch to DONE
12408 `nextset' -> switch to the next set of keywords
12409 `previousset' -> switch to the previous set of keywords
12410 \"WAITING\" -> switch to the specified keyword, but only if it
12411 really is a member of `org-todo-keywords'."
12412 (interactive "P")
12413 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12414 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12415 'region-start-level 'region))
12416 org-loop-over-headlines-in-active-region)
12417 (org-map-entries
12418 `(org-todo ,arg)
12419 org-loop-over-headlines-in-active-region
12420 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12421 (when (equal arg '(16)) (setq arg 'nextset))
12422 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12423 (let ((org-blocker-hook org-blocker-hook)
12424 commentp
12425 case-fold-search)
12426 (when (equal arg '(64))
12427 (setq arg nil org-blocker-hook nil))
12428 (when (and org-blocker-hook
12429 (or org-inhibit-blocking
12430 (org-entry-get nil "NOBLOCKING")))
12431 (setq org-blocker-hook nil))
12432 (save-excursion
12433 (catch 'exit
12434 (org-back-to-heading t)
12435 (when (org-in-commented-heading-p t)
12436 (org-toggle-comment)
12437 (setq commentp t))
12438 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12439 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12440 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12441 (let* ((match-data (match-data))
12442 (startpos (point-at-bol))
12443 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12444 (org-log-done org-log-done)
12445 (org-log-repeat org-log-repeat)
12446 (org-todo-log-states org-todo-log-states)
12447 (org-inhibit-logging
12448 (if (equal arg 0)
12449 (progn (setq arg nil) 'note) org-inhibit-logging))
12450 (this (match-string 1))
12451 (hl-pos (match-beginning 0))
12452 (head (org-get-todo-sequence-head this))
12453 (ass (assoc head org-todo-kwd-alist))
12454 (interpret (nth 1 ass))
12455 (done-word (nth 3 ass))
12456 (final-done-word (nth 4 ass))
12457 (org-last-state (or this ""))
12458 (completion-ignore-case t)
12459 (member (member this org-todo-keywords-1))
12460 (tail (cdr member))
12461 (org-state (cond
12462 ((and org-todo-key-trigger
12463 (or (and (equal arg '(4))
12464 (eq org-use-fast-todo-selection 'prefix))
12465 (and (not arg) org-use-fast-todo-selection
12466 (not (eq org-use-fast-todo-selection
12467 'prefix)))))
12468 ;; Use fast selection
12469 (org-fast-todo-selection))
12470 ((and (equal arg '(4))
12471 (or (not org-use-fast-todo-selection)
12472 (not org-todo-key-trigger)))
12473 ;; Read a state with completion
12474 (completing-read
12475 "State: " (mapcar #'list org-todo-keywords-1)
12476 nil t))
12477 ((eq arg 'right)
12478 (if this
12479 (if tail (car tail) nil)
12480 (car org-todo-keywords-1)))
12481 ((eq arg 'left)
12482 (unless (equal member org-todo-keywords-1)
12483 (if this
12484 (nth (- (length org-todo-keywords-1)
12485 (length tail) 2)
12486 org-todo-keywords-1)
12487 (org-last org-todo-keywords-1))))
12488 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12489 (setq arg nil))) ; hack to fall back to cycling
12490 (arg
12491 ;; user or caller requests a specific state
12492 (cond
12493 ((equal arg "") nil)
12494 ((eq arg 'none) nil)
12495 ((eq arg 'done) (or done-word (car org-done-keywords)))
12496 ((eq arg 'nextset)
12497 (or (car (cdr (member head org-todo-heads)))
12498 (car org-todo-heads)))
12499 ((eq arg 'previousset)
12500 (let ((org-todo-heads (reverse org-todo-heads)))
12501 (or (car (cdr (member head org-todo-heads)))
12502 (car org-todo-heads))))
12503 ((car (member arg org-todo-keywords-1)))
12504 ((stringp arg)
12505 (user-error "State `%s' not valid in this file" arg))
12506 ((nth (1- (prefix-numeric-value arg))
12507 org-todo-keywords-1))))
12508 ((null member) (or head (car org-todo-keywords-1)))
12509 ((equal this final-done-word) nil) ;; -> make empty
12510 ((null tail) nil) ;; -> first entry
12511 ((memq interpret '(type priority))
12512 (if (eq this-command last-command)
12513 (car tail)
12514 (if (> (length tail) 0)
12515 (or done-word (car org-done-keywords))
12516 nil)))
12518 (car tail))))
12519 (org-state (or
12520 (run-hook-with-args-until-success
12521 'org-todo-get-default-hook org-state org-last-state)
12522 org-state))
12523 (next (if org-state (concat " " org-state " ") " "))
12524 (change-plist (list :type 'todo-state-change :from this :to org-state
12525 :position startpos))
12526 dolog now-done-p)
12527 (when org-blocker-hook
12528 (setq org-last-todo-state-is-todo
12529 (not (member this org-done-keywords)))
12530 (unless (save-excursion
12531 (save-match-data
12532 (org-with-wide-buffer
12533 (run-hook-with-args-until-failure
12534 'org-blocker-hook change-plist))))
12535 (if (org-called-interactively-p 'interactive)
12536 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12537 this org-state org-block-entry-blocking)
12538 ;; fail silently
12539 (message "TODO state change from %s to %s blocked (by \"%s\")"
12540 this org-state org-block-entry-blocking)
12541 (throw 'exit nil))))
12542 (store-match-data match-data)
12543 (replace-match next t t)
12544 (cond ((equal this org-state)
12545 (message "TODO state was already %s" (org-trim next)))
12546 ((pos-visible-in-window-p hl-pos)
12547 (message "TODO state changed to %s" (org-trim next))))
12548 (unless head
12549 (setq head (org-get-todo-sequence-head org-state)
12550 ass (assoc head org-todo-kwd-alist)
12551 interpret (nth 1 ass)
12552 done-word (nth 3 ass)
12553 final-done-word (nth 4 ass)))
12554 (when (memq arg '(nextset previousset))
12555 (message "Keyword-Set %d/%d: %s"
12556 (- (length org-todo-sets) -1
12557 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12558 (length org-todo-sets)
12559 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12560 (setq org-last-todo-state-is-todo
12561 (not (member org-state org-done-keywords)))
12562 (setq now-done-p (and (member org-state org-done-keywords)
12563 (not (member this org-done-keywords))))
12564 (and logging (org-local-logging logging))
12565 (when (and (or org-todo-log-states org-log-done)
12566 (not (eq org-inhibit-logging t))
12567 (not (memq arg '(nextset previousset))))
12568 ;; we need to look at recording a time and note
12569 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12570 (nth 2 (assoc this org-todo-log-states))))
12571 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12572 (setq dolog 'time))
12573 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12574 (and org-state
12575 (member org-state org-not-done-keywords)
12576 (not (member this org-not-done-keywords))))
12577 ;; This is now a todo state and was not one before
12578 ;; If there was a CLOSED time stamp, get rid of it.
12579 (org-add-planning-info nil nil 'closed))
12580 (when (and now-done-p org-log-done)
12581 ;; It is now done, and it was not done before
12582 (org-add-planning-info 'closed (org-current-effective-time))
12583 (when (and (not dolog) (eq 'note org-log-done))
12584 (org-add-log-setup 'done org-state this 'note)))
12585 (when (and org-state dolog)
12586 ;; This is a non-nil state, and we need to log it
12587 (org-add-log-setup 'state org-state this dolog)))
12588 ;; Fixup tag positioning
12589 (org-todo-trigger-tag-changes org-state)
12590 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12591 (when org-provide-todo-statistics
12592 (org-update-parent-todo-statistics))
12593 (run-hooks 'org-after-todo-state-change-hook)
12594 (when (and arg (not (member org-state org-done-keywords)))
12595 (setq head (org-get-todo-sequence-head org-state)))
12596 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12597 ;; Do we need to trigger a repeat?
12598 (when now-done-p
12599 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12600 ;; This is for the agenda, take a snapshot of the headline.
12601 (save-match-data
12602 (setq org-agenda-headline-snapshot-before-repeat
12603 (org-get-heading))))
12604 (org-auto-repeat-maybe org-state))
12605 ;; Fixup cursor location if close to the keyword
12606 (when (and (outline-on-heading-p)
12607 (not (bolp))
12608 (save-excursion (beginning-of-line 1)
12609 (looking-at org-todo-line-regexp))
12610 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12611 (goto-char (or (match-end 2) (match-end 1)))
12612 (and (looking-at " ") (just-one-space)))
12613 (when org-trigger-hook
12614 (save-excursion
12615 (run-hook-with-args 'org-trigger-hook change-plist)))
12616 (when commentp (org-toggle-comment))))))))
12618 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12619 "Block turning an entry into a TODO, using the hierarchy.
12620 This checks whether the current task should be blocked from state
12621 changes. Such blocking occurs when:
12623 1. The task has children which are not all in a completed state.
12625 2. A task has a parent with the property :ORDERED:, and there
12626 are siblings prior to the current task with incomplete
12627 status.
12629 3. The parent of the task is blocked because it has siblings that should
12630 be done first, or is child of a block grandparent TODO entry."
12632 (if (not org-enforce-todo-dependencies)
12633 t ; if locally turned off don't block
12634 (catch 'dont-block
12635 ;; If this is not a todo state change, or if this entry is already DONE,
12636 ;; do not block
12637 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12638 (member (plist-get change-plist :from)
12639 (cons 'done org-done-keywords))
12640 (member (plist-get change-plist :to)
12641 (cons 'todo org-not-done-keywords))
12642 (not (plist-get change-plist :to)))
12643 (throw 'dont-block t))
12644 ;; If this task has children, and any are undone, it's blocked
12645 (save-excursion
12646 (org-back-to-heading t)
12647 (let ((this-level (funcall outline-level)))
12648 (outline-next-heading)
12649 (let ((child-level (funcall outline-level)))
12650 (while (and (not (eobp))
12651 (> child-level this-level))
12652 ;; this todo has children, check whether they are all
12653 ;; completed
12654 (when (and (not (org-entry-is-done-p))
12655 (org-entry-is-todo-p))
12656 (setq org-block-entry-blocking (org-get-heading))
12657 (throw 'dont-block nil))
12658 (outline-next-heading)
12659 (setq child-level (funcall outline-level))))))
12660 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12661 ;; any previous siblings are undone, it's blocked
12662 (save-excursion
12663 (org-back-to-heading t)
12664 (let* ((pos (point))
12665 (parent-pos (and (org-up-heading-safe) (point))))
12666 (unless parent-pos (throw 'dont-block t)) ; no parent
12667 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12668 (forward-line 1)
12669 (re-search-forward org-not-done-heading-regexp pos t))
12670 (setq org-block-entry-blocking (match-string 0))
12671 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12672 ;; Search further up the hierarchy, to see if an ancestor is blocked
12673 (while t
12674 (goto-char parent-pos)
12675 (unless (looking-at org-not-done-heading-regexp)
12676 (throw 'dont-block t)) ; do not block, parent is not a TODO
12677 (setq pos (point))
12678 (setq 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 (org-get-heading)))
12684 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12686 (defcustom org-track-ordered-property-with-tag nil
12687 "Should the ORDERED property also be shown as a tag?
12688 The ORDERED property decides if an entry should require subtasks to be
12689 completed in sequence. Since a property is not very visible, setting
12690 this option means that toggling the ORDERED property with the command
12691 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12692 not relevant for the behavior, but it makes things more visible.
12694 Note that toggling the tag with tags commands will not change the property
12695 and therefore not influence behavior!
12697 This can be t, meaning the tag ORDERED should be used, It can also be a
12698 string to select a different tag for this task."
12699 :group 'org-todo
12700 :type '(choice
12701 (const :tag "No tracking" nil)
12702 (const :tag "Track with ORDERED tag" t)
12703 (string :tag "Use other tag")))
12705 (defun org-toggle-ordered-property ()
12706 "Toggle the ORDERED property of the current entry.
12707 For better visibility, you can track the value of this property with a tag.
12708 See variable `org-track-ordered-property-with-tag'."
12709 (interactive)
12710 (let* ((t1 org-track-ordered-property-with-tag)
12711 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12712 (save-excursion
12713 (org-back-to-heading)
12714 (if (org-entry-get nil "ORDERED")
12715 (progn
12716 (org-delete-property "ORDERED")
12717 (and tag (org-toggle-tag tag 'off))
12718 (message "Subtasks can be completed in arbitrary order"))
12719 (org-entry-put nil "ORDERED" "t")
12720 (and tag (org-toggle-tag tag 'on))
12721 (message "Subtasks must be completed in sequence")))))
12723 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12724 (defun org-block-todo-from-checkboxes (change-plist)
12725 "Block turning an entry into a TODO, using checkboxes.
12726 This checks whether the current task should be blocked from state
12727 changes because there are unchecked boxes in this entry."
12728 (if (not org-enforce-todo-checkbox-dependencies)
12729 t ; if locally turned off don't block
12730 (catch 'dont-block
12731 ;; If this is not a todo state change, or if this entry is already DONE,
12732 ;; do not block
12733 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12734 (member (plist-get change-plist :from)
12735 (cons 'done org-done-keywords))
12736 (member (plist-get change-plist :to)
12737 (cons 'todo org-not-done-keywords))
12738 (not (plist-get change-plist :to)))
12739 (throw 'dont-block t))
12740 ;; If this task has checkboxes that are not checked, it's blocked
12741 (save-excursion
12742 (org-back-to-heading t)
12743 (let ((beg (point)) end)
12744 (outline-next-heading)
12745 (setq end (point))
12746 (goto-char beg)
12747 (when (org-list-search-forward
12748 (concat (org-item-beginning-re)
12749 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12750 "\\[[- ]\\]")
12751 end t)
12752 (when (boundp 'org-blocked-by-checkboxes)
12753 (setq org-blocked-by-checkboxes t))
12754 (throw 'dont-block nil))))
12755 t))) ; do not block
12757 (defun org-entry-blocked-p ()
12758 "Non-nil if entry at point is blocked."
12759 (and (not (org-entry-get nil "NOBLOCKING"))
12760 (member (org-entry-get nil "TODO") org-not-done-keywords)
12761 (not (run-hook-with-args-until-failure
12762 'org-blocker-hook
12763 (list :type 'todo-state-change
12764 :position (point)
12765 :from 'todo
12766 :to 'done)))))
12768 (defun org-update-statistics-cookies (all)
12769 "Update the statistics cookie, either from TODO or from checkboxes.
12770 This should be called with the cursor in a line with a statistics cookie."
12771 (interactive "P")
12772 (if all
12773 (progn
12774 (org-update-checkbox-count 'all)
12775 (org-map-entries 'org-update-parent-todo-statistics))
12776 (if (not (org-at-heading-p))
12777 (org-update-checkbox-count)
12778 (let ((pos (point-marker))
12779 end l1 l2)
12780 (ignore-errors (org-back-to-heading t))
12781 (if (not (org-at-heading-p))
12782 (org-update-checkbox-count)
12783 (setq l1 (org-outline-level))
12784 (setq end (save-excursion
12785 (outline-next-heading)
12786 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12787 (point)))
12788 (if (and (save-excursion
12789 (re-search-forward
12790 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12791 (not (save-excursion (re-search-forward
12792 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12793 (org-update-checkbox-count)
12794 (if (and l2 (> l2 l1))
12795 (progn
12796 (goto-char end)
12797 (org-update-parent-todo-statistics))
12798 (goto-char pos)
12799 (beginning-of-line 1)
12800 (while (re-search-forward
12801 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12802 (point-at-eol) t)
12803 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12804 (goto-char pos)
12805 (move-marker pos nil)))))
12807 (defvar org-entry-property-inherited-from) ;; defined below
12808 (defun org-update-parent-todo-statistics ()
12809 "Update any statistics cookie in the parent of the current headline.
12810 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12811 the entire subtree and this will travel up the hierarchy and update
12812 statistics everywhere."
12813 (let* ((prop (save-excursion (org-up-heading-safe)
12814 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12815 (recursive (or (not org-hierarchical-todo-statistics)
12816 (and prop (string-match "\\<recursive\\>" prop))))
12817 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12819 (first t)
12820 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12821 level ltoggle l1 new ndel
12822 (cnt-all 0) (cnt-done 0) is-percent kwd
12823 checkbox-beg ov ovs ove cookie-present)
12824 (catch 'exit
12825 (save-excursion
12826 (beginning-of-line 1)
12827 (setq ltoggle (funcall outline-level))
12828 ;; Three situations are to consider:
12830 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12831 ;; to the top-level ancestor on the headline;
12833 ;; 2. If parent has "recursive" property, repeat up to the
12834 ;; headline setting that property, taking inheritance into
12835 ;; account;
12837 ;; 3. Else, move up to direct parent and proceed only once.
12838 (while (and (setq level (org-up-heading-safe))
12839 (or recursive first)
12840 (>= (point) lim))
12841 (setq first nil cookie-present nil)
12842 (unless (and level
12843 (not (string-match
12844 "\\<checkbox\\>"
12845 (downcase (or (org-entry-get nil "COOKIE_DATA")
12846 "")))))
12847 (throw 'exit nil))
12848 (while (re-search-forward box-re (point-at-eol) t)
12849 (setq cnt-all 0 cnt-done 0 cookie-present t)
12850 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12851 (save-match-data
12852 (unless (outline-next-heading) (throw 'exit nil))
12853 (while (and (looking-at org-complex-heading-regexp)
12854 (> (setq l1 (length (match-string 1))) level))
12855 (setq kwd (and (or recursive (= l1 ltoggle))
12856 (match-string 2)))
12857 (if (or (eq org-provide-todo-statistics 'all-headlines)
12858 (and (eq org-provide-todo-statistics t)
12859 (or (member kwd org-done-keywords)))
12860 (and (listp org-provide-todo-statistics)
12861 (stringp (car org-provide-todo-statistics))
12862 (or (member kwd org-provide-todo-statistics)
12863 (member kwd org-done-keywords)))
12864 (and (listp org-provide-todo-statistics)
12865 (listp (car org-provide-todo-statistics))
12866 (or (member kwd (car org-provide-todo-statistics))
12867 (and (member kwd org-done-keywords)
12868 (member kwd (cadr org-provide-todo-statistics))))))
12869 (setq cnt-all (1+ cnt-all))
12870 (and (eq org-provide-todo-statistics t)
12872 (setq cnt-all (1+ cnt-all))))
12873 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12874 (member kwd org-done-keywords))
12875 (and (listp org-provide-todo-statistics)
12876 (listp (car org-provide-todo-statistics))
12877 (member kwd org-done-keywords)
12878 (member kwd (cadr org-provide-todo-statistics)))
12879 (and (listp org-provide-todo-statistics)
12880 (stringp (car org-provide-todo-statistics))
12881 (member kwd org-done-keywords)))
12882 (setq cnt-done (1+ cnt-done)))
12883 (outline-next-heading)))
12884 (setq new
12885 (if is-percent
12886 (format "[%d%%]" (floor (* 100.0 cnt-done)
12887 (max 1 cnt-all)))
12888 (format "[%d/%d]" cnt-done cnt-all))
12889 ndel (- (match-end 0) checkbox-beg))
12890 ;; handle overlays when updating cookie from column view
12891 (when (setq ov (car (overlays-at checkbox-beg)))
12892 (setq ovs (overlay-start ov) ove (overlay-end ov))
12893 (delete-overlay ov))
12894 (goto-char checkbox-beg)
12895 (insert new)
12896 (delete-region (point) (+ (point) ndel))
12897 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12898 (when ov (move-overlay ov ovs ove)))
12899 (when cookie-present
12900 (run-hook-with-args 'org-after-todo-statistics-hook
12901 cnt-done (- cnt-all cnt-done))))))
12902 (run-hooks 'org-todo-statistics-hook)))
12904 (defvar org-after-todo-statistics-hook nil
12905 "Hook that is called after a TODO statistics cookie has been updated.
12906 Each function is called with two arguments: the number of not-done entries
12907 and the number of done entries.
12909 For example, the following function, when added to this hook, will switch
12910 an entry to DONE when all children are done, and back to TODO when new
12911 entries are set to a TODO status. Note that this hook is only called
12912 when there is a statistics cookie in the headline!
12914 (defun org-summary-todo (n-done n-not-done)
12915 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12916 (let (org-log-done org-log-states) ; turn off logging
12917 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12920 (defvar org-todo-statistics-hook nil
12921 "Hook that is run whenever Org thinks TODO statistics should be updated.
12922 This hook runs even if there is no statistics cookie present, in which case
12923 `org-after-todo-statistics-hook' would not run.")
12925 (defun org-todo-trigger-tag-changes (state)
12926 "Apply the changes defined in `org-todo-state-tags-triggers'."
12927 (let ((l org-todo-state-tags-triggers)
12928 changes)
12929 (when (or (not state) (equal state ""))
12930 (setq changes (append changes (cdr (assoc "" l)))))
12931 (when (and (stringp state) (> (length state) 0))
12932 (setq changes (append changes (cdr (assoc state l)))))
12933 (when (member state org-not-done-keywords)
12934 (setq changes (append changes (cdr (assoc 'todo l)))))
12935 (when (member state org-done-keywords)
12936 (setq changes (append changes (cdr (assoc 'done l)))))
12937 (dolist (c changes)
12938 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12940 (defun org-local-logging (value)
12941 "Get logging settings from a property VALUE."
12942 ;; Directly set the variables, they are already local.
12943 (setq org-log-done nil
12944 org-log-repeat nil
12945 org-todo-log-states nil)
12946 (dolist (w (org-split-string value))
12947 (let (a)
12948 (cond
12949 ((setq a (assoc w org-startup-options))
12950 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12951 (set (nth 1 a) (nth 2 a))))
12952 ((setq a (org-extract-log-state-settings w))
12953 (and (member (car a) org-todo-keywords-1)
12954 (push a org-todo-log-states)))))))
12956 (defun org-get-todo-sequence-head (kwd)
12957 "Return the head of the TODO sequence to which KWD belongs.
12958 If KWD is not set, check if there is a text property remembering the
12959 right sequence."
12960 (let (p)
12961 (cond
12962 ((not kwd)
12963 (or (get-text-property (point-at-bol) 'org-todo-head)
12964 (progn
12965 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12966 nil (point-at-eol)))
12967 (get-text-property p 'org-todo-head))))
12968 ((not (member kwd org-todo-keywords-1))
12969 (car org-todo-keywords-1))
12970 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12972 (defun org-fast-todo-selection ()
12973 "Fast TODO keyword selection with single keys.
12974 Returns the new TODO keyword, or nil if no state change should occur."
12975 (let* ((fulltable org-todo-key-alist)
12976 (done-keywords org-done-keywords) ;; needed for the faces.
12977 (maxlen (apply 'max (mapcar
12978 (lambda (x)
12979 (if (stringp (car x)) (string-width (car x)) 0))
12980 fulltable)))
12981 (expert nil)
12982 (fwidth (+ maxlen 3 1 3))
12983 (ncol (/ (- (window-width) 4) fwidth))
12984 tg cnt e c tbl
12985 groups ingroup)
12986 (save-excursion
12987 (save-window-excursion
12988 (if expert
12989 (set-buffer (get-buffer-create " *Org todo*"))
12990 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12991 (erase-buffer)
12992 (setq-local org-done-keywords done-keywords)
12993 (setq tbl fulltable cnt 0)
12994 (while (setq e (pop tbl))
12995 (cond
12996 ((equal e '(:startgroup))
12997 (push '() groups) (setq ingroup t)
12998 (unless (= cnt 0)
12999 (setq cnt 0)
13000 (insert "\n"))
13001 (insert "{ "))
13002 ((equal e '(:endgroup))
13003 (setq ingroup nil cnt 0)
13004 (insert "}\n"))
13005 ((equal e '(:newline))
13006 (unless (= cnt 0)
13007 (setq cnt 0)
13008 (insert "\n")
13009 (setq e (car tbl))
13010 (while (equal (car tbl) '(:newline))
13011 (insert "\n")
13012 (setq tbl (cdr tbl)))))
13014 (setq tg (car e) c (cdr e))
13015 (when ingroup (push tg (car groups)))
13016 (setq tg (org-add-props tg nil 'face
13017 (org-get-todo-face tg)))
13018 (when (and (= cnt 0) (not ingroup)) (insert " "))
13019 (insert "[" c "] " tg (make-string
13020 (- fwidth 4 (length tg)) ?\ ))
13021 (when (= (setq cnt (1+ cnt)) ncol)
13022 (insert "\n")
13023 (when ingroup (insert " "))
13024 (setq cnt 0)))))
13025 (insert "\n")
13026 (goto-char (point-min))
13027 (unless expert (org-fit-window-to-buffer))
13028 (message "[a-z..]:Set [SPC]:clear")
13029 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13030 (cond
13031 ((or (= c ?\C-g)
13032 (and (= c ?q) (not (rassoc c fulltable))))
13033 (setq quit-flag t))
13034 ((= c ?\ ) nil)
13035 ((setq e (rassoc c fulltable) tg (car e))
13037 (t (setq quit-flag t)))))))
13039 (defun org-entry-is-todo-p ()
13040 (member (org-get-todo-state) org-not-done-keywords))
13042 (defun org-entry-is-done-p ()
13043 (member (org-get-todo-state) org-done-keywords))
13045 (defun org-get-todo-state ()
13046 "Return the TODO keyword of the current subtree."
13047 (save-excursion
13048 (org-back-to-heading t)
13049 (and (looking-at org-todo-line-regexp)
13050 (match-end 2)
13051 (match-string 2))))
13053 (defun org-at-date-range-p (&optional inactive-ok)
13054 "Non-nil if point is inside a date range.
13056 When optional argument INACTIVE-OK is non-nil, also consider
13057 inactive time ranges.
13059 When this function returns a non-nil value, match data is set
13060 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13061 on INACTIVE-OK."
13062 (interactive)
13063 (save-excursion
13064 (catch 'exit
13065 (let ((pos (point)))
13066 (skip-chars-backward "^[<\r\n")
13067 (skip-chars-backward "<[")
13068 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13069 (>= (match-end 0) pos)
13070 (throw 'exit t))
13071 (skip-chars-backward "^<[\r\n")
13072 (skip-chars-backward "<[")
13073 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13074 (>= (match-end 0) pos)
13075 (throw 'exit t)))
13076 nil)))
13078 (defun org-get-repeat (&optional tagline)
13079 "Check if there is a deadline/schedule with repeater in this entry."
13080 (save-match-data
13081 (save-excursion
13082 (org-back-to-heading t)
13083 (and (re-search-forward (if tagline
13084 (concat tagline "\\s-*" org-repeat-re)
13085 org-repeat-re)
13086 (org-entry-end-position) t)
13087 (match-string-no-properties 1)))))
13089 (defvar org-last-changed-timestamp)
13090 (defvar org-last-inserted-timestamp)
13091 (defvar org-log-post-message)
13092 (defvar org-log-note-purpose)
13093 (defvar org-log-note-how nil)
13094 (defvar org-log-note-extra)
13095 (defun org-auto-repeat-maybe (done-word)
13096 "Check if the current headline contains a repeated deadline/schedule.
13097 If yes, set TODO state back to what it was and change the base date
13098 of repeating deadline/scheduled time stamps to new date.
13099 This function is run automatically after each state change to a DONE state."
13100 ;; last-state is dynamically scoped into this function
13101 (let* ((repeat (org-get-repeat))
13102 (aa (assoc org-last-state org-todo-kwd-alist))
13103 (interpret (nth 1 aa))
13104 (head (nth 2 aa))
13105 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13106 (msg "Entry repeats: ")
13107 (org-log-done nil)
13108 (org-todo-log-states nil)
13109 re type n what ts time to-state)
13110 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13111 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13112 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13113 org-todo-repeat-to-state))
13114 (unless (and to-state (member to-state org-todo-keywords-1))
13115 (setq to-state (if (eq interpret 'type) org-last-state head)))
13116 (org-todo to-state)
13117 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13118 (org-entry-put nil "LAST_REPEAT" (format-time-string
13119 (org-time-stamp-format t t))))
13120 (when org-log-repeat
13121 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13122 (memq 'org-add-log-note post-command-hook))
13123 ;; OK, we are already setup for some record
13124 (when (eq org-log-repeat 'note)
13125 ;; make sure we take a note, not only a time stamp
13126 (setq org-log-note-how 'note))
13127 ;; Set up for taking a record
13128 (org-add-log-setup 'state
13129 (or done-word (car org-done-keywords))
13130 org-last-state
13131 org-log-repeat)))
13132 (org-back-to-heading t)
13133 (org-add-planning-info nil nil 'closed)
13134 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13135 org-deadline-time-regexp "\\)\\|\\("
13136 org-ts-regexp "\\)"))
13137 (while (re-search-forward
13138 re (save-excursion (outline-next-heading) (point)) t)
13139 (setq type (if (match-end 1) org-scheduled-string
13140 (if (match-end 3) org-deadline-string "Plain:"))
13141 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13142 (if (not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13143 (org-remove-timestamp-with-keyword org-scheduled-string)
13144 (setq n (string-to-number (match-string 2 ts))
13145 what (match-string 3 ts))
13146 (when (equal what "w") (setq n (* n 7) what "d"))
13147 (when (and (equal what "h")
13148 (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13149 (user-error
13150 "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13151 ;; Preparation, see if we need to modify the start date for the change
13152 (when (match-end 1)
13153 (setq time (save-match-data (org-time-string-to-time ts)))
13154 (cond
13155 ((equal (match-string 1 ts) ".")
13156 ;; Shift starting date to today
13157 (org-timestamp-change
13158 (- (org-today) (time-to-days time))
13159 'day))
13160 ((equal (match-string 1 ts) "+")
13161 (let ((nshiftmax 10) (nshift 0))
13162 (while (or (= nshift 0)
13163 (<= (time-to-days time)
13164 (time-to-days (current-time))))
13165 (when (= (incf nshift) nshiftmax)
13166 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13167 (user-error "Abort")))
13168 (org-timestamp-change n (cdr (assoc what whata)))
13169 (org-at-timestamp-p t)
13170 (setq ts (match-string 1))
13171 (setq time (save-match-data (org-time-string-to-time ts)))))
13172 (org-timestamp-change (- n) (cdr (assoc what whata)))
13173 ;; rematch, so that we have everything in place for the real shift
13174 (org-at-timestamp-p t)
13175 (setq ts (match-string 1))
13176 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13177 (save-excursion
13178 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13179 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13180 (setq org-log-post-message msg)
13181 (message "%s" msg))))
13183 (defun org-show-todo-tree (arg)
13184 "Make a compact tree which shows all headlines marked with TODO.
13185 The tree will show the lines where the regexp matches, and all higher
13186 headlines above the match.
13187 With a \\[universal-argument] prefix, prompt for a regexp to match.
13188 With a numeric prefix N, construct a sparse tree for the Nth element
13189 of `org-todo-keywords-1'."
13190 (interactive "P")
13191 (let ((case-fold-search nil)
13192 (kwd-re
13193 (cond ((null arg) org-not-done-regexp)
13194 ((equal arg '(4))
13195 (let ((kwd
13196 (completing-read "Keyword (or KWD1|KWD2|...): "
13197 (mapcar #'list org-todo-keywords-1))))
13198 (concat "\\("
13199 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13200 "\\)\\>")))
13201 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13202 (regexp-quote (nth (1- (prefix-numeric-value arg))
13203 org-todo-keywords-1)))
13204 (t (user-error "Invalid prefix argument: %s" arg)))))
13205 (message "%d TODO entries found"
13206 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13208 (defun org-deadline (arg &optional time)
13209 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13210 With one universal prefix argument, remove any deadline from the item.
13211 With two universal prefix arguments, prompt for a warning delay.
13212 With argument TIME, set the deadline at the corresponding date. TIME
13213 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13214 (interactive "P")
13215 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13216 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13217 'region-start-level 'region))
13218 org-loop-over-headlines-in-active-region)
13219 (org-map-entries
13220 `(org-deadline ',arg ,time)
13221 org-loop-over-headlines-in-active-region
13222 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13223 (let* ((old-date (org-entry-get nil "DEADLINE"))
13224 (old-date-time (when old-date (org-time-string-to-time old-date)))
13225 (repeater (and old-date
13226 (string-match
13227 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13228 old-date)
13229 (match-string 1 old-date))))
13230 (cond
13231 ((equal arg '(4))
13232 (when (and old-date org-log-redeadline)
13233 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13234 (org-remove-timestamp-with-keyword org-deadline-string)
13235 (message "Item no longer has a deadline."))
13236 ((equal arg '(16))
13237 (save-excursion
13238 (org-back-to-heading t)
13239 (if (re-search-forward
13240 org-deadline-time-regexp
13241 (save-excursion (outline-next-heading) (point)) t)
13242 (let* ((rpl0 (match-string 1))
13243 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13244 (replace-match
13245 (concat org-deadline-string
13246 " <" rpl
13247 (format " -%dd"
13248 (abs
13249 (- (time-to-days
13250 (save-match-data
13251 (org-read-date nil t nil "Warn starting from" old-date-time)))
13252 (time-to-days old-date-time))))
13253 ">") t t))
13254 (user-error "No deadline information to update"))))
13256 (org-add-planning-info 'deadline time 'closed)
13257 (when (and old-date
13258 org-log-redeadline
13259 (not (equal old-date org-last-inserted-timestamp)))
13260 (org-add-log-setup
13261 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13262 (when repeater
13263 (save-excursion
13264 (org-back-to-heading t)
13265 (when (re-search-forward (concat org-deadline-string " "
13266 org-last-inserted-timestamp)
13267 (save-excursion
13268 (outline-next-heading) (point)) t)
13269 (goto-char (1- (match-end 0)))
13270 (insert " " repeater)
13271 (setq org-last-inserted-timestamp
13272 (concat (substring org-last-inserted-timestamp 0 -1)
13273 " " repeater
13274 (substring org-last-inserted-timestamp -1))))))
13275 (message "Deadline on %s" org-last-inserted-timestamp))))))
13277 (defun org-schedule (arg &optional time)
13278 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13279 With one universal prefix argument, remove any scheduling date from the item.
13280 With two universal prefix arguments, prompt for a delay cookie.
13281 With argument TIME, scheduled at the corresponding date. TIME can
13282 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13283 (interactive "P")
13284 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13285 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13286 'region-start-level 'region))
13287 org-loop-over-headlines-in-active-region)
13288 (org-map-entries
13289 `(org-schedule ',arg ,time)
13290 org-loop-over-headlines-in-active-region
13291 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13292 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13293 (old-date-time (when old-date (org-time-string-to-time old-date)))
13294 (repeater (and old-date
13295 (string-match
13296 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13297 old-date)
13298 (match-string 1 old-date))))
13299 (cond
13300 ((equal arg '(4))
13301 (progn
13302 (when (and old-date org-log-reschedule)
13303 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13304 (org-remove-timestamp-with-keyword org-scheduled-string)
13305 (message "Item is no longer scheduled.")))
13306 ((equal arg '(16))
13307 (save-excursion
13308 (org-back-to-heading t)
13309 (if (re-search-forward
13310 org-scheduled-time-regexp
13311 (save-excursion (outline-next-heading) (point)) t)
13312 (let* ((rpl0 (match-string 1))
13313 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13314 (replace-match
13315 (concat org-scheduled-string
13316 " <" rpl
13317 (format " -%dd"
13318 (abs
13319 (- (time-to-days
13320 (save-match-data
13321 (org-read-date nil t nil "Delay until" old-date-time)))
13322 (time-to-days old-date-time))))
13323 ">") t t))
13324 (user-error "No scheduled information to update"))))
13326 (org-add-planning-info 'scheduled time 'closed)
13327 (when (and old-date
13328 org-log-reschedule
13329 (not (equal old-date org-last-inserted-timestamp)))
13330 (org-add-log-setup
13331 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13332 (when repeater
13333 (save-excursion
13334 (org-back-to-heading t)
13335 (when (re-search-forward (concat org-scheduled-string " "
13336 org-last-inserted-timestamp)
13337 (save-excursion
13338 (outline-next-heading) (point)) t)
13339 (goto-char (1- (match-end 0)))
13340 (insert " " repeater)
13341 (setq org-last-inserted-timestamp
13342 (concat (substring org-last-inserted-timestamp 0 -1)
13343 " " repeater
13344 (substring org-last-inserted-timestamp -1))))))
13345 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13347 (defun org-get-scheduled-time (pom &optional inherit)
13348 "Get the scheduled time as a time tuple, of a format suitable
13349 for calling org-schedule with, or if there is no scheduling,
13350 returns nil."
13351 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13352 (when time
13353 (apply 'encode-time (org-parse-time-string time)))))
13355 (defun org-get-deadline-time (pom &optional inherit)
13356 "Get the deadline as a time tuple, of a format suitable for
13357 calling org-deadline with, or if there is no scheduling, returns
13358 nil."
13359 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13360 (when time
13361 (apply 'encode-time (org-parse-time-string time)))))
13363 (defun org-remove-timestamp-with-keyword (keyword)
13364 "Remove all time stamps with KEYWORD in the current entry."
13365 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13366 beg)
13367 (save-excursion
13368 (org-back-to-heading t)
13369 (setq beg (point))
13370 (outline-next-heading)
13371 (while (re-search-backward re beg t)
13372 (replace-match "")
13373 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13374 (equal (char-before) ?\ ))
13375 (backward-delete-char 1)
13376 (when (string-match "^[ \t]*$" (buffer-substring
13377 (point-at-bol) (point-at-eol)))
13378 (delete-region (point-at-bol)
13379 (min (point-max) (1+ (point-at-eol))))))))))
13381 (defvar org-time-was-given) ; dynamically scoped parameter
13382 (defvar org-end-time-was-given) ; dynamically scoped parameter
13384 (defun org-at-planning-p ()
13385 "Non-nil when point is on a planning info line."
13386 ;; This is as accurate and faster than `org-element-at-point' since
13387 ;; planning info location is fixed in the section.
13388 (org-with-wide-buffer
13389 (beginning-of-line)
13390 (and (org-looking-at-p org-planning-line-re)
13391 (eq (point)
13392 (ignore-errors
13393 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13394 (org-back-to-heading t)
13395 (org-with-limited-levels (org-back-to-heading t)))
13396 (line-beginning-position 2))))))
13398 (defun org-add-planning-info (what &optional time &rest remove)
13399 "Insert new timestamp with keyword in the planning line.
13400 WHAT indicates what kind of time stamp to add. It is a symbol
13401 among `closed', `deadline', `scheduled' and nil. TIME indicates
13402 the time to use. If none is given, the user is prompted for
13403 a date. REMOVE indicates what kind of entries to remove. An old
13404 WHAT entry will also be removed."
13405 (let (org-time-was-given org-end-time-was-given default-time default-input)
13406 (catch 'exit
13407 (when (and (memq what '(scheduled deadline))
13408 (or (not time)
13409 (and (stringp time)
13410 (string-match "^[-+]+[0-9]" time))))
13411 ;; Try to get a default date/time from existing timestamp
13412 (save-excursion
13413 (org-back-to-heading t)
13414 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13415 (when (re-search-forward (if (eq what 'scheduled)
13416 org-scheduled-time-regexp
13417 org-deadline-time-regexp)
13418 end t)
13419 (setq ts (match-string 1)
13420 default-time (apply 'encode-time (org-parse-time-string ts))
13421 default-input (and ts (org-get-compact-tod ts)))))))
13422 (when what
13423 (setq time
13424 (if (stringp time)
13425 ;; This is a string (relative or absolute), set
13426 ;; proper date.
13427 (apply #'encode-time
13428 (org-read-date-analyze
13429 time default-time (decode-time default-time)))
13430 ;; If necessary, get the time from the user
13431 (or time (org-read-date nil 'to-time nil nil
13432 default-time default-input)))))
13434 (org-with-wide-buffer
13435 (org-back-to-heading t)
13436 (forward-line)
13437 (unless (bolp) (insert "\n"))
13438 (cond ((org-looking-at-p org-planning-line-re)
13439 ;; Move to current indentation.
13440 (skip-chars-forward " \t")
13441 ;; Check if we have to remove something.
13442 (dolist (type (if what (cons what remove) remove))
13443 (save-excursion
13444 (when (re-search-forward
13445 (case type
13446 (closed org-closed-time-regexp)
13447 (deadline org-deadline-time-regexp)
13448 (scheduled org-scheduled-time-regexp)
13449 (otherwise
13450 (error "Invalid planning type: %s" type)))
13451 (line-end-position) t)
13452 ;; Delete until next keyword or end of line.
13453 (delete-region
13454 (match-beginning 0)
13455 (if (re-search-forward org-keyword-time-not-clock-regexp
13456 (line-end-position)
13458 (match-beginning 0)
13459 (line-end-position))))))
13460 ;; If there is nothing more to add and no more keyword
13461 ;; is left, remove the line completely.
13462 (if (and (org-looking-at-p "[ \t]*$") (not what))
13463 (delete-region (line-beginning-position)
13464 (line-beginning-position 2))
13465 ;; If we removed last keyword, do not leave trailing
13466 ;; white space at the end of line.
13467 (let ((p (point)))
13468 (save-excursion
13469 (end-of-line)
13470 (unless (= (skip-chars-backward " \t" p) 0)
13471 (delete-region (point) (line-end-position)))))))
13472 ((not what) (throw 'exit nil)) ; Nothing to do.
13473 (t (insert-before-markers "\n")
13474 (backward-char 1)
13475 (when org-adapt-indentation
13476 (org-indent-to-column (1+ (org-outline-level))))))
13477 (when what
13478 ;; Insert planning keyword.
13479 (insert (case what
13480 (closed org-closed-string)
13481 (deadline org-deadline-string)
13482 (scheduled org-scheduled-string)
13483 (otherwise (error "Invalid planning type: %s" what)))
13484 " ")
13485 ;; Insert associated timestamp.
13486 (let ((ts (org-insert-time-stamp
13487 time
13488 (or org-time-was-given
13489 (and (eq what 'closed) org-log-done-with-time))
13490 (eq what 'closed)
13491 nil nil (list org-end-time-was-given))))
13492 (unless (eolp) (insert " "))
13493 ts))))))
13495 (defvar org-log-note-marker (make-marker)
13496 "Marker pointing at the entry where the note is to be inserted.")
13497 (defvar org-log-note-purpose nil)
13498 (defvar org-log-note-state nil)
13499 (defvar org-log-note-previous-state nil)
13500 (defvar org-log-note-extra nil)
13501 (defvar org-log-note-window-configuration nil)
13502 (defvar org-log-note-return-to (make-marker))
13503 (defvar org-log-note-effective-time nil
13504 "Remembered current time so that dynamically scoped
13505 `org-extend-today-until' affects timestamps in state change log")
13507 (defvar org-log-post-message nil
13508 "Message to be displayed after a log note has been stored.
13509 The auto-repeater uses this.")
13511 (defun org-add-note ()
13512 "Add a note to the current entry.
13513 This is done in the same way as adding a state change note."
13514 (interactive)
13515 (org-add-log-setup 'note))
13517 (defun org-log-beginning (&optional create)
13518 "Return expected start of log notes in current entry.
13519 When optional argument CREATE is non-nil, the function creates
13520 a drawer to store notes, if necessary. Returned position ignores
13521 narrowing."
13522 (org-with-wide-buffer
13523 (let ((drawer (org-log-into-drawer)))
13524 (cond
13525 (drawer
13526 (org-end-of-meta-data)
13527 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13528 (end (if (org-at-heading-p) (point)
13529 (save-excursion (outline-next-heading) (point))))
13530 (case-fold-search t))
13531 (catch 'exit
13532 ;; Try to find existing drawer.
13533 (while (re-search-forward regexp end t)
13534 (let ((element (org-element-at-point)))
13535 (when (eq (org-element-type element) 'drawer)
13536 (let ((cend (org-element-property :contents-end element)))
13537 (when (and (not org-log-states-order-reversed) cend)
13538 (goto-char cend)))
13539 (throw 'exit nil))))
13540 ;; No drawer found. Create one, if permitted.
13541 (when create
13542 (unless (bolp) (insert "\n"))
13543 (let ((beg (point)))
13544 (insert ":" drawer ":\n:END:\n")
13545 (org-indent-region beg (point)))
13546 (end-of-line -1)))))
13548 (when org-log-state-notes-insert-after-drawers (org-end-of-meta-data t))
13549 (skip-chars-forward " \t\n")
13550 (beginning-of-line)
13551 (unless org-log-states-order-reversed
13552 (org-skip-over-state-notes)
13553 (skip-chars-backward " \t\n")
13554 (forward-line)))))
13555 (if (bolp) (point) (line-beginning-position 2))))
13557 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13558 "Set up the post command hook to take a note.
13559 If this is about to TODO state change, the new state is expected in STATE.
13560 HOW is an indicator what kind of note should be created.
13561 EXTRA is additional text that will be inserted into the notes buffer."
13562 (move-marker org-log-note-marker (point))
13563 (setq org-log-note-purpose purpose
13564 org-log-note-state state
13565 org-log-note-previous-state prev-state
13566 org-log-note-how how
13567 org-log-note-extra extra
13568 org-log-note-effective-time (org-current-effective-time))
13569 (add-hook 'post-command-hook 'org-add-log-note 'append))
13571 (defun org-skip-over-state-notes ()
13572 "Skip past the list of State notes in an entry."
13573 (when (ignore-errors (goto-char (org-in-item-p)))
13574 (let* ((struct (org-list-struct))
13575 (prevs (org-list-prevs-alist struct))
13576 (regexp
13577 (concat "[ \t]*- +"
13578 (replace-regexp-in-string
13579 " +" " +"
13580 (org-replace-escapes
13581 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13582 `(("%d" . ,org-ts-regexp-inactive)
13583 ("%D" . ,org-ts-regexp)
13584 ("%s" . "\"\\S-+\"")
13585 ("%S" . "\"\\S-+\"")
13586 ("%t" . ,org-ts-regexp-inactive)
13587 ("%T" . ,org-ts-regexp)
13588 ("%u" . ".*?")
13589 ("%U" . ".*?")))))))
13590 (while (org-looking-at-p regexp)
13591 (goto-char (or (org-list-get-next-item (point) struct prevs)
13592 (org-list-get-item-end (point) struct)))))))
13594 (defun org-add-log-note (&optional _purpose)
13595 "Pop up a window for taking a note, and add this note later."
13596 (remove-hook 'post-command-hook 'org-add-log-note)
13597 (setq org-log-note-window-configuration (current-window-configuration))
13598 (delete-other-windows)
13599 (move-marker org-log-note-return-to (point))
13600 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13601 (goto-char org-log-note-marker)
13602 (org-switch-to-buffer-other-window "*Org Note*")
13603 (erase-buffer)
13604 (if (memq org-log-note-how '(time state))
13605 (let (current-prefix-arg) (org-store-log-note))
13606 (let ((org-inhibit-startup t)) (org-mode))
13607 (insert (format "# Insert note for %s.
13608 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13609 (cond
13610 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13611 ((eq org-log-note-purpose 'done) "closed todo item")
13612 ((eq org-log-note-purpose 'state)
13613 (format "state change from \"%s\" to \"%s\""
13614 (or org-log-note-previous-state "")
13615 (or org-log-note-state "")))
13616 ((eq org-log-note-purpose 'reschedule)
13617 "rescheduling")
13618 ((eq org-log-note-purpose 'delschedule)
13619 "no longer scheduled")
13620 ((eq org-log-note-purpose 'redeadline)
13621 "changing deadline")
13622 ((eq org-log-note-purpose 'deldeadline)
13623 "removing deadline")
13624 ((eq org-log-note-purpose 'refile)
13625 "refiling")
13626 ((eq org-log-note-purpose 'note)
13627 "this entry")
13628 (t (error "This should not happen")))))
13629 (when org-log-note-extra (insert org-log-note-extra))
13630 (setq-local org-finish-function 'org-store-log-note)
13631 (run-hooks 'org-log-buffer-setup-hook)))
13633 (defvar org-note-abort nil) ; dynamically scoped
13634 (defun org-store-log-note ()
13635 "Finish taking a log note, and insert it to where it belongs."
13636 (let ((txt (prog1 (buffer-string)
13637 (kill-buffer)))
13638 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13639 lines)
13640 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13641 (setq txt (replace-match "" t t txt)))
13642 (when (string-match "\\s-+\\'" txt)
13643 (setq txt (replace-match "" t t txt)))
13644 (setq lines (org-split-string txt "\n"))
13645 (when (org-string-nw-p note)
13646 (setq note
13647 (org-replace-escapes
13648 note
13649 (list (cons "%u" (user-login-name))
13650 (cons "%U" user-full-name)
13651 (cons "%t" (format-time-string
13652 (org-time-stamp-format 'long 'inactive)
13653 org-log-note-effective-time))
13654 (cons "%T" (format-time-string
13655 (org-time-stamp-format 'long nil)
13656 org-log-note-effective-time))
13657 (cons "%d" (format-time-string
13658 (org-time-stamp-format nil 'inactive)
13659 org-log-note-effective-time))
13660 (cons "%D" (format-time-string
13661 (org-time-stamp-format nil nil)
13662 org-log-note-effective-time))
13663 (cons "%s" (cond
13664 ((not org-log-note-state) "")
13665 ((org-string-match-p org-ts-regexp
13666 org-log-note-state)
13667 (format "\"[%s]\""
13668 (substring org-log-note-state 1 -1)))
13669 (t (format "\"%s\"" org-log-note-state))))
13670 (cons "%S"
13671 (cond
13672 ((not org-log-note-previous-state) "")
13673 ((org-string-match-p org-ts-regexp
13674 org-log-note-previous-state)
13675 (format "\"[%s]\""
13676 (substring
13677 org-log-note-previous-state 1 -1)))
13678 (t (format "\"%s\""
13679 org-log-note-previous-state)))))))
13680 (when lines (setq note (concat note " \\\\")))
13681 (push note lines))
13682 (when (and lines (not (or current-prefix-arg org-note-abort)))
13683 (with-current-buffer (marker-buffer org-log-note-marker)
13684 (org-with-wide-buffer
13685 ;; Find location for the new note.
13686 (goto-char org-log-note-marker)
13687 (set-marker org-log-note-marker nil)
13688 (goto-char (org-log-beginning t))
13689 ;; Make sure point is at the beginning of an empty line.
13690 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13691 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13692 ;; In an existing list, add a new item at the top level.
13693 ;; Otherwise, indent line like a regular one.
13694 (let ((itemp (org-in-item-p)))
13695 (if itemp
13696 (org-indent-line-to
13697 (let ((struct (save-excursion
13698 (goto-char itemp) (org-list-struct))))
13699 (org-list-get-ind (org-list-get-top-point struct) struct)))
13700 (org-indent-line)))
13701 (insert (org-list-bullet-string "-") (pop lines))
13702 (let ((ind (org-list-item-body-column (line-beginning-position))))
13703 (dolist (line lines)
13704 (insert "\n")
13705 (org-indent-line-to ind)
13706 (insert line)))
13707 (message "Note stored")
13708 (org-back-to-heading t)
13709 (org-cycle-hide-drawers 'children))
13710 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13711 ;; from within `org-add-log-note' because `buffer-undo-list'
13712 ;; is then modified outside of `org-with-remote-undo'.
13713 (when (eq this-command 'org-agenda-todo)
13714 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13715 ;; Don't add undo information when called from `org-agenda-todo'.
13716 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13717 (set-window-configuration org-log-note-window-configuration)
13718 (with-current-buffer (marker-buffer org-log-note-return-to)
13719 (goto-char org-log-note-return-to))
13720 (move-marker org-log-note-return-to nil)
13721 (when org-log-post-message (message "%s" org-log-post-message))))
13723 (defun org-remove-empty-drawer-at (pos)
13724 "Remove an empty drawer at position POS.
13725 POS may also be a marker."
13726 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13727 (org-with-wide-buffer
13728 (goto-char pos)
13729 (let ((drawer (org-element-at-point)))
13730 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13731 (not (org-element-property :contents-begin drawer)))
13732 (delete-region (org-element-property :begin drawer)
13733 (progn (goto-char (org-element-property :end drawer))
13734 (skip-chars-backward " \r\t\n")
13735 (forward-line)
13736 (point))))))))
13738 (defvar org-ts-type nil)
13739 (defun org-sparse-tree (&optional arg type)
13740 "Create a sparse tree, prompt for the details.
13741 This command can create sparse trees. You first need to select the type
13742 of match used to create the tree:
13744 t Show all TODO entries.
13745 T Show entries with a specific TODO keyword.
13746 m Show entries selected by a tags/property match.
13747 p Enter a property name and its value (both with completion on existing
13748 names/values) and show entries with that property.
13749 r Show entries matching a regular expression (`/' can be used as well).
13750 b Show deadlines and scheduled items before a date.
13751 a Show deadlines and scheduled items after a date.
13752 d Show deadlines due within `org-deadline-warning-days'.
13753 D Show deadlines and scheduled items between a date range."
13754 (interactive "P")
13755 (setq type (or type org-sparse-tree-default-date-type))
13756 (setq org-ts-type type)
13757 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13758 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13759 [c]ycle through date types: %s"
13760 (case type
13761 (all "all timestamps")
13762 (scheduled "only scheduled")
13763 (deadline "only deadline")
13764 (active "only active timestamps")
13765 (inactive "only inactive timestamps")
13766 (closed "with a closed time-stamp")
13767 (otherwise "scheduled/deadline")))
13768 (let ((answer (read-char-exclusive)))
13769 (case answer
13771 (org-sparse-tree
13773 (cadr
13774 (memq type '(nil all scheduled deadline active inactive closed)))))
13775 (?d (call-interactively 'org-check-deadlines))
13776 (?b (call-interactively 'org-check-before-date))
13777 (?a (call-interactively 'org-check-after-date))
13778 (?D (call-interactively 'org-check-dates-range))
13779 (?t (call-interactively 'org-show-todo-tree))
13780 (?T (org-show-todo-tree '(4)))
13781 (?m (call-interactively 'org-match-sparse-tree))
13782 ((?p ?P)
13783 (let* ((kwd (completing-read
13784 "Property: " (mapcar #'list (org-buffer-property-keys))))
13785 (value (completing-read
13786 "Value: " (mapcar #'list (org-property-values kwd)))))
13787 (unless (string-match "\\`{.*}\\'" value)
13788 (setq value (concat "\"" value "\"")))
13789 (org-match-sparse-tree arg (concat kwd "=" value))))
13790 ((?r ?R ?/) (call-interactively 'org-occur))
13791 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13793 (defvar-local org-occur-highlights nil
13794 "List of overlays used for occur matches.")
13795 (defvar-local org-occur-parameters nil
13796 "Parameters of the active org-occur calls.
13797 This is a list, each call to org-occur pushes as cons cell,
13798 containing the regular expression and the callback, onto the list.
13799 The list can contain several entries if `org-occur' has been called
13800 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13801 will only contain one set of parameters. When the highlights are
13802 removed (for example with `C-c C-c', or with the next edit (depending
13803 on `org-remove-highlights-with-change'), this variable is emptied
13804 as well.")
13806 (defun org-occur (regexp &optional keep-previous callback)
13807 "Make a compact tree which shows all matches of REGEXP.
13808 The tree will show the lines where the regexp matches, and all higher
13809 headlines above the match. It will also show the heading after the match,
13810 to make sure editing the matching entry is easy.
13811 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13812 call to `org-occur' will be kept, to allow stacking of calls to this
13813 command.
13814 If CALLBACK is non-nil, it is a function which is called to confirm
13815 that the match should indeed be shown."
13816 (interactive "sRegexp: \nP")
13817 (when (equal regexp "")
13818 (user-error "Regexp cannot be empty"))
13819 (unless keep-previous
13820 (org-remove-occur-highlights nil nil t))
13821 (push (cons regexp callback) org-occur-parameters)
13822 (let ((cnt 0))
13823 (save-excursion
13824 (goto-char (point-min))
13825 (when (or (not keep-previous) ; do not want to keep
13826 (not org-occur-highlights)) ; no previous matches
13827 ;; hide everything
13828 (org-overview))
13829 (while (re-search-forward regexp nil t)
13830 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13831 (when (or (not callback)
13832 (save-match-data (funcall callback)))
13833 (setq cnt (1+ cnt))
13834 (when org-highlight-sparse-tree-matches
13835 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13836 (org-show-context 'occur-tree))))
13837 (when org-remove-highlights-with-change
13838 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13839 nil 'local))
13840 (unless org-sparse-tree-open-archived-trees
13841 (org-hide-archived-subtrees (point-min) (point-max)))
13842 (run-hooks 'org-occur-hook)
13843 (when (org-called-interactively-p 'interactive)
13844 (message "%d match(es) for regexp %s" cnt regexp))
13845 cnt))
13847 (defun org-occur-next-match (&optional n _reset)
13848 "Function for `next-error-function' to find sparse tree matches.
13849 N is the number of matches to move, when negative move backwards.
13850 This function always goes back to the starting point when no
13851 match is found."
13852 (let* ((limit (if (< n 0) (point-min) (point-max)))
13853 (search-func (if (< n 0)
13854 'previous-single-char-property-change
13855 'next-single-char-property-change))
13856 (n (abs n))
13857 (pos (point))
13859 (catch 'exit
13860 (while (setq p1 (funcall search-func (point) 'org-type))
13861 (when (equal p1 limit)
13862 (goto-char pos)
13863 (user-error "No more matches"))
13864 (when (equal (get-char-property p1 'org-type) 'org-occur)
13865 (setq n (1- n))
13866 (when (= n 0)
13867 (goto-char p1)
13868 (throw 'exit (point))))
13869 (goto-char p1))
13870 (goto-char p1)
13871 (user-error "No more matches"))))
13873 (defun org-show-context (&optional key)
13874 "Make sure point and context are visible.
13875 Optional argument KEY, when non-nil, is a symbol. See
13876 `org-show-context-detail' for allowed values and how much is to
13877 be shown."
13878 (org-show-set-visibility
13879 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13880 ((cdr (assq key org-show-context-detail)))
13881 (t (cdr (assq 'default org-show-context-detail))))))
13883 (defun org-show-set-visibility (detail)
13884 "Set visibility around point according to DETAIL.
13885 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13886 `tree', `canonical' or t. See `org-show-context-detail' for more
13887 information."
13888 (unless (org-before-first-heading-p)
13889 ;; Show current heading and possibly its entry, following headline
13890 ;; or all children.
13891 (if (and (org-at-heading-p) (not (eq detail 'local)))
13892 (org-flag-heading nil)
13893 (org-show-entry)
13894 (org-with-limited-levels
13895 (case detail
13896 ((tree canonical t) (org-show-children))
13897 ((nil minimal ancestors))
13898 (t (save-excursion
13899 (outline-next-heading)
13900 (org-flag-heading nil))))))
13901 ;; Show all siblings.
13902 (when (eq detail 'lineage) (org-show-siblings))
13903 ;; Show ancestors, possibly with their children.
13904 (when (memq detail '(ancestors lineage tree canonical t))
13905 (save-excursion
13906 (while (org-up-heading-safe)
13907 (org-flag-heading nil)
13908 (when (memq detail '(canonical t)) (org-show-entry))
13909 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13911 (defvar org-reveal-start-hook nil
13912 "Hook run before revealing a location.")
13914 (defun org-reveal (&optional siblings)
13915 "Show current entry, hierarchy above it, and the following headline.
13917 This can be used to show a consistent set of context around
13918 locations exposed with `org-show-context'.
13920 With optional argument SIBLINGS, on each level of the hierarchy all
13921 siblings are shown. This repairs the tree structure to what it would
13922 look like when opened with hierarchical calls to `org-cycle'.
13924 With double optional argument \\[universal-argument] \\[universal-argument], \
13925 go to the parent and show the
13926 entire tree."
13927 (interactive "P")
13928 (run-hooks 'org-reveal-start-hook)
13929 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13930 ((equal siblings '(16))
13931 (save-excursion
13932 (when (org-up-heading-safe)
13933 (org-show-subtree)
13934 (run-hook-with-args 'org-cycle-hook 'subtree))))
13935 (t (org-show-set-visibility 'lineage))))
13937 (defun org-highlight-new-match (beg end)
13938 "Highlight from BEG to END and mark the highlight is an occur headline."
13939 (let ((ov (make-overlay beg end)))
13940 (overlay-put ov 'face 'secondary-selection)
13941 (overlay-put ov 'org-type 'org-occur)
13942 (push ov org-occur-highlights)))
13944 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13945 "Remove the occur highlights from the buffer.
13946 BEG and END are ignored. If NOREMOVE is nil, remove this function
13947 from the `before-change-functions' in the current buffer."
13948 (interactive)
13949 (unless org-inhibit-highlight-removal
13950 (mapc #'delete-overlay org-occur-highlights)
13951 (setq org-occur-highlights nil)
13952 (setq org-occur-parameters nil)
13953 (unless noremove
13954 (remove-hook 'before-change-functions
13955 'org-remove-occur-highlights 'local))))
13957 ;;;; Priorities
13959 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13960 "Regular expression matching the priority indicator.")
13962 (defvar org-remove-priority-next-time nil)
13964 (defun org-priority-up ()
13965 "Increase the priority of the current item."
13966 (interactive)
13967 (org-priority 'up))
13969 (defun org-priority-down ()
13970 "Decrease the priority of the current item."
13971 (interactive)
13972 (org-priority 'down))
13974 (defun org-priority (&optional action _show)
13975 "Change the priority of an item.
13976 ACTION can be `set', `up', `down', or a character."
13977 (interactive "P")
13978 (if (equal action '(4))
13979 (org-show-priority)
13980 (unless org-enable-priority-commands
13981 (user-error "Priority commands are disabled"))
13982 (setq action (or action 'set))
13983 (let (current new news have remove)
13984 (save-excursion
13985 (org-back-to-heading t)
13986 (when (looking-at org-priority-regexp)
13987 (setq current (string-to-char (match-string 2))
13988 have t))
13989 (cond
13990 ((eq action 'remove)
13991 (setq remove t new ?\ ))
13992 ((or (eq action 'set)
13993 (if (featurep 'xemacs) (characterp action) (integerp action)))
13994 (if (not (eq action 'set))
13995 (setq new action)
13996 (message "Priority %c-%c, SPC to remove: "
13997 org-highest-priority org-lowest-priority)
13998 (save-match-data
13999 (setq new (read-char-exclusive))))
14000 (when (and (= (upcase org-highest-priority) org-highest-priority)
14001 (= (upcase org-lowest-priority) org-lowest-priority))
14002 (setq new (upcase new)))
14003 (cond ((equal new ?\ ) (setq remove t))
14004 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14005 (user-error "Priority must be between `%c' and `%c'"
14006 org-highest-priority org-lowest-priority))))
14007 ((eq action 'up)
14008 (setq new (if have
14009 (1- current) ; normal cycling
14010 ;; last priority was empty
14011 (if (eq last-command this-command)
14012 org-lowest-priority ; wrap around empty to lowest
14013 ;; default
14014 (if org-priority-start-cycle-with-default
14015 org-default-priority
14016 (1- org-default-priority))))))
14017 ((eq action 'down)
14018 (setq new (if have
14019 (1+ current) ; normal cycling
14020 ;; last priority was empty
14021 (if (eq last-command this-command)
14022 org-highest-priority ; wrap around empty to highest
14023 ;; default
14024 (if org-priority-start-cycle-with-default
14025 org-default-priority
14026 (1+ org-default-priority))))))
14027 (t (user-error "Invalid action")))
14028 (when (or (< (upcase new) org-highest-priority)
14029 (> (upcase new) org-lowest-priority))
14030 (if (and (memq action '(up down))
14031 (not have) (not (eq last-command this-command)))
14032 ;; `new' is from default priority
14033 (error
14034 "The default can not be set, see `org-default-priority' why")
14035 ;; normal cycling: `new' is beyond highest/lowest priority
14036 ;; and is wrapped around to the empty priority
14037 (setq remove t)))
14038 (setq news (format "%c" new))
14039 (if have
14040 (if remove
14041 (replace-match "" t t nil 1)
14042 (replace-match news t t nil 2))
14043 (if remove
14044 (user-error "No priority cookie found in line")
14045 (let ((case-fold-search nil))
14046 (looking-at org-todo-line-regexp))
14047 (if (match-end 2)
14048 (progn
14049 (goto-char (match-end 2))
14050 (insert " [#" news "]"))
14051 (goto-char (match-beginning 3))
14052 (insert "[#" news "] "))))
14053 (org-set-tags nil 'align))
14054 (if remove
14055 (message "Priority removed")
14056 (message "Priority of current item set to %s" news)))))
14058 (defun org-show-priority ()
14059 "Show the priority of the current item.
14060 This priority is composed of the main priority given with the [#A] cookies,
14061 and by additional input from the age of a schedules or deadline entry."
14062 (interactive)
14063 (let ((pri (if (eq major-mode 'org-agenda-mode)
14064 (org-get-at-bol 'priority)
14065 (save-excursion
14066 (save-match-data
14067 (beginning-of-line)
14068 (and (looking-at org-heading-regexp)
14069 (org-get-priority (match-string 0))))))))
14070 (message "Priority is %d" (if pri pri -1000))))
14072 (defun org-get-priority (s)
14073 "Find priority cookie and return priority."
14074 (save-match-data
14075 (if (functionp org-get-priority-function)
14076 (funcall org-get-priority-function)
14077 (if (not (string-match org-priority-regexp s))
14078 (* 1000 (- org-lowest-priority org-default-priority))
14079 (* 1000 (- org-lowest-priority
14080 (string-to-char (match-string 2 s))))))))
14082 ;;;; Tags
14084 (defvar org-agenda-archives-mode)
14085 (defvar org-map-continue-from nil
14086 "Position from where mapping should continue.
14087 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14089 (defvar org-scanner-tags nil
14090 "The current tag list while the tags scanner is running.")
14092 (defvar org-trust-scanner-tags nil
14093 "Should `org-get-tags-at' use the tags for the scanner.
14094 This is for internal dynamical scoping only.
14095 When this is non-nil, the function `org-get-tags-at' will return the value
14096 of `org-scanner-tags' instead of building the list by itself. This
14097 can lead to large speed-ups when the tags scanner is used in a file with
14098 many entries, and when the list of tags is retrieved, for example to
14099 obtain a list of properties. Building the tags list for each entry in such
14100 a file becomes an N^2 operation - but with this variable set, it scales
14101 as N.")
14103 (defvar org--matcher-tags-todo-only nil)
14105 (defun org-scan-tags (action matcher todo-only &optional start-level)
14106 "Scan headline tags with inheritance and produce output ACTION.
14108 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14109 or `agenda' to produce an entry list for an agenda view. It can also be
14110 a Lisp form or a function that should be called at each matched headline, in
14111 this case the return value is a list of all return values from these calls.
14113 MATCHER is a function accepting three arguments, returning
14114 a non-nil value whenever a given set of tags qualifies a headline
14115 for inclusion. See `org-make-tags-matcher' for more information.
14116 As a special case, it can also be set to t (respectively nil) in
14117 order to match all (respectively none) headline.
14119 When TODO-ONLY is non-nil, only lines with a not-done TODO
14120 keyword are included in the output.
14122 START-LEVEL can be a string with asterisks, reducing the scope to
14123 headlines matching this string."
14124 (require 'org-agenda)
14125 (let* ((re (concat "^"
14126 (if start-level
14127 ;; Get the correct level to match
14128 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14129 org-outline-regexp)
14130 " *\\(\\<\\("
14131 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14132 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14133 (props (list 'face 'default
14134 'done-face 'org-agenda-done
14135 'undone-face 'default
14136 'mouse-face 'highlight
14137 'org-not-done-regexp org-not-done-regexp
14138 'org-todo-regexp org-todo-regexp
14139 'org-complex-heading-regexp org-complex-heading-regexp
14140 'help-echo
14141 (format "mouse-2 or RET jump to org file %s"
14142 (abbreviate-file-name
14143 (or (buffer-file-name (buffer-base-buffer))
14144 (buffer-name (buffer-base-buffer)))))))
14145 (org-map-continue-from nil)
14146 lspos tags tags-list
14147 (tags-alist (list (cons 0 org-file-tags)))
14148 (llast 0) rtn rtn1 level category i txt
14149 todo marker entry priority
14150 ts-date ts-date-type ts-date-pair)
14151 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14152 (setq action (list 'lambda nil action)))
14153 (save-excursion
14154 (goto-char (point-min))
14155 (when (eq action 'sparse-tree)
14156 (org-overview)
14157 (org-remove-occur-highlights))
14158 (while (let (case-fold-search)
14159 (re-search-forward re nil t))
14160 (setq org-map-continue-from nil)
14161 (catch :skip
14162 (setq todo
14163 ;; TODO: is the 1-2 difference a bug?
14164 (when (match-end 1) (org-match-string-no-properties 2))
14165 tags (when (match-end 4) (org-match-string-no-properties 4)))
14166 (goto-char (setq lspos (match-beginning 0)))
14167 (setq level (org-reduced-level (org-outline-level))
14168 category (org-get-category))
14169 (when (eq action 'agenda)
14170 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14171 ts-date (car ts-date-pair)
14172 ts-date-type (cdr ts-date-pair)))
14173 (setq i llast llast level)
14174 ;; remove tag lists from same and sublevels
14175 (while (>= i level)
14176 (when (setq entry (assoc i tags-alist))
14177 (setq tags-alist (delete entry tags-alist)))
14178 (setq i (1- i)))
14179 ;; add the next tags
14180 (when tags
14181 (setq tags (org-split-string tags ":")
14182 tags-alist
14183 (cons (cons level tags) tags-alist)))
14184 ;; compile tags for current headline
14185 (setq tags-list
14186 (if org-use-tag-inheritance
14187 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14188 tags)
14189 org-scanner-tags tags-list)
14190 (when org-use-tag-inheritance
14191 (setcdr (car tags-alist)
14192 (mapcar (lambda (x)
14193 (setq x (copy-sequence x))
14194 (org-add-prop-inherited x))
14195 (cdar tags-alist))))
14196 (when (and tags org-use-tag-inheritance
14197 (or (not (eq t org-use-tag-inheritance))
14198 org-tags-exclude-from-inheritance))
14199 ;; Selective inheritance, remove uninherited ones.
14200 (setcdr (car tags-alist)
14201 (org-remove-uninherited-tags (cdar tags-alist))))
14202 (when (and
14204 ;; eval matcher only when the todo condition is OK
14205 (and (or (not todo-only) (member todo org-not-done-keywords))
14206 (if (functionp matcher)
14207 (let ((case-fold-search t) (org-trust-scanner-tags t))
14208 (funcall matcher todo tags-list level))
14209 matcher))
14211 ;; Call the skipper, but return t if it does not
14212 ;; skip, so that the `and' form continues evaluating.
14213 (progn
14214 (unless (eq action 'sparse-tree) (org-agenda-skip))
14217 ;; Check if timestamps are deselecting this entry
14218 (or (not todo-only)
14219 (and (member todo org-not-done-keywords)
14220 (or (not org-agenda-tags-todo-honor-ignore-options)
14221 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14223 ;; select this headline
14224 (cond
14225 ((eq action 'sparse-tree)
14226 (and org-highlight-sparse-tree-matches
14227 (org-get-heading) (match-end 0)
14228 (org-highlight-new-match
14229 (match-beginning 1) (match-end 1)))
14230 (org-show-context 'tags-tree))
14231 ((eq action 'agenda)
14232 (setq txt (org-agenda-format-item
14234 (concat
14235 (if (eq org-tags-match-list-sublevels 'indented)
14236 (make-string (1- level) ?.) "")
14237 (org-get-heading))
14238 (make-string level ?\s)
14239 category
14240 tags-list)
14241 priority (org-get-priority txt))
14242 (goto-char lspos)
14243 (setq marker (org-agenda-new-marker))
14244 (org-add-props txt props
14245 'org-marker marker 'org-hd-marker marker 'org-category category
14246 'todo-state todo
14247 'ts-date ts-date
14248 'priority priority
14249 'type (concat "tagsmatch" ts-date-type))
14250 (push txt rtn))
14251 ((functionp action)
14252 (setq org-map-continue-from nil)
14253 (save-excursion
14254 (setq rtn1 (funcall action))
14255 (push rtn1 rtn)))
14256 (t (user-error "Invalid action")))
14258 ;; if we are to skip sublevels, jump to end of subtree
14259 (unless org-tags-match-list-sublevels
14260 (org-end-of-subtree t)
14261 (backward-char 1))))
14262 ;; Get the correct position from where to continue
14263 (if org-map-continue-from
14264 (goto-char org-map-continue-from)
14265 (and (= (point) lspos) (end-of-line 1)))))
14266 (when (and (eq action 'sparse-tree)
14267 (not org-sparse-tree-open-archived-trees))
14268 (org-hide-archived-subtrees (point-min) (point-max)))
14269 (nreverse rtn)))
14271 (defun org-remove-uninherited-tags (tags)
14272 "Remove all tags that are not inherited from the list TAGS."
14273 (cond
14274 ((eq org-use-tag-inheritance t)
14275 (if org-tags-exclude-from-inheritance
14276 (org-delete-all org-tags-exclude-from-inheritance tags)
14277 tags))
14278 ((not org-use-tag-inheritance) nil)
14279 ((stringp org-use-tag-inheritance)
14280 (delq nil (mapcar
14281 (lambda (x)
14282 (if (and (string-match org-use-tag-inheritance x)
14283 (not (member x org-tags-exclude-from-inheritance)))
14284 x nil))
14285 tags)))
14286 ((listp org-use-tag-inheritance)
14287 (delq nil (mapcar
14288 (lambda (x)
14289 (if (member x org-use-tag-inheritance) x nil))
14290 tags)))))
14292 (defun org-match-sparse-tree (&optional todo-only match)
14293 "Create a sparse tree according to tags string MATCH.
14294 MATCH can contain positive and negative selection of tags, like
14295 \"+WORK+URGENT-WITHBOSS\".
14296 If optional argument TODO-ONLY is non-nil, only select lines that are
14297 also TODO lines."
14298 (interactive "P")
14299 (org-agenda-prepare-buffers (list (current-buffer)))
14300 (let ((org--matcher-tags-todo-only todo-only))
14301 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14302 org--matcher-tags-todo-only)))
14304 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14306 (defvar org-cached-props nil)
14307 (defun org-cached-entry-get (pom property)
14308 (if (or (eq t org-use-property-inheritance)
14309 (and (stringp org-use-property-inheritance)
14310 (let ((case-fold-search t))
14311 (org-string-match-p org-use-property-inheritance property)))
14312 (and (listp org-use-property-inheritance)
14313 (member-ignore-case property org-use-property-inheritance)))
14314 ;; Caching is not possible, check it directly.
14315 (org-entry-get pom property 'inherit)
14316 ;; Get all properties, so we can do complicated checks easily.
14317 (cdr (assoc-string property
14318 (or org-cached-props
14319 (setq org-cached-props (org-entry-properties pom)))
14320 t))))
14322 (defun org-global-tags-completion-table (&optional files)
14323 "Return the list of all tags in all agenda buffer/files.
14324 Optional FILES argument is a list of files which can be used
14325 instead of the agenda files."
14326 (save-excursion
14327 (org-uniquify
14328 (delq nil
14329 (apply 'append
14330 (mapcar
14331 (lambda (file)
14332 (set-buffer (find-file-noselect file))
14333 (append (org-get-buffer-tags)
14334 (mapcar (lambda (x) (if (stringp (car-safe x))
14335 (list (car-safe x)) nil))
14336 org-tag-alist)))
14337 (if (and files (car files))
14338 files
14339 (org-agenda-files))))))))
14341 (defun org-make-tags-matcher (match)
14342 "Create the TAGS/TODO matcher form for the selection string MATCH.
14344 Returns a cons of the selection string MATCH and a function
14345 implementing the matcher.
14347 The matcher is to be called at an Org entry, with point on the
14348 headline, and returns non-nil if the entry matches the selection
14349 string MATCH. It must be called with three arguments: the TODO
14350 keyword at the entry (or nil if none), the list of all tags at
14351 the entry including inherited ones and the reduced level of the
14352 headline. Additionally, the category of the entry, if any, must
14353 be specified as the text property `org-category' on the headline.
14355 This function sets the variable `org--matcher-tags-todo-only' to
14356 a non-nil value if the matcher restricts matching to TODO
14357 entries, otherwise it is not touched.
14359 See also `org-scan-tags'."
14360 (unless match
14361 ;; Get a new match request, with completion against the global
14362 ;; tags table and the local tags in current buffer.
14363 (let ((org-last-tags-completion-table
14364 (org-uniquify
14365 (delq nil (append (org-get-buffer-tags)
14366 (org-global-tags-completion-table))))))
14367 (setq match
14368 (completing-read
14369 "Match: "
14370 'org-tags-completion-function nil nil nil 'org-tags-history))))
14372 (let ((match0 match)
14373 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14374 (start 0)
14375 tagsmatch todomatch tagsmatcher todomatcher)
14377 ;; Expand group tags.
14378 (setq match (org-tags-expand match))
14380 ;; Check if there is a TODO part of this match, which would be the
14381 ;; part after a "/". To make sure that this slash is not part of
14382 ;; a property value to be matched against, we also check that
14383 ;; there is no / after that slash. First, find the last slash.
14384 (let ((s 0))
14385 (while (string-match "/+" match s)
14386 (setq start (match-beginning 0))
14387 (setq s (match-end 0))))
14388 (if (and (string-match "/+" match start)
14389 (not (string-match-p "\"" match start)))
14390 ;; Match contains also a TODO-matching request.
14391 (progn
14392 (setq tagsmatch (substring match 0 (match-beginning 0)))
14393 (setq todomatch (substring match (match-end 0)))
14394 (when (string-match "\\`!" todomatch)
14395 (setq org--matcher-tags-todo-only t)
14396 (setq todomatch (substring todomatch 1)))
14397 (when (string-match "\\`\\s-*\\'" todomatch)
14398 (setq todomatch nil)))
14399 ;; Only matching tags.
14400 (setq tagsmatch match)
14401 (setq todomatch nil))
14403 ;; Make the tags matcher.
14404 (if (not (org-string-nw-p tagsmatch))
14405 (setq tagsmatcher t)
14406 (let ((orlist nil)
14407 (orterms (org-split-string tagsmatch "|"))
14408 term)
14409 (while (setq term (pop orterms))
14410 (while (and (equal (substring term -1) "\\") orterms)
14411 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14412 (while (string-match re term)
14413 (let* ((rest (substring term (match-end 0)))
14414 (minus (and (match-end 1)
14415 (equal (match-string 1 term) "-")))
14416 (tag (save-match-data
14417 (replace-regexp-in-string
14418 "\\\\-" "-" (match-string 2 term))))
14419 (regexp (eq (string-to-char tag) ?{))
14420 (levelp (match-end 4))
14421 (propp (match-end 5))
14423 (cond
14424 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14425 (levelp
14426 `(,(org-op-to-function (match-string 3 term))
14427 level
14428 ,(string-to-number (match-string 4 term))))
14429 (propp
14430 (let* ((gv (pcase (upcase (match-string 5 term))
14431 ("CATEGORY"
14432 '(get-text-property (point) 'org-category))
14433 ("TODO" 'todo)
14434 (p `(org-cached-entry-get nil ,p))))
14435 (pv (match-string 7 term))
14436 (regexp (eq (string-to-char pv) ?{))
14437 (strp (eq (string-to-char pv) ?\"))
14438 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14439 (po (org-op-to-function (match-string 6 term)
14440 (if timep 'time strp))))
14441 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14442 (when timep (setq pv (org-matcher-time pv)))
14443 (cond ((and regexp (eq po 'org<>))
14444 `(not (string-match ,pv (or ,gv ""))))
14445 (regexp `(string-match ,pv (or ,gv "")))
14446 (strp `(,po (or ,gv "") ,pv))
14448 `(,po
14449 (string-to-number (or ,gv ""))
14450 ,(string-to-number pv))))))
14451 (t `(member ,tag tags-list)))))
14452 (push (if minus `(not ,mm) mm) tagsmatcher)
14453 (setq term rest)))
14454 (push (if (> (length tagsmatcher) 1)
14455 (cons 'and tagsmatcher)
14456 (car tagsmatcher))
14457 orlist)
14458 (setq tagsmatcher nil))
14459 (setq tagsmatcher
14460 `(progn (setq org-cached-props nil) ,(cons 'or orlist)))))
14462 ;; Make the TODO matcher.
14463 (if (not (org-string-nw-p todomatch))
14464 (setq todomatcher t)
14465 (let ((orlist nil))
14466 (dolist (term (org-split-string todomatch "|"))
14467 (while (string-match re term)
14468 (let* ((minus (and (match-end 1)
14469 (equal (match-string 1 term) "-")))
14470 (kwd (match-string 2 term))
14471 (regexp (eq (string-to-char kwd) ?{))
14472 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14473 `(equal todo ,kwd))))
14474 (push (if minus `(not ,mm) mm) todomatcher))
14475 (setq term (substring term (match-end 0))))
14476 (push (if (> (length todomatcher) 1)
14477 (cons 'and todomatcher)
14478 (car todomatcher))
14479 orlist)
14480 (setq todomatcher nil))
14481 (setq todomatcher (cons 'or orlist))))
14483 ;; Return the string and function of the matcher.
14484 (let ((matcher (if todomatcher `(and ,tagsmatcher ,todomatcher)
14485 tagsmatcher)))
14486 (when org--matcher-tags-todo-only
14487 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14488 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14490 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14491 "Expand group tags in MATCH.
14493 This replaces every group tag in MATCH with a regexp tag search.
14494 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14495 will be replaced like this:
14497 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14498 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14499 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14501 Replacing by a regexp preserves the structure of the match.
14502 E.g., this expansion
14504 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14506 will match anything tagged with \"Lab\" and \"Home\", or tagged
14507 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14509 A group tag in MATCH can contain regular expressions of its own.
14510 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14511 will be replaced like this:
14513 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14515 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14516 assumed to be a single group tag, and the function will return
14517 the list of tags in this group.
14519 When DOWNCASE is non-nil, expand downcased TAGS."
14520 (if org-group-tags
14521 (let* ((case-fold-search t)
14522 (stable org-mode-syntax-table)
14523 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14524 (taggroups (if downcased
14525 (mapcar (lambda (tg) (mapcar #'downcase tg))
14526 taggroups)
14527 taggroups))
14528 (taggroups-keys (mapcar #'car taggroups))
14529 (return-match (if downcased (downcase match) match))
14530 (count 0)
14531 (work-already-expanded tags-already-expanded)
14532 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14533 ;; @ and _ are allowed as word-components in tags.
14534 (modify-syntax-entry ?@ "w" stable)
14535 (modify-syntax-entry ?_ "w" stable)
14536 ;; Temporarily replace regexp-expressions in the match-expression.
14537 (while (string-match "{.+?}" return-match)
14538 (incf count)
14539 (push (match-string 0 return-match) regexps-in-match)
14540 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14541 (while (and taggroups-keys
14542 (with-syntax-table stable
14543 (string-match
14544 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14545 (regexp-opt taggroups-keys) "\\>\\)")
14546 return-match)))
14547 (let* ((dir (match-string 1 return-match))
14548 (tag (match-string 2 return-match))
14549 (tag (if downcased (downcase tag) tag)))
14550 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14551 (member tag work-already-expanded))
14552 (setq tags-in-group (assoc tag taggroups))
14553 (push tag work-already-expanded)
14554 ;; Recursively expand each tag in the group, if the tag hasn't
14555 ;; already been expanded. Restore the match-data after all recursive calls.
14556 (save-match-data
14557 (let (tags-expanded)
14558 (dolist (x (cdr tags-in-group))
14559 (if (and (member x taggroups-keys)
14560 (not (member x work-already-expanded)))
14561 (setq tags-expanded
14562 (delete-dups
14563 (append
14564 (org-tags-expand x t downcased
14565 work-already-expanded)
14566 tags-expanded)))
14567 (setq tags-expanded
14568 (append (list x) tags-expanded)))
14569 (setq work-already-expanded
14570 (delete-dups
14571 (append tags-expanded
14572 work-already-expanded))))
14573 (setq tags-in-group
14574 (delete-dups (cons (car tags-in-group)
14575 tags-expanded)))))
14576 ;; Filter tag-regexps from tags.
14577 (setq regexp-in-group-escaped
14578 (delq nil (mapcar (lambda (x)
14579 (if (stringp x)
14580 (and (equal "{" (substring x 0 1))
14581 (equal "}" (substring x -1))
14584 tags-in-group))
14585 regexp-in-group
14586 (mapcar (lambda (x)
14587 (substring x 1 -1))
14588 regexp-in-group-escaped)
14589 tags-in-group
14590 (delq nil (mapcar (lambda (x)
14591 (if (stringp x)
14592 (and (not (equal "{" (substring x 0 1)))
14593 (not (equal "}" (substring x -1)))
14596 tags-in-group)))
14597 ;; If single-as-list, do no more in the while-loop.
14598 (if (not single-as-list)
14599 (progn
14600 (when regexp-in-group
14601 (setq regexp-in-group
14602 (concat "\\|"
14603 (mapconcat 'identity regexp-in-group
14604 "\\|"))))
14605 (setq tags-in-group
14606 (concat dir
14607 "{\\<"
14608 (regexp-opt tags-in-group)
14609 "\\>"
14610 regexp-in-group
14611 "}"))
14612 (when (stringp tags-in-group)
14613 (org-add-props tags-in-group '(grouptag t)))
14614 (setq return-match
14615 (replace-match tags-in-group t t return-match)))
14616 (setq tags-in-group
14617 (append regexp-in-group-escaped tags-in-group))))
14618 (setq taggroups-keys (delete tag taggroups-keys))))
14619 ;; Add the regular expressions back into the match-expression again.
14620 (while regexps-in-match
14621 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14622 (pop regexps-in-match)
14623 return-match t t))
14624 (decf count))
14625 (if single-as-list
14626 (if tags-in-group tags-in-group (list return-match))
14627 return-match))
14628 (if single-as-list
14629 (list (if downcased (downcase match) match))
14630 match)))
14632 (defun org-op-to-function (op &optional stringp)
14633 "Turn an operator into the appropriate function."
14634 (setq op
14635 (cond
14636 ((equal op "<" ) '(< string< org-time<))
14637 ((equal op ">" ) '(> org-string> org-time>))
14638 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14639 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14640 ((member op '("=" "==")) '(= string= org-time=))
14641 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14642 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14644 (defun org<> (a b) (not (= a b)))
14645 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14646 (defun org-string>= (a b) (not (string< a b)))
14647 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14648 (defun org-string<> (a b) (not (string= a b)))
14649 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14650 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14651 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14652 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14653 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14654 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14655 (defun org-2ft (s)
14656 "Convert S to a floating point time.
14657 If S is already a number, just return it. If it is a string, parse
14658 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14659 (cond
14660 ((numberp s) s)
14661 ((stringp s)
14662 (condition-case nil
14663 (float-time (apply 'encode-time (org-parse-time-string s)))
14664 (error 0.)))
14665 (t 0.)))
14667 (defun org-time-today ()
14668 "Time in seconds today at 0:00.
14669 Returns the float number of seconds since the beginning of the
14670 epoch to the beginning of today (00:00)."
14671 (float-time (apply 'encode-time
14672 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14674 (defun org-matcher-time (s)
14675 "Interpret a time comparison value."
14676 (save-match-data
14677 (cond
14678 ((string= s "<now>") (float-time))
14679 ((string= s "<today>") (org-time-today))
14680 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14681 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14682 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14683 (+ (org-time-today)
14684 (* (string-to-number (match-string 1 s))
14685 (cdr (assoc (match-string 2 s)
14686 '(("d" . 86400.0) ("w" . 604800.0)
14687 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14688 (t (org-2ft s)))))
14690 (defun org-match-any-p (re list)
14691 "Does re match any element of list?"
14692 (setq list (mapcar (lambda (x) (string-match re x)) list))
14693 (delq nil list))
14695 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14696 (defvar org-tags-overlay (make-overlay 1 1))
14697 (org-detach-overlay org-tags-overlay)
14699 (defun org-get-local-tags-at (&optional pos)
14700 "Get a list of tags defined in the current headline."
14701 (org-get-tags-at pos 'local))
14703 (defun org-get-local-tags ()
14704 "Get a list of tags defined in the current headline."
14705 (org-get-tags-at nil 'local))
14707 (defun org-get-tags-at (&optional pos local)
14708 "Get a list of all headline tags applicable at POS.
14709 POS defaults to point. If tags are inherited, the list contains
14710 the targets in the same sequence as the headlines appear, i.e.
14711 the tags of the current headline come last.
14712 When LOCAL is non-nil, only return tags from the current headline,
14713 ignore inherited ones."
14714 (interactive)
14715 (if (and org-trust-scanner-tags
14716 (or (not pos) (equal pos (point)))
14717 (not local))
14718 org-scanner-tags
14719 (let (tags ltags lastpos parent)
14720 (save-excursion
14721 (save-restriction
14722 (widen)
14723 (goto-char (or pos (point)))
14724 (save-match-data
14725 (catch 'done
14726 (condition-case nil
14727 (progn
14728 (org-back-to-heading t)
14729 (while (not (equal lastpos (point)))
14730 (setq lastpos (point))
14731 (when (looking-at
14732 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14733 (setq ltags (org-split-string
14734 (org-match-string-no-properties 1) ":"))
14735 (when parent
14736 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14737 (setq tags (append
14738 (if parent
14739 (org-remove-uninherited-tags ltags)
14740 ltags)
14741 tags)))
14742 (or org-use-tag-inheritance (throw 'done t))
14743 (when local (throw 'done t))
14744 (or (org-up-heading-safe) (error nil))
14745 (setq parent t)))
14746 (error nil)))))
14747 (if local
14748 tags
14749 (reverse (delete-dups
14750 (reverse (append
14751 (org-remove-uninherited-tags
14752 org-file-tags)
14753 tags)))))))))
14755 (defun org-add-prop-inherited (s)
14756 (add-text-properties 0 (length s) '(inherited t) s)
14759 (defun org-toggle-tag (tag &optional onoff)
14760 "Toggle the tag TAG for the current line.
14761 If ONOFF is `on' or `off', don't toggle but set to this state."
14762 (let (res current)
14763 (save-excursion
14764 (org-back-to-heading t)
14765 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14766 (point-at-eol) t)
14767 (progn
14768 (setq current (match-string 1))
14769 (replace-match ""))
14770 (setq current ""))
14771 (setq current (nreverse (org-split-string current ":")))
14772 (cond
14773 ((eq onoff 'on)
14774 (setq res t)
14775 (or (member tag current) (push tag current)))
14776 ((eq onoff 'off)
14777 (or (not (member tag current)) (setq current (delete tag current))))
14778 (t (if (member tag current)
14779 (setq current (delete tag current))
14780 (setq res t)
14781 (push tag current))))
14782 (end-of-line 1)
14783 (if current
14784 (progn
14785 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14786 (org-set-tags nil t))
14787 (delete-horizontal-space))
14788 (run-hooks 'org-after-tags-change-hook))
14789 res))
14791 (defun org-align-tags-here (to-col)
14792 ;; Assumes that this is a headline
14793 "Align tags on the current headline to TO-COL."
14794 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14795 (beginning-of-line 1)
14796 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14797 (< pos (match-beginning 2)))
14798 (progn
14799 (setq tags-l (- (match-end 2) (match-beginning 2)))
14800 (goto-char (match-beginning 1))
14801 (insert " ")
14802 (delete-region (point) (1+ (match-beginning 2)))
14803 (setq ncol (max (current-column)
14804 (1+ col)
14805 (if (> to-col 0)
14806 to-col
14807 (- (abs to-col) tags-l))))
14808 (setq p (point))
14809 (insert (make-string (- ncol (current-column)) ?\ ))
14810 (setq ncol (current-column))
14811 (when indent-tabs-mode (tabify p (point-at-eol)))
14812 (org-move-to-column (min ncol col)))
14813 (goto-char pos))))
14815 (defun org-set-tags-command (&optional arg just-align)
14816 "Call the set-tags command for the current entry."
14817 (interactive "P")
14818 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14819 (org-set-tags arg just-align)
14820 (save-excursion
14821 (unless (and (org-region-active-p)
14822 org-loop-over-headlines-in-active-region)
14823 (org-back-to-heading t))
14824 (org-set-tags arg just-align))))
14826 (defun org-set-tags-to (data)
14827 "Set the tags of the current entry to DATA, replacing the current tags.
14828 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14829 If DATA is nil or the empty string, any tags will be removed."
14830 (interactive "sTags: ")
14831 (setq data
14832 (cond
14833 ((eq data nil) "")
14834 ((equal data "") "")
14835 ((stringp data)
14836 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14837 ":"))
14838 ((listp data)
14839 (concat ":" (mapconcat 'identity data ":") ":"))))
14840 (when data
14841 (save-excursion
14842 (org-back-to-heading t)
14843 (when (looking-at org-complex-heading-regexp)
14844 (if (match-end 5)
14845 (progn
14846 (goto-char (match-beginning 5))
14847 (insert data)
14848 (delete-region (point) (point-at-eol))
14849 (org-set-tags nil 'align))
14850 (goto-char (point-at-eol))
14851 (insert " " data)
14852 (org-set-tags nil 'align)))
14853 (beginning-of-line 1)
14854 (when (looking-at ".*?\\([ \t]+\\)$")
14855 (delete-region (match-beginning 1) (match-end 1))))))
14857 (defun org-align-all-tags ()
14858 "Align the tags i all headings."
14859 (interactive)
14860 (save-excursion
14861 (or (ignore-errors (org-back-to-heading t))
14862 (outline-next-heading))
14863 (if (org-at-heading-p)
14864 (org-set-tags t)
14865 (message "No headings"))))
14867 (defvar org-indent-indentation-per-level)
14868 (defun org-set-tags (&optional arg just-align)
14869 "Set the tags for the current headline.
14870 With prefix ARG, realign all tags in headings in the current buffer.
14871 When JUST-ALIGN is non-nil, only align tags."
14872 (interactive "P")
14873 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14874 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14875 'region-start-level
14876 'region))
14877 org-loop-over-headlines-in-active-region)
14878 (org-map-entries
14879 ;; We don't use ARG and JUST-ALIGN here because these args
14880 ;; are not useful when looping over headlines.
14881 #'org-set-tags
14882 org-loop-over-headlines-in-active-region
14884 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14885 (let ((org-setting-tags t))
14886 (if arg
14887 (save-excursion
14888 (goto-char (point-min))
14889 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14890 (while (re-search-forward org-outline-regexp-bol nil t)
14891 (org-set-tags nil t)
14892 (end-of-line)))
14893 (message "All tags realigned to column %d" org-tags-column))
14894 (let* ((current (org-get-tags-string))
14895 (col (current-column))
14896 (tags
14897 (if just-align current
14898 ;; Get a new set of tags from the user.
14899 (save-excursion
14900 (let* ((table
14901 (setq
14902 org-last-tags-completion-table
14903 (append
14904 org-tag-persistent-alist
14905 (or org-tag-alist (org-get-buffer-tags))
14906 (and
14907 org-complete-tags-always-offer-all-agenda-tags
14908 (org-global-tags-completion-table
14909 (org-agenda-files))))))
14910 (current-tags (org-split-string current ":"))
14911 (inherited-tags
14912 (nreverse (nthcdr (length current-tags)
14913 (nreverse (org-get-tags-at))))))
14914 (replace-regexp-in-string
14915 "\\([-+&]+\\|,\\)"
14917 (if (or (eq t org-use-fast-tag-selection)
14918 (and org-use-fast-tag-selection
14919 (delq nil (mapcar #'cdr table))))
14920 (org-fast-tag-selection
14921 current-tags inherited-tags table
14922 (and org-fast-tag-selection-include-todo
14923 org-todo-key-alist))
14924 (let ((org-add-colon-after-tag-completion
14925 (< 1 (length table))))
14926 (org-trim
14927 (completing-read
14928 "Tags: "
14929 #'org-tags-completion-function
14930 nil nil current 'org-tags-history))))))))))
14932 (when org-tags-sort-function
14933 (setq tags
14934 (mapconcat
14935 #'identity
14936 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14937 org-tags-sort-function)
14938 ":")))
14940 (if (not (org-string-nw-p tags)) (setq tags "")
14941 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14942 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14944 ;; Insert new tags at the correct column
14945 (beginning-of-line)
14946 (let ((level (if (looking-at org-outline-regexp)
14947 (- (match-end 0) (point) 1)
14948 1)))
14949 (cond
14950 ((and (equal current "") (equal tags "")))
14951 ((re-search-forward
14952 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14953 (line-end-position)
14955 (if (equal tags "") (replace-match "" t t)
14956 (goto-char (match-beginning 0))
14957 (let* ((c0 (current-column))
14958 ;; Compute offset for the case of org-indent-mode
14959 ;; active.
14960 (di (if (org-bound-and-true-p org-indent-mode)
14961 (* (1- org-indent-indentation-per-level)
14962 (1- level))
14964 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14965 (tc (+ org-tags-column
14966 (if (> org-tags-column 0) (- di) di)))
14967 (c1 (max (1+ c0)
14968 (if (> tc 0) tc
14969 (- (- tc) (string-width tags)))))
14970 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14971 (replace-match rpl t t)
14972 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14973 (tabify p0 (point))))))
14974 (t (error "Tags alignment failed"))))
14975 (org-move-to-column col))
14976 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14978 (defun org-change-tag-in-region (beg end tag off)
14979 "Add or remove TAG for each entry in the region.
14980 This works in the agenda, and also in an org-mode buffer."
14981 (interactive
14982 (list (region-beginning) (region-end)
14983 (let ((org-last-tags-completion-table
14984 (if (derived-mode-p 'org-mode)
14985 (org-uniquify
14986 (delq nil (append (org-get-buffer-tags)
14987 (org-global-tags-completion-table))))
14988 (org-global-tags-completion-table))))
14989 (completing-read
14990 "Tag: " 'org-tags-completion-function nil nil nil
14991 'org-tags-history))
14992 (progn
14993 (message "[s]et or [r]emove? ")
14994 (equal (read-char-exclusive) ?r))))
14995 (when (fboundp 'deactivate-mark) (deactivate-mark))
14996 (let ((agendap (equal major-mode 'org-agenda-mode))
14997 l1 l2 m buf pos newhead (cnt 0))
14998 (goto-char end)
14999 (setq l2 (1- (org-current-line)))
15000 (goto-char beg)
15001 (setq l1 (org-current-line))
15002 (loop for l from l1 to l2 do
15003 (org-goto-line l)
15004 (setq m (get-text-property (point) 'org-hd-marker))
15005 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15006 (and agendap m))
15007 (setq buf (if agendap (marker-buffer m) (current-buffer))
15008 pos (if agendap m (point)))
15009 (with-current-buffer buf
15010 (save-excursion
15011 (save-restriction
15012 (goto-char pos)
15013 (setq cnt (1+ cnt))
15014 (org-toggle-tag tag (if off 'off 'on))
15015 (setq newhead (org-get-heading)))))
15016 (and agendap (org-agenda-change-all-lines newhead m))))
15017 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15019 (defun org-tags-completion-function (string _predicate &optional flag)
15020 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15021 (confirm (lambda (x) (stringp (car x)))))
15022 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15023 (setq s1 (match-string 1 string)
15024 s2 (match-string 2 string))
15025 (setq s1 "" s2 string))
15026 (cond
15027 ((eq flag nil)
15028 ;; try completion
15029 (setq rtn (try-completion s2 ctable confirm))
15030 (when (stringp rtn)
15031 (setq rtn
15032 (concat s1 s2 (substring rtn (length s2))
15033 (if (and org-add-colon-after-tag-completion
15034 (assoc rtn ctable))
15035 ":" ""))))
15036 rtn)
15037 ((eq flag t)
15038 ;; all-completions
15039 (all-completions s2 ctable confirm))
15040 ((eq flag 'lambda)
15041 ;; exact match?
15042 (assoc s2 ctable)))))
15044 (defun org-fast-tag-insert (kwd tags face &optional end)
15045 "Insert KDW, and the TAGS, the latter with face FACE.
15046 Also insert END."
15047 (insert (format "%-12s" (concat kwd ":"))
15048 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15049 (or end "")))
15051 (defun org-fast-tag-show-exit (flag)
15052 (save-excursion
15053 (org-goto-line 3)
15054 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15055 (replace-match ""))
15056 (when flag
15057 (end-of-line 1)
15058 (org-move-to-column (- (window-width) 19) t)
15059 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15061 (defun org-set-current-tags-overlay (current prefix)
15062 "Add an overlay to CURRENT tag with PREFIX."
15063 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15064 (if (featurep 'xemacs)
15065 (org-overlay-display org-tags-overlay (concat prefix s)
15066 'secondary-selection)
15067 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15068 (org-overlay-display org-tags-overlay (concat prefix s)))))
15070 (defvar org-last-tag-selection-key nil)
15071 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15072 "Fast tag selection with single keys.
15073 CURRENT is the current list of tags in the headline, INHERITED is the
15074 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15075 possibly with grouping information. TODO-TABLE is a similar table with
15076 TODO keywords, should these have keys assigned to them.
15077 If the keys are nil, a-z are automatically assigned.
15078 Returns the new tags string, or nil to not change the current settings."
15079 (let* ((fulltable (append table todo-table))
15080 (maxlen (apply 'max (mapcar
15081 (lambda (x)
15082 (if (stringp (car x)) (string-width (car x)) 0))
15083 fulltable)))
15084 (buf (current-buffer))
15085 (expert (eq org-fast-tag-selection-single-key 'expert))
15086 (buffer-tags nil)
15087 (fwidth (+ maxlen 3 1 3))
15088 (ncol (/ (- (window-width) 4) fwidth))
15089 (i-face 'org-done)
15090 (c-face 'org-todo)
15091 tg cnt e c char c1 c2 ntable tbl rtn
15092 ov-start ov-end ov-prefix
15093 (exit-after-next org-fast-tag-selection-single-key)
15094 (done-keywords org-done-keywords)
15095 groups ingroup intaggroup)
15096 (save-excursion
15097 (beginning-of-line 1)
15098 (if (looking-at
15099 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15100 (setq ov-start (match-beginning 1)
15101 ov-end (match-end 1)
15102 ov-prefix "")
15103 (setq ov-start (1- (point-at-eol))
15104 ov-end (1+ ov-start))
15105 (skip-chars-forward "^\n\r")
15106 (setq ov-prefix
15107 (concat
15108 (buffer-substring (1- (point)) (point))
15109 (if (> (current-column) org-tags-column)
15111 (make-string (- org-tags-column (current-column)) ?\ ))))))
15112 (move-overlay org-tags-overlay ov-start ov-end)
15113 (save-window-excursion
15114 (if expert
15115 (set-buffer (get-buffer-create " *Org tags*"))
15116 (delete-other-windows)
15117 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15118 (org-switch-to-buffer-other-window " *Org tags*"))
15119 (erase-buffer)
15120 (setq-local org-done-keywords done-keywords)
15121 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15122 (org-fast-tag-insert "Current" current c-face "\n\n")
15123 (org-fast-tag-show-exit exit-after-next)
15124 (org-set-current-tags-overlay current ov-prefix)
15125 (setq tbl fulltable char ?a cnt 0)
15126 (while (setq e (pop tbl))
15127 (cond
15128 ((eq (car e) :startgroup)
15129 (push '() groups) (setq ingroup t)
15130 (unless (zerop cnt)
15131 (setq cnt 0)
15132 (insert "\n"))
15133 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15134 ((eq (car e) :endgroup)
15135 (setq ingroup nil cnt 0)
15136 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15137 ((eq (car e) :startgrouptag)
15138 (setq intaggroup t)
15139 (unless (zerop cnt)
15140 (setq cnt 0)
15141 (insert "\n"))
15142 (insert "[ "))
15143 ((eq (car e) :endgrouptag)
15144 (setq intaggroup nil cnt 0)
15145 (insert "]\n"))
15146 ((equal e '(:newline))
15147 (unless (zerop cnt)
15148 (setq cnt 0)
15149 (insert "\n")
15150 (setq e (car tbl))
15151 (while (equal (car tbl) '(:newline))
15152 (insert "\n")
15153 (setq tbl (cdr tbl)))))
15154 ((equal e '(:grouptags)) (insert " : "))
15156 (setq tg (copy-sequence (car e)) c2 nil)
15157 (if (cdr e)
15158 (setq c (cdr e))
15159 ;; automatically assign a character.
15160 (setq c1 (string-to-char
15161 (downcase (substring
15162 tg (if (= (string-to-char tg) ?@) 1 0)))))
15163 (if (or (rassoc c1 ntable) (rassoc c1 table))
15164 (while (or (rassoc char ntable) (rassoc char table))
15165 (setq char (1+ char)))
15166 (setq c2 c1))
15167 (setq c (or c2 char)))
15168 (when ingroup (push tg (car groups)))
15169 (setq tg (org-add-props tg nil 'face
15170 (cond
15171 ((not (assoc tg table))
15172 (org-get-todo-face tg))
15173 ((member tg current) c-face)
15174 ((member tg inherited) i-face))))
15175 (when (equal (caar tbl) :grouptags)
15176 (org-add-props tg nil 'face 'org-tag-group))
15177 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15178 (insert "[" c "] " tg (make-string
15179 (- fwidth 4 (length tg)) ?\ ))
15180 (push (cons tg c) ntable)
15181 (when (= (incf cnt) ncol)
15182 (insert "\n")
15183 (when (or ingroup intaggroup) (insert " "))
15184 (setq cnt 0)))))
15185 (setq ntable (nreverse ntable))
15186 (insert "\n")
15187 (goto-char (point-min))
15188 (unless expert (org-fit-window-to-buffer))
15189 (setq rtn
15190 (catch 'exit
15191 (while t
15192 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15193 (if (not groups) "no " "")
15194 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15195 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15196 (setq org-last-tag-selection-key c)
15197 (cond
15198 ((= c ?\r) (throw 'exit t))
15199 ((= c ?!)
15200 (setq groups (not groups))
15201 (goto-char (point-min))
15202 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15203 ((= c ?\C-c)
15204 (if (not expert)
15205 (org-fast-tag-show-exit
15206 (setq exit-after-next (not exit-after-next)))
15207 (setq expert nil)
15208 (delete-other-windows)
15209 (set-window-buffer (split-window-vertically) " *Org tags*")
15210 (org-switch-to-buffer-other-window " *Org tags*")
15211 (org-fit-window-to-buffer)))
15212 ((or (= c ?\C-g)
15213 (and (= c ?q) (not (rassoc c ntable))))
15214 (org-detach-overlay org-tags-overlay)
15215 (setq quit-flag t))
15216 ((= c ?\ )
15217 (setq current nil)
15218 (when exit-after-next (setq exit-after-next 'now)))
15219 ((= c ?\t)
15220 (condition-case nil
15221 (setq tg (completing-read
15222 "Tag: "
15223 (or buffer-tags
15224 (with-current-buffer buf
15225 (setq buffer-tags
15226 (org-get-buffer-tags))))))
15227 (quit (setq tg "")))
15228 (when (string-match "\\S-" tg)
15229 (add-to-list 'buffer-tags (list tg))
15230 (if (member tg current)
15231 (setq current (delete tg current))
15232 (push tg current)))
15233 (when exit-after-next (setq exit-after-next 'now)))
15234 ((setq e (rassoc c todo-table) tg (car e))
15235 (with-current-buffer buf
15236 (save-excursion (org-todo tg)))
15237 (when exit-after-next (setq exit-after-next 'now)))
15238 ((setq e (rassoc c ntable) tg (car e))
15239 (if (member tg current)
15240 (setq current (delete tg current))
15241 (loop for g in groups do
15242 (when (member tg g)
15243 (dolist (x g) (setq current (delete x current)))))
15244 (push tg current))
15245 (when exit-after-next (setq exit-after-next 'now))))
15247 ;; Create a sorted list
15248 (setq current
15249 (sort current
15250 (lambda (a b)
15251 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15252 (when (eq exit-after-next 'now) (throw 'exit t))
15253 (goto-char (point-min))
15254 (beginning-of-line 2)
15255 (delete-region (point) (point-at-eol))
15256 (org-fast-tag-insert "Current" current c-face)
15257 (org-set-current-tags-overlay current ov-prefix)
15258 (while (re-search-forward
15259 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15260 (setq tg (match-string 1))
15261 (add-text-properties
15262 (match-beginning 1) (match-end 1)
15263 (list 'face
15264 (cond
15265 ((member tg current) c-face)
15266 ((member tg inherited) i-face)
15267 (t (get-text-property (match-beginning 1) 'face))))))
15268 (goto-char (point-min)))))
15269 (org-detach-overlay org-tags-overlay)
15270 (if rtn
15271 (mapconcat 'identity current ":")
15272 nil))))
15274 (defun org-get-tags-string ()
15275 "Get the TAGS string in the current headline."
15276 (unless (org-at-heading-p t)
15277 (user-error "Not on a heading"))
15278 (save-excursion
15279 (beginning-of-line 1)
15280 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15281 (org-match-string-no-properties 1)
15282 "")))
15284 (defun org-get-tags ()
15285 "Get the list of tags specified in the current headline."
15286 (org-split-string (org-get-tags-string) ":"))
15288 (defun org-get-buffer-tags ()
15289 "Get a table of all tags used in the buffer, for completion."
15290 (org-with-wide-buffer
15291 (goto-char (point-min))
15292 (let ((tag-re (concat org-outline-regexp-bol
15293 "\\(?:.*?[ \t]\\)?"
15294 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15295 tags)
15296 (while (re-search-forward tag-re nil t)
15297 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15298 (push tag tags)))
15299 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15301 ;;;; The mapping API
15303 (defun org-map-entries (func &optional match scope &rest skip)
15304 "Call FUNC at each headline selected by MATCH in SCOPE.
15306 FUNC is a function or a lisp form. The function will be called without
15307 arguments, with the cursor positioned at the beginning of the headline.
15308 The return values of all calls to the function will be collected and
15309 returned as a list.
15311 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15312 does not need to preserve point. After evaluation, the cursor will be
15313 moved to the end of the line (presumably of the headline of the
15314 processed entry) and search continues from there. Under some
15315 circumstances, this may not produce the wanted results. For example,
15316 if you have removed (e.g. archived) the current (sub)tree it could
15317 mean that the next entry will be skipped entirely. In such cases, you
15318 can specify the position from where search should continue by making
15319 FUNC set the variable `org-map-continue-from' to the desired buffer
15320 position.
15322 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15323 Only headlines that are matched by this query will be considered during
15324 the iteration. When MATCH is nil or t, all headlines will be
15325 visited by the iteration.
15327 SCOPE determines the scope of this command. It can be any of:
15329 nil The current buffer, respecting the restriction if any
15330 tree The subtree started with the entry at point
15331 region The entries within the active region, if any
15332 region-start-level
15333 The entries within the active region, but only those at
15334 the same level than the first one.
15335 file The current buffer, without restriction
15336 file-with-archives
15337 The current buffer, and any archives associated with it
15338 agenda All agenda files
15339 agenda-with-archives
15340 All agenda files with any archive files associated with them
15341 \(file1 file2 ...)
15342 If this is a list, all files in the list will be scanned
15344 The remaining args are treated as settings for the skipping facilities of
15345 the scanner. The following items can be given here:
15347 archive skip trees with the archive tag
15348 comment skip trees with the COMMENT keyword
15349 function or Emacs Lisp form:
15350 will be used as value for `org-agenda-skip-function', so
15351 whenever the function returns a position, FUNC will not be
15352 called for that entry and search will continue from the
15353 position returned
15355 If your function needs to retrieve the tags including inherited tags
15356 at the *current* entry, you can use the value of the variable
15357 `org-scanner-tags' which will be much faster than getting the value
15358 with `org-get-tags-at'. If your function gets properties with
15359 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15360 to t around the call to `org-entry-properties' to get the same speedup.
15361 Note that if your function moves around to retrieve tags and properties at
15362 a *different* entry, you cannot use these techniques."
15363 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15364 (not (org-region-active-p)))
15365 (let* ((org-agenda-archives-mode nil) ; just to make sure
15366 (org-agenda-skip-archived-trees (memq 'archive skip))
15367 (org-agenda-skip-comment-trees (memq 'comment skip))
15368 (org-agenda-skip-function
15369 (car (org-delete-all '(comment archive) skip)))
15370 (org-tags-match-list-sublevels t)
15371 (start-level (eq scope 'region-start-level))
15372 matcher res
15373 org-todo-keywords-for-agenda
15374 org-done-keywords-for-agenda
15375 org-todo-keyword-alist-for-agenda
15376 org-tag-alist-for-agenda
15377 org--matcher-tags-todo-only)
15379 (cond
15380 ((eq match t) (setq matcher t))
15381 ((eq match nil) (setq matcher t))
15382 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15384 (save-excursion
15385 (save-restriction
15386 (cond ((eq scope 'tree)
15387 (org-back-to-heading t)
15388 (org-narrow-to-subtree)
15389 (setq scope nil))
15390 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15391 (org-region-active-p))
15392 ;; If needed, set start-level to a string like "2"
15393 (when start-level
15394 (save-excursion
15395 (goto-char (region-beginning))
15396 (unless (org-at-heading-p) (outline-next-heading))
15397 (setq start-level (org-current-level))))
15398 (narrow-to-region (region-beginning)
15399 (save-excursion
15400 (goto-char (region-end))
15401 (unless (and (bolp) (org-at-heading-p))
15402 (outline-next-heading))
15403 (point)))
15404 (setq scope nil)))
15406 (if (not scope)
15407 (progn
15408 (org-agenda-prepare-buffers
15409 (and buffer-file-name (list buffer-file-name)))
15410 (setq res
15411 (org-scan-tags
15412 func matcher org--matcher-tags-todo-only start-level)))
15413 ;; Get the right scope
15414 (cond
15415 ((and scope (listp scope) (symbolp (car scope)))
15416 (setq scope (eval scope)))
15417 ((eq scope 'agenda)
15418 (setq scope (org-agenda-files t)))
15419 ((eq scope 'agenda-with-archives)
15420 (setq scope (org-agenda-files t))
15421 (setq scope (org-add-archive-files scope)))
15422 ((eq scope 'file)
15423 (setq scope (and buffer-file-name (list buffer-file-name))))
15424 ((eq scope 'file-with-archives)
15425 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15426 (org-agenda-prepare-buffers scope)
15427 (dolist (file scope)
15428 (with-current-buffer (org-find-base-buffer-visiting file)
15429 (save-excursion
15430 (save-restriction
15431 (widen)
15432 (goto-char (point-min))
15433 (setq res
15434 (append
15436 (org-scan-tags
15437 func matcher org--matcher-tags-todo-only))))))))))
15438 res)))
15440 ;;; Properties API
15442 (defconst org-special-properties
15443 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15444 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15445 "The special properties valid in Org mode.
15446 These are properties that are not defined in the property drawer,
15447 but in some other way.")
15449 (defconst org-default-properties
15450 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15451 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15452 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15453 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15454 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15455 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15456 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15457 "Some properties that are used by Org mode for various purposes.
15458 Being in this list makes sure that they are offered for completion.")
15460 (defun org--valid-property-p (property)
15461 "Non nil when string PROPERTY is a valid property name."
15462 (not
15463 (or (equal property "")
15464 (org-string-match-p "\\s-" property))))
15466 (defun org--update-property-plist (key val props)
15467 "Associate KEY to VAL in alist PROPS.
15468 Modifications are made by side-effect. Return new alist."
15469 (let* ((appending (string= (substring key -1) "+"))
15470 (key (if appending (substring key 0 -1) key))
15471 (old (assoc-string key props t)))
15472 (if (not old) (cons (cons key val) props)
15473 (setcdr old (if appending (concat (cdr old) " " val) val))
15474 props)))
15476 (defun org-get-property-block (&optional beg force)
15477 "Return the (beg . end) range of the body of the property drawer.
15478 BEG is the beginning of the current subtree, or of the part
15479 before the first headline. If it is not given, it will be found.
15480 If the drawer does not exist, create it if FORCE is non-nil, or
15481 return nil."
15482 (org-with-wide-buffer
15483 (when beg (goto-char beg))
15484 (unless (org-before-first-heading-p)
15485 (let ((beg (cond (beg)
15486 ((or (not (featurep 'org-inlinetask))
15487 (org-inlinetask-in-task-p))
15488 (org-back-to-heading t))
15489 (t (org-with-limited-levels (org-back-to-heading t))))))
15490 (forward-line)
15491 (when (org-looking-at-p org-planning-line-re) (forward-line))
15492 (cond ((looking-at org-property-drawer-re)
15493 (forward-line)
15494 (cons (point) (progn (goto-char (match-end 0))
15495 (line-beginning-position))))
15496 (force
15497 (goto-char beg)
15498 (org-insert-property-drawer)
15499 (let ((pos (save-excursion (search-forward ":END:")
15500 (line-beginning-position))))
15501 (cons pos pos))))))))
15503 (defun org-at-property-p ()
15504 "Non-nil when point is inside a property drawer.
15505 See `org-property-re' for match data, if applicable."
15506 (save-excursion
15507 (beginning-of-line)
15508 (and (looking-at org-property-re)
15509 (let ((property-drawer (save-match-data (org-get-property-block))))
15510 (and property-drawer
15511 (>= (point) (car property-drawer))
15512 (< (point) (cdr property-drawer)))))))
15514 (defun org-property-action ()
15515 "Do an action on properties."
15516 (interactive)
15517 (unless (org-at-property-p) (user-error "Not at a property"))
15518 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15519 (let ((c (read-char-exclusive)))
15520 (case c
15521 (?s (call-interactively #'org-set-property))
15522 (?d (call-interactively #'org-delete-property))
15523 (?D (call-interactively #'org-delete-property-globally))
15524 (?c (call-interactively #'org-compute-property-at-point))
15525 (otherwise (user-error "No such property action %c" c)))))
15527 (defun org-inc-effort ()
15528 "Increment the value of the effort property in the current entry."
15529 (interactive)
15530 (org-set-effort nil t))
15532 (defvar org-clock-effort) ; Defined in org-clock.el.
15533 (defvar org-clock-current-task) ; Defined in org-clock.el.
15534 (defun org-set-effort (&optional value increment)
15535 "Set the effort property of the current entry.
15536 With numerical prefix arg, use the nth allowed value, 0 stands for the
15537 10th allowed value.
15539 When INCREMENT is non-nil, set the property to the next allowed value."
15540 (interactive "P")
15541 (when (equal value 0) (setq value 10))
15542 (let* ((completion-ignore-case t)
15543 (prop org-effort-property)
15544 (cur (org-entry-get nil prop))
15545 (allowed (org-property-get-allowed-values nil prop 'table))
15546 (existing (mapcar 'list (org-property-values prop)))
15547 (heading (nth 4 (org-heading-components)))
15549 (val (cond
15550 ((stringp value) value)
15551 ((and allowed (integerp value))
15552 (or (car (nth (1- value) allowed))
15553 (car (org-last allowed))))
15554 ((and allowed increment)
15555 (or (caadr (member (list cur) allowed))
15556 (user-error "Allowed effort values are not set")))
15557 (allowed
15558 (message "Select 1-9,0, [RET%s]: %s"
15559 (if cur (concat "=" cur) "")
15560 (mapconcat 'car allowed " "))
15561 (setq rpl (read-char-exclusive))
15562 (if (equal rpl ?\r)
15564 (setq rpl (- rpl ?0))
15565 (when (equal rpl 0) (setq rpl 10))
15566 (if (and (> rpl 0) (<= rpl (length allowed)))
15567 (car (nth (1- rpl) allowed))
15568 (org-completing-read "Effort: " allowed nil))))
15570 (let (org-completion-use-ido org-completion-use-iswitchb)
15571 (org-completing-read
15572 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15573 (concat "[" cur "]") "")
15574 ": ")
15575 existing nil nil "" nil cur))))))
15576 (unless (equal (org-entry-get nil prop) val)
15577 (org-entry-put nil prop val))
15578 (org-refresh-property
15579 '((effort . identity)
15580 (effort-minutes . org-duration-string-to-minutes))
15581 val)
15582 (when (string= heading org-clock-current-task)
15583 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15584 (org-clock-update-mode-line))
15585 (message "%s is now %s" prop val)))
15587 (defun org-entry-properties (&optional pom which)
15588 "Get all properties of the current entry.
15590 When POM is a buffer position, get all properties from the entry
15591 there instead.
15593 This includes the TODO keyword, the tags, time strings for
15594 deadline, scheduled, and clocking, and any additional properties
15595 defined in the entry.
15597 If WHICH is nil or `all', get all properties. If WHICH is
15598 `special' or `standard', only get that subclass. If WHICH is
15599 a string, only get that property.
15601 Return value is an alist. Keys are properties, as upcased
15602 strings."
15603 (org-with-point-at pom
15604 (when (and (derived-mode-p 'org-mode)
15605 (ignore-errors (org-back-to-heading t)))
15606 (catch 'exit
15607 (let* ((beg (point))
15608 (specific (and (stringp which) (upcase which)))
15609 (which (cond ((not specific) which)
15610 ((member specific org-special-properties) 'special)
15611 (t 'standard)))
15612 props)
15613 ;; Get the special properties, like TODO and TAGS.
15614 (when (memq which '(nil all special))
15615 (when (or (not specific) (string= specific "CLOCKSUM"))
15616 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15617 (when clocksum
15618 (push (cons "CLOCKSUM"
15619 (org-columns-number-to-string
15620 (/ (float clocksum) 60.) 'add_times))
15621 props)))
15622 (when specific (throw 'exit props)))
15623 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15624 (let ((clocksumt (get-text-property (point)
15625 :org-clock-minutes-today)))
15626 (when clocksumt
15627 (push (cons "CLOCKSUM_T"
15628 (org-columns-number-to-string
15629 (/ (float clocksumt) 60.) 'add_times))
15630 props)))
15631 (when specific (throw 'exit props)))
15632 (when (or (not specific) (string= specific "ITEM"))
15633 (when (looking-at org-complex-heading-regexp)
15634 (push (cons "ITEM"
15635 (concat
15636 (org-match-string-no-properties 1)
15637 (let ((title (org-match-string-no-properties 4)))
15638 (when (org-string-nw-p title)
15639 (concat " " (org-remove-tabs title))))))
15640 props))
15641 (when specific (throw 'exit props)))
15642 (when (or (not specific) (string= specific "TODO"))
15643 (let ((case-fold-search nil))
15644 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15645 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "PRIORITY"))
15648 (push (cons "PRIORITY"
15649 (if (looking-at org-priority-regexp)
15650 (org-match-string-no-properties 2)
15651 (char-to-string org-default-priority)))
15652 props)
15653 (when specific (throw 'exit props)))
15654 (when (or (not specific) (string= specific "FILE"))
15655 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15656 props)
15657 (when specific (throw 'exit props)))
15658 (when (or (not specific) (string= specific "TAGS"))
15659 (let ((value (org-string-nw-p (org-get-tags-string))))
15660 (when value (push (cons "TAGS" value) props)))
15661 (when specific (throw 'exit props)))
15662 (when (or (not specific) (string= specific "ALLTAGS"))
15663 (let ((value (org-get-tags-at)))
15664 (when value
15665 (push (cons "ALLTAGS"
15666 (format ":%s:" (mapconcat #'identity value ":")))
15667 props)))
15668 (when specific (throw 'exit props)))
15669 (when (or (not specific) (string= specific "BLOCKED"))
15670 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15671 (when specific (throw 'exit props)))
15672 (when (or (not specific)
15673 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15674 (forward-line)
15675 (when (org-looking-at-p org-planning-line-re)
15676 (end-of-line)
15677 (let ((bol (line-beginning-position))
15678 ;; Backward compatibility: time keywords used to
15679 ;; be configurable (before 8.3). Make sure we
15680 ;; get the correct keyword.
15681 (key-assoc `(("CLOSED" . ,org-closed-string)
15682 ("DEADLINE" . ,org-deadline-string)
15683 ("SCHEDULED" . ,org-scheduled-string))))
15684 (dolist (pair (if specific (list (assoc specific key-assoc))
15685 key-assoc))
15686 (save-excursion
15687 (when (search-backward (cdr pair) bol t)
15688 (goto-char (match-end 0))
15689 (skip-chars-forward " \t")
15690 (and (looking-at org-ts-regexp-both)
15691 (push (cons (car pair)
15692 (org-match-string-no-properties 0))
15693 props)))))))
15694 (when specific (throw 'exit props)))
15695 (when (or (not specific)
15696 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15697 (let ((find-ts
15698 (lambda (end ts)
15699 ;; Fix next time-stamp before END. TS is the
15700 ;; list of time-stamps found so far.
15701 (let ((ts ts)
15702 (regexp (cond
15703 ((string= specific "TIMESTAMP")
15704 org-ts-regexp)
15705 ((string= specific "TIMESTAMP_IA")
15706 org-ts-regexp-inactive)
15707 ((assoc "TIMESTAMP_IA" ts)
15708 org-ts-regexp)
15709 ((assoc "TIMESTAMP" ts)
15710 org-ts-regexp-inactive)
15711 (t org-ts-regexp-both))))
15712 (catch 'next
15713 (while (re-search-forward regexp end t)
15714 (backward-char)
15715 (let ((object (org-element-context)))
15716 ;; Accept to match timestamps in node
15717 ;; properties, too.
15718 (when (memq (org-element-type object)
15719 '(node-property timestamp))
15720 (let ((type
15721 (org-element-property :type object)))
15722 (cond
15723 ((and (memq type '(active active-range))
15724 (not (equal specific "TIMESTAMP_IA")))
15725 (unless (assoc "TIMESTAMP" ts)
15726 (push (cons "TIMESTAMP"
15727 (org-element-property
15728 :raw-value object))
15730 (when specific (throw 'exit ts))))
15731 ((and (memq type '(inactive inactive-range))
15732 (not (string= specific "TIMESTAMP")))
15733 (unless (assoc "TIMESTAMP_IA" ts)
15734 (push (cons "TIMESTAMP_IA"
15735 (org-element-property
15736 :raw-value object))
15738 (when specific (throw 'exit ts))))))
15739 ;; Both timestamp types are found,
15740 ;; move to next part.
15741 (when (= (length ts) 2) (throw 'next ts)))))
15742 ts)))))
15743 (goto-char beg)
15744 ;; First look for timestamps within headline.
15745 (let ((ts (funcall find-ts (line-end-position) nil)))
15746 (if (= (length ts) 2) (setq props (nconc ts props))
15747 (forward-line)
15748 ;; Then find timestamps in the section, skipping
15749 ;; planning line.
15750 (when (org-looking-at-p org-planning-line-re)
15751 (forward-line))
15752 (let ((end (save-excursion (outline-next-heading))))
15753 (setq props (nconc (funcall find-ts end ts) props))))))))
15754 ;; Get the standard properties, like :PROP:.
15755 (when (memq which '(nil all standard))
15756 ;; If we are looking after a specific property, delegate
15757 ;; to `org-entry-get', which is faster. However, make an
15758 ;; exception for "CATEGORY", since it can be also set
15759 ;; through keywords (i.e. #+CATEGORY).
15760 (if (and specific (not (equal specific "CATEGORY")))
15761 (let ((value (org-entry-get beg specific nil t)))
15762 (throw 'exit (and value (list (cons specific value)))))
15763 (let ((range (org-get-property-block beg)))
15764 (when range
15765 (let ((end (cdr range)) seen-base)
15766 (goto-char (car range))
15767 ;; Unlike to `org--update-property-plist', we
15768 ;; handle the case where base values is found
15769 ;; after its extension. We also forbid standard
15770 ;; properties to be named as special properties.
15771 (while (re-search-forward org-property-re end t)
15772 (let* ((key (upcase (org-match-string-no-properties 2)))
15773 (extendp (org-string-match-p "\\+\\'" key))
15774 (key-base (if extendp (substring key 0 -1) key))
15775 (value (org-match-string-no-properties 3)))
15776 (cond
15777 ((member-ignore-case key-base org-special-properties))
15778 (extendp
15779 (setq props
15780 (org--update-property-plist key value props)))
15781 ((member key seen-base))
15782 (t (push key seen-base)
15783 (let ((p (assoc-string key props t)))
15784 (if p (setcdr p (concat value " " (cdr p)))
15785 (push (cons key value) props))))))))))))
15786 (unless (assoc "CATEGORY" props)
15787 (push (cons "CATEGORY" (org-get-category beg)) props)
15788 (when (string= specific "CATEGORY") (throw 'exit props)))
15789 ;; Return value.
15790 props)))))
15792 (defun org-property--local-values (property literal-nil)
15793 "Return value for PROPERTY in current entry.
15794 Value is a list whose care is the base value for PROPERTY and cdr
15795 a list of accumulated values. Return nil if neither is found in
15796 the entry. Also return nil when PROPERTY is set to \"nil\",
15797 unless LITERAL-NIL is non-nil."
15798 (let ((range (org-get-property-block)))
15799 (when range
15800 (goto-char (car range))
15801 (let* ((case-fold-search t)
15802 (end (cdr range))
15803 (value
15804 ;; Base value.
15805 (save-excursion
15806 (let ((v (and (re-search-forward
15807 (org-re-property property nil t) end t)
15808 (org-match-string-no-properties 3))))
15809 (list (if literal-nil v (org-not-nil v)))))))
15810 ;; Find additional values.
15811 (let* ((property+ (org-re-property (concat property "+") nil t)))
15812 (while (re-search-forward property+ end t)
15813 (push (org-match-string-no-properties 3) value)))
15814 ;; Return final values.
15815 (and (not (equal value '(nil))) (nreverse value))))))
15817 (defun org-entry-get (pom property &optional inherit literal-nil)
15818 "Get value of PROPERTY for entry or content at point-or-marker POM.
15820 If INHERIT is non-nil and the entry does not have the property,
15821 then also check higher levels of the hierarchy. If INHERIT is
15822 the symbol `selective', use inheritance only if the setting in
15823 `org-use-property-inheritance' selects PROPERTY for inheritance.
15825 If the property is present but empty, the return value is the
15826 empty string. If the property is not present at all, nil is
15827 returned. In any other case, return the value as a string.
15828 Search is case-insensitive.
15830 If LITERAL-NIL is set, return the string value \"nil\" as
15831 a string, do not interpret it as the list atom nil. This is used
15832 for inheritance when a \"nil\" value can supersede a non-nil
15833 value higher up the hierarchy."
15834 (org-with-point-at pom
15835 (cond
15836 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15837 ;; We need a special property. Use `org-entry-properties' to
15838 ;; retrieve it, but specify the wanted property.
15839 (cdr (assoc-string property (org-entry-properties nil property))))
15840 ((and inherit
15841 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15842 (org-entry-get-with-inheritance property literal-nil))
15844 (let* ((local (org-property--local-values property literal-nil))
15845 (value (and local (mapconcat #'identity (delq nil local) " "))))
15846 (if literal-nil value (org-not-nil value)))))))
15848 (defun org-property-or-variable-value (var &optional inherit)
15849 "Check if there is a property fixing the value of VAR.
15850 If yes, return this value. If not, return the current value of the variable."
15851 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15852 (if (and prop (stringp prop) (string-match "\\S-" prop))
15853 (read prop)
15854 (symbol-value var))))
15856 (defun org-entry-delete (pom property)
15857 "Delete PROPERTY from entry at point-or-marker POM.
15858 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15859 non-nil when a property was removed."
15860 (unless (member property org-special-properties)
15861 (org-with-point-at pom
15862 (let ((range (org-get-property-block)))
15863 (when range
15864 (let* ((begin (car range))
15865 (origin (cdr range))
15866 (end (copy-marker origin))
15867 (re (org-re-property
15868 (concat (regexp-quote property) "\\+?") t t)))
15869 (goto-char begin)
15870 (while (re-search-forward re end t)
15871 (delete-region (match-beginning 0) (line-beginning-position 2)))
15872 ;; If drawer is empty, remove it altogether.
15873 (when (= begin end)
15874 (delete-region (line-beginning-position 0)
15875 (line-beginning-position 2)))
15876 ;; Return non-nil if some property was removed.
15877 (prog1 (/= end origin) (set-marker end nil))))))))
15879 ;; Multi-values properties are properties that contain multiple values
15880 ;; These values are assumed to be single words, separated by whitespace.
15881 (defun org-entry-add-to-multivalued-property (pom property value)
15882 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15883 (let* ((old (org-entry-get pom property))
15884 (values (and old (org-split-string old "[ \t]"))))
15885 (setq value (org-entry-protect-space value))
15886 (unless (member value values)
15887 (setq values (append values (list value)))
15888 (org-entry-put pom property
15889 (mapconcat 'identity values " ")))))
15891 (defun org-entry-remove-from-multivalued-property (pom property value)
15892 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15893 (let* ((old (org-entry-get pom property))
15894 (values (and old (org-split-string old "[ \t]"))))
15895 (setq value (org-entry-protect-space value))
15896 (when (member value values)
15897 (setq values (delete value values))
15898 (org-entry-put pom property
15899 (mapconcat 'identity values " ")))))
15901 (defun org-entry-member-in-multivalued-property (pom property value)
15902 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15903 (let* ((old (org-entry-get pom property))
15904 (values (and old (org-split-string old "[ \t]"))))
15905 (setq value (org-entry-protect-space value))
15906 (member value values)))
15908 (defun org-entry-get-multivalued-property (pom property)
15909 "Return a list of values in a multivalued property."
15910 (let* ((value (org-entry-get pom property))
15911 (values (and value (org-split-string value "[ \t]"))))
15912 (mapcar 'org-entry-restore-space values)))
15914 (defun org-entry-put-multivalued-property (pom property &rest values)
15915 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15916 VALUES should be a list of strings. Spaces will be protected."
15917 (org-entry-put pom property
15918 (mapconcat 'org-entry-protect-space values " "))
15919 (let* ((value (org-entry-get pom property))
15920 (values (and value (org-split-string value "[ \t]"))))
15921 (mapcar 'org-entry-restore-space values)))
15923 (defun org-entry-protect-space (s)
15924 "Protect spaces and newline in string S."
15925 (while (string-match " " s)
15926 (setq s (replace-match "%20" t t s)))
15927 (while (string-match "\n" s)
15928 (setq s (replace-match "%0A" t t s)))
15931 (defun org-entry-restore-space (s)
15932 "Restore spaces and newline in string S."
15933 (while (string-match "%20" s)
15934 (setq s (replace-match " " t t s)))
15935 (while (string-match "%0A" s)
15936 (setq s (replace-match "\n" t t s)))
15939 (defvar org-entry-property-inherited-from (make-marker)
15940 "Marker pointing to the entry from where a property was inherited.
15941 Each call to `org-entry-get-with-inheritance' will set this marker to the
15942 location of the entry where the inheritance search matched. If there was
15943 no match, the marker will point nowhere.
15944 Note that also `org-entry-get' calls this function, if the INHERIT flag
15945 is set.")
15947 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15948 "Get PROPERTY of entry or content at point, search higher levels if needed.
15949 The search will stop at the first ancestor which has the property defined.
15950 If the value found is \"nil\", return nil to show that the property
15951 should be considered as undefined (this is the meaning of nil here).
15952 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15953 (move-marker org-entry-property-inherited-from nil)
15954 (org-with-wide-buffer
15955 (let (value)
15956 (catch 'exit
15957 (while t
15958 (let ((v (org-property--local-values property literal-nil)))
15959 (when v
15960 (setq value
15961 (concat (mapconcat #'identity (delq nil v) " ")
15962 (and value " ")
15963 value)))
15964 (cond
15965 ((car v)
15966 (org-back-to-heading t)
15967 (move-marker org-entry-property-inherited-from (point))
15968 (throw 'exit nil))
15969 ((org-up-heading-safe))
15971 (let ((global
15972 (cdr (or (assoc-string property org-file-properties t)
15973 (assoc-string property org-global-properties t)
15974 (assoc-string property org-global-properties-fixed t)))))
15975 (cond ((not global))
15976 (value (setq value (concat global " " value)))
15977 (t (setq value global))))
15978 (throw 'exit nil))))))
15979 (if literal-nil value (org-not-nil value)))))
15981 (defvar org-property-changed-functions nil
15982 "Hook called when the value of a property has changed.
15983 Each hook function should accept two arguments, the name of the property
15984 and the new value.")
15986 (defun org-entry-put (pom property value)
15987 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15989 If the value is nil, it is converted to the empty string. If it
15990 is not a string, an error is raised. Also raise an error on
15991 invalid property names.
15993 PROPERTY can be any regular property (see
15994 `org-special-properties'). It can also be \"TODO\",
15995 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15997 For the last two properties, VALUE may have any of the special
15998 values \"earlier\" and \"later\". The function then increases or
15999 decreases scheduled or deadline date by one day."
16000 (cond ((null value) (setq value ""))
16001 ((not (stringp value)) (error "Properties values should be strings"))
16002 ((not (org--valid-property-p property))
16003 (user-error "Invalid property name: \"%s\"" property)))
16004 (org-with-point-at pom
16005 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16006 (org-back-to-heading t)
16007 (org-with-limited-levels (org-back-to-heading t)))
16008 (let ((beg (point)))
16009 (cond
16010 ((equal property "TODO")
16011 (cond ((not (org-string-nw-p value)) (setq value 'none))
16012 ((not (member value org-todo-keywords-1))
16013 (user-error "\"%s\" is not a valid TODO state" value)))
16014 (org-todo value)
16015 (org-set-tags nil 'align))
16016 ((equal property "PRIORITY")
16017 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16018 (org-set-tags nil 'align))
16019 ((equal property "SCHEDULED")
16020 (forward-line)
16021 (if (and (org-looking-at-p org-planning-line-re)
16022 (re-search-forward
16023 org-scheduled-time-regexp (line-end-position) t))
16024 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16025 ((string= value "later") (org-timestamp-change 1 'day))
16026 ((string= value "") (org-schedule '(4)))
16027 (t (org-schedule nil value)))
16028 (if (member value '("earlier" "later" ""))
16029 (call-interactively #'org-schedule)
16030 (org-schedule nil value))))
16031 ((equal property "DEADLINE")
16032 (forward-line)
16033 (if (and (org-looking-at-p org-planning-line-re)
16034 (re-search-forward
16035 org-deadline-time-regexp (line-end-position) t))
16036 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16037 ((string= value "later") (org-timestamp-change 1 'day))
16038 ((string= value "") (org-deadline '(4)))
16039 (t (org-deadline nil value)))
16040 (if (member value '("earlier" "later" ""))
16041 (call-interactively #'org-deadline)
16042 (org-deadline nil value))))
16043 ((member property org-special-properties)
16044 (error "The %s property cannot be set with `org-entry-put'" property))
16046 (let* ((range (org-get-property-block beg 'force))
16047 (end (cdr range))
16048 (case-fold-search t))
16049 (goto-char (car range))
16050 (if (re-search-forward (org-re-property property nil t) end t)
16051 (progn (delete-region (match-beginning 0) (match-end 0))
16052 (goto-char (match-beginning 0)))
16053 (goto-char end)
16054 (insert "\n")
16055 (backward-char))
16056 (insert ":" property ":")
16057 (when value (insert " " value))
16058 (org-indent-line)))))
16059 (run-hook-with-args 'org-property-changed-functions property value)))
16061 (defun org-buffer-property-keys
16062 (&optional specials defaults columns ignore-malformed)
16063 "Get all property keys in the current buffer.
16065 When SPECIALS is non-nil, also list the special properties that
16066 reflect things like tags and TODO state.
16068 When DEFAULTS is non-nil, also include properties that has
16069 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16070 DESCRIPTION, LOCATION, and LOGGING and others.
16072 When COLUMNS in non-nil, also include property names given in
16073 COLUMN formats in the current buffer.
16075 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16076 automatically performed, such drawers will be silently ignored."
16077 (let ((case-fold-search t)
16078 (props (append
16079 (and specials org-special-properties)
16080 (and defaults (cons org-effort-property org-default-properties))
16081 nil)))
16082 (org-with-wide-buffer
16083 (goto-char (point-min))
16084 (while (re-search-forward org-property-start-re nil t)
16085 (let ((range (org-get-property-block)))
16086 (catch 'skip
16087 (unless range
16088 (when (and (not ignore-malformed)
16089 (not (org-before-first-heading-p))
16090 (y-or-n-p (format "Malformed drawer at %d, repair?"
16091 (line-beginning-position))))
16092 (org-get-property-block nil t))
16093 (throw 'skip nil))
16094 (goto-char (car range))
16095 (let ((begin (car range))
16096 (end (cdr range)))
16097 ;; Make sure that found property block is not located
16098 ;; before current point, as it would generate an infloop.
16099 ;; It can happen, for example, in the following
16100 ;; situation:
16102 ;; * Headline
16103 ;; :PROPERTIES:
16104 ;; ...
16105 ;; :END:
16106 ;; *************** Inlinetask
16107 ;; #+BEGIN_EXAMPLE
16108 ;; :PROPERTIES:
16109 ;; #+END_EXAMPLE
16111 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16112 (while (< (point) end)
16113 (let ((p (progn (looking-at org-property-re)
16114 (org-match-string-no-properties 2))))
16115 ;; Only add true property name, not extension symbol.
16116 (push (if (not (org-string-match-p "\\+\\'" p)) p
16117 (substring p 0 -1))
16118 props))
16119 (forward-line))))
16120 (outline-next-heading)))
16121 (when columns
16122 (goto-char (point-min))
16123 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16124 (let ((element (org-element-at-point)))
16125 (when (memq (org-element-type element) '(keyword node-property))
16126 (let ((value (org-element-property :value element))
16127 (start 0))
16128 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16129 (setq start (match-end 0))
16130 (let ((p (org-match-string-no-properties 1 value)))
16131 (unless (member-ignore-case p org-special-properties)
16132 (push p props))))))))))
16133 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16135 (defun org-property-values (key)
16136 "List all non-nil values of property KEY in current buffer."
16137 (org-with-wide-buffer
16138 (goto-char (point-min))
16139 (let ((case-fold-search t)
16140 (re (org-re-property key))
16141 values)
16142 (while (re-search-forward re nil t)
16143 (push (org-entry-get (point) key) values))
16144 (delete-dups values))))
16146 (defun org-insert-property-drawer ()
16147 "Insert a property drawer into the current entry."
16148 (org-with-wide-buffer
16149 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16150 (org-back-to-heading t)
16151 (org-with-limited-levels (org-back-to-heading t)))
16152 (forward-line)
16153 (when (org-looking-at-p org-planning-line-re) (forward-line))
16154 (unless (org-looking-at-p org-property-drawer-re)
16155 ;; Make sure we start editing a line from current entry, not from
16156 ;; next one. It prevents extending text properties or overlays
16157 ;; belonging to the latter.
16158 (when (bolp) (backward-char))
16159 (let ((begin (1+ (point)))
16160 (inhibit-read-only t))
16161 (insert "\n:PROPERTIES:\n:END:")
16162 (when (eobp) (insert "\n"))
16163 (org-indent-region begin (point))))))
16165 (defun org-insert-drawer (&optional arg drawer)
16166 "Insert a drawer at point.
16168 When optional argument ARG is non-nil, insert a property drawer.
16170 Optional argument DRAWER, when non-nil, is a string representing
16171 drawer's name. Otherwise, the user is prompted for a name.
16173 If a region is active, insert the drawer around that region
16174 instead.
16176 Point is left between drawer's boundaries."
16177 (interactive "P")
16178 (let* ((drawer (if arg "PROPERTIES"
16179 (or drawer (read-from-minibuffer "Drawer: ")))))
16180 (cond
16181 ;; With C-u, fall back on `org-insert-property-drawer'
16182 (arg (org-insert-property-drawer))
16183 ;; Check validity of suggested drawer's name.
16184 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16185 (user-error "Invalid drawer name"))
16186 ;; With an active region, insert a drawer at point.
16187 ((not (org-region-active-p))
16188 (progn
16189 (unless (bolp) (insert "\n"))
16190 (insert (format ":%s:\n\n:END:\n" drawer))
16191 (forward-line -2)))
16192 ;; Otherwise, insert the drawer at point
16194 (let ((rbeg (region-beginning))
16195 (rend (copy-marker (region-end))))
16196 (unwind-protect
16197 (progn
16198 (goto-char rbeg)
16199 (beginning-of-line)
16200 (when (save-excursion
16201 (re-search-forward org-outline-regexp-bol rend t))
16202 (user-error "Drawers cannot contain headlines"))
16203 ;; Position point at the beginning of the first
16204 ;; non-blank line in region. Insert drawer's opening
16205 ;; there, then indent it.
16206 (org-skip-whitespace)
16207 (beginning-of-line)
16208 (insert ":" drawer ":\n")
16209 (forward-line -1)
16210 (indent-for-tab-command)
16211 ;; Move point to the beginning of the first blank line
16212 ;; after the last non-blank line in region. Insert
16213 ;; drawer's closing, then indent it.
16214 (goto-char rend)
16215 (skip-chars-backward " \r\t\n")
16216 (insert "\n:END:")
16217 (deactivate-mark t)
16218 (indent-for-tab-command)
16219 (unless (eolp) (insert "\n")))
16220 ;; Clear marker, whatever the outcome of insertion is.
16221 (set-marker rend nil)))))))
16223 (defvar org-property-set-functions-alist nil
16224 "Property set function alist.
16225 Each entry should have the following format:
16227 (PROPERTY . READ-FUNCTION)
16229 The read function will be called with the same argument as
16230 `org-completing-read'.")
16232 (defun org-set-property-function (property)
16233 "Get the function that should be used to set PROPERTY.
16234 This is computed according to `org-property-set-functions-alist'."
16235 (or (cdr (assoc property org-property-set-functions-alist))
16236 'org-completing-read))
16238 (defun org-read-property-value (property)
16239 "Read PROPERTY value from user."
16240 (let* ((completion-ignore-case t)
16241 (allowed (org-property-get-allowed-values nil property 'table))
16242 (cur (org-entry-get nil property))
16243 (prompt (concat property " value"
16244 (if (and cur (string-match "\\S-" cur))
16245 (concat " [" cur "]") "") ": "))
16246 (set-function (org-set-property-function property))
16247 (val (if allowed
16248 (funcall set-function prompt allowed nil
16249 (not (get-text-property 0 'org-unrestricted
16250 (caar allowed))))
16251 (let (org-completion-use-ido org-completion-use-iswitchb)
16252 (funcall set-function prompt
16253 (mapcar 'list (org-property-values property))
16254 nil nil "" nil cur)))))
16255 (org-trim val)))
16257 (defvar org-last-set-property nil)
16258 (defvar org-last-set-property-value nil)
16259 (defun org-read-property-name ()
16260 "Read a property name."
16261 (let ((completion-ignore-case t)
16262 (default-prop (or (and (org-at-property-p)
16263 (org-match-string-no-properties 2))
16264 org-last-set-property)))
16265 (org-completing-read
16266 (concat "Property"
16267 (if default-prop (concat " [" default-prop "]") "")
16268 ": ")
16269 (mapcar #'list (org-buffer-property-keys nil t t))
16270 nil nil nil nil default-prop)))
16272 (defun org-set-property-and-value (use-last)
16273 "Allow to set [PROPERTY]: [value] direction from prompt.
16274 When use-default, don't even ask, just use the last
16275 \"[PROPERTY]: [value]\" string from the history."
16276 (interactive "P")
16277 (let* ((completion-ignore-case t)
16278 (pv (or (and use-last org-last-set-property-value)
16279 (org-completing-read
16280 "Enter a \"[Property]: [value]\" pair: "
16281 nil nil nil nil nil
16282 org-last-set-property-value)))
16283 prop val)
16284 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16285 (setq prop (match-string 1 pv)
16286 val (match-string 2 pv))
16287 (org-set-property prop val))))
16289 (defun org-set-property (property value)
16290 "In the current entry, set PROPERTY to VALUE.
16292 When called interactively, this will prompt for a property name, offering
16293 completion on existing and default properties. And then it will prompt
16294 for a value, offering completion either on allowed values (via an inherited
16295 xxx_ALL property) or on existing values in other instances of this property
16296 in the current file.
16298 Throw an error when trying to set a property with an invalid name."
16299 (interactive (list nil nil))
16300 (let ((property (or property (org-read-property-name))))
16301 ;; `org-entry-put' also makes the following check, but this one
16302 ;; avoids polluting `org-last-set-property' and
16303 ;; `org-last-set-property-value' needlessly.
16304 (unless (org--valid-property-p property)
16305 (user-error "Invalid property name: \"%s\"" property))
16306 (let ((value (or value (org-read-property-value property)))
16307 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16308 (setq org-last-set-property property)
16309 (setq org-last-set-property-value (concat property ": " value))
16310 ;; Possibly postprocess the inserted value:
16311 (when fn (setq value (funcall fn value)))
16312 (unless (equal (org-entry-get nil property) value)
16313 (org-entry-put nil property value)))))
16315 (defun org-find-property (property &optional value)
16316 "Find first entry in buffer that sets PROPERTY.
16318 When optional argument VALUE is non-nil, only consider an entry
16319 if it contains PROPERTY set to this value. If PROPERTY should be
16320 explicitly set to nil, use string \"nil\" for VALUE.
16322 Return position where the entry begins, or nil if there is no
16323 such entry. If narrowing is in effect, only search the visible
16324 part of the buffer."
16325 (save-excursion
16326 (goto-char (point-min))
16327 (let ((case-fold-search t)
16328 (re (org-re-property property nil (not value) value)))
16329 (catch 'exit
16330 (while (re-search-forward re nil t)
16331 (when (if value (org-at-property-p)
16332 (org-entry-get (point) property nil t))
16333 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16335 (defun org-delete-property (property)
16336 "In the current entry, delete PROPERTY."
16337 (interactive
16338 (let* ((completion-ignore-case t)
16339 (cat (org-entry-get (point) "CATEGORY"))
16340 (props0 (org-entry-properties nil 'standard))
16341 (props (if cat props0
16342 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16343 (prop (if (< 1 (length props))
16344 (completing-read "Property: " props nil t)
16345 (caar props))))
16346 (list prop)))
16347 (if (not property)
16348 (message "No property to delete in this entry")
16349 (org-entry-delete nil property)
16350 (message "Property \"%s\" deleted" property)))
16352 (defun org-delete-property-globally (property)
16353 "Remove PROPERTY globally, from all entries.
16354 This function ignores narrowing, if any."
16355 (interactive
16356 (let* ((completion-ignore-case t)
16357 (prop (completing-read
16358 "Globally remove property: "
16359 (mapcar #'list (org-buffer-property-keys)))))
16360 (list prop)))
16361 (org-with-wide-buffer
16362 (goto-char (point-min))
16363 (let ((count 0)
16364 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16365 (while (re-search-forward re nil t)
16366 (when (org-entry-delete (point) property) (incf count)))
16367 (message "Property \"%s\" removed from %d entries" property count))))
16369 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16371 (defun org-compute-property-at-point ()
16372 "Compute the property at point.
16373 This looks for an enclosing column format, extracts the operator and
16374 then applies it to the property in the column format's scope."
16375 (interactive)
16376 (unless (org-at-property-p)
16377 (user-error "Not at a property"))
16378 (let ((prop (org-match-string-no-properties 2)))
16379 (org-columns-get-format-and-top-level)
16380 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16381 (user-error "No operator defined for property %s" prop))
16382 (org-columns-compute prop)))
16384 (defvar org-property-allowed-value-functions nil
16385 "Hook for functions supplying allowed values for a specific property.
16386 The functions must take a single argument, the name of the property, and
16387 return a flat list of allowed values. If \":ETC\" is one of
16388 the values, this means that these values are intended as defaults for
16389 completion, but that other values should be allowed too.
16390 The functions must return nil if they are not responsible for this
16391 property.")
16393 (defun org-property-get-allowed-values (pom property &optional table)
16394 "Get allowed values for the property PROPERTY.
16395 When TABLE is non-nil, return an alist that can directly be used for
16396 completion."
16397 (let (vals)
16398 (cond
16399 ((equal property "TODO")
16400 (setq vals (org-with-point-at pom
16401 (append org-todo-keywords-1 '("")))))
16402 ((equal property "PRIORITY")
16403 (let ((n org-lowest-priority))
16404 (while (>= n org-highest-priority)
16405 (push (char-to-string n) vals)
16406 (setq n (1- n)))))
16407 ((equal property "CATEGORY"))
16408 ((member property org-special-properties))
16409 ((setq vals (run-hook-with-args-until-success
16410 'org-property-allowed-value-functions property)))
16412 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16413 (when (and vals (string-match "\\S-" vals))
16414 (setq vals (car (read-from-string (concat "(" vals ")"))))
16415 (setq vals (mapcar (lambda (x)
16416 (cond ((stringp x) x)
16417 ((numberp x) (number-to-string x))
16418 ((symbolp x) (symbol-name x))
16419 (t "???")))
16420 vals)))))
16421 (when (member ":ETC" vals)
16422 (setq vals (remove ":ETC" vals))
16423 (org-add-props (car vals) '(org-unrestricted t)))
16424 (if table (mapcar 'list vals) vals)))
16426 (defun org-property-previous-allowed-value (&optional _previous)
16427 "Switch to the next allowed value for this property."
16428 (interactive)
16429 (org-property-next-allowed-value t))
16431 (defun org-property-next-allowed-value (&optional previous)
16432 "Switch to the next allowed value for this property."
16433 (interactive)
16434 (unless (org-at-property-p)
16435 (user-error "Not at a property"))
16436 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16437 (key (match-string 2))
16438 (value (match-string 3))
16439 (allowed (or (org-property-get-allowed-values (point) key)
16440 (and (member value '("[ ]" "[-]" "[X]"))
16441 '("[ ]" "[X]"))))
16442 (heading (save-match-data (nth 4 (org-heading-components))))
16443 nval)
16444 (unless allowed
16445 (user-error "Allowed values for this property have not been defined"))
16446 (when previous (setq allowed (reverse allowed)))
16447 (when (member value allowed)
16448 (setq nval (car (cdr (member value allowed)))))
16449 (setq nval (or nval (car allowed)))
16450 (when (equal nval value)
16451 (user-error "Only one allowed value for this property"))
16452 (org-at-property-p)
16453 (replace-match (concat " :" key ": " nval) t t)
16454 (org-indent-line)
16455 (beginning-of-line 1)
16456 (skip-chars-forward " \t")
16457 (when (equal prop org-effort-property)
16458 (org-refresh-property
16459 '((effort . identity)
16460 (effort-minutes . org-duration-string-to-minutes))
16461 nval)
16462 (when (string= org-clock-current-task heading)
16463 (setq org-clock-effort nval)
16464 (org-clock-update-mode-line)))
16465 (run-hook-with-args 'org-property-changed-functions key nval)))
16467 (defun org-find-olp (path &optional this-buffer)
16468 "Return a marker pointing to the entry at outline path OLP.
16469 If anything goes wrong, throw an error.
16470 You can wrap this call to catch the error like this:
16472 \(condition-case msg
16473 \(org-mobile-locate-entry (match-string 4))
16474 \(error (nth 1 msg)))
16476 The return value will then be either a string with the error message,
16477 or a marker if everything is OK.
16479 If THIS-BUFFER is set, the outline path does not contain a file,
16480 only headings."
16481 (let* ((file (if this-buffer buffer-file-name (pop path)))
16482 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16483 (level 1)
16484 (lmin 1)
16485 (lmax 1)
16486 end found flevel)
16487 (unless buffer (error "File not found :%s" file))
16488 (with-current-buffer buffer
16489 (org-with-wide-buffer
16490 (goto-char (point-min))
16491 (dolist (heading path)
16492 (let ((re (format org-complex-heading-regexp-format
16493 (regexp-quote heading)))
16494 (cnt 0))
16495 (while (re-search-forward re end t)
16496 (setq level (- (match-end 1) (match-beginning 1)))
16497 (when (and (>= level lmin) (<= level lmax))
16498 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16499 (when (= cnt 0)
16500 (error "Heading not found on level %d: %s" lmax heading))
16501 (when (> cnt 1)
16502 (error "Heading not unique on level %d: %s" lmax heading))
16503 (goto-char found)
16504 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16505 (setq end (save-excursion (org-end-of-subtree t t)))))
16506 (when (org-at-heading-p)
16507 (point-marker))))))
16509 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16510 "Find node HEADING in BUFFER.
16511 Return a marker to the heading if it was found, or nil if not.
16512 If POS-ONLY is set, return just the position instead of a marker.
16514 The heading text must match exact, but it may have a TODO keyword,
16515 a priority cookie and tags in the standard locations."
16516 (with-current-buffer (or buffer (current-buffer))
16517 (save-excursion
16518 (save-restriction
16519 (widen)
16520 (goto-char (point-min))
16521 (let (case-fold-search)
16522 (when (re-search-forward
16523 (format org-complex-heading-regexp-format
16524 (regexp-quote heading)) nil t)
16525 (if pos-only
16526 (match-beginning 0)
16527 (move-marker (make-marker) (match-beginning 0)))))))))
16529 (defun org-find-exact-heading-in-directory (heading &optional dir)
16530 "Find Org node headline HEADING in all .org files in directory DIR.
16531 When the target headline is found, return a marker to this location."
16532 (let ((files (directory-files (or dir default-directory)
16533 t "\\`[^.#].*\\.org\\'"))
16534 visiting m buffer)
16535 (catch 'found
16536 (dolist (file files)
16537 (message "trying %s" file)
16538 (setq visiting (org-find-base-buffer-visiting file))
16539 (setq buffer (or visiting (find-file-noselect file)))
16540 (setq m (org-find-exact-headline-in-buffer
16541 heading buffer))
16542 (when (and (not m) (not visiting)) (kill-buffer buffer))
16543 (and m (throw 'found m))))))
16545 (defun org-find-entry-with-id (ident)
16546 "Locate the entry that contains the ID property with exact value IDENT.
16547 IDENT can be a string, a symbol or a number, this function will search for
16548 the string representation of it.
16549 Return the position where this entry starts, or nil if there is no such entry."
16550 (interactive "sID: ")
16551 (let ((id (cond
16552 ((stringp ident) ident)
16553 ((symbolp ident) (symbol-name ident))
16554 ((numberp ident) (number-to-string ident))
16555 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16556 (org-with-wide-buffer (org-find-property "ID" id))))
16558 ;;;; Timestamps
16560 (defvar org-last-changed-timestamp nil)
16561 (defvar org-last-inserted-timestamp nil
16562 "The last time stamp inserted with `org-insert-time-stamp'.")
16563 (defvar org-ts-what) ; dynamically scoped parameter
16565 (defun org-time-stamp (arg &optional inactive)
16566 "Prompt for a date/time and insert a time stamp.
16568 If the user specifies a time like HH:MM or if this command is
16569 called with at least one prefix argument, the time stamp contains
16570 the date and the time. Otherwise, only the date is included.
16572 All parts of a date not specified by the user are filled in from
16573 the timestamp at point, if any, or the current date/time
16574 otherwise.
16576 If there is already a timestamp at the cursor, it is replaced.
16578 With two universal prefix arguments, insert an active timestamp
16579 with the current time without prompting the user.
16581 When called from lisp, the timestamp is inactive if INACTIVE is
16582 non-nil."
16583 (interactive "P")
16584 (let* ((ts (cond
16585 ((org-at-date-range-p t)
16586 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16587 ((org-at-timestamp-p t) (match-string 0))))
16588 ;; Default time is either the timestamp at point or today.
16589 ;; When entering a range, only the range start is considered.
16590 (default-time (if (not ts) (current-time)
16591 (apply #'encode-time (org-parse-time-string ts))))
16592 (default-input (and ts (org-get-compact-tod ts)))
16593 (repeater (and ts
16594 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16595 (match-string 0 ts)))
16596 org-time-was-given
16597 org-end-time-was-given
16598 (time
16599 (and (if (equal arg '(16)) (current-time)
16600 ;; Preserve `this-command' and `last-command'.
16601 (let ((this-command this-command)
16602 (last-command last-command))
16603 (org-read-date
16604 arg 'totime nil nil default-time default-input
16605 inactive))))))
16606 (cond
16607 ((and ts
16608 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16609 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16610 (insert "--")
16611 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16613 ;; Make sure we're on a timestamp. When in the middle of a date
16614 ;; range, move arbitrarily to range end.
16615 (unless (org-at-timestamp-p t)
16616 (skip-chars-forward "-")
16617 (org-at-timestamp-p t))
16618 (replace-match "")
16619 (setq org-last-changed-timestamp
16620 (org-insert-time-stamp
16621 time (or org-time-was-given arg)
16622 inactive nil nil (list org-end-time-was-given)))
16623 (when repeater
16624 (backward-char)
16625 (insert " " repeater)
16626 (setq org-last-changed-timestamp
16627 (concat (substring org-last-inserted-timestamp 0 -1)
16628 " " repeater ">")))
16629 (message "Timestamp updated"))
16630 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16631 (t (org-insert-time-stamp
16632 time (or org-time-was-given arg) inactive nil nil
16633 (list org-end-time-was-given))))))
16635 ;; FIXME: can we use this for something else, like computing time differences?
16636 (defun org-get-compact-tod (s)
16637 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16638 (let* ((t1 (match-string 1 s))
16639 (h1 (string-to-number (match-string 2 s)))
16640 (m1 (string-to-number (match-string 3 s)))
16641 (t2 (and (match-end 4) (match-string 5 s)))
16642 (h2 (and t2 (string-to-number (match-string 6 s))))
16643 (m2 (and t2 (string-to-number (match-string 7 s))))
16644 dh dm)
16645 (if (not t2)
16647 (setq dh (- h2 h1) dm (- m2 m1))
16648 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16649 (concat t1 "+" (number-to-string dh)
16650 (and (/= 0 dm) (format ":%02d" dm)))))))
16652 (defun org-time-stamp-inactive (&optional arg)
16653 "Insert an inactive time stamp.
16654 An inactive time stamp is enclosed in square brackets instead of angle
16655 brackets. It is inactive in the sense that it does not trigger agenda entries,
16656 does not link to the calendar and cannot be changed with the S-cursor keys.
16657 So these are more for recording a certain time/date."
16658 (interactive "P")
16659 (org-time-stamp arg 'inactive))
16661 (defvar org-date-ovl (make-overlay 1 1))
16662 (overlay-put org-date-ovl 'face 'org-date-selected)
16663 (org-detach-overlay org-date-ovl)
16665 (defvar org-ans1) ; dynamically scoped parameter
16666 (defvar org-ans2) ; dynamically scoped parameter
16668 (defvar org-plain-time-of-day-regexp) ; defined below
16670 (defvar org-overriding-default-time nil) ; dynamically scoped
16671 (defvar org-read-date-overlay nil)
16672 (defvar org-dcst nil) ; dynamically scoped
16673 (defvar org-read-date-history nil)
16674 (defvar org-read-date-final-answer nil)
16675 (defvar org-read-date-analyze-futurep nil)
16676 (defvar org-read-date-analyze-forced-year nil)
16677 (defvar org-read-date-inactive)
16679 (defvar org-read-date-minibuffer-local-map
16680 (let* ((map (make-sparse-keymap)))
16681 (set-keymap-parent map minibuffer-local-map)
16682 (org-defkey map (kbd ".")
16683 (lambda () (interactive)
16684 ;; Are we at the beginning of the prompt?
16685 (if (org-looking-back "^[^:]+: "
16686 (let ((inhibit-field-text-motion t))
16687 (line-beginning-position)))
16688 (org-eval-in-calendar '(calendar-goto-today))
16689 (insert "."))))
16690 (org-defkey map (kbd "C-.")
16691 (lambda () (interactive)
16692 (org-eval-in-calendar '(calendar-goto-today))))
16693 (org-defkey map [(meta shift left)]
16694 (lambda () (interactive)
16695 (org-eval-in-calendar '(calendar-backward-month 1))))
16696 (org-defkey map [(meta shift right)]
16697 (lambda () (interactive)
16698 (org-eval-in-calendar '(calendar-forward-month 1))))
16699 (org-defkey map [(meta shift up)]
16700 (lambda () (interactive)
16701 (org-eval-in-calendar '(calendar-backward-year 1))))
16702 (org-defkey map [(meta shift down)]
16703 (lambda () (interactive)
16704 (org-eval-in-calendar '(calendar-forward-year 1))))
16705 (org-defkey map [?\e (shift left)]
16706 (lambda () (interactive)
16707 (org-eval-in-calendar '(calendar-backward-month 1))))
16708 (org-defkey map [?\e (shift right)]
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(calendar-forward-month 1))))
16711 (org-defkey map [?\e (shift up)]
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(calendar-backward-year 1))))
16714 (org-defkey map [?\e (shift down)]
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-forward-year 1))))
16717 (org-defkey map [(shift up)]
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(calendar-backward-week 1))))
16720 (org-defkey map [(shift down)]
16721 (lambda () (interactive)
16722 (org-eval-in-calendar '(calendar-forward-week 1))))
16723 (org-defkey map [(shift left)]
16724 (lambda () (interactive)
16725 (org-eval-in-calendar '(calendar-backward-day 1))))
16726 (org-defkey map [(shift right)]
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-forward-day 1))))
16729 (org-defkey map "!"
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(diary-view-entries))
16732 (message "")))
16733 (org-defkey map ">"
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-scroll-left 1))))
16736 (org-defkey map "<"
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(calendar-scroll-right 1))))
16739 (org-defkey map "\C-v"
16740 (lambda () (interactive)
16741 (org-eval-in-calendar
16742 '(calendar-scroll-left-three-months 1))))
16743 (org-defkey map "\M-v"
16744 (lambda () (interactive)
16745 (org-eval-in-calendar
16746 '(calendar-scroll-right-three-months 1))))
16747 map)
16748 "Keymap for minibuffer commands when using `org-read-date'.")
16750 (defvar org-def)
16751 (defvar org-defdecode)
16752 (defvar org-with-time)
16754 (defvar calendar-setup) ; Dynamically scoped.
16755 (defun org-read-date (&optional with-time to-time from-string prompt
16756 default-time default-input inactive)
16757 "Read a date, possibly a time, and make things smooth for the user.
16758 The prompt will suggest to enter an ISO date, but you can also enter anything
16759 which will at least partially be understood by `parse-time-string'.
16760 Unrecognized parts of the date will default to the current day, month, year,
16761 hour and minute. If this command is called to replace a timestamp at point,
16762 or to enter the second timestamp of a range, the default time is taken
16763 from the existing stamp. Furthermore, the command prefers the future,
16764 so if you are giving a date where the year is not given, and the day-month
16765 combination is already past in the current year, it will assume you
16766 mean next year. For details, see the manual. A few examples:
16768 3-2-5 --> 2003-02-05
16769 feb 15 --> currentyear-02-15
16770 2/15 --> currentyear-02-15
16771 sep 12 9 --> 2009-09-12
16772 12:45 --> today 12:45
16773 22 sept 0:34 --> currentyear-09-22 0:34
16774 12 --> currentyear-currentmonth-12
16775 Fri --> nearest Friday after today
16776 -Tue --> last Tuesday
16777 etc.
16779 Furthermore you can specify a relative date by giving, as the *first* thing
16780 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16781 change in days weeks, months, years.
16782 With a single plus or minus, the date is relative to today. With a double
16783 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16784 +4d --> four days from today
16785 +4 --> same as above
16786 +2w --> two weeks from today
16787 ++5 --> five days from default date
16789 The function understands only English month and weekday abbreviations.
16791 While prompting, a calendar is popped up - you can also select the
16792 date with the mouse (button 1). The calendar shows a period of three
16793 months. To scroll it to other months, use the keys `>' and `<'.
16794 If you don't like the calendar, turn it off with
16795 (setq org-read-date-popup-calendar nil)
16797 With optional argument TO-TIME, the date will immediately be converted
16798 to an internal time.
16799 With an optional argument WITH-TIME, the prompt will suggest to
16800 also insert a time. Note that when WITH-TIME is not set, you can
16801 still enter a time, and this function will inform the calling routine
16802 about this change. The calling routine may then choose to change the
16803 format used to insert the time stamp into the buffer to include the time.
16804 With optional argument FROM-STRING, read from this string instead from
16805 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16806 the time/date that is used for everything that is not specified by the
16807 user."
16808 (require 'parse-time)
16809 (let* ((org-with-time with-time)
16810 (org-time-stamp-rounding-minutes
16811 (if (equal org-with-time '(16))
16812 '(0 0)
16813 org-time-stamp-rounding-minutes))
16814 (org-dcst org-display-custom-times)
16815 (ct (org-current-time))
16816 (org-def (or org-overriding-default-time default-time ct))
16817 (org-defdecode (decode-time org-def))
16818 (cur-frame (selected-frame))
16819 (mouse-autoselect-window nil) ; Don't let the mouse jump
16820 (calendar-setup
16821 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16822 (calendar-move-hook nil)
16823 (calendar-view-diary-initially-flag nil)
16824 (calendar-view-holidays-initially-flag nil)
16825 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16826 ;; Rationalize `org-def' and `org-defdecode', if required.
16827 (when (< (nth 2 org-defdecode) org-extend-today-until)
16828 (setf (nth 2 org-defdecode) -1)
16829 (setf (nth 1 org-defdecode) 59)
16830 (setq org-def (apply #'encode-time org-defdecode))
16831 (setq org-defdecode (decode-time org-def)))
16832 (let* ((timestr (format-time-string
16833 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16834 org-def))
16835 (prompt (concat (if prompt (concat prompt " ") "")
16836 (format "Date+time [%s]: " timestr))))
16837 (cond
16838 (from-string (setq ans from-string))
16839 (org-read-date-popup-calendar
16840 (save-excursion
16841 (save-window-excursion
16842 (calendar)
16843 (when (eq calendar-setup 'calendar-only)
16844 (setq cal-frame
16845 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16846 (select-frame cal-frame))
16847 (org-eval-in-calendar '(setq cursor-type nil) t)
16848 (unwind-protect
16849 (progn
16850 (calendar-forward-day (- (time-to-days org-def)
16851 (calendar-absolute-from-gregorian
16852 (calendar-current-date))))
16853 (org-eval-in-calendar nil t)
16854 (let* ((old-map (current-local-map))
16855 (map (copy-keymap calendar-mode-map))
16856 (minibuffer-local-map
16857 (copy-keymap org-read-date-minibuffer-local-map)))
16858 (org-defkey map (kbd "RET") 'org-calendar-select)
16859 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16860 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16861 (unwind-protect
16862 (progn
16863 (use-local-map map)
16864 (setq org-read-date-inactive inactive)
16865 (add-hook 'post-command-hook 'org-read-date-display)
16866 (setq org-ans0
16867 (read-string prompt
16868 default-input
16869 'org-read-date-history
16870 nil))
16871 ;; org-ans0: from prompt
16872 ;; org-ans1: from mouse click
16873 ;; org-ans2: from calendar motion
16874 (setq ans
16875 (concat org-ans0 " " (or org-ans1 org-ans2))))
16876 (remove-hook 'post-command-hook 'org-read-date-display)
16877 (use-local-map old-map)
16878 (when org-read-date-overlay
16879 (delete-overlay org-read-date-overlay)
16880 (setq org-read-date-overlay nil)))))
16881 (bury-buffer "*Calendar*")
16882 (when cal-frame
16883 (delete-frame cal-frame)
16884 (select-frame-set-input-focus cur-frame))))))
16886 (t ; Naked prompt only
16887 (unwind-protect
16888 (setq ans (read-string prompt default-input
16889 'org-read-date-history timestr))
16890 (when org-read-date-overlay
16891 (delete-overlay org-read-date-overlay)
16892 (setq org-read-date-overlay nil))))))
16894 (setq final (org-read-date-analyze ans org-def org-defdecode))
16896 (when org-read-date-analyze-forced-year
16897 (message "Year was forced into %s"
16898 (if org-read-date-force-compatible-dates
16899 "compatible range (1970-2037)"
16900 "range representable on this machine"))
16901 (ding))
16903 ;; One round trip to get rid of 34th of August and stuff like that....
16904 (setq final (decode-time (apply 'encode-time final)))
16906 (setq org-read-date-final-answer ans)
16908 (if to-time
16909 (apply 'encode-time final)
16910 (if (and (boundp 'org-time-was-given) org-time-was-given)
16911 (format "%04d-%02d-%02d %02d:%02d"
16912 (nth 5 final) (nth 4 final) (nth 3 final)
16913 (nth 2 final) (nth 1 final))
16914 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16916 (defun org-read-date-display ()
16917 "Display the current date prompt interpretation in the minibuffer."
16918 (when org-read-date-display-live
16919 (when org-read-date-overlay
16920 (delete-overlay org-read-date-overlay))
16921 (when (minibufferp (current-buffer))
16922 (save-excursion
16923 (end-of-line 1)
16924 (while (not (equal (buffer-substring
16925 (max (point-min) (- (point) 4)) (point))
16926 " "))
16927 (insert " ")))
16928 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16929 " " (or org-ans1 org-ans2)))
16930 (org-end-time-was-given nil)
16931 (f (org-read-date-analyze ans org-def org-defdecode))
16932 (fmts (if org-dcst
16933 org-time-stamp-custom-formats
16934 org-time-stamp-formats))
16935 (fmt (if (or org-with-time
16936 (and (boundp 'org-time-was-given) org-time-was-given))
16937 (cdr fmts)
16938 (car fmts)))
16939 (txt (format-time-string fmt (apply 'encode-time f)))
16940 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16941 (txt (concat "=> " txt)))
16942 (when (and org-end-time-was-given
16943 (string-match org-plain-time-of-day-regexp txt))
16944 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16945 org-end-time-was-given
16946 (substring txt (match-end 0)))))
16947 (when org-read-date-analyze-futurep
16948 (setq txt (concat txt " (=>F)")))
16949 (setq org-read-date-overlay
16950 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16951 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16953 (defun org-read-date-analyze (ans def defdecode)
16954 "Analyze the combined answer of the date prompt."
16955 ;; FIXME: cleanup and comment
16956 ;; Pass `current-time' result to `decode-time' (instead of calling
16957 ;; without arguments) so that only `current-time' has to be
16958 ;; overriden in tests.
16959 (let ((org-def def)
16960 (org-defdecode defdecode)
16961 (nowdecode (decode-time (current-time)))
16962 delta deltan deltaw deltadef year month day
16963 hour minute second wday pm h2 m2 tl wday1
16964 iso-year iso-weekday iso-week iso-date futurep kill-year)
16965 (setq org-read-date-analyze-futurep nil
16966 org-read-date-analyze-forced-year nil)
16967 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16968 (setq ans "+0"))
16970 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16971 (setq ans (replace-match "" t t ans)
16972 deltan (car delta)
16973 deltaw (nth 1 delta)
16974 deltadef (nth 2 delta)))
16976 ;; Check if there is an iso week date in there. If yes, store the
16977 ;; info and postpone interpreting it until the rest of the parsing
16978 ;; is done.
16979 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16980 (setq iso-year (when (match-end 1)
16981 (org-small-year-to-year
16982 (string-to-number (match-string 1 ans))))
16983 iso-weekday (when (match-end 3)
16984 (string-to-number (match-string 3 ans)))
16985 iso-week (string-to-number (match-string 2 ans)))
16986 (setq ans (replace-match "" t t ans)))
16988 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16989 (when (string-match
16990 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16991 (setq year (if (match-end 2)
16992 (string-to-number (match-string 2 ans))
16993 (progn (setq kill-year t)
16994 (string-to-number (format-time-string "%Y"))))
16995 month (string-to-number (match-string 3 ans))
16996 day (string-to-number (match-string 4 ans)))
16997 (when (< year 100) (setq year (+ 2000 year)))
16998 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16999 t nil ans)))
17001 ;; Help matching dotted european dates
17002 (when (string-match
17003 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17004 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17005 (setq kill-year t)
17006 (string-to-number (format-time-string "%Y")))
17007 day (string-to-number (match-string 1 ans))
17008 month (string-to-number (match-string 2 ans))
17009 ans (replace-match (format "%04d-%02d-%02d" year month day)
17010 t nil ans)))
17012 ;; Help matching american dates, like 5/30 or 5/30/7
17013 (when (string-match
17014 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17015 (setq year (if (match-end 4)
17016 (string-to-number (match-string 4 ans))
17017 (progn (setq kill-year t)
17018 (string-to-number (format-time-string "%Y"))))
17019 month (string-to-number (match-string 1 ans))
17020 day (string-to-number (match-string 2 ans)))
17021 (when (< year 100) (setq year (+ 2000 year)))
17022 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17023 t nil ans)))
17024 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17025 ;; If there is a time with am/pm, and *no* time without it, we convert
17026 ;; so that matching will be successful.
17027 (loop for i from 1 to 2 do ; twice, for end time as well
17028 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17029 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17030 (setq hour (string-to-number (match-string 1 ans))
17031 minute (if (match-end 3)
17032 (string-to-number (match-string 3 ans))
17034 pm (equal ?p
17035 (string-to-char (downcase (match-string 4 ans)))))
17036 (if (and (= hour 12) (not pm))
17037 (setq hour 0)
17038 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17039 (setq ans (replace-match (format "%02d:%02d" hour minute)
17040 t t ans))))
17042 ;; Check if a time range is given as a duration
17043 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17044 (setq hour (string-to-number (match-string 1 ans))
17045 h2 (+ hour (string-to-number (match-string 3 ans)))
17046 minute (string-to-number (match-string 2 ans))
17047 m2 (+ minute (if (match-end 5) (string-to-number
17048 (match-string 5 ans))0)))
17049 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17050 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17051 t t ans)))
17053 ;; Check if there is a time range
17054 (when (boundp 'org-end-time-was-given)
17055 (setq org-time-was-given nil)
17056 (when (and (string-match org-plain-time-of-day-regexp ans)
17057 (match-end 8))
17058 (setq org-end-time-was-given (match-string 8 ans))
17059 (setq ans (concat (substring ans 0 (match-beginning 7))
17060 (substring ans (match-end 7))))))
17062 (setq tl (parse-time-string ans)
17063 day (or (nth 3 tl) (nth 3 org-defdecode))
17064 month
17065 (cond ((nth 4 tl))
17066 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17067 ;; Day was specified. Make sure DAY+MONTH
17068 ;; combination happens in the future.
17069 ((nth 3 tl)
17070 (setq futurep t)
17071 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17072 (nth 4 nowdecode)))
17073 (t (nth 4 org-defdecode)))
17074 year
17075 (cond ((and (not kill-year) (nth 5 tl)))
17076 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17077 ;; Month was guessed in the future and is at least
17078 ;; equal to NOWDECODE's. Fix year accordingly.
17079 (futurep
17080 (if (or (> month (nth 4 nowdecode))
17081 (>= day (nth 3 nowdecode)))
17082 (nth 5 nowdecode)
17083 (1+ (nth 5 nowdecode))))
17084 ;; Month was specified. Make sure MONTH+YEAR
17085 ;; combination happens in the future.
17086 ((nth 4 tl)
17087 (setq futurep t)
17088 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17089 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17090 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17091 (t (nth 5 nowdecode))))
17092 (t (nth 5 org-defdecode)))
17093 hour (or (nth 2 tl) (nth 2 org-defdecode))
17094 minute (or (nth 1 tl) (nth 1 org-defdecode))
17095 second (or (nth 0 tl) 0)
17096 wday (nth 6 tl))
17098 (when (and (eq org-read-date-prefer-future 'time)
17099 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17100 (equal day (nth 3 nowdecode))
17101 (equal month (nth 4 nowdecode))
17102 (equal year (nth 5 nowdecode))
17103 (nth 2 tl)
17104 (or (< (nth 2 tl) (nth 2 nowdecode))
17105 (and (= (nth 2 tl) (nth 2 nowdecode))
17106 (nth 1 tl)
17107 (< (nth 1 tl) (nth 1 nowdecode)))))
17108 (setq day (1+ day)
17109 futurep t))
17111 ;; Special date definitions below
17112 (cond
17113 (iso-week
17114 ;; There was an iso week
17115 (require 'cal-iso)
17116 (setq futurep nil)
17117 (setq year (or iso-year year)
17118 day (or iso-weekday wday 1)
17119 wday nil ; to make sure that the trigger below does not match
17120 iso-date (calendar-gregorian-from-absolute
17121 (calendar-iso-to-absolute
17122 (list iso-week day year))))
17123 ; FIXME: Should we also push ISO weeks into the future?
17124 ; (when (and org-read-date-prefer-future
17125 ; (not iso-year)
17126 ; (< (calendar-absolute-from-gregorian iso-date)
17127 ; (time-to-days (current-time))))
17128 ; (setq year (1+ year)
17129 ; iso-date (calendar-gregorian-from-absolute
17130 ; (calendar-iso-to-absolute
17131 ; (list iso-week day year)))))
17132 (setq month (car iso-date)
17133 year (nth 2 iso-date)
17134 day (nth 1 iso-date)))
17135 (deltan
17136 (setq futurep nil)
17137 (unless deltadef
17138 ;; Pass `current-time' result to `decode-time' (instead of
17139 ;; calling without arguments) so that only `current-time' has
17140 ;; to be overriden in tests.
17141 (let ((now (decode-time (current-time))))
17142 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17143 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17144 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17145 ((equal deltaw "m") (setq month (+ month deltan)))
17146 ((equal deltaw "y") (setq year (+ year deltan)))))
17147 ((and wday (not (nth 3 tl)))
17148 ;; Weekday was given, but no day, so pick that day in the week
17149 ;; on or after the derived date.
17150 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17151 (unless (equal wday wday1)
17152 (setq day (+ day (% (- wday wday1 -7) 7))))))
17153 (when (and (boundp 'org-time-was-given)
17154 (nth 2 tl))
17155 (setq org-time-was-given t))
17156 (when (< year 100) (setq year (+ 2000 year)))
17157 ;; Check of the date is representable
17158 (if org-read-date-force-compatible-dates
17159 (progn
17160 (when (< year 1970)
17161 (setq year 1970 org-read-date-analyze-forced-year t))
17162 (when (> year 2037)
17163 (setq year 2037 org-read-date-analyze-forced-year t)))
17164 (condition-case nil
17165 (ignore (encode-time second minute hour day month year))
17166 (error
17167 (setq year (nth 5 org-defdecode))
17168 (setq org-read-date-analyze-forced-year t))))
17169 (setq org-read-date-analyze-futurep futurep)
17170 (list second minute hour day month year)))
17172 (defvar parse-time-weekdays)
17173 (defun org-read-date-get-relative (s today default)
17174 "Check string S for special relative date string.
17175 TODAY and DEFAULT are internal times, for today and for a default.
17176 Return shift list (N what def-flag)
17177 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17178 N is the number of WHATs to shift.
17179 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17180 the DEFAULT date rather than TODAY."
17181 (require 'parse-time)
17182 (when (and
17183 (string-match
17184 (concat
17185 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17186 "\\([0-9]+\\)?"
17187 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17188 "\\([ \t]\\|$\\)") s)
17189 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17190 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17191 (string-to-char (substring (match-string 1 s) -1))
17192 ?+))
17193 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17194 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17195 (what (if (match-end 3) (match-string 3 s) "d"))
17196 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17197 (date (if rel default today))
17198 (wday (nth 6 (decode-time date)))
17199 delta)
17200 (if wday1
17201 (progn
17202 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17203 (when (= delta 0) (setq delta 7))
17204 (when (= dir ?-)
17205 (setq delta (- delta 7))
17206 (when (= delta 0) (setq delta -7)))
17207 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17208 (list delta "d" rel))
17209 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17211 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17212 "Turn a user-specified date into the internal representation.
17213 The internal representation needed by the calendar is (month day year).
17214 This is a wrapper to handle the brain-dead convention in calendar that
17215 user function argument order change dependent on argument order."
17216 (if (boundp 'calendar-date-style)
17217 (cond
17218 ((eq calendar-date-style 'american)
17219 (list arg1 arg2 arg3))
17220 ((eq calendar-date-style 'european)
17221 (list arg2 arg1 arg3))
17222 ((eq calendar-date-style 'iso)
17223 (list arg2 arg3 arg1)))
17224 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17225 (if (org-bound-and-true-p european-calendar-style)
17226 (list arg2 arg1 arg3)
17227 (list arg1 arg2 arg3)))))
17229 (defun org-eval-in-calendar (form &optional keepdate)
17230 "Eval FORM in the calendar window and return to current window.
17231 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17232 otherwise stick to the current value of `org-ans2'."
17233 (let ((sf (selected-frame))
17234 (sw (selected-window)))
17235 (select-window (get-buffer-window "*Calendar*" t))
17236 (eval form)
17237 (when (and (not keepdate) (calendar-cursor-to-date))
17238 (let* ((date (calendar-cursor-to-date))
17239 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17240 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17241 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17242 (select-window sw)
17243 (org-select-frame-set-input-focus sf)))
17245 (defun org-calendar-select ()
17246 "Return to `org-read-date' with the date currently selected.
17247 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17248 (interactive)
17249 (when (calendar-cursor-to-date)
17250 (let* ((date (calendar-cursor-to-date))
17251 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17252 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17253 (when (active-minibuffer-window) (exit-minibuffer))))
17255 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17256 "Insert a date stamp for the date given by the internal TIME.
17257 See `format-time-string' for the format of TIME.
17258 WITH-HM means use the stamp format that includes the time of the day.
17259 INACTIVE means use square brackets instead of angular ones, so that the
17260 stamp will not contribute to the agenda.
17261 PRE and POST are optional strings to be inserted before and after the
17262 stamp.
17263 The command returns the inserted time stamp."
17264 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17265 stamp)
17266 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17267 (insert-before-markers (or pre ""))
17268 (when (listp extra)
17269 (setq extra (car extra))
17270 (if (and (stringp extra)
17271 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17272 (setq extra (format "-%02d:%02d"
17273 (string-to-number (match-string 1 extra))
17274 (string-to-number (match-string 2 extra))))
17275 (setq extra nil)))
17276 (when extra
17277 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17278 (insert-before-markers (setq stamp (format-time-string fmt time)))
17279 (insert-before-markers (or post ""))
17280 (setq org-last-inserted-timestamp stamp)))
17282 (defun org-toggle-time-stamp-overlays ()
17283 "Toggle the use of custom time stamp formats."
17284 (interactive)
17285 (setq org-display-custom-times (not org-display-custom-times))
17286 (unless org-display-custom-times
17287 (let ((p (point-min)) (bmp (buffer-modified-p)))
17288 (while (setq p (next-single-property-change p 'display))
17289 (when (and (get-text-property p 'display)
17290 (eq (get-text-property p 'face) 'org-date))
17291 (remove-text-properties
17292 p (setq p (next-single-property-change p 'display))
17293 '(display t))))
17294 (set-buffer-modified-p bmp)))
17295 (when (featurep 'xemacs)
17296 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17297 (org-restart-font-lock)
17298 (setq org-table-may-need-update t)
17299 (if org-display-custom-times
17300 (message "Time stamps are overlaid with custom format")
17301 (message "Time stamp overlays removed")))
17303 (defun org-display-custom-time (beg end)
17304 "Overlay modified time stamp format over timestamp between BEG and END."
17305 (let* ((ts (buffer-substring beg end))
17306 t1 w1 with-hm tf time str w2 (off 0))
17307 (save-match-data
17308 (setq t1 (org-parse-time-string ts t))
17309 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17310 (setq off (- (match-end 0) (match-beginning 0)))))
17311 (setq end (- end off))
17312 (setq w1 (- end beg)
17313 with-hm (and (nth 1 t1) (nth 2 t1))
17314 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17315 time (org-fix-decoded-time t1)
17316 str (org-add-props
17317 (format-time-string
17318 (substring tf 1 -1) (apply 'encode-time time))
17319 nil 'mouse-face 'highlight)
17320 w2 (length str))
17321 (unless (= w2 w1)
17322 (add-text-properties (1+ beg) (+ 2 beg)
17323 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17324 (if (featurep 'xemacs)
17325 (progn
17326 (put-text-property beg end 'invisible t)
17327 (put-text-property beg end 'end-glyph (make-glyph str)))
17328 (put-text-property beg end 'display str))))
17330 (defun org-fix-decoded-time (time)
17331 "Set 0 instead of nil for the first 6 elements of time.
17332 Don't touch the rest."
17333 (let ((n 0))
17334 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17336 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17338 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17339 "Difference between TIMESTAMP-STRING and now in days.
17340 If SECONDS is non-nil, return the difference in seconds."
17341 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17342 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17343 (funcall fdiff (current-time)))))
17345 (defun org-deadline-close (timestamp-string &optional ndays)
17346 "Is the time in TIMESTAMP-STRING close to the current date?"
17347 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17348 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17349 (not (org-entry-is-done-p))))
17351 (defun org-get-wdays (ts &optional delay zero-delay)
17352 "Get the deadline lead time appropriate for timestring TS.
17353 When DELAY is non-nil, get the delay time for scheduled items
17354 instead of the deadline lead time. When ZERO-DELAY is non-nil
17355 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17356 don't try to find the delay cookie in the scheduled timestamp."
17357 (let ((tv (if delay org-scheduled-delay-days
17358 org-deadline-warning-days)))
17359 (cond
17360 ((or (and delay (< tv 0))
17361 (and delay zero-delay (<= tv 0))
17362 (and (not delay) (<= tv 0)))
17363 ;; Enforce this value no matter what
17364 (- tv))
17365 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17366 ;; lead time is specified.
17367 (floor (* (string-to-number (match-string 1 ts))
17368 (cdr (assoc (match-string 2 ts)
17369 '(("d" . 1) ("w" . 7)
17370 ("m" . 30.4) ("y" . 365.25)
17371 ("h" . 0.041667)))))))
17372 ;; go for the default.
17373 (t tv))))
17375 (defun org-calendar-select-mouse (ev)
17376 "Return to `org-read-date' with the date currently selected.
17377 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17378 (interactive "e")
17379 (mouse-set-point ev)
17380 (when (calendar-cursor-to-date)
17381 (let* ((date (calendar-cursor-to-date))
17382 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17383 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17384 (when (active-minibuffer-window) (exit-minibuffer))))
17386 (defun org-check-deadlines (ndays)
17387 "Check if there are any deadlines due or past due.
17388 A deadline is considered due if it happens within `org-deadline-warning-days'
17389 days from today's date. If the deadline appears in an entry marked DONE,
17390 it is not shown. The prefix arg NDAYS can be used to test that many
17391 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17392 (interactive "P")
17393 (let* ((org-warn-days
17394 (cond
17395 ((equal ndays '(4)) 100000)
17396 (ndays (prefix-numeric-value ndays))
17397 (t (abs org-deadline-warning-days))))
17398 (case-fold-search nil)
17399 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17400 (callback
17401 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17402 (message "%d deadlines past-due or due within %d days"
17403 (org-occur regexp nil callback)
17404 org-warn-days)))
17406 (defsubst org-re-timestamp (type)
17407 "Return a regexp for timestamp TYPE.
17408 Allowed values for TYPE are:
17410 all: all timestamps
17411 active: only active timestamps (<...>)
17412 inactive: only inactive timestamps ([...])
17413 scheduled: only scheduled timestamps
17414 deadline: only deadline timestamps
17415 closed: only closed time-stamps
17417 When TYPE is nil, fall back on returning a regexp that matches
17418 both scheduled and deadline timestamps."
17419 (case type
17420 (all org-ts-regexp-both)
17421 (active org-ts-regexp)
17422 (inactive org-ts-regexp-inactive)
17423 (scheduled org-scheduled-time-regexp)
17424 (deadline org-deadline-time-regexp)
17425 (closed org-closed-time-regexp)
17426 (otherwise
17427 (concat "\\<"
17428 (regexp-opt (list org-deadline-string org-scheduled-string))
17429 " *<\\([^>]+\\)>"))))
17431 (defun org-check-before-date (d)
17432 "Check if there are deadlines or scheduled entries before date D."
17433 (interactive (list (org-read-date)))
17434 (let ((case-fold-search nil)
17435 (regexp (org-re-timestamp org-ts-type))
17436 (callback
17437 `(lambda ()
17438 (let ((match (match-string 1)))
17439 (and ,(if (memq org-ts-type '(active inactive all))
17440 '(eq (org-element-type (org-element-context)) 'timestamp)
17441 '(org-at-planning-p))
17442 (time-less-p
17443 (org-time-string-to-time match)
17444 (org-time-string-to-time d)))))))
17445 (message "%d entries before %s"
17446 (org-occur regexp nil callback)
17447 d)))
17449 (defun org-check-after-date (d)
17450 "Check if there are deadlines or scheduled entries after date D."
17451 (interactive (list (org-read-date)))
17452 (let ((case-fold-search nil)
17453 (regexp (org-re-timestamp org-ts-type))
17454 (callback
17455 `(lambda ()
17456 (let ((match (match-string 1)))
17457 (and ,(if (memq org-ts-type '(active inactive all))
17458 '(eq (org-element-type (org-element-context)) 'timestamp)
17459 '(org-at-planning-p))
17460 (not (time-less-p
17461 (org-time-string-to-time match)
17462 (org-time-string-to-time d))))))))
17463 (message "%d entries after %s"
17464 (org-occur regexp nil callback)
17465 d)))
17467 (defun org-check-dates-range (start-date end-date)
17468 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17469 (interactive (list (org-read-date nil nil nil "Range starts")
17470 (org-read-date nil nil nil "Range end")))
17471 (let ((case-fold-search nil)
17472 (regexp (org-re-timestamp org-ts-type))
17473 (callback
17474 `(lambda ()
17475 (let ((match (match-string 1)))
17476 (and
17477 ,(if (memq org-ts-type '(active inactive all))
17478 '(eq (org-element-type (org-element-context)) 'timestamp)
17479 '(org-at-planning-p))
17480 (not (time-less-p
17481 (org-time-string-to-time match)
17482 (org-time-string-to-time start-date)))
17483 (time-less-p
17484 (org-time-string-to-time match)
17485 (org-time-string-to-time end-date)))))))
17486 (message "%d entries between %s and %s"
17487 (org-occur regexp nil callback) start-date end-date)))
17489 (defun org-evaluate-time-range (&optional to-buffer)
17490 "Evaluate a time range by computing the difference between start and end.
17491 Normally the result is just printed in the echo area, but with prefix arg
17492 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17493 If the time range is actually in a table, the result is inserted into the
17494 next column.
17495 For time difference computation, a year is assumed to be exactly 365
17496 days in order to avoid rounding problems."
17497 (interactive "P")
17499 (org-clock-update-time-maybe)
17500 (save-excursion
17501 (unless (org-at-date-range-p t)
17502 (goto-char (point-at-bol))
17503 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17504 (unless (org-at-date-range-p t)
17505 (user-error "Not at a time-stamp range, and none found in current line")))
17506 (let* ((ts1 (match-string 1))
17507 (ts2 (match-string 2))
17508 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17509 (match-end (match-end 0))
17510 (time1 (org-time-string-to-time ts1))
17511 (time2 (org-time-string-to-time ts2))
17512 (t1 (org-float-time time1))
17513 (t2 (org-float-time time2))
17514 (diff (abs (- t2 t1)))
17515 (negative (< (- t2 t1) 0))
17516 ;; (ys (floor (* 365 24 60 60)))
17517 (ds (* 24 60 60))
17518 (hs (* 60 60))
17519 (fy "%dy %dd %02d:%02d")
17520 (fy1 "%dy %dd")
17521 (fd "%dd %02d:%02d")
17522 (fd1 "%dd")
17523 (fh "%02d:%02d")
17524 y d h m align)
17525 (if havetime
17526 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17528 d (floor (/ diff ds)) diff (mod diff ds)
17529 h (floor (/ diff hs)) diff (mod diff hs)
17530 m (floor (/ diff 60)))
17531 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17533 d (floor (+ (/ diff ds) 0.5))
17534 h 0 m 0))
17535 (if (not to-buffer)
17536 (message "%s" (org-make-tdiff-string y d h m))
17537 (if (org-at-table-p)
17538 (progn
17539 (goto-char match-end)
17540 (setq align t)
17541 (and (looking-at " *|") (goto-char (match-end 0))))
17542 (goto-char match-end))
17543 (when (looking-at
17544 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17545 (replace-match ""))
17546 (when negative (insert " -"))
17547 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17548 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17549 (insert " " (format fh h m))))
17550 (when align (org-table-align))
17551 (message "Time difference inserted")))))
17553 (defun org-make-tdiff-string (y d h m)
17554 (let ((fmt "")
17555 (l nil))
17556 (when (> y 0)
17557 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17558 (push y l))
17559 (when (> d 0)
17560 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17561 (push d l))
17562 (when (> h 0)
17563 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17564 (push h l))
17565 (when (> m 0)
17566 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17567 (push m l))
17568 (apply 'format fmt (nreverse l))))
17570 (defun org-time-string-to-time (s &optional buffer pos)
17571 "Convert a timestamp string into internal time."
17572 (condition-case errdata
17573 (apply 'encode-time (org-parse-time-string s))
17574 (error (error "Bad timestamp `%s'%s\nError was: %s"
17575 s (if (not (and buffer pos))
17577 (format-message " at %d in buffer `%s'" pos buffer))
17578 (cdr errdata)))))
17580 (defun org-time-string-to-seconds (s)
17581 "Convert a timestamp string to a number of seconds."
17582 (org-float-time (org-time-string-to-time s)))
17584 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17586 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17587 "Convert time stamp S to an absolute day number.
17589 If DAYNR in non-nil, and there is a specifier for a cyclic time
17590 stamp, get the closest date to DAYNR. If PREFER is
17591 `past' (respectively `future') return a date past (respectively
17592 after) or equal to DAYNR.
17594 POS is the location of time stamp S, as a buffer position in
17595 BUFFER.
17597 Diary sexp timestamps are matched against DAYNR, when non-nil.
17598 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17599 signalled."
17600 (cond
17601 ((string-match "\\`%%\\((.*)\\)" s)
17602 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17603 ;; only able to match individual dates. If it fails, raise an
17604 ;; error.
17605 (if (and daynr
17606 (org-diary-sexp-entry
17607 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17608 daynr
17609 (signal 'org-diary-sexp-no-match (list s))))
17610 ((and daynr show-all) (org-closest-date s daynr prefer))
17611 (t (time-to-days
17612 (condition-case errdata
17613 (apply #'encode-time (org-parse-time-string s))
17614 (error (error "Bad timestamp `%s'%s\nError was: %s"
17616 (if (not (and buffer pos)) ""
17617 (format-message " at %d in buffer `%s'" pos buffer))
17618 (cdr errdata))))))))
17620 (defun org-days-to-iso-week (days)
17621 "Return the iso week number."
17622 (require 'cal-iso)
17623 (car (calendar-iso-from-absolute days)))
17625 (defun org-small-year-to-year (year)
17626 "Convert 2-digit years into 4-digit years.
17627 YEAR is expanded into one of the 30 next years, if possible, or
17628 into a past one. Any year larger than 99 is returned unchanged."
17629 (if (>= year 100) year
17630 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17631 (century (/ current 100))
17632 (offset (- year (% current 100))))
17633 (cond ((> offset 30) (+ (* (1- century) 100) year))
17634 ((> offset -70) (+ (* century 100) year))
17635 (t (+ (* (1+ century) 100) year))))))
17637 (defun org-time-from-absolute (d)
17638 "Return the time corresponding to date D.
17639 D may be an absolute day number, or a calendar-type list (month day year)."
17640 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17641 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17643 (defun org-calendar-holiday ()
17644 "List of holidays, for Diary display in Org-mode."
17645 (declare (special date))
17646 (require 'holidays)
17647 (let ((hl (funcall
17648 (if (fboundp 'calendar-check-holidays)
17649 'calendar-check-holidays 'check-calendar-holidays) date)))
17650 (when hl (mapconcat 'identity hl "; "))))
17652 (defun org-diary-sexp-entry (sexp entry d)
17653 "Process a SEXP diary ENTRY for date D."
17654 (require 'diary-lib)
17655 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17656 ;; dynamically.
17657 (let* ((sexp `(let ((entry ,entry)
17658 (date ',d))
17659 ,(car (read-from-string sexp))))
17660 (result (if calendar-debug-sexp (eval sexp)
17661 (condition-case nil
17662 (eval sexp)
17663 (error
17664 (beep)
17665 (message "Bad sexp at line %d in %s: %s"
17666 (org-current-line)
17667 (buffer-file-name) sexp)
17668 (sleep-for 2))))))
17669 (cond ((stringp result) (split-string result "; "))
17670 ((and (consp result)
17671 (not (consp (cdr result)))
17672 (stringp (cdr result))) (cdr result))
17673 ((and (consp result)
17674 (stringp (car result))) result)
17675 (result entry))))
17677 (defun org-diary-to-ical-string (frombuf)
17678 "Get iCalendar entries from diary entries in buffer FROMBUF.
17679 This uses the icalendar.el library."
17680 (let* ((tmpdir (if (featurep 'xemacs)
17681 (temp-directory)
17682 temporary-file-directory))
17683 (tmpfile (make-temp-name
17684 (expand-file-name "orgics" tmpdir)))
17685 buf rtn b e)
17686 (with-current-buffer frombuf
17687 (icalendar-export-region (point-min) (point-max) tmpfile)
17688 (setq buf (find-buffer-visiting tmpfile))
17689 (set-buffer buf)
17690 (goto-char (point-min))
17691 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17692 (setq b (match-beginning 0)))
17693 (goto-char (point-max))
17694 (when (re-search-backward "^END:VEVENT" nil t)
17695 (setq e (match-end 0)))
17696 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17697 (kill-buffer buf)
17698 (delete-file tmpfile)
17699 rtn))
17701 (defun org-closest-date (start current prefer)
17702 "Return closest date to CURRENT starting from START.
17704 CURRENT and START are both time stamps.
17706 When PREFER is `past', return a date that is either CURRENT or
17707 past. When PREFER is `future', return a date that is either
17708 CURRENT or future.
17710 Only time stamps with a repeater are modified. Any other time
17711 stamp stay unchanged. In any case, return value is an absolute
17712 day number."
17713 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17714 ;; No repeater. Do not shift time stamp.
17715 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17716 (let ((value (string-to-number (match-string 1 start)))
17717 (type (match-string 2 start)))
17718 (if (= 0 value)
17719 ;; Repeater with a 0-value is considered as void.
17720 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17721 (let* ((base (org-date-to-gregorian start))
17722 (target (org-date-to-gregorian current))
17723 (sday (calendar-absolute-from-gregorian base))
17724 (cday (calendar-absolute-from-gregorian target))
17725 n1 n2)
17726 ;; If START is already past CURRENT, just return START.
17727 (if (<= cday sday) sday
17728 ;; Compute closest date before (N1) and closest date past
17729 ;; (N2) CURRENT.
17730 (pcase type
17731 ("h"
17732 (let ((missing-hours
17733 (mod (+ (- (* 24 (- cday sday))
17734 (nth 2 (org-parse-time-string start)))
17735 org-extend-today-until)
17736 value)))
17737 (setf n1 (if (= missing-hours 0) cday
17738 (- cday (1+ (/ missing-hours 24)))))
17739 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17740 ((or "d" "w")
17741 (let ((value (if (equal type "w") (* 7 value) value)))
17742 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17743 (setf n2 (+ n1 value))))
17744 ("m"
17745 (let* ((add-months
17746 (lambda (d n)
17747 ;; Add N months to gregorian date D, i.e.,
17748 ;; a list (MONTH DAY YEAR). Return a valid
17749 ;; gregorian date.
17750 (let ((m (+ (nth 0 d) n)))
17751 (list (mod m 12)
17752 (nth 1 d)
17753 (+ (/ m 12) (nth 2 d))))))
17754 (months ; Complete months to TARGET.
17755 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17756 (- (nth 0 target) (nth 0 base))
17757 ;; If START's day is greater than
17758 ;; TARGET's, remove incomplete month.
17759 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17760 value)
17761 value))
17762 (before (funcall add-months base months)))
17763 (setf n1 (calendar-absolute-from-gregorian before))
17764 (setf n2
17765 (calendar-absolute-from-gregorian
17766 (funcall add-months before value)))))
17768 (let* ((d (nth 1 base))
17769 (m (nth 0 base))
17770 (y (nth 2 base))
17771 (years ; Complete years to TARGET.
17772 (* (/ (- (nth 2 target)
17774 ;; If START's month and day are
17775 ;; greater than TARGET's, remove
17776 ;; incomplete year.
17777 (if (or (> (nth 0 target) m)
17778 (and (= (nth 0 target) m)
17779 (> (nth 1 target) d)))
17782 value)
17783 value))
17784 (before (list m d (+ y years))))
17785 (setf n1 (calendar-absolute-from-gregorian before))
17786 (setf n2 (calendar-absolute-from-gregorian
17787 (list m d (+ (nth 2 before) value)))))))
17788 ;; Handle PREFER parameter, if any.
17789 (cond
17790 ((eq prefer 'past) (if (= cday n2) n2 n1))
17791 ((eq prefer 'future) (if (= cday n1) n1 n2))
17792 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17794 (defun org-date-to-gregorian (d)
17795 "Turn any specification of date D into a Gregorian date for the calendar."
17796 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17797 ((and (listp d) (= (length d) 3)) d)
17798 ((stringp d)
17799 (let ((d (org-parse-time-string d)))
17800 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17801 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17803 (defun org-parse-time-string (s &optional nodefault)
17804 "Parse the standard Org-mode time string.
17805 This should be a lot faster than the normal `parse-time-string'.
17806 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17807 hour and minute fields will be nil if not given."
17808 (cond ((string-match org-ts-regexp0 s)
17809 (list 0
17810 (when (or (match-beginning 8) (not nodefault))
17811 (string-to-number (or (match-string 8 s) "0")))
17812 (when (or (match-beginning 7) (not nodefault))
17813 (string-to-number (or (match-string 7 s) "0")))
17814 (string-to-number (match-string 4 s))
17815 (string-to-number (match-string 3 s))
17816 (string-to-number (match-string 2 s))
17817 nil nil nil))
17818 ((string-match "^<[^>]+>$" s)
17819 (decode-time (seconds-to-time (org-matcher-time s))))
17820 (t (error "Not a standard Org-mode time string: %s" s))))
17822 (defun org-timestamp-up (&optional arg)
17823 "Increase the date item at the cursor by one.
17824 If the cursor is on the year, change the year. If it is on the month,
17825 the day or the time, change that.
17826 With prefix ARG, change by that many units."
17827 (interactive "p")
17828 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17830 (defun org-timestamp-down (&optional arg)
17831 "Decrease the date item at the cursor by one.
17832 If the cursor is on the year, change the year. If it is on the month,
17833 the day or the time, change that.
17834 With prefix ARG, change by that many units."
17835 (interactive "p")
17836 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17838 (defun org-timestamp-up-day (&optional arg)
17839 "Increase the date in the time stamp by one day.
17840 With prefix ARG, change that many days."
17841 (interactive "p")
17842 (if (and (not (org-at-timestamp-p t))
17843 (org-at-heading-p))
17844 (org-todo 'up)
17845 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17847 (defun org-timestamp-down-day (&optional arg)
17848 "Decrease the date in the time stamp by one day.
17849 With prefix ARG, change that many days."
17850 (interactive "p")
17851 (if (and (not (org-at-timestamp-p t))
17852 (org-at-heading-p))
17853 (org-todo 'down)
17854 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17856 (defun org-at-timestamp-p (&optional inactive-ok)
17857 "Non-nil if point is inside a timestamp.
17859 When optional argument INACTIVE-OK is non-nil, also consider
17860 inactive timestamps.
17862 When this function returns a non-nil value, match data is set
17863 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17864 INACTIVE-OK."
17865 (interactive)
17866 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17867 (pos (point))
17868 (ans (or (looking-at tsr)
17869 (save-excursion
17870 (skip-chars-backward "^[<\n\r\t")
17871 (when (> (point) (point-min)) (backward-char 1))
17872 (and (looking-at tsr)
17873 (> (- (match-end 0) pos) -1))))))
17874 (and ans
17875 (boundp 'org-ts-what)
17876 (setq org-ts-what
17877 (cond
17878 ((= pos (match-beginning 0)) 'bracket)
17879 ;; Point is considered to be "on the bracket" whether
17880 ;; it's really on it or right after it.
17881 ((= pos (1- (match-end 0))) 'bracket)
17882 ((= pos (match-end 0)) 'after)
17883 ((org-pos-in-match-range pos 2) 'year)
17884 ((org-pos-in-match-range pos 3) 'month)
17885 ((org-pos-in-match-range pos 7) 'hour)
17886 ((org-pos-in-match-range pos 8) 'minute)
17887 ((or (org-pos-in-match-range pos 4)
17888 (org-pos-in-match-range pos 5)) 'day)
17889 ((and (> pos (or (match-end 8) (match-end 5)))
17890 (< pos (match-end 0)))
17891 (- pos (or (match-end 8) (match-end 5))))
17892 (t 'day))))
17893 ans))
17895 (defun org-toggle-timestamp-type ()
17896 "Toggle the type (<active> or [inactive]) of a time stamp."
17897 (interactive)
17898 (when (org-at-timestamp-p t)
17899 (let ((beg (match-beginning 0)) (end (match-end 0))
17900 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17901 (save-excursion
17902 (goto-char beg)
17903 (while (re-search-forward "[][<>]" end t)
17904 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17905 t t)))
17906 (message "Timestamp is now %sactive"
17907 (if (equal (char-after beg) ?<) "" "in")))))
17909 (defun org-at-clock-log-p nil
17910 "Is the cursor on the clock log line?"
17911 (save-excursion
17912 (move-beginning-of-line 1)
17913 (looking-at org-clock-line-re)))
17915 (defvar org-clock-history) ; defined in org-clock.el
17916 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17917 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17918 "Change the date in the time stamp at point.
17919 The date will be changed by N times WHAT. WHAT can be `day', `month',
17920 `year', `minute', `second'. If WHAT is not given, the cursor position
17921 in the timestamp determines what will be changed.
17922 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17923 (let ((origin (point)) origin-cat
17924 with-hm inactive
17925 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17926 org-ts-what
17927 extra rem
17928 ts time time0 fixnext clrgx)
17929 (unless (org-at-timestamp-p t)
17930 (user-error "Not at a timestamp"))
17931 (if (and (not what) (eq org-ts-what 'bracket))
17932 (org-toggle-timestamp-type)
17933 ;; Point isn't on brackets. Remember the part of the time-stamp
17934 ;; the point was in. Indeed, size of time-stamps may change,
17935 ;; but point must be kept in the same category nonetheless.
17936 (setq origin-cat org-ts-what)
17937 (when (and (not what) (not (eq org-ts-what 'day))
17938 org-display-custom-times
17939 (get-text-property (point) 'display)
17940 (not (get-text-property (1- (point)) 'display)))
17941 (setq org-ts-what 'day))
17942 (setq org-ts-what (or what org-ts-what)
17943 inactive (= (char-after (match-beginning 0)) ?\[)
17944 ts (match-string 0))
17945 (replace-match "")
17946 (when (string-match
17947 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17949 (setq extra (match-string 1 ts))
17950 (when suppress-tmp-delay
17951 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17952 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17953 (setq with-hm t))
17954 (setq time0 (org-parse-time-string ts))
17955 (when (and updown
17956 (eq org-ts-what 'minute)
17957 (not current-prefix-arg))
17958 ;; This looks like s-up and s-down. Change by one rounding step.
17959 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17960 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17961 (setcar (cdr time0) (+ (nth 1 time0)
17962 (if (> n 0) (- rem) (- dm rem))))))
17963 (setq time
17964 (encode-time (or (car time0) 0)
17965 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17966 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17967 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17968 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17969 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17970 (nthcdr 6 time0)))
17971 (when (and (member org-ts-what '(hour minute))
17972 extra
17973 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17974 (setq extra (org-modify-ts-extra
17975 extra
17976 (if (eq org-ts-what 'hour) 2 5)
17977 n dm)))
17978 (when (integerp org-ts-what)
17979 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17980 (when (eq what 'calendar)
17981 (let ((cal-date (org-get-date-from-calendar)))
17982 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17983 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17984 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17985 (setcar time0 (or (car time0) 0))
17986 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17987 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17988 (setq time (apply 'encode-time time0))))
17989 ;; Insert the new time-stamp, and ensure point stays in the same
17990 ;; category as before (i.e. not after the last position in that
17991 ;; category).
17992 (let ((pos (point)))
17993 ;; Stay before inserted string. `save-excursion' is of no use.
17994 (setq org-last-changed-timestamp
17995 (org-insert-time-stamp time with-hm inactive nil nil extra))
17996 (goto-char pos))
17997 (save-match-data
17998 (looking-at org-ts-regexp3)
17999 (goto-char (cond
18000 ;; `day' category ends before `hour' if any, or at
18001 ;; the end of the day name.
18002 ((eq origin-cat 'day)
18003 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18004 ((eq origin-cat 'hour) (min (match-end 7) origin))
18005 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18006 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18007 ;; `year' and `month' have both fixed size: point
18008 ;; couldn't have moved into another part.
18009 (t origin))))
18010 ;; Update clock if on a CLOCK line.
18011 (org-clock-update-time-maybe)
18012 ;; Maybe adjust the closest clock in `org-clock-history'
18013 (when org-clock-adjust-closest
18014 (if (not (and (org-at-clock-log-p)
18015 (< 1 (length (delq nil (mapcar 'marker-position
18016 org-clock-history))))))
18017 (message "No clock to adjust")
18018 (cond ((save-excursion ; fix previous clock?
18019 (re-search-backward org-ts-regexp0 nil t)
18020 (org-looking-back (concat org-clock-string " \\[")
18021 (line-beginning-position)))
18022 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18023 ((save-excursion ; fix next clock?
18024 (re-search-backward org-ts-regexp0 nil t)
18025 (looking-at (concat org-ts-regexp0 "\\] =>")))
18026 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18027 (save-window-excursion
18028 ;; Find closest clock to point, adjust the previous/next one in history
18029 (let* ((p (save-excursion (org-back-to-heading t)))
18030 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18031 (clfixnth
18032 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18033 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18034 (if (not clfixpos)
18035 (message "No clock to adjust")
18036 (save-excursion
18037 (org-goto-marker-or-bmk clfixpos)
18038 (org-show-subtree)
18039 (when (re-search-forward clrgx nil t)
18040 (goto-char (match-beginning 1))
18041 (let (org-clock-adjust-closest)
18042 (org-timestamp-change n org-ts-what updown))
18043 (message "Clock adjusted in %s for heading: %s"
18044 (file-name-nondirectory (buffer-file-name))
18045 (org-get-heading t t)))))))))
18046 ;; Try to recenter the calendar window, if any.
18047 (when (and org-calendar-follow-timestamp-change
18048 (get-buffer-window "*Calendar*" t)
18049 (memq org-ts-what '(day month year)))
18050 (org-recenter-calendar (time-to-days time))))))
18052 (defun org-modify-ts-extra (s pos n dm)
18053 "Change the different parts of the lead-time and repeat fields in timestamp."
18054 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18055 ng h m new rem)
18056 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18057 (cond
18058 ((or (org-pos-in-match-range pos 2)
18059 (org-pos-in-match-range pos 3))
18060 (setq m (string-to-number (match-string 3 s))
18061 h (string-to-number (match-string 2 s)))
18062 (if (org-pos-in-match-range pos 2)
18063 (setq h (+ h n))
18064 (setq n (* dm (org-no-warnings (signum n))))
18065 (unless (= 0 (setq rem (% m dm)))
18066 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18067 (setq m (+ m n)))
18068 (when (< m 0) (setq m (+ m 60) h (1- h)))
18069 (when (> m 59) (setq m (- m 60) h (1+ h)))
18070 (setq h (mod h 24))
18071 (setq ng 1 new (format "-%02d:%02d" h m)))
18072 ((org-pos-in-match-range pos 6)
18073 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18074 ((org-pos-in-match-range pos 5)
18075 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18077 ((org-pos-in-match-range pos 9)
18078 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18079 ((org-pos-in-match-range pos 8)
18080 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18082 (when ng
18083 (setq s (concat
18084 (substring s 0 (match-beginning ng))
18086 (substring s (match-end ng))))))
18089 (defun org-recenter-calendar (d)
18090 "If the calendar is visible, recenter it to date D."
18091 (let ((cwin (get-buffer-window "*Calendar*" t)))
18092 (when cwin
18093 (let ((calendar-move-hook nil))
18094 (with-selected-window cwin
18095 (calendar-goto-date
18096 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18098 (defun org-goto-calendar (&optional arg)
18099 "Go to the Emacs calendar at the current date.
18100 If there is a time stamp in the current line, go to that date.
18101 A prefix ARG can be used to force the current date."
18102 (interactive "P")
18103 (let ((tsr org-ts-regexp) diff
18104 (calendar-move-hook nil)
18105 (calendar-view-holidays-initially-flag nil)
18106 (calendar-view-diary-initially-flag nil))
18107 (when (or (org-at-timestamp-p)
18108 (save-excursion
18109 (beginning-of-line 1)
18110 (looking-at (concat ".*" tsr))))
18111 (let ((d1 (time-to-days (current-time)))
18112 (d2 (time-to-days
18113 (org-time-string-to-time (match-string 1)))))
18114 (setq diff (- d2 d1))))
18115 (calendar)
18116 (calendar-goto-today)
18117 (when (and diff (not arg)) (calendar-forward-day diff))))
18119 (defun org-get-date-from-calendar ()
18120 "Return a list (month day year) of date at point in calendar."
18121 (with-current-buffer "*Calendar*"
18122 (save-match-data
18123 (calendar-cursor-to-date))))
18125 (defun org-date-from-calendar ()
18126 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18127 If there is already a time stamp at the cursor position, update it."
18128 (interactive)
18129 (if (org-at-timestamp-p t)
18130 (org-timestamp-change 0 'calendar)
18131 (let ((cal-date (org-get-date-from-calendar)))
18132 (org-insert-time-stamp
18133 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18135 (defcustom org-effort-durations
18136 `(("min" . 1)
18137 ("h" . 60)
18138 ("d" . ,(* 60 8))
18139 ("w" . ,(* 60 8 5))
18140 ("m" . ,(* 60 8 5 4))
18141 ("y" . ,(* 60 8 5 40)))
18142 "Conversion factor to minutes for an effort modifier.
18144 Each entry has the form (MODIFIER . MINUTES).
18146 In an effort string, a number followed by MODIFIER is multiplied
18147 by the specified number of MINUTES to obtain an effort in
18148 minutes.
18150 For example, if the value of this variable is ((\"hours\" . 60)), then an
18151 effort string \"2hours\" is equivalent to 120 minutes."
18152 :group 'org-agenda
18153 :version "25.1"
18154 :package-version '(Org . "8.3")
18155 :type '(alist :key-type (string :tag "Modifier")
18156 :value-type (number :tag "Minutes")))
18158 (defun org-minutes-to-clocksum-string (m)
18159 "Format number of minutes as a clocksum string.
18160 The format is determined by `org-time-clocksum-format',
18161 `org-time-clocksum-use-fractional' and
18162 `org-time-clocksum-fractional-format' and
18163 `org-time-clocksum-use-effort-durations'."
18164 (let ((clocksum "")
18165 (m (round m)) ; Don't allow fractions of minutes
18166 h d w mo y fmt n)
18167 (setq h (if org-time-clocksum-use-effort-durations
18168 (cdr (assoc "h" org-effort-durations)) 60)
18169 d (if org-time-clocksum-use-effort-durations
18170 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18171 w (if org-time-clocksum-use-effort-durations
18172 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18173 mo (if org-time-clocksum-use-effort-durations
18174 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18175 y (if org-time-clocksum-use-effort-durations
18176 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18177 ;; fractional format
18178 (if org-time-clocksum-use-fractional
18179 (cond
18180 ;; single format string
18181 ((stringp org-time-clocksum-fractional-format)
18182 (format org-time-clocksum-fractional-format (/ m (float h))))
18183 ;; choice of fractional formats for different time units
18184 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18185 (> (/ (truncate m) (* y d h)) 0))
18186 (format fmt (/ m (* y d (float h)))))
18187 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18188 (> (/ (truncate m) (* mo d h)) 0))
18189 (format fmt (/ m (* mo d (float h)))))
18190 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18191 (> (/ (truncate m) (* w d h)) 0))
18192 (format fmt (/ m (* w d (float h)))))
18193 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18194 (> (/ (truncate m) (* d h)) 0))
18195 (format fmt (/ m (* d (float h)))))
18196 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18197 (> (/ (truncate m) h) 0))
18198 (format fmt (/ m (float h))))
18199 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18200 (format fmt m))
18201 ;; fall back to smallest time unit with a format
18202 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18203 (format fmt (/ m (float h))))
18204 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18205 (format fmt (/ m (* d (float h)))))
18206 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18207 (format fmt (/ m (* w d (float h)))))
18208 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18209 (format fmt (/ m (* mo d (float h)))))
18210 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18211 (format fmt (/ m (* y d (float h))))))
18212 ;; standard (non-fractional) format, with single format string
18213 (if (stringp org-time-clocksum-format)
18214 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18215 ;; separate formats components
18216 (and (setq fmt (plist-get org-time-clocksum-format :years))
18217 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18218 (plist-get org-time-clocksum-format :require-years))
18219 (setq clocksum (concat clocksum (format fmt n))
18220 m (- m (* n y d h))))
18221 (and (setq fmt (plist-get org-time-clocksum-format :months))
18222 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18223 (plist-get org-time-clocksum-format :require-months))
18224 (setq clocksum (concat clocksum (format fmt n))
18225 m (- m (* n mo d h))))
18226 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18227 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18228 (plist-get org-time-clocksum-format :require-weeks))
18229 (setq clocksum (concat clocksum (format fmt n))
18230 m (- m (* n w d h))))
18231 (and (setq fmt (plist-get org-time-clocksum-format :days))
18232 (or (> (setq n (/ (truncate m) (* d h))) 0)
18233 (plist-get org-time-clocksum-format :require-days))
18234 (setq clocksum (concat clocksum (format fmt n))
18235 m (- m (* n d h))))
18236 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18237 (or (> (setq n (/ (truncate m) h)) 0)
18238 (plist-get org-time-clocksum-format :require-hours))
18239 (setq clocksum (concat clocksum (format fmt n))
18240 m (- m (* n h))))
18241 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18242 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18243 (setq clocksum (concat clocksum (format fmt m))))
18244 ;; return formatted time duration
18245 clocksum))))
18247 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18248 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18249 "Org mode version 8.0")
18251 (defun org-hours-to-clocksum-string (n)
18252 (org-minutes-to-clocksum-string (* n 60)))
18254 (defun org-hh:mm-string-to-minutes (s)
18255 "Convert a string H:MM to a number of minutes.
18256 If the string is just a number, interpret it as minutes.
18257 In fact, the first hh:mm or number in the string will be taken,
18258 there can be extra stuff in the string.
18259 If no number is found, the return value is 0."
18260 (cond
18261 ((integerp s) s)
18262 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18263 (+ (* (string-to-number (match-string 1 s)) 60)
18264 (string-to-number (match-string 2 s))))
18265 ((string-match "\\([0-9]+\\)" s)
18266 (string-to-number (match-string 1 s)))
18267 (t 0)))
18269 (defcustom org-image-actual-width t
18270 "Should we use the actual width of images when inlining them?
18272 When set to t, always use the image width.
18274 When set to a number, use imagemagick (when available) to set
18275 the image's width to this value.
18277 When set to a number in a list, try to get the width from any
18278 #+ATTR.* keyword if it matches a width specification like
18280 #+ATTR_HTML: :width 300px
18282 and fall back on that number if none is found.
18284 When set to nil, try to get the width from an #+ATTR.* keyword
18285 and fall back on the original width if none is found.
18287 This requires Emacs >= 24.1, build with imagemagick support."
18288 :group 'org-appearance
18289 :version "24.4"
18290 :package-version '(Org . "8.0")
18291 :type '(choice
18292 (const :tag "Use the image width" t)
18293 (integer :tag "Use a number of pixels")
18294 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18295 (const :tag "Use #+ATTR* or don't resize" nil)))
18297 (defcustom org-agenda-inhibit-startup nil
18298 "Inhibit startup when preparing agenda buffers.
18299 When this variable is t, the initialization of the Org agenda
18300 buffers is inhibited: e.g. the visibility state is not set, the
18301 tables are not re-aligned, etc."
18302 :type 'boolean
18303 :version "24.3"
18304 :group 'org-agenda)
18306 (define-obsolete-variable-alias
18307 'org-agenda-ignore-drawer-properties
18308 'org-agenda-ignore-properties "25.1")
18310 (defcustom org-agenda-ignore-properties nil
18311 "Avoid updating text properties when building the agenda.
18312 Properties are used to prepare buffers for effort estimates,
18313 appointments, statistics and subtree-local categories.
18314 If you don't use these in the agenda, you can add them to this
18315 list and agenda building will be a bit faster.
18316 The value is a list, with zero or more of the symbols `effort', `appt',
18317 `stats' or `category'."
18318 :type '(set :greedy t
18319 (const effort)
18320 (const appt)
18321 (const stats)
18322 (const category))
18323 :version "25.1"
18324 :package-version '(Org . "8.3")
18325 :group 'org-agenda)
18327 (defun org-duration-string-to-minutes (s &optional output-to-string)
18328 "Convert a duration string S to minutes.
18330 A bare number is interpreted as minutes, modifiers can be set by
18331 customizing `org-effort-durations' (which see).
18333 Entries containing a colon are interpreted as H:MM by
18334 `org-hh:mm-string-to-minutes'."
18335 (let ((result 0)
18336 (re (concat "\\([0-9.]+\\) *\\("
18337 (regexp-opt (mapcar 'car org-effort-durations))
18338 "\\)")))
18339 (while (string-match re s)
18340 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18341 (string-to-number (match-string 1 s))))
18342 (setq s (replace-match "" nil t s)))
18343 (setq result (floor result))
18344 (incf result (org-hh:mm-string-to-minutes s))
18345 (if output-to-string (number-to-string result) result)))
18347 ;;;; Files
18349 (defun org-save-all-org-buffers ()
18350 "Save all Org-mode buffers without user confirmation."
18351 (interactive)
18352 (message "Saving all Org-mode buffers...")
18353 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18354 (when (featurep 'org-id) (org-id-locations-save))
18355 (message "Saving all Org-mode buffers... done"))
18357 (defun org-revert-all-org-buffers ()
18358 "Revert all Org-mode buffers.
18359 Prompt for confirmation when there are unsaved changes.
18360 Be sure you know what you are doing before letting this function
18361 overwrite your changes.
18363 This function is useful in a setup where one tracks org files
18364 with a version control system, to revert on one machine after pulling
18365 changes from another. I believe the procedure must be like this:
18367 1. M-x org-save-all-org-buffers
18368 2. Pull changes from the other machine, resolve conflicts
18369 3. M-x org-revert-all-org-buffers"
18370 (interactive)
18371 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18372 (user-error "Abort"))
18373 (save-excursion
18374 (save-window-excursion
18375 (dolist (b (buffer-list))
18376 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18377 (with-current-buffer b buffer-file-name))
18378 (org-pop-to-buffer-same-window b)
18379 (revert-buffer t 'no-confirm)))
18380 (when (and (featurep 'org-id) org-id-track-globally)
18381 (org-id-locations-load)))))
18383 ;;;; Agenda files
18385 ;;;###autoload
18386 (defun org-switchb (&optional arg)
18387 "Switch between Org buffers.
18388 With one prefix argument, restrict available buffers to files.
18389 With two prefix arguments, restrict available buffers to agenda files.
18391 Defaults to `iswitchb' for buffer name completion.
18392 Set `org-completion-use-ido' to make it use ido instead."
18393 (interactive "P")
18394 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18395 ((equal arg '(16)) (org-buffer-list 'agenda))
18396 (t (org-buffer-list))))
18397 (org-completion-use-iswitchb org-completion-use-iswitchb)
18398 (org-completion-use-ido org-completion-use-ido))
18399 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18400 (setq org-completion-use-iswitchb t))
18401 (org-pop-to-buffer-same-window
18402 (completing-read "Org buffer: "
18403 (mapcar #'list (mapcar #'buffer-name blist))
18404 nil t))))
18406 ;;; Define some older names previously used for this functionality
18407 ;;;###autoload
18408 (defalias 'org-ido-switchb 'org-switchb)
18409 ;;;###autoload
18410 (defalias 'org-iswitchb 'org-switchb)
18412 (defun org-buffer-list (&optional predicate exclude-tmp)
18413 "Return a list of Org buffers.
18414 PREDICATE can be `export', `files' or `agenda'.
18416 export restrict the list to Export buffers.
18417 files restrict the list to buffers visiting Org files.
18418 agenda restrict the list to buffers visiting agenda files.
18420 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18421 (let* ((bfn nil)
18422 (agenda-files (and (eq predicate 'agenda)
18423 (mapcar 'file-truename (org-agenda-files t))))
18424 (filter
18425 (cond
18426 ((eq predicate 'files)
18427 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18428 ((eq predicate 'export)
18429 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18430 ((eq predicate 'agenda)
18431 (lambda (b)
18432 (with-current-buffer b
18433 (and (derived-mode-p 'org-mode)
18434 (setq bfn (buffer-file-name b))
18435 (member (file-truename bfn) agenda-files)))))
18436 (t (lambda (b) (with-current-buffer b
18437 (or (derived-mode-p 'org-mode)
18438 (string-match "\\*Org .*Export"
18439 (buffer-name b)))))))))
18440 (delq nil
18441 (mapcar
18442 (lambda(b)
18443 (if (and (funcall filter b)
18444 (or (not exclude-tmp)
18445 (not (string-match "tmp" (buffer-name b)))))
18447 nil))
18448 (buffer-list)))))
18450 (defun org-agenda-files (&optional unrestricted archives)
18451 "Get the list of agenda files.
18452 Optional UNRESTRICTED means return the full list even if a restriction
18453 is currently in place.
18454 When ARCHIVES is t, include all archive files that are really being
18455 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18456 `org-agenda-archives-mode' is t."
18457 (let ((files
18458 (cond
18459 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18460 ((stringp org-agenda-files) (org-read-agenda-file-list))
18461 ((listp org-agenda-files) org-agenda-files)
18462 (t (error "Invalid value of `org-agenda-files'")))))
18463 (setq files (apply 'append
18464 (mapcar (lambda (f)
18465 (if (file-directory-p f)
18466 (directory-files
18467 f t org-agenda-file-regexp)
18468 (list f)))
18469 files)))
18470 (when org-agenda-skip-unavailable-files
18471 (setq files (delq nil
18472 (mapcar (function
18473 (lambda (file)
18474 (and (file-readable-p file) file)))
18475 files))))
18476 (when (or (eq archives t)
18477 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18478 (setq files (org-add-archive-files files)))
18479 files))
18481 (defun org-agenda-file-p (&optional file)
18482 "Return non-nil, if FILE is an agenda file.
18483 If FILE is omitted, use the file associated with the current
18484 buffer."
18485 (let ((fname (or file (buffer-file-name))))
18486 (and fname
18487 (member (file-truename fname)
18488 (mapcar #'file-truename (org-agenda-files t))))))
18490 (defun org-edit-agenda-file-list ()
18491 "Edit the list of agenda files.
18492 Depending on setup, this either uses customize to edit the variable
18493 `org-agenda-files', or it visits the file that is holding the list. In the
18494 latter case, the buffer is set up in a way that saving it automatically kills
18495 the buffer and restores the previous window configuration."
18496 (interactive)
18497 (if (stringp org-agenda-files)
18498 (let ((cw (current-window-configuration)))
18499 (find-file org-agenda-files)
18500 (setq-local org-window-configuration cw)
18501 (org-add-hook 'after-save-hook
18502 (lambda ()
18503 (set-window-configuration
18504 (prog1 org-window-configuration
18505 (kill-buffer (current-buffer))))
18506 (org-install-agenda-files-menu)
18507 (message "New agenda file list installed"))
18508 nil 'local)
18509 (message "%s" (substitute-command-keys
18510 "Edit list and finish with \\[save-buffer]")))
18511 (customize-variable 'org-agenda-files)))
18513 (defun org-store-new-agenda-file-list (list)
18514 "Set new value for the agenda file list and save it correctly."
18515 (if (stringp org-agenda-files)
18516 (let ((fe (org-read-agenda-file-list t)) b u)
18517 (while (setq b (find-buffer-visiting org-agenda-files))
18518 (kill-buffer b))
18519 (with-temp-file org-agenda-files
18520 (insert
18521 (mapconcat
18522 (lambda (f) ;; Keep un-expanded entries.
18523 (if (setq u (assoc f fe))
18524 (cdr u)
18526 list "\n")
18527 "\n")))
18528 (let ((org-mode-hook nil) (org-inhibit-startup t)
18529 (org-insert-mode-line-in-empty-file nil))
18530 (setq org-agenda-files list)
18531 (customize-save-variable 'org-agenda-files org-agenda-files))))
18533 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18534 "Read the list of agenda files from a file.
18535 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18536 filenames, used by `org-store-new-agenda-file-list' to write back
18537 un-expanded file names."
18538 (when (file-directory-p org-agenda-files)
18539 (error "`org-agenda-files' cannot be a single directory"))
18540 (when (stringp org-agenda-files)
18541 (with-temp-buffer
18542 (insert-file-contents org-agenda-files)
18543 (mapcar
18544 (lambda (f)
18545 (let ((e (expand-file-name (substitute-in-file-name f)
18546 org-directory)))
18547 (if pair-with-expansion
18548 (cons e f)
18549 e)))
18550 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18552 ;;;###autoload
18553 (defun org-cycle-agenda-files ()
18554 "Cycle through the files in `org-agenda-files'.
18555 If the current buffer visits an agenda file, find the next one in the list.
18556 If the current buffer does not, find the first agenda file."
18557 (interactive)
18558 (let* ((fs (or (org-agenda-files t)
18559 (user-error "No agenda files")))
18560 (files (copy-sequence fs))
18561 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18562 file)
18563 (when tcf
18564 (while (and (setq file (pop files))
18565 (not (equal (file-truename file) tcf)))))
18566 (find-file (car (or files fs)))
18567 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18569 (defun org-agenda-file-to-front (&optional to-end)
18570 "Move/add the current file to the top of the agenda file list.
18571 If the file is not present in the list, it is added to the front. If it is
18572 present, it is moved there. With optional argument TO-END, add/move to the
18573 end of the list."
18574 (interactive "P")
18575 (let ((org-agenda-skip-unavailable-files nil)
18576 (file-alist (mapcar (lambda (x)
18577 (cons (file-truename x) x))
18578 (org-agenda-files t)))
18579 (ctf (file-truename
18580 (or buffer-file-name
18581 (user-error "Please save the current buffer to a file"))))
18582 x had)
18583 (setq x (assoc ctf file-alist) had x)
18585 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18586 (if to-end
18587 (setq file-alist (append (delq x file-alist) (list x)))
18588 (setq file-alist (cons x (delq x file-alist))))
18589 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18590 (org-install-agenda-files-menu)
18591 (message "File %s to %s of agenda file list"
18592 (if had "moved" "added") (if to-end "end" "front"))))
18594 (defun org-remove-file (&optional file)
18595 "Remove current file from the list of files in variable `org-agenda-files'.
18596 These are the files which are being checked for agenda entries.
18597 Optional argument FILE means use this file instead of the current."
18598 (interactive)
18599 (let* ((org-agenda-skip-unavailable-files nil)
18600 (file (or file buffer-file-name
18601 (user-error "Current buffer does not visit a file")))
18602 (true-file (file-truename file))
18603 (afile (abbreviate-file-name file))
18604 (files (delq nil (mapcar
18605 (lambda (x)
18606 (unless (equal true-file
18607 (file-truename x))
18609 (org-agenda-files t)))))
18610 (if (not (= (length files) (length (org-agenda-files t))))
18611 (progn
18612 (org-store-new-agenda-file-list files)
18613 (org-install-agenda-files-menu)
18614 (message "Removed from Org Agenda list: %s" afile))
18615 (message "File was not in list: %s (not removed)" afile))))
18617 (defun org-file-menu-entry (file)
18618 (vector file (list 'find-file file) t))
18620 (defun org-check-agenda-file (file)
18621 "Make sure FILE exists. If not, ask user what to do."
18622 (unless (file-exists-p file)
18623 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18624 (abbreviate-file-name file))
18625 (let ((r (downcase (read-char-exclusive))))
18626 (cond
18627 ((equal r ?r)
18628 (org-remove-file file)
18629 (throw 'nextfile t))
18630 (t (user-error "Abort"))))))
18632 (defun org-get-agenda-file-buffer (file)
18633 "Get an agenda buffer visiting FILE.
18634 If the buffer needs to be created, add it to the list of buffers
18635 which might be released later."
18636 (let ((buf (org-find-base-buffer-visiting file)))
18637 (if buf
18638 buf ; just return it
18639 ;; Make a new buffer and remember it
18640 (setq buf (find-file-noselect file))
18641 (when buf (push buf org-agenda-new-buffers))
18642 buf)))
18644 (defun org-release-buffers (blist)
18645 "Release all buffers in list, asking the user for confirmation when needed.
18646 When a buffer is unmodified, it is just killed. When modified, it is saved
18647 \(if the user agrees) and then killed."
18648 (let (file)
18649 (dolist (buf blist)
18650 (setq file (buffer-file-name buf))
18651 (when (and (buffer-modified-p buf)
18652 file
18653 (y-or-n-p (format "Save file %s? " file)))
18654 (with-current-buffer buf (save-buffer)))
18655 (kill-buffer buf))))
18657 (defun org-agenda-prepare-buffers (files)
18658 "Create buffers for all agenda files, protect archived trees and comments."
18659 (interactive)
18660 (let ((pa '(:org-archived t))
18661 (pc '(:org-comment t))
18662 (pall '(:org-archived t :org-comment t))
18663 (inhibit-read-only t)
18664 (org-inhibit-startup org-agenda-inhibit-startup)
18665 (rea (concat ":" org-archive-tag ":"))
18666 re pos)
18667 (setq org-tag-alist-for-agenda nil
18668 org-tag-groups-alist-for-agenda nil)
18669 (save-excursion
18670 (save-restriction
18671 (dolist (file files)
18672 (catch 'nextfile
18673 (if (bufferp file)
18674 (set-buffer file)
18675 (org-check-agenda-file file)
18676 (set-buffer (org-get-agenda-file-buffer file)))
18677 (widen)
18678 (org-set-regexps-and-options 'tags-only)
18679 (setq pos (point))
18680 (or (memq 'category org-agenda-ignore-properties)
18681 (org-refresh-category-properties))
18682 (or (memq 'stats org-agenda-ignore-properties)
18683 (org-refresh-stats-properties))
18684 (or (memq 'effort org-agenda-ignore-properties)
18685 (org-refresh-effort-properties))
18686 (or (memq 'appt org-agenda-ignore-properties)
18687 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18688 (setq org-todo-keywords-for-agenda
18689 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18690 (setq org-done-keywords-for-agenda
18691 (append org-done-keywords-for-agenda org-done-keywords))
18692 (setq org-todo-keyword-alist-for-agenda
18693 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18694 (setq org-tag-alist-for-agenda
18695 (org-uniquify
18696 (append org-tag-alist-for-agenda
18697 org-tag-alist
18698 org-tag-persistent-alist)))
18699 (when org-group-tags
18700 (setq org-tag-groups-alist-for-agenda
18701 (org-uniquify-alist
18702 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18703 (org-with-silent-modifications
18704 (save-excursion
18705 (remove-text-properties (point-min) (point-max) pall)
18706 (when org-agenda-skip-archived-trees
18707 (goto-char (point-min))
18708 (while (re-search-forward rea nil t)
18709 (when (org-at-heading-p t)
18710 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18711 (goto-char (point-min))
18712 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18713 (while (re-search-forward re nil t)
18714 (when (save-match-data (org-in-commented-heading-p t))
18715 (add-text-properties
18716 (match-beginning 0) (org-end-of-subtree t) pc)))))
18717 (goto-char pos)))))
18718 (setq org-todo-keywords-for-agenda
18719 (org-uniquify org-todo-keywords-for-agenda))
18720 (setq org-todo-keyword-alist-for-agenda
18721 (org-uniquify org-todo-keyword-alist-for-agenda))))
18724 ;;;; CDLaTeX minor mode
18726 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18727 "Keymap for the minor `org-cdlatex-mode'.")
18729 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18730 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18731 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18732 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18733 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18735 (defvar org-cdlatex-texmathp-advice-is-done nil
18736 "Flag remembering if we have applied the advice to texmathp already.")
18738 (define-minor-mode org-cdlatex-mode
18739 "Toggle the minor `org-cdlatex-mode'.
18740 This mode supports entering LaTeX environment and math in LaTeX fragments
18741 in Org-mode.
18742 \\{org-cdlatex-mode-map}"
18743 nil " OCDL" nil
18744 (when org-cdlatex-mode
18745 (require 'cdlatex)
18746 (run-hooks 'cdlatex-mode-hook)
18747 (cdlatex-compute-tables))
18748 (unless org-cdlatex-texmathp-advice-is-done
18749 (setq org-cdlatex-texmathp-advice-is-done t)
18750 (defadvice texmathp (around org-math-always-on activate)
18751 "Always return t in org-mode buffers.
18752 This is because we want to insert math symbols without dollars even outside
18753 the LaTeX math segments. If Orgmode thinks that point is actually inside
18754 an embedded LaTeX fragment, let texmathp do its job.
18755 \\[org-cdlatex-mode-map]"
18756 (interactive)
18757 (let (p)
18758 (cond
18759 ((not (derived-mode-p 'org-mode)) ad-do-it)
18760 ((eq this-command 'cdlatex-math-symbol)
18761 (setq ad-return-value t
18762 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18764 (let ((p (org-inside-LaTeX-fragment-p)))
18765 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18766 (setq ad-return-value t
18767 texmathp-why '("Org-mode embedded math" . 0))
18768 (when p ad-do-it)))))))))
18770 (defun turn-on-org-cdlatex ()
18771 "Unconditionally turn on `org-cdlatex-mode'."
18772 (org-cdlatex-mode 1))
18774 (defun org-try-cdlatex-tab ()
18775 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18776 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18777 - inside a LaTeX fragment, or
18778 - after the first word in a line, where an abbreviation expansion could
18779 insert a LaTeX environment."
18780 (when org-cdlatex-mode
18781 (cond
18782 ;; Before any word on the line: No expansion possible.
18783 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18784 ;; Just after first word on the line: Expand it. Make sure it
18785 ;; cannot happen on headlines, though.
18786 ((save-excursion
18787 (skip-chars-backward "a-zA-Z0-9*")
18788 (skip-chars-backward " \t")
18789 (and (bolp) (not (org-at-heading-p))))
18790 (cdlatex-tab) t)
18791 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18793 (defun org-cdlatex-underscore-caret (&optional _arg)
18794 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18795 Revert to the normal definition outside of these fragments."
18796 (interactive "P")
18797 (if (org-inside-LaTeX-fragment-p)
18798 (call-interactively 'cdlatex-sub-superscript)
18799 (let (org-cdlatex-mode)
18800 (call-interactively (key-binding (vector last-input-event))))))
18802 (defun org-cdlatex-math-modify (&optional _arg)
18803 "Execute `cdlatex-math-modify' in LaTeX fragments.
18804 Revert to the normal definition outside of these fragments."
18805 (interactive "P")
18806 (if (org-inside-LaTeX-fragment-p)
18807 (call-interactively 'cdlatex-math-modify)
18808 (let (org-cdlatex-mode)
18809 (call-interactively (key-binding (vector last-input-event))))))
18811 (defun org-cdlatex-environment-indent (&optional environment item)
18812 "Execute `cdlatex-environment' and indent the inserted environment.
18814 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18816 The inserted environment is indented to current indentation
18817 unless point is at the beginning of the line, in which the
18818 environment remains unintended."
18819 (interactive)
18820 ;; cdlatex-environment always return nil. Therefore, capture output
18821 ;; first and determine if an environment was selected.
18822 (let* ((beg (point-marker))
18823 (end (copy-marker (point) t))
18824 (inserted (progn
18825 (ignore-errors (cdlatex-environment environment item))
18826 (< beg end)))
18827 ;; Figure out how many lines to move forward after the
18828 ;; environment has been inserted.
18829 (lines (when inserted
18830 (save-excursion
18831 (- (loop while (< beg (point))
18832 with x = 0
18833 do (forward-line -1)
18834 (incf x)
18835 finally return x)
18836 (if (progn (goto-char beg)
18837 (and (progn (skip-chars-forward " \t") (eolp))
18838 (progn (skip-chars-backward " \t") (bolp))))
18839 1 0)))))
18840 (env (org-trim (delete-and-extract-region beg end))))
18841 (when inserted
18842 ;; Get indentation of next line unless at column 0.
18843 (let ((ind (if (bolp) 0
18844 (save-excursion
18845 (org-return-indent)
18846 (prog1 (org-get-indentation)
18847 (when (progn (skip-chars-forward " \t") (eolp))
18848 (delete-region beg (point)))))))
18849 (bol (progn (skip-chars-backward " \t") (bolp))))
18850 ;; Insert a newline before environment unless at column zero
18851 ;; to "escape" the current line. Insert a newline if
18852 ;; something is one the same line as \end{ENVIRONMENT}.
18853 (insert
18854 (concat (unless bol "\n") env
18855 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18856 (unless (zerop ind)
18857 (save-excursion
18858 (goto-char beg)
18859 (while (< (point) end)
18860 (unless (eolp) (org-indent-line-to ind))
18861 (forward-line))))
18862 (goto-char beg)
18863 (forward-line lines)
18864 (org-indent-line-to ind)))
18865 (set-marker beg nil)
18866 (set-marker end nil)))
18869 ;;;; LaTeX fragments
18871 (defun org-inside-LaTeX-fragment-p ()
18872 "Test if point is inside a LaTeX fragment.
18873 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18874 sequence appearing also before point.
18875 Even though the matchers for math are configurable, this function assumes
18876 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18877 delimiters are skipped when they have been removed by customization.
18878 The return value is nil, or a cons cell with the delimiter and the
18879 position of this delimiter.
18881 This function does a reasonably good job, but can locally be fooled by
18882 for example currency specifications. For example it will assume being in
18883 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18884 fragments that are properly closed, but during editing, we have to live
18885 with the uncertainty caused by missing closing delimiters. This function
18886 looks only before point, not after."
18887 (catch 'exit
18888 (let ((pos (point))
18889 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18890 (lim (progn
18891 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18892 (point)))
18893 dd-on str (start 0) m re)
18894 (goto-char pos)
18895 (when dodollar
18896 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18897 re (nth 1 (assoc "$" org-latex-regexps)))
18898 (while (string-match re str start)
18899 (cond
18900 ((= (match-end 0) (length str))
18901 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18902 ((= (match-end 0) (- (length str) 5))
18903 (throw 'exit nil))
18904 (t (setq start (match-end 0))))))
18905 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18906 (goto-char pos)
18907 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18908 (and (match-beginning 2) (throw 'exit nil))
18909 ;; count $$
18910 (while (re-search-backward "\\$\\$" lim t)
18911 (setq dd-on (not dd-on)))
18912 (goto-char pos)
18913 (when dd-on (cons "$$" m))))))
18915 (defun org-inside-latex-macro-p ()
18916 "Is point inside a LaTeX macro or its arguments?"
18917 (save-match-data
18918 (org-in-regexp
18919 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18921 (defvar-local org-latex-fragment-image-overlays nil
18922 "List of overlays carrying the images of latex fragments.")
18924 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18925 "Remove all overlays with LaTeX fragment images in current buffer.
18926 When optional arguments BEG and END are non-nil, remove all
18927 overlays between them instead. Return t when some overlays were
18928 removed, nil otherwise."
18929 (let (removedp)
18930 (setq org-latex-fragment-image-overlays
18931 (let ((beg (or beg (point-min)))
18932 (end (or end (point-max))))
18933 (cl-remove-if
18934 (lambda (o)
18935 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18936 ((and (>= (overlay-start o) beg)
18937 (<= (overlay-end o) end))
18938 (delete-overlay o)
18939 (unless removedp (setq removedp t)))
18940 (t nil)))
18941 org-latex-fragment-image-overlays)))
18942 removedp))
18944 (define-obsolete-function-alias
18945 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18946 (defun org-toggle-latex-fragment (&optional arg)
18947 "Preview the LaTeX fragment at point, or all locally or globally.
18949 If the cursor is on a LaTeX fragment, create the image and overlay
18950 it over the source code, if there is none. Remove it otherwise.
18951 If there is no fragment at point, display all fragments in the
18952 current section.
18954 With prefix ARG, preview or clear image for all fragments in the
18955 current subtree or in the whole buffer when used before the first
18956 headline. With a double prefix ARG \\[universal-argument] \
18957 \\[universal-argument] preview or clear images
18958 for all fragments in the buffer."
18959 (interactive "P")
18960 (unless (buffer-file-name (buffer-base-buffer))
18961 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18962 (when (display-graphic-p)
18963 (catch 'exit
18964 (save-excursion
18965 (let ((window-start (window-start)) msg)
18966 (save-restriction
18967 (cond
18968 ((or (equal arg '(16))
18969 (and (equal arg '(4))
18970 (org-with-limited-levels (org-before-first-heading-p))))
18971 (if (org-remove-latex-fragment-image-overlays)
18972 (progn (message "LaTeX fragments images removed from buffer")
18973 (throw 'exit nil))
18974 (setq msg "Creating images for buffer...")))
18975 ((equal arg '(4))
18976 (org-with-limited-levels (org-back-to-heading t))
18977 (let ((beg (point))
18978 (end (progn (org-end-of-subtree t) (point))))
18979 (if (org-remove-latex-fragment-image-overlays beg end)
18980 (progn
18981 (message "LaTeX fragment images removed from subtree")
18982 (throw 'exit nil))
18983 (setq msg "Creating images for subtree...")
18984 (narrow-to-region beg end))))
18985 ((let ((datum (org-element-context)))
18986 (when (memq (org-element-type datum)
18987 '(latex-environment latex-fragment))
18988 (let* ((beg (org-element-property :begin datum))
18989 (end (org-element-property :end datum)))
18990 (if (org-remove-latex-fragment-image-overlays beg end)
18991 (progn (message "LaTeX fragment image removed")
18992 (throw 'exit nil))
18993 (narrow-to-region beg end)
18994 (setq msg "Creating image..."))))))
18996 (org-with-limited-levels
18997 (let ((beg (if (org-at-heading-p) (line-beginning-position)
18998 (outline-previous-heading)
18999 (point)))
19000 (end (progn (outline-next-heading) (point))))
19001 (if (org-remove-latex-fragment-image-overlays beg end)
19002 (progn
19003 (message "LaTeX fragment images removed from section")
19004 (throw 'exit nil))
19005 (setq msg "Creating images for section...")
19006 (narrow-to-region beg end))))))
19007 (let ((file (buffer-file-name (buffer-base-buffer))))
19008 (org-format-latex
19009 (concat org-latex-preview-ltxpng-directory
19010 (file-name-sans-extension (file-name-nondirectory file)))
19011 ;; Emacs cannot overlay images from remote hosts.
19012 ;; Create it in `temporary-file-directory' instead.
19013 (if (file-remote-p file) temporary-file-directory
19014 default-directory)
19015 'overlays msg 'forbuffer
19016 org-latex-create-formula-image-program)))
19017 ;; Work around a bug that doesn't restore window's start
19018 ;; when widening back the buffer.
19019 (set-window-start nil window-start)
19020 (message (concat msg "done")))))))
19022 (defun org-format-latex
19023 (prefix &optional dir overlays msg forbuffer processing-type)
19024 "Replace LaTeX fragments with links to an image, and produce images.
19026 When optional argument OVERLAYS is non-nil, display the image on
19027 top of the fragment instead of replacing it.
19029 PROCESSING-TYPE is the conversion method to use, as a symbol.
19031 Some of the options can be changed using the variable
19032 `org-format-latex-options', which see."
19033 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19034 (unless (eq processing-type 'verbatim)
19035 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19036 (cnt 0)
19037 checkdir-flag)
19038 (goto-char (point-min))
19039 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19040 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19041 (overlay-recenter (point-max)))
19042 (while (re-search-forward math-regexp nil t)
19043 (unless (and overlays
19044 (eq (get-char-property (point) 'org-overlay-type)
19045 'org-latex-overlay))
19046 (let* ((context (org-element-context))
19047 (type (org-element-type context)))
19048 (when (memq type '(latex-environment latex-fragment))
19049 (let ((block-type (eq type 'latex-environment))
19050 (value (org-element-property :value context))
19051 (beg (org-element-property :begin context))
19052 (end (save-excursion
19053 (goto-char (org-element-property :end context))
19054 (skip-chars-backward " \r\t\n")
19055 (point))))
19056 (case processing-type
19057 (mathjax
19058 ;; Prepare for MathJax processing.
19059 (if (eq (char-after beg) ?$)
19060 (save-excursion
19061 (delete-region beg end)
19062 (insert "\\(" (substring value 1 -1) "\\)"))
19063 (goto-char end)))
19064 ((dvipng imagemagick)
19065 ;; Process to an image.
19066 (incf cnt)
19067 (goto-char beg)
19068 (let* ((face (face-at-point))
19069 ;; Get the colors from the face at point.
19071 (let ((color (plist-get org-format-latex-options
19072 :foreground)))
19073 (if (and forbuffer (eq color 'auto))
19074 (face-attribute face :foreground nil 'default)
19075 color)))
19077 (let ((color (plist-get org-format-latex-options
19078 :background)))
19079 (if (and forbuffer (eq color 'auto))
19080 (face-attribute face :background nil 'default)
19081 color)))
19082 (hash (sha1 (prin1-to-string
19083 (list org-format-latex-header
19084 org-latex-default-packages-alist
19085 org-latex-packages-alist
19086 org-format-latex-options
19087 forbuffer value fg bg))))
19088 (absprefix (expand-file-name prefix dir))
19089 (linkfile (format "%s_%s.png" prefix hash))
19090 (movefile (format "%s_%s.png" absprefix hash))
19091 (sep (and block-type "\n\n"))
19092 (link (concat sep "[[file:" linkfile "]]" sep))
19093 (options
19094 (org-combine-plists
19095 org-format-latex-options
19096 `(:foreground ,fg :background ,bg))))
19097 (when msg (message msg cnt))
19098 (unless checkdir-flag ; Ensure the directory exists.
19099 (setq checkdir-flag t)
19100 (let ((todir (file-name-directory absprefix)))
19101 (unless (file-directory-p todir)
19102 (make-directory todir t))))
19103 (unless (file-exists-p movefile)
19104 (org-create-formula-image
19105 value movefile options forbuffer processing-type))
19106 (if overlays
19107 (progn
19108 (dolist (o (overlays-in beg end))
19109 (when (eq (overlay-get o 'org-overlay-type)
19110 'org-latex-overlay)
19111 (delete-overlay o)))
19112 (let ((ov (make-overlay beg end)))
19113 (overlay-put ov
19114 'org-overlay-type
19115 'org-latex-overlay)
19116 (overlay-put ov 'evaporate t)
19117 (if (featurep 'xemacs)
19118 (progn
19119 (overlay-put ov 'invisible t)
19120 (overlay-put
19121 ov 'end-glyph
19122 (make-glyph
19123 (vector 'png :file movefile))))
19124 (overlay-put
19125 ov 'display
19126 (list 'image
19127 :type 'png
19128 :file movefile
19129 :ascent 'center)))
19130 (push ov org-latex-fragment-image-overlays))
19131 (goto-char end))
19132 (delete-region beg end)
19133 (insert
19134 (org-add-props link
19135 (list 'org-latex-src
19136 (replace-regexp-in-string "\"" "" value)
19137 'org-latex-src-embed-type
19138 (if block-type 'paragraph 'character)))))))
19139 (mathml
19140 ;; Process to MathML.
19141 (unless (org-format-latex-mathml-available-p)
19142 (user-error "LaTeX to MathML converter not configured"))
19143 (incf cnt)
19144 (when msg (message msg cnt))
19145 (goto-char beg)
19146 (delete-region beg end)
19147 (insert (org-format-latex-as-mathml
19148 value block-type prefix dir)))
19149 (otherwise
19150 (error "Unknown conversion type %s for LaTeX fragments"
19151 processing-type)))))))))))
19153 (defun org-create-math-formula (latex-frag &optional mathml-file)
19154 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19155 Use `org-latex-to-mathml-convert-command'. If the conversion is
19156 sucessful, return the portion between \"<math...> </math>\"
19157 elements otherwise return nil. When MATHML-FILE is specified,
19158 write the results in to that file. When invoked as an
19159 interactive command, prompt for LATEX-FRAG, with initial value
19160 set to the current active region and echo the results for user
19161 inspection."
19162 (interactive (list (let ((frag (when (org-region-active-p)
19163 (buffer-substring-no-properties
19164 (region-beginning) (region-end)))))
19165 (read-string "LaTeX Fragment: " frag nil frag))))
19166 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19167 (let* ((tmp-in-file
19168 (let ((file (file-relative-name
19169 (make-temp-name (expand-file-name "ltxmathml-in")))))
19170 (write-region latex-frag nil file)
19171 file))
19172 (tmp-out-file (file-relative-name
19173 (make-temp-name (expand-file-name "ltxmathml-out"))))
19174 (cmd (format-spec
19175 org-latex-to-mathml-convert-command
19176 `((?j . ,(and org-latex-to-mathml-jar-file
19177 (shell-quote-argument
19178 (expand-file-name
19179 org-latex-to-mathml-jar-file))))
19180 (?I . ,(shell-quote-argument tmp-in-file))
19181 (?i . ,latex-frag)
19182 (?o . ,(shell-quote-argument tmp-out-file)))))
19183 mathml shell-command-output)
19184 (when (org-called-interactively-p 'any)
19185 (unless (org-format-latex-mathml-available-p)
19186 (user-error "LaTeX to MathML converter not configured")))
19187 (message "Running %s" cmd)
19188 (setq shell-command-output (shell-command-to-string cmd))
19189 (setq mathml
19190 (when (file-readable-p tmp-out-file)
19191 (with-current-buffer (find-file-noselect tmp-out-file t)
19192 (goto-char (point-min))
19193 (when (re-search-forward
19194 (concat
19195 (regexp-quote
19196 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19197 "[^>]*?>"
19198 "\\(.\\|\n\\)*"
19199 "</math>")
19200 nil t)
19201 (prog1 (match-string 0) (kill-buffer))))))
19202 (cond
19203 (mathml
19204 (setq mathml
19205 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19206 (when mathml-file
19207 (write-region mathml nil mathml-file))
19208 (when (org-called-interactively-p 'any)
19209 (message mathml)))
19210 ((message "LaTeX to MathML conversion failed")
19211 (message shell-command-output)))
19212 (delete-file tmp-in-file)
19213 (when (file-exists-p tmp-out-file)
19214 (delete-file tmp-out-file))
19215 mathml))
19217 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19218 prefix &optional dir)
19219 "Use `org-create-math-formula' but check local cache first."
19220 (let* ((absprefix (expand-file-name prefix dir))
19221 (print-length nil) (print-level nil)
19222 (formula-id (concat
19223 "formula-"
19224 (sha1
19225 (prin1-to-string
19226 (list latex-frag
19227 org-latex-to-mathml-convert-command)))))
19228 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19229 (formula-cache-dir (file-name-directory formula-cache)))
19231 (unless (file-directory-p formula-cache-dir)
19232 (make-directory formula-cache-dir t))
19234 (unless (file-exists-p formula-cache)
19235 (org-create-math-formula latex-frag formula-cache))
19237 (if (file-exists-p formula-cache)
19238 ;; Successful conversion. Return the link to MathML file.
19239 (org-add-props
19240 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19241 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19242 'org-latex-src-embed-type (if latex-frag-type
19243 'paragraph 'character)))
19244 ;; Failed conversion. Return the LaTeX fragment verbatim
19245 latex-frag)))
19247 (defun org-create-formula-image (string tofile options buffer &optional type)
19248 "Create an image from LaTeX source using dvipng or convert.
19249 This function calls either `org-create-formula-image-with-dvipng'
19250 or `org-create-formula-image-with-imagemagick' depending on the
19251 value of `org-latex-create-formula-image-program' or on the value
19252 of the optional TYPE variable.
19254 Note: ultimately these two function should be combined as they
19255 share a good deal of logic."
19256 (org-check-external-command
19257 "latex" "needed to convert LaTeX fragments to images")
19258 (funcall
19259 (case (or type org-latex-create-formula-image-program)
19260 (dvipng
19261 (org-check-external-command
19262 "dvipng" "needed to convert LaTeX fragments to images")
19263 #'org-create-formula-image-with-dvipng)
19264 (imagemagick
19265 (org-check-external-command
19266 "convert" "you need to install imagemagick")
19267 #'org-create-formula-image-with-imagemagick)
19268 (t (error
19269 "Invalid value of `org-latex-create-formula-image-program'")))
19270 string tofile options buffer))
19272 (declare-function org-export-get-backend "ox" (name))
19273 (declare-function org-export--get-global-options "ox" (&optional backend))
19274 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19275 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19276 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19277 (defun org-create-formula--latex-header ()
19278 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19279 (let ((info (org-combine-plists (org-export--get-global-options
19280 (org-export-get-backend 'latex))
19281 (org-export--get-inbuffer-options
19282 (org-export-get-backend 'latex)))))
19283 (org-latex-guess-babel-language
19284 (org-latex-guess-inputenc
19285 (org-splice-latex-header
19286 org-format-latex-header
19287 org-latex-default-packages-alist
19288 org-latex-packages-alist t
19289 (plist-get info :latex-header)))
19290 info)))
19292 (defun org--get-display-dpi ()
19293 "Get the DPI of the display.
19295 Assumes that the display has the same pixel width in the
19296 horizontal and vertical directions."
19297 (if (display-graphic-p)
19298 (round (/ (display-pixel-height)
19299 (/ (display-mm-height) 25.4)))
19300 (error "Attempt to calculate the dpi of a non-graphic display")))
19302 ;; This function borrows from Ganesh Swami's latex2png.el
19303 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19304 "This calls dvipng."
19305 (require 'ox-latex)
19306 (let* ((tmpdir (if (featurep 'xemacs)
19307 (temp-directory)
19308 temporary-file-directory))
19309 (texfilebase (make-temp-name
19310 (expand-file-name "orgtex" tmpdir)))
19311 (texfile (concat texfilebase ".tex"))
19312 (dvifile (concat texfilebase ".dvi"))
19313 (pngfile (concat texfilebase ".png"))
19314 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19315 ;; This assumes that the display has the same pixel width in
19316 ;; the horizontal and vertical directions
19317 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19318 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19319 "Black"))
19320 (bg (or (plist-get options (if buffer :background :html-background))
19321 "Transparent")))
19322 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19323 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19324 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19325 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19326 (let ((latex-header (org-create-formula--latex-header)))
19327 (with-temp-file texfile
19328 (insert latex-header)
19329 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19330 (let ((dir default-directory))
19331 (ignore-errors
19332 (cd tmpdir)
19333 (call-process "latex" nil nil nil texfile))
19334 (cd dir))
19335 (if (not (file-exists-p dvifile))
19336 (progn (message "Failed to create dvi file from %s" texfile) nil)
19337 (ignore-errors
19338 (if (featurep 'xemacs)
19339 (call-process "dvipng" nil nil nil
19340 "-fg" fg "-bg" bg
19341 "-T" "tight"
19342 "-o" pngfile
19343 dvifile)
19344 (call-process "dvipng" nil nil nil
19345 "-fg" fg "-bg" bg
19346 "-D" dpi
19347 ;;"-x" scale "-y" scale
19348 "-T" "tight"
19349 "-o" pngfile
19350 dvifile)))
19351 (if (not (file-exists-p pngfile))
19352 (if org-format-latex-signal-error
19353 (error "Failed to create png file from %s" texfile)
19354 (message "Failed to create png file from %s" texfile)
19355 nil)
19356 ;; Use the requested file name and clean up
19357 (copy-file pngfile tofile 'replace)
19358 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19359 (when (file-exists-p (concat texfilebase e))
19360 (delete-file (concat texfilebase e))))
19361 pngfile))))
19363 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19364 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19365 "This calls convert, which is included into imagemagick."
19366 (require 'ox-latex)
19367 (let* ((tmpdir (if (featurep 'xemacs)
19368 (temp-directory)
19369 temporary-file-directory))
19370 (texfilebase (make-temp-name
19371 (expand-file-name "orgtex" tmpdir)))
19372 (texfile (concat texfilebase ".tex"))
19373 (pdffile (concat texfilebase ".pdf"))
19374 (pngfile (concat texfilebase ".png"))
19375 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19376 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19377 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19378 "black"))
19379 (bg (or (plist-get options (if buffer :background :html-background))
19380 "white")))
19381 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19382 (setq fg (org-latex-color-format fg)))
19383 (if (eq bg 'default) (setq bg (org-latex-color :background))
19384 (setq bg (org-latex-color-format
19385 (if (string= bg "Transparent") "white" bg))))
19386 (let ((latex-header (org-create-formula--latex-header)))
19387 (with-temp-file texfile
19388 (insert latex-header)
19389 (insert "\n\\begin{document}\n"
19390 "\\definecolor{fg}{rgb}{" fg "}\n"
19391 "\\definecolor{bg}{rgb}{" bg "}\n"
19392 "\n\\pagecolor{bg}\n"
19393 "\n{\\color{fg}\n"
19394 string
19395 "\n}\n"
19396 "\n\\end{document}\n")))
19397 (org-latex-compile texfile t)
19398 (if (not (file-exists-p pdffile))
19399 (progn (message "Failed to create pdf file from %s" texfile) nil)
19400 (ignore-errors
19401 (if (featurep 'xemacs)
19402 (call-process "convert" nil nil nil
19403 "-density" "96"
19404 "-trim"
19405 "-antialias"
19406 pdffile
19407 "-quality" "100"
19408 ;; "-sharpen" "0x1.0"
19409 pngfile)
19410 (call-process "convert" nil nil nil
19411 "-density" dpi
19412 "-trim"
19413 "-antialias"
19414 pdffile
19415 "-quality" "100"
19416 ;; "-sharpen" "0x1.0"
19417 pngfile)))
19418 (if (not (file-exists-p pngfile))
19419 (if org-format-latex-signal-error
19420 (error "Failed to create png file from %s" texfile)
19421 (message "Failed to create png file from %s" texfile)
19422 nil)
19423 ;; Use the requested file name and clean up
19424 (copy-file pngfile tofile 'replace)
19425 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19426 (when (file-exists-p (concat texfilebase e))
19427 (delete-file (concat texfilebase e))))
19428 pngfile))))
19430 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19431 "Fill a LaTeX header template TPL.
19432 In the template, the following place holders will be recognized:
19434 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19435 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19436 [PACKAGES] \\usepackage statements for PKG
19437 [NO-PACKAGES] do not include PKG
19438 [EXTRA] the string EXTRA
19439 [NO-EXTRA] do not include EXTRA
19441 For backward compatibility, if both the positive and the negative place
19442 holder is missing, the positive one (without the \"NO-\") will be
19443 assumed to be present at the end of the template.
19444 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19445 EXTRA is a string.
19446 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19447 (let (rpl (end ""))
19448 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19449 (setq rpl (if (or (match-end 1) (not def-pkg))
19450 "" (org-latex-packages-to-string def-pkg snippets-p t))
19451 tpl (replace-match rpl t t tpl))
19452 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19454 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19455 (setq rpl (if (or (match-end 1) (not pkg))
19456 "" (org-latex-packages-to-string pkg snippets-p t))
19457 tpl (replace-match rpl t t tpl))
19458 (when pkg (setq end
19459 (concat end "\n"
19460 (org-latex-packages-to-string pkg snippets-p)))))
19462 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19463 (setq rpl (if (or (match-end 1) (not extra))
19464 "" (concat extra "\n"))
19465 tpl (replace-match rpl t t tpl))
19466 (when (and extra (string-match "\\S-" extra))
19467 (setq end (concat end "\n" extra))))
19469 (if (string-match "\\S-" end)
19470 (concat tpl "\n" end)
19471 tpl)))
19473 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19474 "Turn an alist of packages into a string with the \\usepackage macros."
19475 (setq pkg (mapconcat (lambda(p)
19476 (cond
19477 ((stringp p) p)
19478 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19479 (format "%% Package %s omitted" (cadr p)))
19480 ((equal "" (car p))
19481 (format "\\usepackage{%s}" (cadr p)))
19483 (format "\\usepackage[%s]{%s}"
19484 (car p) (cadr p)))))
19486 "\n"))
19487 (if newline (concat pkg "\n") pkg))
19489 (defun org-dvipng-color (attr)
19490 "Return a RGB color specification for dvipng."
19491 (apply 'format "rgb %s %s %s"
19492 (mapcar 'org-normalize-color
19493 (if (featurep 'xemacs)
19494 (color-rgb-components
19495 (face-property 'default
19496 (cond ((eq attr :foreground) 'foreground)
19497 ((eq attr :background) 'background))))
19498 (color-values (face-attribute 'default attr nil))))))
19500 (defun org-dvipng-color-format (color-name)
19501 "Convert COLOR-NAME to a RGB color value for dvipng."
19502 (apply 'format "rgb %s %s %s"
19503 (mapcar 'org-normalize-color
19504 (color-values color-name))))
19506 (defun org-latex-color (attr)
19507 "Return a RGB color for the LaTeX color package."
19508 (apply 'format "%s,%s,%s"
19509 (mapcar 'org-normalize-color
19510 (if (featurep 'xemacs)
19511 (color-rgb-components
19512 (face-property 'default
19513 (cond ((eq attr :foreground) 'foreground)
19514 ((eq attr :background) 'background))))
19515 (color-values (face-attribute 'default attr nil))))))
19517 (defun org-latex-color-format (color-name)
19518 "Convert COLOR-NAME to a RGB color value."
19519 (apply 'format "%s,%s,%s"
19520 (mapcar 'org-normalize-color
19521 (color-values color-name))))
19523 (defun org-normalize-color (value)
19524 "Return string to be used as color value for an RGB component."
19525 (format "%g" (/ value 65535.0)))
19529 ;; Image display
19531 (defvar-local org-inline-image-overlays nil)
19533 (defun org-toggle-inline-images (&optional include-linked)
19534 "Toggle the display of inline images.
19535 INCLUDE-LINKED is passed to `org-display-inline-images'."
19536 (interactive "P")
19537 (if org-inline-image-overlays
19538 (progn
19539 (org-remove-inline-images)
19540 (when (org-called-interactively-p 'interactive)
19541 (message "Inline image display turned off")))
19542 (org-display-inline-images include-linked)
19543 (when (org-called-interactively-p 'interactive)
19544 (message (if org-inline-image-overlays
19545 (format "%d images displayed inline"
19546 (length org-inline-image-overlays))
19547 "No images to display inline")))))
19549 (defun org-redisplay-inline-images ()
19550 "Refresh the display of inline images."
19551 (interactive)
19552 (if (not org-inline-image-overlays)
19553 (org-toggle-inline-images)
19554 (org-toggle-inline-images)
19555 (org-toggle-inline-images)))
19557 (defun org-display-inline-images (&optional include-linked refresh beg end)
19558 "Display inline images.
19560 An inline image is a link which follows either of these
19561 conventions:
19563 1. Its path is a file with an extension matching return value
19564 from `image-file-name-regexp' and it has no contents.
19566 2. Its description consists in a single link of the previous
19567 type.
19569 When optional argument INCLUDE-LINKED is non-nil, also links with
19570 a text description part will be inlined. This can be nice for
19571 a quick look at those images, but it does not reflect what
19572 exported files will look like.
19574 When optional argument REFRESH is non-nil, refresh existing
19575 images between BEG and END. This will create new image displays
19576 only if necessary. BEG and END default to the buffer
19577 boundaries."
19578 (interactive "P")
19579 (when (display-graphic-p)
19580 (unless refresh
19581 (org-remove-inline-images)
19582 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19583 (org-with-wide-buffer
19584 (goto-char (or beg (point-min)))
19585 (let ((case-fold-search t)
19586 (file-extension-re (image-file-name-regexp)))
19587 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19588 (let ((link (save-match-data (org-element-context))))
19589 ;; Check if we're at an inline image.
19590 (when (and (equal (org-element-property :type link) "file")
19591 (or include-linked
19592 (not (org-element-property :contents-begin link)))
19593 (let ((parent (org-element-property :parent link)))
19594 (or (not (eq (org-element-type parent) 'link))
19595 (not (cdr (org-element-contents parent)))))
19596 (org-string-match-p file-extension-re
19597 (org-element-property :path link)))
19598 (let ((file (expand-file-name
19599 (org-link-unescape
19600 (org-element-property :path link)))))
19601 (when (file-exists-p file)
19602 (let ((width
19603 ;; Apply `org-image-actual-width' specifications.
19604 (cond
19605 ((not (image-type-available-p 'imagemagick)) nil)
19606 ((eq org-image-actual-width t) nil)
19607 ((listp org-image-actual-width)
19609 ;; First try to find a width among
19610 ;; attributes associated to the paragraph
19611 ;; containing link.
19612 (let ((paragraph
19613 (let ((e link))
19614 (while (and (setq e (org-element-property
19615 :parent e))
19616 (not (eq (org-element-type e)
19617 'paragraph))))
19618 e)))
19619 (when paragraph
19620 (save-excursion
19621 (goto-char (org-element-property :begin paragraph))
19622 (when
19623 (re-search-forward
19624 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19625 (org-element-property
19626 :post-affiliated paragraph)
19628 (string-to-number (match-string 1))))))
19629 ;; Otherwise, fall-back to provided number.
19630 (car org-image-actual-width)))
19631 ((numberp org-image-actual-width)
19632 org-image-actual-width)))
19633 (old (get-char-property-and-overlay
19634 (org-element-property :begin link)
19635 'org-image-overlay)))
19636 (if (and (car-safe old) refresh)
19637 (image-refresh (overlay-get (cdr old) 'display))
19638 (let ((image (create-image file
19639 (and width 'imagemagick)
19641 :width width)))
19642 (when image
19643 (let* ((link
19644 ;; If inline image is the description
19645 ;; of another link, be sure to
19646 ;; consider the latter as the one to
19647 ;; apply the overlay on.
19648 (let ((parent
19649 (org-element-property :parent link)))
19650 (if (eq (org-element-type parent) 'link)
19651 parent
19652 link)))
19653 (ov (make-overlay
19654 (org-element-property :begin link)
19655 (progn
19656 (goto-char
19657 (org-element-property :end link))
19658 (skip-chars-backward " \t")
19659 (point)))))
19660 (overlay-put ov 'display image)
19661 (overlay-put ov 'face 'default)
19662 (overlay-put ov 'org-image-overlay t)
19663 (overlay-put
19664 ov 'modification-hooks
19665 (list 'org-display-inline-remove-overlay))
19666 (push ov org-inline-image-overlays)))))))))))))))
19668 (define-obsolete-function-alias
19669 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19671 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19672 "Remove inline-display overlay if a corresponding region is modified."
19673 (let ((inhibit-modification-hooks t))
19674 (when (and ov after)
19675 (delete ov org-inline-image-overlays)
19676 (delete-overlay ov))))
19678 (defun org-remove-inline-images ()
19679 "Remove inline display of images."
19680 (interactive)
19681 (mapc #'delete-overlay org-inline-image-overlays)
19682 (setq org-inline-image-overlays nil))
19684 ;;;; Key bindings
19686 ;; Outline functions from `outline-mode-prefix-map'
19687 ;; that can be remapped in Org:
19688 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19689 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19690 (define-key org-mode-map [remap outline-forward-same-level]
19691 'org-forward-heading-same-level)
19692 (define-key org-mode-map [remap outline-backward-same-level]
19693 'org-backward-heading-same-level)
19694 (define-key org-mode-map [remap outline-show-branches]
19695 'org-kill-note-or-show-branches)
19696 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19697 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19698 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19699 (define-key org-mode-map [remap outline-next-visible-heading]
19700 'org-next-visible-heading)
19701 (define-key org-mode-map [remap outline-previous-visible-heading]
19702 'org-previous-visible-heading)
19703 (define-key org-mode-map [remap show-children] 'org-show-children)
19705 ;; Outline functions from `outline-mode-prefix-map' that can not
19706 ;; be remapped in Org:
19708 ;; - the column "key binding" shows whether the Outline function is still
19709 ;; available in Org mode on the same key that it has been bound to in
19710 ;; Outline mode:
19711 ;; - "overridden": key used for a different functionality in Org mode
19712 ;; - else: key still bound to the same Outline function in Org mode
19714 ;; | Outline function | key binding | Org replacement |
19715 ;; |------------------------------------+-------------+--------------------------|
19716 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19717 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19718 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19719 ;; | `show-entry' | overridden | no replacement |
19720 ;; | `show-branches' | `C-c C-k' | still same function |
19721 ;; | `show-subtree' | overridden | visibility cycling |
19722 ;; | `show-all' | overridden | no replacement |
19723 ;; | `hide-subtree' | overridden | visibility cycling |
19724 ;; | `hide-body' | overridden | no replacement |
19725 ;; | `hide-entry' | overridden | visibility cycling |
19726 ;; | `hide-leaves' | overridden | no replacement |
19727 ;; | `hide-sublevels' | overridden | no replacement |
19728 ;; | `hide-other' | overridden | no replacement |
19730 ;; Make `C-c C-x' a prefix key
19731 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19733 ;; TAB key with modifiers
19734 (org-defkey org-mode-map "\C-i" 'org-cycle)
19735 (org-defkey org-mode-map [(tab)] 'org-cycle)
19736 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19737 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19738 ;; The following line is necessary under Suse GNU/Linux
19739 (unless (featurep 'xemacs)
19740 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19741 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19742 (define-key org-mode-map [backtab] 'org-shifttab)
19744 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19745 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19746 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19748 ;; Cursor keys with modifiers
19749 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19750 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19751 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19752 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19754 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19755 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19756 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19757 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19758 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19759 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19761 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19762 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19763 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19764 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19766 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19767 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19768 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19769 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19771 ;; Babel keys
19772 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19773 (dolist (pair org-babel-key-bindings)
19774 (define-key org-babel-map (car pair) (cdr pair)))
19776 ;;; Extra keys for tty access.
19777 ;; We only set them when really needed because otherwise the
19778 ;; menus don't show the simple keys
19780 (when (or org-use-extra-keys
19781 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19782 (not window-system))
19783 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19784 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19785 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19786 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19787 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19788 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19789 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19790 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19791 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19792 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19793 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19794 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19795 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19796 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19797 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19798 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19799 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19800 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19801 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19802 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19803 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19804 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19805 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19806 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19807 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19808 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19809 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19810 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19812 ;; All the other keys
19814 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19815 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19816 (if (boundp 'narrow-map)
19817 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19818 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19819 (if (boundp 'narrow-map)
19820 (org-defkey narrow-map "b" 'org-narrow-to-block)
19821 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19822 (if (boundp 'narrow-map)
19823 (org-defkey narrow-map "e" 'org-narrow-to-element)
19824 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19825 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19826 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19827 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19828 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19829 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19830 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19831 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19832 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19833 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19834 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19835 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19836 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19837 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19838 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19839 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19840 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19841 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19842 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19843 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19844 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19845 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19846 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19847 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19848 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19849 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19850 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19851 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19852 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19853 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19854 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19855 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19856 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19857 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19858 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19859 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19860 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19861 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19862 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19863 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19864 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19865 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19866 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19867 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19868 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19869 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19870 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19871 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19872 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19873 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19874 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19875 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19876 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19877 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19878 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19879 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19880 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19881 (org-defkey org-mode-map "\C-c^" 'org-sort)
19882 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19883 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19884 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19885 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19886 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19887 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19888 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19889 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19890 (org-defkey org-mode-map "\C-m" 'org-return)
19891 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19892 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19893 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19894 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19895 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19896 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19897 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19898 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19899 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19900 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19901 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19902 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19903 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19904 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19905 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19906 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19907 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19908 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19909 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19910 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19911 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19912 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19913 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19914 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19915 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19917 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19918 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19919 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19921 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19922 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19923 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19924 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19925 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19926 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19927 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19928 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19929 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19930 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19931 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19932 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19933 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19934 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19935 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19936 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19937 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19938 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19939 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19940 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19941 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19942 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19944 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19945 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19946 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19947 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19948 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19950 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19952 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19954 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19955 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19957 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19960 (when (featurep 'xemacs)
19961 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19964 (defconst org-speed-commands-default
19966 ("Outline Navigation")
19967 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19968 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19969 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19970 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19971 ("F" . org-next-block)
19972 ("B" . org-previous-block)
19973 ("u" . (org-speed-move-safe 'outline-up-heading))
19974 ("j" . org-goto)
19975 ("g" . (org-refile t))
19976 ("Outline Visibility")
19977 ("c" . org-cycle)
19978 ("C" . org-shifttab)
19979 (" " . org-display-outline-path)
19980 ("s" . org-narrow-to-subtree)
19981 ("=" . org-columns)
19982 ("Outline Structure Editing")
19983 ("U" . org-metaup)
19984 ("D" . org-metadown)
19985 ("r" . org-metaright)
19986 ("l" . org-metaleft)
19987 ("R" . org-shiftmetaright)
19988 ("L" . org-shiftmetaleft)
19989 ("i" . (progn (forward-char 1) (call-interactively
19990 'org-insert-heading-respect-content)))
19991 ("^" . org-sort)
19992 ("w" . org-refile)
19993 ("a" . org-archive-subtree-default-with-confirmation)
19994 ("@" . org-mark-subtree)
19995 ("#" . org-toggle-comment)
19996 ("Clock Commands")
19997 ("I" . org-clock-in)
19998 ("O" . org-clock-out)
19999 ("Meta Data Editing")
20000 ("t" . org-todo)
20001 ("," . (org-priority))
20002 ("0" . (org-priority ?\ ))
20003 ("1" . (org-priority ?A))
20004 ("2" . (org-priority ?B))
20005 ("3" . (org-priority ?C))
20006 (":" . org-set-tags-command)
20007 ("e" . org-set-effort)
20008 ("E" . org-inc-effort)
20009 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20010 (org-entry-put (point) "APPT_WARNTIME" m)))
20011 ("Agenda Views etc")
20012 ("v" . org-agenda)
20013 ("/" . org-sparse-tree)
20014 ("Misc")
20015 ("o" . org-open-at-point)
20016 ("?" . org-speed-command-help)
20017 ("<" . (org-agenda-set-restriction-lock 'subtree))
20018 (">" . (org-agenda-remove-restriction-lock))
20020 "The default speed commands.")
20022 (defun org-print-speed-command (e)
20023 (if (> (length (car e)) 1)
20024 (progn
20025 (princ "\n")
20026 (princ (car e))
20027 (princ "\n")
20028 (princ (make-string (length (car e)) ?-))
20029 (princ "\n"))
20030 (princ (car e))
20031 (princ " ")
20032 (if (symbolp (cdr e))
20033 (princ (symbol-name (cdr e)))
20034 (prin1 (cdr e)))
20035 (princ "\n")))
20037 (defun org-speed-command-help ()
20038 "Show the available speed commands."
20039 (interactive)
20040 (if (not org-use-speed-commands)
20041 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20042 (with-output-to-temp-buffer "*Help*"
20043 (princ "User-defined Speed commands\n===========================\n")
20044 (mapc #'org-print-speed-command org-speed-commands-user)
20045 (princ "\n")
20046 (princ "Built-in Speed commands\n=======================\n")
20047 (mapc #'org-print-speed-command org-speed-commands-default))
20048 (with-current-buffer "*Help*"
20049 (setq truncate-lines t))))
20051 (defun org-speed-move-safe (cmd)
20052 "Execute CMD, but make sure that the cursor always ends up in a headline.
20053 If not, return to the original position and throw an error."
20054 (interactive)
20055 (let ((pos (point)))
20056 (call-interactively cmd)
20057 (unless (and (bolp) (org-at-heading-p))
20058 (goto-char pos)
20059 (error "Boundary reached while executing %s" cmd))))
20061 (defvar org-self-insert-command-undo-counter 0)
20063 (defvar org-table-auto-blank-field) ; defined in org-table.el
20064 (defvar org-speed-command nil)
20066 (define-obsolete-function-alias
20067 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20069 (defun org-speed-command-activate (keys)
20070 "Hook for activating single-letter speed commands.
20071 `org-speed-commands-default' specifies a minimal command set.
20072 Use `org-speed-commands-user' for further customization."
20073 (when (or (and (bolp) (looking-at org-outline-regexp))
20074 (and (functionp org-use-speed-commands)
20075 (funcall org-use-speed-commands)))
20076 (cdr (assoc keys (append org-speed-commands-user
20077 org-speed-commands-default)))))
20079 (define-obsolete-function-alias
20080 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20082 (defun org-babel-speed-command-activate (keys)
20083 "Hook for activating single-letter code block commands."
20084 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20085 (cdr (assoc keys org-babel-key-bindings))))
20087 (defcustom org-speed-command-hook
20088 '(org-speed-command-default-hook org-babel-speed-command-hook)
20089 "Hook for activating speed commands at strategic locations.
20090 Hook functions are called in sequence until a valid handler is
20091 found.
20093 Each hook takes a single argument, a user-pressed command key
20094 which is also a `self-insert-command' from the global map.
20096 Within the hook, examine the cursor position and the command key
20097 and return nil or a valid handler as appropriate. Handler could
20098 be one of an interactive command, a function, or a form.
20100 Set `org-use-speed-commands' to non-nil value to enable this
20101 hook. The default setting is `org-speed-command-activate'."
20102 :group 'org-structure
20103 :version "24.1"
20104 :type 'hook)
20106 (defun org-self-insert-command (N)
20107 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20108 If the cursor is in a table looking at whitespace, the whitespace is
20109 overwritten, and the table is not marked as requiring realignment."
20110 (interactive "p")
20111 (org-check-before-invisible-edit 'insert)
20112 (cond
20113 ((and org-use-speed-commands
20114 (let ((kv (this-command-keys-vector)))
20115 (setq org-speed-command
20116 (run-hook-with-args-until-success
20117 'org-speed-command-hook
20118 (make-string 1 (aref kv (1- (length kv))))))))
20119 (cond
20120 ((commandp org-speed-command)
20121 (setq this-command org-speed-command)
20122 (call-interactively org-speed-command))
20123 ((functionp org-speed-command)
20124 (funcall org-speed-command))
20125 ((and org-speed-command (listp org-speed-command))
20126 (eval org-speed-command))
20127 (t (let (org-use-speed-commands)
20128 (call-interactively 'org-self-insert-command)))))
20129 ((and
20130 (org-at-table-p)
20131 (progn
20132 ;; Check if we blank the field, and if that triggers align.
20133 (and (featurep 'org-table) org-table-auto-blank-field
20134 (memq last-command
20135 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20136 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20137 ;; Got extra space, this field does not determine
20138 ;; column width.
20139 (let (org-table-may-need-update) (org-table-blank-field))
20140 ;; No extra space, this field may determine column
20141 ;; width.
20142 (org-table-blank-field)))
20144 (eq N 1)
20145 (looking-at "[^|\n]* \\( \\)|"))
20146 ;; There is room for insertion without re-aligning the table.
20147 (delete-region (match-beginning 1) (match-end 1))
20148 (self-insert-command N))
20150 (setq org-table-may-need-update t)
20151 (self-insert-command N)
20152 (org-fix-tags-on-the-fly)
20153 (when org-self-insert-cluster-for-undo
20154 (if (not (eq last-command 'org-self-insert-command))
20155 (setq org-self-insert-command-undo-counter 1)
20156 (if (>= org-self-insert-command-undo-counter 20)
20157 (setq org-self-insert-command-undo-counter 1)
20158 (and (> org-self-insert-command-undo-counter 0)
20159 buffer-undo-list (listp buffer-undo-list)
20160 (not (cadr buffer-undo-list)) ; remove nil entry
20161 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20162 (setq org-self-insert-command-undo-counter
20163 (1+ org-self-insert-command-undo-counter))))))))
20165 (defun org-check-before-invisible-edit (kind)
20166 "Check is editing if kind KIND would be dangerous with invisible text around.
20167 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20168 ;; First, try to get out of here as quickly as possible, to reduce overhead
20169 (when (and org-catch-invisible-edits
20170 (or (not (boundp 'visible-mode)) (not visible-mode))
20171 (or (get-char-property (point) 'invisible)
20172 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20173 ;; OK, we need to take a closer look
20174 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20175 (invisible-before-point (unless (bobp) (get-char-property
20176 (1- (point)) 'invisible)))
20177 (border-and-ok-direction
20179 ;; Check if we are acting predictably before invisible text
20180 (and invisible-at-point (not invisible-before-point)
20181 (memq kind '(insert delete-backward)))
20182 ;; Check if we are acting predictably after invisible text
20183 ;; This works not well, and I have turned it off. It seems
20184 ;; better to always show and stop after invisible text.
20185 ;; (and (not invisible-at-point) invisible-before-point
20186 ;; (memq kind '(insert delete)))
20188 (when (or (memq invisible-at-point '(outline org-hide-block t))
20189 (memq invisible-before-point '(outline org-hide-block t)))
20190 (when (eq org-catch-invisible-edits 'error)
20191 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20192 (if (and org-custom-properties-overlays
20193 (y-or-n-p "Display invisible properties in this buffer? "))
20194 (org-toggle-custom-properties-visibility)
20195 ;; Make the area visible
20196 (save-excursion
20197 (when invisible-before-point
20198 (goto-char (previous-single-char-property-change
20199 (point) 'invisible)))
20200 (outline-show-subtree))
20201 (cond
20202 ((eq org-catch-invisible-edits 'show)
20203 ;; That's it, we do the edit after showing
20204 (message
20205 "Unfolding invisible region around point before editing")
20206 (sit-for 1))
20207 ((and (eq org-catch-invisible-edits 'smart)
20208 border-and-ok-direction)
20209 (message "Unfolding invisible region around point before editing"))
20211 ;; Don't do the edit, make the user repeat it in full visibility
20212 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20214 (defun org-fix-tags-on-the-fly ()
20215 (when (and (equal (char-after (point-at-bol)) ?*)
20216 (org-at-heading-p))
20217 (org-align-tags-here org-tags-column)))
20219 (defun org-delete-backward-char (N)
20220 "Like `delete-backward-char', insert whitespace at field end in tables.
20221 When deleting backwards, in tables this function will insert whitespace in
20222 front of the next \"|\" separator, to keep the table aligned. The table will
20223 still be marked for re-alignment if the field did fill the entire column,
20224 because, in this case the deletion might narrow the column."
20225 (interactive "p")
20226 (save-match-data
20227 (org-check-before-invisible-edit 'delete-backward)
20228 (if (and (org-at-table-p)
20229 (eq N 1)
20230 (string-match "|" (buffer-substring (point-at-bol) (point)))
20231 (looking-at ".*?|"))
20232 (let ((pos (point))
20233 (noalign (looking-at "[^|\n\r]* |"))
20234 (c org-table-may-need-update))
20235 (backward-delete-char N)
20236 (unless overwrite-mode
20237 (skip-chars-forward "^|")
20238 (insert " ")
20239 (goto-char (1- pos)))
20240 ;; noalign: if there were two spaces at the end, this field
20241 ;; does not determine the width of the column.
20242 (when noalign (setq org-table-may-need-update c)))
20243 (backward-delete-char N)
20244 (org-fix-tags-on-the-fly))))
20246 (defun org-delete-char (N)
20247 "Like `delete-char', but insert whitespace at field end in tables.
20248 When deleting characters, in tables this function will insert whitespace in
20249 front of the next \"|\" separator, to keep the table aligned. The table will
20250 still be marked for re-alignment if the field did fill the entire column,
20251 because, in this case the deletion might narrow the column."
20252 (interactive "p")
20253 (save-match-data
20254 (org-check-before-invisible-edit 'delete)
20255 (if (and (org-at-table-p)
20256 (not (bolp))
20257 (not (= (char-after) ?|))
20258 (eq N 1))
20259 (if (looking-at ".*?|")
20260 (let ((pos (point))
20261 (noalign (looking-at "[^|\n\r]* |"))
20262 (c org-table-may-need-update))
20263 (replace-match
20264 (concat (substring (match-string 0) 1 -1) " |") nil t)
20265 (goto-char pos)
20266 ;; noalign: if there were two spaces at the end, this field
20267 ;; does not determine the width of the column.
20268 (when noalign (setq org-table-may-need-update c)))
20269 (delete-char N))
20270 (delete-char N)
20271 (org-fix-tags-on-the-fly))))
20273 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20274 (put 'org-self-insert-command 'delete-selection
20275 (lambda ()
20276 (not (run-hook-with-args-until-success
20277 'self-insert-uses-region-functions))))
20278 (put 'orgtbl-self-insert-command 'delete-selection
20279 (lambda ()
20280 (not (run-hook-with-args-until-success
20281 'self-insert-uses-region-functions))))
20282 (put 'org-delete-char 'delete-selection 'supersede)
20283 (put 'org-delete-backward-char 'delete-selection 'supersede)
20284 (put 'org-yank 'delete-selection 'yank)
20286 ;; Make `flyspell-mode' delay after some commands
20287 (put 'org-self-insert-command 'flyspell-delayed t)
20288 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20289 (put 'org-delete-char 'flyspell-delayed t)
20290 (put 'org-delete-backward-char 'flyspell-delayed t)
20292 ;; Make pabbrev-mode expand after org-mode commands
20293 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20294 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20296 (defun org-remap (map &rest commands)
20297 "In MAP, remap the functions given in COMMANDS.
20298 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20299 (let (new old)
20300 (while commands
20301 (setq old (pop commands) new (pop commands))
20302 (if (fboundp 'command-remapping)
20303 (org-defkey map (vector 'remap old) new)
20304 (substitute-key-definition old new map global-map)))))
20306 (defun org-transpose-words ()
20307 "Transpose words for Org.
20308 This uses the `org-mode-transpose-word-syntax-table' syntax
20309 table, which interprets characters in `org-emphasis-alist' as
20310 word constituents."
20311 (interactive)
20312 (with-syntax-table org-mode-transpose-word-syntax-table
20313 (call-interactively 'transpose-words)))
20314 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20316 (when (eq org-enable-table-editor 'optimized)
20317 ;; If the user wants maximum table support, we need to hijack
20318 ;; some standard editing functions
20319 (org-remap org-mode-map
20320 'self-insert-command 'org-self-insert-command
20321 'delete-char 'org-delete-char
20322 'delete-backward-char 'org-delete-backward-char)
20323 (org-defkey org-mode-map "|" 'org-force-self-insert))
20325 (defvar org-ctrl-c-ctrl-c-hook nil
20326 "Hook for functions attaching themselves to `C-c C-c'.
20328 This can be used to add additional functionality to the C-c C-c
20329 key which executes context-dependent commands. This hook is run
20330 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20331 run after the last test.
20333 Each function will be called with no arguments. The function
20334 must check if the context is appropriate for it to act. If yes,
20335 it should do its thing and then return a non-nil value. If the
20336 context is wrong, just do nothing and return nil.")
20338 (defvar org-ctrl-c-ctrl-c-final-hook nil
20339 "Hook for functions attaching themselves to `C-c C-c'.
20341 This can be used to add additional functionality to the C-c C-c
20342 key which executes context-dependent commands. This hook is run
20343 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20344 before the first test.
20346 Each function will be called with no arguments. The function
20347 must check if the context is appropriate for it to act. If yes,
20348 it should do its thing and then return a non-nil value. If the
20349 context is wrong, just do nothing and return nil.")
20351 (defvar org-tab-first-hook nil
20352 "Hook for functions to attach themselves to TAB.
20353 See `org-ctrl-c-ctrl-c-hook' for more information.
20354 This hook runs as the first action when TAB is pressed, even before
20355 `org-cycle' messes around with the `outline-regexp' to cater for
20356 inline tasks and plain list item folding.
20357 If any function in this hook returns t, any other actions that
20358 would have been caused by TAB (such as table field motion or visibility
20359 cycling) will not occur.")
20361 (defvar org-tab-after-check-for-table-hook nil
20362 "Hook for functions to attach themselves to TAB.
20363 See `org-ctrl-c-ctrl-c-hook' for more information.
20364 This hook runs after it has been established that the cursor is not in a
20365 table, but before checking if the cursor is in a headline or if global cycling
20366 should be done.
20367 If any function in this hook returns t, not other actions like visibility
20368 cycling will be done.")
20370 (defvar org-tab-after-check-for-cycling-hook nil
20371 "Hook for functions to attach themselves to TAB.
20372 See `org-ctrl-c-ctrl-c-hook' for more information.
20373 This hook runs after it has been established that not table field motion and
20374 not visibility should be done because of current context. This is probably
20375 the place where a package like yasnippets can hook in.")
20377 (defvar org-tab-before-tab-emulation-hook nil
20378 "Hook for functions to attach themselves to TAB.
20379 See `org-ctrl-c-ctrl-c-hook' for more information.
20380 This hook runs after every other options for TAB have been exhausted, but
20381 before indentation and \t insertion takes place.")
20383 (defvar org-metaleft-hook nil
20384 "Hook for functions attaching themselves to `M-left'.
20385 See `org-ctrl-c-ctrl-c-hook' for more information.")
20386 (defvar org-metaright-hook nil
20387 "Hook for functions attaching themselves to `M-right'.
20388 See `org-ctrl-c-ctrl-c-hook' for more information.")
20389 (defvar org-metaup-hook nil
20390 "Hook for functions attaching themselves to `M-up'.
20391 See `org-ctrl-c-ctrl-c-hook' for more information.")
20392 (defvar org-metadown-hook nil
20393 "Hook for functions attaching themselves to `M-down'.
20394 See `org-ctrl-c-ctrl-c-hook' for more information.")
20395 (defvar org-shiftmetaleft-hook nil
20396 "Hook for functions attaching themselves to `M-S-left'.
20397 See `org-ctrl-c-ctrl-c-hook' for more information.")
20398 (defvar org-shiftmetaright-hook nil
20399 "Hook for functions attaching themselves to `M-S-right'.
20400 See `org-ctrl-c-ctrl-c-hook' for more information.")
20401 (defvar org-shiftmetaup-hook nil
20402 "Hook for functions attaching themselves to `M-S-up'.
20403 See `org-ctrl-c-ctrl-c-hook' for more information.")
20404 (defvar org-shiftmetadown-hook nil
20405 "Hook for functions attaching themselves to `M-S-down'.
20406 See `org-ctrl-c-ctrl-c-hook' for more information.")
20407 (defvar org-metareturn-hook nil
20408 "Hook for functions attaching themselves to `M-RET'.
20409 See `org-ctrl-c-ctrl-c-hook' for more information.")
20410 (defvar org-shiftup-hook nil
20411 "Hook for functions attaching themselves to `S-up'.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.")
20413 (defvar org-shiftup-final-hook nil
20414 "Hook for functions attaching themselves to `S-up'.
20415 This one runs after all other options except shift-select have been excluded.
20416 See `org-ctrl-c-ctrl-c-hook' for more information.")
20417 (defvar org-shiftdown-hook nil
20418 "Hook for functions attaching themselves to `S-down'.
20419 See `org-ctrl-c-ctrl-c-hook' for more information.")
20420 (defvar org-shiftdown-final-hook nil
20421 "Hook for functions attaching themselves to `S-down'.
20422 This one runs after all other options except shift-select have been excluded.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftleft-hook nil
20425 "Hook for functions attaching themselves to `S-left'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-shiftleft-final-hook nil
20428 "Hook for functions attaching themselves to `S-left'.
20429 This one runs after all other options except shift-select have been excluded.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftright-hook nil
20432 "Hook for functions attaching themselves to `S-right'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftright-final-hook nil
20435 "Hook for functions attaching themselves to `S-right'.
20436 This one runs after all other options except shift-select have been excluded.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20439 (defun org-modifier-cursor-error ()
20440 "Throw an error, a modified cursor command was applied in wrong context."
20441 (user-error "This command is active in special context like tables, headlines or items"))
20443 (defun org-shiftselect-error ()
20444 "Throw an error because Shift-Cursor command was applied in wrong context."
20445 (if (and (boundp 'shift-select-mode) shift-select-mode)
20446 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20447 (user-error "This command works only in special context like headlines or timestamps")))
20449 (defun org-call-for-shift-select (cmd)
20450 (let ((this-command-keys-shift-translated t))
20451 (call-interactively cmd)))
20453 (defun org-shifttab (&optional arg)
20454 "Global visibility cycling or move to previous table field.
20455 Call `org-table-previous-field' within a table.
20456 When ARG is nil, cycle globally through visibility states.
20457 When ARG is a numeric prefix, show contents of this level."
20458 (interactive "P")
20459 (cond
20460 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20461 ((integerp arg)
20462 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20463 (message "Content view to level: %d" arg)
20464 (org-content (prefix-numeric-value arg2))
20465 (org-cycle-show-empty-lines t)
20466 (setq org-cycle-global-status 'overview)))
20467 (t (call-interactively 'org-global-cycle))))
20469 (defun org-shiftmetaleft ()
20470 "Promote subtree or delete table column.
20471 Calls `org-promote-subtree', `org-outdent-item-tree', or
20472 `org-table-delete-column', depending on context. See the
20473 individual commands for more information."
20474 (interactive)
20475 (cond
20476 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20477 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20478 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20479 ((if (not (org-region-active-p)) (org-at-item-p)
20480 (save-excursion (goto-char (region-beginning))
20481 (org-at-item-p)))
20482 (call-interactively 'org-outdent-item-tree))
20483 (t (org-modifier-cursor-error))))
20485 (defun org-shiftmetaright ()
20486 "Demote subtree or insert table column.
20487 Calls `org-demote-subtree', `org-indent-item-tree', or
20488 `org-table-insert-column', depending on context. See the
20489 individual commands for more information."
20490 (interactive)
20491 (cond
20492 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20493 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20494 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20495 ((if (not (org-region-active-p)) (org-at-item-p)
20496 (save-excursion (goto-char (region-beginning))
20497 (org-at-item-p)))
20498 (call-interactively 'org-indent-item-tree))
20499 (t (org-modifier-cursor-error))))
20501 (defun org-shiftmetaup (&optional _arg)
20502 "Drag the line at point up.
20503 In a table, kill the current row.
20504 On a clock timestamp, update the value of the timestamp like `S-<up>'
20505 but also adjust the previous clocked item in the clock history.
20506 Everywhere else, drag the line at point up."
20507 (interactive "P")
20508 (cond
20509 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20510 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20511 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20512 (call-interactively 'org-timestamp-up)))
20513 (t (call-interactively 'org-drag-line-backward))))
20515 (defun org-shiftmetadown (&optional _arg)
20516 "Drag the line at point down.
20517 In a table, insert an empty row at the current line.
20518 On a clock timestamp, update the value of the timestamp like `S-<down>'
20519 but also adjust the previous clocked item in the clock history.
20520 Everywhere else, drag the line at point down."
20521 (interactive "P")
20522 (cond
20523 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20524 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20525 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20526 (call-interactively 'org-timestamp-down)))
20527 (t (call-interactively 'org-drag-line-forward))))
20529 (defsubst org-hidden-tree-error ()
20530 (user-error
20531 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20533 (defun org-metaleft (&optional _arg)
20534 "Promote heading, list item at point or move table column left.
20536 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20537 depending on context. With no specific context, calls the Emacs
20538 default `backward-word'. See the individual commands for more
20539 information.
20541 This function runs the hook `org-metaleft-hook' as a first step,
20542 and returns at first non-nil value."
20543 (interactive "P")
20544 (cond
20545 ((run-hook-with-args-until-success 'org-metaleft-hook))
20546 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20547 ((org-with-limited-levels
20548 (or (org-at-heading-p)
20549 (and (org-region-active-p)
20550 (save-excursion
20551 (goto-char (region-beginning))
20552 (org-at-heading-p)))))
20553 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20554 (call-interactively 'org-do-promote))
20555 ;; At an inline task.
20556 ((org-at-heading-p)
20557 (call-interactively 'org-inlinetask-promote))
20558 ((or (org-at-item-p)
20559 (and (org-region-active-p)
20560 (save-excursion
20561 (goto-char (region-beginning))
20562 (org-at-item-p))))
20563 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20564 (call-interactively 'org-outdent-item))
20565 (t (call-interactively 'backward-word))))
20567 (defun org-metaright (&optional _arg)
20568 "Demote heading, list item at point or move table column right.
20570 In front of a drawer or a block keyword, indent it correctly.
20572 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20573 `org-indnet-drawer' or `org-indent-block' depending on context.
20574 With no specific context, calls the Emacs default `forward-word'.
20575 See the individual commands for more information.
20577 This function runs the hook `org-metaright-hook' as a first step,
20578 and returns at first non-nil value."
20579 (interactive "P")
20580 (cond
20581 ((run-hook-with-args-until-success 'org-metaright-hook))
20582 ((org-at-table-p) (call-interactively 'org-table-move-column))
20583 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20584 ((org-at-block-p) (call-interactively 'org-indent-block))
20585 ((org-with-limited-levels
20586 (or (org-at-heading-p)
20587 (and (org-region-active-p)
20588 (save-excursion
20589 (goto-char (region-beginning))
20590 (org-at-heading-p)))))
20591 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20592 (call-interactively 'org-do-demote))
20593 ;; At an inline task.
20594 ((org-at-heading-p)
20595 (call-interactively 'org-inlinetask-demote))
20596 ((or (org-at-item-p)
20597 (and (org-region-active-p)
20598 (save-excursion
20599 (goto-char (region-beginning))
20600 (org-at-item-p))))
20601 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20602 (call-interactively 'org-indent-item))
20603 (t (call-interactively 'forward-word))))
20605 (defun org-check-for-hidden (what)
20606 "Check if there are hidden headlines/items in the current visual line.
20607 WHAT can be either `headlines' or `items'. If the current line is
20608 an outline or item heading and it has a folded subtree below it,
20609 this function returns t, nil otherwise."
20610 (let ((re (cond
20611 ((eq what 'headlines) org-outline-regexp-bol)
20612 ((eq what 'items) (org-item-beginning-re))
20613 (t (error "This should not happen"))))
20614 beg end)
20615 (save-excursion
20616 (catch 'exit
20617 (unless (org-region-active-p)
20618 (setq beg (point-at-bol))
20619 (beginning-of-line 2)
20620 (while (and (not (eobp)) ;; this is like `next-line'
20621 (get-char-property (1- (point)) 'invisible))
20622 (beginning-of-line 2))
20623 (setq end (point))
20624 (goto-char beg)
20625 (goto-char (point-at-eol))
20626 (setq end (max end (point)))
20627 (while (re-search-forward re end t)
20628 (when (get-char-property (match-beginning 0) 'invisible)
20629 (throw 'exit t))))
20630 nil))))
20632 (defun org-metaup (&optional _arg)
20633 "Move subtree up or move table row up.
20634 Calls `org-move-subtree-up' or `org-table-move-row' or
20635 `org-move-item-up', depending on context. See the individual commands
20636 for more information."
20637 (interactive "P")
20638 (cond
20639 ((run-hook-with-args-until-success 'org-metaup-hook))
20640 ((org-region-active-p)
20641 (let* ((a (min (region-beginning) (region-end)))
20642 (b (1- (max (region-beginning) (region-end))))
20643 (c (save-excursion (goto-char a)
20644 (move-beginning-of-line 0)))
20645 (d (save-excursion (goto-char a)
20646 (move-end-of-line 0) (point))))
20647 (transpose-regions a b c d)
20648 (goto-char c)))
20649 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20650 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20651 ((org-at-item-p) (call-interactively 'org-move-item-up))
20652 (t (org-drag-element-backward))))
20654 (defun org-metadown (&optional _arg)
20655 "Move subtree down or move table row down.
20656 Calls `org-move-subtree-down' or `org-table-move-row' or
20657 `org-move-item-down', depending on context. See the individual
20658 commands for more information."
20659 (interactive "P")
20660 (cond
20661 ((run-hook-with-args-until-success 'org-metadown-hook))
20662 ((org-region-active-p)
20663 (let* ((a (min (region-beginning) (region-end)))
20664 (b (max (region-beginning) (region-end)))
20665 (c (save-excursion (goto-char b)
20666 (move-beginning-of-line 1)))
20667 (d (save-excursion (goto-char b)
20668 (move-end-of-line 1) (1+ (point)))))
20669 (transpose-regions a b c d)
20670 (goto-char d)))
20671 ((org-at-table-p) (call-interactively 'org-table-move-row))
20672 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20673 ((org-at-item-p) (call-interactively 'org-move-item-down))
20674 (t (org-drag-element-forward))))
20676 (defun org-shiftup (&optional arg)
20677 "Increase item in timestamp or increase priority of current headline.
20678 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20679 depending on context. See the individual commands for more information."
20680 (interactive "P")
20681 (cond
20682 ((run-hook-with-args-until-success 'org-shiftup-hook))
20683 ((and org-support-shift-select (org-region-active-p))
20684 (org-call-for-shift-select 'previous-line))
20685 ((org-at-timestamp-p t)
20686 (call-interactively (if org-edit-timestamp-down-means-later
20687 'org-timestamp-down 'org-timestamp-up)))
20688 ((and (not (eq org-support-shift-select 'always))
20689 org-enable-priority-commands
20690 (org-at-heading-p))
20691 (call-interactively 'org-priority-up))
20692 ((and (not org-support-shift-select) (org-at-item-p))
20693 (call-interactively 'org-previous-item))
20694 ((org-clocktable-try-shift 'up arg))
20695 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20696 (org-support-shift-select
20697 (org-call-for-shift-select 'previous-line))
20698 (t (org-shiftselect-error))))
20700 (defun org-shiftdown (&optional arg)
20701 "Decrease item in timestamp or decrease priority of current headline.
20702 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20703 depending on context. See the individual commands for more information."
20704 (interactive "P")
20705 (cond
20706 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20707 ((and org-support-shift-select (org-region-active-p))
20708 (org-call-for-shift-select 'next-line))
20709 ((org-at-timestamp-p t)
20710 (call-interactively (if org-edit-timestamp-down-means-later
20711 'org-timestamp-up 'org-timestamp-down)))
20712 ((and (not (eq org-support-shift-select 'always))
20713 org-enable-priority-commands
20714 (org-at-heading-p))
20715 (call-interactively 'org-priority-down))
20716 ((and (not org-support-shift-select) (org-at-item-p))
20717 (call-interactively 'org-next-item))
20718 ((org-clocktable-try-shift 'down arg))
20719 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20720 (org-support-shift-select
20721 (org-call-for-shift-select 'next-line))
20722 (t (org-shiftselect-error))))
20724 (defun org-shiftright (&optional arg)
20725 "Cycle the thing at point or in the current line, depending on context.
20726 Depending on context, this does one of the following:
20728 - switch a timestamp at point one day into the future
20729 - on a headline, switch to the next TODO keyword.
20730 - on an item, switch entire list to the next bullet type
20731 - on a property line, switch to the next allowed value
20732 - on a clocktable definition line, move time block into the future"
20733 (interactive "P")
20734 (cond
20735 ((run-hook-with-args-until-success 'org-shiftright-hook))
20736 ((and org-support-shift-select (org-region-active-p))
20737 (org-call-for-shift-select 'forward-char))
20738 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20739 ((and (not (eq org-support-shift-select 'always))
20740 (org-at-heading-p))
20741 (let ((org-inhibit-logging
20742 (not org-treat-S-cursor-todo-selection-as-state-change))
20743 (org-inhibit-blocking
20744 (not org-treat-S-cursor-todo-selection-as-state-change)))
20745 (org-call-with-arg 'org-todo 'right)))
20746 ((or (and org-support-shift-select
20747 (not (eq org-support-shift-select 'always))
20748 (org-at-item-bullet-p))
20749 (and (not org-support-shift-select) (org-at-item-p)))
20750 (org-call-with-arg 'org-cycle-list-bullet nil))
20751 ((and (not (eq org-support-shift-select 'always))
20752 (org-at-property-p))
20753 (call-interactively 'org-property-next-allowed-value))
20754 ((org-clocktable-try-shift 'right arg))
20755 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20756 (org-support-shift-select
20757 (org-call-for-shift-select 'forward-char))
20758 (t (org-shiftselect-error))))
20760 (defun org-shiftleft (&optional arg)
20761 "Cycle the thing at point or in the current line, depending on context.
20762 Depending on context, this does one of the following:
20764 - switch a timestamp at point one day into the past
20765 - on a headline, switch to the previous TODO keyword.
20766 - on an item, switch entire list to the previous bullet type
20767 - on a property line, switch to the previous allowed value
20768 - on a clocktable definition line, move time block into the past"
20769 (interactive "P")
20770 (cond
20771 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20772 ((and org-support-shift-select (org-region-active-p))
20773 (org-call-for-shift-select 'backward-char))
20774 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20775 ((and (not (eq org-support-shift-select 'always))
20776 (org-at-heading-p))
20777 (let ((org-inhibit-logging
20778 (not org-treat-S-cursor-todo-selection-as-state-change))
20779 (org-inhibit-blocking
20780 (not org-treat-S-cursor-todo-selection-as-state-change)))
20781 (org-call-with-arg 'org-todo 'left)))
20782 ((or (and org-support-shift-select
20783 (not (eq org-support-shift-select 'always))
20784 (org-at-item-bullet-p))
20785 (and (not org-support-shift-select) (org-at-item-p)))
20786 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20787 ((and (not (eq org-support-shift-select 'always))
20788 (org-at-property-p))
20789 (call-interactively 'org-property-previous-allowed-value))
20790 ((org-clocktable-try-shift 'left arg))
20791 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20792 (org-support-shift-select
20793 (org-call-for-shift-select 'backward-char))
20794 (t (org-shiftselect-error))))
20796 (defun org-shiftcontrolright ()
20797 "Switch to next TODO set."
20798 (interactive)
20799 (cond
20800 ((and org-support-shift-select (org-region-active-p))
20801 (org-call-for-shift-select 'forward-word))
20802 ((and (not (eq org-support-shift-select 'always))
20803 (org-at-heading-p))
20804 (org-call-with-arg 'org-todo 'nextset))
20805 (org-support-shift-select
20806 (org-call-for-shift-select 'forward-word))
20807 (t (org-shiftselect-error))))
20809 (defun org-shiftcontrolleft ()
20810 "Switch to previous TODO set."
20811 (interactive)
20812 (cond
20813 ((and org-support-shift-select (org-region-active-p))
20814 (org-call-for-shift-select 'backward-word))
20815 ((and (not (eq org-support-shift-select 'always))
20816 (org-at-heading-p))
20817 (org-call-with-arg 'org-todo 'previousset))
20818 (org-support-shift-select
20819 (org-call-for-shift-select 'backward-word))
20820 (t (org-shiftselect-error))))
20822 (defun org-shiftcontrolup (&optional n)
20823 "Change timestamps synchronously up in CLOCK log lines.
20824 Optional argument N tells to change by that many units."
20825 (interactive "P")
20826 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20827 (let (org-support-shift-select)
20828 (org-clock-timestamps-up n))
20829 (user-error "Not at a clock log")))
20831 (defun org-shiftcontroldown (&optional n)
20832 "Change timestamps synchronously down in CLOCK log lines.
20833 Optional argument N tells to change by that many units."
20834 (interactive "P")
20835 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20836 (let (org-support-shift-select)
20837 (org-clock-timestamps-down n))
20838 (user-error "Not at a clock log")))
20840 (defun org-increase-number-at-point (&optional inc)
20841 "Increment the number at point.
20842 With an optional prefix numeric argument INC, increment using
20843 this numeric value."
20844 (interactive "p")
20845 (if (not (number-at-point))
20846 (user-error "Not on a number")
20847 (unless inc (setq inc 1))
20848 (let ((pos (point))
20849 (beg (skip-chars-backward "-+^/*0-9eE."))
20850 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20851 (setq nap (buffer-substring-no-properties
20852 (+ pos beg) (+ pos beg end)))
20853 (delete-region (+ pos beg) (+ pos beg end))
20854 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20855 (when (org-at-table-p)
20856 (org-table-align)
20857 (org-table-end-of-field 1))))
20859 (defun org-decrease-number-at-point (&optional inc)
20860 "Decrement the number at point.
20861 With an optional prefix numeric argument INC, decrement using
20862 this numeric value."
20863 (interactive "p")
20864 (org-increase-number-at-point (- (or inc 1))))
20866 (defun org-ctrl-c-ret ()
20867 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20868 (interactive)
20869 (cond
20870 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20871 (t (call-interactively 'org-insert-heading))))
20873 (defun org-find-visible ()
20874 (let ((s (point)))
20875 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20876 (get-char-property s 'invisible)))
20878 (defun org-find-invisible ()
20879 (let ((s (point)))
20880 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20881 (not (get-char-property s 'invisible))))
20884 (defun org-copy-visible (beg end)
20885 "Copy the visible parts of the region."
20886 (interactive "r")
20887 (let (snippets s)
20888 (save-excursion
20889 (save-restriction
20890 (narrow-to-region beg end)
20891 (setq s (goto-char (point-min)))
20892 (while (not (= (point) (point-max)))
20893 (goto-char (org-find-invisible))
20894 (push (buffer-substring s (point)) snippets)
20895 (setq s (goto-char (org-find-visible))))))
20896 (kill-new (apply 'concat (nreverse snippets)))))
20898 (defun org-copy-special ()
20899 "Copy region in table or copy current subtree.
20900 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20901 See the individual commands for more information."
20902 (interactive)
20903 (call-interactively
20904 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20906 (defun org-cut-special ()
20907 "Cut region in table or cut current subtree.
20908 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20909 See the individual commands for more information."
20910 (interactive)
20911 (call-interactively
20912 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20914 (defun org-paste-special (arg)
20915 "Paste rectangular region into table, or past subtree relative to level.
20916 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20917 See the individual commands for more information."
20918 (interactive "P")
20919 (if (org-at-table-p)
20920 (org-table-paste-rectangle)
20921 (org-paste-subtree arg)))
20923 (defsubst org-in-fixed-width-region-p ()
20924 "Is point in a fixed-width region?"
20925 (save-match-data
20926 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20928 (defun org-edit-special (&optional arg)
20929 "Call a special editor for the element at point.
20930 When at a table, call the formula editor with `org-table-edit-formulas'.
20931 When in a source code block, call `org-edit-src-code'.
20932 When in a fixed-width region, call `org-edit-fixed-width-region'.
20933 When in an export block, call `org-edit-export-block'.
20934 When at an #+INCLUDE keyword, visit the included file.
20935 When at a footnote reference, call `org-edit-footnote-reference'
20936 On a link, call `ffap' to visit the link at point.
20937 Otherwise, return a user error."
20938 (interactive "P")
20939 (let ((element (org-element-at-point)))
20940 (assert (not buffer-read-only) nil
20941 "Buffer is read-only: %s" (buffer-name))
20942 (pcase (org-element-type element)
20943 (`src-block
20944 (if (not arg) (org-edit-src-code)
20945 (let* ((info (org-babel-get-src-block-info))
20946 (lang (nth 0 info))
20947 (params (nth 2 info))
20948 (session (cdr (assq :session params))))
20949 (if (not session) (org-edit-src-code)
20950 ;; At a src-block with a session and function called with
20951 ;; an ARG: switch to the buffer related to the inferior
20952 ;; process.
20953 (switch-to-buffer
20954 (funcall (intern (concat "org-babel-prep-session:" lang))
20955 session params))))))
20956 (`keyword
20957 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20958 (org-open-link-from-string
20959 (format "[[%s]]"
20960 (expand-file-name
20961 (let ((value (org-element-property :value element)))
20962 (cond ((not (org-string-nw-p value))
20963 (user-error "No file to edit"))
20964 ((string-match "\\`\"\\(.*?\\)\"" value)
20965 (match-string 1 value))
20966 ((string-match "\\`[^ \t\"]\\S-*" value)
20967 (match-string 0 value))
20968 (t (user-error "No valid file specified")))))))
20969 (user-error "No special environment to edit here")))
20970 (`table
20971 (if (eq (org-element-property :type element) 'table.el)
20972 (org-edit-table.el)
20973 (call-interactively 'org-table-edit-formulas)))
20974 ;; Only Org tables contain `table-row' type elements.
20975 (`table-row (call-interactively 'org-table-edit-formulas))
20976 (`example-block (org-edit-src-code))
20977 (`export-block (org-edit-export-block))
20978 (`fixed-width (org-edit-fixed-width-region))
20980 ;; No notable element at point. Though, we may be at a link or
20981 ;; a footnote reference, which are objects. Thus, scan deeper.
20982 (let ((context (org-element-context element)))
20983 (pcase (org-element-type context)
20984 (`footnote-reference (org-edit-footnote-reference))
20985 (`inline-src-block (org-edit-inline-src-code))
20986 (`link (call-interactively #'ffap))
20987 (_ (user-error "No special environment to edit here"))))))))
20989 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20990 (defun org-ctrl-c-ctrl-c (&optional arg)
20991 "Set tags in headline, or update according to changed information at point.
20993 This command does many different things, depending on context:
20995 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20996 this is what we do.
20998 - If the cursor is on a statistics cookie, update it.
21000 - If the cursor is in a headline, prompt for tags and insert them
21001 into the current line, aligned to `org-tags-column'. When called
21002 with prefix arg, realign all tags in the current buffer.
21004 - If the cursor is in one of the special #+KEYWORD lines, this
21005 triggers scanning the buffer for these lines and updating the
21006 information.
21008 - If the cursor is inside a table, realign the table. This command
21009 works even if the automatic table editor has been turned off.
21011 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21012 the entire table.
21014 - If the cursor is at a footnote reference or definition, jump to
21015 the corresponding definition or references, respectively.
21017 - If the cursor is a the beginning of a dynamic block, update it.
21019 - If the current buffer is a capture buffer, close note and file it.
21021 - If the cursor is on a <<<target>>>, update radio targets and
21022 corresponding links in this buffer.
21024 - If the cursor is on a numbered item in a plain list, renumber the
21025 ordered list.
21027 - If the cursor is on a checkbox, toggle it.
21029 - If the cursor is on a code block, evaluate it. The variable
21030 `org-confirm-babel-evaluate' can be used to control prompting
21031 before code block evaluation, by default every code block
21032 evaluation requires confirmation. Code block evaluation can be
21033 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21034 (interactive "P")
21035 (cond
21036 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21037 org-occur-highlights)
21038 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21039 (org-remove-occur-highlights)
21040 (message "Temporary highlights/overlays removed from current buffer"))
21041 ((and (local-variable-p 'org-finish-function (current-buffer))
21042 (fboundp org-finish-function))
21043 (funcall org-finish-function))
21044 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21046 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21047 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21048 (user-error "C-c C-c can do nothing useful at this location"))
21049 (let* ((context (org-element-context))
21050 (type (org-element-type context)))
21051 (case type
21052 ;; When at a link, act according to the parent instead.
21053 (link (setq context (org-element-property :parent context))
21054 (setq type (org-element-type context)))
21055 ;; Unsupported object types: refer to the first supported
21056 ;; element or object containing it.
21057 ((bold code entity export-snippet inline-babel-call inline-src-block
21058 italic latex-fragment line-break macro strike-through subscript
21059 superscript underline verbatim)
21060 (setq context
21061 (org-element-lineage
21062 context '(radio-target paragraph verse-block table-cell)))))
21063 ;; For convenience: at the first line of a paragraph on the
21064 ;; same line as an item, apply function on that item instead.
21065 (when (eq type 'paragraph)
21066 (let ((parent (org-element-property :parent context)))
21067 (when (and (eq (org-element-type parent) 'item)
21068 (= (line-beginning-position)
21069 (org-element-property :begin parent)))
21070 (setq context parent type 'item))))
21071 ;; Act according to type of element or object at point.
21072 (case type
21073 (clock (org-clock-update-time-maybe))
21074 (dynamic-block
21075 (save-excursion
21076 (goto-char (org-element-property :post-affiliated context))
21077 (org-update-dblock)))
21078 (footnote-definition
21079 (goto-char (org-element-property :post-affiliated context))
21080 (call-interactively 'org-footnote-action))
21081 (footnote-reference (call-interactively 'org-footnote-action))
21082 ((headline inlinetask)
21083 (save-excursion (goto-char (org-element-property :begin context))
21084 (call-interactively 'org-set-tags)))
21085 (item
21086 ;; At an item: a double C-u set checkbox to "[-]"
21087 ;; unconditionally, whereas a single one will toggle its
21088 ;; presence. Without a universal argument, if the item
21089 ;; has a checkbox, toggle it. Otherwise repair the list.
21090 (let* ((box (org-element-property :checkbox context))
21091 (struct (org-element-property :structure context))
21092 (old-struct (copy-tree struct))
21093 (parents (org-list-parents-alist struct))
21094 (prevs (org-list-prevs-alist struct))
21095 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21096 (org-list-set-checkbox
21097 (org-element-property :begin context) struct
21098 (cond ((equal arg '(16)) "[-]")
21099 ((and (not box) (equal arg '(4))) "[ ]")
21100 ((or (not box) (equal arg '(4))) nil)
21101 ((eq box 'on) "[ ]")
21102 (t "[X]")))
21103 ;; Mimic `org-list-write-struct' but with grabbing
21104 ;; a return value from `org-list-struct-fix-box'.
21105 (org-list-struct-fix-ind struct parents 2)
21106 (org-list-struct-fix-item-end struct)
21107 (org-list-struct-fix-bul struct prevs)
21108 (org-list-struct-fix-ind struct parents)
21109 (let ((block-item
21110 (org-list-struct-fix-box struct parents prevs orderedp)))
21111 (if (and box (equal struct old-struct))
21112 (if (equal arg '(16))
21113 (message "Checkboxes already reset")
21114 (user-error "Cannot toggle this checkbox: %s"
21115 (if (eq box 'on)
21116 "all subitems checked"
21117 "unchecked subitems")))
21118 (org-list-struct-apply-struct struct old-struct)
21119 (org-update-checkbox-count-maybe))
21120 (when block-item
21121 (message "Checkboxes were removed due to empty box at line %d"
21122 (org-current-line block-item))))))
21123 (keyword
21124 (let ((org-inhibit-startup-visibility-stuff t)
21125 (org-startup-align-all-tables nil))
21126 (when (boundp 'org-table-coordinate-overlays)
21127 (mapc #'delete-overlay org-table-coordinate-overlays)
21128 (setq org-table-coordinate-overlays nil))
21129 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21130 (message "Local setup has been refreshed"))
21131 (plain-list
21132 ;; At a plain list, with a double C-u argument, set
21133 ;; checkboxes of each item to "[-]", whereas a single one
21134 ;; will toggle their presence according to the state of the
21135 ;; first item in the list. Without an argument, repair the
21136 ;; list.
21137 (let* ((begin (org-element-property :contents-begin context))
21138 (beginm (move-marker (make-marker) begin))
21139 (struct (org-element-property :structure context))
21140 (old-struct (copy-tree struct))
21141 (first-box (save-excursion
21142 (goto-char begin)
21143 (looking-at org-list-full-item-re)
21144 (match-string-no-properties 3)))
21145 (new-box (cond ((equal arg '(16)) "[-]")
21146 ((equal arg '(4)) (unless first-box "[ ]"))
21147 ((equal first-box "[X]") "[ ]")
21148 (t "[X]"))))
21149 (cond
21150 (arg
21151 (dolist (pos
21152 (org-list-get-all-items
21153 begin struct (org-list-prevs-alist struct)))
21154 (org-list-set-checkbox pos struct new-box)))
21155 ((and first-box (eq (point) begin))
21156 ;; For convenience, when point is at bol on the first
21157 ;; item of the list and no argument is provided, simply
21158 ;; toggle checkbox of that item, if any.
21159 (org-list-set-checkbox begin struct new-box)))
21160 (org-list-write-struct
21161 struct (org-list-parents-alist struct) old-struct)
21162 (org-update-checkbox-count-maybe)
21163 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21164 ((property-drawer node-property)
21165 (call-interactively 'org-property-action))
21166 ((radio-target target)
21167 (call-interactively 'org-update-radio-target-regexp))
21168 (statistics-cookie
21169 (call-interactively 'org-update-statistics-cookies))
21170 ((table table-cell table-row)
21171 ;; At a table, recalculate every field and align it. Also
21172 ;; send the table if necessary. If the table has
21173 ;; a `table.el' type, just give up. At a table row or
21174 ;; cell, maybe recalculate line but always align table.
21175 (if (eq (org-element-property :type context) 'table.el)
21176 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21177 Use \\[org-edit-special] to edit table.el tables"))
21178 (let ((org-enable-table-editor t))
21179 (if (or (eq type 'table)
21180 ;; Check if point is at a TBLFM line.
21181 (and (eq type 'table-row)
21182 (= (point) (org-element-property :end context))))
21183 (save-excursion
21184 (if (org-at-TBLFM-p)
21185 (progn (require 'org-table)
21186 (org-table-calc-current-TBLFM))
21187 (goto-char (org-element-property :contents-begin context))
21188 (org-call-with-arg 'org-table-recalculate (or arg t))
21189 (orgtbl-send-table 'maybe)))
21190 (org-table-maybe-eval-formula)
21191 (cond (arg (call-interactively 'org-table-recalculate))
21192 ((org-table-maybe-recalculate-line))
21193 (t (org-table-align)))))))
21194 (timestamp (org-timestamp-change 0 'day))
21195 (otherwise
21196 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21197 (user-error
21198 "C-c C-c can do nothing useful at this location")))))))))
21200 (defun org-mode-restart ()
21201 (interactive)
21202 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21203 (funcall major-mode)
21204 (hack-local-variables)
21205 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21206 (org-indent-mode -1)))
21207 (message "%s restarted" major-mode))
21209 (defun org-kill-note-or-show-branches ()
21210 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21211 (interactive)
21212 (if (not org-finish-function)
21213 (progn
21214 (outline-hide-subtree)
21215 (call-interactively 'outline-show-branches))
21216 (let ((org-note-abort t))
21217 (funcall org-finish-function))))
21219 (defun org-delete-indentation (&optional ARG)
21220 "Join current line to previous and fix whitespace at join.
21222 If previous line is a headline add to headline title. Otherwise
21223 the function calls `delete-indentation'.
21225 With argument, join this line to following line."
21226 (interactive "*P")
21227 (if (save-excursion
21228 (if ARG (beginning-of-line)
21229 (forward-line -1))
21230 (looking-at org-complex-heading-regexp))
21231 ;; At headline.
21232 (let ((tags-column (when (match-beginning 5)
21233 (save-excursion (goto-char (match-beginning 5))
21234 (current-column))))
21235 (string (concat " " (progn (when ARG (forward-line 1))
21236 (org-trim (delete-and-extract-region
21237 (line-beginning-position)
21238 (line-end-position)))))))
21239 (unless (bobp) (delete-region (point) (1- (point))))
21240 (goto-char (or (match-end 4)
21241 (match-beginning 5)
21242 (match-end 0)))
21243 (skip-chars-backward " \t")
21244 (save-excursion (insert string))
21245 ;; Adjust alignment of tags.
21246 (when tags-column
21247 (org-align-tags-here (if org-auto-align-tags
21248 org-tags-column
21249 tags-column))))
21250 (delete-indentation ARG)))
21252 (defun org-open-line (n)
21253 "Insert a new row in tables, call `open-line' elsewhere.
21254 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21255 (interactive "*p")
21256 (cond
21257 ((not org-special-ctrl-o)
21258 (open-line n))
21259 ((org-at-table-p)
21260 (org-table-insert-row))
21262 (open-line n))))
21264 (defun org-return (&optional indent)
21265 "Goto next table row or insert a newline.
21267 Calls `org-table-next-row' or `newline', depending on context.
21269 When optional INDENT argument is non-nil, call
21270 `newline-and-indent' instead of `newline'.
21272 When `org-return-follows-link' is non-nil and point is on
21273 a timestamp or a link, call `org-open-at-point'. However, it
21274 will not happen if point is in a table or on a \"dead\"
21275 object (e.g., within a comment). In these case, you need to use
21276 `org-open-at-point' directly."
21277 (interactive)
21278 (let ((context (if org-return-follows-link (org-element-context)
21279 (org-element-at-point))))
21280 (cond
21281 ;; In a table, call `org-table-next-row'.
21282 ((or (and (eq (org-element-type context) 'table)
21283 (>= (point) (org-element-property :contents-begin context))
21284 (< (point) (org-element-property :contents-end context)))
21285 (org-element-lineage context '(table-row table-cell) t))
21286 (org-table-justify-field-maybe)
21287 (call-interactively #'org-table-next-row))
21288 ;; On a link or a timestamp, call `org-open-at-point' if
21289 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21290 ;; locations, e.g., in a comment, as `org-open-at-point'.
21291 ((and org-return-follows-link
21292 (or (org-in-regexp org-ts-regexp-both nil t)
21293 (org-in-regexp org-tsr-regexp-both nil t)
21294 (org-in-regexp org-any-link-re nil t)))
21295 (call-interactively #'org-open-at-point))
21296 ;; Insert newline in heading, but preserve tags.
21297 ((and (not (bolp))
21298 (save-excursion (beginning-of-line)
21299 (looking-at org-complex-heading-regexp)))
21300 ;; At headline. Split line. However, if point is on keyword,
21301 ;; priority cookie or tags, do not break any of them: add
21302 ;; a newline after the headline instead.
21303 (let ((tags-column (and (match-beginning 5)
21304 (save-excursion (goto-char (match-beginning 5))
21305 (current-column))))
21306 (string
21307 (when (and (match-end 4)
21308 (>= (point)
21309 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21310 (<= (point) (match-end 4)))
21311 (delete-and-extract-region (point) (match-end 4)))))
21312 (when (and tags-column string) ; Adjust tag alignment.
21313 (org-align-tags-here
21314 (if org-auto-align-tags org-tags-column tags-column)))
21315 (end-of-line)
21316 (org-show-entry)
21317 (if indent (newline-and-indent) (newline))
21318 (when string (save-excursion (insert (org-trim string))))))
21319 ;; In a list, make sure indenting keeps trailing text within.
21320 ((and indent
21321 (not (eolp))
21322 (org-element-lineage context '(item)))
21323 (let ((trailing-data
21324 (delete-and-extract-region (point) (line-end-position))))
21325 (newline-and-indent)
21326 (save-excursion (insert trailing-data))))
21327 (t (if indent (newline-and-indent) (newline))))))
21329 (defun org-return-indent ()
21330 "Goto next table row or insert a newline and indent.
21331 Calls `org-table-next-row' or `newline-and-indent', depending on
21332 context. See the individual commands for more information."
21333 (interactive)
21334 (org-return t))
21336 (defun org-ctrl-c-star ()
21337 "Compute table, or change heading status of lines.
21338 Calls `org-table-recalculate' or `org-toggle-heading',
21339 depending on context."
21340 (interactive)
21341 (cond
21342 ((org-at-table-p)
21343 (call-interactively 'org-table-recalculate))
21345 ;; Convert all lines in region to list items
21346 (call-interactively 'org-toggle-heading))))
21348 (defun org-ctrl-c-minus ()
21349 "Insert separator line in table or modify bullet status of line.
21350 Also turns a plain line or a region of lines into list items.
21351 Calls `org-table-insert-hline', `org-toggle-item', or
21352 `org-cycle-list-bullet', depending on context."
21353 (interactive)
21354 (cond
21355 ((org-at-table-p)
21356 (call-interactively 'org-table-insert-hline))
21357 ((org-region-active-p)
21358 (call-interactively 'org-toggle-item))
21359 ((org-in-item-p)
21360 (call-interactively 'org-cycle-list-bullet))
21362 (call-interactively 'org-toggle-item))))
21364 (defun org-toggle-item (arg)
21365 "Convert headings or normal lines to items, items to normal lines.
21366 If there is no active region, only the current line is considered.
21368 If the first non blank line in the region is a headline, convert
21369 all headlines to items, shifting text accordingly.
21371 If it is an item, convert all items to normal lines.
21373 If it is normal text, change region into a list of items.
21374 With a prefix argument ARG, change the region in a single item."
21375 (interactive "P")
21376 (let ((shift-text
21377 (function
21378 ;; Shift text in current section to IND, from point to END.
21379 ;; The function leaves point to END line.
21380 (lambda (ind end)
21381 (let ((min-i 1000) (end (copy-marker end)))
21382 ;; First determine the minimum indentation (MIN-I) of
21383 ;; the text.
21384 (save-excursion
21385 (catch 'exit
21386 (while (< (point) end)
21387 (let ((i (org-get-indentation)))
21388 (cond
21389 ;; Skip blank lines and inline tasks.
21390 ((looking-at "^[ \t]*$"))
21391 ((looking-at org-outline-regexp-bol))
21392 ;; We can't find less than 0 indentation.
21393 ((zerop i) (throw 'exit (setq min-i 0)))
21394 ((< i min-i) (setq min-i i))))
21395 (forward-line))))
21396 ;; Then indent each line so that a line indented to
21397 ;; MIN-I becomes indented to IND. Ignore blank lines
21398 ;; and inline tasks in the process.
21399 (let ((delta (- ind min-i)))
21400 (while (< (point) end)
21401 (unless (or (looking-at "^[ \t]*$")
21402 (looking-at org-outline-regexp-bol))
21403 (org-indent-line-to (+ (org-get-indentation) delta)))
21404 (forward-line)))))))
21405 (skip-blanks
21406 (function
21407 ;; Return beginning of first non-blank line, starting from
21408 ;; line at POS.
21409 (lambda (pos)
21410 (save-excursion
21411 (goto-char pos)
21412 (skip-chars-forward " \r\t\n")
21413 (point-at-bol)))))
21414 beg end)
21415 ;; Determine boundaries of changes.
21416 (if (org-region-active-p)
21417 (setq beg (funcall skip-blanks (region-beginning))
21418 end (copy-marker (region-end)))
21419 (setq beg (funcall skip-blanks (point-at-bol))
21420 end (copy-marker (point-at-eol))))
21421 ;; Depending on the starting line, choose an action on the text
21422 ;; between BEG and END.
21423 (org-with-limited-levels
21424 (save-excursion
21425 (goto-char beg)
21426 (cond
21427 ;; Case 1. Start at an item: de-itemize. Note that it only
21428 ;; happens when a region is active: `org-ctrl-c-minus'
21429 ;; would call `org-cycle-list-bullet' otherwise.
21430 ((org-at-item-p)
21431 (while (< (point) end)
21432 (when (org-at-item-p)
21433 (skip-chars-forward " \t")
21434 (delete-region (point) (match-end 0)))
21435 (forward-line)))
21436 ;; Case 2. Start at an heading: convert to items.
21437 ((org-at-heading-p)
21438 (let* ((bul (org-list-bullet-string "-"))
21439 (bul-len (length bul))
21440 (done (org-entry-is-done-p))
21441 (todo (org-entry-is-todo-p))
21442 ;; Indentation of the first heading. It should be
21443 ;; relative to the indentation of its parent, if any.
21444 (start-ind (save-excursion
21445 (cond
21446 ((not org-adapt-indentation) 0)
21447 ((not (outline-previous-heading)) 0)
21448 (t (length (match-string 0))))))
21449 ;; Level of first heading. Further headings will be
21450 ;; compared to it to determine hierarchy in the list.
21451 (ref-level (org-reduced-level (org-outline-level))))
21452 (when (or done todo) (org-todo ""))
21453 (while (< (point) end)
21454 (let* ((level (org-reduced-level (org-outline-level)))
21455 (delta (max 0 (- level ref-level))))
21456 ;; If current headline is less indented than the first
21457 ;; one, set it as reference, in order to preserve
21458 ;; subtrees.
21459 (when (< level ref-level) (setq ref-level level))
21460 (replace-match bul t t)
21461 (org-indent-line-to (+ start-ind (* delta bul-len)))
21462 (when (or done todo)
21463 (let* ((struct (org-list-struct))
21464 (old (copy-tree struct)))
21465 (org-list-set-checkbox (line-beginning-position)
21466 struct
21467 (if done "[X]" "[ ]"))
21468 (org-list-write-struct struct
21469 (org-list-parents-alist struct)
21470 old)))
21471 ;; Ensure all text down to END (or SECTION-END) belongs
21472 ;; to the newly created item.
21473 (let ((section-end (save-excursion
21474 (or (outline-next-heading) (point)))))
21475 (forward-line)
21476 (funcall shift-text
21477 (+ start-ind (* (1+ delta) bul-len))
21478 (min end section-end)))))))
21479 ;; Case 3. Normal line with ARG: make the first line of region
21480 ;; an item, and shift indentation of others lines to
21481 ;; set them as item's body.
21482 (arg (let* ((bul (org-list-bullet-string "-"))
21483 (bul-len (length bul))
21484 (ref-ind (org-get-indentation)))
21485 (skip-chars-forward " \t")
21486 (insert bul)
21487 (forward-line)
21488 (while (< (point) end)
21489 ;; Ensure that lines less indented than first one
21490 ;; still get included in item body.
21491 (funcall shift-text
21492 (+ ref-ind bul-len)
21493 (min end (save-excursion (or (outline-next-heading)
21494 (point)))))
21495 (forward-line))))
21496 ;; Case 4. Normal line without ARG: turn each non-item line
21497 ;; into an item.
21499 (while (< (point) end)
21500 (unless (or (org-at-heading-p) (org-at-item-p))
21501 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21502 (replace-match
21503 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21504 (forward-line))))))))
21506 (defun org-toggle-heading (&optional nstars)
21507 "Convert headings to normal text, or items or text to headings.
21508 If there is no active region, only convert the current line.
21510 With a \\[universal-argument] prefix, convert the whole list at
21511 point into heading.
21513 In a region:
21515 - If the first non blank line is a headline, remove the stars
21516 from all headlines in the region.
21518 - If it is a normal line, turn each and every normal line (i.e.,
21519 not an heading or an item) in the region into headings. If you
21520 want to convert only the first line of this region, use one
21521 universal prefix argument.
21523 - If it is a plain list item, turn all plain list items into headings.
21525 When converting a line into a heading, the number of stars is chosen
21526 such that the lines become children of the current entry. However,
21527 when a numeric prefix argument is given, its value determines the
21528 number of stars to add."
21529 (interactive "P")
21530 (let ((skip-blanks
21531 (function
21532 ;; Return beginning of first non-blank line, starting from
21533 ;; line at POS.
21534 (lambda (pos)
21535 (save-excursion
21536 (goto-char pos)
21537 (while (org-at-comment-p) (forward-line))
21538 (skip-chars-forward " \r\t\n")
21539 (point-at-bol)))))
21540 beg end toggled)
21541 ;; Determine boundaries of changes. If a universal prefix has
21542 ;; been given, put the list in a region. If region ends at a bol,
21543 ;; do not consider the last line to be in the region.
21545 (when (and current-prefix-arg (org-at-item-p))
21546 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21547 (org-mark-element))
21549 (if (org-region-active-p)
21550 (setq beg (funcall skip-blanks (region-beginning))
21551 end (copy-marker (save-excursion
21552 (goto-char (region-end))
21553 (if (bolp) (point) (point-at-eol)))))
21554 (setq beg (funcall skip-blanks (point-at-bol))
21555 end (copy-marker (point-at-eol))))
21556 ;; Ensure inline tasks don't count as headings.
21557 (org-with-limited-levels
21558 (save-excursion
21559 (goto-char beg)
21560 (cond
21561 ;; Case 1. Started at an heading: de-star headings.
21562 ((org-at-heading-p)
21563 (while (< (point) end)
21564 (when (org-at-heading-p t)
21565 (looking-at org-outline-regexp) (replace-match "")
21566 (setq toggled t))
21567 (forward-line)))
21568 ;; Case 2. Started at an item: change items into headlines.
21569 ;; One star will be added by `org-list-to-subtree'.
21570 ((org-at-item-p)
21571 (while (< (point) end)
21572 (when (org-at-item-p)
21573 ;; Pay attention to cases when region ends before list.
21574 (let* ((struct (org-list-struct))
21575 (list-end
21576 (min (org-list-get-bottom-point struct) (1+ end))))
21577 (save-restriction
21578 (narrow-to-region (point) list-end)
21579 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21580 (setq toggled t))
21581 (forward-line)))
21582 ;; Case 3. Started at normal text: make every line an heading,
21583 ;; skipping headlines and items.
21584 (t (let* ((stars
21585 (make-string
21586 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21587 (add-stars
21588 (cond (nstars "") ; stars from prefix only
21589 ((equal stars "") "*") ; before first heading
21590 (org-odd-levels-only "**") ; inside heading, odd
21591 (t "*"))) ; inside heading, oddeven
21592 (rpl (concat stars add-stars " "))
21593 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21594 (while (< (point) (if (equal nstars '(4)) lend end))
21595 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21596 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21597 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21598 (forward-line)))))))
21599 (unless toggled (message "Cannot toggle heading from here"))))
21601 (defun org-meta-return (&optional _arg)
21602 "Insert a new heading or wrap a region in a table.
21603 Calls `org-insert-heading' or `org-table-wrap-region', depending
21604 on context. See the individual commands for more information."
21605 (interactive)
21606 (org-check-before-invisible-edit 'insert)
21607 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21608 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21609 #'org-insert-heading))))
21611 ;;; Menu entries
21613 (defsubst org-in-subtree-not-table-p ()
21614 "Are we in a subtree and not in a table?"
21615 (and (not (org-before-first-heading-p))
21616 (not (org-at-table-p))))
21618 ;; Define the Org-mode menus
21619 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21620 '("Tbl"
21621 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21622 ["Next Field" org-cycle (org-at-table-p)]
21623 ["Previous Field" org-shifttab (org-at-table-p)]
21624 ["Next Row" org-return (org-at-table-p)]
21625 "--"
21626 ["Blank Field" org-table-blank-field (org-at-table-p)]
21627 ["Edit Field" org-table-edit-field (org-at-table-p)]
21628 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21629 "--"
21630 ("Column"
21631 ["Move Column Left" org-metaleft (org-at-table-p)]
21632 ["Move Column Right" org-metaright (org-at-table-p)]
21633 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21634 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21635 ("Row"
21636 ["Move Row Up" org-metaup (org-at-table-p)]
21637 ["Move Row Down" org-metadown (org-at-table-p)]
21638 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21639 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21640 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21641 "--"
21642 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21643 ("Rectangle"
21644 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21645 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21646 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21647 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21648 "--"
21649 ("Calculate"
21650 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21651 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21652 ["Edit Formulas" org-edit-special (org-at-table-p)]
21653 "--"
21654 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21655 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21656 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21657 "--"
21658 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21659 "--"
21660 ["Sum Column/Rectangle" org-table-sum
21661 (or (org-at-table-p) (org-region-active-p))]
21662 ["Which Column?" org-table-current-column (org-at-table-p)])
21663 ["Debug Formulas"
21664 org-table-toggle-formula-debugger
21665 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21666 ["Show Col/Row Numbers"
21667 org-table-toggle-coordinate-overlays
21668 :style toggle
21669 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21670 "--"
21671 ["Create" org-table-create (and (not (org-at-table-p))
21672 org-enable-table-editor)]
21673 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21674 ["Import from File" org-table-import (not (org-at-table-p))]
21675 ["Export to File" org-table-export (org-at-table-p)]
21676 "--"
21677 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21678 "--"
21679 ("Plot"
21680 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21681 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21683 (easy-menu-define org-org-menu org-mode-map "Org menu"
21684 '("Org"
21685 ("Show/Hide"
21686 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21687 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21688 ["Sparse Tree..." org-sparse-tree t]
21689 ["Reveal Context" org-reveal t]
21690 ["Show All" outline-show-all t]
21691 "--"
21692 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21693 "--"
21694 ["New Heading" org-insert-heading t]
21695 ("Navigate Headings"
21696 ["Up" outline-up-heading t]
21697 ["Next" outline-next-visible-heading t]
21698 ["Previous" outline-previous-visible-heading t]
21699 ["Next Same Level" outline-forward-same-level t]
21700 ["Previous Same Level" outline-backward-same-level t]
21701 "--"
21702 ["Jump" org-goto t])
21703 ("Edit Structure"
21704 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21705 "--"
21706 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21707 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21708 "--"
21709 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21710 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21711 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21712 "--"
21713 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21714 "--"
21715 ["Copy visible text" org-copy-visible t]
21716 "--"
21717 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21718 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21719 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21720 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21721 "--"
21722 ["Sort Region/Children" org-sort t]
21723 "--"
21724 ["Convert to odd levels" org-convert-to-odd-levels t]
21725 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21726 ("Editing"
21727 ["Emphasis..." org-emphasize t]
21728 ["Edit Source Example" org-edit-special t]
21729 "--"
21730 ["Footnote new/jump" org-footnote-action t]
21731 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21732 ("Archive"
21733 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21734 "--"
21735 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21736 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21737 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21739 "--"
21740 ("Hyperlinks"
21741 ["Store Link (Global)" org-store-link t]
21742 ["Find existing link to here" org-occur-link-in-agenda-files t]
21743 ["Insert Link" org-insert-link t]
21744 ["Follow Link" org-open-at-point t]
21745 "--"
21746 ["Next link" org-next-link t]
21747 ["Previous link" org-previous-link t]
21748 "--"
21749 ["Descriptive Links"
21750 org-toggle-link-display
21751 :style radio
21752 :selected org-descriptive-links
21754 ["Literal Links"
21755 org-toggle-link-display
21756 :style radio
21757 :selected (not org-descriptive-links)])
21758 "--"
21759 ("TODO Lists"
21760 ["TODO/DONE/-" org-todo t]
21761 ("Select keyword"
21762 ["Next keyword" org-shiftright (org-at-heading-p)]
21763 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21764 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21765 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21766 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21767 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21768 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21769 "--"
21770 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21771 :selected org-enforce-todo-dependencies :style toggle :active t]
21772 "Settings for tree at point"
21773 ["Do Children sequentially" org-toggle-ordered-property :style radio
21774 :selected (org-entry-get nil "ORDERED")
21775 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21776 ["Do Children parallel" org-toggle-ordered-property :style radio
21777 :selected (not (org-entry-get nil "ORDERED"))
21778 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21779 "--"
21780 ["Set Priority" org-priority t]
21781 ["Priority Up" org-shiftup t]
21782 ["Priority Down" org-shiftdown t]
21783 "--"
21784 ["Get news from all feeds" org-feed-update-all t]
21785 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21786 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21787 ("TAGS and Properties"
21788 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21789 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21790 "--"
21791 ["Set property" org-set-property (not (org-before-first-heading-p))]
21792 ["Column view of properties" org-columns t]
21793 ["Insert Column View DBlock" org-insert-columns-dblock t])
21794 ("Dates and Scheduling"
21795 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21796 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21797 ("Change Date"
21798 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21799 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21800 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21801 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21802 ["Compute Time Range" org-evaluate-time-range t]
21803 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21804 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21805 "--"
21806 ["Custom time format" org-toggle-time-stamp-overlays
21807 :style radio :selected org-display-custom-times]
21808 "--"
21809 ["Goto Calendar" org-goto-calendar t]
21810 ["Date from Calendar" org-date-from-calendar t]
21811 "--"
21812 ["Start/Restart Timer" org-timer-start t]
21813 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21814 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21815 ["Insert Timer String" org-timer t]
21816 ["Insert Timer Item" org-timer-item t])
21817 ("Logging work"
21818 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21819 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21820 ["Clock out" org-clock-out t]
21821 ["Clock cancel" org-clock-cancel t]
21822 "--"
21823 ["Mark as default task" org-clock-mark-default-task t]
21824 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21825 ["Goto running clock" org-clock-goto t]
21826 "--"
21827 ["Display times" org-clock-display t]
21828 ["Create clock table" org-clock-report t]
21829 "--"
21830 ["Record DONE time"
21831 (progn (setq org-log-done (not org-log-done))
21832 (message "Switching to %s will %s record a timestamp"
21833 (car org-done-keywords)
21834 (if org-log-done "automatically" "not")))
21835 :style toggle :selected org-log-done])
21836 "--"
21837 ["Agenda Command..." org-agenda t]
21838 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21839 ("File List for Agenda")
21840 ("Special views current file"
21841 ["TODO Tree" org-show-todo-tree t]
21842 ["Check Deadlines" org-check-deadlines t]
21843 ["Timeline" org-timeline t]
21844 ["Tags/Property tree" org-match-sparse-tree t])
21845 "--"
21846 ["Export/Publish..." org-export-dispatch t]
21847 ("LaTeX"
21848 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21849 :selected org-cdlatex-mode]
21850 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21851 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21852 ["Modify math symbol" org-cdlatex-math-modify
21853 (org-inside-LaTeX-fragment-p)]
21854 ["Insert citation" org-reftex-citation t]
21855 "--"
21856 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21857 "--"
21858 ("MobileOrg"
21859 ["Push Files and Views" org-mobile-push t]
21860 ["Get Captured and Flagged" org-mobile-pull t]
21861 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21862 "--"
21863 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21864 "--"
21865 ("Documentation"
21866 ["Show Version" org-version t]
21867 ["Info Documentation" org-info t])
21868 ("Customize"
21869 ["Browse Org Group" org-customize t]
21870 "--"
21871 ["Expand This Menu" org-create-customize-menu
21872 (fboundp 'customize-menu-create)])
21873 ["Send bug report" org-submit-bug-report t]
21874 "--"
21875 ("Refresh/Reload"
21876 ["Refresh setup current buffer" org-mode-restart t]
21877 ["Reload Org (after update)" org-reload t]
21878 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21881 (defun org-info (&optional node)
21882 "Read documentation for Org-mode in the info system.
21883 With optional NODE, go directly to that node."
21884 (interactive)
21885 (info (format "(org)%s" (or node ""))))
21887 ;;;###autoload
21888 (defun org-submit-bug-report ()
21889 "Submit a bug report on Org-mode via mail.
21891 Don't hesitate to report any problems or inaccurate documentation.
21893 If you don't have setup sending mail from (X)Emacs, please copy the
21894 output buffer into your mail program, as it gives us important
21895 information about your Org-mode version and configuration."
21896 (interactive)
21897 (require 'reporter)
21898 (defvar reporter-prompt-for-summary-p)
21899 (org-load-modules-maybe)
21900 (org-require-autoloaded-modules)
21901 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21902 (reporter-submit-bug-report
21903 "emacs-orgmode@gnu.org"
21904 (org-version nil 'full)
21905 (let (list)
21906 (save-window-excursion
21907 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21908 (delete-other-windows)
21909 (erase-buffer)
21910 (insert "You are about to submit a bug report to the Org-mode mailing list.
21912 We would like to add your full Org-mode and Outline configuration to the
21913 bug report. This greatly simplifies the work of the maintainer and
21914 other experts on the mailing list.
21916 HOWEVER, some variables you have customized may contain private
21917 information. The names of customers, colleagues, or friends, might
21918 appear in the form of file names, tags, todo states, or search strings.
21919 If you answer yes to the prompt, you might want to check and remove
21920 such private information before sending the email.")
21921 (add-text-properties (point-min) (point-max) '(face org-warning))
21922 (when (yes-or-no-p "Include your Org-mode configuration ")
21923 (mapatoms
21924 (lambda (v)
21925 (and (boundp v)
21926 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21927 (or (and (symbol-value v)
21928 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21929 (and
21930 (get v 'custom-type) (get v 'standard-value)
21931 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21932 (push v list)))))
21933 (kill-buffer (get-buffer "*Warn about privacy*"))
21934 list))
21935 nil nil
21936 "Remember to cover the basics, that is, what you expected to happen and
21937 what in fact did happen. You don't know how to make a good report? See
21939 http://orgmode.org/manual/Feedback.html#Feedback
21941 Your bug report will be posted to the Org-mode mailing list.
21942 ------------------------------------------------------------------------")
21943 (save-excursion
21944 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21945 (replace-match "\\1Bug: \\3 [\\2]")))))
21948 (defun org-install-agenda-files-menu ()
21949 (let ((bl (buffer-list)))
21950 (save-excursion
21951 (while bl
21952 (set-buffer (pop bl))
21953 (when (derived-mode-p 'org-mode) (setq bl nil)))
21954 (when (derived-mode-p 'org-mode)
21955 (easy-menu-change
21956 '("Org") "File List for Agenda"
21957 (append
21958 (list
21959 ["Edit File List" (org-edit-agenda-file-list) t]
21960 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21961 ["Remove Current File from List" org-remove-file t]
21962 ["Cycle through agenda files" org-cycle-agenda-files t]
21963 ["Occur in all agenda files" org-occur-in-agenda-files t]
21964 "--")
21965 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21967 ;;;; Documentation
21969 (defun org-require-autoloaded-modules ()
21970 (interactive)
21971 (mapc #'require
21972 '(org-agenda org-archive org-attach org-clock org-colview org-id
21973 org-table org-timer)))
21975 ;;;###autoload
21976 (defun org-reload (&optional uncompiled)
21977 "Reload all org lisp files.
21978 With prefix arg UNCOMPILED, load the uncompiled versions."
21979 (interactive "P")
21980 (require 'loadhist)
21981 (let* ((org-dir (org-find-library-dir "org"))
21982 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21983 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21984 (remove-re (mapconcat 'identity
21985 (mapcar (lambda (f) (concat "^" f "$"))
21986 (list (if (featurep 'xemacs)
21987 "org-colview"
21988 "org-colview-xemacs")
21989 "org" "org-loaddefs" "org-version"))
21990 "\\|"))
21991 (feats (delete-dups
21992 (mapcar 'file-name-sans-extension
21993 (mapcar 'file-name-nondirectory
21994 (delq nil
21995 (mapcar 'feature-file
21996 features))))))
21997 (lfeat (append
21998 (sort
21999 (setq feats
22000 (delq nil (mapcar
22001 (lambda (f)
22002 (if (and (string-match feature-re f)
22003 (not (string-match remove-re f)))
22004 f nil))
22005 feats)))
22006 'string-lessp)
22007 (list "org-version" "org")))
22008 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22009 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22010 load-uncore load-misses)
22011 (setq load-misses
22012 (delq 't
22013 (mapcar (lambda (f)
22014 (or (org-load-noerror-mustsuffix (concat org-dir f))
22015 (and (string= org-dir contrib-dir)
22016 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22017 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22018 (add-to-list 'load-uncore f 'append)
22021 lfeat)))
22022 (when load-uncore
22023 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22024 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22025 (if load-misses
22026 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22027 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22028 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22030 ;;;###autoload
22031 (defun org-customize ()
22032 "Call the customize function with org as argument."
22033 (interactive)
22034 (org-load-modules-maybe)
22035 (org-require-autoloaded-modules)
22036 (customize-browse 'org))
22038 (defun org-create-customize-menu ()
22039 "Create a full customization menu for Org-mode, insert it into the menu."
22040 (interactive)
22041 (org-load-modules-maybe)
22042 (org-require-autoloaded-modules)
22043 (if (fboundp 'customize-menu-create)
22044 (progn
22045 (easy-menu-change
22046 '("Org") "Customize"
22047 `(["Browse Org group" org-customize t]
22048 "--"
22049 ,(customize-menu-create 'org)
22050 ["Set" Custom-set t]
22051 ["Save" Custom-save t]
22052 ["Reset to Current" Custom-reset-current t]
22053 ["Reset to Saved" Custom-reset-saved t]
22054 ["Reset to Standard Settings" Custom-reset-standard t]))
22055 (message "\"Org\"-menu now contains full customization menu"))
22056 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22058 ;;;; Miscellaneous stuff
22060 ;;; Generally useful functions
22062 (defsubst org-get-at-eol (property n)
22063 "Get text property PROPERTY at the end of line less N characters."
22064 (get-text-property (- (point-at-eol) n) property))
22066 (defun org-find-text-property-in-string (prop s)
22067 "Return the first non-nil value of property PROP in string S."
22068 (or (get-text-property 0 prop s)
22069 (get-text-property (or (next-single-property-change 0 prop s) 0)
22070 prop s)))
22072 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22073 "Display the given MESSAGE as a warning."
22074 (if (fboundp 'display-warning)
22075 (display-warning 'org message
22076 (if (featurep 'xemacs) 'warning :warning))
22077 (let ((buf (get-buffer-create "*Org warnings*")))
22078 (with-current-buffer buf
22079 (goto-char (point-max))
22080 (insert "Warning (Org): " message)
22081 (unless (bolp)
22082 (newline)))
22083 (display-buffer buf)
22084 (sit-for 0))))
22086 (defun org-eval (form)
22087 "Eval FORM and return result."
22088 (condition-case error
22089 (eval form)
22090 (error (format "%%![Error: %s]" error))))
22092 (defun org-in-clocktable-p ()
22093 "Check if the cursor is in a clocktable."
22094 (let ((pos (point)) start)
22095 (save-excursion
22096 (end-of-line 1)
22097 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22098 (setq start (match-beginning 0))
22099 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22100 (>= (match-end 0) pos)
22101 start))))
22103 (defun org-in-verbatim-emphasis ()
22104 (save-match-data
22105 (and (org-in-regexp org-emph-re 2)
22106 (>= (point) (match-beginning 3))
22107 (<= (point) (match-end 4))
22108 (member (match-string 3) '("=" "~")))))
22110 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22111 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22112 (if (and marker (marker-buffer marker)
22113 (buffer-live-p (marker-buffer marker)))
22114 (progn
22115 (org-pop-to-buffer-same-window (marker-buffer marker))
22116 (when (or (> marker (point-max)) (< marker (point-min)))
22117 (widen))
22118 (goto-char marker)
22119 (org-show-context 'org-goto))
22120 (if bookmark
22121 (bookmark-jump bookmark)
22122 (error "Cannot find location"))))
22124 (defun org-quote-csv-field (s)
22125 "Quote field for inclusion in CSV material."
22126 (if (string-match "[\",]" s)
22127 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22130 (defun org-force-self-insert (N)
22131 "Needed to enforce self-insert under remapping."
22132 (interactive "p")
22133 (self-insert-command N))
22135 (defun org-string-width (s)
22136 "Compute width of string, ignoring invisible characters.
22137 This ignores character with invisibility property `org-link', and also
22138 characters with property `org-cwidth', because these will become invisible
22139 upon the next fontification round."
22140 (let (b l)
22141 (when (or (eq t buffer-invisibility-spec)
22142 (assq 'org-link buffer-invisibility-spec))
22143 (while (setq b (text-property-any 0 (length s)
22144 'invisible 'org-link s))
22145 (setq s (concat (substring s 0 b)
22146 (substring s (or (next-single-property-change
22147 b 'invisible s)
22148 (length s)))))))
22149 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22150 (setq s (concat (substring s 0 b)
22151 (substring s (or (next-single-property-change
22152 b 'org-cwidth s)
22153 (length s))))))
22154 (setq l (string-width s) b -1)
22155 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22156 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22159 (defun org-shorten-string (s maxlength)
22160 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22161 If the string is shorter or has length MAXLENGTH, just return the
22162 original string. If it is longer, the functions finds a space in the
22163 string, breaks this string off at that locations and adds three dots
22164 as ellipsis. Including the ellipsis, the string will not be longer
22165 than MAXLENGTH. If finding a good breaking point in the string does
22166 not work, the string is just chopped off in the middle of a word
22167 if necessary."
22168 (if (<= (length s) maxlength)
22170 (let* ((n (max (- maxlength 4) 1))
22171 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22172 (if (string-match re s)
22173 (concat (match-string 1 s) "...")
22174 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22176 (defun org-get-indentation (&optional line)
22177 "Get the indentation of the current line, interpreting tabs.
22178 When LINE is given, assume it represents a line and compute its indentation."
22179 (if line
22180 (when (string-match "^ *" (org-remove-tabs line))
22181 (match-end 0))
22182 (save-excursion
22183 (beginning-of-line 1)
22184 (skip-chars-forward " \t")
22185 (current-column))))
22187 (defun org-get-string-indentation (s)
22188 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22189 (let ((n -1) (i 0) (w tab-width) c)
22190 (catch 'exit
22191 (while (< (setq n (1+ n)) (length s))
22192 (setq c (aref s n))
22193 (cond ((= c ?\ ) (setq i (1+ i)))
22194 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22195 (t (throw 'exit t)))))
22198 (defun org-remove-tabs (s &optional width)
22199 "Replace tabulators in S with spaces.
22200 Assumes that s is a single line, starting in column 0."
22201 (setq width (or width tab-width))
22202 (while (string-match "\t" s)
22203 (setq s (replace-match
22204 (make-string
22205 (- (* width (/ (+ (match-beginning 0) width) width))
22206 (match-beginning 0)) ?\ )
22207 t t s)))
22210 (defun org-fix-indentation (line ind)
22211 "Fix indentation in LINE.
22212 IND is a cons cell with target and minimum indentation.
22213 If the current indentation in LINE is smaller than the minimum,
22214 leave it alone. If it is larger than ind, set it to the target."
22215 (let* ((l (org-remove-tabs line))
22216 (i (org-get-indentation l))
22217 (i1 (car ind)) (i2 (cdr ind)))
22218 (when (>= i i2) (setq l (substring line i2)))
22219 (if (> i1 0)
22220 (concat (make-string i1 ?\ ) l)
22221 l)))
22223 (defun org-remove-indentation (code &optional n)
22224 "Remove maximum common indentation in string CODE and return it.
22225 N may optionally be the number of columns to remove. Return CODE
22226 as-is if removal failed."
22227 (with-temp-buffer
22228 (insert code)
22229 (if (org-do-remove-indentation n) (buffer-string) code)))
22231 (defun org-do-remove-indentation (&optional n)
22232 "Remove the maximum common indentation from the buffer.
22233 When optional argument N is a positive integer, remove exactly
22234 that much characters from indentation, if possible. Return nil
22235 if it fails."
22236 (catch :exit
22237 (goto-char (point-min))
22238 ;; Find maximum common indentation, if not specified.
22239 (let ((n (or n
22240 (let ((min-ind (point-max)))
22241 (save-excursion
22242 (while (re-search-forward "^[ \t]*\\S-" nil t)
22243 (let ((ind (1- (current-column))))
22244 (if (zerop ind) (throw :exit nil)
22245 (setq min-ind (min min-ind ind))))))
22246 min-ind))))
22247 (if (zerop n) (throw :exit nil)
22248 ;; Remove exactly N indentation, but give up if not possible.
22249 (while (not (eobp))
22250 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22251 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22252 ((< ind n) (throw :exit nil))
22253 (t (org-indent-line-to (- ind n))))
22254 (forward-line)))
22255 ;; Signal success.
22256 t))))
22258 (defun org-fill-template (template alist)
22259 "Find each %key of ALIST in TEMPLATE and replace it."
22260 (let ((case-fold-search nil))
22261 (dolist (entry (sort (copy-sequence alist)
22262 (lambda (a b) (< (length (car a)) (length (car b))))))
22263 (setq template
22264 (replace-regexp-in-string
22265 (concat "%" (regexp-quote (car entry)))
22266 (or (cdr entry) "") template t t)))
22267 template))
22269 (defun org-base-buffer (buffer)
22270 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22271 (if (not buffer)
22272 buffer
22273 (or (buffer-base-buffer buffer)
22274 buffer)))
22276 (defun org-wrap (string &optional width lines)
22277 "Wrap string to either a number of lines, or a width in characters.
22278 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22279 that costs. If there is a word longer than WIDTH, the text is actually
22280 wrapped to the length of that word.
22281 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22282 many lines, whatever width that takes.
22283 The return value is a list of lines, without newlines at the end."
22284 (let* ((words (org-split-string string "[ \t\n]+"))
22285 (maxword (apply 'max (mapcar 'org-string-width words)))
22286 w ll)
22287 (cond (width
22288 (org-do-wrap words (max maxword width)))
22289 (lines
22290 (setq w maxword)
22291 (setq ll (org-do-wrap words maxword))
22292 (if (<= (length ll) lines)
22294 (setq ll words)
22295 (while (> (length ll) lines)
22296 (setq w (1+ w))
22297 (setq ll (org-do-wrap words w)))
22298 ll))
22299 (t (error "Cannot wrap this")))))
22301 (defun org-do-wrap (words width)
22302 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22303 (let (lines line)
22304 (while words
22305 (setq line (pop words))
22306 (while (and words (< (+ (length line) (length (car words))) width))
22307 (setq line (concat line " " (pop words))))
22308 (setq lines (push line lines)))
22309 (nreverse lines)))
22311 (defun org-split-string (string &optional separators)
22312 "Splits STRING into substrings at SEPARATORS.
22313 SEPARATORS is a regular expression.
22314 No empty strings are returned if there are matches at the beginning
22315 and end of string."
22316 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22317 (let ((start 0) notfirst list)
22318 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22319 (if (and notfirst
22320 (= start (match-beginning 0))
22321 (< start (length string)))
22322 (1+ start) start))
22323 (< (match-beginning 0) (length string)))
22324 (setq notfirst t)
22325 (or (eq (match-beginning 0) 0)
22326 (and (eq (match-beginning 0) (match-end 0))
22327 (eq (match-beginning 0) start))
22328 (push (substring string start (match-beginning 0)) list))
22329 (setq start (match-end 0)))
22330 (or (eq start (length string))
22331 (push (substring string start) list))
22332 (nreverse list)))
22334 (defun org-quote-vert (s)
22335 "Replace \"|\" with \"\\vert\"."
22336 (while (string-match "|" s)
22337 (setq s (replace-match "\\vert" t t s)))
22340 (defun org-uuidgen-p (s)
22341 "Is S an ID created by UUIDGEN?"
22342 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22344 (defun org-in-src-block-p (&optional inside)
22345 "Whether point is in a code source block.
22346 When INSIDE is non-nil, don't consider we are within a src block
22347 when point is at #+BEGIN_SRC or #+END_SRC."
22348 (let ((case-fold-search t))
22349 (or (and (eq (get-char-property (point) 'src-block) t))
22350 (and (not inside)
22351 (save-match-data
22352 (save-excursion
22353 (beginning-of-line)
22354 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22356 (defun org-context ()
22357 "Return a list of contexts of the current cursor position.
22358 If several contexts apply, all are returned.
22359 Each context entry is a list with a symbol naming the context, and
22360 two positions indicating start and end of the context. Possible
22361 contexts are:
22363 :headline anywhere in a headline
22364 :headline-stars on the leading stars in a headline
22365 :todo-keyword on a TODO keyword (including DONE) in a headline
22366 :tags on the TAGS in a headline
22367 :priority on the priority cookie in a headline
22368 :item on the first line of a plain list item
22369 :item-bullet on the bullet/number of a plain list item
22370 :checkbox on the checkbox in a plain list item
22371 :table in an org-mode table
22372 :table-special on a special filed in a table
22373 :table-table in a table.el table
22374 :clocktable in a clocktable
22375 :src-block in a source block
22376 :link on a hyperlink
22377 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22378 :target on a <<target>>
22379 :radio-target on a <<<radio-target>>>
22380 :latex-fragment on a LaTeX fragment
22381 :latex-preview on a LaTeX fragment with overlaid preview image
22383 This function expects the position to be visible because it uses font-lock
22384 faces as a help to recognize the following contexts: :table-special, :link,
22385 and :keyword."
22386 (let* ((f (get-text-property (point) 'face))
22387 (faces (if (listp f) f (list f)))
22388 (case-fold-search t)
22389 (p (point)) clist o)
22390 ;; First the large context
22391 (cond
22392 ((org-at-heading-p t)
22393 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22394 (when (progn
22395 (beginning-of-line 1)
22396 (looking-at org-todo-line-tags-regexp))
22397 (push (org-point-in-group p 1 :headline-stars) clist)
22398 (push (org-point-in-group p 2 :todo-keyword) clist)
22399 (push (org-point-in-group p 4 :tags) clist))
22400 (goto-char p)
22401 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22402 (when (looking-at "\\[#[A-Z0-9]\\]")
22403 (push (org-point-in-group p 0 :priority) clist)))
22405 ((org-at-item-p)
22406 (push (org-point-in-group p 2 :item-bullet) clist)
22407 (push (list :item (point-at-bol)
22408 (save-excursion (org-end-of-item) (point)))
22409 clist)
22410 (and (org-at-item-checkbox-p)
22411 (push (org-point-in-group p 0 :checkbox) clist)))
22413 ((org-at-table-p)
22414 (push (list :table (org-table-begin) (org-table-end)) clist)
22415 (when (memq 'org-formula faces)
22416 (push (list :table-special
22417 (previous-single-property-change p 'face)
22418 (next-single-property-change p 'face)) clist)))
22419 ((org-at-table-p 'any)
22420 (push (list :table-table) clist)))
22421 (goto-char p)
22423 (let ((case-fold-search t))
22424 ;; New the "medium" contexts: clocktables, source blocks
22425 (cond ((org-in-clocktable-p)
22426 (push (list :clocktable
22427 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22428 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22429 (match-beginning 1))
22430 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22431 (match-end 0))) clist))
22432 ((org-in-src-block-p)
22433 (push (list :src-block
22434 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22435 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22436 (match-beginning 1))
22437 (and (search-forward "#+END_SRC" nil t)
22438 (match-beginning 0))) clist))))
22439 (goto-char p)
22441 ;; Now the small context
22442 (cond
22443 ((org-at-timestamp-p)
22444 (push (org-point-in-group p 0 :timestamp) clist))
22445 ((memq 'org-link faces)
22446 (push (list :link
22447 (previous-single-property-change p 'face)
22448 (next-single-property-change p 'face)) clist))
22449 ((memq 'org-special-keyword faces)
22450 (push (list :keyword
22451 (previous-single-property-change p 'face)
22452 (next-single-property-change p 'face)) clist))
22453 ((org-at-target-p)
22454 (push (org-point-in-group p 0 :target) clist)
22455 (goto-char (1- (match-beginning 0)))
22456 (when (looking-at org-radio-target-regexp)
22457 (push (org-point-in-group p 0 :radio-target) clist))
22458 (goto-char p))
22459 ((setq o (car (delq nil
22460 (mapcar
22461 (lambda (x)
22462 (when (memq x org-latex-fragment-image-overlays) x))
22463 (overlays-at (point))))))
22464 (push (list :latex-fragment
22465 (overlay-start o) (overlay-end o)) clist)
22466 (push (list :latex-preview
22467 (overlay-start o) (overlay-end o)) clist))
22468 ((org-inside-LaTeX-fragment-p)
22469 ;; FIXME: positions wrong.
22470 (push (list :latex-fragment (point) (point)) clist)))
22472 (setq clist (nreverse (delq nil clist)))
22473 clist))
22475 (defun org-in-regexp (regexp &optional nlines visually)
22476 "Check if point is inside a match of REGEXP.
22478 Normally only the current line is checked, but you can include
22479 NLINES extra lines around point into the search. If VISUALLY is
22480 set, require that the cursor is not after the match but really
22481 on, so that the block visually is on the match.
22483 Return nil or a cons cell (BEG . END) where BEG and END are,
22484 respectively, the positions at the beginning and the end of the
22485 match."
22486 (catch :exit
22487 (let ((pos (point))
22488 (eol (line-end-position (if nlines (1+ nlines) 1))))
22489 (save-excursion
22490 (beginning-of-line (- 1 (or nlines 0)))
22491 (while (and (re-search-forward regexp eol t)
22492 (<= (match-beginning 0) pos))
22493 (let ((end (match-end 0)))
22494 (when (or (> end pos) (and (= end pos) (not visually)))
22495 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22496 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22497 "Org mode 8.3")
22499 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22500 "Non-nil when point is between matches of START-RE and END-RE.
22502 Also return a non-nil value when point is on one of the matches.
22504 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22505 buffer positions. Default values are the positions of headlines
22506 surrounding the point.
22508 The functions returns a cons cell whose car (resp. cdr) is the
22509 position before START-RE (resp. after END-RE)."
22510 (save-match-data
22511 (let ((pos (point))
22512 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22513 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22514 beg end)
22515 (save-excursion
22516 ;; Point is on a block when on START-RE or if START-RE can be
22517 ;; found before it...
22518 (and (or (org-in-regexp start-re)
22519 (re-search-backward start-re limit-up t))
22520 (setq beg (match-beginning 0))
22521 ;; ... and END-RE after it...
22522 (goto-char (match-end 0))
22523 (re-search-forward end-re limit-down t)
22524 (> (setq end (match-end 0)) pos)
22525 ;; ... without another START-RE in-between.
22526 (goto-char (match-beginning 0))
22527 (not (re-search-backward start-re (1+ beg) t))
22528 ;; Return value.
22529 (cons beg end))))))
22531 (defun org-in-block-p (names)
22532 "Non-nil when point belongs to a block whose name belongs to NAMES.
22534 NAMES is a list of strings containing names of blocks.
22536 Return first block name matched, or nil. Beware that in case of
22537 nested blocks, the returned name may not belong to the closest
22538 block from point."
22539 (save-match-data
22540 (catch 'exit
22541 (let ((case-fold-search t)
22542 (lim-up (save-excursion (outline-previous-heading)))
22543 (lim-down (save-excursion (outline-next-heading))))
22544 (dolist (name names)
22545 (let ((n (regexp-quote name)))
22546 (when (org-between-regexps-p
22547 (concat "^[ \t]*#\\+begin_" n)
22548 (concat "^[ \t]*#\\+end_" n)
22549 lim-up lim-down)
22550 (throw 'exit n)))))
22551 nil)))
22553 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22554 "Call `multi-occur' with buffers for all agenda files."
22555 (interactive "sOrg-files matching: ")
22556 (let* ((files (org-agenda-files))
22557 (tnames (mapcar #'file-truename files))
22558 (extra org-agenda-text-search-extra-files))
22559 (when (eq (car extra) 'agenda-archives)
22560 (setq extra (cdr extra))
22561 (setq files (org-add-archive-files files)))
22562 (dolist (f extra)
22563 (unless (member (file-truename f) tnames)
22564 (unless (member f files) (setq files (append files (list f))))
22565 (setq tnames (append tnames (list (file-truename f))))))
22566 (multi-occur
22567 (mapcar (lambda (x)
22568 (with-current-buffer
22569 ;; FIXME: Why not just (find-file-noselect x)?
22570 ;; Is it to avoid the "revert buffer" prompt?
22571 (or (get-file-buffer x) (find-file-noselect x))
22572 (widen)
22573 (current-buffer)))
22574 files)
22575 regexp)))
22577 (if (boundp 'occur-mode-find-occurrence-hook)
22578 ;; Emacs 23
22579 (add-hook 'occur-mode-find-occurrence-hook
22580 (lambda ()
22581 (when (derived-mode-p 'org-mode)
22582 (org-reveal))))
22583 ;; Emacs 22
22584 (defadvice occur-mode-goto-occurrence
22585 (after org-occur-reveal activate)
22586 (and (derived-mode-p 'org-mode) (org-reveal)))
22587 (defadvice occur-mode-goto-occurrence-other-window
22588 (after org-occur-reveal activate)
22589 (and (derived-mode-p 'org-mode) (org-reveal)))
22590 (defadvice occur-mode-display-occurrence
22591 (after org-occur-reveal activate)
22592 (when (derived-mode-p 'org-mode)
22593 (let ((pos (occur-mode-find-occurrence)))
22594 (with-current-buffer (marker-buffer pos)
22595 (save-excursion
22596 (goto-char pos)
22597 (org-reveal)))))))
22599 (defun org-occur-link-in-agenda-files ()
22600 "Create a link and search for it in the agendas.
22601 The link is not stored in `org-stored-links', it is just created
22602 for the search purpose."
22603 (interactive)
22604 (let ((link (condition-case nil
22605 (org-store-link nil)
22606 (error "Unable to create a link to here"))))
22607 (org-occur-in-agenda-files (regexp-quote link))))
22609 (defun org-reverse-string (string)
22610 "Return the reverse of STRING."
22611 (apply 'string (reverse (string-to-list string))))
22613 ;; defsubst org-uniquify must be defined before first use
22615 (defun org-uniquify-alist (alist)
22616 "Merge elements of ALIST with the same key.
22618 For example, in this alist:
22620 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22621 => \\='((a 1 3) (b 2))
22623 merge (a 1) and (a 3) into (a 1 3).
22625 The function returns the new ALIST."
22626 (let (rtn)
22627 (dolist (e alist rtn)
22628 (let (n)
22629 (if (not (assoc (car e) rtn))
22630 (push e rtn)
22631 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22632 (setq rtn (assq-delete-all (car e) rtn))
22633 (push n rtn))))))
22635 (defun org-delete-all (elts list)
22636 "Remove all elements in ELTS from LIST."
22637 (while elts
22638 (setq list (delete (pop elts) list)))
22639 list)
22641 (defun org-back-over-empty-lines ()
22642 "Move backwards over whitespace, to the beginning of the first empty line.
22643 Returns the number of empty lines passed."
22644 (let ((pos (point)))
22645 (if (cdr (assoc 'heading org-blank-before-new-entry))
22646 (skip-chars-backward " \t\n\r")
22647 (unless (eobp)
22648 (forward-line -1)))
22649 (beginning-of-line 2)
22650 (goto-char (min (point) pos))
22651 (count-lines (point) pos)))
22653 (defun org-skip-whitespace ()
22654 (skip-chars-forward " \t\n\r"))
22656 (defun org-point-in-group (point group &optional context)
22657 "Check if POINT is in match-group GROUP.
22658 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22659 match. If the match group does not exist or point is not inside it,
22660 return nil."
22661 (and (match-beginning group)
22662 (>= point (match-beginning group))
22663 (<= point (match-end group))
22664 (if context
22665 (list context (match-beginning group) (match-end group))
22666 t)))
22668 (defun org-switch-to-buffer-other-window (&rest args)
22669 "Switch to buffer in a second window on the current frame.
22670 In particular, do not allow pop-up frames.
22671 Returns the newly created buffer."
22672 (org-no-popups
22673 (apply 'switch-to-buffer-other-window args)))
22675 (defun org-combine-plists (&rest plists)
22676 "Create a single property list from all plists in PLISTS.
22677 The process starts by copying the first list, and then setting properties
22678 from the other lists. Settings in the last list are the most significant
22679 ones and overrule settings in the other lists."
22680 (let ((rtn (copy-sequence (pop plists)))
22681 p v ls)
22682 (while plists
22683 (setq ls (pop plists))
22684 (while ls
22685 (setq p (pop ls) v (pop ls))
22686 (setq rtn (plist-put rtn p v))))
22687 rtn))
22689 (defun org-replace-escapes (string table)
22690 "Replace %-escapes in STRING with values in TABLE.
22691 TABLE is an association list with keys like \"%a\" and string values.
22692 The sequences in STRING may contain normal field width and padding information,
22693 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22694 so values can contain further %-escapes if they are define later in TABLE."
22695 (let ((tbl (copy-alist table))
22696 (case-fold-search nil)
22697 (pchg 0)
22698 re rpl)
22699 (dolist (e tbl)
22700 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22701 (when (and (cdr e) (string-match re (cdr e)))
22702 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22703 (safe "SREF"))
22704 (add-text-properties 0 3 (list 'sref sref) safe)
22705 (setcdr e (replace-match safe t t (cdr e)))))
22706 (while (string-match re string)
22707 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22708 (cdr e)))
22709 (setq string (replace-match rpl t t string))))
22710 (while (setq pchg (next-property-change pchg string))
22711 (let ((sref (get-text-property pchg 'sref string)))
22712 (when (and sref (string-match "SREF" string pchg))
22713 (setq string (replace-match sref t t string)))))
22714 string))
22716 (defun org-sublist (list start end)
22717 "Return a section of LIST, from START to END.
22719 Counting starts at 1."
22720 (cl-subseq list (1- start) end))
22721 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22723 (defun org-find-base-buffer-visiting (file)
22724 "Like `find-buffer-visiting' but always return the base buffer and
22725 not an indirect buffer."
22726 (let ((buf (or (get-file-buffer file)
22727 (find-buffer-visiting file))))
22728 (if buf
22729 (or (buffer-base-buffer buf) buf)
22730 nil)))
22732 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22733 "Org 9.0")
22735 ;;; TODO: Only called once, from ox-odt which should probably use
22736 ;;; org-export-inline-image-p or something.
22737 (defun org-file-image-p (file)
22738 "Return non-nil if FILE is an image."
22739 (save-match-data
22740 (string-match (image-file-name-regexp) file)))
22742 (defun org-get-cursor-date (&optional with-time)
22743 "Return the date at cursor in as a time.
22744 This works in the calendar and in the agenda, anywhere else it just
22745 returns the current time.
22746 If WITH-TIME is non-nil, returns the time of the event at point (in
22747 the agenda) or the current time of the day."
22748 (let (date day defd tp hod mod)
22749 (when with-time
22750 (setq tp (get-text-property (point) 'time))
22751 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22752 (setq hod (string-to-number (match-string 1 tp))
22753 mod (string-to-number (match-string 2 tp))))
22754 (or tp (let ((now (decode-time)))
22755 (setq hod (nth 2 now)
22756 mod (nth 1 now)))))
22757 (cond
22758 ((eq major-mode 'calendar-mode)
22759 (setq date (calendar-cursor-to-date)
22760 defd (encode-time 0 (or mod 0) (or hod 0)
22761 (nth 1 date) (nth 0 date) (nth 2 date))))
22762 ((eq major-mode 'org-agenda-mode)
22763 (setq day (get-text-property (point) 'day))
22764 (when day
22765 (setq date (calendar-gregorian-from-absolute day)
22766 defd (encode-time 0 (or mod 0) (or hod 0)
22767 (nth 1 date) (nth 0 date) (nth 2 date))))))
22768 (or defd (current-time))))
22770 (defun org-mark-subtree (&optional up)
22771 "Mark the current subtree.
22772 This puts point at the start of the current subtree, and mark at
22773 the end. If a numeric prefix UP is given, move up into the
22774 hierarchy of headlines by UP levels before marking the subtree."
22775 (interactive "P")
22776 (org-with-limited-levels
22777 (cond ((org-at-heading-p) (beginning-of-line))
22778 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22779 (t (outline-previous-visible-heading 1))))
22780 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22781 (if (org-called-interactively-p 'any)
22782 (call-interactively 'org-mark-element)
22783 (org-mark-element)))
22786 ;;; Indentation
22788 (defun org--get-expected-indentation (element contentsp)
22789 "Expected indentation column for current line, according to ELEMENT.
22790 ELEMENT is an element containing point. CONTENTSP is non-nil
22791 when indentation is to be computed according to contents of
22792 ELEMENT."
22793 (let ((type (org-element-type element))
22794 (start (org-element-property :begin element))
22795 (post-affiliated (org-element-property :post-affiliated element)))
22796 (org-with-wide-buffer
22797 (cond
22798 (contentsp
22799 (case type
22800 ((diary-sexp footnote-definition) 0)
22801 ((headline inlinetask nil)
22802 (if (not org-adapt-indentation) 0
22803 (let ((level (org-current-level)))
22804 (if level (1+ level) 0))))
22805 ((item plain-list) (org-list-item-body-column post-affiliated))
22807 (goto-char start)
22808 (org-get-indentation))))
22809 ((memq type '(headline inlinetask nil))
22810 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22811 (org--get-expected-indentation element t)
22813 ((memq type '(diary-sexp footnote-definition)) 0)
22814 ;; First paragraph of a footnote definition or an item.
22815 ;; Indent like parent.
22816 ((< (line-beginning-position) start)
22817 (org--get-expected-indentation
22818 (org-element-property :parent element) t))
22819 ;; At first line: indent according to previous sibling, if any,
22820 ;; ignoring footnote definitions and inline tasks, or parent's
22821 ;; contents.
22822 ((= (line-beginning-position) start)
22823 (catch 'exit
22824 (while t
22825 (if (= (point-min) start) (throw 'exit 0)
22826 (goto-char (1- start))
22827 (let* ((previous (org-element-at-point))
22828 (parent previous))
22829 (while (and parent (<= (org-element-property :end parent) start))
22830 (setq previous parent
22831 parent (org-element-property :parent parent)))
22832 (cond
22833 ((not previous) (throw 'exit 0))
22834 ((> (org-element-property :end previous) start)
22835 (throw 'exit (org--get-expected-indentation previous t)))
22836 ((memq (org-element-type previous)
22837 '(footnote-definition inlinetask))
22838 (setq start (org-element-property :begin previous)))
22839 (t (goto-char (org-element-property :begin previous))
22840 (throw 'exit
22841 (if (bolp) (org-get-indentation)
22842 ;; At first paragraph in an item or
22843 ;; a footnote definition.
22844 (org--get-expected-indentation
22845 (org-element-property :parent previous) t))))))))))
22846 ;; Otherwise, move to the first non-blank line above.
22848 (beginning-of-line)
22849 (let ((pos (point)))
22850 (skip-chars-backward " \r\t\n")
22851 (cond
22852 ;; Two blank lines end a footnote definition or a plain
22853 ;; list. When we indent an empty line after them, the
22854 ;; containing list or footnote definition is over, so it
22855 ;; qualifies as a previous sibling. Therefore, we indent
22856 ;; like its first line.
22857 ((and (memq type '(footnote-definition plain-list))
22858 (> (count-lines (point) pos) 2))
22859 (goto-char start)
22860 (org-get-indentation))
22861 ;; Line above is the first one of a paragraph at the
22862 ;; beginning of an item or a footnote definition. Indent
22863 ;; like parent.
22864 ((< (line-beginning-position) start)
22865 (org--get-expected-indentation
22866 (org-element-property :parent element) t))
22867 ;; Line above is the beginning of an element, i.e., point
22868 ;; was originally on the blank lines between element's start
22869 ;; and contents.
22870 ((= (line-beginning-position) post-affiliated)
22871 (org--get-expected-indentation element t))
22872 ;; POS is after contents in a greater element. Indent like
22873 ;; the beginning of the element.
22875 ;; As a special case, if point is at the end of a footnote
22876 ;; definition or an item, indent like the very last element
22877 ;; within.
22878 ((and (not (eq type 'paragraph))
22879 (let ((cend (org-element-property :contents-end element)))
22880 (and cend (<= cend pos))))
22881 (if (memq type '(footnote-definition item plain-list))
22882 (let ((last (org-element-at-point)))
22883 (org--get-expected-indentation
22884 last
22885 (memq (org-element-type last)
22886 '(footnote-definition item plain-list))))
22887 (goto-char start)
22888 (org-get-indentation)))
22889 ;; In any other case, indent like the current line.
22890 (t (org-get-indentation)))))))))
22892 (defun org--align-node-property ()
22893 "Align node property at point.
22894 Alignment is done according to `org-property-format', which see."
22895 (when (save-excursion
22896 (beginning-of-line)
22897 (looking-at org-property-re))
22898 (replace-match
22899 (concat (match-string 4)
22900 (org-trim
22901 (format org-property-format (match-string 1) (match-string 3))))
22902 t t)))
22904 (defun org-indent-line ()
22905 "Indent line depending on context.
22907 Indentation is done according to the following rules:
22909 - Footnote definitions, diary sexps, headlines and inline tasks
22910 have to start at column 0.
22912 - On the very first line of an element, consider, in order, the
22913 next rules until one matches:
22915 1. If there's a sibling element before, ignoring footnote
22916 definitions and inline tasks, indent like its first line.
22918 2. If element has a parent, indent like its contents. More
22919 precisely, if parent is an item, indent after the
22920 description part, if any, or the bullet (see
22921 `org-list-description-max-indent'). Else, indent like
22922 parent's first line.
22924 3. Otherwise, indent relatively to current level, if
22925 `org-adapt-indentation' is non-nil, or to left margin.
22927 - On a blank line at the end of an element, indent according to
22928 the type of the element. More precisely
22930 1. If element is a plain list, an item, or a footnote
22931 definition, indent like the very last element within.
22933 2. If element is a paragraph, indent like its last non blank
22934 line.
22936 3. Otherwise, indent like its very first line.
22938 - In the code part of a source block, use language major mode
22939 to indent current line if `org-src-tab-acts-natively' is
22940 non-nil. If it is nil, do nothing.
22942 - Otherwise, indent like the first non-blank line above.
22944 The function doesn't indent an item as it could break the whole
22945 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22946 \\[org-shiftmetaright].
22948 Also align node properties according to `org-property-format'."
22949 (interactive)
22950 (cond
22951 (orgstruct-is-++
22952 (let ((indent-line-function
22953 (cadadr (assq 'indent-line-function org-fb-vars))))
22954 (indent-according-to-mode)))
22955 ((org-at-heading-p) 'noindent)
22957 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22958 (type (org-element-type element)))
22959 (cond ((and (memq type '(plain-list item))
22960 (= (line-beginning-position)
22961 (org-element-property :post-affiliated element)))
22962 'noindent)
22963 ((and (eq type 'src-block)
22964 org-src-tab-acts-natively
22965 (> (line-beginning-position)
22966 (org-element-property :post-affiliated element))
22967 (< (line-beginning-position)
22968 (org-with-wide-buffer
22969 (goto-char (org-element-property :end element))
22970 (skip-chars-backward " \r\t\n")
22971 (line-beginning-position))))
22972 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22974 (let ((column (org--get-expected-indentation element nil)))
22975 ;; Preserve current column.
22976 (if (<= (current-column) (current-indentation))
22977 (org-indent-line-to column)
22978 (save-excursion (org-indent-line-to column))))
22979 ;; Align node property. Also preserve current column.
22980 (when (eq type 'node-property)
22981 (let ((column (current-column)))
22982 (org--align-node-property)
22983 (org-move-to-column column)))))))))
22985 (defun org-indent-region (start end)
22986 "Indent each non-blank line in the region.
22987 Called from a program, START and END specify the region to
22988 indent. The function will not indent contents of example blocks,
22989 verse blocks and export blocks as leading white spaces are
22990 assumed to be significant there."
22991 (interactive "r")
22992 (save-excursion
22993 (goto-char start)
22994 (skip-chars-forward " \r\t\n")
22995 (unless (eobp) (beginning-of-line))
22996 (let ((indent-to
22997 (lambda (ind pos)
22998 ;; Set IND as indentation for all lines between point and
22999 ;; POS. Blank lines are ignored. Leave point after POS
23000 ;; once done.
23001 (let ((limit (copy-marker pos)))
23002 (while (< (point) limit)
23003 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23004 (forward-line))
23005 (set-marker limit nil))))
23006 (end (copy-marker end)))
23007 (while (< (point) end)
23008 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23009 (let* ((element (org-element-at-point))
23010 (type (org-element-type element))
23011 (element-end (copy-marker (org-element-property :end element)))
23012 (ind (org--get-expected-indentation element nil)))
23013 (cond
23014 ((or (memq type '(paragraph table table-row))
23015 (not (or (org-element-property :contents-begin element)
23016 (memq type
23017 '(example-block export-block src-block)))))
23018 ;; Elements here are indented as a single block. Also
23019 ;; align node properties.
23020 (when (eq type 'node-property)
23021 (org--align-node-property)
23022 (beginning-of-line))
23023 (funcall indent-to ind (min element-end end)))
23025 ;; Elements in this category consist of three parts:
23026 ;; before the contents, the contents, and after the
23027 ;; contents. The contents are treated specially,
23028 ;; according to the element type, or not indented at
23029 ;; all. Other parts are indented as a single block.
23030 (let* ((post (copy-marker
23031 (org-element-property :post-affiliated element)))
23032 (cbeg
23033 (copy-marker
23034 (cond
23035 ((not (org-element-property :contents-begin element))
23036 ;; Fake contents for source blocks.
23037 (org-with-wide-buffer
23038 (goto-char post)
23039 (forward-line)
23040 (point)))
23041 ((memq type '(footnote-definition item plain-list))
23042 ;; Contents in these elements could start on
23043 ;; the same line as the beginning of the
23044 ;; element. Make sure we start indenting
23045 ;; from the second line.
23046 (org-with-wide-buffer
23047 (goto-char post)
23048 (end-of-line)
23049 (skip-chars-forward " \r\t\n")
23050 (if (eobp) (point) (line-beginning-position))))
23051 (t (org-element-property :contents-begin element)))))
23052 (cend (copy-marker
23053 (or (org-element-property :contents-end element)
23054 ;; Fake contents for source blocks.
23055 (org-with-wide-buffer
23056 (goto-char element-end)
23057 (skip-chars-backward " \r\t\n")
23058 (line-beginning-position)))
23059 t)))
23060 ;; Do not change items indentation individually as it
23061 ;; might break the list as a whole. On the other
23062 ;; hand, when at a plain list, indent it as a whole.
23063 (cond ((eq type 'plain-list)
23064 (let ((offset (- ind (org-get-indentation))))
23065 (unless (zerop offset)
23066 (indent-rigidly (org-element-property :begin element)
23067 (org-element-property :end element)
23068 offset))
23069 (goto-char cbeg)))
23070 ((eq type 'item) (goto-char cbeg))
23071 (t (funcall indent-to ind (min cbeg end))))
23072 (when (< (point) end)
23073 (case type
23074 ((example-block export-block verse-block))
23075 (src-block
23076 ;; In a source block, indent source code
23077 ;; according to language major mode, but only if
23078 ;; `org-src-tab-acts-natively' is non-nil.
23079 (when (and (< (point) end) org-src-tab-acts-natively)
23080 (ignore-errors
23081 (org-babel-do-in-edit-buffer
23082 (indent-region (point-min) (point-max))))))
23083 (t (org-indent-region (point) (min cend end))))
23084 (goto-char (min cend end))
23085 (when (< (point) end)
23086 (funcall indent-to ind (min element-end end))))
23087 (set-marker post nil)
23088 (set-marker cbeg nil)
23089 (set-marker cend nil))))
23090 (set-marker element-end nil))))
23091 (set-marker end nil))))
23093 (defun org-indent-drawer ()
23094 "Indent the drawer at point."
23095 (interactive)
23096 (unless (save-excursion
23097 (beginning-of-line)
23098 (org-looking-at-p org-drawer-regexp))
23099 (user-error "Not at a drawer"))
23100 (let ((element (org-element-at-point)))
23101 (unless (memq (org-element-type element) '(drawer property-drawer))
23102 (user-error "Not at a drawer"))
23103 (org-with-wide-buffer
23104 (org-indent-region (org-element-property :begin element)
23105 (org-element-property :end element))))
23106 (message "Drawer at point indented"))
23108 (defun org-indent-block ()
23109 "Indent the block at point."
23110 (interactive)
23111 (unless (save-excursion
23112 (beginning-of-line)
23113 (let ((case-fold-search t))
23114 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23115 (user-error "Not at a block"))
23116 (let ((element (org-element-at-point)))
23117 (unless (memq (org-element-type element)
23118 '(comment-block center-block dynamic-block example-block
23119 export-block quote-block special-block
23120 src-block verse-block))
23121 (user-error "Not at a block"))
23122 (org-with-wide-buffer
23123 (org-indent-region (org-element-property :begin element)
23124 (org-element-property :end element))))
23125 (message "Block at point indented"))
23128 ;;; Filling
23130 ;; We use our own fill-paragraph and auto-fill functions.
23132 ;; `org-fill-paragraph' relies on adaptive filling and context
23133 ;; checking. Appropriate `fill-prefix' is computed with
23134 ;; `org-adaptive-fill-function'.
23136 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23137 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23138 ;; `org-adaptive-fill-function' value. Internally,
23139 ;; `org-comment-line-break-function' breaks the line.
23141 ;; `org-setup-filling' installs filling and auto-filling related
23142 ;; variables during `org-mode' initialization.
23144 (defvar org-element-paragraph-separate) ; org-element.el
23145 (defun org-setup-filling ()
23146 (require 'org-element)
23147 ;; Prevent auto-fill from inserting unwanted new items.
23148 (when (boundp 'fill-nobreak-predicate)
23149 (setq-local
23150 fill-nobreak-predicate
23151 (org-uniquify
23152 (append fill-nobreak-predicate
23153 '(org-fill-line-break-nobreak-p
23154 org-fill-paragraph-with-timestamp-nobreak-p)))))
23155 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23156 (setq-local paragraph-start paragraph-ending)
23157 (setq-local paragraph-separate paragraph-ending))
23158 (setq-local fill-paragraph-function 'org-fill-paragraph)
23159 (setq-local auto-fill-inhibit-regexp nil)
23160 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23161 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23162 (setq-local comment-line-break-function 'org-comment-line-break-function))
23164 (defun org-fill-line-break-nobreak-p ()
23165 "Non-nil when a new line at point would create an Org line break."
23166 (save-excursion
23167 (skip-chars-backward "[ \t]")
23168 (skip-chars-backward "\\\\")
23169 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23171 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23172 "Non-nil when a new line at point would split a timestamp."
23173 (and (org-at-timestamp-p t)
23174 (not (looking-at org-ts-regexp-both))))
23176 (declare-function message-in-body-p "message" ())
23177 (defvar orgtbl-line-start-regexp) ; From org-table.el
23178 (defun org-adaptive-fill-function ()
23179 "Compute a fill prefix for the current line.
23180 Return fill prefix, as a string, or nil if current line isn't
23181 meant to be filled. For convenience, if `adaptive-fill-regexp'
23182 matches in paragraphs or comments, use it."
23183 (catch 'exit
23184 (when (derived-mode-p 'message-mode)
23185 (save-excursion
23186 (beginning-of-line)
23187 (cond ((not (message-in-body-p)) (throw 'exit nil))
23188 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23189 ((looking-at message-cite-prefix-regexp)
23190 (throw 'exit (match-string-no-properties 0)))
23191 ((looking-at org-outline-regexp)
23192 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23193 (org-with-wide-buffer
23194 (unless (org-at-heading-p)
23195 (let* ((p (line-beginning-position))
23196 (element (save-excursion
23197 (beginning-of-line)
23198 (org-element-at-point)))
23199 (type (org-element-type element))
23200 (post-affiliated (org-element-property :post-affiliated element)))
23201 (unless (< p post-affiliated)
23202 (case type
23203 (comment
23204 (save-excursion
23205 (beginning-of-line)
23206 (looking-at "[ \t]*")
23207 (concat (match-string 0) "# ")))
23208 (footnote-definition "")
23209 ((item plain-list)
23210 (make-string (org-list-item-body-column post-affiliated) ?\s))
23211 (paragraph
23212 ;; Fill prefix is usually the same as the current line,
23213 ;; unless the paragraph is at the beginning of an item.
23214 (let ((parent (org-element-property :parent element)))
23215 (save-excursion
23216 (beginning-of-line)
23217 (cond ((eq (org-element-type parent) 'item)
23218 (make-string (org-list-item-body-column
23219 (org-element-property :begin parent))
23220 ?\s))
23221 ((and adaptive-fill-regexp
23222 ;; Locally disable
23223 ;; `adaptive-fill-function' to let
23224 ;; `fill-context-prefix' handle
23225 ;; `adaptive-fill-regexp' variable.
23226 (let (adaptive-fill-function)
23227 (fill-context-prefix
23228 post-affiliated
23229 (org-element-property :end element)))))
23230 ((looking-at "[ \t]+") (match-string 0))
23231 (t "")))))
23232 (comment-block
23233 ;; Only fill contents if P is within block boundaries.
23234 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23235 (forward-line)
23236 (point)))
23237 (cend (save-excursion
23238 (goto-char (org-element-property :end element))
23239 (skip-chars-backward " \r\t\n")
23240 (line-beginning-position))))
23241 (when (and (>= p cbeg) (< p cend))
23242 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23243 (match-string 0)
23244 "")))))))))))
23246 (declare-function message-goto-body "message" ())
23247 (defvar message-cite-prefix-regexp) ; From message.el
23248 (defun org-fill-paragraph (&optional justify)
23249 "Fill element at point, when applicable.
23251 This function only applies to comment blocks, comments, example
23252 blocks and paragraphs. Also, as a special case, re-align table
23253 when point is at one.
23255 If JUSTIFY is non-nil (interactively, with prefix argument),
23256 justify as well. If `sentence-end-double-space' is non-nil, then
23257 period followed by one space does not end a sentence, so don't
23258 break a line there. The variable `fill-column' controls the
23259 width for filling.
23261 For convenience, when point is at a plain list, an item or
23262 a footnote definition, try to fill the first paragraph within."
23263 (interactive)
23264 (if (and (derived-mode-p 'message-mode)
23265 (or (not (message-in-body-p))
23266 (save-excursion (move-beginning-of-line 1)
23267 (looking-at message-cite-prefix-regexp))))
23268 ;; First ensure filling is correct in message-mode.
23269 (let ((fill-paragraph-function
23270 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23271 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23272 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23273 (paragraph-separate
23274 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23275 (fill-paragraph nil))
23276 (with-syntax-table org-mode-transpose-word-syntax-table
23277 ;; Move to end of line in order to get the first paragraph
23278 ;; within a plain list or a footnote definition.
23279 (let ((element (save-excursion
23280 (end-of-line)
23281 (or (ignore-errors (org-element-at-point))
23282 (user-error "An element cannot be parsed line %d"
23283 (line-number-at-pos (point)))))))
23284 ;; First check if point is in a blank line at the beginning of
23285 ;; the buffer. In that case, ignore filling.
23286 (case (org-element-type element)
23287 ;; Use major mode filling function is src blocks.
23288 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23289 ;; Align Org tables, leave table.el tables as-is.
23290 (table-row (org-table-align) t)
23291 (table
23292 (when (eq (org-element-property :type element) 'org)
23293 (save-excursion
23294 (goto-char (org-element-property :post-affiliated element))
23295 (org-table-align)))
23297 (paragraph
23298 ;; Paragraphs may contain `line-break' type objects.
23299 (let ((beg (max (point-min)
23300 (org-element-property :contents-begin element)))
23301 (end (min (point-max)
23302 (org-element-property :contents-end element))))
23303 ;; Do nothing if point is at an affiliated keyword.
23304 (if (< (line-end-position) beg) t
23305 (when (derived-mode-p 'message-mode)
23306 ;; In `message-mode', do not fill following citation
23307 ;; in current paragraph nor text before message body.
23308 (let ((body-start (save-excursion (message-goto-body))))
23309 (when body-start (setq beg (max body-start beg))))
23310 (when (save-excursion
23311 (re-search-forward
23312 (concat "^" message-cite-prefix-regexp) end t))
23313 (setq end (match-beginning 0))))
23314 ;; Fill paragraph, taking line breaks into account.
23315 (save-excursion
23316 (goto-char beg)
23317 (let ((cuts (list beg)))
23318 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23319 (when (eq 'line-break
23320 (org-element-type
23321 (save-excursion (backward-char)
23322 (org-element-context))))
23323 (push (point) cuts)))
23324 (dolist (c (delq end cuts))
23325 (fill-region-as-paragraph c end justify)
23326 (setq end c))))
23327 t)))
23328 ;; Contents of `comment-block' type elements should be
23329 ;; filled as plain text, but only if point is within block
23330 ;; markers.
23331 (comment-block
23332 (let* ((case-fold-search t)
23333 (beg (save-excursion
23334 (goto-char (org-element-property :begin element))
23335 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23336 (forward-line)
23337 (point)))
23338 (end (save-excursion
23339 (goto-char (org-element-property :end element))
23340 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23341 (line-beginning-position))))
23342 (if (or (< (point) beg) (> (point) end)) t
23343 (fill-region-as-paragraph
23344 (save-excursion (end-of-line)
23345 (re-search-backward "^[ \t]*$" beg 'move)
23346 (line-beginning-position))
23347 (save-excursion (beginning-of-line)
23348 (re-search-forward "^[ \t]*$" end 'move)
23349 (line-beginning-position))
23350 justify))))
23351 ;; Fill comments.
23352 (comment
23353 (let ((begin (org-element-property :post-affiliated element))
23354 (end (org-element-property :end element)))
23355 (when (and (>= (point) begin) (<= (point) end))
23356 (let ((begin (save-excursion
23357 (end-of-line)
23358 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23359 (progn (forward-line) (point))
23360 begin)))
23361 (end (save-excursion
23362 (end-of-line)
23363 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23364 (1- (line-beginning-position))
23365 (skip-chars-backward " \r\t\n")
23366 (line-end-position)))))
23367 ;; Do not fill comments when at a blank line.
23368 (when (> end begin)
23369 (let ((fill-prefix
23370 (save-excursion
23371 (beginning-of-line)
23372 (looking-at "[ \t]*#")
23373 (let ((comment-prefix (match-string 0)))
23374 (goto-char (match-end 0))
23375 (if (looking-at adaptive-fill-regexp)
23376 (concat comment-prefix (match-string 0))
23377 (concat comment-prefix " "))))))
23378 (save-excursion
23379 (fill-region-as-paragraph begin end justify))))))
23381 ;; Ignore every other element.
23382 (otherwise t))))))
23384 (defun org-auto-fill-function ()
23385 "Auto-fill function."
23386 ;; Check if auto-filling is meaningful.
23387 (let ((fc (current-fill-column)))
23388 (when (and fc (> (current-column) fc))
23389 (let* ((fill-prefix (org-adaptive-fill-function))
23390 ;; Enforce empty fill prefix, if required. Otherwise, it
23391 ;; will be computed again.
23392 (adaptive-fill-mode (not (equal fill-prefix ""))))
23393 (when fill-prefix (do-auto-fill))))))
23395 (defun org-comment-line-break-function (&optional soft)
23396 "Break line at point and indent, continuing comment if within one.
23397 The inserted newline is marked hard if variable
23398 `use-hard-newlines' is true, unless optional argument SOFT is
23399 non-nil."
23400 (if soft (insert-and-inherit ?\n) (newline 1))
23401 (save-excursion (forward-char -1) (delete-horizontal-space))
23402 (delete-horizontal-space)
23403 (indent-to-left-margin)
23404 (insert-before-markers-and-inherit fill-prefix))
23407 ;;; Fixed Width Areas
23409 (defun org-toggle-fixed-width ()
23410 "Toggle fixed-width markup.
23412 Add or remove fixed-width markup on current line, whenever it
23413 makes sense. Return an error otherwise.
23415 If a region is active and if it contains only fixed-width areas
23416 or blank lines, remove all fixed-width markup in it. If the
23417 region contains anything else, convert all non-fixed-width lines
23418 to fixed-width ones.
23420 Blank lines at the end of the region are ignored unless the
23421 region only contains such lines."
23422 (interactive)
23423 (if (not (org-region-active-p))
23424 ;; No region:
23426 ;; Remove fixed width marker only in a fixed-with element.
23428 ;; Add fixed width maker in paragraphs, in blank lines after
23429 ;; elements or at the beginning of a headline or an inlinetask,
23430 ;; and before any one-line elements (e.g., a clock).
23431 (progn
23432 (beginning-of-line)
23433 (let* ((element (org-element-at-point))
23434 (type (org-element-type element)))
23435 (cond
23436 ((and (eq type 'fixed-width)
23437 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23438 (replace-match
23439 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23440 ((and (memq type '(babel-call clock comment diary-sexp headline
23441 horizontal-rule keyword paragraph
23442 planning))
23443 (<= (org-element-property :post-affiliated element) (point)))
23444 (skip-chars-forward " \t")
23445 (insert ": "))
23446 ((and (org-looking-at-p "[ \t]*$")
23447 (or (eq type 'inlinetask)
23448 (save-excursion
23449 (skip-chars-forward " \r\t\n")
23450 (<= (org-element-property :end element) (point)))))
23451 (delete-region (point) (line-end-position))
23452 (org-indent-line)
23453 (insert ": "))
23454 (t (user-error "Cannot insert a fixed-width line here")))))
23455 ;; Region active.
23456 (let* ((begin (save-excursion
23457 (goto-char (region-beginning))
23458 (line-beginning-position)))
23459 (end (copy-marker
23460 (save-excursion
23461 (goto-char (region-end))
23462 (unless (eolp) (beginning-of-line))
23463 (if (save-excursion (re-search-backward "\\S-" begin t))
23464 (progn (skip-chars-backward " \r\t\n") (point))
23465 (point)))))
23466 (all-fixed-width-p
23467 (catch 'not-all-p
23468 (save-excursion
23469 (goto-char begin)
23470 (skip-chars-forward " \r\t\n")
23471 (when (eobp) (throw 'not-all-p nil))
23472 (while (< (point) end)
23473 (let ((element (org-element-at-point)))
23474 (if (eq (org-element-type element) 'fixed-width)
23475 (goto-char (org-element-property :end element))
23476 (throw 'not-all-p nil))))
23477 t))))
23478 (if all-fixed-width-p
23479 (save-excursion
23480 (goto-char begin)
23481 (while (< (point) end)
23482 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23483 (replace-match
23484 "" nil nil nil
23485 (if (= (line-end-position) (match-end 0)) 0 1)))
23486 (forward-line)))
23487 (let ((min-ind (point-max)))
23488 ;; Find minimum indentation across all lines.
23489 (save-excursion
23490 (goto-char begin)
23491 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23492 (setq min-ind 0)
23493 (catch 'zerop
23494 (while (< (point) end)
23495 (unless (org-looking-at-p "[ \t]*$")
23496 (let ((ind (org-get-indentation)))
23497 (setq min-ind (min min-ind ind))
23498 (when (zerop ind) (throw 'zerop t))))
23499 (forward-line)))))
23500 ;; Loop over all lines and add fixed-width markup everywhere
23501 ;; but in fixed-width lines.
23502 (save-excursion
23503 (goto-char begin)
23504 (while (< (point) end)
23505 (cond
23506 ((org-at-heading-p)
23507 (insert ": ")
23508 (forward-line)
23509 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23510 (insert ":")
23511 (forward-line)))
23512 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23513 (let* ((element (org-element-at-point))
23514 (element-end (org-element-property :end element)))
23515 (if (eq (org-element-type element) 'fixed-width)
23516 (progn (goto-char element-end)
23517 (skip-chars-backward " \r\t\n")
23518 (forward-line))
23519 (let ((limit (min end element-end)))
23520 (while (< (point) limit)
23521 (org-move-to-column min-ind t)
23522 (insert ": ")
23523 (forward-line))))))
23525 (org-move-to-column min-ind t)
23526 (insert ": ")
23527 (forward-line)))))))
23528 (set-marker end nil))))
23531 ;;; Comments
23533 ;; Org comments syntax is quite complex. It requires the entire line
23534 ;; to be just a comment. Also, even with the right syntax at the
23535 ;; beginning of line, some some elements (i.e. verse-block or
23536 ;; example-block) don't accept comments. Usual Emacs comment commands
23537 ;; cannot cope with those requirements. Therefore, Org replaces them.
23539 ;; Org still relies on `comment-dwim', but cannot trust
23540 ;; `comment-only-p'. So, `comment-region-function' and
23541 ;; `uncomment-region-function' both point
23542 ;; to`org-comment-or-uncomment-region'. Eventually,
23543 ;; `org-insert-comment' takes care of insertion of comments at the
23544 ;; beginning of line.
23546 ;; `org-setup-comments-handling' install comments related variables
23547 ;; during `org-mode' initialization.
23549 (defun org-setup-comments-handling ()
23550 (interactive)
23551 (setq-local comment-use-syntax nil)
23552 (setq-local comment-start "# ")
23553 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23554 (setq-local comment-insert-comment-function 'org-insert-comment)
23555 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23556 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23558 (defun org-insert-comment ()
23559 "Insert an empty comment above current line.
23560 If the line is empty, insert comment at its beginning. When
23561 point is within a source block, comment according to the related
23562 major mode."
23563 (if (let ((element (org-element-at-point)))
23564 (and (eq (org-element-type element) 'src-block)
23565 (< (save-excursion
23566 (goto-char (org-element-property :post-affiliated element))
23567 (line-end-position))
23568 (point))
23569 (> (save-excursion
23570 (goto-char (org-element-property :end element))
23571 (skip-chars-backward " \r\t\n")
23572 (line-beginning-position))
23573 (point))))
23574 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23575 (beginning-of-line)
23576 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23577 (open-line 1))
23578 (org-indent-line)
23579 (insert "# ")))
23581 (defvar comment-empty-lines) ; From newcomment.el.
23582 (defun org-comment-or-uncomment-region (beg end &rest _)
23583 "Comment or uncomment each non-blank line in the region.
23584 Uncomment each non-blank line between BEG and END if it only
23585 contains commented lines. Otherwise, comment them. If region is
23586 strictly within a source block, use appropriate comment syntax."
23587 (if (let ((element (org-element-at-point)))
23588 (and (eq (org-element-type element) 'src-block)
23589 (< (save-excursion
23590 (goto-char (org-element-property :post-affiliated element))
23591 (line-end-position))
23592 beg)
23593 (>= (save-excursion
23594 (goto-char (org-element-property :end element))
23595 (skip-chars-backward " \r\t\n")
23596 (line-beginning-position))
23597 end)))
23598 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23599 (save-restriction
23600 ;; Restrict region
23601 (narrow-to-region (save-excursion (goto-char beg)
23602 (skip-chars-forward " \r\t\n" end)
23603 (line-beginning-position))
23604 (save-excursion (goto-char end)
23605 (skip-chars-backward " \r\t\n" beg)
23606 (line-end-position)))
23607 (let ((uncommentp
23608 ;; UNCOMMENTP is non-nil when every non blank line between
23609 ;; BEG and END is a comment.
23610 (save-excursion
23611 (goto-char (point-min))
23612 (while (and (not (eobp))
23613 (let ((element (org-element-at-point)))
23614 (and (eq (org-element-type element) 'comment)
23615 (goto-char (min (point-max)
23616 (org-element-property
23617 :end element)))))))
23618 (eobp))))
23619 (if uncommentp
23620 ;; Only blank lines and comments in region: uncomment it.
23621 (save-excursion
23622 (goto-char (point-min))
23623 (while (not (eobp))
23624 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23625 (replace-match "" nil nil nil 1))
23626 (forward-line)))
23627 ;; Comment each line in region.
23628 (let ((min-indent (point-max)))
23629 ;; First find the minimum indentation across all lines.
23630 (save-excursion
23631 (goto-char (point-min))
23632 (while (and (not (eobp)) (not (zerop min-indent)))
23633 (unless (looking-at "[ \t]*$")
23634 (setq min-indent (min min-indent (current-indentation))))
23635 (forward-line)))
23636 ;; Then loop over all lines.
23637 (save-excursion
23638 (goto-char (point-min))
23639 (while (not (eobp))
23640 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23641 ;; Don't get fooled by invisible text (e.g. link path)
23642 ;; when moving to column MIN-INDENT.
23643 (let ((buffer-invisibility-spec nil))
23644 (org-move-to-column min-indent t))
23645 (insert comment-start))
23646 (forward-line)))))))))
23648 (defun org-comment-dwim (_arg)
23649 "Call `comment-dwim' within a source edit buffer if needed."
23650 (interactive "*P")
23651 (if (org-in-src-block-p)
23652 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23653 (call-interactively 'comment-dwim)))
23656 ;;; Timestamps API
23658 ;; This section contains tools to operate on timestamp objects, as
23659 ;; returned by, e.g. `org-element-context'.
23661 (defun org-timestamp--to-internal-time (timestamp &optional end)
23662 "Encode TIMESTAMP object into Emacs internal time.
23663 Use end of date range or time range when END is non-nil."
23664 (apply #'encode-time
23665 (cons 0
23666 (mapcar
23667 (lambda (prop) (or (org-element-property prop timestamp) 0))
23668 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23669 '(:minute-start :hour-start :day-start :month-start
23670 :year-start))))))
23672 (defun org-timestamp-has-time-p (timestamp)
23673 "Non-nil when TIMESTAMP has a time specified."
23674 (org-element-property :hour-start timestamp))
23676 (defun org-timestamp-format (timestamp format &optional end utc)
23677 "Format a TIMESTAMP object into a string.
23679 FORMAT is a format specifier to be passed to
23680 `format-time-string'.
23682 When optional argument END is non-nil, use end of date-range or
23683 time-range, if possible.
23685 When optional argument UTC is non-nil, time will be expressed as
23686 Universal Time."
23687 (format-time-string
23688 format (org-timestamp--to-internal-time timestamp end) utc))
23690 (defun org-timestamp-split-range (timestamp &optional end)
23691 "Extract a TIMESTAMP object from a date or time range.
23693 END, when non-nil, means extract the end of the range.
23694 Otherwise, extract its start.
23696 Return a new timestamp object."
23697 (let ((type (org-element-property :type timestamp)))
23698 (if (memq type '(active inactive diary)) timestamp
23699 (let ((split-ts (org-element-copy timestamp)))
23700 ;; Set new type.
23701 (org-element-put-property
23702 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23703 ;; Copy start properties over end properties if END is
23704 ;; non-nil. Otherwise, copy end properties over `start' ones.
23705 (let ((p-alist '((:minute-start . :minute-end)
23706 (:hour-start . :hour-end)
23707 (:day-start . :day-end)
23708 (:month-start . :month-end)
23709 (:year-start . :year-end))))
23710 (dolist (p-cell p-alist)
23711 (org-element-put-property
23712 split-ts
23713 (funcall (if end #'car #'cdr) p-cell)
23714 (org-element-property
23715 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23716 ;; Eventually refresh `:raw-value'.
23717 (org-element-put-property split-ts :raw-value nil)
23718 (org-element-put-property
23719 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23721 (defun org-timestamp-translate (timestamp &optional boundary)
23722 "Translate TIMESTAMP object to custom format.
23724 Format string is defined in `org-time-stamp-custom-formats',
23725 which see.
23727 When optional argument BOUNDARY is non-nil, it is either the
23728 symbol `start' or `end'. In this case, only translate the
23729 starting or ending part of TIMESTAMP if it is a date or time
23730 range. Otherwise, translate both parts.
23732 Return timestamp as-is if `org-display-custom-times' is nil or if
23733 it has a `diary' type."
23734 (let ((type (org-element-property :type timestamp)))
23735 (if (or (not org-display-custom-times) (eq type 'diary))
23736 (org-element-interpret-data timestamp)
23737 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23738 org-time-stamp-custom-formats)))
23739 (if (and (not boundary) (memq type '(active-range inactive-range)))
23740 (concat (org-timestamp-format timestamp fmt)
23741 "--"
23742 (org-timestamp-format timestamp fmt t))
23743 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23747 ;;; Other stuff.
23749 (defvar reftex-docstruct-symbol)
23750 (defvar reftex-cite-format)
23751 (defvar org--rds)
23753 (defun org-reftex-citation ()
23754 "Use reftex-citation to insert a citation into the buffer.
23755 This looks for a line like
23757 #+BIBLIOGRAPHY: foo plain option:-d
23759 and derives from it that foo.bib is the bibliography file relevant
23760 for this document. It then installs the necessary environment for RefTeX
23761 to work in this buffer and calls `reftex-citation' to insert a citation
23762 into the buffer.
23764 Export of such citations to both LaTeX and HTML is handled by the contributed
23765 package ox-bibtex by Taru Karttunen."
23766 (interactive)
23767 (let ((reftex-docstruct-symbol 'org--rds)
23768 (reftex-cite-format "\\cite{%l}")
23769 org--rds bib)
23770 (save-excursion
23771 (save-restriction
23772 (widen)
23773 (let ((case-fold-search t)
23774 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23775 (if (not (save-excursion
23776 (or (re-search-forward re nil t)
23777 (re-search-backward re nil t))))
23778 (user-error "No bibliography defined in file")
23779 (setq bib (concat (match-string 1) ".bib")
23780 org--rds (list (list 'bib bib)))))))
23781 (call-interactively 'reftex-citation)))
23783 ;;;; Functions extending outline functionality
23785 (defun org-beginning-of-line (&optional arg)
23786 "Go to the beginning of the current line. If that is invisible, continue
23787 to a visible line beginning. This makes the function of C-a more intuitive.
23788 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23789 first attempt, and only move to after the tags when the cursor is already
23790 beyond the end of the headline."
23791 (interactive "P")
23792 (let ((pos (point))
23793 (special (if (consp org-special-ctrl-a/e)
23794 (car org-special-ctrl-a/e)
23795 org-special-ctrl-a/e))
23796 deactivate-mark refpos)
23797 (if (org-bound-and-true-p visual-line-mode)
23798 (beginning-of-visual-line 1)
23799 (beginning-of-line 1))
23800 (if (and arg (fboundp 'move-beginning-of-line))
23801 (call-interactively 'move-beginning-of-line)
23802 (unless (bobp)
23803 (backward-char 1)
23804 (if (org-truely-invisible-p)
23805 (while (and (not (bobp)) (org-truely-invisible-p))
23806 (backward-char 1)
23807 (beginning-of-line 1))
23808 (forward-char 1))))
23809 (when special
23810 (cond
23811 ((and (looking-at org-complex-heading-regexp)
23812 (eq (char-after (match-end 1)) ?\s))
23813 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23814 (point-at-eol)))
23815 (goto-char
23816 (if (eq special t)
23817 (cond ((> pos refpos) refpos)
23818 ((= pos (point)) refpos)
23819 (t (point)))
23820 (cond ((> pos (point)) (point))
23821 ((not (eq last-command this-command)) (point))
23822 (t refpos)))))
23823 ((org-at-item-p)
23824 ;; Being at an item and not looking at an the item means point
23825 ;; was previously moved to beginning of a visual line, which
23826 ;; doesn't contain the item. Therefore, do nothing special,
23827 ;; just stay here.
23828 (when (looking-at org-list-full-item-re)
23829 ;; Set special position at first white space character after
23830 ;; bullet, and check-box, if any.
23831 (let ((after-bullet
23832 (let ((box (match-end 3)))
23833 (if (not box) (match-end 1)
23834 (let ((after (char-after box)))
23835 (if (and after (= after ? )) (1+ box) box))))))
23836 ;; Special case: Move point to special position when
23837 ;; currently after it or at beginning of line.
23838 (if (eq special t)
23839 (when (or (> pos after-bullet) (= (point) pos))
23840 (goto-char after-bullet))
23841 ;; Reversed case: Move point to special position when
23842 ;; point was already at beginning of line and command is
23843 ;; repeated.
23844 (when (and (= (point) pos) (eq last-command this-command))
23845 (goto-char after-bullet))))))))
23846 (org-no-warnings
23847 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23848 (setq disable-point-adjustment
23849 (or (not (invisible-p (point)))
23850 (not (invisible-p (max (point-min) (1- (point))))))))
23852 (defun org-end-of-line (&optional arg)
23853 "Go to the end of the line.
23854 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23855 tags on the first attempt, and only move to after the tags when
23856 the cursor is already beyond the end of the headline."
23857 (interactive "P")
23858 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23859 org-special-ctrl-a/e))
23860 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23861 'end-of-visual-line)
23862 ((fboundp 'move-end-of-line) 'move-end-of-line)
23863 (t 'end-of-line)))
23864 deactivate-mark)
23865 (if (or (not special) arg) (call-interactively move-fun)
23866 (let* ((element (save-excursion (beginning-of-line)
23867 (org-element-at-point)))
23868 (type (org-element-type element)))
23869 (cond
23870 ((memq type '(headline inlinetask))
23871 (let ((pos (point)))
23872 (beginning-of-line 1)
23873 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23874 (if (eq special t)
23875 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23876 (goto-char (match-beginning 1))
23877 (goto-char (match-end 0)))
23878 (if (or (< pos (match-end 0))
23879 (not (eq this-command last-command)))
23880 (goto-char (match-end 0))
23881 (goto-char (match-beginning 1))))
23882 (call-interactively move-fun))))
23883 ((outline-invisible-p (line-end-position))
23884 ;; If element is hidden, `move-end-of-line' would put point
23885 ;; after it. Use `end-of-line' to stay on current line.
23886 (call-interactively 'end-of-line))
23887 (t (call-interactively move-fun)))))
23888 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23889 (setq disable-point-adjustment
23890 (or (not (invisible-p (point)))
23891 (not (invisible-p (max (point-min) (1- (point))))))))
23893 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23894 (define-key org-mode-map "\C-e" 'org-end-of-line)
23896 (defun org-backward-sentence (&optional _arg)
23897 "Go to beginning of sentence, or beginning of table field.
23898 This will call `backward-sentence' or `org-table-beginning-of-field',
23899 depending on context."
23900 (interactive)
23901 (let* ((element (org-element-at-point))
23902 (contents-begin (org-element-property :contents-begin element))
23903 (table (org-element-lineage element '(table) t)))
23904 (if (and table
23905 (> (point) contents-begin)
23906 (<= (point) (org-element-property :contents-end table)))
23907 (call-interactively #'org-table-beginning-of-field)
23908 (save-restriction
23909 (when (and contents-begin
23910 (< (point-min) contents-begin)
23911 (> (point) contents-begin))
23912 (narrow-to-region contents-begin
23913 (org-element-property :contents-end element)))
23914 (call-interactively #'backward-sentence)))))
23916 (defun org-forward-sentence (&optional _arg)
23917 "Go to end of sentence, or end of table field.
23918 This will call `forward-sentence' or `org-table-end-of-field',
23919 depending on context."
23920 (interactive)
23921 (let* ((element (org-element-at-point))
23922 (contents-end (org-element-property :contents-end element))
23923 (table (org-element-lineage element '(table) t)))
23924 (if (and table
23925 (>= (point) (org-element-property :contents-begin table))
23926 (< (point) contents-end))
23927 (call-interactively #'org-table-end-of-field)
23928 (save-restriction
23929 (when (and contents-end
23930 (> (point-max) contents-end)
23931 ;; Skip blank lines between elements.
23932 (< (org-element-property :end element)
23933 (save-excursion (goto-char contents-end)
23934 (skip-chars-forward " \r\t\n"))))
23935 (narrow-to-region (org-element-property :contents-begin element)
23936 contents-end))
23937 (call-interactively #'forward-sentence)))))
23939 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23940 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23942 (defun org-kill-line (&optional _arg)
23943 "Kill line, to tags or end of line."
23944 (interactive)
23945 (cond
23946 ((or (not org-special-ctrl-k)
23947 (bolp)
23948 (not (org-at-heading-p)))
23949 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23950 org-ctrl-k-protect-subtree
23951 (or (eq org-ctrl-k-protect-subtree 'error)
23952 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23953 (user-error "C-k aborted as it would kill a hidden subtree"))
23954 (call-interactively
23955 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23956 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23957 (kill-region (point) (match-beginning 1))
23958 (org-set-tags nil t))
23959 (t (kill-region (point) (point-at-eol)))))
23961 (define-key org-mode-map "\C-k" 'org-kill-line)
23963 (defun org-yank (&optional arg)
23964 "Yank. If the kill is a subtree, treat it specially.
23965 This command will look at the current kill and check if is a single
23966 subtree, or a series of subtrees[1]. If it passes the test, and if the
23967 cursor is at the beginning of a line or after the stars of a currently
23968 empty headline, then the yank is handled specially. How exactly depends
23969 on the value of the following variables, both set by default.
23971 `org-yank-folded-subtrees'
23972 When set, the subtree(s) will be folded after insertion, but only
23973 if doing so would now swallow text after the yanked text.
23975 `org-yank-adjusted-subtrees'
23976 When set, the subtree will be promoted or demoted in order to
23977 fit into the local outline tree structure, which means that the
23978 level will be adjusted so that it becomes the smaller one of the
23979 two *visible* surrounding headings.
23981 Any prefix to this command will cause `yank' to be called directly with
23982 no special treatment. In particular, a simple \\[universal-argument] prefix \
23983 will just
23984 plainly yank the text as it is.
23986 \[1] The test checks if the first non-white line is a heading
23987 and if there are no other headings with fewer stars."
23988 (interactive "P")
23989 (org-yank-generic 'yank arg))
23991 (defun org-yank-generic (command arg)
23992 "Perform some yank-like command.
23994 This function implements the behavior described in the `org-yank'
23995 documentation. However, it has been generalized to work for any
23996 interactive command with similar behavior."
23998 ;; pretend to be command COMMAND
23999 (setq this-command command)
24001 (if arg
24002 (call-interactively command)
24004 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24005 (and (org-kill-is-subtree-p)
24006 (or (bolp)
24007 (and (looking-at "[ \t]*$")
24008 (string-match
24009 "\\`\\*+\\'"
24010 (buffer-substring (point-at-bol) (point)))))))
24011 swallowp)
24012 (cond
24013 ((and subtreep org-yank-folded-subtrees)
24014 (let ((beg (point))
24015 end)
24016 (if (and subtreep org-yank-adjusted-subtrees)
24017 (org-paste-subtree nil nil 'for-yank)
24018 (call-interactively command))
24020 (setq end (point))
24021 (goto-char beg)
24022 (when (and (bolp) subtreep
24023 (not (setq swallowp
24024 (org-yank-folding-would-swallow-text beg end))))
24025 (org-with-limited-levels
24026 (or (looking-at org-outline-regexp)
24027 (re-search-forward org-outline-regexp-bol end t))
24028 (while (and (< (point) end) (looking-at org-outline-regexp))
24029 (outline-hide-subtree)
24030 (org-cycle-show-empty-lines 'folded)
24031 (condition-case nil
24032 (outline-forward-same-level 1)
24033 (error (goto-char end))))))
24034 (when swallowp
24035 (message
24036 "Inserted text not folded because that would swallow text"))
24038 (goto-char end)
24039 (skip-chars-forward " \t\n\r")
24040 (beginning-of-line 1)
24041 (push-mark beg 'nomsg)))
24042 ((and subtreep org-yank-adjusted-subtrees)
24043 (let ((beg (point-at-bol)))
24044 (org-paste-subtree nil nil 'for-yank)
24045 (push-mark beg 'nomsg)))
24047 (call-interactively command))))))
24049 (defun org-yank-folding-would-swallow-text (beg end)
24050 "Would hide-subtree at BEG swallow any text after END?"
24051 (let (level)
24052 (org-with-limited-levels
24053 (save-excursion
24054 (goto-char beg)
24055 (when (or (looking-at org-outline-regexp)
24056 (re-search-forward org-outline-regexp-bol end t))
24057 (setq level (org-outline-level)))
24058 (goto-char end)
24059 (skip-chars-forward " \t\r\n\v\f")
24060 (not (or (eobp)
24061 (and (bolp) (looking-at-p org-outline-regexp)
24062 (<= (org-outline-level) level))))))))
24064 (define-key org-mode-map "\C-y" 'org-yank)
24066 (defun org-truely-invisible-p ()
24067 "Check if point is at a character currently not visible.
24068 This version does not only check the character property, but also
24069 `visible-mode'."
24070 ;; Early versions of noutline don't have `outline-invisible-p'.
24071 (unless (org-bound-and-true-p visible-mode)
24072 (outline-invisible-p)))
24074 (defun org-invisible-p2 ()
24075 "Check if point is at a character currently not visible."
24076 (save-excursion
24077 (when (and (eolp) (not (bobp))) (backward-char 1))
24078 ;; Early versions of noutline don't have `outline-invisible-p'.
24079 (outline-invisible-p)))
24081 (defun org-back-to-heading (&optional invisible-ok)
24082 "Call `outline-back-to-heading', but provide a better error message."
24083 (condition-case nil
24084 (outline-back-to-heading invisible-ok)
24085 (error (error "Before first headline at position %d in buffer %s"
24086 (point) (current-buffer)))))
24088 (defun org-before-first-heading-p ()
24089 "Before first heading?"
24090 (save-excursion
24091 (end-of-line)
24092 (null (re-search-backward org-outline-regexp-bol nil t))))
24094 (defun org-at-heading-p (&optional ignored)
24095 (outline-on-heading-p t))
24096 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24097 ;;; warning was only added in Org 9.0, which should be taken into
24098 ;;; account when deciding when to remove the alias.
24099 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24101 (defun org-in-commented-heading-p (&optional no-inheritance)
24102 "Non-nil if point is under a commented heading.
24103 This function also checks ancestors of the current headline,
24104 unless optional argument NO-INHERITANCE is non-nil."
24105 (cond
24106 ((org-before-first-heading-p) nil)
24107 ((let ((headline (nth 4 (org-heading-components))))
24108 (and headline
24109 (let ((case-fold-search nil))
24110 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24111 headline)))))
24112 (no-inheritance nil)
24114 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24116 (defun org-at-comment-p nil
24117 "Is cursor in a commented line?"
24118 (save-excursion
24119 (save-match-data
24120 (beginning-of-line)
24121 (looking-at "^[ \t]*# "))))
24123 (defun org-at-drawer-p nil
24124 "Is cursor at a drawer keyword?"
24125 (save-excursion
24126 (move-beginning-of-line 1)
24127 (looking-at org-drawer-regexp)))
24129 (defun org-at-block-p nil
24130 "Is cursor at a block keyword?"
24131 (save-excursion
24132 (move-beginning-of-line 1)
24133 (looking-at org-block-regexp)))
24135 (defun org-point-at-end-of-empty-headline ()
24136 "If point is at the end of an empty headline, return t, else nil.
24137 If the heading only contains a TODO keyword, it is still still considered
24138 empty."
24139 (and (looking-at "[ \t]*$")
24140 (when org-todo-line-regexp
24141 (save-excursion
24142 (beginning-of-line 1)
24143 (let ((case-fold-search nil))
24144 (looking-at org-todo-line-regexp)
24145 (string= (match-string 3) ""))))))
24147 (defun org-at-heading-or-item-p ()
24148 (or (org-at-heading-p) (org-at-item-p)))
24150 (defun org-at-target-p ()
24151 (or (org-in-regexp org-radio-target-regexp)
24152 (org-in-regexp org-target-regexp)))
24153 ;; Compatibility alias with Org versions < 7.8.03
24154 (defalias 'org-on-target-p 'org-at-target-p)
24156 (defun org-up-heading-all (arg)
24157 "Move to the heading line of which the present line is a subheading.
24158 This function considers both visible and invisible heading lines.
24159 With argument, move up ARG levels."
24160 (if (fboundp 'outline-up-heading-all)
24161 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24162 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24164 (defun org-up-heading-safe ()
24165 "Move to the heading line of which the present line is a subheading.
24166 This version will not throw an error. It will return the level of the
24167 headline found, or nil if no higher level is found.
24169 Also, this function will be a lot faster than `outline-up-heading',
24170 because it relies on stars being the outline starters. This can really
24171 make a significant difference in outlines with very many siblings."
24172 (when (ignore-errors (org-back-to-heading t))
24173 (let ((level-up (1- (funcall outline-level))))
24174 (and (> level-up 0)
24175 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24176 (funcall outline-level)))))
24178 (defun org-first-sibling-p ()
24179 "Is this heading the first child of its parents?"
24180 (interactive)
24181 (let ((re org-outline-regexp-bol)
24182 level l)
24183 (unless (org-at-heading-p t)
24184 (user-error "Not at a heading"))
24185 (setq level (funcall outline-level))
24186 (save-excursion
24187 (if (not (re-search-backward re nil t))
24189 (setq l (funcall outline-level))
24190 (< l level)))))
24192 (defun org-goto-sibling (&optional previous)
24193 "Goto the next sibling, even if it is invisible.
24194 When PREVIOUS is set, go to the previous sibling instead. Returns t
24195 when a sibling was found. When none is found, return nil and don't
24196 move point."
24197 (let ((fun (if previous 're-search-backward 're-search-forward))
24198 (pos (point))
24199 (re org-outline-regexp-bol)
24200 level l)
24201 (when (ignore-errors (org-back-to-heading t))
24202 (setq level (funcall outline-level))
24203 (catch 'exit
24204 (or previous (forward-char 1))
24205 (while (funcall fun re nil t)
24206 (setq l (funcall outline-level))
24207 (when (< l level) (goto-char pos) (throw 'exit nil))
24208 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24209 (goto-char pos)
24210 nil))))
24212 (defun org-show-siblings ()
24213 "Show all siblings of the current headline."
24214 (save-excursion
24215 (while (org-goto-sibling) (org-flag-heading nil)))
24216 (save-excursion
24217 (while (org-goto-sibling 'previous)
24218 (org-flag-heading nil))))
24220 (defun org-goto-first-child ()
24221 "Goto the first child, even if it is invisible.
24222 Return t when a child was found. Otherwise don't move point and
24223 return nil."
24224 (let (level (pos (point)) (re org-outline-regexp-bol))
24225 (when (ignore-errors (org-back-to-heading t))
24226 (setq level (outline-level))
24227 (forward-char 1)
24228 (if (and (re-search-forward re nil t) (> (outline-level) level))
24229 (progn (goto-char (match-beginning 0)) t)
24230 (goto-char pos) nil))))
24232 (defun org-show-hidden-entry ()
24233 "Show an entry where even the heading is hidden."
24234 (save-excursion
24235 (org-show-entry)))
24237 (defun org-flag-heading (flag &optional entry)
24238 "Flag the current heading. FLAG non-nil means make invisible.
24239 When ENTRY is non-nil, show the entire entry."
24240 (save-excursion
24241 (org-back-to-heading t)
24242 ;; Check if we should show the entire entry
24243 (if entry
24244 (progn
24245 (org-show-entry)
24246 (save-excursion
24247 (and (outline-next-heading)
24248 (org-flag-heading nil))))
24249 (outline-flag-region (max (point-min) (1- (point)))
24250 (save-excursion (outline-end-of-heading) (point))
24251 flag))))
24253 (defun org-get-next-sibling ()
24254 "Move to next heading of the same level, and return point.
24255 If there is no such heading, return nil.
24256 This is like outline-next-sibling, but invisible headings are ok."
24257 (let ((level (funcall outline-level)))
24258 (outline-next-heading)
24259 (while (and (not (eobp)) (> (funcall outline-level) level))
24260 (outline-next-heading))
24261 (unless (or (eobp) (< (funcall outline-level) level))
24262 (point))))
24264 (defun org-get-last-sibling ()
24265 "Move to previous heading of the same level, and return point.
24266 If there is no such heading, return nil."
24267 (let ((opoint (point))
24268 (level (funcall outline-level)))
24269 (outline-previous-heading)
24270 (when (and (/= (point) opoint) (outline-on-heading-p t))
24271 (while (and (> (funcall outline-level) level)
24272 (not (bobp)))
24273 (outline-previous-heading))
24274 (unless (< (funcall outline-level) level)
24275 (point)))))
24277 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24278 "Goto to the end of a subtree."
24279 ;; This contains an exact copy of the original function, but it uses
24280 ;; `org-back-to-heading', to make it work also in invisible
24281 ;; trees. And is uses an invisible-ok argument.
24282 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24283 ;; Furthermore, when used inside Org, finding the end of a large subtree
24284 ;; with many children and grandchildren etc, this can be much faster
24285 ;; than the outline version.
24286 (org-back-to-heading invisible-ok)
24287 (let ((first t)
24288 (level (funcall outline-level)))
24289 (if (and (derived-mode-p 'org-mode) (< level 1000))
24290 ;; A true heading (not a plain list item), in Org-mode
24291 ;; This means we can easily find the end by looking
24292 ;; only for the right number of stars. Using a regexp to do
24293 ;; this is so much faster than using a Lisp loop.
24294 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24295 (forward-char 1)
24296 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24297 ;; something else, do it the slow way
24298 (while (and (not (eobp))
24299 (or first (> (funcall outline-level) level)))
24300 (setq first nil)
24301 (outline-next-heading)))
24302 (unless to-heading
24303 (when (memq (preceding-char) '(?\n ?\^M))
24304 ;; Go to end of line before heading
24305 (forward-char -1)
24306 (when (memq (preceding-char) '(?\n ?\^M))
24307 ;; leave blank line before heading
24308 (forward-char -1)))))
24309 (point))
24311 (defun org-end-of-meta-data (&optional full)
24312 "Skip planning line and properties drawer in current entry.
24313 When optional argument FULL is non-nil, also skip empty lines,
24314 clocking lines and regular drawers at the beginning of the
24315 entry."
24316 (org-back-to-heading t)
24317 (forward-line)
24318 (when (org-looking-at-p org-planning-line-re) (forward-line))
24319 (when (looking-at org-property-drawer-re)
24320 (goto-char (match-end 0))
24321 (forward-line))
24322 (when (and full (not (org-at-heading-p)))
24323 (catch 'exit
24324 (let ((end (save-excursion (outline-next-heading) (point)))
24325 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24326 (while (not (eobp))
24327 (cond ((org-looking-at-p org-drawer-regexp)
24328 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24329 (forward-line)
24330 (throw 'exit t)))
24331 ((org-looking-at-p re) (forward-line))
24332 (t (throw 'exit t))))))))
24334 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24335 "Move forward to the ARG'th subheading at same level as this one.
24336 Stop at the first and last subheadings of a superior heading.
24337 Normally this only looks at visible headings, but when INVISIBLE-OK is
24338 non-nil it will also look at invisible ones."
24339 (interactive "p")
24340 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24341 (if (and arg (< arg 0))
24342 (goto-char (point-min))
24343 (outline-next-heading))
24344 (org-at-heading-p)
24345 (let ((level (- (match-end 0) (match-beginning 0) 1))
24346 (f (if (and arg (< arg 0))
24347 're-search-backward
24348 're-search-forward))
24349 (count (if arg (abs arg) 1))
24350 (result (point)))
24351 (while (and (prog1 (> count 0)
24352 (forward-char (if (and arg (< arg 0)) -1 1)))
24353 (funcall f org-outline-regexp-bol nil 'move))
24354 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24355 (cond ((< l level) (setq count 0))
24356 ((and (= l level)
24357 (or invisible-ok
24358 (progn
24359 (goto-char (line-beginning-position))
24360 (not (outline-invisible-p)))))
24361 (setq count (1- count))
24362 (when (eq l level)
24363 (setq result (point)))))))
24364 (goto-char result))
24365 (beginning-of-line 1)))
24367 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24368 "Move backward to the ARG'th subheading at same level as this one.
24369 Stop at the first and last subheadings of a superior heading."
24370 (interactive "p")
24371 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24373 (defun org-next-visible-heading (arg)
24374 "Move to the next visible heading.
24376 This function wraps `outline-next-visible-heading' with
24377 `org-with-limited-levels' in order to skip over inline tasks and
24378 respect customization of `org-odd-levels-only'."
24379 (interactive "p")
24380 (org-with-limited-levels
24381 (outline-next-visible-heading arg)))
24383 (defun org-previous-visible-heading (arg)
24384 "Move to the next visible heading.
24386 This function wraps `outline-previous-visible-heading' with
24387 `org-with-limited-levels' in order to skip over inline tasks and
24388 respect customization of `org-odd-levels-only'."
24389 (interactive "p")
24390 (org-with-limited-levels
24391 (outline-previous-visible-heading arg)))
24393 (defun org-next-block (arg &optional backward block-regexp)
24394 "Jump to the next block.
24396 With a prefix argument ARG, jump forward ARG many blocks.
24398 When BACKWARD is non-nil, jump to the previous block.
24400 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24401 Match data is set according to this regexp when the function
24402 returns.
24404 Return point at beginning of the opening line of found block.
24405 Throw an error if no block is found."
24406 (interactive "p")
24407 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24408 (case-fold-search t)
24409 (search-fn (if backward #'re-search-backward #'re-search-forward))
24410 (count (or arg 1))
24411 (origin (point))
24412 last-element)
24413 (if backward (beginning-of-line) (end-of-line))
24414 (while (and (> count 0) (funcall search-fn re nil t))
24415 (let ((element (save-excursion
24416 (goto-char (match-beginning 0))
24417 (save-match-data (org-element-at-point)))))
24418 (when (and (memq (org-element-type element)
24419 '(center-block comment-block dynamic-block
24420 example-block export-block quote-block
24421 special-block src-block verse-block))
24422 (<= (match-beginning 0)
24423 (org-element-property :post-affiliated element)))
24424 (setq last-element element)
24425 (decf count))))
24426 (if (= count 0)
24427 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24428 (save-match-data (org-show-context)))
24429 (goto-char origin)
24430 (user-error "No %s code blocks" (if backward "previous" "further")))))
24432 (defun org-previous-block (arg &optional block-regexp)
24433 "Jump to the previous block.
24434 With a prefix argument ARG, jump backward ARG many source blocks.
24435 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24436 (interactive "p")
24437 (org-next-block arg t block-regexp))
24439 (defun org-forward-paragraph ()
24440 "Move forward to beginning of next paragraph or equivalent.
24442 The function moves point to the beginning of the next visible
24443 structural element, which can be a paragraph, a table, a list
24444 item, etc. It also provides some special moves for convenience:
24446 - On an affiliated keyword, jump to the beginning of the
24447 relative element.
24448 - On an item or a footnote definition, move to the second
24449 element inside, if any.
24450 - On a table or a property drawer, jump after it.
24451 - On a verse or source block, stop after blank lines."
24452 (interactive)
24453 (when (eobp) (user-error "Cannot move further down"))
24454 (let* ((deactivate-mark nil)
24455 (element (org-element-at-point))
24456 (type (org-element-type element))
24457 (post-affiliated (org-element-property :post-affiliated element))
24458 (contents-begin (org-element-property :contents-begin element))
24459 (contents-end (org-element-property :contents-end element))
24460 (end (let ((end (org-element-property :end element)) (parent element))
24461 (while (and (setq parent (org-element-property :parent parent))
24462 (= (org-element-property :contents-end parent) end))
24463 (setq end (org-element-property :end parent)))
24464 end)))
24465 (cond ((not element)
24466 (skip-chars-forward " \r\t\n")
24467 (or (eobp) (beginning-of-line)))
24468 ;; On affiliated keywords, move to element's beginning.
24469 ((< (point) post-affiliated)
24470 (goto-char post-affiliated))
24471 ;; At a table row, move to the end of the table. Similarly,
24472 ;; at a node property, move to the end of the property
24473 ;; drawer.
24474 ((memq type '(node-property table-row))
24475 (goto-char (org-element-property
24476 :end (org-element-property :parent element))))
24477 ((memq type '(property-drawer table)) (goto-char end))
24478 ;; Consider blank lines as separators in verse and source
24479 ;; blocks to ease editing.
24480 ((memq type '(src-block verse-block))
24481 (when (eq type 'src-block)
24482 (setq contents-end
24483 (save-excursion (goto-char end)
24484 (skip-chars-backward " \r\t\n")
24485 (line-beginning-position))))
24486 (beginning-of-line)
24487 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24488 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24489 (goto-char end)
24490 (skip-chars-forward " \r\t\n")
24491 (if (= (point) contents-end) (goto-char end)
24492 (beginning-of-line))))
24493 ;; With no contents, just skip element.
24494 ((not contents-begin) (goto-char end))
24495 ;; If contents are invisible, skip the element altogether.
24496 ((outline-invisible-p (line-end-position))
24497 (case type
24498 (headline
24499 (org-with-limited-levels (outline-next-visible-heading 1)))
24500 ;; At a plain list, make sure we move to the next item
24501 ;; instead of skipping the whole list.
24502 (plain-list (forward-char)
24503 (org-forward-paragraph))
24504 (otherwise (goto-char end))))
24505 ((>= (point) contents-end) (goto-char end))
24506 ((>= (point) contents-begin)
24507 ;; This can only happen on paragraphs and plain lists.
24508 (case type
24509 (paragraph (goto-char end))
24510 ;; At a plain list, try to move to second element in
24511 ;; first item, if possible.
24512 (plain-list (end-of-line)
24513 (org-forward-paragraph))))
24514 ;; When contents start on the middle of a line (e.g. in
24515 ;; items and footnote definitions), try to reach first
24516 ;; element starting after current line.
24517 ((> (line-end-position) contents-begin)
24518 (end-of-line)
24519 (org-forward-paragraph))
24520 (t (goto-char contents-begin)))))
24522 (defun org-backward-paragraph ()
24523 "Move backward to start of previous paragraph or equivalent.
24525 The function moves point to the beginning of the current
24526 structural element, which can be a paragraph, a table, a list
24527 item, etc., or to the beginning of the previous visible one if
24528 point is already there. It also provides some special moves for
24529 convenience:
24531 - On an affiliated keyword, jump to the first one.
24532 - On a table or a property drawer, move to its beginning.
24533 - On a verse or source block, stop before blank lines."
24534 (interactive)
24535 (when (bobp) (user-error "Cannot move further up"))
24536 (let* ((deactivate-mark nil)
24537 (element (org-element-at-point))
24538 (type (org-element-type element))
24539 (contents-begin (org-element-property :contents-begin element))
24540 (contents-end (org-element-property :contents-end element))
24541 (post-affiliated (org-element-property :post-affiliated element))
24542 (begin (org-element-property :begin element)))
24543 (cond
24544 ((not element) (goto-char (point-min)))
24545 ((= (point) begin)
24546 (backward-char)
24547 (org-backward-paragraph))
24548 ((<= (point) post-affiliated) (goto-char begin))
24549 ((memq type '(node-property table-row))
24550 (goto-char (org-element-property
24551 :post-affiliated (org-element-property :parent element))))
24552 ((memq type '(property-drawer table)) (goto-char begin))
24553 ((memq type '(src-block verse-block))
24554 (when (eq type 'src-block)
24555 (setq contents-begin
24556 (save-excursion (goto-char begin) (forward-line) (point))))
24557 (if (= (point) contents-begin) (goto-char post-affiliated)
24558 ;; Inside a verse block, see blank lines as paragraph
24559 ;; separators.
24560 (let ((origin (point)))
24561 (skip-chars-backward " \r\t\n" contents-begin)
24562 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24563 (skip-chars-forward " \r\t\n" origin)
24564 (if (= (point) origin) (goto-char contents-begin)
24565 (beginning-of-line))))))
24566 ((not contents-begin) (goto-char (or post-affiliated begin)))
24567 ((eq type 'paragraph)
24568 (goto-char contents-begin)
24569 ;; When at first paragraph in an item or a footnote definition,
24570 ;; move directly to beginning of line.
24571 (let ((parent-contents
24572 (org-element-property
24573 :contents-begin (org-element-property :parent element))))
24574 (when (and parent-contents (= parent-contents contents-begin))
24575 (beginning-of-line))))
24576 ;; At the end of a greater element, move to the beginning of the
24577 ;; last element within.
24578 ((>= (point) contents-end)
24579 (goto-char (1- contents-end))
24580 (org-backward-paragraph))
24581 (t (goto-char (or post-affiliated begin))))
24582 ;; Ensure we never leave point invisible.
24583 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24585 (defun org-forward-element ()
24586 "Move forward by one element.
24587 Move to the next element at the same level, when possible."
24588 (interactive)
24589 (cond ((eobp) (user-error "Cannot move further down"))
24590 ((org-with-limited-levels (org-at-heading-p))
24591 (let ((origin (point)))
24592 (goto-char (org-end-of-subtree nil t))
24593 (unless (org-with-limited-levels (org-at-heading-p))
24594 (goto-char origin)
24595 (user-error "Cannot move further down"))))
24597 (let* ((elem (org-element-at-point))
24598 (end (org-element-property :end elem))
24599 (parent (org-element-property :parent elem)))
24600 (cond ((and parent (= (org-element-property :contents-end parent) end))
24601 (goto-char (org-element-property :end parent)))
24602 ((integer-or-marker-p end) (goto-char end))
24603 (t (message "No element at point")))))))
24605 (defun org-backward-element ()
24606 "Move backward by one element.
24607 Move to the previous element at the same level, when possible."
24608 (interactive)
24609 (cond ((bobp) (user-error "Cannot move further up"))
24610 ((org-with-limited-levels (org-at-heading-p))
24611 ;; At a headline, move to the previous one, if any, or stay
24612 ;; here.
24613 (let ((origin (point)))
24614 (org-with-limited-levels (org-backward-heading-same-level 1))
24615 ;; When current headline has no sibling above, move to its
24616 ;; parent.
24617 (when (= (point) origin)
24618 (or (org-with-limited-levels (org-up-heading-safe))
24619 (progn (goto-char origin)
24620 (user-error "Cannot move further up"))))))
24622 (let* ((elem (org-element-at-point))
24623 (beg (org-element-property :begin elem)))
24624 (cond
24625 ;; Move to beginning of current element if point isn't
24626 ;; there already.
24627 ((null beg) (message "No element at point"))
24628 ((/= (point) beg) (goto-char beg))
24629 (t (goto-char beg)
24630 (skip-chars-backward " \r\t\n")
24631 (unless (bobp)
24632 (let ((prev (org-element-at-point)))
24633 (goto-char (org-element-property :begin prev))
24634 (while (and (setq prev (org-element-property :parent prev))
24635 (<= (org-element-property :end prev) beg))
24636 (goto-char (org-element-property :begin prev)))))))))))
24638 (defun org-up-element ()
24639 "Move to upper element."
24640 (interactive)
24641 (if (org-with-limited-levels (org-at-heading-p))
24642 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24643 (let* ((elem (org-element-at-point))
24644 (parent (org-element-property :parent elem)))
24645 (if parent (goto-char (org-element-property :begin parent))
24646 (if (org-with-limited-levels (org-before-first-heading-p))
24647 (user-error "No surrounding element")
24648 (org-with-limited-levels (org-back-to-heading)))))))
24650 (defvar org-element-greater-elements)
24651 (defun org-down-element ()
24652 "Move to inner element."
24653 (interactive)
24654 (let ((element (org-element-at-point)))
24655 (cond
24656 ((memq (org-element-type element) '(plain-list table))
24657 (goto-char (org-element-property :contents-begin element))
24658 (forward-char))
24659 ((memq (org-element-type element) org-element-greater-elements)
24660 ;; If contents are hidden, first disclose them.
24661 (when (outline-invisible-p (line-end-position)) (org-cycle))
24662 (goto-char (or (org-element-property :contents-begin element)
24663 (user-error "No content for this element"))))
24664 (t (user-error "No inner element")))))
24666 (defun org-drag-element-backward ()
24667 "Move backward element at point."
24668 (interactive)
24669 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24670 (let* ((elem (org-element-at-point))
24671 (prev-elem
24672 (save-excursion
24673 (goto-char (org-element-property :begin elem))
24674 (skip-chars-backward " \r\t\n")
24675 (unless (bobp)
24676 (let* ((beg (org-element-property :begin elem))
24677 (prev (org-element-at-point))
24678 (up prev))
24679 (while (and (setq up (org-element-property :parent up))
24680 (<= (org-element-property :end up) beg))
24681 (setq prev up))
24682 prev)))))
24683 ;; Error out if no previous element or previous element is
24684 ;; a parent of the current one.
24685 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24686 (user-error "Cannot drag element backward")
24687 (let ((pos (point)))
24688 (org-element-swap-A-B prev-elem elem)
24689 (goto-char (+ (org-element-property :begin prev-elem)
24690 (- pos (org-element-property :begin elem)))))))))
24692 (defun org-drag-element-forward ()
24693 "Move forward element at point."
24694 (interactive)
24695 (let* ((pos (point))
24696 (elem (org-element-at-point)))
24697 (when (= (point-max) (org-element-property :end elem))
24698 (user-error "Cannot drag element forward"))
24699 (goto-char (org-element-property :end elem))
24700 (let ((next-elem (org-element-at-point)))
24701 (when (or (org-element-nested-p elem next-elem)
24702 (and (eq (org-element-type next-elem) 'headline)
24703 (not (eq (org-element-type elem) 'headline))))
24704 (goto-char pos)
24705 (user-error "Cannot drag element forward"))
24706 ;; Compute new position of point: it's shifted by NEXT-ELEM
24707 ;; body's length (without final blanks) and by the length of
24708 ;; blanks between ELEM and NEXT-ELEM.
24709 (let ((size-next (- (save-excursion
24710 (goto-char (org-element-property :end next-elem))
24711 (skip-chars-backward " \r\t\n")
24712 (forward-line)
24713 ;; Small correction if buffer doesn't end
24714 ;; with a newline character.
24715 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24716 (org-element-property :begin next-elem)))
24717 (size-blank (- (org-element-property :end elem)
24718 (save-excursion
24719 (goto-char (org-element-property :end elem))
24720 (skip-chars-backward " \r\t\n")
24721 (forward-line)
24722 (point)))))
24723 (org-element-swap-A-B elem next-elem)
24724 (goto-char (+ pos size-next size-blank))))))
24726 (defun org-drag-line-forward (arg)
24727 "Drag the line at point ARG lines forward."
24728 (interactive "p")
24729 (dotimes (_ (abs arg))
24730 (let ((c (current-column)))
24731 (if (< 0 arg)
24732 (progn
24733 (beginning-of-line 2)
24734 (transpose-lines 1)
24735 (beginning-of-line 0))
24736 (transpose-lines 1)
24737 (beginning-of-line -1))
24738 (org-move-to-column c))))
24740 (defun org-drag-line-backward (arg)
24741 "Drag the line at point ARG lines backward."
24742 (interactive "p")
24743 (org-drag-line-forward (- arg)))
24745 (defun org-mark-element ()
24746 "Put point at beginning of this element, mark at end.
24748 Interactively, if this command is repeated or (in Transient Mark
24749 mode) if the mark is active, it marks the next element after the
24750 ones already marked."
24751 (interactive)
24752 (let (deactivate-mark)
24753 (if (and (org-called-interactively-p 'any)
24754 (or (and (eq last-command this-command) (mark t))
24755 (and transient-mark-mode mark-active)))
24756 (set-mark
24757 (save-excursion
24758 (goto-char (mark))
24759 (goto-char (org-element-property :end (org-element-at-point)))))
24760 (let ((element (org-element-at-point)))
24761 (end-of-line)
24762 (push-mark (org-element-property :end element) t t)
24763 (goto-char (org-element-property :begin element))))))
24765 (defun org-narrow-to-element ()
24766 "Narrow buffer to current element."
24767 (interactive)
24768 (let ((elem (org-element-at-point)))
24769 (cond
24770 ((eq (car elem) 'headline)
24771 (narrow-to-region
24772 (org-element-property :begin elem)
24773 (org-element-property :end elem)))
24774 ((memq (car elem) org-element-greater-elements)
24775 (narrow-to-region
24776 (org-element-property :contents-begin elem)
24777 (org-element-property :contents-end elem)))
24779 (narrow-to-region
24780 (org-element-property :begin elem)
24781 (org-element-property :end elem))))))
24783 (defun org-transpose-element ()
24784 "Transpose current and previous elements, keeping blank lines between.
24785 Point is moved after both elements."
24786 (interactive)
24787 (org-skip-whitespace)
24788 (let ((end (org-element-property :end (org-element-at-point))))
24789 (org-drag-element-backward)
24790 (goto-char end)))
24792 (defun org-unindent-buffer ()
24793 "Un-indent the visible part of the buffer.
24794 Relative indentation (between items, inside blocks, etc.) isn't
24795 modified."
24796 (interactive)
24797 (unless (eq major-mode 'org-mode)
24798 (user-error "Cannot un-indent a buffer not in Org mode"))
24799 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24800 (unindent-tree
24801 (lambda (contents)
24802 (dolist (element (reverse contents))
24803 (if (memq (org-element-type element) '(headline section))
24804 (funcall unindent-tree (org-element-contents element))
24805 (save-excursion
24806 (save-restriction
24807 (narrow-to-region
24808 (org-element-property :begin element)
24809 (org-element-property :end element))
24810 (org-do-remove-indentation))))))))
24811 (funcall unindent-tree (org-element-contents parse-tree))))
24813 (defun org-show-children (&optional level)
24814 "Show all direct subheadings of this heading.
24815 Prefix arg LEVEL is how many levels below the current level
24816 should be shown. Default is enough to cause the following
24817 heading to appear."
24818 (interactive "p")
24819 ;; If `orgstruct-mode' is active, use the slower version.
24820 (if orgstruct-mode (call-interactively #'outline-show-children)
24821 (save-excursion
24822 (org-back-to-heading t)
24823 (let* ((current-level (funcall outline-level))
24824 (max-level (org-get-valid-level
24825 current-level
24826 (if level (prefix-numeric-value level) 1)))
24827 (end (save-excursion (org-end-of-subtree t t)))
24828 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24829 (past-first-child nil)
24830 ;; Make sure to skip inlinetasks.
24831 (re (format regexp-fmt
24832 current-level
24833 (cond
24834 ((not (featurep 'org-inlinetask)) "")
24835 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24837 (t (1- org-inlinetask-min-level))))))
24838 ;; Display parent heading.
24839 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24840 (forward-line)
24841 ;; Display children. First child may be deeper than expected
24842 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24843 ;; MAX-LEVEL accordingly.
24844 (while (re-search-forward re end t)
24845 (unless past-first-child
24846 (setq re (format regexp-fmt
24847 current-level
24848 (max (funcall outline-level) max-level)))
24849 (setq past-first-child t))
24850 (outline-flag-region
24851 (line-end-position 0) (line-end-position) nil))))))
24853 (defun org-show-subtree ()
24854 "Show everything after this heading at deeper levels."
24855 (interactive)
24856 (outline-flag-region
24857 (point)
24858 (save-excursion
24859 (org-end-of-subtree t t))
24860 nil))
24862 (defun org-show-entry ()
24863 "Show the body directly following this heading.
24864 Show the heading too, if it is currently invisible."
24865 (interactive)
24866 (save-excursion
24867 (ignore-errors
24868 (org-back-to-heading t)
24869 (outline-flag-region
24870 (max (point-min) (1- (point)))
24871 (save-excursion
24872 (if (re-search-forward
24873 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24874 (match-beginning 1)
24875 (point-max)))
24876 nil)
24877 (org-cycle-hide-drawers 'children))))
24879 (defun org-make-options-regexp (kwds &optional extra)
24880 "Make a regular expression for keyword lines.
24881 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24882 when non-nil, is a regexp matching keywords names."
24883 (concat "^[ \t]*#\\+\\("
24884 (regexp-opt kwds)
24885 (and extra (concat (and kwds "\\|") extra))
24886 "\\):[ \t]*\\(.*\\)"))
24888 ;; Make isearch reveal the necessary context
24889 (defun org-isearch-end ()
24890 "Reveal context after isearch exits."
24891 (when isearch-success ; only if search was successful
24892 (if (featurep 'xemacs)
24893 ;; Under XEmacs, the hook is run in the correct place,
24894 ;; we directly show the context.
24895 (org-show-context 'isearch)
24896 ;; In Emacs the hook runs *before* restoring the overlays.
24897 ;; So we have to use a one-time post-command-hook to do this.
24898 ;; (Emacs 22 has a special variable, see function `org-mode')
24899 (unless (and (boundp 'isearch-mode-end-hook-quit)
24900 isearch-mode-end-hook-quit)
24901 ;; Only when the isearch was not quitted.
24902 (org-add-hook 'post-command-hook 'org-isearch-post-command
24903 'append 'local)))))
24905 (defun org-isearch-post-command ()
24906 "Remove self from hook, and show context."
24907 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24908 (org-show-context 'isearch))
24911 ;;;; Integration with and fixes for other packages
24913 ;;; Imenu support
24915 (defvar-local org-imenu-markers nil
24916 "All markers currently used by Imenu.")
24918 (defun org-imenu-new-marker (&optional pos)
24919 "Return a new marker for use by Imenu, and remember the marker."
24920 (let ((m (make-marker)))
24921 (move-marker m (or pos (point)))
24922 (push m org-imenu-markers)
24925 (defun org-imenu-get-tree ()
24926 "Produce the index for Imenu."
24927 (dolist (x org-imenu-markers) (move-marker x nil))
24928 (setq org-imenu-markers nil)
24929 (let* ((n org-imenu-depth)
24930 (re (concat "^" (org-get-limited-outline-regexp)))
24931 (subs (make-vector (1+ n) nil))
24932 (last-level 0)
24933 m level head0 head)
24934 (save-excursion
24935 (save-restriction
24936 (widen)
24937 (goto-char (point-max))
24938 (while (re-search-backward re nil t)
24939 (setq level (org-reduced-level (funcall outline-level)))
24940 (when (and (<= level n)
24941 (looking-at org-complex-heading-regexp)
24942 (setq head0 (org-match-string-no-properties 4)))
24943 (setq head (org-link-display-format head0)
24944 m (org-imenu-new-marker))
24945 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24946 (if (>= level last-level)
24947 (push (cons head m) (aref subs level))
24948 (push (cons head (aref subs (1+ level))) (aref subs level))
24949 (loop for i from (1+ level) to n do (aset subs i nil)))
24950 (setq last-level level)))))
24951 (aref subs 1)))
24953 (eval-after-load "imenu"
24954 '(progn
24955 (add-hook 'imenu-after-jump-hook
24956 (lambda ()
24957 (when (derived-mode-p 'org-mode)
24958 (org-show-context 'org-goto))))))
24960 (defun org-link-display-format (link)
24961 "Replace a link with its the description.
24962 If there is no description, use the link target."
24963 (save-match-data
24964 (if (string-match org-bracket-link-analytic-regexp link)
24965 (replace-match (if (match-end 5)
24966 (match-string 5 link)
24967 (concat (match-string 1 link)
24968 (match-string 3 link)))
24969 nil t link)
24970 link)))
24972 (defun org-toggle-link-display ()
24973 "Toggle the literal or descriptive display of links."
24974 (interactive)
24975 (if org-descriptive-links
24976 (progn (org-remove-from-invisibility-spec '(org-link))
24977 (org-restart-font-lock)
24978 (setq org-descriptive-links nil))
24979 (progn (add-to-invisibility-spec '(org-link))
24980 (org-restart-font-lock)
24981 (setq org-descriptive-links t))))
24983 ;; Speedbar support
24985 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24986 "Overlay marking the agenda restriction line in speedbar.")
24987 (overlay-put org-speedbar-restriction-lock-overlay
24988 'face 'org-agenda-restriction-lock)
24989 (overlay-put org-speedbar-restriction-lock-overlay
24990 'help-echo "Agendas are currently limited to this item.")
24991 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24993 (defun org-speedbar-set-agenda-restriction ()
24994 "Restrict future agenda commands to the location at point in speedbar.
24995 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24996 (interactive)
24997 (require 'org-agenda)
24998 (let (p m tp np dir txt)
24999 (cond
25000 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25001 'org-imenu t))
25002 (setq m (get-text-property p 'org-imenu-marker))
25003 (with-current-buffer (marker-buffer m)
25004 (goto-char m)
25005 (org-agenda-set-restriction-lock 'subtree)))
25006 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25007 'speedbar-function 'speedbar-find-file))
25008 (setq tp (previous-single-property-change
25009 (1+ p) 'speedbar-function)
25010 np (next-single-property-change
25011 tp 'speedbar-function)
25012 dir (speedbar-line-directory)
25013 txt (buffer-substring-no-properties (or tp (point-min))
25014 (or np (point-max))))
25015 (with-current-buffer (find-file-noselect
25016 (let ((default-directory dir))
25017 (expand-file-name txt)))
25018 (unless (derived-mode-p 'org-mode)
25019 (user-error "Cannot restrict to non-Org-mode file"))
25020 (org-agenda-set-restriction-lock 'file)))
25021 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25022 (move-overlay org-speedbar-restriction-lock-overlay
25023 (point-at-bol) (point-at-eol))
25024 (setq current-prefix-arg nil)
25025 (org-agenda-maybe-redo)))
25027 (defvar speedbar-file-key-map)
25028 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25029 (eval-after-load "speedbar"
25030 '(progn
25031 (speedbar-add-supported-extension ".org")
25032 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25033 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25034 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25035 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25036 (add-hook 'speedbar-visiting-tag-hook
25037 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25039 ;;; Fixes and Hacks for problems with other packages
25041 (defun org--flyspell-object-check-p (element)
25042 "Non-nil when Flyspell can check object at point.
25043 ELEMENT is the element at point."
25044 (let ((object (save-excursion
25045 (when (org-looking-at-p "\\>") (backward-char))
25046 (org-element-context element))))
25047 (case (org-element-type object)
25048 ;; Prevent checks in links due to keybinding conflict with
25049 ;; Flyspell.
25050 ((code entity export-snippet inline-babel-call
25051 inline-src-block line-break latex-fragment link macro
25052 statistics-cookie target timestamp verbatim)
25053 nil)
25054 (footnote-reference
25055 ;; Only in inline footnotes, within the definition.
25056 (and (eq (org-element-property :type object) 'inline)
25057 (< (save-excursion
25058 (goto-char (org-element-property :begin object))
25059 (search-forward ":" nil t 2))
25060 (point))))
25061 (otherwise t))))
25063 (defun org-mode-flyspell-verify ()
25064 "Function used for `flyspell-generic-check-word-predicate'."
25065 (if (org-at-heading-p)
25066 ;; At a headline or an inlinetask, check title only. This is
25067 ;; faster than relying on `org-element-at-point'.
25068 (and (save-excursion (beginning-of-line)
25069 (and (let ((case-fold-search t))
25070 (not (looking-at "\\*+ END[ \t]*$")))
25071 (looking-at org-complex-heading-regexp)))
25072 (match-beginning 4)
25073 (>= (point) (match-beginning 4))
25074 (or (not (match-beginning 5))
25075 (< (point) (match-beginning 5))))
25076 (let* ((element (org-element-at-point))
25077 (post-affiliated (org-element-property :post-affiliated element)))
25078 (cond
25079 ;; Ignore checks in all affiliated keywords but captions.
25080 ((< (point) post-affiliated)
25081 (and (save-excursion
25082 (beginning-of-line)
25083 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25084 (> (point) (match-end 0))
25085 (org--flyspell-object-check-p element)))
25086 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25087 ((let ((log (org-log-into-drawer)))
25088 (and log
25089 (let ((drawer (org-element-lineage element '(drawer))))
25090 (and drawer
25091 (eq (compare-strings
25092 log nil nil
25093 (org-element-property :drawer-name drawer) nil nil t)
25094 t)))))
25095 nil)
25097 (case (org-element-type element)
25098 ((comment quote-section) t)
25099 (comment-block
25100 ;; Allow checks between block markers, not on them.
25101 (and (> (line-beginning-position) post-affiliated)
25102 (save-excursion
25103 (end-of-line)
25104 (skip-chars-forward " \r\t\n")
25105 (< (point) (org-element-property :end element)))))
25106 ;; Arbitrary list of keywords where checks are meaningful.
25107 ;; Make sure point is on the value part of the element.
25108 (keyword
25109 (and (member (org-element-property :key element)
25110 '("DESCRIPTION" "TITLE"))
25111 (save-excursion
25112 (search-backward ":" (line-beginning-position) t))))
25113 ;; Check is globally allowed in paragraphs verse blocks and
25114 ;; table rows (after affiliated keywords) but some objects
25115 ;; must not be affected.
25116 ((paragraph table-row verse-block)
25117 (let ((cbeg (org-element-property :contents-begin element))
25118 (cend (org-element-property :contents-end element)))
25119 (and cbeg (>= (point) cbeg) (< (point) cend)
25120 (org--flyspell-object-check-p element))))))))))
25121 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25123 (defun org-remove-flyspell-overlays-in (beg end)
25124 "Remove flyspell overlays in region."
25125 (and (org-bound-and-true-p flyspell-mode)
25126 (fboundp 'flyspell-delete-region-overlays)
25127 (flyspell-delete-region-overlays beg end)))
25129 (defvar flyspell-delayed-commands)
25130 (eval-after-load "flyspell"
25131 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25133 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25134 (eval-after-load "bookmark"
25135 '(if (boundp 'bookmark-after-jump-hook)
25136 ;; We can use the hook
25137 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25138 ;; Hook not available, use advice
25139 (defadvice bookmark-jump (after org-make-visible activate)
25140 "Make the position visible."
25141 (org-bookmark-jump-unhide))))
25143 ;; Make sure saveplace shows the location if it was hidden
25144 (eval-after-load "saveplace"
25145 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25146 "Make the position visible."
25147 (org-bookmark-jump-unhide)))
25149 ;; Make sure ecb shows the location if it was hidden
25150 (eval-after-load "ecb"
25151 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25152 "Make hierarchy visible when jumping into location from ECB tree buffer."
25153 (when (derived-mode-p 'org-mode)
25154 (org-show-context))))
25156 (defun org-bookmark-jump-unhide ()
25157 "Unhide the current position, to show the bookmark location."
25158 (and (derived-mode-p 'org-mode)
25159 (or (outline-invisible-p)
25160 (save-excursion (goto-char (max (point-min) (1- (point))))
25161 (outline-invisible-p)))
25162 (org-show-context 'bookmark-jump)))
25164 (defun org-mark-jump-unhide ()
25165 "Make the point visible with `org-show-context' after jumping to the mark."
25166 (when (and (derived-mode-p 'org-mode)
25167 (outline-invisible-p))
25168 (org-show-context 'mark-goto)))
25170 (eval-after-load "simple"
25171 '(defadvice pop-to-mark-command (after org-make-visible activate)
25172 "Make the point visible with `org-show-context'."
25173 (org-mark-jump-unhide)))
25175 (eval-after-load "simple"
25176 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25177 "Make the point visible with `org-show-context'."
25178 (org-mark-jump-unhide)))
25180 (eval-after-load "simple"
25181 '(defadvice pop-global-mark (after org-make-visible activate)
25182 "Make the point visible with `org-show-context'."
25183 (org-mark-jump-unhide)))
25185 ;; Make session.el ignore our circular variable
25186 (defvar session-globals-exclude)
25187 (eval-after-load "session"
25188 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25190 ;;;; Finish up
25192 (provide 'org)
25194 (run-hooks 'org-load-hook)
25196 ;;; org.el ends here