Fix `org-auto-repeat-maybe'
[org-mode/org-tableheadings.git] / lisp / org.el
blob42b221817a566317cabe82da182506ae3418302f
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 time-stamp.
13098 If yes, set TODO state back to what it was and change the base date
13099 of repeating deadline/scheduled time stamps to new date.
13101 This function is run automatically after each state change to a DONE state."
13102 (let* ((repeat (org-get-repeat))
13103 (aa (assoc org-last-state org-todo-kwd-alist))
13104 (interpret (nth 1 aa))
13105 (head (nth 2 aa))
13106 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13107 (msg "Entry repeats: ")
13108 (org-log-done nil)
13109 (org-todo-log-states nil))
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 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
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 ;; 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 (let ((regexp (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13135 org-deadline-time-regexp "\\)\\|\\("
13136 org-ts-regexp "\\)"))
13137 (end (save-excursion (outline-next-heading) (point))))
13138 (while (re-search-forward regexp end t)
13139 (let ((type (cond ((match-end 1) org-scheduled-string)
13140 ((match-end 3) org-deadline-string)
13141 (t "Plain:")))
13142 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13143 (cond
13144 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13145 ;; Time-stamps without a repeater are usually skipped.
13146 ;; However, a SCHEDULED or DEADLINE time-stamp without
13147 ;; one is removed, as it is considered outdated.
13148 (unless (equal type "Plain:")
13149 (org-remove-timestamp-with-keyword type)))
13151 (let ((n (string-to-number (match-string 2 ts)))
13152 (what (match-string 3 ts)))
13153 (when (equal what "w") (setq n (* n 7) what "d"))
13154 (when (and (equal what "h")
13155 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13156 ts)))
13157 (user-error
13158 "Cannot repeat in Repeat in %d hour(s) because no hour has \
13159 been set"
13161 ;; Preparation, see if we need to modify the start
13162 ;; date for the change.
13163 (when (match-end 1)
13164 (let ((time (save-match-data (org-time-string-to-time ts))))
13165 (cond
13166 ((equal (match-string 1 ts) ".")
13167 ;; Shift starting date to today
13168 (org-timestamp-change
13169 (- (org-today) (time-to-days time))
13170 'day))
13171 ((equal (match-string 1 ts) "+")
13172 (let ((nshiftmax 10)
13173 (nshift 0))
13174 (while (or (= nshift 0)
13175 (<= (time-to-days time)
13176 (time-to-days (current-time))))
13177 (when (= (incf nshift) nshiftmax)
13178 (or (y-or-n-p
13179 (format "%d repeater intervals were not \
13180 enough to shift date past today. Continue? "
13181 nshift))
13182 (user-error "Abort")))
13183 (org-timestamp-change n (cdr (assoc what whata)))
13184 (org-at-timestamp-p t)
13185 (setq ts (match-string 1))
13186 (setq time
13187 (save-match-data
13188 (org-time-string-to-time ts)))))
13189 (org-timestamp-change (- n) (cdr (assoc what whata)))
13190 ;; Rematch, so that we have everything in place
13191 ;; for the real shift.
13192 (org-at-timestamp-p t)
13193 (setq ts (match-string 1))
13194 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13195 ts)))))
13196 (save-excursion
13197 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13198 (setq msg
13199 (concat
13200 msg type " " org-last-changed-timestamp " "))))))))
13201 (setq org-log-post-message msg)
13202 (message "%s" msg))))
13204 (defun org-show-todo-tree (arg)
13205 "Make a compact tree which shows all headlines marked with TODO.
13206 The tree will show the lines where the regexp matches, and all higher
13207 headlines above the match.
13208 With a \\[universal-argument] prefix, prompt for a regexp to match.
13209 With a numeric prefix N, construct a sparse tree for the Nth element
13210 of `org-todo-keywords-1'."
13211 (interactive "P")
13212 (let ((case-fold-search nil)
13213 (kwd-re
13214 (cond ((null arg) org-not-done-regexp)
13215 ((equal arg '(4))
13216 (let ((kwd
13217 (completing-read "Keyword (or KWD1|KWD2|...): "
13218 (mapcar #'list org-todo-keywords-1))))
13219 (concat "\\("
13220 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13221 "\\)\\>")))
13222 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13223 (regexp-quote (nth (1- (prefix-numeric-value arg))
13224 org-todo-keywords-1)))
13225 (t (user-error "Invalid prefix argument: %s" arg)))))
13226 (message "%d TODO entries found"
13227 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13229 (defun org-deadline (arg &optional time)
13230 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13231 With one universal prefix argument, remove any deadline from the item.
13232 With two universal prefix arguments, prompt for a warning delay.
13233 With argument TIME, set the deadline at the corresponding date. TIME
13234 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13235 (interactive "P")
13236 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13237 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13238 'region-start-level 'region))
13239 org-loop-over-headlines-in-active-region)
13240 (org-map-entries
13241 `(org-deadline ',arg ,time)
13242 org-loop-over-headlines-in-active-region
13243 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13244 (let* ((old-date (org-entry-get nil "DEADLINE"))
13245 (old-date-time (when old-date (org-time-string-to-time old-date)))
13246 (repeater (and old-date
13247 (string-match
13248 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13249 old-date)
13250 (match-string 1 old-date))))
13251 (cond
13252 ((equal arg '(4))
13253 (when (and old-date org-log-redeadline)
13254 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13255 (org-remove-timestamp-with-keyword org-deadline-string)
13256 (message "Item no longer has a deadline."))
13257 ((equal arg '(16))
13258 (save-excursion
13259 (org-back-to-heading t)
13260 (if (re-search-forward
13261 org-deadline-time-regexp
13262 (save-excursion (outline-next-heading) (point)) t)
13263 (let* ((rpl0 (match-string 1))
13264 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13265 (replace-match
13266 (concat org-deadline-string
13267 " <" rpl
13268 (format " -%dd"
13269 (abs
13270 (- (time-to-days
13271 (save-match-data
13272 (org-read-date nil t nil "Warn starting from" old-date-time)))
13273 (time-to-days old-date-time))))
13274 ">") t t))
13275 (user-error "No deadline information to update"))))
13277 (org-add-planning-info 'deadline time 'closed)
13278 (when (and old-date
13279 org-log-redeadline
13280 (not (equal old-date org-last-inserted-timestamp)))
13281 (org-add-log-setup
13282 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13283 (when repeater
13284 (save-excursion
13285 (org-back-to-heading t)
13286 (when (re-search-forward (concat org-deadline-string " "
13287 org-last-inserted-timestamp)
13288 (save-excursion
13289 (outline-next-heading) (point)) t)
13290 (goto-char (1- (match-end 0)))
13291 (insert " " repeater)
13292 (setq org-last-inserted-timestamp
13293 (concat (substring org-last-inserted-timestamp 0 -1)
13294 " " repeater
13295 (substring org-last-inserted-timestamp -1))))))
13296 (message "Deadline on %s" org-last-inserted-timestamp))))))
13298 (defun org-schedule (arg &optional time)
13299 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13300 With one universal prefix argument, remove any scheduling date from the item.
13301 With two universal prefix arguments, prompt for a delay cookie.
13302 With argument TIME, scheduled at the corresponding date. TIME can
13303 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13304 (interactive "P")
13305 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13306 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13307 'region-start-level 'region))
13308 org-loop-over-headlines-in-active-region)
13309 (org-map-entries
13310 `(org-schedule ',arg ,time)
13311 org-loop-over-headlines-in-active-region
13312 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13313 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13314 (old-date-time (when old-date (org-time-string-to-time old-date)))
13315 (repeater (and old-date
13316 (string-match
13317 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13318 old-date)
13319 (match-string 1 old-date))))
13320 (cond
13321 ((equal arg '(4))
13322 (progn
13323 (when (and old-date org-log-reschedule)
13324 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13325 (org-remove-timestamp-with-keyword org-scheduled-string)
13326 (message "Item is no longer scheduled.")))
13327 ((equal arg '(16))
13328 (save-excursion
13329 (org-back-to-heading t)
13330 (if (re-search-forward
13331 org-scheduled-time-regexp
13332 (save-excursion (outline-next-heading) (point)) t)
13333 (let* ((rpl0 (match-string 1))
13334 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13335 (replace-match
13336 (concat org-scheduled-string
13337 " <" rpl
13338 (format " -%dd"
13339 (abs
13340 (- (time-to-days
13341 (save-match-data
13342 (org-read-date nil t nil "Delay until" old-date-time)))
13343 (time-to-days old-date-time))))
13344 ">") t t))
13345 (user-error "No scheduled information to update"))))
13347 (org-add-planning-info 'scheduled time 'closed)
13348 (when (and old-date
13349 org-log-reschedule
13350 (not (equal old-date org-last-inserted-timestamp)))
13351 (org-add-log-setup
13352 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13353 (when repeater
13354 (save-excursion
13355 (org-back-to-heading t)
13356 (when (re-search-forward (concat org-scheduled-string " "
13357 org-last-inserted-timestamp)
13358 (save-excursion
13359 (outline-next-heading) (point)) t)
13360 (goto-char (1- (match-end 0)))
13361 (insert " " repeater)
13362 (setq org-last-inserted-timestamp
13363 (concat (substring org-last-inserted-timestamp 0 -1)
13364 " " repeater
13365 (substring org-last-inserted-timestamp -1))))))
13366 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13368 (defun org-get-scheduled-time (pom &optional inherit)
13369 "Get the scheduled time as a time tuple, of a format suitable
13370 for calling org-schedule with, or if there is no scheduling,
13371 returns nil."
13372 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13373 (when time
13374 (apply 'encode-time (org-parse-time-string time)))))
13376 (defun org-get-deadline-time (pom &optional inherit)
13377 "Get the deadline as a time tuple, of a format suitable for
13378 calling org-deadline with, or if there is no scheduling, returns
13379 nil."
13380 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13381 (when time
13382 (apply 'encode-time (org-parse-time-string time)))))
13384 (defun org-remove-timestamp-with-keyword (keyword)
13385 "Remove all time stamps with KEYWORD in the current entry."
13386 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13387 beg)
13388 (save-excursion
13389 (org-back-to-heading t)
13390 (setq beg (point))
13391 (outline-next-heading)
13392 (while (re-search-backward re beg t)
13393 (replace-match "")
13394 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13395 (equal (char-before) ?\ ))
13396 (backward-delete-char 1)
13397 (when (string-match "^[ \t]*$" (buffer-substring
13398 (point-at-bol) (point-at-eol)))
13399 (delete-region (point-at-bol)
13400 (min (point-max) (1+ (point-at-eol))))))))))
13402 (defvar org-time-was-given) ; dynamically scoped parameter
13403 (defvar org-end-time-was-given) ; dynamically scoped parameter
13405 (defun org-at-planning-p ()
13406 "Non-nil when point is on a planning info line."
13407 ;; This is as accurate and faster than `org-element-at-point' since
13408 ;; planning info location is fixed in the section.
13409 (org-with-wide-buffer
13410 (beginning-of-line)
13411 (and (org-looking-at-p org-planning-line-re)
13412 (eq (point)
13413 (ignore-errors
13414 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13415 (org-back-to-heading t)
13416 (org-with-limited-levels (org-back-to-heading t)))
13417 (line-beginning-position 2))))))
13419 (defun org-add-planning-info (what &optional time &rest remove)
13420 "Insert new timestamp with keyword in the planning line.
13421 WHAT indicates what kind of time stamp to add. It is a symbol
13422 among `closed', `deadline', `scheduled' and nil. TIME indicates
13423 the time to use. If none is given, the user is prompted for
13424 a date. REMOVE indicates what kind of entries to remove. An old
13425 WHAT entry will also be removed."
13426 (let (org-time-was-given org-end-time-was-given default-time default-input)
13427 (catch 'exit
13428 (when (and (memq what '(scheduled deadline))
13429 (or (not time)
13430 (and (stringp time)
13431 (string-match "^[-+]+[0-9]" time))))
13432 ;; Try to get a default date/time from existing timestamp
13433 (save-excursion
13434 (org-back-to-heading t)
13435 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13436 (when (re-search-forward (if (eq what 'scheduled)
13437 org-scheduled-time-regexp
13438 org-deadline-time-regexp)
13439 end t)
13440 (setq ts (match-string 1)
13441 default-time (apply 'encode-time (org-parse-time-string ts))
13442 default-input (and ts (org-get-compact-tod ts)))))))
13443 (when what
13444 (setq time
13445 (if (stringp time)
13446 ;; This is a string (relative or absolute), set
13447 ;; proper date.
13448 (apply #'encode-time
13449 (org-read-date-analyze
13450 time default-time (decode-time default-time)))
13451 ;; If necessary, get the time from the user
13452 (or time (org-read-date nil 'to-time nil nil
13453 default-time default-input)))))
13455 (org-with-wide-buffer
13456 (org-back-to-heading t)
13457 (forward-line)
13458 (unless (bolp) (insert "\n"))
13459 (cond ((org-looking-at-p org-planning-line-re)
13460 ;; Move to current indentation.
13461 (skip-chars-forward " \t")
13462 ;; Check if we have to remove something.
13463 (dolist (type (if what (cons what remove) remove))
13464 (save-excursion
13465 (when (re-search-forward
13466 (case type
13467 (closed org-closed-time-regexp)
13468 (deadline org-deadline-time-regexp)
13469 (scheduled org-scheduled-time-regexp)
13470 (otherwise
13471 (error "Invalid planning type: %s" type)))
13472 (line-end-position) t)
13473 ;; Delete until next keyword or end of line.
13474 (delete-region
13475 (match-beginning 0)
13476 (if (re-search-forward org-keyword-time-not-clock-regexp
13477 (line-end-position)
13479 (match-beginning 0)
13480 (line-end-position))))))
13481 ;; If there is nothing more to add and no more keyword
13482 ;; is left, remove the line completely.
13483 (if (and (org-looking-at-p "[ \t]*$") (not what))
13484 (delete-region (line-beginning-position)
13485 (line-beginning-position 2))
13486 ;; If we removed last keyword, do not leave trailing
13487 ;; white space at the end of line.
13488 (let ((p (point)))
13489 (save-excursion
13490 (end-of-line)
13491 (unless (= (skip-chars-backward " \t" p) 0)
13492 (delete-region (point) (line-end-position)))))))
13493 ((not what) (throw 'exit nil)) ; Nothing to do.
13494 (t (insert-before-markers "\n")
13495 (backward-char 1)
13496 (when org-adapt-indentation
13497 (org-indent-to-column (1+ (org-outline-level))))))
13498 (when what
13499 ;; Insert planning keyword.
13500 (insert (case what
13501 (closed org-closed-string)
13502 (deadline org-deadline-string)
13503 (scheduled org-scheduled-string)
13504 (otherwise (error "Invalid planning type: %s" what)))
13505 " ")
13506 ;; Insert associated timestamp.
13507 (let ((ts (org-insert-time-stamp
13508 time
13509 (or org-time-was-given
13510 (and (eq what 'closed) org-log-done-with-time))
13511 (eq what 'closed)
13512 nil nil (list org-end-time-was-given))))
13513 (unless (eolp) (insert " "))
13514 ts))))))
13516 (defvar org-log-note-marker (make-marker)
13517 "Marker pointing at the entry where the note is to be inserted.")
13518 (defvar org-log-note-purpose nil)
13519 (defvar org-log-note-state nil)
13520 (defvar org-log-note-previous-state nil)
13521 (defvar org-log-note-extra nil)
13522 (defvar org-log-note-window-configuration nil)
13523 (defvar org-log-note-return-to (make-marker))
13524 (defvar org-log-note-effective-time nil
13525 "Remembered current time so that dynamically scoped
13526 `org-extend-today-until' affects timestamps in state change log")
13528 (defvar org-log-post-message nil
13529 "Message to be displayed after a log note has been stored.
13530 The auto-repeater uses this.")
13532 (defun org-add-note ()
13533 "Add a note to the current entry.
13534 This is done in the same way as adding a state change note."
13535 (interactive)
13536 (org-add-log-setup 'note))
13538 (defun org-log-beginning (&optional create)
13539 "Return expected start of log notes in current entry.
13540 When optional argument CREATE is non-nil, the function creates
13541 a drawer to store notes, if necessary. Returned position ignores
13542 narrowing."
13543 (org-with-wide-buffer
13544 (let ((drawer (org-log-into-drawer)))
13545 (cond
13546 (drawer
13547 (org-end-of-meta-data)
13548 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13549 (end (if (org-at-heading-p) (point)
13550 (save-excursion (outline-next-heading) (point))))
13551 (case-fold-search t))
13552 (catch 'exit
13553 ;; Try to find existing drawer.
13554 (while (re-search-forward regexp end t)
13555 (let ((element (org-element-at-point)))
13556 (when (eq (org-element-type element) 'drawer)
13557 (let ((cend (org-element-property :contents-end element)))
13558 (when (and (not org-log-states-order-reversed) cend)
13559 (goto-char cend)))
13560 (throw 'exit nil))))
13561 ;; No drawer found. Create one, if permitted.
13562 (when create
13563 (unless (bolp) (insert "\n"))
13564 (let ((beg (point)))
13565 (insert ":" drawer ":\n:END:\n")
13566 (org-indent-region beg (point)))
13567 (end-of-line -1)))))
13569 (when org-log-state-notes-insert-after-drawers (org-end-of-meta-data t))
13570 (skip-chars-forward " \t\n")
13571 (beginning-of-line)
13572 (unless org-log-states-order-reversed
13573 (org-skip-over-state-notes)
13574 (skip-chars-backward " \t\n")
13575 (forward-line)))))
13576 (if (bolp) (point) (line-beginning-position 2))))
13578 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13579 "Set up the post command hook to take a note.
13580 If this is about to TODO state change, the new state is expected in STATE.
13581 HOW is an indicator what kind of note should be created.
13582 EXTRA is additional text that will be inserted into the notes buffer."
13583 (move-marker org-log-note-marker (point))
13584 (setq org-log-note-purpose purpose
13585 org-log-note-state state
13586 org-log-note-previous-state prev-state
13587 org-log-note-how how
13588 org-log-note-extra extra
13589 org-log-note-effective-time (org-current-effective-time))
13590 (add-hook 'post-command-hook 'org-add-log-note 'append))
13592 (defun org-skip-over-state-notes ()
13593 "Skip past the list of State notes in an entry."
13594 (when (ignore-errors (goto-char (org-in-item-p)))
13595 (let* ((struct (org-list-struct))
13596 (prevs (org-list-prevs-alist struct))
13597 (regexp
13598 (concat "[ \t]*- +"
13599 (replace-regexp-in-string
13600 " +" " +"
13601 (org-replace-escapes
13602 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13603 `(("%d" . ,org-ts-regexp-inactive)
13604 ("%D" . ,org-ts-regexp)
13605 ("%s" . "\"\\S-+\"")
13606 ("%S" . "\"\\S-+\"")
13607 ("%t" . ,org-ts-regexp-inactive)
13608 ("%T" . ,org-ts-regexp)
13609 ("%u" . ".*?")
13610 ("%U" . ".*?")))))))
13611 (while (org-looking-at-p regexp)
13612 (goto-char (or (org-list-get-next-item (point) struct prevs)
13613 (org-list-get-item-end (point) struct)))))))
13615 (defun org-add-log-note (&optional _purpose)
13616 "Pop up a window for taking a note, and add this note later."
13617 (remove-hook 'post-command-hook 'org-add-log-note)
13618 (setq org-log-note-window-configuration (current-window-configuration))
13619 (delete-other-windows)
13620 (move-marker org-log-note-return-to (point))
13621 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13622 (goto-char org-log-note-marker)
13623 (org-switch-to-buffer-other-window "*Org Note*")
13624 (erase-buffer)
13625 (if (memq org-log-note-how '(time state))
13626 (let (current-prefix-arg) (org-store-log-note))
13627 (let ((org-inhibit-startup t)) (org-mode))
13628 (insert (format "# Insert note for %s.
13629 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13630 (cond
13631 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13632 ((eq org-log-note-purpose 'done) "closed todo item")
13633 ((eq org-log-note-purpose 'state)
13634 (format "state change from \"%s\" to \"%s\""
13635 (or org-log-note-previous-state "")
13636 (or org-log-note-state "")))
13637 ((eq org-log-note-purpose 'reschedule)
13638 "rescheduling")
13639 ((eq org-log-note-purpose 'delschedule)
13640 "no longer scheduled")
13641 ((eq org-log-note-purpose 'redeadline)
13642 "changing deadline")
13643 ((eq org-log-note-purpose 'deldeadline)
13644 "removing deadline")
13645 ((eq org-log-note-purpose 'refile)
13646 "refiling")
13647 ((eq org-log-note-purpose 'note)
13648 "this entry")
13649 (t (error "This should not happen")))))
13650 (when org-log-note-extra (insert org-log-note-extra))
13651 (setq-local org-finish-function 'org-store-log-note)
13652 (run-hooks 'org-log-buffer-setup-hook)))
13654 (defvar org-note-abort nil) ; dynamically scoped
13655 (defun org-store-log-note ()
13656 "Finish taking a log note, and insert it to where it belongs."
13657 (let ((txt (prog1 (buffer-string)
13658 (kill-buffer)))
13659 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13660 lines)
13661 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13662 (setq txt (replace-match "" t t txt)))
13663 (when (string-match "\\s-+\\'" txt)
13664 (setq txt (replace-match "" t t txt)))
13665 (setq lines (org-split-string txt "\n"))
13666 (when (org-string-nw-p note)
13667 (setq note
13668 (org-replace-escapes
13669 note
13670 (list (cons "%u" (user-login-name))
13671 (cons "%U" user-full-name)
13672 (cons "%t" (format-time-string
13673 (org-time-stamp-format 'long 'inactive)
13674 org-log-note-effective-time))
13675 (cons "%T" (format-time-string
13676 (org-time-stamp-format 'long nil)
13677 org-log-note-effective-time))
13678 (cons "%d" (format-time-string
13679 (org-time-stamp-format nil 'inactive)
13680 org-log-note-effective-time))
13681 (cons "%D" (format-time-string
13682 (org-time-stamp-format nil nil)
13683 org-log-note-effective-time))
13684 (cons "%s" (cond
13685 ((not org-log-note-state) "")
13686 ((org-string-match-p org-ts-regexp
13687 org-log-note-state)
13688 (format "\"[%s]\""
13689 (substring org-log-note-state 1 -1)))
13690 (t (format "\"%s\"" org-log-note-state))))
13691 (cons "%S"
13692 (cond
13693 ((not org-log-note-previous-state) "")
13694 ((org-string-match-p org-ts-regexp
13695 org-log-note-previous-state)
13696 (format "\"[%s]\""
13697 (substring
13698 org-log-note-previous-state 1 -1)))
13699 (t (format "\"%s\""
13700 org-log-note-previous-state)))))))
13701 (when lines (setq note (concat note " \\\\")))
13702 (push note lines))
13703 (when (and lines (not (or current-prefix-arg org-note-abort)))
13704 (with-current-buffer (marker-buffer org-log-note-marker)
13705 (org-with-wide-buffer
13706 ;; Find location for the new note.
13707 (goto-char org-log-note-marker)
13708 (set-marker org-log-note-marker nil)
13709 (goto-char (org-log-beginning t))
13710 ;; Make sure point is at the beginning of an empty line.
13711 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13712 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13713 ;; In an existing list, add a new item at the top level.
13714 ;; Otherwise, indent line like a regular one.
13715 (let ((itemp (org-in-item-p)))
13716 (if itemp
13717 (org-indent-line-to
13718 (let ((struct (save-excursion
13719 (goto-char itemp) (org-list-struct))))
13720 (org-list-get-ind (org-list-get-top-point struct) struct)))
13721 (org-indent-line)))
13722 (insert (org-list-bullet-string "-") (pop lines))
13723 (let ((ind (org-list-item-body-column (line-beginning-position))))
13724 (dolist (line lines)
13725 (insert "\n")
13726 (org-indent-line-to ind)
13727 (insert line)))
13728 (message "Note stored")
13729 (org-back-to-heading t)
13730 (org-cycle-hide-drawers 'children))
13731 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13732 ;; from within `org-add-log-note' because `buffer-undo-list'
13733 ;; is then modified outside of `org-with-remote-undo'.
13734 (when (eq this-command 'org-agenda-todo)
13735 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13736 ;; Don't add undo information when called from `org-agenda-todo'.
13737 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13738 (set-window-configuration org-log-note-window-configuration)
13739 (with-current-buffer (marker-buffer org-log-note-return-to)
13740 (goto-char org-log-note-return-to))
13741 (move-marker org-log-note-return-to nil)
13742 (when org-log-post-message (message "%s" org-log-post-message))))
13744 (defun org-remove-empty-drawer-at (pos)
13745 "Remove an empty drawer at position POS.
13746 POS may also be a marker."
13747 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13748 (org-with-wide-buffer
13749 (goto-char pos)
13750 (let ((drawer (org-element-at-point)))
13751 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13752 (not (org-element-property :contents-begin drawer)))
13753 (delete-region (org-element-property :begin drawer)
13754 (progn (goto-char (org-element-property :end drawer))
13755 (skip-chars-backward " \r\t\n")
13756 (forward-line)
13757 (point))))))))
13759 (defvar org-ts-type nil)
13760 (defun org-sparse-tree (&optional arg type)
13761 "Create a sparse tree, prompt for the details.
13762 This command can create sparse trees. You first need to select the type
13763 of match used to create the tree:
13765 t Show all TODO entries.
13766 T Show entries with a specific TODO keyword.
13767 m Show entries selected by a tags/property match.
13768 p Enter a property name and its value (both with completion on existing
13769 names/values) and show entries with that property.
13770 r Show entries matching a regular expression (`/' can be used as well).
13771 b Show deadlines and scheduled items before a date.
13772 a Show deadlines and scheduled items after a date.
13773 d Show deadlines due within `org-deadline-warning-days'.
13774 D Show deadlines and scheduled items between a date range."
13775 (interactive "P")
13776 (setq type (or type org-sparse-tree-default-date-type))
13777 (setq org-ts-type type)
13778 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13779 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13780 \[c]ycle through date types: %s"
13781 (case type
13782 (all "all timestamps")
13783 (scheduled "only scheduled")
13784 (deadline "only deadline")
13785 (active "only active timestamps")
13786 (inactive "only inactive timestamps")
13787 (closed "with a closed time-stamp")
13788 (otherwise "scheduled/deadline")))
13789 (let ((answer (read-char-exclusive)))
13790 (case answer
13792 (org-sparse-tree
13794 (cadr
13795 (memq type '(nil all scheduled deadline active inactive closed)))))
13796 (?d (call-interactively 'org-check-deadlines))
13797 (?b (call-interactively 'org-check-before-date))
13798 (?a (call-interactively 'org-check-after-date))
13799 (?D (call-interactively 'org-check-dates-range))
13800 (?t (call-interactively 'org-show-todo-tree))
13801 (?T (org-show-todo-tree '(4)))
13802 (?m (call-interactively 'org-match-sparse-tree))
13803 ((?p ?P)
13804 (let* ((kwd (completing-read
13805 "Property: " (mapcar #'list (org-buffer-property-keys))))
13806 (value (completing-read
13807 "Value: " (mapcar #'list (org-property-values kwd)))))
13808 (unless (string-match "\\`{.*}\\'" value)
13809 (setq value (concat "\"" value "\"")))
13810 (org-match-sparse-tree arg (concat kwd "=" value))))
13811 ((?r ?R ?/) (call-interactively 'org-occur))
13812 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13814 (defvar-local org-occur-highlights nil
13815 "List of overlays used for occur matches.")
13816 (defvar-local org-occur-parameters nil
13817 "Parameters of the active org-occur calls.
13818 This is a list, each call to org-occur pushes as cons cell,
13819 containing the regular expression and the callback, onto the list.
13820 The list can contain several entries if `org-occur' has been called
13821 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13822 will only contain one set of parameters. When the highlights are
13823 removed (for example with `C-c C-c', or with the next edit (depending
13824 on `org-remove-highlights-with-change'), this variable is emptied
13825 as well.")
13827 (defun org-occur (regexp &optional keep-previous callback)
13828 "Make a compact tree which shows all matches of REGEXP.
13829 The tree will show the lines where the regexp matches, and all higher
13830 headlines above the match. It will also show the heading after the match,
13831 to make sure editing the matching entry is easy.
13832 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13833 call to `org-occur' will be kept, to allow stacking of calls to this
13834 command.
13835 If CALLBACK is non-nil, it is a function which is called to confirm
13836 that the match should indeed be shown."
13837 (interactive "sRegexp: \nP")
13838 (when (equal regexp "")
13839 (user-error "Regexp cannot be empty"))
13840 (unless keep-previous
13841 (org-remove-occur-highlights nil nil t))
13842 (push (cons regexp callback) org-occur-parameters)
13843 (let ((cnt 0))
13844 (save-excursion
13845 (goto-char (point-min))
13846 (when (or (not keep-previous) ; do not want to keep
13847 (not org-occur-highlights)) ; no previous matches
13848 ;; hide everything
13849 (org-overview))
13850 (while (re-search-forward regexp nil t)
13851 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13852 (when (or (not callback)
13853 (save-match-data (funcall callback)))
13854 (setq cnt (1+ cnt))
13855 (when org-highlight-sparse-tree-matches
13856 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13857 (org-show-context 'occur-tree))))
13858 (when org-remove-highlights-with-change
13859 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13860 nil 'local))
13861 (unless org-sparse-tree-open-archived-trees
13862 (org-hide-archived-subtrees (point-min) (point-max)))
13863 (run-hooks 'org-occur-hook)
13864 (when (org-called-interactively-p 'interactive)
13865 (message "%d match(es) for regexp %s" cnt regexp))
13866 cnt))
13868 (defun org-occur-next-match (&optional n _reset)
13869 "Function for `next-error-function' to find sparse tree matches.
13870 N is the number of matches to move, when negative move backwards.
13871 This function always goes back to the starting point when no
13872 match is found."
13873 (let* ((limit (if (< n 0) (point-min) (point-max)))
13874 (search-func (if (< n 0)
13875 'previous-single-char-property-change
13876 'next-single-char-property-change))
13877 (n (abs n))
13878 (pos (point))
13880 (catch 'exit
13881 (while (setq p1 (funcall search-func (point) 'org-type))
13882 (when (equal p1 limit)
13883 (goto-char pos)
13884 (user-error "No more matches"))
13885 (when (equal (get-char-property p1 'org-type) 'org-occur)
13886 (setq n (1- n))
13887 (when (= n 0)
13888 (goto-char p1)
13889 (throw 'exit (point))))
13890 (goto-char p1))
13891 (goto-char p1)
13892 (user-error "No more matches"))))
13894 (defun org-show-context (&optional key)
13895 "Make sure point and context are visible.
13896 Optional argument KEY, when non-nil, is a symbol. See
13897 `org-show-context-detail' for allowed values and how much is to
13898 be shown."
13899 (org-show-set-visibility
13900 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13901 ((cdr (assq key org-show-context-detail)))
13902 (t (cdr (assq 'default org-show-context-detail))))))
13904 (defun org-show-set-visibility (detail)
13905 "Set visibility around point according to DETAIL.
13906 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13907 `tree', `canonical' or t. See `org-show-context-detail' for more
13908 information."
13909 (unless (org-before-first-heading-p)
13910 ;; Show current heading and possibly its entry, following headline
13911 ;; or all children.
13912 (if (and (org-at-heading-p) (not (eq detail 'local)))
13913 (org-flag-heading nil)
13914 (org-show-entry)
13915 (org-with-limited-levels
13916 (case detail
13917 ((tree canonical t) (org-show-children))
13918 ((nil minimal ancestors))
13919 (t (save-excursion
13920 (outline-next-heading)
13921 (org-flag-heading nil))))))
13922 ;; Show all siblings.
13923 (when (eq detail 'lineage) (org-show-siblings))
13924 ;; Show ancestors, possibly with their children.
13925 (when (memq detail '(ancestors lineage tree canonical t))
13926 (save-excursion
13927 (while (org-up-heading-safe)
13928 (org-flag-heading nil)
13929 (when (memq detail '(canonical t)) (org-show-entry))
13930 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13932 (defvar org-reveal-start-hook nil
13933 "Hook run before revealing a location.")
13935 (defun org-reveal (&optional siblings)
13936 "Show current entry, hierarchy above it, and the following headline.
13938 This can be used to show a consistent set of context around
13939 locations exposed with `org-show-context'.
13941 With optional argument SIBLINGS, on each level of the hierarchy all
13942 siblings are shown. This repairs the tree structure to what it would
13943 look like when opened with hierarchical calls to `org-cycle'.
13945 With double optional argument \\[universal-argument] \\[universal-argument], \
13946 go to the parent and show the
13947 entire tree."
13948 (interactive "P")
13949 (run-hooks 'org-reveal-start-hook)
13950 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13951 ((equal siblings '(16))
13952 (save-excursion
13953 (when (org-up-heading-safe)
13954 (org-show-subtree)
13955 (run-hook-with-args 'org-cycle-hook 'subtree))))
13956 (t (org-show-set-visibility 'lineage))))
13958 (defun org-highlight-new-match (beg end)
13959 "Highlight from BEG to END and mark the highlight is an occur headline."
13960 (let ((ov (make-overlay beg end)))
13961 (overlay-put ov 'face 'secondary-selection)
13962 (overlay-put ov 'org-type 'org-occur)
13963 (push ov org-occur-highlights)))
13965 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13966 "Remove the occur highlights from the buffer.
13967 BEG and END are ignored. If NOREMOVE is nil, remove this function
13968 from the `before-change-functions' in the current buffer."
13969 (interactive)
13970 (unless org-inhibit-highlight-removal
13971 (mapc #'delete-overlay org-occur-highlights)
13972 (setq org-occur-highlights nil)
13973 (setq org-occur-parameters nil)
13974 (unless noremove
13975 (remove-hook 'before-change-functions
13976 'org-remove-occur-highlights 'local))))
13978 ;;;; Priorities
13980 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13981 "Regular expression matching the priority indicator.")
13983 (defvar org-remove-priority-next-time nil)
13985 (defun org-priority-up ()
13986 "Increase the priority of the current item."
13987 (interactive)
13988 (org-priority 'up))
13990 (defun org-priority-down ()
13991 "Decrease the priority of the current item."
13992 (interactive)
13993 (org-priority 'down))
13995 (defun org-priority (&optional action _show)
13996 "Change the priority of an item.
13997 ACTION can be `set', `up', `down', or a character."
13998 (interactive "P")
13999 (if (equal action '(4))
14000 (org-show-priority)
14001 (unless org-enable-priority-commands
14002 (user-error "Priority commands are disabled"))
14003 (setq action (or action 'set))
14004 (let (current new news have remove)
14005 (save-excursion
14006 (org-back-to-heading t)
14007 (when (looking-at org-priority-regexp)
14008 (setq current (string-to-char (match-string 2))
14009 have t))
14010 (cond
14011 ((eq action 'remove)
14012 (setq remove t new ?\ ))
14013 ((or (eq action 'set)
14014 (if (featurep 'xemacs) (characterp action) (integerp action)))
14015 (if (not (eq action 'set))
14016 (setq new action)
14017 (message "Priority %c-%c, SPC to remove: "
14018 org-highest-priority org-lowest-priority)
14019 (save-match-data
14020 (setq new (read-char-exclusive))))
14021 (when (and (= (upcase org-highest-priority) org-highest-priority)
14022 (= (upcase org-lowest-priority) org-lowest-priority))
14023 (setq new (upcase new)))
14024 (cond ((equal new ?\ ) (setq remove t))
14025 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14026 (user-error "Priority must be between `%c' and `%c'"
14027 org-highest-priority org-lowest-priority))))
14028 ((eq action 'up)
14029 (setq new (if have
14030 (1- current) ; normal cycling
14031 ;; last priority was empty
14032 (if (eq last-command this-command)
14033 org-lowest-priority ; wrap around empty to lowest
14034 ;; default
14035 (if org-priority-start-cycle-with-default
14036 org-default-priority
14037 (1- org-default-priority))))))
14038 ((eq action 'down)
14039 (setq new (if have
14040 (1+ current) ; normal cycling
14041 ;; last priority was empty
14042 (if (eq last-command this-command)
14043 org-highest-priority ; wrap around empty to highest
14044 ;; default
14045 (if org-priority-start-cycle-with-default
14046 org-default-priority
14047 (1+ org-default-priority))))))
14048 (t (user-error "Invalid action")))
14049 (when (or (< (upcase new) org-highest-priority)
14050 (> (upcase new) org-lowest-priority))
14051 (if (and (memq action '(up down))
14052 (not have) (not (eq last-command this-command)))
14053 ;; `new' is from default priority
14054 (error
14055 "The default can not be set, see `org-default-priority' why")
14056 ;; normal cycling: `new' is beyond highest/lowest priority
14057 ;; and is wrapped around to the empty priority
14058 (setq remove t)))
14059 (setq news (format "%c" new))
14060 (if have
14061 (if remove
14062 (replace-match "" t t nil 1)
14063 (replace-match news t t nil 2))
14064 (if remove
14065 (user-error "No priority cookie found in line")
14066 (let ((case-fold-search nil))
14067 (looking-at org-todo-line-regexp))
14068 (if (match-end 2)
14069 (progn
14070 (goto-char (match-end 2))
14071 (insert " [#" news "]"))
14072 (goto-char (match-beginning 3))
14073 (insert "[#" news "] "))))
14074 (org-set-tags nil 'align))
14075 (if remove
14076 (message "Priority removed")
14077 (message "Priority of current item set to %s" news)))))
14079 (defun org-show-priority ()
14080 "Show the priority of the current item.
14081 This priority is composed of the main priority given with the [#A] cookies,
14082 and by additional input from the age of a schedules or deadline entry."
14083 (interactive)
14084 (let ((pri (if (eq major-mode 'org-agenda-mode)
14085 (org-get-at-bol 'priority)
14086 (save-excursion
14087 (save-match-data
14088 (beginning-of-line)
14089 (and (looking-at org-heading-regexp)
14090 (org-get-priority (match-string 0))))))))
14091 (message "Priority is %d" (if pri pri -1000))))
14093 (defun org-get-priority (s)
14094 "Find priority cookie and return priority."
14095 (save-match-data
14096 (if (functionp org-get-priority-function)
14097 (funcall org-get-priority-function)
14098 (if (not (string-match org-priority-regexp s))
14099 (* 1000 (- org-lowest-priority org-default-priority))
14100 (* 1000 (- org-lowest-priority
14101 (string-to-char (match-string 2 s))))))))
14103 ;;;; Tags
14105 (defvar org-agenda-archives-mode)
14106 (defvar org-map-continue-from nil
14107 "Position from where mapping should continue.
14108 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14110 (defvar org-scanner-tags nil
14111 "The current tag list while the tags scanner is running.")
14113 (defvar org-trust-scanner-tags nil
14114 "Should `org-get-tags-at' use the tags for the scanner.
14115 This is for internal dynamical scoping only.
14116 When this is non-nil, the function `org-get-tags-at' will return the value
14117 of `org-scanner-tags' instead of building the list by itself. This
14118 can lead to large speed-ups when the tags scanner is used in a file with
14119 many entries, and when the list of tags is retrieved, for example to
14120 obtain a list of properties. Building the tags list for each entry in such
14121 a file becomes an N^2 operation - but with this variable set, it scales
14122 as N.")
14124 (defvar org--matcher-tags-todo-only nil)
14126 (defun org-scan-tags (action matcher todo-only &optional start-level)
14127 "Scan headline tags with inheritance and produce output ACTION.
14129 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14130 or `agenda' to produce an entry list for an agenda view. It can also be
14131 a Lisp form or a function that should be called at each matched headline, in
14132 this case the return value is a list of all return values from these calls.
14134 MATCHER is a function accepting three arguments, returning
14135 a non-nil value whenever a given set of tags qualifies a headline
14136 for inclusion. See `org-make-tags-matcher' for more information.
14137 As a special case, it can also be set to t (respectively nil) in
14138 order to match all (respectively none) headline.
14140 When TODO-ONLY is non-nil, only lines with a not-done TODO
14141 keyword are included in the output.
14143 START-LEVEL can be a string with asterisks, reducing the scope to
14144 headlines matching this string."
14145 (require 'org-agenda)
14146 (let* ((re (concat "^"
14147 (if start-level
14148 ;; Get the correct level to match
14149 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14150 org-outline-regexp)
14151 " *\\(\\<\\("
14152 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14153 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14154 (props (list 'face 'default
14155 'done-face 'org-agenda-done
14156 'undone-face 'default
14157 'mouse-face 'highlight
14158 'org-not-done-regexp org-not-done-regexp
14159 'org-todo-regexp org-todo-regexp
14160 'org-complex-heading-regexp org-complex-heading-regexp
14161 'help-echo
14162 (format "mouse-2 or RET jump to org file %s"
14163 (abbreviate-file-name
14164 (or (buffer-file-name (buffer-base-buffer))
14165 (buffer-name (buffer-base-buffer)))))))
14166 (org-map-continue-from nil)
14167 lspos tags tags-list
14168 (tags-alist (list (cons 0 org-file-tags)))
14169 (llast 0) rtn rtn1 level category i txt
14170 todo marker entry priority
14171 ts-date ts-date-type ts-date-pair)
14172 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14173 (setq action (list 'lambda nil action)))
14174 (save-excursion
14175 (goto-char (point-min))
14176 (when (eq action 'sparse-tree)
14177 (org-overview)
14178 (org-remove-occur-highlights))
14179 (while (let (case-fold-search)
14180 (re-search-forward re nil t))
14181 (setq org-map-continue-from nil)
14182 (catch :skip
14183 (setq todo
14184 ;; TODO: is the 1-2 difference a bug?
14185 (when (match-end 1) (org-match-string-no-properties 2))
14186 tags (when (match-end 4) (org-match-string-no-properties 4)))
14187 (goto-char (setq lspos (match-beginning 0)))
14188 (setq level (org-reduced-level (org-outline-level))
14189 category (org-get-category))
14190 (when (eq action 'agenda)
14191 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14192 ts-date (car ts-date-pair)
14193 ts-date-type (cdr ts-date-pair)))
14194 (setq i llast llast level)
14195 ;; remove tag lists from same and sublevels
14196 (while (>= i level)
14197 (when (setq entry (assoc i tags-alist))
14198 (setq tags-alist (delete entry tags-alist)))
14199 (setq i (1- i)))
14200 ;; add the next tags
14201 (when tags
14202 (setq tags (org-split-string tags ":")
14203 tags-alist
14204 (cons (cons level tags) tags-alist)))
14205 ;; compile tags for current headline
14206 (setq tags-list
14207 (if org-use-tag-inheritance
14208 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14209 tags)
14210 org-scanner-tags tags-list)
14211 (when org-use-tag-inheritance
14212 (setcdr (car tags-alist)
14213 (mapcar (lambda (x)
14214 (setq x (copy-sequence x))
14215 (org-add-prop-inherited x))
14216 (cdar tags-alist))))
14217 (when (and tags org-use-tag-inheritance
14218 (or (not (eq t org-use-tag-inheritance))
14219 org-tags-exclude-from-inheritance))
14220 ;; Selective inheritance, remove uninherited ones.
14221 (setcdr (car tags-alist)
14222 (org-remove-uninherited-tags (cdar tags-alist))))
14223 (when (and
14225 ;; eval matcher only when the todo condition is OK
14226 (and (or (not todo-only) (member todo org-not-done-keywords))
14227 (if (functionp matcher)
14228 (let ((case-fold-search t) (org-trust-scanner-tags t))
14229 (funcall matcher todo tags-list level))
14230 matcher))
14232 ;; Call the skipper, but return t if it does not
14233 ;; skip, so that the `and' form continues evaluating.
14234 (progn
14235 (unless (eq action 'sparse-tree) (org-agenda-skip))
14238 ;; Check if timestamps are deselecting this entry
14239 (or (not todo-only)
14240 (and (member todo org-not-done-keywords)
14241 (or (not org-agenda-tags-todo-honor-ignore-options)
14242 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14244 ;; select this headline
14245 (cond
14246 ((eq action 'sparse-tree)
14247 (and org-highlight-sparse-tree-matches
14248 (org-get-heading) (match-end 0)
14249 (org-highlight-new-match
14250 (match-beginning 1) (match-end 1)))
14251 (org-show-context 'tags-tree))
14252 ((eq action 'agenda)
14253 (setq txt (org-agenda-format-item
14255 (concat
14256 (if (eq org-tags-match-list-sublevels 'indented)
14257 (make-string (1- level) ?.) "")
14258 (org-get-heading))
14259 (make-string level ?\s)
14260 category
14261 tags-list)
14262 priority (org-get-priority txt))
14263 (goto-char lspos)
14264 (setq marker (org-agenda-new-marker))
14265 (org-add-props txt props
14266 'org-marker marker 'org-hd-marker marker 'org-category category
14267 'todo-state todo
14268 'ts-date ts-date
14269 'priority priority
14270 'type (concat "tagsmatch" ts-date-type))
14271 (push txt rtn))
14272 ((functionp action)
14273 (setq org-map-continue-from nil)
14274 (save-excursion
14275 (setq rtn1 (funcall action))
14276 (push rtn1 rtn)))
14277 (t (user-error "Invalid action")))
14279 ;; if we are to skip sublevels, jump to end of subtree
14280 (unless org-tags-match-list-sublevels
14281 (org-end-of-subtree t)
14282 (backward-char 1))))
14283 ;; Get the correct position from where to continue
14284 (if org-map-continue-from
14285 (goto-char org-map-continue-from)
14286 (and (= (point) lspos) (end-of-line 1)))))
14287 (when (and (eq action 'sparse-tree)
14288 (not org-sparse-tree-open-archived-trees))
14289 (org-hide-archived-subtrees (point-min) (point-max)))
14290 (nreverse rtn)))
14292 (defun org-remove-uninherited-tags (tags)
14293 "Remove all tags that are not inherited from the list TAGS."
14294 (cond
14295 ((eq org-use-tag-inheritance t)
14296 (if org-tags-exclude-from-inheritance
14297 (org-delete-all org-tags-exclude-from-inheritance tags)
14298 tags))
14299 ((not org-use-tag-inheritance) nil)
14300 ((stringp org-use-tag-inheritance)
14301 (delq nil (mapcar
14302 (lambda (x)
14303 (if (and (string-match org-use-tag-inheritance x)
14304 (not (member x org-tags-exclude-from-inheritance)))
14305 x nil))
14306 tags)))
14307 ((listp org-use-tag-inheritance)
14308 (delq nil (mapcar
14309 (lambda (x)
14310 (if (member x org-use-tag-inheritance) x nil))
14311 tags)))))
14313 (defun org-match-sparse-tree (&optional todo-only match)
14314 "Create a sparse tree according to tags string MATCH.
14315 MATCH can contain positive and negative selection of tags, like
14316 \"+WORK+URGENT-WITHBOSS\".
14317 If optional argument TODO-ONLY is non-nil, only select lines that are
14318 also TODO lines."
14319 (interactive "P")
14320 (org-agenda-prepare-buffers (list (current-buffer)))
14321 (let ((org--matcher-tags-todo-only todo-only))
14322 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14323 org--matcher-tags-todo-only)))
14325 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14327 (defvar org-cached-props nil)
14328 (defun org-cached-entry-get (pom property)
14329 (if (or (eq t org-use-property-inheritance)
14330 (and (stringp org-use-property-inheritance)
14331 (let ((case-fold-search t))
14332 (org-string-match-p org-use-property-inheritance property)))
14333 (and (listp org-use-property-inheritance)
14334 (member-ignore-case property org-use-property-inheritance)))
14335 ;; Caching is not possible, check it directly.
14336 (org-entry-get pom property 'inherit)
14337 ;; Get all properties, so we can do complicated checks easily.
14338 (cdr (assoc-string property
14339 (or org-cached-props
14340 (setq org-cached-props (org-entry-properties pom)))
14341 t))))
14343 (defun org-global-tags-completion-table (&optional files)
14344 "Return the list of all tags in all agenda buffer/files.
14345 Optional FILES argument is a list of files which can be used
14346 instead of the agenda files."
14347 (save-excursion
14348 (org-uniquify
14349 (delq nil
14350 (apply 'append
14351 (mapcar
14352 (lambda (file)
14353 (set-buffer (find-file-noselect file))
14354 (append (org-get-buffer-tags)
14355 (mapcar (lambda (x) (if (stringp (car-safe x))
14356 (list (car-safe x)) nil))
14357 org-tag-alist)))
14358 (if (and files (car files))
14359 files
14360 (org-agenda-files))))))))
14362 (defun org-make-tags-matcher (match)
14363 "Create the TAGS/TODO matcher form for the selection string MATCH.
14365 Returns a cons of the selection string MATCH and a function
14366 implementing the matcher.
14368 The matcher is to be called at an Org entry, with point on the
14369 headline, and returns non-nil if the entry matches the selection
14370 string MATCH. It must be called with three arguments: the TODO
14371 keyword at the entry (or nil if none), the list of all tags at
14372 the entry including inherited ones and the reduced level of the
14373 headline. Additionally, the category of the entry, if any, must
14374 be specified as the text property `org-category' on the headline.
14376 This function sets the variable `org--matcher-tags-todo-only' to
14377 a non-nil value if the matcher restricts matching to TODO
14378 entries, otherwise it is not touched.
14380 See also `org-scan-tags'."
14381 (unless match
14382 ;; Get a new match request, with completion against the global
14383 ;; tags table and the local tags in current buffer.
14384 (let ((org-last-tags-completion-table
14385 (org-uniquify
14386 (delq nil (append (org-get-buffer-tags)
14387 (org-global-tags-completion-table))))))
14388 (setq match
14389 (completing-read
14390 "Match: "
14391 'org-tags-completion-function nil nil nil 'org-tags-history))))
14393 (let ((match0 match)
14394 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14395 (start 0)
14396 tagsmatch todomatch tagsmatcher todomatcher)
14398 ;; Expand group tags.
14399 (setq match (org-tags-expand match))
14401 ;; Check if there is a TODO part of this match, which would be the
14402 ;; part after a "/". To make sure that this slash is not part of
14403 ;; a property value to be matched against, we also check that
14404 ;; there is no / after that slash. First, find the last slash.
14405 (let ((s 0))
14406 (while (string-match "/+" match s)
14407 (setq start (match-beginning 0))
14408 (setq s (match-end 0))))
14409 (if (and (string-match "/+" match start)
14410 (not (string-match-p "\"" match start)))
14411 ;; Match contains also a TODO-matching request.
14412 (progn
14413 (setq tagsmatch (substring match 0 (match-beginning 0)))
14414 (setq todomatch (substring match (match-end 0)))
14415 (when (string-match "\\`!" todomatch)
14416 (setq org--matcher-tags-todo-only t)
14417 (setq todomatch (substring todomatch 1)))
14418 (when (string-match "\\`\\s-*\\'" todomatch)
14419 (setq todomatch nil)))
14420 ;; Only matching tags.
14421 (setq tagsmatch match)
14422 (setq todomatch nil))
14424 ;; Make the tags matcher.
14425 (if (not (org-string-nw-p tagsmatch))
14426 (setq tagsmatcher t)
14427 (let ((orlist nil)
14428 (orterms (org-split-string tagsmatch "|"))
14429 term)
14430 (while (setq term (pop orterms))
14431 (while (and (equal (substring term -1) "\\") orterms)
14432 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14433 (while (string-match re term)
14434 (let* ((rest (substring term (match-end 0)))
14435 (minus (and (match-end 1)
14436 (equal (match-string 1 term) "-")))
14437 (tag (save-match-data
14438 (replace-regexp-in-string
14439 "\\\\-" "-" (match-string 2 term))))
14440 (regexp (eq (string-to-char tag) ?{))
14441 (levelp (match-end 4))
14442 (propp (match-end 5))
14444 (cond
14445 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14446 (levelp
14447 `(,(org-op-to-function (match-string 3 term))
14448 level
14449 ,(string-to-number (match-string 4 term))))
14450 (propp
14451 (let* ((gv (pcase (upcase (match-string 5 term))
14452 ("CATEGORY"
14453 '(get-text-property (point) 'org-category))
14454 ("TODO" 'todo)
14455 (p `(org-cached-entry-get nil ,p))))
14456 (pv (match-string 7 term))
14457 (regexp (eq (string-to-char pv) ?{))
14458 (strp (eq (string-to-char pv) ?\"))
14459 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14460 (po (org-op-to-function (match-string 6 term)
14461 (if timep 'time strp))))
14462 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14463 (when timep (setq pv (org-matcher-time pv)))
14464 (cond ((and regexp (eq po 'org<>))
14465 `(not (string-match ,pv (or ,gv ""))))
14466 (regexp `(string-match ,pv (or ,gv "")))
14467 (strp `(,po (or ,gv "") ,pv))
14469 `(,po
14470 (string-to-number (or ,gv ""))
14471 ,(string-to-number pv))))))
14472 (t `(member ,tag tags-list)))))
14473 (push (if minus `(not ,mm) mm) tagsmatcher)
14474 (setq term rest)))
14475 (push (if (> (length tagsmatcher) 1)
14476 (cons 'and tagsmatcher)
14477 (car tagsmatcher))
14478 orlist)
14479 (setq tagsmatcher nil))
14480 (setq tagsmatcher
14481 `(progn (setq org-cached-props nil) ,(cons 'or orlist)))))
14483 ;; Make the TODO matcher.
14484 (if (not (org-string-nw-p todomatch))
14485 (setq todomatcher t)
14486 (let ((orlist nil))
14487 (dolist (term (org-split-string todomatch "|"))
14488 (while (string-match re term)
14489 (let* ((minus (and (match-end 1)
14490 (equal (match-string 1 term) "-")))
14491 (kwd (match-string 2 term))
14492 (regexp (eq (string-to-char kwd) ?{))
14493 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14494 `(equal todo ,kwd))))
14495 (push (if minus `(not ,mm) mm) todomatcher))
14496 (setq term (substring term (match-end 0))))
14497 (push (if (> (length todomatcher) 1)
14498 (cons 'and todomatcher)
14499 (car todomatcher))
14500 orlist)
14501 (setq todomatcher nil))
14502 (setq todomatcher (cons 'or orlist))))
14504 ;; Return the string and function of the matcher.
14505 (let ((matcher (if todomatcher `(and ,tagsmatcher ,todomatcher)
14506 tagsmatcher)))
14507 (when org--matcher-tags-todo-only
14508 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14509 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14511 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14512 "Expand group tags in MATCH.
14514 This replaces every group tag in MATCH with a regexp tag search.
14515 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14516 will be replaced like this:
14518 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14519 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14520 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14522 Replacing by a regexp preserves the structure of the match.
14523 E.g., this expansion
14525 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14527 will match anything tagged with \"Lab\" and \"Home\", or tagged
14528 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14530 A group tag in MATCH can contain regular expressions of its own.
14531 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14532 will be replaced like this:
14534 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14536 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14537 assumed to be a single group tag, and the function will return
14538 the list of tags in this group.
14540 When DOWNCASE is non-nil, expand downcased TAGS."
14541 (if org-group-tags
14542 (let* ((case-fold-search t)
14543 (stable org-mode-syntax-table)
14544 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14545 (taggroups (if downcased
14546 (mapcar (lambda (tg) (mapcar #'downcase tg))
14547 taggroups)
14548 taggroups))
14549 (taggroups-keys (mapcar #'car taggroups))
14550 (return-match (if downcased (downcase match) match))
14551 (count 0)
14552 (work-already-expanded tags-already-expanded)
14553 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14554 ;; @ and _ are allowed as word-components in tags.
14555 (modify-syntax-entry ?@ "w" stable)
14556 (modify-syntax-entry ?_ "w" stable)
14557 ;; Temporarily replace regexp-expressions in the match-expression.
14558 (while (string-match "{.+?}" return-match)
14559 (incf count)
14560 (push (match-string 0 return-match) regexps-in-match)
14561 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14562 (while (and taggroups-keys
14563 (with-syntax-table stable
14564 (string-match
14565 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14566 (regexp-opt taggroups-keys) "\\>\\)")
14567 return-match)))
14568 (let* ((dir (match-string 1 return-match))
14569 (tag (match-string 2 return-match))
14570 (tag (if downcased (downcase tag) tag)))
14571 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14572 (member tag work-already-expanded))
14573 (setq tags-in-group (assoc tag taggroups))
14574 (push tag work-already-expanded)
14575 ;; Recursively expand each tag in the group, if the tag hasn't
14576 ;; already been expanded. Restore the match-data after all recursive calls.
14577 (save-match-data
14578 (let (tags-expanded)
14579 (dolist (x (cdr tags-in-group))
14580 (if (and (member x taggroups-keys)
14581 (not (member x work-already-expanded)))
14582 (setq tags-expanded
14583 (delete-dups
14584 (append
14585 (org-tags-expand x t downcased
14586 work-already-expanded)
14587 tags-expanded)))
14588 (setq tags-expanded
14589 (append (list x) tags-expanded)))
14590 (setq work-already-expanded
14591 (delete-dups
14592 (append tags-expanded
14593 work-already-expanded))))
14594 (setq tags-in-group
14595 (delete-dups (cons (car tags-in-group)
14596 tags-expanded)))))
14597 ;; Filter tag-regexps from tags.
14598 (setq regexp-in-group-escaped
14599 (delq nil (mapcar (lambda (x)
14600 (if (stringp x)
14601 (and (equal "{" (substring x 0 1))
14602 (equal "}" (substring x -1))
14605 tags-in-group))
14606 regexp-in-group
14607 (mapcar (lambda (x)
14608 (substring x 1 -1))
14609 regexp-in-group-escaped)
14610 tags-in-group
14611 (delq nil (mapcar (lambda (x)
14612 (if (stringp x)
14613 (and (not (equal "{" (substring x 0 1)))
14614 (not (equal "}" (substring x -1)))
14617 tags-in-group)))
14618 ;; If single-as-list, do no more in the while-loop.
14619 (if (not single-as-list)
14620 (progn
14621 (when regexp-in-group
14622 (setq regexp-in-group
14623 (concat "\\|"
14624 (mapconcat 'identity regexp-in-group
14625 "\\|"))))
14626 (setq tags-in-group
14627 (concat dir
14628 "{\\<"
14629 (regexp-opt tags-in-group)
14630 "\\>"
14631 regexp-in-group
14632 "}"))
14633 (when (stringp tags-in-group)
14634 (org-add-props tags-in-group '(grouptag t)))
14635 (setq return-match
14636 (replace-match tags-in-group t t return-match)))
14637 (setq tags-in-group
14638 (append regexp-in-group-escaped tags-in-group))))
14639 (setq taggroups-keys (delete tag taggroups-keys))))
14640 ;; Add the regular expressions back into the match-expression again.
14641 (while regexps-in-match
14642 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14643 (pop regexps-in-match)
14644 return-match t t))
14645 (decf count))
14646 (if single-as-list
14647 (if tags-in-group tags-in-group (list return-match))
14648 return-match))
14649 (if single-as-list
14650 (list (if downcased (downcase match) match))
14651 match)))
14653 (defun org-op-to-function (op &optional stringp)
14654 "Turn an operator into the appropriate function."
14655 (setq op
14656 (cond
14657 ((equal op "<" ) '(< string< org-time<))
14658 ((equal op ">" ) '(> org-string> org-time>))
14659 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14660 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14661 ((member op '("=" "==")) '(= string= org-time=))
14662 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14663 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14665 (defun org<> (a b) (not (= a b)))
14666 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14667 (defun org-string>= (a b) (not (string< a b)))
14668 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14669 (defun org-string<> (a b) (not (string= a b)))
14670 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14671 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14672 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14673 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14674 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14675 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14676 (defun org-2ft (s)
14677 "Convert S to a floating point time.
14678 If S is already a number, just return it. If it is a string, parse
14679 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14680 (cond
14681 ((numberp s) s)
14682 ((stringp s)
14683 (condition-case nil
14684 (float-time (apply 'encode-time (org-parse-time-string s)))
14685 (error 0.)))
14686 (t 0.)))
14688 (defun org-time-today ()
14689 "Time in seconds today at 0:00.
14690 Returns the float number of seconds since the beginning of the
14691 epoch to the beginning of today (00:00)."
14692 (float-time (apply 'encode-time
14693 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14695 (defun org-matcher-time (s)
14696 "Interpret a time comparison value."
14697 (save-match-data
14698 (cond
14699 ((string= s "<now>") (float-time))
14700 ((string= s "<today>") (org-time-today))
14701 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14702 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14703 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14704 (+ (org-time-today)
14705 (* (string-to-number (match-string 1 s))
14706 (cdr (assoc (match-string 2 s)
14707 '(("d" . 86400.0) ("w" . 604800.0)
14708 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14709 (t (org-2ft s)))))
14711 (defun org-match-any-p (re list)
14712 "Does re match any element of list?"
14713 (setq list (mapcar (lambda (x) (string-match re x)) list))
14714 (delq nil list))
14716 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14717 (defvar org-tags-overlay (make-overlay 1 1))
14718 (org-detach-overlay org-tags-overlay)
14720 (defun org-get-local-tags-at (&optional pos)
14721 "Get a list of tags defined in the current headline."
14722 (org-get-tags-at pos 'local))
14724 (defun org-get-local-tags ()
14725 "Get a list of tags defined in the current headline."
14726 (org-get-tags-at nil 'local))
14728 (defun org-get-tags-at (&optional pos local)
14729 "Get a list of all headline tags applicable at POS.
14730 POS defaults to point. If tags are inherited, the list contains
14731 the targets in the same sequence as the headlines appear, i.e.
14732 the tags of the current headline come last.
14733 When LOCAL is non-nil, only return tags from the current headline,
14734 ignore inherited ones."
14735 (interactive)
14736 (if (and org-trust-scanner-tags
14737 (or (not pos) (equal pos (point)))
14738 (not local))
14739 org-scanner-tags
14740 (let (tags ltags lastpos parent)
14741 (save-excursion
14742 (save-restriction
14743 (widen)
14744 (goto-char (or pos (point)))
14745 (save-match-data
14746 (catch 'done
14747 (condition-case nil
14748 (progn
14749 (org-back-to-heading t)
14750 (while (not (equal lastpos (point)))
14751 (setq lastpos (point))
14752 (when (looking-at
14753 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14754 (setq ltags (org-split-string
14755 (org-match-string-no-properties 1) ":"))
14756 (when parent
14757 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14758 (setq tags (append
14759 (if parent
14760 (org-remove-uninherited-tags ltags)
14761 ltags)
14762 tags)))
14763 (or org-use-tag-inheritance (throw 'done t))
14764 (when local (throw 'done t))
14765 (or (org-up-heading-safe) (error nil))
14766 (setq parent t)))
14767 (error nil)))))
14768 (if local
14769 tags
14770 (reverse (delete-dups
14771 (reverse (append
14772 (org-remove-uninherited-tags
14773 org-file-tags)
14774 tags)))))))))
14776 (defun org-add-prop-inherited (s)
14777 (add-text-properties 0 (length s) '(inherited t) s)
14780 (defun org-toggle-tag (tag &optional onoff)
14781 "Toggle the tag TAG for the current line.
14782 If ONOFF is `on' or `off', don't toggle but set to this state."
14783 (let (res current)
14784 (save-excursion
14785 (org-back-to-heading t)
14786 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14787 (point-at-eol) t)
14788 (progn
14789 (setq current (match-string 1))
14790 (replace-match ""))
14791 (setq current ""))
14792 (setq current (nreverse (org-split-string current ":")))
14793 (cond
14794 ((eq onoff 'on)
14795 (setq res t)
14796 (or (member tag current) (push tag current)))
14797 ((eq onoff 'off)
14798 (or (not (member tag current)) (setq current (delete tag current))))
14799 (t (if (member tag current)
14800 (setq current (delete tag current))
14801 (setq res t)
14802 (push tag current))))
14803 (end-of-line 1)
14804 (if current
14805 (progn
14806 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14807 (org-set-tags nil t))
14808 (delete-horizontal-space))
14809 (run-hooks 'org-after-tags-change-hook))
14810 res))
14812 (defun org-align-tags-here (to-col)
14813 ;; Assumes that this is a headline
14814 "Align tags on the current headline to TO-COL."
14815 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14816 (beginning-of-line 1)
14817 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14818 (< pos (match-beginning 2)))
14819 (progn
14820 (setq tags-l (- (match-end 2) (match-beginning 2)))
14821 (goto-char (match-beginning 1))
14822 (insert " ")
14823 (delete-region (point) (1+ (match-beginning 2)))
14824 (setq ncol (max (current-column)
14825 (1+ col)
14826 (if (> to-col 0)
14827 to-col
14828 (- (abs to-col) tags-l))))
14829 (setq p (point))
14830 (insert (make-string (- ncol (current-column)) ?\ ))
14831 (setq ncol (current-column))
14832 (when indent-tabs-mode (tabify p (point-at-eol)))
14833 (org-move-to-column (min ncol col)))
14834 (goto-char pos))))
14836 (defun org-set-tags-command (&optional arg just-align)
14837 "Call the set-tags command for the current entry."
14838 (interactive "P")
14839 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14840 (org-set-tags arg just-align)
14841 (save-excursion
14842 (unless (and (org-region-active-p)
14843 org-loop-over-headlines-in-active-region)
14844 (org-back-to-heading t))
14845 (org-set-tags arg just-align))))
14847 (defun org-set-tags-to (data)
14848 "Set the tags of the current entry to DATA, replacing the current tags.
14849 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14850 If DATA is nil or the empty string, any tags will be removed."
14851 (interactive "sTags: ")
14852 (setq data
14853 (cond
14854 ((eq data nil) "")
14855 ((equal data "") "")
14856 ((stringp data)
14857 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14858 ":"))
14859 ((listp data)
14860 (concat ":" (mapconcat 'identity data ":") ":"))))
14861 (when data
14862 (save-excursion
14863 (org-back-to-heading t)
14864 (when (looking-at org-complex-heading-regexp)
14865 (if (match-end 5)
14866 (progn
14867 (goto-char (match-beginning 5))
14868 (insert data)
14869 (delete-region (point) (point-at-eol))
14870 (org-set-tags nil 'align))
14871 (goto-char (point-at-eol))
14872 (insert " " data)
14873 (org-set-tags nil 'align)))
14874 (beginning-of-line 1)
14875 (when (looking-at ".*?\\([ \t]+\\)$")
14876 (delete-region (match-beginning 1) (match-end 1))))))
14878 (defun org-align-all-tags ()
14879 "Align the tags i all headings."
14880 (interactive)
14881 (save-excursion
14882 (or (ignore-errors (org-back-to-heading t))
14883 (outline-next-heading))
14884 (if (org-at-heading-p)
14885 (org-set-tags t)
14886 (message "No headings"))))
14888 (defvar org-indent-indentation-per-level)
14889 (defun org-set-tags (&optional arg just-align)
14890 "Set the tags for the current headline.
14891 With prefix ARG, realign all tags in headings in the current buffer.
14892 When JUST-ALIGN is non-nil, only align tags."
14893 (interactive "P")
14894 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14895 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14896 'region-start-level
14897 'region))
14898 org-loop-over-headlines-in-active-region)
14899 (org-map-entries
14900 ;; We don't use ARG and JUST-ALIGN here because these args
14901 ;; are not useful when looping over headlines.
14902 #'org-set-tags
14903 org-loop-over-headlines-in-active-region
14905 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14906 (let ((org-setting-tags t))
14907 (if arg
14908 (save-excursion
14909 (goto-char (point-min))
14910 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14911 (while (re-search-forward org-outline-regexp-bol nil t)
14912 (org-set-tags nil t)
14913 (end-of-line)))
14914 (message "All tags realigned to column %d" org-tags-column))
14915 (let* ((current (org-get-tags-string))
14916 (col (current-column))
14917 (tags
14918 (if just-align current
14919 ;; Get a new set of tags from the user.
14920 (save-excursion
14921 (let* ((table
14922 (setq
14923 org-last-tags-completion-table
14924 (append
14925 org-tag-persistent-alist
14926 (or org-tag-alist (org-get-buffer-tags))
14927 (and
14928 org-complete-tags-always-offer-all-agenda-tags
14929 (org-global-tags-completion-table
14930 (org-agenda-files))))))
14931 (current-tags (org-split-string current ":"))
14932 (inherited-tags
14933 (nreverse (nthcdr (length current-tags)
14934 (nreverse (org-get-tags-at))))))
14935 (replace-regexp-in-string
14936 "\\([-+&]+\\|,\\)"
14938 (if (or (eq t org-use-fast-tag-selection)
14939 (and org-use-fast-tag-selection
14940 (delq nil (mapcar #'cdr table))))
14941 (org-fast-tag-selection
14942 current-tags inherited-tags table
14943 (and org-fast-tag-selection-include-todo
14944 org-todo-key-alist))
14945 (let ((org-add-colon-after-tag-completion
14946 (< 1 (length table))))
14947 (org-trim
14948 (completing-read
14949 "Tags: "
14950 #'org-tags-completion-function
14951 nil nil current 'org-tags-history))))))))))
14953 (when org-tags-sort-function
14954 (setq tags
14955 (mapconcat
14956 #'identity
14957 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14958 org-tags-sort-function)
14959 ":")))
14961 (if (not (org-string-nw-p tags)) (setq tags "")
14962 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14963 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14965 ;; Insert new tags at the correct column
14966 (beginning-of-line)
14967 (let ((level (if (looking-at org-outline-regexp)
14968 (- (match-end 0) (point) 1)
14969 1)))
14970 (cond
14971 ((and (equal current "") (equal tags "")))
14972 ((re-search-forward
14973 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14974 (line-end-position)
14976 (if (equal tags "") (replace-match "" t t)
14977 (goto-char (match-beginning 0))
14978 (let* ((c0 (current-column))
14979 ;; Compute offset for the case of org-indent-mode
14980 ;; active.
14981 (di (if (org-bound-and-true-p org-indent-mode)
14982 (* (1- org-indent-indentation-per-level)
14983 (1- level))
14985 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14986 (tc (+ org-tags-column
14987 (if (> org-tags-column 0) (- di) di)))
14988 (c1 (max (1+ c0)
14989 (if (> tc 0) tc
14990 (- (- tc) (string-width tags)))))
14991 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14992 (replace-match rpl t t)
14993 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14994 (tabify p0 (point))))))
14995 (t (error "Tags alignment failed"))))
14996 (org-move-to-column col))
14997 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14999 (defun org-change-tag-in-region (beg end tag off)
15000 "Add or remove TAG for each entry in the region.
15001 This works in the agenda, and also in an org-mode buffer."
15002 (interactive
15003 (list (region-beginning) (region-end)
15004 (let ((org-last-tags-completion-table
15005 (if (derived-mode-p 'org-mode)
15006 (org-uniquify
15007 (delq nil (append (org-get-buffer-tags)
15008 (org-global-tags-completion-table))))
15009 (org-global-tags-completion-table))))
15010 (completing-read
15011 "Tag: " 'org-tags-completion-function nil nil nil
15012 'org-tags-history))
15013 (progn
15014 (message "[s]et or [r]emove? ")
15015 (equal (read-char-exclusive) ?r))))
15016 (when (fboundp 'deactivate-mark) (deactivate-mark))
15017 (let ((agendap (equal major-mode 'org-agenda-mode))
15018 l1 l2 m buf pos newhead (cnt 0))
15019 (goto-char end)
15020 (setq l2 (1- (org-current-line)))
15021 (goto-char beg)
15022 (setq l1 (org-current-line))
15023 (loop for l from l1 to l2 do
15024 (org-goto-line l)
15025 (setq m (get-text-property (point) 'org-hd-marker))
15026 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15027 (and agendap m))
15028 (setq buf (if agendap (marker-buffer m) (current-buffer))
15029 pos (if agendap m (point)))
15030 (with-current-buffer buf
15031 (save-excursion
15032 (save-restriction
15033 (goto-char pos)
15034 (setq cnt (1+ cnt))
15035 (org-toggle-tag tag (if off 'off 'on))
15036 (setq newhead (org-get-heading)))))
15037 (and agendap (org-agenda-change-all-lines newhead m))))
15038 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15040 (defun org-tags-completion-function (string _predicate &optional flag)
15041 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15042 (confirm (lambda (x) (stringp (car x)))))
15043 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15044 (setq s1 (match-string 1 string)
15045 s2 (match-string 2 string))
15046 (setq s1 "" s2 string))
15047 (cond
15048 ((eq flag nil)
15049 ;; try completion
15050 (setq rtn (try-completion s2 ctable confirm))
15051 (when (stringp rtn)
15052 (setq rtn
15053 (concat s1 s2 (substring rtn (length s2))
15054 (if (and org-add-colon-after-tag-completion
15055 (assoc rtn ctable))
15056 ":" ""))))
15057 rtn)
15058 ((eq flag t)
15059 ;; all-completions
15060 (all-completions s2 ctable confirm))
15061 ((eq flag 'lambda)
15062 ;; exact match?
15063 (assoc s2 ctable)))))
15065 (defun org-fast-tag-insert (kwd tags face &optional end)
15066 "Insert KDW, and the TAGS, the latter with face FACE.
15067 Also insert END."
15068 (insert (format "%-12s" (concat kwd ":"))
15069 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15070 (or end "")))
15072 (defun org-fast-tag-show-exit (flag)
15073 (save-excursion
15074 (org-goto-line 3)
15075 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15076 (replace-match ""))
15077 (when flag
15078 (end-of-line 1)
15079 (org-move-to-column (- (window-width) 19) t)
15080 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15082 (defun org-set-current-tags-overlay (current prefix)
15083 "Add an overlay to CURRENT tag with PREFIX."
15084 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15085 (if (featurep 'xemacs)
15086 (org-overlay-display org-tags-overlay (concat prefix s)
15087 'secondary-selection)
15088 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15089 (org-overlay-display org-tags-overlay (concat prefix s)))))
15091 (defvar org-last-tag-selection-key nil)
15092 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15093 "Fast tag selection with single keys.
15094 CURRENT is the current list of tags in the headline, INHERITED is the
15095 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15096 possibly with grouping information. TODO-TABLE is a similar table with
15097 TODO keywords, should these have keys assigned to them.
15098 If the keys are nil, a-z are automatically assigned.
15099 Returns the new tags string, or nil to not change the current settings."
15100 (let* ((fulltable (append table todo-table))
15101 (maxlen (apply 'max (mapcar
15102 (lambda (x)
15103 (if (stringp (car x)) (string-width (car x)) 0))
15104 fulltable)))
15105 (buf (current-buffer))
15106 (expert (eq org-fast-tag-selection-single-key 'expert))
15107 (buffer-tags nil)
15108 (fwidth (+ maxlen 3 1 3))
15109 (ncol (/ (- (window-width) 4) fwidth))
15110 (i-face 'org-done)
15111 (c-face 'org-todo)
15112 tg cnt e c char c1 c2 ntable tbl rtn
15113 ov-start ov-end ov-prefix
15114 (exit-after-next org-fast-tag-selection-single-key)
15115 (done-keywords org-done-keywords)
15116 groups ingroup intaggroup)
15117 (save-excursion
15118 (beginning-of-line 1)
15119 (if (looking-at
15120 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15121 (setq ov-start (match-beginning 1)
15122 ov-end (match-end 1)
15123 ov-prefix "")
15124 (setq ov-start (1- (point-at-eol))
15125 ov-end (1+ ov-start))
15126 (skip-chars-forward "^\n\r")
15127 (setq ov-prefix
15128 (concat
15129 (buffer-substring (1- (point)) (point))
15130 (if (> (current-column) org-tags-column)
15132 (make-string (- org-tags-column (current-column)) ?\ ))))))
15133 (move-overlay org-tags-overlay ov-start ov-end)
15134 (save-window-excursion
15135 (if expert
15136 (set-buffer (get-buffer-create " *Org tags*"))
15137 (delete-other-windows)
15138 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15139 (org-switch-to-buffer-other-window " *Org tags*"))
15140 (erase-buffer)
15141 (setq-local org-done-keywords done-keywords)
15142 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15143 (org-fast-tag-insert "Current" current c-face "\n\n")
15144 (org-fast-tag-show-exit exit-after-next)
15145 (org-set-current-tags-overlay current ov-prefix)
15146 (setq tbl fulltable char ?a cnt 0)
15147 (while (setq e (pop tbl))
15148 (cond
15149 ((eq (car e) :startgroup)
15150 (push '() groups) (setq ingroup t)
15151 (unless (zerop cnt)
15152 (setq cnt 0)
15153 (insert "\n"))
15154 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15155 ((eq (car e) :endgroup)
15156 (setq ingroup nil cnt 0)
15157 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15158 ((eq (car e) :startgrouptag)
15159 (setq intaggroup t)
15160 (unless (zerop cnt)
15161 (setq cnt 0)
15162 (insert "\n"))
15163 (insert "[ "))
15164 ((eq (car e) :endgrouptag)
15165 (setq intaggroup nil cnt 0)
15166 (insert "]\n"))
15167 ((equal e '(:newline))
15168 (unless (zerop cnt)
15169 (setq cnt 0)
15170 (insert "\n")
15171 (setq e (car tbl))
15172 (while (equal (car tbl) '(:newline))
15173 (insert "\n")
15174 (setq tbl (cdr tbl)))))
15175 ((equal e '(:grouptags)) (insert " : "))
15177 (setq tg (copy-sequence (car e)) c2 nil)
15178 (if (cdr e)
15179 (setq c (cdr e))
15180 ;; automatically assign a character.
15181 (setq c1 (string-to-char
15182 (downcase (substring
15183 tg (if (= (string-to-char tg) ?@) 1 0)))))
15184 (if (or (rassoc c1 ntable) (rassoc c1 table))
15185 (while (or (rassoc char ntable) (rassoc char table))
15186 (setq char (1+ char)))
15187 (setq c2 c1))
15188 (setq c (or c2 char)))
15189 (when ingroup (push tg (car groups)))
15190 (setq tg (org-add-props tg nil 'face
15191 (cond
15192 ((not (assoc tg table))
15193 (org-get-todo-face tg))
15194 ((member tg current) c-face)
15195 ((member tg inherited) i-face))))
15196 (when (equal (caar tbl) :grouptags)
15197 (org-add-props tg nil 'face 'org-tag-group))
15198 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15199 (insert "[" c "] " tg (make-string
15200 (- fwidth 4 (length tg)) ?\ ))
15201 (push (cons tg c) ntable)
15202 (when (= (incf cnt) ncol)
15203 (insert "\n")
15204 (when (or ingroup intaggroup) (insert " "))
15205 (setq cnt 0)))))
15206 (setq ntable (nreverse ntable))
15207 (insert "\n")
15208 (goto-char (point-min))
15209 (unless expert (org-fit-window-to-buffer))
15210 (setq rtn
15211 (catch 'exit
15212 (while t
15213 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15214 (if (not groups) "no " "")
15215 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15216 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15217 (setq org-last-tag-selection-key c)
15218 (cond
15219 ((= c ?\r) (throw 'exit t))
15220 ((= c ?!)
15221 (setq groups (not groups))
15222 (goto-char (point-min))
15223 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15224 ((= c ?\C-c)
15225 (if (not expert)
15226 (org-fast-tag-show-exit
15227 (setq exit-after-next (not exit-after-next)))
15228 (setq expert nil)
15229 (delete-other-windows)
15230 (set-window-buffer (split-window-vertically) " *Org tags*")
15231 (org-switch-to-buffer-other-window " *Org tags*")
15232 (org-fit-window-to-buffer)))
15233 ((or (= c ?\C-g)
15234 (and (= c ?q) (not (rassoc c ntable))))
15235 (org-detach-overlay org-tags-overlay)
15236 (setq quit-flag t))
15237 ((= c ?\ )
15238 (setq current nil)
15239 (when exit-after-next (setq exit-after-next 'now)))
15240 ((= c ?\t)
15241 (condition-case nil
15242 (setq tg (completing-read
15243 "Tag: "
15244 (or buffer-tags
15245 (with-current-buffer buf
15246 (setq buffer-tags
15247 (org-get-buffer-tags))))))
15248 (quit (setq tg "")))
15249 (when (string-match "\\S-" tg)
15250 (add-to-list 'buffer-tags (list tg))
15251 (if (member tg current)
15252 (setq current (delete tg current))
15253 (push tg current)))
15254 (when exit-after-next (setq exit-after-next 'now)))
15255 ((setq e (rassoc c todo-table) tg (car e))
15256 (with-current-buffer buf
15257 (save-excursion (org-todo tg)))
15258 (when exit-after-next (setq exit-after-next 'now)))
15259 ((setq e (rassoc c ntable) tg (car e))
15260 (if (member tg current)
15261 (setq current (delete tg current))
15262 (loop for g in groups do
15263 (when (member tg g)
15264 (dolist (x g) (setq current (delete x current)))))
15265 (push tg current))
15266 (when exit-after-next (setq exit-after-next 'now))))
15268 ;; Create a sorted list
15269 (setq current
15270 (sort current
15271 (lambda (a b)
15272 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15273 (when (eq exit-after-next 'now) (throw 'exit t))
15274 (goto-char (point-min))
15275 (beginning-of-line 2)
15276 (delete-region (point) (point-at-eol))
15277 (org-fast-tag-insert "Current" current c-face)
15278 (org-set-current-tags-overlay current ov-prefix)
15279 (while (re-search-forward
15280 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15281 (setq tg (match-string 1))
15282 (add-text-properties
15283 (match-beginning 1) (match-end 1)
15284 (list 'face
15285 (cond
15286 ((member tg current) c-face)
15287 ((member tg inherited) i-face)
15288 (t (get-text-property (match-beginning 1) 'face))))))
15289 (goto-char (point-min)))))
15290 (org-detach-overlay org-tags-overlay)
15291 (if rtn
15292 (mapconcat 'identity current ":")
15293 nil))))
15295 (defun org-get-tags-string ()
15296 "Get the TAGS string in the current headline."
15297 (unless (org-at-heading-p t)
15298 (user-error "Not on a heading"))
15299 (save-excursion
15300 (beginning-of-line 1)
15301 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15302 (org-match-string-no-properties 1)
15303 "")))
15305 (defun org-get-tags ()
15306 "Get the list of tags specified in the current headline."
15307 (org-split-string (org-get-tags-string) ":"))
15309 (defun org-get-buffer-tags ()
15310 "Get a table of all tags used in the buffer, for completion."
15311 (org-with-wide-buffer
15312 (goto-char (point-min))
15313 (let ((tag-re (concat org-outline-regexp-bol
15314 "\\(?:.*?[ \t]\\)?"
15315 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15316 tags)
15317 (while (re-search-forward tag-re nil t)
15318 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15319 (push tag tags)))
15320 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15322 ;;;; The mapping API
15324 (defun org-map-entries (func &optional match scope &rest skip)
15325 "Call FUNC at each headline selected by MATCH in SCOPE.
15327 FUNC is a function or a lisp form. The function will be called without
15328 arguments, with the cursor positioned at the beginning of the headline.
15329 The return values of all calls to the function will be collected and
15330 returned as a list.
15332 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15333 does not need to preserve point. After evaluation, the cursor will be
15334 moved to the end of the line (presumably of the headline of the
15335 processed entry) and search continues from there. Under some
15336 circumstances, this may not produce the wanted results. For example,
15337 if you have removed (e.g. archived) the current (sub)tree it could
15338 mean that the next entry will be skipped entirely. In such cases, you
15339 can specify the position from where search should continue by making
15340 FUNC set the variable `org-map-continue-from' to the desired buffer
15341 position.
15343 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15344 Only headlines that are matched by this query will be considered during
15345 the iteration. When MATCH is nil or t, all headlines will be
15346 visited by the iteration.
15348 SCOPE determines the scope of this command. It can be any of:
15350 nil The current buffer, respecting the restriction if any
15351 tree The subtree started with the entry at point
15352 region The entries within the active region, if any
15353 region-start-level
15354 The entries within the active region, but only those at
15355 the same level than the first one.
15356 file The current buffer, without restriction
15357 file-with-archives
15358 The current buffer, and any archives associated with it
15359 agenda All agenda files
15360 agenda-with-archives
15361 All agenda files with any archive files associated with them
15362 \(file1 file2 ...)
15363 If this is a list, all files in the list will be scanned
15365 The remaining args are treated as settings for the skipping facilities of
15366 the scanner. The following items can be given here:
15368 archive skip trees with the archive tag
15369 comment skip trees with the COMMENT keyword
15370 function or Emacs Lisp form:
15371 will be used as value for `org-agenda-skip-function', so
15372 whenever the function returns a position, FUNC will not be
15373 called for that entry and search will continue from the
15374 position returned
15376 If your function needs to retrieve the tags including inherited tags
15377 at the *current* entry, you can use the value of the variable
15378 `org-scanner-tags' which will be much faster than getting the value
15379 with `org-get-tags-at'. If your function gets properties with
15380 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15381 to t around the call to `org-entry-properties' to get the same speedup.
15382 Note that if your function moves around to retrieve tags and properties at
15383 a *different* entry, you cannot use these techniques."
15384 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15385 (not (org-region-active-p)))
15386 (let* ((org-agenda-archives-mode nil) ; just to make sure
15387 (org-agenda-skip-archived-trees (memq 'archive skip))
15388 (org-agenda-skip-comment-trees (memq 'comment skip))
15389 (org-agenda-skip-function
15390 (car (org-delete-all '(comment archive) skip)))
15391 (org-tags-match-list-sublevels t)
15392 (start-level (eq scope 'region-start-level))
15393 matcher res
15394 org-todo-keywords-for-agenda
15395 org-done-keywords-for-agenda
15396 org-todo-keyword-alist-for-agenda
15397 org-tag-alist-for-agenda
15398 org--matcher-tags-todo-only)
15400 (cond
15401 ((eq match t) (setq matcher t))
15402 ((eq match nil) (setq matcher t))
15403 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15405 (save-excursion
15406 (save-restriction
15407 (cond ((eq scope 'tree)
15408 (org-back-to-heading t)
15409 (org-narrow-to-subtree)
15410 (setq scope nil))
15411 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15412 (org-region-active-p))
15413 ;; If needed, set start-level to a string like "2"
15414 (when start-level
15415 (save-excursion
15416 (goto-char (region-beginning))
15417 (unless (org-at-heading-p) (outline-next-heading))
15418 (setq start-level (org-current-level))))
15419 (narrow-to-region (region-beginning)
15420 (save-excursion
15421 (goto-char (region-end))
15422 (unless (and (bolp) (org-at-heading-p))
15423 (outline-next-heading))
15424 (point)))
15425 (setq scope nil)))
15427 (if (not scope)
15428 (progn
15429 (org-agenda-prepare-buffers
15430 (and buffer-file-name (list buffer-file-name)))
15431 (setq res
15432 (org-scan-tags
15433 func matcher org--matcher-tags-todo-only start-level)))
15434 ;; Get the right scope
15435 (cond
15436 ((and scope (listp scope) (symbolp (car scope)))
15437 (setq scope (eval scope)))
15438 ((eq scope 'agenda)
15439 (setq scope (org-agenda-files t)))
15440 ((eq scope 'agenda-with-archives)
15441 (setq scope (org-agenda-files t))
15442 (setq scope (org-add-archive-files scope)))
15443 ((eq scope 'file)
15444 (setq scope (and buffer-file-name (list buffer-file-name))))
15445 ((eq scope 'file-with-archives)
15446 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15447 (org-agenda-prepare-buffers scope)
15448 (dolist (file scope)
15449 (with-current-buffer (org-find-base-buffer-visiting file)
15450 (save-excursion
15451 (save-restriction
15452 (widen)
15453 (goto-char (point-min))
15454 (setq res
15455 (append
15457 (org-scan-tags
15458 func matcher org--matcher-tags-todo-only))))))))))
15459 res)))
15461 ;;; Properties API
15463 (defconst org-special-properties
15464 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15465 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15466 "The special properties valid in Org mode.
15467 These are properties that are not defined in the property drawer,
15468 but in some other way.")
15470 (defconst org-default-properties
15471 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15472 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15473 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15474 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15475 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15476 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15477 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15478 "Some properties that are used by Org mode for various purposes.
15479 Being in this list makes sure that they are offered for completion.")
15481 (defun org--valid-property-p (property)
15482 "Non nil when string PROPERTY is a valid property name."
15483 (not
15484 (or (equal property "")
15485 (org-string-match-p "\\s-" property))))
15487 (defun org--update-property-plist (key val props)
15488 "Associate KEY to VAL in alist PROPS.
15489 Modifications are made by side-effect. Return new alist."
15490 (let* ((appending (string= (substring key -1) "+"))
15491 (key (if appending (substring key 0 -1) key))
15492 (old (assoc-string key props t)))
15493 (if (not old) (cons (cons key val) props)
15494 (setcdr old (if appending (concat (cdr old) " " val) val))
15495 props)))
15497 (defun org-get-property-block (&optional beg force)
15498 "Return the (beg . end) range of the body of the property drawer.
15499 BEG is the beginning of the current subtree, or of the part
15500 before the first headline. If it is not given, it will be found.
15501 If the drawer does not exist, create it if FORCE is non-nil, or
15502 return nil."
15503 (org-with-wide-buffer
15504 (when beg (goto-char beg))
15505 (unless (org-before-first-heading-p)
15506 (let ((beg (cond (beg)
15507 ((or (not (featurep 'org-inlinetask))
15508 (org-inlinetask-in-task-p))
15509 (org-back-to-heading t))
15510 (t (org-with-limited-levels (org-back-to-heading t))))))
15511 (forward-line)
15512 (when (org-looking-at-p org-planning-line-re) (forward-line))
15513 (cond ((looking-at org-property-drawer-re)
15514 (forward-line)
15515 (cons (point) (progn (goto-char (match-end 0))
15516 (line-beginning-position))))
15517 (force
15518 (goto-char beg)
15519 (org-insert-property-drawer)
15520 (let ((pos (save-excursion (search-forward ":END:")
15521 (line-beginning-position))))
15522 (cons pos pos))))))))
15524 (defun org-at-property-p ()
15525 "Non-nil when point is inside a property drawer.
15526 See `org-property-re' for match data, if applicable."
15527 (save-excursion
15528 (beginning-of-line)
15529 (and (looking-at org-property-re)
15530 (let ((property-drawer (save-match-data (org-get-property-block))))
15531 (and property-drawer
15532 (>= (point) (car property-drawer))
15533 (< (point) (cdr property-drawer)))))))
15535 (defun org-property-action ()
15536 "Do an action on properties."
15537 (interactive)
15538 (unless (org-at-property-p) (user-error "Not at a property"))
15539 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15540 (let ((c (read-char-exclusive)))
15541 (case c
15542 (?s (call-interactively #'org-set-property))
15543 (?d (call-interactively #'org-delete-property))
15544 (?D (call-interactively #'org-delete-property-globally))
15545 (?c (call-interactively #'org-compute-property-at-point))
15546 (otherwise (user-error "No such property action %c" c)))))
15548 (defun org-inc-effort ()
15549 "Increment the value of the effort property in the current entry."
15550 (interactive)
15551 (org-set-effort nil t))
15553 (defvar org-clock-effort) ; Defined in org-clock.el.
15554 (defvar org-clock-current-task) ; Defined in org-clock.el.
15555 (defun org-set-effort (&optional value increment)
15556 "Set the effort property of the current entry.
15557 With numerical prefix arg, use the nth allowed value, 0 stands for the
15558 10th allowed value.
15560 When INCREMENT is non-nil, set the property to the next allowed value."
15561 (interactive "P")
15562 (when (equal value 0) (setq value 10))
15563 (let* ((completion-ignore-case t)
15564 (prop org-effort-property)
15565 (cur (org-entry-get nil prop))
15566 (allowed (org-property-get-allowed-values nil prop 'table))
15567 (existing (mapcar 'list (org-property-values prop)))
15568 (heading (nth 4 (org-heading-components)))
15570 (val (cond
15571 ((stringp value) value)
15572 ((and allowed (integerp value))
15573 (or (car (nth (1- value) allowed))
15574 (car (org-last allowed))))
15575 ((and allowed increment)
15576 (or (caadr (member (list cur) allowed))
15577 (user-error "Allowed effort values are not set")))
15578 (allowed
15579 (message "Select 1-9,0, [RET%s]: %s"
15580 (if cur (concat "=" cur) "")
15581 (mapconcat 'car allowed " "))
15582 (setq rpl (read-char-exclusive))
15583 (if (equal rpl ?\r)
15585 (setq rpl (- rpl ?0))
15586 (when (equal rpl 0) (setq rpl 10))
15587 (if (and (> rpl 0) (<= rpl (length allowed)))
15588 (car (nth (1- rpl) allowed))
15589 (org-completing-read "Effort: " allowed nil))))
15591 (let (org-completion-use-ido org-completion-use-iswitchb)
15592 (org-completing-read
15593 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15594 (concat "[" cur "]") "")
15595 ": ")
15596 existing nil nil "" nil cur))))))
15597 (unless (equal (org-entry-get nil prop) val)
15598 (org-entry-put nil prop val))
15599 (org-refresh-property
15600 '((effort . identity)
15601 (effort-minutes . org-duration-string-to-minutes))
15602 val)
15603 (when (string= heading org-clock-current-task)
15604 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15605 (org-clock-update-mode-line))
15606 (message "%s is now %s" prop val)))
15608 (defun org-entry-properties (&optional pom which)
15609 "Get all properties of the current entry.
15611 When POM is a buffer position, get all properties from the entry
15612 there instead.
15614 This includes the TODO keyword, the tags, time strings for
15615 deadline, scheduled, and clocking, and any additional properties
15616 defined in the entry.
15618 If WHICH is nil or `all', get all properties. If WHICH is
15619 `special' or `standard', only get that subclass. If WHICH is
15620 a string, only get that property.
15622 Return value is an alist. Keys are properties, as upcased
15623 strings."
15624 (org-with-point-at pom
15625 (when (and (derived-mode-p 'org-mode)
15626 (ignore-errors (org-back-to-heading t)))
15627 (catch 'exit
15628 (let* ((beg (point))
15629 (specific (and (stringp which) (upcase which)))
15630 (which (cond ((not specific) which)
15631 ((member specific org-special-properties) 'special)
15632 (t 'standard)))
15633 props)
15634 ;; Get the special properties, like TODO and TAGS.
15635 (when (memq which '(nil all special))
15636 (when (or (not specific) (string= specific "CLOCKSUM"))
15637 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15638 (when clocksum
15639 (push (cons "CLOCKSUM"
15640 (org-columns-number-to-string
15641 (/ (float clocksum) 60.) 'add_times))
15642 props)))
15643 (when specific (throw 'exit props)))
15644 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15645 (let ((clocksumt (get-text-property (point)
15646 :org-clock-minutes-today)))
15647 (when clocksumt
15648 (push (cons "CLOCKSUM_T"
15649 (org-columns-number-to-string
15650 (/ (float clocksumt) 60.) 'add_times))
15651 props)))
15652 (when specific (throw 'exit props)))
15653 (when (or (not specific) (string= specific "ITEM"))
15654 (when (looking-at org-complex-heading-regexp)
15655 (push (cons "ITEM"
15656 (concat
15657 (org-match-string-no-properties 1)
15658 (let ((title (org-match-string-no-properties 4)))
15659 (when (org-string-nw-p title)
15660 (concat " " (org-remove-tabs title))))))
15661 props))
15662 (when specific (throw 'exit props)))
15663 (when (or (not specific) (string= specific "TODO"))
15664 (let ((case-fold-search nil))
15665 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15666 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15667 (when specific (throw 'exit props)))
15668 (when (or (not specific) (string= specific "PRIORITY"))
15669 (push (cons "PRIORITY"
15670 (if (looking-at org-priority-regexp)
15671 (org-match-string-no-properties 2)
15672 (char-to-string org-default-priority)))
15673 props)
15674 (when specific (throw 'exit props)))
15675 (when (or (not specific) (string= specific "FILE"))
15676 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15677 props)
15678 (when specific (throw 'exit props)))
15679 (when (or (not specific) (string= specific "TAGS"))
15680 (let ((value (org-string-nw-p (org-get-tags-string))))
15681 (when value (push (cons "TAGS" value) props)))
15682 (when specific (throw 'exit props)))
15683 (when (or (not specific) (string= specific "ALLTAGS"))
15684 (let ((value (org-get-tags-at)))
15685 (when value
15686 (push (cons "ALLTAGS"
15687 (format ":%s:" (mapconcat #'identity value ":")))
15688 props)))
15689 (when specific (throw 'exit props)))
15690 (when (or (not specific) (string= specific "BLOCKED"))
15691 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15692 (when specific (throw 'exit props)))
15693 (when (or (not specific)
15694 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15695 (forward-line)
15696 (when (org-looking-at-p org-planning-line-re)
15697 (end-of-line)
15698 (let ((bol (line-beginning-position))
15699 ;; Backward compatibility: time keywords used to
15700 ;; be configurable (before 8.3). Make sure we
15701 ;; get the correct keyword.
15702 (key-assoc `(("CLOSED" . ,org-closed-string)
15703 ("DEADLINE" . ,org-deadline-string)
15704 ("SCHEDULED" . ,org-scheduled-string))))
15705 (dolist (pair (if specific (list (assoc specific key-assoc))
15706 key-assoc))
15707 (save-excursion
15708 (when (search-backward (cdr pair) bol t)
15709 (goto-char (match-end 0))
15710 (skip-chars-forward " \t")
15711 (and (looking-at org-ts-regexp-both)
15712 (push (cons (car pair)
15713 (org-match-string-no-properties 0))
15714 props)))))))
15715 (when specific (throw 'exit props)))
15716 (when (or (not specific)
15717 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15718 (let ((find-ts
15719 (lambda (end ts)
15720 ;; Fix next time-stamp before END. TS is the
15721 ;; list of time-stamps found so far.
15722 (let ((ts ts)
15723 (regexp (cond
15724 ((string= specific "TIMESTAMP")
15725 org-ts-regexp)
15726 ((string= specific "TIMESTAMP_IA")
15727 org-ts-regexp-inactive)
15728 ((assoc "TIMESTAMP_IA" ts)
15729 org-ts-regexp)
15730 ((assoc "TIMESTAMP" ts)
15731 org-ts-regexp-inactive)
15732 (t org-ts-regexp-both))))
15733 (catch 'next
15734 (while (re-search-forward regexp end t)
15735 (backward-char)
15736 (let ((object (org-element-context)))
15737 ;; Accept to match timestamps in node
15738 ;; properties, too.
15739 (when (memq (org-element-type object)
15740 '(node-property timestamp))
15741 (let ((type
15742 (org-element-property :type object)))
15743 (cond
15744 ((and (memq type '(active active-range))
15745 (not (equal specific "TIMESTAMP_IA")))
15746 (unless (assoc "TIMESTAMP" ts)
15747 (push (cons "TIMESTAMP"
15748 (org-element-property
15749 :raw-value object))
15751 (when specific (throw 'exit ts))))
15752 ((and (memq type '(inactive inactive-range))
15753 (not (string= specific "TIMESTAMP")))
15754 (unless (assoc "TIMESTAMP_IA" ts)
15755 (push (cons "TIMESTAMP_IA"
15756 (org-element-property
15757 :raw-value object))
15759 (when specific (throw 'exit ts))))))
15760 ;; Both timestamp types are found,
15761 ;; move to next part.
15762 (when (= (length ts) 2) (throw 'next ts)))))
15763 ts)))))
15764 (goto-char beg)
15765 ;; First look for timestamps within headline.
15766 (let ((ts (funcall find-ts (line-end-position) nil)))
15767 (if (= (length ts) 2) (setq props (nconc ts props))
15768 (forward-line)
15769 ;; Then find timestamps in the section, skipping
15770 ;; planning line.
15771 (when (org-looking-at-p org-planning-line-re)
15772 (forward-line))
15773 (let ((end (save-excursion (outline-next-heading))))
15774 (setq props (nconc (funcall find-ts end ts) props))))))))
15775 ;; Get the standard properties, like :PROP:.
15776 (when (memq which '(nil all standard))
15777 ;; If we are looking after a specific property, delegate
15778 ;; to `org-entry-get', which is faster. However, make an
15779 ;; exception for "CATEGORY", since it can be also set
15780 ;; through keywords (i.e. #+CATEGORY).
15781 (if (and specific (not (equal specific "CATEGORY")))
15782 (let ((value (org-entry-get beg specific nil t)))
15783 (throw 'exit (and value (list (cons specific value)))))
15784 (let ((range (org-get-property-block beg)))
15785 (when range
15786 (let ((end (cdr range)) seen-base)
15787 (goto-char (car range))
15788 ;; Unlike to `org--update-property-plist', we
15789 ;; handle the case where base values is found
15790 ;; after its extension. We also forbid standard
15791 ;; properties to be named as special properties.
15792 (while (re-search-forward org-property-re end t)
15793 (let* ((key (upcase (org-match-string-no-properties 2)))
15794 (extendp (org-string-match-p "\\+\\'" key))
15795 (key-base (if extendp (substring key 0 -1) key))
15796 (value (org-match-string-no-properties 3)))
15797 (cond
15798 ((member-ignore-case key-base org-special-properties))
15799 (extendp
15800 (setq props
15801 (org--update-property-plist key value props)))
15802 ((member key seen-base))
15803 (t (push key seen-base)
15804 (let ((p (assoc-string key props t)))
15805 (if p (setcdr p (concat value " " (cdr p)))
15806 (push (cons key value) props))))))))))))
15807 (unless (assoc "CATEGORY" props)
15808 (push (cons "CATEGORY" (org-get-category beg)) props)
15809 (when (string= specific "CATEGORY") (throw 'exit props)))
15810 ;; Return value.
15811 props)))))
15813 (defun org-property--local-values (property literal-nil)
15814 "Return value for PROPERTY in current entry.
15815 Value is a list whose care is the base value for PROPERTY and cdr
15816 a list of accumulated values. Return nil if neither is found in
15817 the entry. Also return nil when PROPERTY is set to \"nil\",
15818 unless LITERAL-NIL is non-nil."
15819 (let ((range (org-get-property-block)))
15820 (when range
15821 (goto-char (car range))
15822 (let* ((case-fold-search t)
15823 (end (cdr range))
15824 (value
15825 ;; Base value.
15826 (save-excursion
15827 (let ((v (and (re-search-forward
15828 (org-re-property property nil t) end t)
15829 (org-match-string-no-properties 3))))
15830 (list (if literal-nil v (org-not-nil v)))))))
15831 ;; Find additional values.
15832 (let* ((property+ (org-re-property (concat property "+") nil t)))
15833 (while (re-search-forward property+ end t)
15834 (push (org-match-string-no-properties 3) value)))
15835 ;; Return final values.
15836 (and (not (equal value '(nil))) (nreverse value))))))
15838 (defun org-entry-get (pom property &optional inherit literal-nil)
15839 "Get value of PROPERTY for entry or content at point-or-marker POM.
15841 If INHERIT is non-nil and the entry does not have the property,
15842 then also check higher levels of the hierarchy. If INHERIT is
15843 the symbol `selective', use inheritance only if the setting in
15844 `org-use-property-inheritance' selects PROPERTY for inheritance.
15846 If the property is present but empty, the return value is the
15847 empty string. If the property is not present at all, nil is
15848 returned. In any other case, return the value as a string.
15849 Search is case-insensitive.
15851 If LITERAL-NIL is set, return the string value \"nil\" as
15852 a string, do not interpret it as the list atom nil. This is used
15853 for inheritance when a \"nil\" value can supersede a non-nil
15854 value higher up the hierarchy."
15855 (org-with-point-at pom
15856 (cond
15857 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15858 ;; We need a special property. Use `org-entry-properties' to
15859 ;; retrieve it, but specify the wanted property.
15860 (cdr (assoc-string property (org-entry-properties nil property))))
15861 ((and inherit
15862 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15863 (org-entry-get-with-inheritance property literal-nil))
15865 (let* ((local (org-property--local-values property literal-nil))
15866 (value (and local (mapconcat #'identity (delq nil local) " "))))
15867 (if literal-nil value (org-not-nil value)))))))
15869 (defun org-property-or-variable-value (var &optional inherit)
15870 "Check if there is a property fixing the value of VAR.
15871 If yes, return this value. If not, return the current value of the variable."
15872 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15873 (if (and prop (stringp prop) (string-match "\\S-" prop))
15874 (read prop)
15875 (symbol-value var))))
15877 (defun org-entry-delete (pom property)
15878 "Delete PROPERTY from entry at point-or-marker POM.
15879 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15880 non-nil when a property was removed."
15881 (unless (member property org-special-properties)
15882 (org-with-point-at pom
15883 (let ((range (org-get-property-block)))
15884 (when range
15885 (let* ((begin (car range))
15886 (origin (cdr range))
15887 (end (copy-marker origin))
15888 (re (org-re-property
15889 (concat (regexp-quote property) "\\+?") t t)))
15890 (goto-char begin)
15891 (while (re-search-forward re end t)
15892 (delete-region (match-beginning 0) (line-beginning-position 2)))
15893 ;; If drawer is empty, remove it altogether.
15894 (when (= begin end)
15895 (delete-region (line-beginning-position 0)
15896 (line-beginning-position 2)))
15897 ;; Return non-nil if some property was removed.
15898 (prog1 (/= end origin) (set-marker end nil))))))))
15900 ;; Multi-values properties are properties that contain multiple values
15901 ;; These values are assumed to be single words, separated by whitespace.
15902 (defun org-entry-add-to-multivalued-property (pom property value)
15903 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15904 (let* ((old (org-entry-get pom property))
15905 (values (and old (org-split-string old "[ \t]"))))
15906 (setq value (org-entry-protect-space value))
15907 (unless (member value values)
15908 (setq values (append values (list value)))
15909 (org-entry-put pom property
15910 (mapconcat 'identity values " ")))))
15912 (defun org-entry-remove-from-multivalued-property (pom property value)
15913 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15914 (let* ((old (org-entry-get pom property))
15915 (values (and old (org-split-string old "[ \t]"))))
15916 (setq value (org-entry-protect-space value))
15917 (when (member value values)
15918 (setq values (delete value values))
15919 (org-entry-put pom property
15920 (mapconcat 'identity values " ")))))
15922 (defun org-entry-member-in-multivalued-property (pom property value)
15923 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15924 (let* ((old (org-entry-get pom property))
15925 (values (and old (org-split-string old "[ \t]"))))
15926 (setq value (org-entry-protect-space value))
15927 (member value values)))
15929 (defun org-entry-get-multivalued-property (pom property)
15930 "Return a list of values in a multivalued property."
15931 (let* ((value (org-entry-get pom property))
15932 (values (and value (org-split-string value "[ \t]"))))
15933 (mapcar 'org-entry-restore-space values)))
15935 (defun org-entry-put-multivalued-property (pom property &rest values)
15936 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15937 VALUES should be a list of strings. Spaces will be protected."
15938 (org-entry-put pom property
15939 (mapconcat 'org-entry-protect-space values " "))
15940 (let* ((value (org-entry-get pom property))
15941 (values (and value (org-split-string value "[ \t]"))))
15942 (mapcar 'org-entry-restore-space values)))
15944 (defun org-entry-protect-space (s)
15945 "Protect spaces and newline in string S."
15946 (while (string-match " " s)
15947 (setq s (replace-match "%20" t t s)))
15948 (while (string-match "\n" s)
15949 (setq s (replace-match "%0A" t t s)))
15952 (defun org-entry-restore-space (s)
15953 "Restore spaces and newline in string S."
15954 (while (string-match "%20" s)
15955 (setq s (replace-match " " t t s)))
15956 (while (string-match "%0A" s)
15957 (setq s (replace-match "\n" t t s)))
15960 (defvar org-entry-property-inherited-from (make-marker)
15961 "Marker pointing to the entry from where a property was inherited.
15962 Each call to `org-entry-get-with-inheritance' will set this marker to the
15963 location of the entry where the inheritance search matched. If there was
15964 no match, the marker will point nowhere.
15965 Note that also `org-entry-get' calls this function, if the INHERIT flag
15966 is set.")
15968 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15969 "Get PROPERTY of entry or content at point, search higher levels if needed.
15970 The search will stop at the first ancestor which has the property defined.
15971 If the value found is \"nil\", return nil to show that the property
15972 should be considered as undefined (this is the meaning of nil here).
15973 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15974 (move-marker org-entry-property-inherited-from nil)
15975 (org-with-wide-buffer
15976 (let (value)
15977 (catch 'exit
15978 (while t
15979 (let ((v (org-property--local-values property literal-nil)))
15980 (when v
15981 (setq value
15982 (concat (mapconcat #'identity (delq nil v) " ")
15983 (and value " ")
15984 value)))
15985 (cond
15986 ((car v)
15987 (org-back-to-heading t)
15988 (move-marker org-entry-property-inherited-from (point))
15989 (throw 'exit nil))
15990 ((org-up-heading-safe))
15992 (let ((global
15993 (cdr (or (assoc-string property org-file-properties t)
15994 (assoc-string property org-global-properties t)
15995 (assoc-string property org-global-properties-fixed t)))))
15996 (cond ((not global))
15997 (value (setq value (concat global " " value)))
15998 (t (setq value global))))
15999 (throw 'exit nil))))))
16000 (if literal-nil value (org-not-nil value)))))
16002 (defvar org-property-changed-functions nil
16003 "Hook called when the value of a property has changed.
16004 Each hook function should accept two arguments, the name of the property
16005 and the new value.")
16007 (defun org-entry-put (pom property value)
16008 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16010 If the value is nil, it is converted to the empty string. If it
16011 is not a string, an error is raised. Also raise an error on
16012 invalid property names.
16014 PROPERTY can be any regular property (see
16015 `org-special-properties'). It can also be \"TODO\",
16016 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16018 For the last two properties, VALUE may have any of the special
16019 values \"earlier\" and \"later\". The function then increases or
16020 decreases scheduled or deadline date by one day."
16021 (cond ((null value) (setq value ""))
16022 ((not (stringp value)) (error "Properties values should be strings"))
16023 ((not (org--valid-property-p property))
16024 (user-error "Invalid property name: \"%s\"" property)))
16025 (org-with-point-at pom
16026 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16027 (org-back-to-heading t)
16028 (org-with-limited-levels (org-back-to-heading t)))
16029 (let ((beg (point)))
16030 (cond
16031 ((equal property "TODO")
16032 (cond ((not (org-string-nw-p value)) (setq value 'none))
16033 ((not (member value org-todo-keywords-1))
16034 (user-error "\"%s\" is not a valid TODO state" value)))
16035 (org-todo value)
16036 (org-set-tags nil 'align))
16037 ((equal property "PRIORITY")
16038 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16039 (org-set-tags nil 'align))
16040 ((equal property "SCHEDULED")
16041 (forward-line)
16042 (if (and (org-looking-at-p org-planning-line-re)
16043 (re-search-forward
16044 org-scheduled-time-regexp (line-end-position) t))
16045 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16046 ((string= value "later") (org-timestamp-change 1 'day))
16047 ((string= value "") (org-schedule '(4)))
16048 (t (org-schedule nil value)))
16049 (if (member value '("earlier" "later" ""))
16050 (call-interactively #'org-schedule)
16051 (org-schedule nil value))))
16052 ((equal property "DEADLINE")
16053 (forward-line)
16054 (if (and (org-looking-at-p org-planning-line-re)
16055 (re-search-forward
16056 org-deadline-time-regexp (line-end-position) t))
16057 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16058 ((string= value "later") (org-timestamp-change 1 'day))
16059 ((string= value "") (org-deadline '(4)))
16060 (t (org-deadline nil value)))
16061 (if (member value '("earlier" "later" ""))
16062 (call-interactively #'org-deadline)
16063 (org-deadline nil value))))
16064 ((member property org-special-properties)
16065 (error "The %s property cannot be set with `org-entry-put'" property))
16067 (let* ((range (org-get-property-block beg 'force))
16068 (end (cdr range))
16069 (case-fold-search t))
16070 (goto-char (car range))
16071 (if (re-search-forward (org-re-property property nil t) end t)
16072 (progn (delete-region (match-beginning 0) (match-end 0))
16073 (goto-char (match-beginning 0)))
16074 (goto-char end)
16075 (insert "\n")
16076 (backward-char))
16077 (insert ":" property ":")
16078 (when value (insert " " value))
16079 (org-indent-line)))))
16080 (run-hook-with-args 'org-property-changed-functions property value)))
16082 (defun org-buffer-property-keys
16083 (&optional specials defaults columns ignore-malformed)
16084 "Get all property keys in the current buffer.
16086 When SPECIALS is non-nil, also list the special properties that
16087 reflect things like tags and TODO state.
16089 When DEFAULTS is non-nil, also include properties that has
16090 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16091 DESCRIPTION, LOCATION, and LOGGING and others.
16093 When COLUMNS in non-nil, also include property names given in
16094 COLUMN formats in the current buffer.
16096 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16097 automatically performed, such drawers will be silently ignored."
16098 (let ((case-fold-search t)
16099 (props (append
16100 (and specials org-special-properties)
16101 (and defaults (cons org-effort-property org-default-properties))
16102 nil)))
16103 (org-with-wide-buffer
16104 (goto-char (point-min))
16105 (while (re-search-forward org-property-start-re nil t)
16106 (let ((range (org-get-property-block)))
16107 (catch 'skip
16108 (unless range
16109 (when (and (not ignore-malformed)
16110 (not (org-before-first-heading-p))
16111 (y-or-n-p (format "Malformed drawer at %d, repair?"
16112 (line-beginning-position))))
16113 (org-get-property-block nil t))
16114 (throw 'skip nil))
16115 (goto-char (car range))
16116 (let ((begin (car range))
16117 (end (cdr range)))
16118 ;; Make sure that found property block is not located
16119 ;; before current point, as it would generate an infloop.
16120 ;; It can happen, for example, in the following
16121 ;; situation:
16123 ;; * Headline
16124 ;; :PROPERTIES:
16125 ;; ...
16126 ;; :END:
16127 ;; *************** Inlinetask
16128 ;; #+BEGIN_EXAMPLE
16129 ;; :PROPERTIES:
16130 ;; #+END_EXAMPLE
16132 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16133 (while (< (point) end)
16134 (let ((p (progn (looking-at org-property-re)
16135 (org-match-string-no-properties 2))))
16136 ;; Only add true property name, not extension symbol.
16137 (push (if (not (org-string-match-p "\\+\\'" p)) p
16138 (substring p 0 -1))
16139 props))
16140 (forward-line))))
16141 (outline-next-heading)))
16142 (when columns
16143 (goto-char (point-min))
16144 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16145 (let ((element (org-element-at-point)))
16146 (when (memq (org-element-type element) '(keyword node-property))
16147 (let ((value (org-element-property :value element))
16148 (start 0))
16149 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16150 (setq start (match-end 0))
16151 (let ((p (org-match-string-no-properties 1 value)))
16152 (unless (member-ignore-case p org-special-properties)
16153 (push p props))))))))))
16154 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16156 (defun org-property-values (key)
16157 "List all non-nil values of property KEY in current buffer."
16158 (org-with-wide-buffer
16159 (goto-char (point-min))
16160 (let ((case-fold-search t)
16161 (re (org-re-property key))
16162 values)
16163 (while (re-search-forward re nil t)
16164 (push (org-entry-get (point) key) values))
16165 (delete-dups values))))
16167 (defun org-insert-property-drawer ()
16168 "Insert a property drawer into the current entry."
16169 (org-with-wide-buffer
16170 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16171 (org-back-to-heading t)
16172 (org-with-limited-levels (org-back-to-heading t)))
16173 (forward-line)
16174 (when (org-looking-at-p org-planning-line-re) (forward-line))
16175 (unless (org-looking-at-p org-property-drawer-re)
16176 ;; Make sure we start editing a line from current entry, not from
16177 ;; next one. It prevents extending text properties or overlays
16178 ;; belonging to the latter.
16179 (when (bolp) (backward-char))
16180 (let ((begin (1+ (point)))
16181 (inhibit-read-only t))
16182 (insert "\n:PROPERTIES:\n:END:")
16183 (when (eobp) (insert "\n"))
16184 (org-indent-region begin (point))))))
16186 (defun org-insert-drawer (&optional arg drawer)
16187 "Insert a drawer at point.
16189 When optional argument ARG is non-nil, insert a property drawer.
16191 Optional argument DRAWER, when non-nil, is a string representing
16192 drawer's name. Otherwise, the user is prompted for a name.
16194 If a region is active, insert the drawer around that region
16195 instead.
16197 Point is left between drawer's boundaries."
16198 (interactive "P")
16199 (let* ((drawer (if arg "PROPERTIES"
16200 (or drawer (read-from-minibuffer "Drawer: ")))))
16201 (cond
16202 ;; With C-u, fall back on `org-insert-property-drawer'
16203 (arg (org-insert-property-drawer))
16204 ;; Check validity of suggested drawer's name.
16205 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16206 (user-error "Invalid drawer name"))
16207 ;; With an active region, insert a drawer at point.
16208 ((not (org-region-active-p))
16209 (progn
16210 (unless (bolp) (insert "\n"))
16211 (insert (format ":%s:\n\n:END:\n" drawer))
16212 (forward-line -2)))
16213 ;; Otherwise, insert the drawer at point
16215 (let ((rbeg (region-beginning))
16216 (rend (copy-marker (region-end))))
16217 (unwind-protect
16218 (progn
16219 (goto-char rbeg)
16220 (beginning-of-line)
16221 (when (save-excursion
16222 (re-search-forward org-outline-regexp-bol rend t))
16223 (user-error "Drawers cannot contain headlines"))
16224 ;; Position point at the beginning of the first
16225 ;; non-blank line in region. Insert drawer's opening
16226 ;; there, then indent it.
16227 (org-skip-whitespace)
16228 (beginning-of-line)
16229 (insert ":" drawer ":\n")
16230 (forward-line -1)
16231 (indent-for-tab-command)
16232 ;; Move point to the beginning of the first blank line
16233 ;; after the last non-blank line in region. Insert
16234 ;; drawer's closing, then indent it.
16235 (goto-char rend)
16236 (skip-chars-backward " \r\t\n")
16237 (insert "\n:END:")
16238 (deactivate-mark t)
16239 (indent-for-tab-command)
16240 (unless (eolp) (insert "\n")))
16241 ;; Clear marker, whatever the outcome of insertion is.
16242 (set-marker rend nil)))))))
16244 (defvar org-property-set-functions-alist nil
16245 "Property set function alist.
16246 Each entry should have the following format:
16248 (PROPERTY . READ-FUNCTION)
16250 The read function will be called with the same argument as
16251 `org-completing-read'.")
16253 (defun org-set-property-function (property)
16254 "Get the function that should be used to set PROPERTY.
16255 This is computed according to `org-property-set-functions-alist'."
16256 (or (cdr (assoc property org-property-set-functions-alist))
16257 'org-completing-read))
16259 (defun org-read-property-value (property)
16260 "Read PROPERTY value from user."
16261 (let* ((completion-ignore-case t)
16262 (allowed (org-property-get-allowed-values nil property 'table))
16263 (cur (org-entry-get nil property))
16264 (prompt (concat property " value"
16265 (if (and cur (string-match "\\S-" cur))
16266 (concat " [" cur "]") "") ": "))
16267 (set-function (org-set-property-function property))
16268 (val (if allowed
16269 (funcall set-function prompt allowed nil
16270 (not (get-text-property 0 'org-unrestricted
16271 (caar allowed))))
16272 (let (org-completion-use-ido org-completion-use-iswitchb)
16273 (funcall set-function prompt
16274 (mapcar 'list (org-property-values property))
16275 nil nil "" nil cur)))))
16276 (org-trim val)))
16278 (defvar org-last-set-property nil)
16279 (defvar org-last-set-property-value nil)
16280 (defun org-read-property-name ()
16281 "Read a property name."
16282 (let ((completion-ignore-case t)
16283 (default-prop (or (and (org-at-property-p)
16284 (org-match-string-no-properties 2))
16285 org-last-set-property)))
16286 (org-completing-read
16287 (concat "Property"
16288 (if default-prop (concat " [" default-prop "]") "")
16289 ": ")
16290 (mapcar #'list (org-buffer-property-keys nil t t))
16291 nil nil nil nil default-prop)))
16293 (defun org-set-property-and-value (use-last)
16294 "Allow to set [PROPERTY]: [value] direction from prompt.
16295 When use-default, don't even ask, just use the last
16296 \"[PROPERTY]: [value]\" string from the history."
16297 (interactive "P")
16298 (let* ((completion-ignore-case t)
16299 (pv (or (and use-last org-last-set-property-value)
16300 (org-completing-read
16301 "Enter a \"[Property]: [value]\" pair: "
16302 nil nil nil nil nil
16303 org-last-set-property-value)))
16304 prop val)
16305 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16306 (setq prop (match-string 1 pv)
16307 val (match-string 2 pv))
16308 (org-set-property prop val))))
16310 (defun org-set-property (property value)
16311 "In the current entry, set PROPERTY to VALUE.
16313 When called interactively, this will prompt for a property name, offering
16314 completion on existing and default properties. And then it will prompt
16315 for a value, offering completion either on allowed values (via an inherited
16316 xxx_ALL property) or on existing values in other instances of this property
16317 in the current file.
16319 Throw an error when trying to set a property with an invalid name."
16320 (interactive (list nil nil))
16321 (let ((property (or property (org-read-property-name))))
16322 ;; `org-entry-put' also makes the following check, but this one
16323 ;; avoids polluting `org-last-set-property' and
16324 ;; `org-last-set-property-value' needlessly.
16325 (unless (org--valid-property-p property)
16326 (user-error "Invalid property name: \"%s\"" property))
16327 (let ((value (or value (org-read-property-value property)))
16328 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16329 (setq org-last-set-property property)
16330 (setq org-last-set-property-value (concat property ": " value))
16331 ;; Possibly postprocess the inserted value:
16332 (when fn (setq value (funcall fn value)))
16333 (unless (equal (org-entry-get nil property) value)
16334 (org-entry-put nil property value)))))
16336 (defun org-find-property (property &optional value)
16337 "Find first entry in buffer that sets PROPERTY.
16339 When optional argument VALUE is non-nil, only consider an entry
16340 if it contains PROPERTY set to this value. If PROPERTY should be
16341 explicitly set to nil, use string \"nil\" for VALUE.
16343 Return position where the entry begins, or nil if there is no
16344 such entry. If narrowing is in effect, only search the visible
16345 part of the buffer."
16346 (save-excursion
16347 (goto-char (point-min))
16348 (let ((case-fold-search t)
16349 (re (org-re-property property nil (not value) value)))
16350 (catch 'exit
16351 (while (re-search-forward re nil t)
16352 (when (if value (org-at-property-p)
16353 (org-entry-get (point) property nil t))
16354 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16356 (defun org-delete-property (property)
16357 "In the current entry, delete PROPERTY."
16358 (interactive
16359 (let* ((completion-ignore-case t)
16360 (cat (org-entry-get (point) "CATEGORY"))
16361 (props0 (org-entry-properties nil 'standard))
16362 (props (if cat props0
16363 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16364 (prop (if (< 1 (length props))
16365 (completing-read "Property: " props nil t)
16366 (caar props))))
16367 (list prop)))
16368 (if (not property)
16369 (message "No property to delete in this entry")
16370 (org-entry-delete nil property)
16371 (message "Property \"%s\" deleted" property)))
16373 (defun org-delete-property-globally (property)
16374 "Remove PROPERTY globally, from all entries.
16375 This function ignores narrowing, if any."
16376 (interactive
16377 (let* ((completion-ignore-case t)
16378 (prop (completing-read
16379 "Globally remove property: "
16380 (mapcar #'list (org-buffer-property-keys)))))
16381 (list prop)))
16382 (org-with-wide-buffer
16383 (goto-char (point-min))
16384 (let ((count 0)
16385 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16386 (while (re-search-forward re nil t)
16387 (when (org-entry-delete (point) property) (incf count)))
16388 (message "Property \"%s\" removed from %d entries" property count))))
16390 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16392 (defun org-compute-property-at-point ()
16393 "Compute the property at point.
16394 This looks for an enclosing column format, extracts the operator and
16395 then applies it to the property in the column format's scope."
16396 (interactive)
16397 (unless (org-at-property-p)
16398 (user-error "Not at a property"))
16399 (let ((prop (org-match-string-no-properties 2)))
16400 (org-columns-get-format-and-top-level)
16401 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16402 (user-error "No operator defined for property %s" prop))
16403 (org-columns-compute prop)))
16405 (defvar org-property-allowed-value-functions nil
16406 "Hook for functions supplying allowed values for a specific property.
16407 The functions must take a single argument, the name of the property, and
16408 return a flat list of allowed values. If \":ETC\" is one of
16409 the values, this means that these values are intended as defaults for
16410 completion, but that other values should be allowed too.
16411 The functions must return nil if they are not responsible for this
16412 property.")
16414 (defun org-property-get-allowed-values (pom property &optional table)
16415 "Get allowed values for the property PROPERTY.
16416 When TABLE is non-nil, return an alist that can directly be used for
16417 completion."
16418 (let (vals)
16419 (cond
16420 ((equal property "TODO")
16421 (setq vals (org-with-point-at pom
16422 (append org-todo-keywords-1 '("")))))
16423 ((equal property "PRIORITY")
16424 (let ((n org-lowest-priority))
16425 (while (>= n org-highest-priority)
16426 (push (char-to-string n) vals)
16427 (setq n (1- n)))))
16428 ((equal property "CATEGORY"))
16429 ((member property org-special-properties))
16430 ((setq vals (run-hook-with-args-until-success
16431 'org-property-allowed-value-functions property)))
16433 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16434 (when (and vals (string-match "\\S-" vals))
16435 (setq vals (car (read-from-string (concat "(" vals ")"))))
16436 (setq vals (mapcar (lambda (x)
16437 (cond ((stringp x) x)
16438 ((numberp x) (number-to-string x))
16439 ((symbolp x) (symbol-name x))
16440 (t "???")))
16441 vals)))))
16442 (when (member ":ETC" vals)
16443 (setq vals (remove ":ETC" vals))
16444 (org-add-props (car vals) '(org-unrestricted t)))
16445 (if table (mapcar 'list vals) vals)))
16447 (defun org-property-previous-allowed-value (&optional _previous)
16448 "Switch to the next allowed value for this property."
16449 (interactive)
16450 (org-property-next-allowed-value t))
16452 (defun org-property-next-allowed-value (&optional previous)
16453 "Switch to the next allowed value for this property."
16454 (interactive)
16455 (unless (org-at-property-p)
16456 (user-error "Not at a property"))
16457 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16458 (key (match-string 2))
16459 (value (match-string 3))
16460 (allowed (or (org-property-get-allowed-values (point) key)
16461 (and (member value '("[ ]" "[-]" "[X]"))
16462 '("[ ]" "[X]"))))
16463 (heading (save-match-data (nth 4 (org-heading-components))))
16464 nval)
16465 (unless allowed
16466 (user-error "Allowed values for this property have not been defined"))
16467 (when previous (setq allowed (reverse allowed)))
16468 (when (member value allowed)
16469 (setq nval (car (cdr (member value allowed)))))
16470 (setq nval (or nval (car allowed)))
16471 (when (equal nval value)
16472 (user-error "Only one allowed value for this property"))
16473 (org-at-property-p)
16474 (replace-match (concat " :" key ": " nval) t t)
16475 (org-indent-line)
16476 (beginning-of-line 1)
16477 (skip-chars-forward " \t")
16478 (when (equal prop org-effort-property)
16479 (org-refresh-property
16480 '((effort . identity)
16481 (effort-minutes . org-duration-string-to-minutes))
16482 nval)
16483 (when (string= org-clock-current-task heading)
16484 (setq org-clock-effort nval)
16485 (org-clock-update-mode-line)))
16486 (run-hook-with-args 'org-property-changed-functions key nval)))
16488 (defun org-find-olp (path &optional this-buffer)
16489 "Return a marker pointing to the entry at outline path OLP.
16490 If anything goes wrong, throw an error.
16491 You can wrap this call to catch the error like this:
16493 \(condition-case msg
16494 \(org-mobile-locate-entry (match-string 4))
16495 \(error (nth 1 msg)))
16497 The return value will then be either a string with the error message,
16498 or a marker if everything is OK.
16500 If THIS-BUFFER is set, the outline path does not contain a file,
16501 only headings."
16502 (let* ((file (if this-buffer buffer-file-name (pop path)))
16503 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16504 (level 1)
16505 (lmin 1)
16506 (lmax 1)
16507 end found flevel)
16508 (unless buffer (error "File not found :%s" file))
16509 (with-current-buffer buffer
16510 (org-with-wide-buffer
16511 (goto-char (point-min))
16512 (dolist (heading path)
16513 (let ((re (format org-complex-heading-regexp-format
16514 (regexp-quote heading)))
16515 (cnt 0))
16516 (while (re-search-forward re end t)
16517 (setq level (- (match-end 1) (match-beginning 1)))
16518 (when (and (>= level lmin) (<= level lmax))
16519 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16520 (when (= cnt 0)
16521 (error "Heading not found on level %d: %s" lmax heading))
16522 (when (> cnt 1)
16523 (error "Heading not unique on level %d: %s" lmax heading))
16524 (goto-char found)
16525 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16526 (setq end (save-excursion (org-end-of-subtree t t)))))
16527 (when (org-at-heading-p)
16528 (point-marker))))))
16530 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16531 "Find node HEADING in BUFFER.
16532 Return a marker to the heading if it was found, or nil if not.
16533 If POS-ONLY is set, return just the position instead of a marker.
16535 The heading text must match exact, but it may have a TODO keyword,
16536 a priority cookie and tags in the standard locations."
16537 (with-current-buffer (or buffer (current-buffer))
16538 (save-excursion
16539 (save-restriction
16540 (widen)
16541 (goto-char (point-min))
16542 (let (case-fold-search)
16543 (when (re-search-forward
16544 (format org-complex-heading-regexp-format
16545 (regexp-quote heading)) nil t)
16546 (if pos-only
16547 (match-beginning 0)
16548 (move-marker (make-marker) (match-beginning 0)))))))))
16550 (defun org-find-exact-heading-in-directory (heading &optional dir)
16551 "Find Org node headline HEADING in all .org files in directory DIR.
16552 When the target headline is found, return a marker to this location."
16553 (let ((files (directory-files (or dir default-directory)
16554 t "\\`[^.#].*\\.org\\'"))
16555 visiting m buffer)
16556 (catch 'found
16557 (dolist (file files)
16558 (message "trying %s" file)
16559 (setq visiting (org-find-base-buffer-visiting file))
16560 (setq buffer (or visiting (find-file-noselect file)))
16561 (setq m (org-find-exact-headline-in-buffer
16562 heading buffer))
16563 (when (and (not m) (not visiting)) (kill-buffer buffer))
16564 (and m (throw 'found m))))))
16566 (defun org-find-entry-with-id (ident)
16567 "Locate the entry that contains the ID property with exact value IDENT.
16568 IDENT can be a string, a symbol or a number, this function will search for
16569 the string representation of it.
16570 Return the position where this entry starts, or nil if there is no such entry."
16571 (interactive "sID: ")
16572 (let ((id (cond
16573 ((stringp ident) ident)
16574 ((symbolp ident) (symbol-name ident))
16575 ((numberp ident) (number-to-string ident))
16576 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16577 (org-with-wide-buffer (org-find-property "ID" id))))
16579 ;;;; Timestamps
16581 (defvar org-last-changed-timestamp nil)
16582 (defvar org-last-inserted-timestamp nil
16583 "The last time stamp inserted with `org-insert-time-stamp'.")
16584 (defvar org-ts-what) ; dynamically scoped parameter
16586 (defun org-time-stamp (arg &optional inactive)
16587 "Prompt for a date/time and insert a time stamp.
16589 If the user specifies a time like HH:MM or if this command is
16590 called with at least one prefix argument, the time stamp contains
16591 the date and the time. Otherwise, only the date is included.
16593 All parts of a date not specified by the user are filled in from
16594 the timestamp at point, if any, or the current date/time
16595 otherwise.
16597 If there is already a timestamp at the cursor, it is replaced.
16599 With two universal prefix arguments, insert an active timestamp
16600 with the current time without prompting the user.
16602 When called from lisp, the timestamp is inactive if INACTIVE is
16603 non-nil."
16604 (interactive "P")
16605 (let* ((ts (cond
16606 ((org-at-date-range-p t)
16607 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16608 ((org-at-timestamp-p t) (match-string 0))))
16609 ;; Default time is either the timestamp at point or today.
16610 ;; When entering a range, only the range start is considered.
16611 (default-time (if (not ts) (current-time)
16612 (apply #'encode-time (org-parse-time-string ts))))
16613 (default-input (and ts (org-get-compact-tod ts)))
16614 (repeater (and ts
16615 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16616 (match-string 0 ts)))
16617 org-time-was-given
16618 org-end-time-was-given
16619 (time
16620 (and (if (equal arg '(16)) (current-time)
16621 ;; Preserve `this-command' and `last-command'.
16622 (let ((this-command this-command)
16623 (last-command last-command))
16624 (org-read-date
16625 arg 'totime nil nil default-time default-input
16626 inactive))))))
16627 (cond
16628 ((and ts
16629 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16630 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16631 (insert "--")
16632 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16634 ;; Make sure we're on a timestamp. When in the middle of a date
16635 ;; range, move arbitrarily to range end.
16636 (unless (org-at-timestamp-p t)
16637 (skip-chars-forward "-")
16638 (org-at-timestamp-p t))
16639 (replace-match "")
16640 (setq org-last-changed-timestamp
16641 (org-insert-time-stamp
16642 time (or org-time-was-given arg)
16643 inactive nil nil (list org-end-time-was-given)))
16644 (when repeater
16645 (backward-char)
16646 (insert " " repeater)
16647 (setq org-last-changed-timestamp
16648 (concat (substring org-last-inserted-timestamp 0 -1)
16649 " " repeater ">")))
16650 (message "Timestamp updated"))
16651 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16652 (t (org-insert-time-stamp
16653 time (or org-time-was-given arg) inactive nil nil
16654 (list org-end-time-was-given))))))
16656 ;; FIXME: can we use this for something else, like computing time differences?
16657 (defun org-get-compact-tod (s)
16658 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16659 (let* ((t1 (match-string 1 s))
16660 (h1 (string-to-number (match-string 2 s)))
16661 (m1 (string-to-number (match-string 3 s)))
16662 (t2 (and (match-end 4) (match-string 5 s)))
16663 (h2 (and t2 (string-to-number (match-string 6 s))))
16664 (m2 (and t2 (string-to-number (match-string 7 s))))
16665 dh dm)
16666 (if (not t2)
16668 (setq dh (- h2 h1) dm (- m2 m1))
16669 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16670 (concat t1 "+" (number-to-string dh)
16671 (and (/= 0 dm) (format ":%02d" dm)))))))
16673 (defun org-time-stamp-inactive (&optional arg)
16674 "Insert an inactive time stamp.
16675 An inactive time stamp is enclosed in square brackets instead of angle
16676 brackets. It is inactive in the sense that it does not trigger agenda entries,
16677 does not link to the calendar and cannot be changed with the S-cursor keys.
16678 So these are more for recording a certain time/date."
16679 (interactive "P")
16680 (org-time-stamp arg 'inactive))
16682 (defvar org-date-ovl (make-overlay 1 1))
16683 (overlay-put org-date-ovl 'face 'org-date-selected)
16684 (org-detach-overlay org-date-ovl)
16686 (defvar org-ans1) ; dynamically scoped parameter
16687 (defvar org-ans2) ; dynamically scoped parameter
16689 (defvar org-plain-time-of-day-regexp) ; defined below
16691 (defvar org-overriding-default-time nil) ; dynamically scoped
16692 (defvar org-read-date-overlay nil)
16693 (defvar org-dcst nil) ; dynamically scoped
16694 (defvar org-read-date-history nil)
16695 (defvar org-read-date-final-answer nil)
16696 (defvar org-read-date-analyze-futurep nil)
16697 (defvar org-read-date-analyze-forced-year nil)
16698 (defvar org-read-date-inactive)
16700 (defvar org-read-date-minibuffer-local-map
16701 (let* ((map (make-sparse-keymap)))
16702 (set-keymap-parent map minibuffer-local-map)
16703 (org-defkey map (kbd ".")
16704 (lambda () (interactive)
16705 ;; Are we at the beginning of the prompt?
16706 (if (org-looking-back "^[^:]+: "
16707 (let ((inhibit-field-text-motion t))
16708 (line-beginning-position)))
16709 (org-eval-in-calendar '(calendar-goto-today))
16710 (insert "."))))
16711 (org-defkey map (kbd "C-.")
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(calendar-goto-today))))
16714 (org-defkey map [(meta shift left)]
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-backward-month 1))))
16717 (org-defkey map [(meta shift right)]
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(calendar-forward-month 1))))
16720 (org-defkey map [(meta shift up)]
16721 (lambda () (interactive)
16722 (org-eval-in-calendar '(calendar-backward-year 1))))
16723 (org-defkey map [(meta shift down)]
16724 (lambda () (interactive)
16725 (org-eval-in-calendar '(calendar-forward-year 1))))
16726 (org-defkey map [?\e (shift left)]
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-backward-month 1))))
16729 (org-defkey map [?\e (shift right)]
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(calendar-forward-month 1))))
16732 (org-defkey map [?\e (shift up)]
16733 (lambda () (interactive)
16734 (org-eval-in-calendar '(calendar-backward-year 1))))
16735 (org-defkey map [?\e (shift down)]
16736 (lambda () (interactive)
16737 (org-eval-in-calendar '(calendar-forward-year 1))))
16738 (org-defkey map [(shift up)]
16739 (lambda () (interactive)
16740 (org-eval-in-calendar '(calendar-backward-week 1))))
16741 (org-defkey map [(shift down)]
16742 (lambda () (interactive)
16743 (org-eval-in-calendar '(calendar-forward-week 1))))
16744 (org-defkey map [(shift left)]
16745 (lambda () (interactive)
16746 (org-eval-in-calendar '(calendar-backward-day 1))))
16747 (org-defkey map [(shift right)]
16748 (lambda () (interactive)
16749 (org-eval-in-calendar '(calendar-forward-day 1))))
16750 (org-defkey map "!"
16751 (lambda () (interactive)
16752 (org-eval-in-calendar '(diary-view-entries))
16753 (message "")))
16754 (org-defkey map ">"
16755 (lambda () (interactive)
16756 (org-eval-in-calendar '(calendar-scroll-left 1))))
16757 (org-defkey map "<"
16758 (lambda () (interactive)
16759 (org-eval-in-calendar '(calendar-scroll-right 1))))
16760 (org-defkey map "\C-v"
16761 (lambda () (interactive)
16762 (org-eval-in-calendar
16763 '(calendar-scroll-left-three-months 1))))
16764 (org-defkey map "\M-v"
16765 (lambda () (interactive)
16766 (org-eval-in-calendar
16767 '(calendar-scroll-right-three-months 1))))
16768 map)
16769 "Keymap for minibuffer commands when using `org-read-date'.")
16771 (defvar org-def)
16772 (defvar org-defdecode)
16773 (defvar org-with-time)
16775 (defvar calendar-setup) ; Dynamically scoped.
16776 (defun org-read-date (&optional with-time to-time from-string prompt
16777 default-time default-input inactive)
16778 "Read a date, possibly a time, and make things smooth for the user.
16779 The prompt will suggest to enter an ISO date, but you can also enter anything
16780 which will at least partially be understood by `parse-time-string'.
16781 Unrecognized parts of the date will default to the current day, month, year,
16782 hour and minute. If this command is called to replace a timestamp at point,
16783 or to enter the second timestamp of a range, the default time is taken
16784 from the existing stamp. Furthermore, the command prefers the future,
16785 so if you are giving a date where the year is not given, and the day-month
16786 combination is already past in the current year, it will assume you
16787 mean next year. For details, see the manual. A few examples:
16789 3-2-5 --> 2003-02-05
16790 feb 15 --> currentyear-02-15
16791 2/15 --> currentyear-02-15
16792 sep 12 9 --> 2009-09-12
16793 12:45 --> today 12:45
16794 22 sept 0:34 --> currentyear-09-22 0:34
16795 12 --> currentyear-currentmonth-12
16796 Fri --> nearest Friday after today
16797 -Tue --> last Tuesday
16798 etc.
16800 Furthermore you can specify a relative date by giving, as the *first* thing
16801 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16802 change in days weeks, months, years.
16803 With a single plus or minus, the date is relative to today. With a double
16804 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16805 +4d --> four days from today
16806 +4 --> same as above
16807 +2w --> two weeks from today
16808 ++5 --> five days from default date
16810 The function understands only English month and weekday abbreviations.
16812 While prompting, a calendar is popped up - you can also select the
16813 date with the mouse (button 1). The calendar shows a period of three
16814 months. To scroll it to other months, use the keys `>' and `<'.
16815 If you don't like the calendar, turn it off with
16816 (setq org-read-date-popup-calendar nil)
16818 With optional argument TO-TIME, the date will immediately be converted
16819 to an internal time.
16820 With an optional argument WITH-TIME, the prompt will suggest to
16821 also insert a time. Note that when WITH-TIME is not set, you can
16822 still enter a time, and this function will inform the calling routine
16823 about this change. The calling routine may then choose to change the
16824 format used to insert the time stamp into the buffer to include the time.
16825 With optional argument FROM-STRING, read from this string instead from
16826 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16827 the time/date that is used for everything that is not specified by the
16828 user."
16829 (require 'parse-time)
16830 (let* ((org-with-time with-time)
16831 (org-time-stamp-rounding-minutes
16832 (if (equal org-with-time '(16))
16833 '(0 0)
16834 org-time-stamp-rounding-minutes))
16835 (org-dcst org-display-custom-times)
16836 (ct (org-current-time))
16837 (org-def (or org-overriding-default-time default-time ct))
16838 (org-defdecode (decode-time org-def))
16839 (cur-frame (selected-frame))
16840 (mouse-autoselect-window nil) ; Don't let the mouse jump
16841 (calendar-setup
16842 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16843 (calendar-move-hook nil)
16844 (calendar-view-diary-initially-flag nil)
16845 (calendar-view-holidays-initially-flag nil)
16846 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16847 ;; Rationalize `org-def' and `org-defdecode', if required.
16848 (when (< (nth 2 org-defdecode) org-extend-today-until)
16849 (setf (nth 2 org-defdecode) -1)
16850 (setf (nth 1 org-defdecode) 59)
16851 (setq org-def (apply #'encode-time org-defdecode))
16852 (setq org-defdecode (decode-time org-def)))
16853 (let* ((timestr (format-time-string
16854 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16855 org-def))
16856 (prompt (concat (if prompt (concat prompt " ") "")
16857 (format "Date+time [%s]: " timestr))))
16858 (cond
16859 (from-string (setq ans from-string))
16860 (org-read-date-popup-calendar
16861 (save-excursion
16862 (save-window-excursion
16863 (calendar)
16864 (when (eq calendar-setup 'calendar-only)
16865 (setq cal-frame
16866 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16867 (select-frame cal-frame))
16868 (org-eval-in-calendar '(setq cursor-type nil) t)
16869 (unwind-protect
16870 (progn
16871 (calendar-forward-day (- (time-to-days org-def)
16872 (calendar-absolute-from-gregorian
16873 (calendar-current-date))))
16874 (org-eval-in-calendar nil t)
16875 (let* ((old-map (current-local-map))
16876 (map (copy-keymap calendar-mode-map))
16877 (minibuffer-local-map
16878 (copy-keymap org-read-date-minibuffer-local-map)))
16879 (org-defkey map (kbd "RET") 'org-calendar-select)
16880 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16881 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16882 (unwind-protect
16883 (progn
16884 (use-local-map map)
16885 (setq org-read-date-inactive inactive)
16886 (add-hook 'post-command-hook 'org-read-date-display)
16887 (setq org-ans0
16888 (read-string prompt
16889 default-input
16890 'org-read-date-history
16891 nil))
16892 ;; org-ans0: from prompt
16893 ;; org-ans1: from mouse click
16894 ;; org-ans2: from calendar motion
16895 (setq ans
16896 (concat org-ans0 " " (or org-ans1 org-ans2))))
16897 (remove-hook 'post-command-hook 'org-read-date-display)
16898 (use-local-map old-map)
16899 (when org-read-date-overlay
16900 (delete-overlay org-read-date-overlay)
16901 (setq org-read-date-overlay nil)))))
16902 (bury-buffer "*Calendar*")
16903 (when cal-frame
16904 (delete-frame cal-frame)
16905 (select-frame-set-input-focus cur-frame))))))
16907 (t ; Naked prompt only
16908 (unwind-protect
16909 (setq ans (read-string prompt default-input
16910 'org-read-date-history timestr))
16911 (when org-read-date-overlay
16912 (delete-overlay org-read-date-overlay)
16913 (setq org-read-date-overlay nil))))))
16915 (setq final (org-read-date-analyze ans org-def org-defdecode))
16917 (when org-read-date-analyze-forced-year
16918 (message "Year was forced into %s"
16919 (if org-read-date-force-compatible-dates
16920 "compatible range (1970-2037)"
16921 "range representable on this machine"))
16922 (ding))
16924 ;; One round trip to get rid of 34th of August and stuff like that....
16925 (setq final (decode-time (apply 'encode-time final)))
16927 (setq org-read-date-final-answer ans)
16929 (if to-time
16930 (apply 'encode-time final)
16931 (if (and (boundp 'org-time-was-given) org-time-was-given)
16932 (format "%04d-%02d-%02d %02d:%02d"
16933 (nth 5 final) (nth 4 final) (nth 3 final)
16934 (nth 2 final) (nth 1 final))
16935 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16937 (defun org-read-date-display ()
16938 "Display the current date prompt interpretation in the minibuffer."
16939 (when org-read-date-display-live
16940 (when org-read-date-overlay
16941 (delete-overlay org-read-date-overlay))
16942 (when (minibufferp (current-buffer))
16943 (save-excursion
16944 (end-of-line 1)
16945 (while (not (equal (buffer-substring
16946 (max (point-min) (- (point) 4)) (point))
16947 " "))
16948 (insert " ")))
16949 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16950 " " (or org-ans1 org-ans2)))
16951 (org-end-time-was-given nil)
16952 (f (org-read-date-analyze ans org-def org-defdecode))
16953 (fmts (if org-dcst
16954 org-time-stamp-custom-formats
16955 org-time-stamp-formats))
16956 (fmt (if (or org-with-time
16957 (and (boundp 'org-time-was-given) org-time-was-given))
16958 (cdr fmts)
16959 (car fmts)))
16960 (txt (format-time-string fmt (apply 'encode-time f)))
16961 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16962 (txt (concat "=> " txt)))
16963 (when (and org-end-time-was-given
16964 (string-match org-plain-time-of-day-regexp txt))
16965 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16966 org-end-time-was-given
16967 (substring txt (match-end 0)))))
16968 (when org-read-date-analyze-futurep
16969 (setq txt (concat txt " (=>F)")))
16970 (setq org-read-date-overlay
16971 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16972 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16974 (defun org-read-date-analyze (ans def defdecode)
16975 "Analyze the combined answer of the date prompt."
16976 ;; FIXME: cleanup and comment
16977 ;; Pass `current-time' result to `decode-time' (instead of calling
16978 ;; without arguments) so that only `current-time' has to be
16979 ;; overriden in tests.
16980 (let ((org-def def)
16981 (org-defdecode defdecode)
16982 (nowdecode (decode-time (current-time)))
16983 delta deltan deltaw deltadef year month day
16984 hour minute second wday pm h2 m2 tl wday1
16985 iso-year iso-weekday iso-week iso-date futurep kill-year)
16986 (setq org-read-date-analyze-futurep nil
16987 org-read-date-analyze-forced-year nil)
16988 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16989 (setq ans "+0"))
16991 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16992 (setq ans (replace-match "" t t ans)
16993 deltan (car delta)
16994 deltaw (nth 1 delta)
16995 deltadef (nth 2 delta)))
16997 ;; Check if there is an iso week date in there. If yes, store the
16998 ;; info and postpone interpreting it until the rest of the parsing
16999 ;; is done.
17000 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17001 (setq iso-year (when (match-end 1)
17002 (org-small-year-to-year
17003 (string-to-number (match-string 1 ans))))
17004 iso-weekday (when (match-end 3)
17005 (string-to-number (match-string 3 ans)))
17006 iso-week (string-to-number (match-string 2 ans)))
17007 (setq ans (replace-match "" t t ans)))
17009 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17010 (when (string-match
17011 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17012 (setq year (if (match-end 2)
17013 (string-to-number (match-string 2 ans))
17014 (progn (setq kill-year t)
17015 (string-to-number (format-time-string "%Y"))))
17016 month (string-to-number (match-string 3 ans))
17017 day (string-to-number (match-string 4 ans)))
17018 (when (< year 100) (setq year (+ 2000 year)))
17019 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17020 t nil ans)))
17022 ;; Help matching dotted european dates
17023 (when (string-match
17024 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17025 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17026 (setq kill-year t)
17027 (string-to-number (format-time-string "%Y")))
17028 day (string-to-number (match-string 1 ans))
17029 month (string-to-number (match-string 2 ans))
17030 ans (replace-match (format "%04d-%02d-%02d" year month day)
17031 t nil ans)))
17033 ;; Help matching american dates, like 5/30 or 5/30/7
17034 (when (string-match
17035 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17036 (setq year (if (match-end 4)
17037 (string-to-number (match-string 4 ans))
17038 (progn (setq kill-year t)
17039 (string-to-number (format-time-string "%Y"))))
17040 month (string-to-number (match-string 1 ans))
17041 day (string-to-number (match-string 2 ans)))
17042 (when (< year 100) (setq year (+ 2000 year)))
17043 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17044 t nil ans)))
17045 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17046 ;; If there is a time with am/pm, and *no* time without it, we convert
17047 ;; so that matching will be successful.
17048 (loop for i from 1 to 2 do ; twice, for end time as well
17049 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17050 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17051 (setq hour (string-to-number (match-string 1 ans))
17052 minute (if (match-end 3)
17053 (string-to-number (match-string 3 ans))
17055 pm (equal ?p
17056 (string-to-char (downcase (match-string 4 ans)))))
17057 (if (and (= hour 12) (not pm))
17058 (setq hour 0)
17059 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17060 (setq ans (replace-match (format "%02d:%02d" hour minute)
17061 t t ans))))
17063 ;; Check if a time range is given as a duration
17064 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17065 (setq hour (string-to-number (match-string 1 ans))
17066 h2 (+ hour (string-to-number (match-string 3 ans)))
17067 minute (string-to-number (match-string 2 ans))
17068 m2 (+ minute (if (match-end 5) (string-to-number
17069 (match-string 5 ans))0)))
17070 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17071 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17072 t t ans)))
17074 ;; Check if there is a time range
17075 (when (boundp 'org-end-time-was-given)
17076 (setq org-time-was-given nil)
17077 (when (and (string-match org-plain-time-of-day-regexp ans)
17078 (match-end 8))
17079 (setq org-end-time-was-given (match-string 8 ans))
17080 (setq ans (concat (substring ans 0 (match-beginning 7))
17081 (substring ans (match-end 7))))))
17083 (setq tl (parse-time-string ans)
17084 day (or (nth 3 tl) (nth 3 org-defdecode))
17085 month
17086 (cond ((nth 4 tl))
17087 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17088 ;; Day was specified. Make sure DAY+MONTH
17089 ;; combination happens in the future.
17090 ((nth 3 tl)
17091 (setq futurep t)
17092 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17093 (nth 4 nowdecode)))
17094 (t (nth 4 org-defdecode)))
17095 year
17096 (cond ((and (not kill-year) (nth 5 tl)))
17097 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17098 ;; Month was guessed in the future and is at least
17099 ;; equal to NOWDECODE's. Fix year accordingly.
17100 (futurep
17101 (if (or (> month (nth 4 nowdecode))
17102 (>= day (nth 3 nowdecode)))
17103 (nth 5 nowdecode)
17104 (1+ (nth 5 nowdecode))))
17105 ;; Month was specified. Make sure MONTH+YEAR
17106 ;; combination happens in the future.
17107 ((nth 4 tl)
17108 (setq futurep t)
17109 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17110 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17111 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17112 (t (nth 5 nowdecode))))
17113 (t (nth 5 org-defdecode)))
17114 hour (or (nth 2 tl) (nth 2 org-defdecode))
17115 minute (or (nth 1 tl) (nth 1 org-defdecode))
17116 second (or (nth 0 tl) 0)
17117 wday (nth 6 tl))
17119 (when (and (eq org-read-date-prefer-future 'time)
17120 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17121 (equal day (nth 3 nowdecode))
17122 (equal month (nth 4 nowdecode))
17123 (equal year (nth 5 nowdecode))
17124 (nth 2 tl)
17125 (or (< (nth 2 tl) (nth 2 nowdecode))
17126 (and (= (nth 2 tl) (nth 2 nowdecode))
17127 (nth 1 tl)
17128 (< (nth 1 tl) (nth 1 nowdecode)))))
17129 (setq day (1+ day)
17130 futurep t))
17132 ;; Special date definitions below
17133 (cond
17134 (iso-week
17135 ;; There was an iso week
17136 (require 'cal-iso)
17137 (setq futurep nil)
17138 (setq year (or iso-year year)
17139 day (or iso-weekday wday 1)
17140 wday nil ; to make sure that the trigger below does not match
17141 iso-date (calendar-gregorian-from-absolute
17142 (calendar-iso-to-absolute
17143 (list iso-week day year))))
17144 ; FIXME: Should we also push ISO weeks into the future?
17145 ; (when (and org-read-date-prefer-future
17146 ; (not iso-year)
17147 ; (< (calendar-absolute-from-gregorian iso-date)
17148 ; (time-to-days (current-time))))
17149 ; (setq year (1+ year)
17150 ; iso-date (calendar-gregorian-from-absolute
17151 ; (calendar-iso-to-absolute
17152 ; (list iso-week day year)))))
17153 (setq month (car iso-date)
17154 year (nth 2 iso-date)
17155 day (nth 1 iso-date)))
17156 (deltan
17157 (setq futurep nil)
17158 (unless deltadef
17159 ;; Pass `current-time' result to `decode-time' (instead of
17160 ;; calling without arguments) so that only `current-time' has
17161 ;; to be overriden in tests.
17162 (let ((now (decode-time (current-time))))
17163 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17164 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17165 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17166 ((equal deltaw "m") (setq month (+ month deltan)))
17167 ((equal deltaw "y") (setq year (+ year deltan)))))
17168 ((and wday (not (nth 3 tl)))
17169 ;; Weekday was given, but no day, so pick that day in the week
17170 ;; on or after the derived date.
17171 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17172 (unless (equal wday wday1)
17173 (setq day (+ day (% (- wday wday1 -7) 7))))))
17174 (when (and (boundp 'org-time-was-given)
17175 (nth 2 tl))
17176 (setq org-time-was-given t))
17177 (when (< year 100) (setq year (+ 2000 year)))
17178 ;; Check of the date is representable
17179 (if org-read-date-force-compatible-dates
17180 (progn
17181 (when (< year 1970)
17182 (setq year 1970 org-read-date-analyze-forced-year t))
17183 (when (> year 2037)
17184 (setq year 2037 org-read-date-analyze-forced-year t)))
17185 (condition-case nil
17186 (ignore (encode-time second minute hour day month year))
17187 (error
17188 (setq year (nth 5 org-defdecode))
17189 (setq org-read-date-analyze-forced-year t))))
17190 (setq org-read-date-analyze-futurep futurep)
17191 (list second minute hour day month year)))
17193 (defvar parse-time-weekdays)
17194 (defun org-read-date-get-relative (s today default)
17195 "Check string S for special relative date string.
17196 TODAY and DEFAULT are internal times, for today and for a default.
17197 Return shift list (N what def-flag)
17198 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17199 N is the number of WHATs to shift.
17200 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17201 the DEFAULT date rather than TODAY."
17202 (require 'parse-time)
17203 (when (and
17204 (string-match
17205 (concat
17206 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17207 "\\([0-9]+\\)?"
17208 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17209 "\\([ \t]\\|$\\)") s)
17210 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17211 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17212 (string-to-char (substring (match-string 1 s) -1))
17213 ?+))
17214 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17215 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17216 (what (if (match-end 3) (match-string 3 s) "d"))
17217 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17218 (date (if rel default today))
17219 (wday (nth 6 (decode-time date)))
17220 delta)
17221 (if wday1
17222 (progn
17223 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17224 (when (= delta 0) (setq delta 7))
17225 (when (= dir ?-)
17226 (setq delta (- delta 7))
17227 (when (= delta 0) (setq delta -7)))
17228 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17229 (list delta "d" rel))
17230 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17232 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17233 "Turn a user-specified date into the internal representation.
17234 The internal representation needed by the calendar is (month day year).
17235 This is a wrapper to handle the brain-dead convention in calendar that
17236 user function argument order change dependent on argument order."
17237 (if (boundp 'calendar-date-style)
17238 (cond
17239 ((eq calendar-date-style 'american)
17240 (list arg1 arg2 arg3))
17241 ((eq calendar-date-style 'european)
17242 (list arg2 arg1 arg3))
17243 ((eq calendar-date-style 'iso)
17244 (list arg2 arg3 arg1)))
17245 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17246 (if (org-bound-and-true-p european-calendar-style)
17247 (list arg2 arg1 arg3)
17248 (list arg1 arg2 arg3)))))
17250 (defun org-eval-in-calendar (form &optional keepdate)
17251 "Eval FORM in the calendar window and return to current window.
17252 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17253 otherwise stick to the current value of `org-ans2'."
17254 (let ((sf (selected-frame))
17255 (sw (selected-window)))
17256 (select-window (get-buffer-window "*Calendar*" t))
17257 (eval form)
17258 (when (and (not keepdate) (calendar-cursor-to-date))
17259 (let* ((date (calendar-cursor-to-date))
17260 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17261 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17262 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17263 (select-window sw)
17264 (org-select-frame-set-input-focus sf)))
17266 (defun org-calendar-select ()
17267 "Return to `org-read-date' with the date currently selected.
17268 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17269 (interactive)
17270 (when (calendar-cursor-to-date)
17271 (let* ((date (calendar-cursor-to-date))
17272 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17273 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17274 (when (active-minibuffer-window) (exit-minibuffer))))
17276 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17277 "Insert a date stamp for the date given by the internal TIME.
17278 See `format-time-string' for the format of TIME.
17279 WITH-HM means use the stamp format that includes the time of the day.
17280 INACTIVE means use square brackets instead of angular ones, so that the
17281 stamp will not contribute to the agenda.
17282 PRE and POST are optional strings to be inserted before and after the
17283 stamp.
17284 The command returns the inserted time stamp."
17285 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17286 stamp)
17287 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17288 (insert-before-markers (or pre ""))
17289 (when (listp extra)
17290 (setq extra (car extra))
17291 (if (and (stringp extra)
17292 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17293 (setq extra (format "-%02d:%02d"
17294 (string-to-number (match-string 1 extra))
17295 (string-to-number (match-string 2 extra))))
17296 (setq extra nil)))
17297 (when extra
17298 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17299 (insert-before-markers (setq stamp (format-time-string fmt time)))
17300 (insert-before-markers (or post ""))
17301 (setq org-last-inserted-timestamp stamp)))
17303 (defun org-toggle-time-stamp-overlays ()
17304 "Toggle the use of custom time stamp formats."
17305 (interactive)
17306 (setq org-display-custom-times (not org-display-custom-times))
17307 (unless org-display-custom-times
17308 (let ((p (point-min)) (bmp (buffer-modified-p)))
17309 (while (setq p (next-single-property-change p 'display))
17310 (when (and (get-text-property p 'display)
17311 (eq (get-text-property p 'face) 'org-date))
17312 (remove-text-properties
17313 p (setq p (next-single-property-change p 'display))
17314 '(display t))))
17315 (set-buffer-modified-p bmp)))
17316 (when (featurep 'xemacs)
17317 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17318 (org-restart-font-lock)
17319 (setq org-table-may-need-update t)
17320 (if org-display-custom-times
17321 (message "Time stamps are overlaid with custom format")
17322 (message "Time stamp overlays removed")))
17324 (defun org-display-custom-time (beg end)
17325 "Overlay modified time stamp format over timestamp between BEG and END."
17326 (let* ((ts (buffer-substring beg end))
17327 t1 w1 with-hm tf time str w2 (off 0))
17328 (save-match-data
17329 (setq t1 (org-parse-time-string ts t))
17330 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17331 (setq off (- (match-end 0) (match-beginning 0)))))
17332 (setq end (- end off))
17333 (setq w1 (- end beg)
17334 with-hm (and (nth 1 t1) (nth 2 t1))
17335 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17336 time (org-fix-decoded-time t1)
17337 str (org-add-props
17338 (format-time-string
17339 (substring tf 1 -1) (apply 'encode-time time))
17340 nil 'mouse-face 'highlight)
17341 w2 (length str))
17342 (unless (= w2 w1)
17343 (add-text-properties (1+ beg) (+ 2 beg)
17344 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17345 (if (featurep 'xemacs)
17346 (progn
17347 (put-text-property beg end 'invisible t)
17348 (put-text-property beg end 'end-glyph (make-glyph str)))
17349 (put-text-property beg end 'display str))))
17351 (defun org-fix-decoded-time (time)
17352 "Set 0 instead of nil for the first 6 elements of time.
17353 Don't touch the rest."
17354 (let ((n 0))
17355 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17357 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17359 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17360 "Difference between TIMESTAMP-STRING and now in days.
17361 If SECONDS is non-nil, return the difference in seconds."
17362 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17363 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17364 (funcall fdiff (current-time)))))
17366 (defun org-deadline-close (timestamp-string &optional ndays)
17367 "Is the time in TIMESTAMP-STRING close to the current date?"
17368 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17369 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17370 (not (org-entry-is-done-p))))
17372 (defun org-get-wdays (ts &optional delay zero-delay)
17373 "Get the deadline lead time appropriate for timestring TS.
17374 When DELAY is non-nil, get the delay time for scheduled items
17375 instead of the deadline lead time. When ZERO-DELAY is non-nil
17376 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17377 don't try to find the delay cookie in the scheduled timestamp."
17378 (let ((tv (if delay org-scheduled-delay-days
17379 org-deadline-warning-days)))
17380 (cond
17381 ((or (and delay (< tv 0))
17382 (and delay zero-delay (<= tv 0))
17383 (and (not delay) (<= tv 0)))
17384 ;; Enforce this value no matter what
17385 (- tv))
17386 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17387 ;; lead time is specified.
17388 (floor (* (string-to-number (match-string 1 ts))
17389 (cdr (assoc (match-string 2 ts)
17390 '(("d" . 1) ("w" . 7)
17391 ("m" . 30.4) ("y" . 365.25)
17392 ("h" . 0.041667)))))))
17393 ;; go for the default.
17394 (t tv))))
17396 (defun org-calendar-select-mouse (ev)
17397 "Return to `org-read-date' with the date currently selected.
17398 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17399 (interactive "e")
17400 (mouse-set-point ev)
17401 (when (calendar-cursor-to-date)
17402 (let* ((date (calendar-cursor-to-date))
17403 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17404 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17405 (when (active-minibuffer-window) (exit-minibuffer))))
17407 (defun org-check-deadlines (ndays)
17408 "Check if there are any deadlines due or past due.
17409 A deadline is considered due if it happens within `org-deadline-warning-days'
17410 days from today's date. If the deadline appears in an entry marked DONE,
17411 it is not shown. The prefix arg NDAYS can be used to test that many
17412 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17413 (interactive "P")
17414 (let* ((org-warn-days
17415 (cond
17416 ((equal ndays '(4)) 100000)
17417 (ndays (prefix-numeric-value ndays))
17418 (t (abs org-deadline-warning-days))))
17419 (case-fold-search nil)
17420 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17421 (callback
17422 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17423 (message "%d deadlines past-due or due within %d days"
17424 (org-occur regexp nil callback)
17425 org-warn-days)))
17427 (defsubst org-re-timestamp (type)
17428 "Return a regexp for timestamp TYPE.
17429 Allowed values for TYPE are:
17431 all: all timestamps
17432 active: only active timestamps (<...>)
17433 inactive: only inactive timestamps ([...])
17434 scheduled: only scheduled timestamps
17435 deadline: only deadline timestamps
17436 closed: only closed time-stamps
17438 When TYPE is nil, fall back on returning a regexp that matches
17439 both scheduled and deadline timestamps."
17440 (case type
17441 (all org-ts-regexp-both)
17442 (active org-ts-regexp)
17443 (inactive org-ts-regexp-inactive)
17444 (scheduled org-scheduled-time-regexp)
17445 (deadline org-deadline-time-regexp)
17446 (closed org-closed-time-regexp)
17447 (otherwise
17448 (concat "\\<"
17449 (regexp-opt (list org-deadline-string org-scheduled-string))
17450 " *<\\([^>]+\\)>"))))
17452 (defun org-check-before-date (d)
17453 "Check if there are deadlines or scheduled entries before date D."
17454 (interactive (list (org-read-date)))
17455 (let ((case-fold-search nil)
17456 (regexp (org-re-timestamp org-ts-type))
17457 (callback
17458 `(lambda ()
17459 (let ((match (match-string 1)))
17460 (and ,(if (memq org-ts-type '(active inactive all))
17461 '(eq (org-element-type (org-element-context)) 'timestamp)
17462 '(org-at-planning-p))
17463 (time-less-p
17464 (org-time-string-to-time match)
17465 (org-time-string-to-time d)))))))
17466 (message "%d entries before %s"
17467 (org-occur regexp nil callback)
17468 d)))
17470 (defun org-check-after-date (d)
17471 "Check if there are deadlines or scheduled entries after date D."
17472 (interactive (list (org-read-date)))
17473 (let ((case-fold-search nil)
17474 (regexp (org-re-timestamp org-ts-type))
17475 (callback
17476 `(lambda ()
17477 (let ((match (match-string 1)))
17478 (and ,(if (memq org-ts-type '(active inactive all))
17479 '(eq (org-element-type (org-element-context)) 'timestamp)
17480 '(org-at-planning-p))
17481 (not (time-less-p
17482 (org-time-string-to-time match)
17483 (org-time-string-to-time d))))))))
17484 (message "%d entries after %s"
17485 (org-occur regexp nil callback)
17486 d)))
17488 (defun org-check-dates-range (start-date end-date)
17489 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17490 (interactive (list (org-read-date nil nil nil "Range starts")
17491 (org-read-date nil nil nil "Range end")))
17492 (let ((case-fold-search nil)
17493 (regexp (org-re-timestamp org-ts-type))
17494 (callback
17495 `(lambda ()
17496 (let ((match (match-string 1)))
17497 (and
17498 ,(if (memq org-ts-type '(active inactive all))
17499 '(eq (org-element-type (org-element-context)) 'timestamp)
17500 '(org-at-planning-p))
17501 (not (time-less-p
17502 (org-time-string-to-time match)
17503 (org-time-string-to-time start-date)))
17504 (time-less-p
17505 (org-time-string-to-time match)
17506 (org-time-string-to-time end-date)))))))
17507 (message "%d entries between %s and %s"
17508 (org-occur regexp nil callback) start-date end-date)))
17510 (defun org-evaluate-time-range (&optional to-buffer)
17511 "Evaluate a time range by computing the difference between start and end.
17512 Normally the result is just printed in the echo area, but with prefix arg
17513 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17514 If the time range is actually in a table, the result is inserted into the
17515 next column.
17516 For time difference computation, a year is assumed to be exactly 365
17517 days in order to avoid rounding problems."
17518 (interactive "P")
17520 (org-clock-update-time-maybe)
17521 (save-excursion
17522 (unless (org-at-date-range-p t)
17523 (goto-char (point-at-bol))
17524 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17525 (unless (org-at-date-range-p t)
17526 (user-error "Not at a time-stamp range, and none found in current line")))
17527 (let* ((ts1 (match-string 1))
17528 (ts2 (match-string 2))
17529 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17530 (match-end (match-end 0))
17531 (time1 (org-time-string-to-time ts1))
17532 (time2 (org-time-string-to-time ts2))
17533 (t1 (org-float-time time1))
17534 (t2 (org-float-time time2))
17535 (diff (abs (- t2 t1)))
17536 (negative (< (- t2 t1) 0))
17537 ;; (ys (floor (* 365 24 60 60)))
17538 (ds (* 24 60 60))
17539 (hs (* 60 60))
17540 (fy "%dy %dd %02d:%02d")
17541 (fy1 "%dy %dd")
17542 (fd "%dd %02d:%02d")
17543 (fd1 "%dd")
17544 (fh "%02d:%02d")
17545 y d h m align)
17546 (if havetime
17547 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17549 d (floor (/ diff ds)) diff (mod diff ds)
17550 h (floor (/ diff hs)) diff (mod diff hs)
17551 m (floor (/ diff 60)))
17552 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17554 d (floor (+ (/ diff ds) 0.5))
17555 h 0 m 0))
17556 (if (not to-buffer)
17557 (message "%s" (org-make-tdiff-string y d h m))
17558 (if (org-at-table-p)
17559 (progn
17560 (goto-char match-end)
17561 (setq align t)
17562 (and (looking-at " *|") (goto-char (match-end 0))))
17563 (goto-char match-end))
17564 (when (looking-at
17565 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17566 (replace-match ""))
17567 (when negative (insert " -"))
17568 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17569 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17570 (insert " " (format fh h m))))
17571 (when align (org-table-align))
17572 (message "Time difference inserted")))))
17574 (defun org-make-tdiff-string (y d h m)
17575 (let ((fmt "")
17576 (l nil))
17577 (when (> y 0)
17578 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17579 (push y l))
17580 (when (> d 0)
17581 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17582 (push d l))
17583 (when (> h 0)
17584 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17585 (push h l))
17586 (when (> m 0)
17587 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17588 (push m l))
17589 (apply 'format fmt (nreverse l))))
17591 (defun org-time-string-to-time (s &optional buffer pos)
17592 "Convert a timestamp string into internal time."
17593 (condition-case errdata
17594 (apply 'encode-time (org-parse-time-string s))
17595 (error (error "Bad timestamp `%s'%s\nError was: %s"
17596 s (if (not (and buffer pos))
17598 (format-message " at %d in buffer `%s'" pos buffer))
17599 (cdr errdata)))))
17601 (defun org-time-string-to-seconds (s)
17602 "Convert a timestamp string to a number of seconds."
17603 (org-float-time (org-time-string-to-time s)))
17605 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17607 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17608 "Convert time stamp S to an absolute day number.
17610 If DAYNR in non-nil, and there is a specifier for a cyclic time
17611 stamp, get the closest date to DAYNR. If PREFER is
17612 `past' (respectively `future') return a date past (respectively
17613 after) or equal to DAYNR.
17615 POS is the location of time stamp S, as a buffer position in
17616 BUFFER.
17618 Diary sexp timestamps are matched against DAYNR, when non-nil.
17619 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17620 signalled."
17621 (cond
17622 ((string-match "\\`%%\\((.*)\\)" s)
17623 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17624 ;; only able to match individual dates. If it fails, raise an
17625 ;; error.
17626 (if (and daynr
17627 (org-diary-sexp-entry
17628 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17629 daynr
17630 (signal 'org-diary-sexp-no-match (list s))))
17631 ((and daynr show-all) (org-closest-date s daynr prefer))
17632 (t (time-to-days
17633 (condition-case errdata
17634 (apply #'encode-time (org-parse-time-string s))
17635 (error (error "Bad timestamp `%s'%s\nError was: %s"
17637 (if (not (and buffer pos)) ""
17638 (format-message " at %d in buffer `%s'" pos buffer))
17639 (cdr errdata))))))))
17641 (defun org-days-to-iso-week (days)
17642 "Return the iso week number."
17643 (require 'cal-iso)
17644 (car (calendar-iso-from-absolute days)))
17646 (defun org-small-year-to-year (year)
17647 "Convert 2-digit years into 4-digit years.
17648 YEAR is expanded into one of the 30 next years, if possible, or
17649 into a past one. Any year larger than 99 is returned unchanged."
17650 (if (>= year 100) year
17651 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17652 (century (/ current 100))
17653 (offset (- year (% current 100))))
17654 (cond ((> offset 30) (+ (* (1- century) 100) year))
17655 ((> offset -70) (+ (* century 100) year))
17656 (t (+ (* (1+ century) 100) year))))))
17658 (defun org-time-from-absolute (d)
17659 "Return the time corresponding to date D.
17660 D may be an absolute day number, or a calendar-type list (month day year)."
17661 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17662 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17664 (defun org-calendar-holiday ()
17665 "List of holidays, for Diary display in Org-mode."
17666 (declare (special date))
17667 (require 'holidays)
17668 (let ((hl (funcall
17669 (if (fboundp 'calendar-check-holidays)
17670 'calendar-check-holidays 'check-calendar-holidays) date)))
17671 (when hl (mapconcat 'identity hl "; "))))
17673 (defun org-diary-sexp-entry (sexp entry d)
17674 "Process a SEXP diary ENTRY for date D."
17675 (require 'diary-lib)
17676 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17677 ;; dynamically.
17678 (let* ((sexp `(let ((entry ,entry)
17679 (date ',d))
17680 ,(car (read-from-string sexp))))
17681 (result (if calendar-debug-sexp (eval sexp)
17682 (condition-case nil
17683 (eval sexp)
17684 (error
17685 (beep)
17686 (message "Bad sexp at line %d in %s: %s"
17687 (org-current-line)
17688 (buffer-file-name) sexp)
17689 (sleep-for 2))))))
17690 (cond ((stringp result) (split-string result "; "))
17691 ((and (consp result)
17692 (not (consp (cdr result)))
17693 (stringp (cdr result))) (cdr result))
17694 ((and (consp result)
17695 (stringp (car result))) result)
17696 (result entry))))
17698 (defun org-diary-to-ical-string (frombuf)
17699 "Get iCalendar entries from diary entries in buffer FROMBUF.
17700 This uses the icalendar.el library."
17701 (let* ((tmpdir (if (featurep 'xemacs)
17702 (temp-directory)
17703 temporary-file-directory))
17704 (tmpfile (make-temp-name
17705 (expand-file-name "orgics" tmpdir)))
17706 buf rtn b e)
17707 (with-current-buffer frombuf
17708 (icalendar-export-region (point-min) (point-max) tmpfile)
17709 (setq buf (find-buffer-visiting tmpfile))
17710 (set-buffer buf)
17711 (goto-char (point-min))
17712 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17713 (setq b (match-beginning 0)))
17714 (goto-char (point-max))
17715 (when (re-search-backward "^END:VEVENT" nil t)
17716 (setq e (match-end 0)))
17717 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17718 (kill-buffer buf)
17719 (delete-file tmpfile)
17720 rtn))
17722 (defun org-closest-date (start current prefer)
17723 "Return closest date to CURRENT starting from START.
17725 CURRENT and START are both time stamps.
17727 When PREFER is `past', return a date that is either CURRENT or
17728 past. When PREFER is `future', return a date that is either
17729 CURRENT or future.
17731 Only time stamps with a repeater are modified. Any other time
17732 stamp stay unchanged. In any case, return value is an absolute
17733 day number."
17734 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17735 ;; No repeater. Do not shift time stamp.
17736 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17737 (let ((value (string-to-number (match-string 1 start)))
17738 (type (match-string 2 start)))
17739 (if (= 0 value)
17740 ;; Repeater with a 0-value is considered as void.
17741 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17742 (let* ((base (org-date-to-gregorian start))
17743 (target (org-date-to-gregorian current))
17744 (sday (calendar-absolute-from-gregorian base))
17745 (cday (calendar-absolute-from-gregorian target))
17746 n1 n2)
17747 ;; If START is already past CURRENT, just return START.
17748 (if (<= cday sday) sday
17749 ;; Compute closest date before (N1) and closest date past
17750 ;; (N2) CURRENT.
17751 (pcase type
17752 ("h"
17753 (let ((missing-hours
17754 (mod (+ (- (* 24 (- cday sday))
17755 (nth 2 (org-parse-time-string start)))
17756 org-extend-today-until)
17757 value)))
17758 (setf n1 (if (= missing-hours 0) cday
17759 (- cday (1+ (/ missing-hours 24)))))
17760 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17761 ((or "d" "w")
17762 (let ((value (if (equal type "w") (* 7 value) value)))
17763 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17764 (setf n2 (+ n1 value))))
17765 ("m"
17766 (let* ((add-months
17767 (lambda (d n)
17768 ;; Add N months to gregorian date D, i.e.,
17769 ;; a list (MONTH DAY YEAR). Return a valid
17770 ;; gregorian date.
17771 (let ((m (+ (nth 0 d) n)))
17772 (list (mod m 12)
17773 (nth 1 d)
17774 (+ (/ m 12) (nth 2 d))))))
17775 (months ; Complete months to TARGET.
17776 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17777 (- (nth 0 target) (nth 0 base))
17778 ;; If START's day is greater than
17779 ;; TARGET's, remove incomplete month.
17780 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17781 value)
17782 value))
17783 (before (funcall add-months base months)))
17784 (setf n1 (calendar-absolute-from-gregorian before))
17785 (setf n2
17786 (calendar-absolute-from-gregorian
17787 (funcall add-months before value)))))
17789 (let* ((d (nth 1 base))
17790 (m (nth 0 base))
17791 (y (nth 2 base))
17792 (years ; Complete years to TARGET.
17793 (* (/ (- (nth 2 target)
17795 ;; If START's month and day are
17796 ;; greater than TARGET's, remove
17797 ;; incomplete year.
17798 (if (or (> (nth 0 target) m)
17799 (and (= (nth 0 target) m)
17800 (> (nth 1 target) d)))
17803 value)
17804 value))
17805 (before (list m d (+ y years))))
17806 (setf n1 (calendar-absolute-from-gregorian before))
17807 (setf n2 (calendar-absolute-from-gregorian
17808 (list m d (+ (nth 2 before) value)))))))
17809 ;; Handle PREFER parameter, if any.
17810 (cond
17811 ((eq prefer 'past) (if (= cday n2) n2 n1))
17812 ((eq prefer 'future) (if (= cday n1) n1 n2))
17813 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17815 (defun org-date-to-gregorian (d)
17816 "Turn any specification of date D into a Gregorian date for the calendar."
17817 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17818 ((and (listp d) (= (length d) 3)) d)
17819 ((stringp d)
17820 (let ((d (org-parse-time-string d)))
17821 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17822 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17824 (defun org-parse-time-string (s &optional nodefault)
17825 "Parse the standard Org-mode time string.
17826 This should be a lot faster than the normal `parse-time-string'.
17827 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17828 hour and minute fields will be nil if not given."
17829 (cond ((string-match org-ts-regexp0 s)
17830 (list 0
17831 (when (or (match-beginning 8) (not nodefault))
17832 (string-to-number (or (match-string 8 s) "0")))
17833 (when (or (match-beginning 7) (not nodefault))
17834 (string-to-number (or (match-string 7 s) "0")))
17835 (string-to-number (match-string 4 s))
17836 (string-to-number (match-string 3 s))
17837 (string-to-number (match-string 2 s))
17838 nil nil nil))
17839 ((string-match "^<[^>]+>$" s)
17840 (decode-time (seconds-to-time (org-matcher-time s))))
17841 (t (error "Not a standard Org-mode time string: %s" s))))
17843 (defun org-timestamp-up (&optional arg)
17844 "Increase the date item at the cursor by one.
17845 If the cursor is on the year, change the year. If it is on the month,
17846 the day or the time, change that.
17847 With prefix ARG, change by that many units."
17848 (interactive "p")
17849 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17851 (defun org-timestamp-down (&optional arg)
17852 "Decrease the date item at the cursor by one.
17853 If the cursor is on the year, change the year. If it is on the month,
17854 the day or the time, change that.
17855 With prefix ARG, change by that many units."
17856 (interactive "p")
17857 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17859 (defun org-timestamp-up-day (&optional arg)
17860 "Increase the date in the time stamp by one day.
17861 With prefix ARG, change that many days."
17862 (interactive "p")
17863 (if (and (not (org-at-timestamp-p t))
17864 (org-at-heading-p))
17865 (org-todo 'up)
17866 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17868 (defun org-timestamp-down-day (&optional arg)
17869 "Decrease the date in the time stamp by one day.
17870 With prefix ARG, change that many days."
17871 (interactive "p")
17872 (if (and (not (org-at-timestamp-p t))
17873 (org-at-heading-p))
17874 (org-todo 'down)
17875 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17877 (defun org-at-timestamp-p (&optional inactive-ok)
17878 "Non-nil if point is inside a timestamp.
17880 When optional argument INACTIVE-OK is non-nil, also consider
17881 inactive timestamps.
17883 When this function returns a non-nil value, match data is set
17884 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17885 INACTIVE-OK."
17886 (interactive)
17887 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17888 (pos (point))
17889 (ans (or (looking-at tsr)
17890 (save-excursion
17891 (skip-chars-backward "^[<\n\r\t")
17892 (when (> (point) (point-min)) (backward-char 1))
17893 (and (looking-at tsr)
17894 (> (- (match-end 0) pos) -1))))))
17895 (and ans
17896 (boundp 'org-ts-what)
17897 (setq org-ts-what
17898 (cond
17899 ((= pos (match-beginning 0)) 'bracket)
17900 ;; Point is considered to be "on the bracket" whether
17901 ;; it's really on it or right after it.
17902 ((= pos (1- (match-end 0))) 'bracket)
17903 ((= pos (match-end 0)) 'after)
17904 ((org-pos-in-match-range pos 2) 'year)
17905 ((org-pos-in-match-range pos 3) 'month)
17906 ((org-pos-in-match-range pos 7) 'hour)
17907 ((org-pos-in-match-range pos 8) 'minute)
17908 ((or (org-pos-in-match-range pos 4)
17909 (org-pos-in-match-range pos 5)) 'day)
17910 ((and (> pos (or (match-end 8) (match-end 5)))
17911 (< pos (match-end 0)))
17912 (- pos (or (match-end 8) (match-end 5))))
17913 (t 'day))))
17914 ans))
17916 (defun org-toggle-timestamp-type ()
17917 "Toggle the type (<active> or [inactive]) of a time stamp."
17918 (interactive)
17919 (when (org-at-timestamp-p t)
17920 (let ((beg (match-beginning 0)) (end (match-end 0))
17921 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17922 (save-excursion
17923 (goto-char beg)
17924 (while (re-search-forward "[][<>]" end t)
17925 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17926 t t)))
17927 (message "Timestamp is now %sactive"
17928 (if (equal (char-after beg) ?<) "" "in")))))
17930 (defun org-at-clock-log-p nil
17931 "Is the cursor on the clock log line?"
17932 (save-excursion
17933 (move-beginning-of-line 1)
17934 (looking-at org-clock-line-re)))
17936 (defvar org-clock-history) ; defined in org-clock.el
17937 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17938 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17939 "Change the date in the time stamp at point.
17940 The date will be changed by N times WHAT. WHAT can be `day', `month',
17941 `year', `minute', `second'. If WHAT is not given, the cursor position
17942 in the timestamp determines what will be changed.
17943 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17944 (let ((origin (point)) origin-cat
17945 with-hm inactive
17946 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17947 org-ts-what
17948 extra rem
17949 ts time time0 fixnext clrgx)
17950 (unless (org-at-timestamp-p t)
17951 (user-error "Not at a timestamp"))
17952 (if (and (not what) (eq org-ts-what 'bracket))
17953 (org-toggle-timestamp-type)
17954 ;; Point isn't on brackets. Remember the part of the time-stamp
17955 ;; the point was in. Indeed, size of time-stamps may change,
17956 ;; but point must be kept in the same category nonetheless.
17957 (setq origin-cat org-ts-what)
17958 (when (and (not what) (not (eq org-ts-what 'day))
17959 org-display-custom-times
17960 (get-text-property (point) 'display)
17961 (not (get-text-property (1- (point)) 'display)))
17962 (setq org-ts-what 'day))
17963 (setq org-ts-what (or what org-ts-what)
17964 inactive (= (char-after (match-beginning 0)) ?\[)
17965 ts (match-string 0))
17966 (replace-match "")
17967 (when (string-match
17968 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17970 (setq extra (match-string 1 ts))
17971 (when suppress-tmp-delay
17972 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17973 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17974 (setq with-hm t))
17975 (setq time0 (org-parse-time-string ts))
17976 (when (and updown
17977 (eq org-ts-what 'minute)
17978 (not current-prefix-arg))
17979 ;; This looks like s-up and s-down. Change by one rounding step.
17980 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17981 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17982 (setcar (cdr time0) (+ (nth 1 time0)
17983 (if (> n 0) (- rem) (- dm rem))))))
17984 (setq time
17985 (encode-time (or (car time0) 0)
17986 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17987 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17988 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17989 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17990 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17991 (nthcdr 6 time0)))
17992 (when (and (member org-ts-what '(hour minute))
17993 extra
17994 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17995 (setq extra (org-modify-ts-extra
17996 extra
17997 (if (eq org-ts-what 'hour) 2 5)
17998 n dm)))
17999 (when (integerp org-ts-what)
18000 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18001 (when (eq what 'calendar)
18002 (let ((cal-date (org-get-date-from-calendar)))
18003 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18004 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18005 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18006 (setcar time0 (or (car time0) 0))
18007 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18008 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18009 (setq time (apply 'encode-time time0))))
18010 ;; Insert the new time-stamp, and ensure point stays in the same
18011 ;; category as before (i.e. not after the last position in that
18012 ;; category).
18013 (let ((pos (point)))
18014 ;; Stay before inserted string. `save-excursion' is of no use.
18015 (setq org-last-changed-timestamp
18016 (org-insert-time-stamp time with-hm inactive nil nil extra))
18017 (goto-char pos))
18018 (save-match-data
18019 (looking-at org-ts-regexp3)
18020 (goto-char (cond
18021 ;; `day' category ends before `hour' if any, or at
18022 ;; the end of the day name.
18023 ((eq origin-cat 'day)
18024 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18025 ((eq origin-cat 'hour) (min (match-end 7) origin))
18026 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18027 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18028 ;; `year' and `month' have both fixed size: point
18029 ;; couldn't have moved into another part.
18030 (t origin))))
18031 ;; Update clock if on a CLOCK line.
18032 (org-clock-update-time-maybe)
18033 ;; Maybe adjust the closest clock in `org-clock-history'
18034 (when org-clock-adjust-closest
18035 (if (not (and (org-at-clock-log-p)
18036 (< 1 (length (delq nil (mapcar 'marker-position
18037 org-clock-history))))))
18038 (message "No clock to adjust")
18039 (cond ((save-excursion ; fix previous clock?
18040 (re-search-backward org-ts-regexp0 nil t)
18041 (org-looking-back (concat org-clock-string " \\[")
18042 (line-beginning-position)))
18043 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18044 ((save-excursion ; fix next clock?
18045 (re-search-backward org-ts-regexp0 nil t)
18046 (looking-at (concat org-ts-regexp0 "\\] =>")))
18047 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18048 (save-window-excursion
18049 ;; Find closest clock to point, adjust the previous/next one in history
18050 (let* ((p (save-excursion (org-back-to-heading t)))
18051 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18052 (clfixnth
18053 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18054 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18055 (if (not clfixpos)
18056 (message "No clock to adjust")
18057 (save-excursion
18058 (org-goto-marker-or-bmk clfixpos)
18059 (org-show-subtree)
18060 (when (re-search-forward clrgx nil t)
18061 (goto-char (match-beginning 1))
18062 (let (org-clock-adjust-closest)
18063 (org-timestamp-change n org-ts-what updown))
18064 (message "Clock adjusted in %s for heading: %s"
18065 (file-name-nondirectory (buffer-file-name))
18066 (org-get-heading t t)))))))))
18067 ;; Try to recenter the calendar window, if any.
18068 (when (and org-calendar-follow-timestamp-change
18069 (get-buffer-window "*Calendar*" t)
18070 (memq org-ts-what '(day month year)))
18071 (org-recenter-calendar (time-to-days time))))))
18073 (defun org-modify-ts-extra (s pos n dm)
18074 "Change the different parts of the lead-time and repeat fields in timestamp."
18075 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18076 ng h m new rem)
18077 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18078 (cond
18079 ((or (org-pos-in-match-range pos 2)
18080 (org-pos-in-match-range pos 3))
18081 (setq m (string-to-number (match-string 3 s))
18082 h (string-to-number (match-string 2 s)))
18083 (if (org-pos-in-match-range pos 2)
18084 (setq h (+ h n))
18085 (setq n (* dm (org-no-warnings (signum n))))
18086 (unless (= 0 (setq rem (% m dm)))
18087 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18088 (setq m (+ m n)))
18089 (when (< m 0) (setq m (+ m 60) h (1- h)))
18090 (when (> m 59) (setq m (- m 60) h (1+ h)))
18091 (setq h (mod h 24))
18092 (setq ng 1 new (format "-%02d:%02d" h m)))
18093 ((org-pos-in-match-range pos 6)
18094 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18095 ((org-pos-in-match-range pos 5)
18096 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18098 ((org-pos-in-match-range pos 9)
18099 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18100 ((org-pos-in-match-range pos 8)
18101 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18103 (when ng
18104 (setq s (concat
18105 (substring s 0 (match-beginning ng))
18107 (substring s (match-end ng))))))
18110 (defun org-recenter-calendar (d)
18111 "If the calendar is visible, recenter it to date D."
18112 (let ((cwin (get-buffer-window "*Calendar*" t)))
18113 (when cwin
18114 (let ((calendar-move-hook nil))
18115 (with-selected-window cwin
18116 (calendar-goto-date
18117 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18119 (defun org-goto-calendar (&optional arg)
18120 "Go to the Emacs calendar at the current date.
18121 If there is a time stamp in the current line, go to that date.
18122 A prefix ARG can be used to force the current date."
18123 (interactive "P")
18124 (let ((tsr org-ts-regexp) diff
18125 (calendar-move-hook nil)
18126 (calendar-view-holidays-initially-flag nil)
18127 (calendar-view-diary-initially-flag nil))
18128 (when (or (org-at-timestamp-p)
18129 (save-excursion
18130 (beginning-of-line 1)
18131 (looking-at (concat ".*" tsr))))
18132 (let ((d1 (time-to-days (current-time)))
18133 (d2 (time-to-days
18134 (org-time-string-to-time (match-string 1)))))
18135 (setq diff (- d2 d1))))
18136 (calendar)
18137 (calendar-goto-today)
18138 (when (and diff (not arg)) (calendar-forward-day diff))))
18140 (defun org-get-date-from-calendar ()
18141 "Return a list (month day year) of date at point in calendar."
18142 (with-current-buffer "*Calendar*"
18143 (save-match-data
18144 (calendar-cursor-to-date))))
18146 (defun org-date-from-calendar ()
18147 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18148 If there is already a time stamp at the cursor position, update it."
18149 (interactive)
18150 (if (org-at-timestamp-p t)
18151 (org-timestamp-change 0 'calendar)
18152 (let ((cal-date (org-get-date-from-calendar)))
18153 (org-insert-time-stamp
18154 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18156 (defcustom org-effort-durations
18157 `(("min" . 1)
18158 ("h" . 60)
18159 ("d" . ,(* 60 8))
18160 ("w" . ,(* 60 8 5))
18161 ("m" . ,(* 60 8 5 4))
18162 ("y" . ,(* 60 8 5 40)))
18163 "Conversion factor to minutes for an effort modifier.
18165 Each entry has the form (MODIFIER . MINUTES).
18167 In an effort string, a number followed by MODIFIER is multiplied
18168 by the specified number of MINUTES to obtain an effort in
18169 minutes.
18171 For example, if the value of this variable is ((\"hours\" . 60)), then an
18172 effort string \"2hours\" is equivalent to 120 minutes."
18173 :group 'org-agenda
18174 :version "25.1"
18175 :package-version '(Org . "8.3")
18176 :type '(alist :key-type (string :tag "Modifier")
18177 :value-type (number :tag "Minutes")))
18179 (defun org-minutes-to-clocksum-string (m)
18180 "Format number of minutes as a clocksum string.
18181 The format is determined by `org-time-clocksum-format',
18182 `org-time-clocksum-use-fractional' and
18183 `org-time-clocksum-fractional-format' and
18184 `org-time-clocksum-use-effort-durations'."
18185 (let ((clocksum "")
18186 (m (round m)) ; Don't allow fractions of minutes
18187 h d w mo y fmt n)
18188 (setq h (if org-time-clocksum-use-effort-durations
18189 (cdr (assoc "h" org-effort-durations)) 60)
18190 d (if org-time-clocksum-use-effort-durations
18191 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18192 w (if org-time-clocksum-use-effort-durations
18193 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18194 mo (if org-time-clocksum-use-effort-durations
18195 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18196 y (if org-time-clocksum-use-effort-durations
18197 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18198 ;; fractional format
18199 (if org-time-clocksum-use-fractional
18200 (cond
18201 ;; single format string
18202 ((stringp org-time-clocksum-fractional-format)
18203 (format org-time-clocksum-fractional-format (/ m (float h))))
18204 ;; choice of fractional formats for different time units
18205 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18206 (> (/ (truncate m) (* y d h)) 0))
18207 (format fmt (/ m (* y d (float h)))))
18208 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18209 (> (/ (truncate m) (* mo d h)) 0))
18210 (format fmt (/ m (* mo d (float h)))))
18211 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18212 (> (/ (truncate m) (* w d h)) 0))
18213 (format fmt (/ m (* w d (float h)))))
18214 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18215 (> (/ (truncate m) (* d h)) 0))
18216 (format fmt (/ m (* d (float h)))))
18217 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18218 (> (/ (truncate m) h) 0))
18219 (format fmt (/ m (float h))))
18220 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18221 (format fmt m))
18222 ;; fall back to smallest time unit with a format
18223 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18224 (format fmt (/ m (float h))))
18225 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18226 (format fmt (/ m (* d (float h)))))
18227 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18228 (format fmt (/ m (* w d (float h)))))
18229 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18230 (format fmt (/ m (* mo d (float h)))))
18231 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18232 (format fmt (/ m (* y d (float h))))))
18233 ;; standard (non-fractional) format, with single format string
18234 (if (stringp org-time-clocksum-format)
18235 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18236 ;; separate formats components
18237 (and (setq fmt (plist-get org-time-clocksum-format :years))
18238 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18239 (plist-get org-time-clocksum-format :require-years))
18240 (setq clocksum (concat clocksum (format fmt n))
18241 m (- m (* n y d h))))
18242 (and (setq fmt (plist-get org-time-clocksum-format :months))
18243 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18244 (plist-get org-time-clocksum-format :require-months))
18245 (setq clocksum (concat clocksum (format fmt n))
18246 m (- m (* n mo d h))))
18247 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18248 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18249 (plist-get org-time-clocksum-format :require-weeks))
18250 (setq clocksum (concat clocksum (format fmt n))
18251 m (- m (* n w d h))))
18252 (and (setq fmt (plist-get org-time-clocksum-format :days))
18253 (or (> (setq n (/ (truncate m) (* d h))) 0)
18254 (plist-get org-time-clocksum-format :require-days))
18255 (setq clocksum (concat clocksum (format fmt n))
18256 m (- m (* n d h))))
18257 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18258 (or (> (setq n (/ (truncate m) h)) 0)
18259 (plist-get org-time-clocksum-format :require-hours))
18260 (setq clocksum (concat clocksum (format fmt n))
18261 m (- m (* n h))))
18262 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18263 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18264 (setq clocksum (concat clocksum (format fmt m))))
18265 ;; return formatted time duration
18266 clocksum))))
18268 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18269 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18270 "Org mode version 8.0")
18272 (defun org-hours-to-clocksum-string (n)
18273 (org-minutes-to-clocksum-string (* n 60)))
18275 (defun org-hh:mm-string-to-minutes (s)
18276 "Convert a string H:MM to a number of minutes.
18277 If the string is just a number, interpret it as minutes.
18278 In fact, the first hh:mm or number in the string will be taken,
18279 there can be extra stuff in the string.
18280 If no number is found, the return value is 0."
18281 (cond
18282 ((integerp s) s)
18283 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18284 (+ (* (string-to-number (match-string 1 s)) 60)
18285 (string-to-number (match-string 2 s))))
18286 ((string-match "\\([0-9]+\\)" s)
18287 (string-to-number (match-string 1 s)))
18288 (t 0)))
18290 (defcustom org-image-actual-width t
18291 "Should we use the actual width of images when inlining them?
18293 When set to t, always use the image width.
18295 When set to a number, use imagemagick (when available) to set
18296 the image's width to this value.
18298 When set to a number in a list, try to get the width from any
18299 #+ATTR.* keyword if it matches a width specification like
18301 #+ATTR_HTML: :width 300px
18303 and fall back on that number if none is found.
18305 When set to nil, try to get the width from an #+ATTR.* keyword
18306 and fall back on the original width if none is found.
18308 This requires Emacs >= 24.1, build with imagemagick support."
18309 :group 'org-appearance
18310 :version "24.4"
18311 :package-version '(Org . "8.0")
18312 :type '(choice
18313 (const :tag "Use the image width" t)
18314 (integer :tag "Use a number of pixels")
18315 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18316 (const :tag "Use #+ATTR* or don't resize" nil)))
18318 (defcustom org-agenda-inhibit-startup nil
18319 "Inhibit startup when preparing agenda buffers.
18320 When this variable is t, the initialization of the Org agenda
18321 buffers is inhibited: e.g. the visibility state is not set, the
18322 tables are not re-aligned, etc."
18323 :type 'boolean
18324 :version "24.3"
18325 :group 'org-agenda)
18327 (define-obsolete-variable-alias
18328 'org-agenda-ignore-drawer-properties
18329 'org-agenda-ignore-properties "25.1")
18331 (defcustom org-agenda-ignore-properties nil
18332 "Avoid updating text properties when building the agenda.
18333 Properties are used to prepare buffers for effort estimates,
18334 appointments, statistics and subtree-local categories.
18335 If you don't use these in the agenda, you can add them to this
18336 list and agenda building will be a bit faster.
18337 The value is a list, with zero or more of the symbols `effort', `appt',
18338 `stats' or `category'."
18339 :type '(set :greedy t
18340 (const effort)
18341 (const appt)
18342 (const stats)
18343 (const category))
18344 :version "25.1"
18345 :package-version '(Org . "8.3")
18346 :group 'org-agenda)
18348 (defun org-duration-string-to-minutes (s &optional output-to-string)
18349 "Convert a duration string S to minutes.
18351 A bare number is interpreted as minutes, modifiers can be set by
18352 customizing `org-effort-durations' (which see).
18354 Entries containing a colon are interpreted as H:MM by
18355 `org-hh:mm-string-to-minutes'."
18356 (let ((result 0)
18357 (re (concat "\\([0-9.]+\\) *\\("
18358 (regexp-opt (mapcar 'car org-effort-durations))
18359 "\\)")))
18360 (while (string-match re s)
18361 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18362 (string-to-number (match-string 1 s))))
18363 (setq s (replace-match "" nil t s)))
18364 (setq result (floor result))
18365 (incf result (org-hh:mm-string-to-minutes s))
18366 (if output-to-string (number-to-string result) result)))
18368 ;;;; Files
18370 (defun org-save-all-org-buffers ()
18371 "Save all Org-mode buffers without user confirmation."
18372 (interactive)
18373 (message "Saving all Org-mode buffers...")
18374 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18375 (when (featurep 'org-id) (org-id-locations-save))
18376 (message "Saving all Org-mode buffers... done"))
18378 (defun org-revert-all-org-buffers ()
18379 "Revert all Org-mode buffers.
18380 Prompt for confirmation when there are unsaved changes.
18381 Be sure you know what you are doing before letting this function
18382 overwrite your changes.
18384 This function is useful in a setup where one tracks org files
18385 with a version control system, to revert on one machine after pulling
18386 changes from another. I believe the procedure must be like this:
18388 1. M-x org-save-all-org-buffers
18389 2. Pull changes from the other machine, resolve conflicts
18390 3. M-x org-revert-all-org-buffers"
18391 (interactive)
18392 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18393 (user-error "Abort"))
18394 (save-excursion
18395 (save-window-excursion
18396 (dolist (b (buffer-list))
18397 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18398 (with-current-buffer b buffer-file-name))
18399 (org-pop-to-buffer-same-window b)
18400 (revert-buffer t 'no-confirm)))
18401 (when (and (featurep 'org-id) org-id-track-globally)
18402 (org-id-locations-load)))))
18404 ;;;; Agenda files
18406 ;;;###autoload
18407 (defun org-switchb (&optional arg)
18408 "Switch between Org buffers.
18409 With one prefix argument, restrict available buffers to files.
18410 With two prefix arguments, restrict available buffers to agenda files.
18412 Defaults to `iswitchb' for buffer name completion.
18413 Set `org-completion-use-ido' to make it use ido instead."
18414 (interactive "P")
18415 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18416 ((equal arg '(16)) (org-buffer-list 'agenda))
18417 (t (org-buffer-list))))
18418 (org-completion-use-iswitchb org-completion-use-iswitchb)
18419 (org-completion-use-ido org-completion-use-ido))
18420 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18421 (setq org-completion-use-iswitchb t))
18422 (org-pop-to-buffer-same-window
18423 (completing-read "Org buffer: "
18424 (mapcar #'list (mapcar #'buffer-name blist))
18425 nil t))))
18427 ;;; Define some older names previously used for this functionality
18428 ;;;###autoload
18429 (defalias 'org-ido-switchb 'org-switchb)
18430 ;;;###autoload
18431 (defalias 'org-iswitchb 'org-switchb)
18433 (defun org-buffer-list (&optional predicate exclude-tmp)
18434 "Return a list of Org buffers.
18435 PREDICATE can be `export', `files' or `agenda'.
18437 export restrict the list to Export buffers.
18438 files restrict the list to buffers visiting Org files.
18439 agenda restrict the list to buffers visiting agenda files.
18441 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18442 (let* ((bfn nil)
18443 (agenda-files (and (eq predicate 'agenda)
18444 (mapcar 'file-truename (org-agenda-files t))))
18445 (filter
18446 (cond
18447 ((eq predicate 'files)
18448 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18449 ((eq predicate 'export)
18450 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18451 ((eq predicate 'agenda)
18452 (lambda (b)
18453 (with-current-buffer b
18454 (and (derived-mode-p 'org-mode)
18455 (setq bfn (buffer-file-name b))
18456 (member (file-truename bfn) agenda-files)))))
18457 (t (lambda (b) (with-current-buffer b
18458 (or (derived-mode-p 'org-mode)
18459 (string-match "\\*Org .*Export"
18460 (buffer-name b)))))))))
18461 (delq nil
18462 (mapcar
18463 (lambda(b)
18464 (if (and (funcall filter b)
18465 (or (not exclude-tmp)
18466 (not (string-match "tmp" (buffer-name b)))))
18468 nil))
18469 (buffer-list)))))
18471 (defun org-agenda-files (&optional unrestricted archives)
18472 "Get the list of agenda files.
18473 Optional UNRESTRICTED means return the full list even if a restriction
18474 is currently in place.
18475 When ARCHIVES is t, include all archive files that are really being
18476 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18477 `org-agenda-archives-mode' is t."
18478 (let ((files
18479 (cond
18480 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18481 ((stringp org-agenda-files) (org-read-agenda-file-list))
18482 ((listp org-agenda-files) org-agenda-files)
18483 (t (error "Invalid value of `org-agenda-files'")))))
18484 (setq files (apply 'append
18485 (mapcar (lambda (f)
18486 (if (file-directory-p f)
18487 (directory-files
18488 f t org-agenda-file-regexp)
18489 (list f)))
18490 files)))
18491 (when org-agenda-skip-unavailable-files
18492 (setq files (delq nil
18493 (mapcar (function
18494 (lambda (file)
18495 (and (file-readable-p file) file)))
18496 files))))
18497 (when (or (eq archives t)
18498 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18499 (setq files (org-add-archive-files files)))
18500 files))
18502 (defun org-agenda-file-p (&optional file)
18503 "Return non-nil, if FILE is an agenda file.
18504 If FILE is omitted, use the file associated with the current
18505 buffer."
18506 (let ((fname (or file (buffer-file-name))))
18507 (and fname
18508 (member (file-truename fname)
18509 (mapcar #'file-truename (org-agenda-files t))))))
18511 (defun org-edit-agenda-file-list ()
18512 "Edit the list of agenda files.
18513 Depending on setup, this either uses customize to edit the variable
18514 `org-agenda-files', or it visits the file that is holding the list. In the
18515 latter case, the buffer is set up in a way that saving it automatically kills
18516 the buffer and restores the previous window configuration."
18517 (interactive)
18518 (if (stringp org-agenda-files)
18519 (let ((cw (current-window-configuration)))
18520 (find-file org-agenda-files)
18521 (setq-local org-window-configuration cw)
18522 (org-add-hook 'after-save-hook
18523 (lambda ()
18524 (set-window-configuration
18525 (prog1 org-window-configuration
18526 (kill-buffer (current-buffer))))
18527 (org-install-agenda-files-menu)
18528 (message "New agenda file list installed"))
18529 nil 'local)
18530 (message "%s" (substitute-command-keys
18531 "Edit list and finish with \\[save-buffer]")))
18532 (customize-variable 'org-agenda-files)))
18534 (defun org-store-new-agenda-file-list (list)
18535 "Set new value for the agenda file list and save it correctly."
18536 (if (stringp org-agenda-files)
18537 (let ((fe (org-read-agenda-file-list t)) b u)
18538 (while (setq b (find-buffer-visiting org-agenda-files))
18539 (kill-buffer b))
18540 (with-temp-file org-agenda-files
18541 (insert
18542 (mapconcat
18543 (lambda (f) ;; Keep un-expanded entries.
18544 (if (setq u (assoc f fe))
18545 (cdr u)
18547 list "\n")
18548 "\n")))
18549 (let ((org-mode-hook nil) (org-inhibit-startup t)
18550 (org-insert-mode-line-in-empty-file nil))
18551 (setq org-agenda-files list)
18552 (customize-save-variable 'org-agenda-files org-agenda-files))))
18554 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18555 "Read the list of agenda files from a file.
18556 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18557 filenames, used by `org-store-new-agenda-file-list' to write back
18558 un-expanded file names."
18559 (when (file-directory-p org-agenda-files)
18560 (error "`org-agenda-files' cannot be a single directory"))
18561 (when (stringp org-agenda-files)
18562 (with-temp-buffer
18563 (insert-file-contents org-agenda-files)
18564 (mapcar
18565 (lambda (f)
18566 (let ((e (expand-file-name (substitute-in-file-name f)
18567 org-directory)))
18568 (if pair-with-expansion
18569 (cons e f)
18570 e)))
18571 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18573 ;;;###autoload
18574 (defun org-cycle-agenda-files ()
18575 "Cycle through the files in `org-agenda-files'.
18576 If the current buffer visits an agenda file, find the next one in the list.
18577 If the current buffer does not, find the first agenda file."
18578 (interactive)
18579 (let* ((fs (or (org-agenda-files t)
18580 (user-error "No agenda files")))
18581 (files (copy-sequence fs))
18582 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18583 file)
18584 (when tcf
18585 (while (and (setq file (pop files))
18586 (not (equal (file-truename file) tcf)))))
18587 (find-file (car (or files fs)))
18588 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18590 (defun org-agenda-file-to-front (&optional to-end)
18591 "Move/add the current file to the top of the agenda file list.
18592 If the file is not present in the list, it is added to the front. If it is
18593 present, it is moved there. With optional argument TO-END, add/move to the
18594 end of the list."
18595 (interactive "P")
18596 (let ((org-agenda-skip-unavailable-files nil)
18597 (file-alist (mapcar (lambda (x)
18598 (cons (file-truename x) x))
18599 (org-agenda-files t)))
18600 (ctf (file-truename
18601 (or buffer-file-name
18602 (user-error "Please save the current buffer to a file"))))
18603 x had)
18604 (setq x (assoc ctf file-alist) had x)
18606 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18607 (if to-end
18608 (setq file-alist (append (delq x file-alist) (list x)))
18609 (setq file-alist (cons x (delq x file-alist))))
18610 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18611 (org-install-agenda-files-menu)
18612 (message "File %s to %s of agenda file list"
18613 (if had "moved" "added") (if to-end "end" "front"))))
18615 (defun org-remove-file (&optional file)
18616 "Remove current file from the list of files in variable `org-agenda-files'.
18617 These are the files which are being checked for agenda entries.
18618 Optional argument FILE means use this file instead of the current."
18619 (interactive)
18620 (let* ((org-agenda-skip-unavailable-files nil)
18621 (file (or file buffer-file-name
18622 (user-error "Current buffer does not visit a file")))
18623 (true-file (file-truename file))
18624 (afile (abbreviate-file-name file))
18625 (files (delq nil (mapcar
18626 (lambda (x)
18627 (unless (equal true-file
18628 (file-truename x))
18630 (org-agenda-files t)))))
18631 (if (not (= (length files) (length (org-agenda-files t))))
18632 (progn
18633 (org-store-new-agenda-file-list files)
18634 (org-install-agenda-files-menu)
18635 (message "Removed from Org Agenda list: %s" afile))
18636 (message "File was not in list: %s (not removed)" afile))))
18638 (defun org-file-menu-entry (file)
18639 (vector file (list 'find-file file) t))
18641 (defun org-check-agenda-file (file)
18642 "Make sure FILE exists. If not, ask user what to do."
18643 (unless (file-exists-p file)
18644 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18645 (abbreviate-file-name file))
18646 (let ((r (downcase (read-char-exclusive))))
18647 (cond
18648 ((equal r ?r)
18649 (org-remove-file file)
18650 (throw 'nextfile t))
18651 (t (user-error "Abort"))))))
18653 (defun org-get-agenda-file-buffer (file)
18654 "Get an agenda buffer visiting FILE.
18655 If the buffer needs to be created, add it to the list of buffers
18656 which might be released later."
18657 (let ((buf (org-find-base-buffer-visiting file)))
18658 (if buf
18659 buf ; just return it
18660 ;; Make a new buffer and remember it
18661 (setq buf (find-file-noselect file))
18662 (when buf (push buf org-agenda-new-buffers))
18663 buf)))
18665 (defun org-release-buffers (blist)
18666 "Release all buffers in list, asking the user for confirmation when needed.
18667 When a buffer is unmodified, it is just killed. When modified, it is saved
18668 \(if the user agrees) and then killed."
18669 (let (file)
18670 (dolist (buf blist)
18671 (setq file (buffer-file-name buf))
18672 (when (and (buffer-modified-p buf)
18673 file
18674 (y-or-n-p (format "Save file %s? " file)))
18675 (with-current-buffer buf (save-buffer)))
18676 (kill-buffer buf))))
18678 (defun org-agenda-prepare-buffers (files)
18679 "Create buffers for all agenda files, protect archived trees and comments."
18680 (interactive)
18681 (let ((pa '(:org-archived t))
18682 (pc '(:org-comment t))
18683 (pall '(:org-archived t :org-comment t))
18684 (inhibit-read-only t)
18685 (org-inhibit-startup org-agenda-inhibit-startup)
18686 (rea (concat ":" org-archive-tag ":"))
18687 re pos)
18688 (setq org-tag-alist-for-agenda nil
18689 org-tag-groups-alist-for-agenda nil)
18690 (save-excursion
18691 (save-restriction
18692 (dolist (file files)
18693 (catch 'nextfile
18694 (if (bufferp file)
18695 (set-buffer file)
18696 (org-check-agenda-file file)
18697 (set-buffer (org-get-agenda-file-buffer file)))
18698 (widen)
18699 (org-set-regexps-and-options 'tags-only)
18700 (setq pos (point))
18701 (or (memq 'category org-agenda-ignore-properties)
18702 (org-refresh-category-properties))
18703 (or (memq 'stats org-agenda-ignore-properties)
18704 (org-refresh-stats-properties))
18705 (or (memq 'effort org-agenda-ignore-properties)
18706 (org-refresh-effort-properties))
18707 (or (memq 'appt org-agenda-ignore-properties)
18708 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18709 (setq org-todo-keywords-for-agenda
18710 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18711 (setq org-done-keywords-for-agenda
18712 (append org-done-keywords-for-agenda org-done-keywords))
18713 (setq org-todo-keyword-alist-for-agenda
18714 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18715 (setq org-tag-alist-for-agenda
18716 (org-uniquify
18717 (append org-tag-alist-for-agenda
18718 org-tag-alist
18719 org-tag-persistent-alist)))
18720 (when org-group-tags
18721 (setq org-tag-groups-alist-for-agenda
18722 (org-uniquify-alist
18723 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18724 (org-with-silent-modifications
18725 (save-excursion
18726 (remove-text-properties (point-min) (point-max) pall)
18727 (when org-agenda-skip-archived-trees
18728 (goto-char (point-min))
18729 (while (re-search-forward rea nil t)
18730 (when (org-at-heading-p t)
18731 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18732 (goto-char (point-min))
18733 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18734 (while (re-search-forward re nil t)
18735 (when (save-match-data (org-in-commented-heading-p t))
18736 (add-text-properties
18737 (match-beginning 0) (org-end-of-subtree t) pc)))))
18738 (goto-char pos)))))
18739 (setq org-todo-keywords-for-agenda
18740 (org-uniquify org-todo-keywords-for-agenda))
18741 (setq org-todo-keyword-alist-for-agenda
18742 (org-uniquify org-todo-keyword-alist-for-agenda))))
18745 ;;;; CDLaTeX minor mode
18747 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18748 "Keymap for the minor `org-cdlatex-mode'.")
18750 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18751 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18752 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18753 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18754 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18756 (defvar org-cdlatex-texmathp-advice-is-done nil
18757 "Flag remembering if we have applied the advice to texmathp already.")
18759 (define-minor-mode org-cdlatex-mode
18760 "Toggle the minor `org-cdlatex-mode'.
18761 This mode supports entering LaTeX environment and math in LaTeX fragments
18762 in Org-mode.
18763 \\{org-cdlatex-mode-map}"
18764 nil " OCDL" nil
18765 (when org-cdlatex-mode
18766 (require 'cdlatex)
18767 (run-hooks 'cdlatex-mode-hook)
18768 (cdlatex-compute-tables))
18769 (unless org-cdlatex-texmathp-advice-is-done
18770 (setq org-cdlatex-texmathp-advice-is-done t)
18771 (defadvice texmathp (around org-math-always-on activate)
18772 "Always return t in org-mode buffers.
18773 This is because we want to insert math symbols without dollars even outside
18774 the LaTeX math segments. If Orgmode thinks that point is actually inside
18775 an embedded LaTeX fragment, let texmathp do its job.
18776 \\[org-cdlatex-mode-map]"
18777 (interactive)
18778 (let (p)
18779 (cond
18780 ((not (derived-mode-p 'org-mode)) ad-do-it)
18781 ((eq this-command 'cdlatex-math-symbol)
18782 (setq ad-return-value t
18783 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18785 (let ((p (org-inside-LaTeX-fragment-p)))
18786 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18787 (setq ad-return-value t
18788 texmathp-why '("Org-mode embedded math" . 0))
18789 (when p ad-do-it)))))))))
18791 (defun turn-on-org-cdlatex ()
18792 "Unconditionally turn on `org-cdlatex-mode'."
18793 (org-cdlatex-mode 1))
18795 (defun org-try-cdlatex-tab ()
18796 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18797 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18798 - inside a LaTeX fragment, or
18799 - after the first word in a line, where an abbreviation expansion could
18800 insert a LaTeX environment."
18801 (when org-cdlatex-mode
18802 (cond
18803 ;; Before any word on the line: No expansion possible.
18804 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18805 ;; Just after first word on the line: Expand it. Make sure it
18806 ;; cannot happen on headlines, though.
18807 ((save-excursion
18808 (skip-chars-backward "a-zA-Z0-9*")
18809 (skip-chars-backward " \t")
18810 (and (bolp) (not (org-at-heading-p))))
18811 (cdlatex-tab) t)
18812 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18814 (defun org-cdlatex-underscore-caret (&optional _arg)
18815 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18816 Revert to the normal definition outside of these fragments."
18817 (interactive "P")
18818 (if (org-inside-LaTeX-fragment-p)
18819 (call-interactively 'cdlatex-sub-superscript)
18820 (let (org-cdlatex-mode)
18821 (call-interactively (key-binding (vector last-input-event))))))
18823 (defun org-cdlatex-math-modify (&optional _arg)
18824 "Execute `cdlatex-math-modify' in LaTeX fragments.
18825 Revert to the normal definition outside of these fragments."
18826 (interactive "P")
18827 (if (org-inside-LaTeX-fragment-p)
18828 (call-interactively 'cdlatex-math-modify)
18829 (let (org-cdlatex-mode)
18830 (call-interactively (key-binding (vector last-input-event))))))
18832 (defun org-cdlatex-environment-indent (&optional environment item)
18833 "Execute `cdlatex-environment' and indent the inserted environment.
18835 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18837 The inserted environment is indented to current indentation
18838 unless point is at the beginning of the line, in which the
18839 environment remains unintended."
18840 (interactive)
18841 ;; cdlatex-environment always return nil. Therefore, capture output
18842 ;; first and determine if an environment was selected.
18843 (let* ((beg (point-marker))
18844 (end (copy-marker (point) t))
18845 (inserted (progn
18846 (ignore-errors (cdlatex-environment environment item))
18847 (< beg end)))
18848 ;; Figure out how many lines to move forward after the
18849 ;; environment has been inserted.
18850 (lines (when inserted
18851 (save-excursion
18852 (- (loop while (< beg (point))
18853 with x = 0
18854 do (forward-line -1)
18855 (incf x)
18856 finally return x)
18857 (if (progn (goto-char beg)
18858 (and (progn (skip-chars-forward " \t") (eolp))
18859 (progn (skip-chars-backward " \t") (bolp))))
18860 1 0)))))
18861 (env (org-trim (delete-and-extract-region beg end))))
18862 (when inserted
18863 ;; Get indentation of next line unless at column 0.
18864 (let ((ind (if (bolp) 0
18865 (save-excursion
18866 (org-return-indent)
18867 (prog1 (org-get-indentation)
18868 (when (progn (skip-chars-forward " \t") (eolp))
18869 (delete-region beg (point)))))))
18870 (bol (progn (skip-chars-backward " \t") (bolp))))
18871 ;; Insert a newline before environment unless at column zero
18872 ;; to "escape" the current line. Insert a newline if
18873 ;; something is one the same line as \end{ENVIRONMENT}.
18874 (insert
18875 (concat (unless bol "\n") env
18876 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18877 (unless (zerop ind)
18878 (save-excursion
18879 (goto-char beg)
18880 (while (< (point) end)
18881 (unless (eolp) (org-indent-line-to ind))
18882 (forward-line))))
18883 (goto-char beg)
18884 (forward-line lines)
18885 (org-indent-line-to ind)))
18886 (set-marker beg nil)
18887 (set-marker end nil)))
18890 ;;;; LaTeX fragments
18892 (defun org-inside-LaTeX-fragment-p ()
18893 "Test if point is inside a LaTeX fragment.
18894 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18895 sequence appearing also before point.
18896 Even though the matchers for math are configurable, this function assumes
18897 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18898 delimiters are skipped when they have been removed by customization.
18899 The return value is nil, or a cons cell with the delimiter and the
18900 position of this delimiter.
18902 This function does a reasonably good job, but can locally be fooled by
18903 for example currency specifications. For example it will assume being in
18904 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18905 fragments that are properly closed, but during editing, we have to live
18906 with the uncertainty caused by missing closing delimiters. This function
18907 looks only before point, not after."
18908 (catch 'exit
18909 (let ((pos (point))
18910 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18911 (lim (progn
18912 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18913 (point)))
18914 dd-on str (start 0) m re)
18915 (goto-char pos)
18916 (when dodollar
18917 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18918 re (nth 1 (assoc "$" org-latex-regexps)))
18919 (while (string-match re str start)
18920 (cond
18921 ((= (match-end 0) (length str))
18922 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18923 ((= (match-end 0) (- (length str) 5))
18924 (throw 'exit nil))
18925 (t (setq start (match-end 0))))))
18926 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18927 (goto-char pos)
18928 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18929 (and (match-beginning 2) (throw 'exit nil))
18930 ;; count $$
18931 (while (re-search-backward "\\$\\$" lim t)
18932 (setq dd-on (not dd-on)))
18933 (goto-char pos)
18934 (when dd-on (cons "$$" m))))))
18936 (defun org-inside-latex-macro-p ()
18937 "Is point inside a LaTeX macro or its arguments?"
18938 (save-match-data
18939 (org-in-regexp
18940 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18942 (defvar-local org-latex-fragment-image-overlays nil
18943 "List of overlays carrying the images of latex fragments.")
18945 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18946 "Remove all overlays with LaTeX fragment images in current buffer.
18947 When optional arguments BEG and END are non-nil, remove all
18948 overlays between them instead. Return t when some overlays were
18949 removed, nil otherwise."
18950 (let (removedp)
18951 (setq org-latex-fragment-image-overlays
18952 (let ((beg (or beg (point-min)))
18953 (end (or end (point-max))))
18954 (cl-remove-if
18955 (lambda (o)
18956 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18957 ((and (>= (overlay-start o) beg)
18958 (<= (overlay-end o) end))
18959 (delete-overlay o)
18960 (unless removedp (setq removedp t)))
18961 (t nil)))
18962 org-latex-fragment-image-overlays)))
18963 removedp))
18965 (define-obsolete-function-alias
18966 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18967 (defun org-toggle-latex-fragment (&optional arg)
18968 "Preview the LaTeX fragment at point, or all locally or globally.
18970 If the cursor is on a LaTeX fragment, create the image and overlay
18971 it over the source code, if there is none. Remove it otherwise.
18972 If there is no fragment at point, display all fragments in the
18973 current section.
18975 With prefix ARG, preview or clear image for all fragments in the
18976 current subtree or in the whole buffer when used before the first
18977 headline. With a double prefix ARG \\[universal-argument] \
18978 \\[universal-argument] preview or clear images
18979 for all fragments in the buffer."
18980 (interactive "P")
18981 (unless (buffer-file-name (buffer-base-buffer))
18982 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18983 (when (display-graphic-p)
18984 (catch 'exit
18985 (save-excursion
18986 (let ((window-start (window-start)) msg)
18987 (save-restriction
18988 (cond
18989 ((or (equal arg '(16))
18990 (and (equal arg '(4))
18991 (org-with-limited-levels (org-before-first-heading-p))))
18992 (if (org-remove-latex-fragment-image-overlays)
18993 (progn (message "LaTeX fragments images removed from buffer")
18994 (throw 'exit nil))
18995 (setq msg "Creating images for buffer...")))
18996 ((equal arg '(4))
18997 (org-with-limited-levels (org-back-to-heading t))
18998 (let ((beg (point))
18999 (end (progn (org-end-of-subtree t) (point))))
19000 (if (org-remove-latex-fragment-image-overlays beg end)
19001 (progn
19002 (message "LaTeX fragment images removed from subtree")
19003 (throw 'exit nil))
19004 (setq msg "Creating images for subtree...")
19005 (narrow-to-region beg end))))
19006 ((let ((datum (org-element-context)))
19007 (when (memq (org-element-type datum)
19008 '(latex-environment latex-fragment))
19009 (let* ((beg (org-element-property :begin datum))
19010 (end (org-element-property :end datum)))
19011 (if (org-remove-latex-fragment-image-overlays beg end)
19012 (progn (message "LaTeX fragment image removed")
19013 (throw 'exit nil))
19014 (narrow-to-region beg end)
19015 (setq msg "Creating image..."))))))
19017 (org-with-limited-levels
19018 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19019 (outline-previous-heading)
19020 (point)))
19021 (end (progn (outline-next-heading) (point))))
19022 (if (org-remove-latex-fragment-image-overlays beg end)
19023 (progn
19024 (message "LaTeX fragment images removed from section")
19025 (throw 'exit nil))
19026 (setq msg "Creating images for section...")
19027 (narrow-to-region beg end))))))
19028 (let ((file (buffer-file-name (buffer-base-buffer))))
19029 (org-format-latex
19030 (concat org-latex-preview-ltxpng-directory
19031 (file-name-sans-extension (file-name-nondirectory file)))
19032 ;; Emacs cannot overlay images from remote hosts.
19033 ;; Create it in `temporary-file-directory' instead.
19034 (if (file-remote-p file) temporary-file-directory
19035 default-directory)
19036 'overlays msg 'forbuffer
19037 org-latex-create-formula-image-program)))
19038 ;; Work around a bug that doesn't restore window's start
19039 ;; when widening back the buffer.
19040 (set-window-start nil window-start)
19041 (message (concat msg "done")))))))
19043 (defun org-format-latex
19044 (prefix &optional dir overlays msg forbuffer processing-type)
19045 "Replace LaTeX fragments with links to an image, and produce images.
19047 When optional argument OVERLAYS is non-nil, display the image on
19048 top of the fragment instead of replacing it.
19050 PROCESSING-TYPE is the conversion method to use, as a symbol.
19052 Some of the options can be changed using the variable
19053 `org-format-latex-options', which see."
19054 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19055 (unless (eq processing-type 'verbatim)
19056 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19057 (cnt 0)
19058 checkdir-flag)
19059 (goto-char (point-min))
19060 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19061 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19062 (overlay-recenter (point-max)))
19063 (while (re-search-forward math-regexp nil t)
19064 (unless (and overlays
19065 (eq (get-char-property (point) 'org-overlay-type)
19066 'org-latex-overlay))
19067 (let* ((context (org-element-context))
19068 (type (org-element-type context)))
19069 (when (memq type '(latex-environment latex-fragment))
19070 (let ((block-type (eq type 'latex-environment))
19071 (value (org-element-property :value context))
19072 (beg (org-element-property :begin context))
19073 (end (save-excursion
19074 (goto-char (org-element-property :end context))
19075 (skip-chars-backward " \r\t\n")
19076 (point))))
19077 (case processing-type
19078 (mathjax
19079 ;; Prepare for MathJax processing.
19080 (if (eq (char-after beg) ?$)
19081 (save-excursion
19082 (delete-region beg end)
19083 (insert "\\(" (substring value 1 -1) "\\)"))
19084 (goto-char end)))
19085 ((dvipng imagemagick)
19086 ;; Process to an image.
19087 (incf cnt)
19088 (goto-char beg)
19089 (let* ((face (face-at-point))
19090 ;; Get the colors from the face at point.
19092 (let ((color (plist-get org-format-latex-options
19093 :foreground)))
19094 (if (and forbuffer (eq color 'auto))
19095 (face-attribute face :foreground nil 'default)
19096 color)))
19098 (let ((color (plist-get org-format-latex-options
19099 :background)))
19100 (if (and forbuffer (eq color 'auto))
19101 (face-attribute face :background nil 'default)
19102 color)))
19103 (hash (sha1 (prin1-to-string
19104 (list org-format-latex-header
19105 org-latex-default-packages-alist
19106 org-latex-packages-alist
19107 org-format-latex-options
19108 forbuffer value fg bg))))
19109 (absprefix (expand-file-name prefix dir))
19110 (linkfile (format "%s_%s.png" prefix hash))
19111 (movefile (format "%s_%s.png" absprefix hash))
19112 (sep (and block-type "\n\n"))
19113 (link (concat sep "[[file:" linkfile "]]" sep))
19114 (options
19115 (org-combine-plists
19116 org-format-latex-options
19117 `(:foreground ,fg :background ,bg))))
19118 (when msg (message msg cnt))
19119 (unless checkdir-flag ; Ensure the directory exists.
19120 (setq checkdir-flag t)
19121 (let ((todir (file-name-directory absprefix)))
19122 (unless (file-directory-p todir)
19123 (make-directory todir t))))
19124 (unless (file-exists-p movefile)
19125 (org-create-formula-image
19126 value movefile options forbuffer processing-type))
19127 (if overlays
19128 (progn
19129 (dolist (o (overlays-in beg end))
19130 (when (eq (overlay-get o 'org-overlay-type)
19131 'org-latex-overlay)
19132 (delete-overlay o)))
19133 (let ((ov (make-overlay beg end)))
19134 (overlay-put ov
19135 'org-overlay-type
19136 'org-latex-overlay)
19137 (overlay-put ov 'evaporate t)
19138 (if (featurep 'xemacs)
19139 (progn
19140 (overlay-put ov 'invisible t)
19141 (overlay-put
19142 ov 'end-glyph
19143 (make-glyph
19144 (vector 'png :file movefile))))
19145 (overlay-put
19146 ov 'display
19147 (list 'image
19148 :type 'png
19149 :file movefile
19150 :ascent 'center)))
19151 (push ov org-latex-fragment-image-overlays))
19152 (goto-char end))
19153 (delete-region beg end)
19154 (insert
19155 (org-add-props link
19156 (list 'org-latex-src
19157 (replace-regexp-in-string "\"" "" value)
19158 'org-latex-src-embed-type
19159 (if block-type 'paragraph 'character)))))))
19160 (mathml
19161 ;; Process to MathML.
19162 (unless (org-format-latex-mathml-available-p)
19163 (user-error "LaTeX to MathML converter not configured"))
19164 (incf cnt)
19165 (when msg (message msg cnt))
19166 (goto-char beg)
19167 (delete-region beg end)
19168 (insert (org-format-latex-as-mathml
19169 value block-type prefix dir)))
19170 (otherwise
19171 (error "Unknown conversion type %s for LaTeX fragments"
19172 processing-type)))))))))))
19174 (defun org-create-math-formula (latex-frag &optional mathml-file)
19175 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19176 Use `org-latex-to-mathml-convert-command'. If the conversion is
19177 sucessful, return the portion between \"<math...> </math>\"
19178 elements otherwise return nil. When MATHML-FILE is specified,
19179 write the results in to that file. When invoked as an
19180 interactive command, prompt for LATEX-FRAG, with initial value
19181 set to the current active region and echo the results for user
19182 inspection."
19183 (interactive (list (let ((frag (when (org-region-active-p)
19184 (buffer-substring-no-properties
19185 (region-beginning) (region-end)))))
19186 (read-string "LaTeX Fragment: " frag nil frag))))
19187 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19188 (let* ((tmp-in-file
19189 (let ((file (file-relative-name
19190 (make-temp-name (expand-file-name "ltxmathml-in")))))
19191 (write-region latex-frag nil file)
19192 file))
19193 (tmp-out-file (file-relative-name
19194 (make-temp-name (expand-file-name "ltxmathml-out"))))
19195 (cmd (format-spec
19196 org-latex-to-mathml-convert-command
19197 `((?j . ,(and org-latex-to-mathml-jar-file
19198 (shell-quote-argument
19199 (expand-file-name
19200 org-latex-to-mathml-jar-file))))
19201 (?I . ,(shell-quote-argument tmp-in-file))
19202 (?i . ,latex-frag)
19203 (?o . ,(shell-quote-argument tmp-out-file)))))
19204 mathml shell-command-output)
19205 (when (org-called-interactively-p 'any)
19206 (unless (org-format-latex-mathml-available-p)
19207 (user-error "LaTeX to MathML converter not configured")))
19208 (message "Running %s" cmd)
19209 (setq shell-command-output (shell-command-to-string cmd))
19210 (setq mathml
19211 (when (file-readable-p tmp-out-file)
19212 (with-current-buffer (find-file-noselect tmp-out-file t)
19213 (goto-char (point-min))
19214 (when (re-search-forward
19215 (concat
19216 (regexp-quote
19217 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19218 "[^>]*?>"
19219 "\\(.\\|\n\\)*"
19220 "</math>")
19221 nil t)
19222 (prog1 (match-string 0) (kill-buffer))))))
19223 (cond
19224 (mathml
19225 (setq mathml
19226 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19227 (when mathml-file
19228 (write-region mathml nil mathml-file))
19229 (when (org-called-interactively-p 'any)
19230 (message mathml)))
19231 ((message "LaTeX to MathML conversion failed")
19232 (message shell-command-output)))
19233 (delete-file tmp-in-file)
19234 (when (file-exists-p tmp-out-file)
19235 (delete-file tmp-out-file))
19236 mathml))
19238 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19239 prefix &optional dir)
19240 "Use `org-create-math-formula' but check local cache first."
19241 (let* ((absprefix (expand-file-name prefix dir))
19242 (print-length nil) (print-level nil)
19243 (formula-id (concat
19244 "formula-"
19245 (sha1
19246 (prin1-to-string
19247 (list latex-frag
19248 org-latex-to-mathml-convert-command)))))
19249 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19250 (formula-cache-dir (file-name-directory formula-cache)))
19252 (unless (file-directory-p formula-cache-dir)
19253 (make-directory formula-cache-dir t))
19255 (unless (file-exists-p formula-cache)
19256 (org-create-math-formula latex-frag formula-cache))
19258 (if (file-exists-p formula-cache)
19259 ;; Successful conversion. Return the link to MathML file.
19260 (org-add-props
19261 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19262 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19263 'org-latex-src-embed-type (if latex-frag-type
19264 'paragraph 'character)))
19265 ;; Failed conversion. Return the LaTeX fragment verbatim
19266 latex-frag)))
19268 (defun org-create-formula-image (string tofile options buffer &optional type)
19269 "Create an image from LaTeX source using dvipng or convert.
19270 This function calls either `org-create-formula-image-with-dvipng'
19271 or `org-create-formula-image-with-imagemagick' depending on the
19272 value of `org-latex-create-formula-image-program' or on the value
19273 of the optional TYPE variable.
19275 Note: ultimately these two function should be combined as they
19276 share a good deal of logic."
19277 (org-check-external-command
19278 "latex" "needed to convert LaTeX fragments to images")
19279 (funcall
19280 (case (or type org-latex-create-formula-image-program)
19281 (dvipng
19282 (org-check-external-command
19283 "dvipng" "needed to convert LaTeX fragments to images")
19284 #'org-create-formula-image-with-dvipng)
19285 (imagemagick
19286 (org-check-external-command
19287 "convert" "you need to install imagemagick")
19288 #'org-create-formula-image-with-imagemagick)
19289 (t (error
19290 "Invalid value of `org-latex-create-formula-image-program'")))
19291 string tofile options buffer))
19293 (declare-function org-export-get-backend "ox" (name))
19294 (declare-function org-export--get-global-options "ox" (&optional backend))
19295 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19296 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19297 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19298 (defun org-create-formula--latex-header ()
19299 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19300 (let ((info (org-combine-plists (org-export--get-global-options
19301 (org-export-get-backend 'latex))
19302 (org-export--get-inbuffer-options
19303 (org-export-get-backend 'latex)))))
19304 (org-latex-guess-babel-language
19305 (org-latex-guess-inputenc
19306 (org-splice-latex-header
19307 org-format-latex-header
19308 org-latex-default-packages-alist
19309 org-latex-packages-alist t
19310 (plist-get info :latex-header)))
19311 info)))
19313 (defun org--get-display-dpi ()
19314 "Get the DPI of the display.
19316 Assumes that the display has the same pixel width in the
19317 horizontal and vertical directions."
19318 (if (display-graphic-p)
19319 (round (/ (display-pixel-height)
19320 (/ (display-mm-height) 25.4)))
19321 (error "Attempt to calculate the dpi of a non-graphic display")))
19323 ;; This function borrows from Ganesh Swami's latex2png.el
19324 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19325 "This calls dvipng."
19326 (require 'ox-latex)
19327 (let* ((tmpdir (if (featurep 'xemacs)
19328 (temp-directory)
19329 temporary-file-directory))
19330 (texfilebase (make-temp-name
19331 (expand-file-name "orgtex" tmpdir)))
19332 (texfile (concat texfilebase ".tex"))
19333 (dvifile (concat texfilebase ".dvi"))
19334 (pngfile (concat texfilebase ".png"))
19335 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19336 ;; This assumes that the display has the same pixel width in
19337 ;; the horizontal and vertical directions
19338 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19339 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19340 "Black"))
19341 (bg (or (plist-get options (if buffer :background :html-background))
19342 "Transparent")))
19343 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19344 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19345 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19346 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19347 (let ((latex-header (org-create-formula--latex-header)))
19348 (with-temp-file texfile
19349 (insert latex-header)
19350 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19351 (let ((dir default-directory))
19352 (ignore-errors
19353 (cd tmpdir)
19354 (call-process "latex" nil nil nil texfile))
19355 (cd dir))
19356 (if (not (file-exists-p dvifile))
19357 (progn (message "Failed to create dvi file from %s" texfile) nil)
19358 (ignore-errors
19359 (if (featurep 'xemacs)
19360 (call-process "dvipng" nil nil nil
19361 "-fg" fg "-bg" bg
19362 "-T" "tight"
19363 "-o" pngfile
19364 dvifile)
19365 (call-process "dvipng" nil nil nil
19366 "-fg" fg "-bg" bg
19367 "-D" dpi
19368 ;;"-x" scale "-y" scale
19369 "-T" "tight"
19370 "-o" pngfile
19371 dvifile)))
19372 (if (not (file-exists-p pngfile))
19373 (if org-format-latex-signal-error
19374 (error "Failed to create png file from %s" texfile)
19375 (message "Failed to create png file from %s" texfile)
19376 nil)
19377 ;; Use the requested file name and clean up
19378 (copy-file pngfile tofile 'replace)
19379 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19380 (when (file-exists-p (concat texfilebase e))
19381 (delete-file (concat texfilebase e))))
19382 pngfile))))
19384 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19385 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19386 "This calls convert, which is included into imagemagick."
19387 (require 'ox-latex)
19388 (let* ((tmpdir (if (featurep 'xemacs)
19389 (temp-directory)
19390 temporary-file-directory))
19391 (texfilebase (make-temp-name
19392 (expand-file-name "orgtex" tmpdir)))
19393 (texfile (concat texfilebase ".tex"))
19394 (pdffile (concat texfilebase ".pdf"))
19395 (pngfile (concat texfilebase ".png"))
19396 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19397 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19398 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19399 "black"))
19400 (bg (or (plist-get options (if buffer :background :html-background))
19401 "white")))
19402 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19403 (setq fg (org-latex-color-format fg)))
19404 (if (eq bg 'default) (setq bg (org-latex-color :background))
19405 (setq bg (org-latex-color-format
19406 (if (string= bg "Transparent") "white" bg))))
19407 (let ((latex-header (org-create-formula--latex-header)))
19408 (with-temp-file texfile
19409 (insert latex-header)
19410 (insert "\n\\begin{document}\n"
19411 "\\definecolor{fg}{rgb}{" fg "}\n"
19412 "\\definecolor{bg}{rgb}{" bg "}\n"
19413 "\n\\pagecolor{bg}\n"
19414 "\n{\\color{fg}\n"
19415 string
19416 "\n}\n"
19417 "\n\\end{document}\n")))
19418 (org-latex-compile texfile t)
19419 (if (not (file-exists-p pdffile))
19420 (progn (message "Failed to create pdf file from %s" texfile) nil)
19421 (ignore-errors
19422 (if (featurep 'xemacs)
19423 (call-process "convert" nil nil nil
19424 "-density" "96"
19425 "-trim"
19426 "-antialias"
19427 pdffile
19428 "-quality" "100"
19429 ;; "-sharpen" "0x1.0"
19430 pngfile)
19431 (call-process "convert" nil nil nil
19432 "-density" dpi
19433 "-trim"
19434 "-antialias"
19435 pdffile
19436 "-quality" "100"
19437 ;; "-sharpen" "0x1.0"
19438 pngfile)))
19439 (if (not (file-exists-p pngfile))
19440 (if org-format-latex-signal-error
19441 (error "Failed to create png file from %s" texfile)
19442 (message "Failed to create png file from %s" texfile)
19443 nil)
19444 ;; Use the requested file name and clean up
19445 (copy-file pngfile tofile 'replace)
19446 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19447 (when (file-exists-p (concat texfilebase e))
19448 (delete-file (concat texfilebase e))))
19449 pngfile))))
19451 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19452 "Fill a LaTeX header template TPL.
19453 In the template, the following place holders will be recognized:
19455 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19456 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19457 [PACKAGES] \\usepackage statements for PKG
19458 [NO-PACKAGES] do not include PKG
19459 [EXTRA] the string EXTRA
19460 [NO-EXTRA] do not include EXTRA
19462 For backward compatibility, if both the positive and the negative place
19463 holder is missing, the positive one (without the \"NO-\") will be
19464 assumed to be present at the end of the template.
19465 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19466 EXTRA is a string.
19467 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19468 (let (rpl (end ""))
19469 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19470 (setq rpl (if (or (match-end 1) (not def-pkg))
19471 "" (org-latex-packages-to-string def-pkg snippets-p t))
19472 tpl (replace-match rpl t t tpl))
19473 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19475 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19476 (setq rpl (if (or (match-end 1) (not pkg))
19477 "" (org-latex-packages-to-string pkg snippets-p t))
19478 tpl (replace-match rpl t t tpl))
19479 (when pkg (setq end
19480 (concat end "\n"
19481 (org-latex-packages-to-string pkg snippets-p)))))
19483 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19484 (setq rpl (if (or (match-end 1) (not extra))
19485 "" (concat extra "\n"))
19486 tpl (replace-match rpl t t tpl))
19487 (when (and extra (string-match "\\S-" extra))
19488 (setq end (concat end "\n" extra))))
19490 (if (string-match "\\S-" end)
19491 (concat tpl "\n" end)
19492 tpl)))
19494 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19495 "Turn an alist of packages into a string with the \\usepackage macros."
19496 (setq pkg (mapconcat (lambda(p)
19497 (cond
19498 ((stringp p) p)
19499 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19500 (format "%% Package %s omitted" (cadr p)))
19501 ((equal "" (car p))
19502 (format "\\usepackage{%s}" (cadr p)))
19504 (format "\\usepackage[%s]{%s}"
19505 (car p) (cadr p)))))
19507 "\n"))
19508 (if newline (concat pkg "\n") pkg))
19510 (defun org-dvipng-color (attr)
19511 "Return a RGB color specification for dvipng."
19512 (apply 'format "rgb %s %s %s"
19513 (mapcar 'org-normalize-color
19514 (if (featurep 'xemacs)
19515 (color-rgb-components
19516 (face-property 'default
19517 (cond ((eq attr :foreground) 'foreground)
19518 ((eq attr :background) 'background))))
19519 (color-values (face-attribute 'default attr nil))))))
19521 (defun org-dvipng-color-format (color-name)
19522 "Convert COLOR-NAME to a RGB color value for dvipng."
19523 (apply 'format "rgb %s %s %s"
19524 (mapcar 'org-normalize-color
19525 (color-values color-name))))
19527 (defun org-latex-color (attr)
19528 "Return a RGB color for the LaTeX color package."
19529 (apply 'format "%s,%s,%s"
19530 (mapcar 'org-normalize-color
19531 (if (featurep 'xemacs)
19532 (color-rgb-components
19533 (face-property 'default
19534 (cond ((eq attr :foreground) 'foreground)
19535 ((eq attr :background) 'background))))
19536 (color-values (face-attribute 'default attr nil))))))
19538 (defun org-latex-color-format (color-name)
19539 "Convert COLOR-NAME to a RGB color value."
19540 (apply 'format "%s,%s,%s"
19541 (mapcar 'org-normalize-color
19542 (color-values color-name))))
19544 (defun org-normalize-color (value)
19545 "Return string to be used as color value for an RGB component."
19546 (format "%g" (/ value 65535.0)))
19550 ;; Image display
19552 (defvar-local org-inline-image-overlays nil)
19554 (defun org-toggle-inline-images (&optional include-linked)
19555 "Toggle the display of inline images.
19556 INCLUDE-LINKED is passed to `org-display-inline-images'."
19557 (interactive "P")
19558 (if org-inline-image-overlays
19559 (progn
19560 (org-remove-inline-images)
19561 (when (org-called-interactively-p 'interactive)
19562 (message "Inline image display turned off")))
19563 (org-display-inline-images include-linked)
19564 (when (org-called-interactively-p 'interactive)
19565 (message (if org-inline-image-overlays
19566 (format "%d images displayed inline"
19567 (length org-inline-image-overlays))
19568 "No images to display inline")))))
19570 (defun org-redisplay-inline-images ()
19571 "Refresh the display of inline images."
19572 (interactive)
19573 (if (not org-inline-image-overlays)
19574 (org-toggle-inline-images)
19575 (org-toggle-inline-images)
19576 (org-toggle-inline-images)))
19578 (defun org-display-inline-images (&optional include-linked refresh beg end)
19579 "Display inline images.
19581 An inline image is a link which follows either of these
19582 conventions:
19584 1. Its path is a file with an extension matching return value
19585 from `image-file-name-regexp' and it has no contents.
19587 2. Its description consists in a single link of the previous
19588 type.
19590 When optional argument INCLUDE-LINKED is non-nil, also links with
19591 a text description part will be inlined. This can be nice for
19592 a quick look at those images, but it does not reflect what
19593 exported files will look like.
19595 When optional argument REFRESH is non-nil, refresh existing
19596 images between BEG and END. This will create new image displays
19597 only if necessary. BEG and END default to the buffer
19598 boundaries."
19599 (interactive "P")
19600 (when (display-graphic-p)
19601 (unless refresh
19602 (org-remove-inline-images)
19603 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19604 (org-with-wide-buffer
19605 (goto-char (or beg (point-min)))
19606 (let ((case-fold-search t)
19607 (file-extension-re (image-file-name-regexp)))
19608 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19609 (let ((link (save-match-data (org-element-context))))
19610 ;; Check if we're at an inline image.
19611 (when (and (equal (org-element-property :type link) "file")
19612 (or include-linked
19613 (not (org-element-property :contents-begin link)))
19614 (let ((parent (org-element-property :parent link)))
19615 (or (not (eq (org-element-type parent) 'link))
19616 (not (cdr (org-element-contents parent)))))
19617 (org-string-match-p file-extension-re
19618 (org-element-property :path link)))
19619 (let ((file (expand-file-name
19620 (org-link-unescape
19621 (org-element-property :path link)))))
19622 (when (file-exists-p file)
19623 (let ((width
19624 ;; Apply `org-image-actual-width' specifications.
19625 (cond
19626 ((not (image-type-available-p 'imagemagick)) nil)
19627 ((eq org-image-actual-width t) nil)
19628 ((listp org-image-actual-width)
19630 ;; First try to find a width among
19631 ;; attributes associated to the paragraph
19632 ;; containing link.
19633 (let ((paragraph
19634 (let ((e link))
19635 (while (and (setq e (org-element-property
19636 :parent e))
19637 (not (eq (org-element-type e)
19638 'paragraph))))
19639 e)))
19640 (when paragraph
19641 (save-excursion
19642 (goto-char (org-element-property :begin paragraph))
19643 (when
19644 (re-search-forward
19645 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19646 (org-element-property
19647 :post-affiliated paragraph)
19649 (string-to-number (match-string 1))))))
19650 ;; Otherwise, fall-back to provided number.
19651 (car org-image-actual-width)))
19652 ((numberp org-image-actual-width)
19653 org-image-actual-width)))
19654 (old (get-char-property-and-overlay
19655 (org-element-property :begin link)
19656 'org-image-overlay)))
19657 (if (and (car-safe old) refresh)
19658 (image-refresh (overlay-get (cdr old) 'display))
19659 (let ((image (create-image file
19660 (and width 'imagemagick)
19662 :width width)))
19663 (when image
19664 (let* ((link
19665 ;; If inline image is the description
19666 ;; of another link, be sure to
19667 ;; consider the latter as the one to
19668 ;; apply the overlay on.
19669 (let ((parent
19670 (org-element-property :parent link)))
19671 (if (eq (org-element-type parent) 'link)
19672 parent
19673 link)))
19674 (ov (make-overlay
19675 (org-element-property :begin link)
19676 (progn
19677 (goto-char
19678 (org-element-property :end link))
19679 (skip-chars-backward " \t")
19680 (point)))))
19681 (overlay-put ov 'display image)
19682 (overlay-put ov 'face 'default)
19683 (overlay-put ov 'org-image-overlay t)
19684 (overlay-put
19685 ov 'modification-hooks
19686 (list 'org-display-inline-remove-overlay))
19687 (push ov org-inline-image-overlays)))))))))))))))
19689 (define-obsolete-function-alias
19690 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19692 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19693 "Remove inline-display overlay if a corresponding region is modified."
19694 (let ((inhibit-modification-hooks t))
19695 (when (and ov after)
19696 (delete ov org-inline-image-overlays)
19697 (delete-overlay ov))))
19699 (defun org-remove-inline-images ()
19700 "Remove inline display of images."
19701 (interactive)
19702 (mapc #'delete-overlay org-inline-image-overlays)
19703 (setq org-inline-image-overlays nil))
19705 ;;;; Key bindings
19707 ;; Outline functions from `outline-mode-prefix-map'
19708 ;; that can be remapped in Org:
19709 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19710 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19711 (define-key org-mode-map [remap outline-forward-same-level]
19712 'org-forward-heading-same-level)
19713 (define-key org-mode-map [remap outline-backward-same-level]
19714 'org-backward-heading-same-level)
19715 (define-key org-mode-map [remap outline-show-branches]
19716 'org-kill-note-or-show-branches)
19717 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19718 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19719 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19720 (define-key org-mode-map [remap outline-next-visible-heading]
19721 'org-next-visible-heading)
19722 (define-key org-mode-map [remap outline-previous-visible-heading]
19723 'org-previous-visible-heading)
19724 (define-key org-mode-map [remap show-children] 'org-show-children)
19726 ;; Outline functions from `outline-mode-prefix-map' that can not
19727 ;; be remapped in Org:
19729 ;; - the column "key binding" shows whether the Outline function is still
19730 ;; available in Org mode on the same key that it has been bound to in
19731 ;; Outline mode:
19732 ;; - "overridden": key used for a different functionality in Org mode
19733 ;; - else: key still bound to the same Outline function in Org mode
19735 ;; | Outline function | key binding | Org replacement |
19736 ;; |------------------------------------+-------------+--------------------------|
19737 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19738 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19739 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19740 ;; | `show-entry' | overridden | no replacement |
19741 ;; | `show-branches' | `C-c C-k' | still same function |
19742 ;; | `show-subtree' | overridden | visibility cycling |
19743 ;; | `show-all' | overridden | no replacement |
19744 ;; | `hide-subtree' | overridden | visibility cycling |
19745 ;; | `hide-body' | overridden | no replacement |
19746 ;; | `hide-entry' | overridden | visibility cycling |
19747 ;; | `hide-leaves' | overridden | no replacement |
19748 ;; | `hide-sublevels' | overridden | no replacement |
19749 ;; | `hide-other' | overridden | no replacement |
19751 ;; Make `C-c C-x' a prefix key
19752 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19754 ;; TAB key with modifiers
19755 (org-defkey org-mode-map "\C-i" 'org-cycle)
19756 (org-defkey org-mode-map [(tab)] 'org-cycle)
19757 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19758 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19759 ;; The following line is necessary under Suse GNU/Linux
19760 (unless (featurep 'xemacs)
19761 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19762 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19763 (define-key org-mode-map [backtab] 'org-shifttab)
19765 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19766 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19767 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19769 ;; Cursor keys with modifiers
19770 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19771 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19772 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19773 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19775 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19776 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19777 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19778 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19779 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19780 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19782 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19783 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19784 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19785 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19787 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19788 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19789 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19790 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19792 ;; Babel keys
19793 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19794 (dolist (pair org-babel-key-bindings)
19795 (define-key org-babel-map (car pair) (cdr pair)))
19797 ;;; Extra keys for tty access.
19798 ;; We only set them when really needed because otherwise the
19799 ;; menus don't show the simple keys
19801 (when (or org-use-extra-keys
19802 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19803 (not window-system))
19804 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19805 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19806 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19807 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19808 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19809 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19810 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19811 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19812 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19813 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19814 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19815 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19816 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19817 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19818 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19819 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19820 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19821 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19822 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19823 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19824 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19825 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19826 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19827 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19828 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19829 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19830 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19831 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19833 ;; All the other keys
19835 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19836 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19837 (if (boundp 'narrow-map)
19838 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19839 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19840 (if (boundp 'narrow-map)
19841 (org-defkey narrow-map "b" 'org-narrow-to-block)
19842 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19843 (if (boundp 'narrow-map)
19844 (org-defkey narrow-map "e" 'org-narrow-to-element)
19845 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19846 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19847 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19848 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19849 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19850 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19851 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19852 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19853 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19854 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19855 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19856 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19857 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19858 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19859 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19860 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19861 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19862 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19863 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19864 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19865 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19866 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19867 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19868 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19869 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19870 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19871 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19872 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19873 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19874 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19875 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19876 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19877 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19878 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19879 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19880 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19881 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19882 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19883 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19884 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19885 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19886 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19887 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19888 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19889 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19890 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19891 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19892 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19893 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19894 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19895 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19896 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19897 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19898 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19899 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19900 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19901 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19902 (org-defkey org-mode-map "\C-c^" 'org-sort)
19903 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19904 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19905 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19906 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19907 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19908 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19909 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19910 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19911 (org-defkey org-mode-map "\C-m" 'org-return)
19912 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19913 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19914 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19915 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19916 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19917 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19918 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19919 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19920 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19921 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19922 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19923 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19924 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19925 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19926 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19927 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19928 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19929 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19930 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19931 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19932 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19933 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19934 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19935 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19936 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19938 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19939 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19940 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19942 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19943 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19944 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19945 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19946 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19947 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19948 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19949 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19950 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19951 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19952 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19953 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19954 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19955 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19956 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19957 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19958 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19959 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19960 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19961 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19962 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19963 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19965 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19966 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19967 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19968 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19969 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19971 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19973 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19975 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19976 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19978 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19981 (when (featurep 'xemacs)
19982 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19985 (defconst org-speed-commands-default
19987 ("Outline Navigation")
19988 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19989 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19990 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19991 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19992 ("F" . org-next-block)
19993 ("B" . org-previous-block)
19994 ("u" . (org-speed-move-safe 'outline-up-heading))
19995 ("j" . org-goto)
19996 ("g" . (org-refile t))
19997 ("Outline Visibility")
19998 ("c" . org-cycle)
19999 ("C" . org-shifttab)
20000 (" " . org-display-outline-path)
20001 ("s" . org-narrow-to-subtree)
20002 ("=" . org-columns)
20003 ("Outline Structure Editing")
20004 ("U" . org-metaup)
20005 ("D" . org-metadown)
20006 ("r" . org-metaright)
20007 ("l" . org-metaleft)
20008 ("R" . org-shiftmetaright)
20009 ("L" . org-shiftmetaleft)
20010 ("i" . (progn (forward-char 1) (call-interactively
20011 'org-insert-heading-respect-content)))
20012 ("^" . org-sort)
20013 ("w" . org-refile)
20014 ("a" . org-archive-subtree-default-with-confirmation)
20015 ("@" . org-mark-subtree)
20016 ("#" . org-toggle-comment)
20017 ("Clock Commands")
20018 ("I" . org-clock-in)
20019 ("O" . org-clock-out)
20020 ("Meta Data Editing")
20021 ("t" . org-todo)
20022 ("," . (org-priority))
20023 ("0" . (org-priority ?\ ))
20024 ("1" . (org-priority ?A))
20025 ("2" . (org-priority ?B))
20026 ("3" . (org-priority ?C))
20027 (":" . org-set-tags-command)
20028 ("e" . org-set-effort)
20029 ("E" . org-inc-effort)
20030 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20031 (org-entry-put (point) "APPT_WARNTIME" m)))
20032 ("Agenda Views etc")
20033 ("v" . org-agenda)
20034 ("/" . org-sparse-tree)
20035 ("Misc")
20036 ("o" . org-open-at-point)
20037 ("?" . org-speed-command-help)
20038 ("<" . (org-agenda-set-restriction-lock 'subtree))
20039 (">" . (org-agenda-remove-restriction-lock))
20041 "The default speed commands.")
20043 (defun org-print-speed-command (e)
20044 (if (> (length (car e)) 1)
20045 (progn
20046 (princ "\n")
20047 (princ (car e))
20048 (princ "\n")
20049 (princ (make-string (length (car e)) ?-))
20050 (princ "\n"))
20051 (princ (car e))
20052 (princ " ")
20053 (if (symbolp (cdr e))
20054 (princ (symbol-name (cdr e)))
20055 (prin1 (cdr e)))
20056 (princ "\n")))
20058 (defun org-speed-command-help ()
20059 "Show the available speed commands."
20060 (interactive)
20061 (if (not org-use-speed-commands)
20062 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20063 (with-output-to-temp-buffer "*Help*"
20064 (princ "User-defined Speed commands\n===========================\n")
20065 (mapc #'org-print-speed-command org-speed-commands-user)
20066 (princ "\n")
20067 (princ "Built-in Speed commands\n=======================\n")
20068 (mapc #'org-print-speed-command org-speed-commands-default))
20069 (with-current-buffer "*Help*"
20070 (setq truncate-lines t))))
20072 (defun org-speed-move-safe (cmd)
20073 "Execute CMD, but make sure that the cursor always ends up in a headline.
20074 If not, return to the original position and throw an error."
20075 (interactive)
20076 (let ((pos (point)))
20077 (call-interactively cmd)
20078 (unless (and (bolp) (org-at-heading-p))
20079 (goto-char pos)
20080 (error "Boundary reached while executing %s" cmd))))
20082 (defvar org-self-insert-command-undo-counter 0)
20084 (defvar org-table-auto-blank-field) ; defined in org-table.el
20085 (defvar org-speed-command nil)
20087 (define-obsolete-function-alias
20088 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20090 (defun org-speed-command-activate (keys)
20091 "Hook for activating single-letter speed commands.
20092 `org-speed-commands-default' specifies a minimal command set.
20093 Use `org-speed-commands-user' for further customization."
20094 (when (or (and (bolp) (looking-at org-outline-regexp))
20095 (and (functionp org-use-speed-commands)
20096 (funcall org-use-speed-commands)))
20097 (cdr (assoc keys (append org-speed-commands-user
20098 org-speed-commands-default)))))
20100 (define-obsolete-function-alias
20101 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20103 (defun org-babel-speed-command-activate (keys)
20104 "Hook for activating single-letter code block commands."
20105 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20106 (cdr (assoc keys org-babel-key-bindings))))
20108 (defcustom org-speed-command-hook
20109 '(org-speed-command-default-hook org-babel-speed-command-hook)
20110 "Hook for activating speed commands at strategic locations.
20111 Hook functions are called in sequence until a valid handler is
20112 found.
20114 Each hook takes a single argument, a user-pressed command key
20115 which is also a `self-insert-command' from the global map.
20117 Within the hook, examine the cursor position and the command key
20118 and return nil or a valid handler as appropriate. Handler could
20119 be one of an interactive command, a function, or a form.
20121 Set `org-use-speed-commands' to non-nil value to enable this
20122 hook. The default setting is `org-speed-command-activate'."
20123 :group 'org-structure
20124 :version "24.1"
20125 :type 'hook)
20127 (defun org-self-insert-command (N)
20128 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20129 If the cursor is in a table looking at whitespace, the whitespace is
20130 overwritten, and the table is not marked as requiring realignment."
20131 (interactive "p")
20132 (org-check-before-invisible-edit 'insert)
20133 (cond
20134 ((and org-use-speed-commands
20135 (let ((kv (this-command-keys-vector)))
20136 (setq org-speed-command
20137 (run-hook-with-args-until-success
20138 'org-speed-command-hook
20139 (make-string 1 (aref kv (1- (length kv))))))))
20140 (cond
20141 ((commandp org-speed-command)
20142 (setq this-command org-speed-command)
20143 (call-interactively org-speed-command))
20144 ((functionp org-speed-command)
20145 (funcall org-speed-command))
20146 ((and org-speed-command (listp org-speed-command))
20147 (eval org-speed-command))
20148 (t (let (org-use-speed-commands)
20149 (call-interactively 'org-self-insert-command)))))
20150 ((and
20151 (org-at-table-p)
20152 (progn
20153 ;; Check if we blank the field, and if that triggers align.
20154 (and (featurep 'org-table) org-table-auto-blank-field
20155 (memq last-command
20156 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20157 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20158 ;; Got extra space, this field does not determine
20159 ;; column width.
20160 (let (org-table-may-need-update) (org-table-blank-field))
20161 ;; No extra space, this field may determine column
20162 ;; width.
20163 (org-table-blank-field)))
20165 (eq N 1)
20166 (looking-at "[^|\n]* \\( \\)|"))
20167 ;; There is room for insertion without re-aligning the table.
20168 (delete-region (match-beginning 1) (match-end 1))
20169 (self-insert-command N))
20171 (setq org-table-may-need-update t)
20172 (self-insert-command N)
20173 (org-fix-tags-on-the-fly)
20174 (when org-self-insert-cluster-for-undo
20175 (if (not (eq last-command 'org-self-insert-command))
20176 (setq org-self-insert-command-undo-counter 1)
20177 (if (>= org-self-insert-command-undo-counter 20)
20178 (setq org-self-insert-command-undo-counter 1)
20179 (and (> org-self-insert-command-undo-counter 0)
20180 buffer-undo-list (listp buffer-undo-list)
20181 (not (cadr buffer-undo-list)) ; remove nil entry
20182 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20183 (setq org-self-insert-command-undo-counter
20184 (1+ org-self-insert-command-undo-counter))))))))
20186 (defun org-check-before-invisible-edit (kind)
20187 "Check is editing if kind KIND would be dangerous with invisible text around.
20188 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20189 ;; First, try to get out of here as quickly as possible, to reduce overhead
20190 (when (and org-catch-invisible-edits
20191 (or (not (boundp 'visible-mode)) (not visible-mode))
20192 (or (get-char-property (point) 'invisible)
20193 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20194 ;; OK, we need to take a closer look
20195 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20196 (invisible-before-point (unless (bobp) (get-char-property
20197 (1- (point)) 'invisible)))
20198 (border-and-ok-direction
20200 ;; Check if we are acting predictably before invisible text
20201 (and invisible-at-point (not invisible-before-point)
20202 (memq kind '(insert delete-backward)))
20203 ;; Check if we are acting predictably after invisible text
20204 ;; This works not well, and I have turned it off. It seems
20205 ;; better to always show and stop after invisible text.
20206 ;; (and (not invisible-at-point) invisible-before-point
20207 ;; (memq kind '(insert delete)))
20209 (when (or (memq invisible-at-point '(outline org-hide-block t))
20210 (memq invisible-before-point '(outline org-hide-block t)))
20211 (when (eq org-catch-invisible-edits 'error)
20212 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20213 (if (and org-custom-properties-overlays
20214 (y-or-n-p "Display invisible properties in this buffer? "))
20215 (org-toggle-custom-properties-visibility)
20216 ;; Make the area visible
20217 (save-excursion
20218 (when invisible-before-point
20219 (goto-char (previous-single-char-property-change
20220 (point) 'invisible)))
20221 (outline-show-subtree))
20222 (cond
20223 ((eq org-catch-invisible-edits 'show)
20224 ;; That's it, we do the edit after showing
20225 (message
20226 "Unfolding invisible region around point before editing")
20227 (sit-for 1))
20228 ((and (eq org-catch-invisible-edits 'smart)
20229 border-and-ok-direction)
20230 (message "Unfolding invisible region around point before editing"))
20232 ;; Don't do the edit, make the user repeat it in full visibility
20233 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20235 (defun org-fix-tags-on-the-fly ()
20236 (when (and (equal (char-after (point-at-bol)) ?*)
20237 (org-at-heading-p))
20238 (org-align-tags-here org-tags-column)))
20240 (defun org-delete-backward-char (N)
20241 "Like `delete-backward-char', insert whitespace at field end in tables.
20242 When deleting backwards, in tables this function will insert whitespace in
20243 front of the next \"|\" separator, to keep the table aligned. The table will
20244 still be marked for re-alignment if the field did fill the entire column,
20245 because, in this case the deletion might narrow the column."
20246 (interactive "p")
20247 (save-match-data
20248 (org-check-before-invisible-edit 'delete-backward)
20249 (if (and (org-at-table-p)
20250 (eq N 1)
20251 (string-match "|" (buffer-substring (point-at-bol) (point)))
20252 (looking-at ".*?|"))
20253 (let ((pos (point))
20254 (noalign (looking-at "[^|\n\r]* |"))
20255 (c org-table-may-need-update))
20256 (backward-delete-char N)
20257 (unless overwrite-mode
20258 (skip-chars-forward "^|")
20259 (insert " ")
20260 (goto-char (1- pos)))
20261 ;; noalign: if there were two spaces at the end, this field
20262 ;; does not determine the width of the column.
20263 (when noalign (setq org-table-may-need-update c)))
20264 (backward-delete-char N)
20265 (org-fix-tags-on-the-fly))))
20267 (defun org-delete-char (N)
20268 "Like `delete-char', but insert whitespace at field end in tables.
20269 When deleting characters, in tables this function will insert whitespace in
20270 front of the next \"|\" separator, to keep the table aligned. The table will
20271 still be marked for re-alignment if the field did fill the entire column,
20272 because, in this case the deletion might narrow the column."
20273 (interactive "p")
20274 (save-match-data
20275 (org-check-before-invisible-edit 'delete)
20276 (if (and (org-at-table-p)
20277 (not (bolp))
20278 (not (= (char-after) ?|))
20279 (eq N 1))
20280 (if (looking-at ".*?|")
20281 (let ((pos (point))
20282 (noalign (looking-at "[^|\n\r]* |"))
20283 (c org-table-may-need-update))
20284 (replace-match
20285 (concat (substring (match-string 0) 1 -1) " |") nil t)
20286 (goto-char pos)
20287 ;; noalign: if there were two spaces at the end, this field
20288 ;; does not determine the width of the column.
20289 (when noalign (setq org-table-may-need-update c)))
20290 (delete-char N))
20291 (delete-char N)
20292 (org-fix-tags-on-the-fly))))
20294 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20295 (put 'org-self-insert-command 'delete-selection
20296 (lambda ()
20297 (not (run-hook-with-args-until-success
20298 'self-insert-uses-region-functions))))
20299 (put 'orgtbl-self-insert-command 'delete-selection
20300 (lambda ()
20301 (not (run-hook-with-args-until-success
20302 'self-insert-uses-region-functions))))
20303 (put 'org-delete-char 'delete-selection 'supersede)
20304 (put 'org-delete-backward-char 'delete-selection 'supersede)
20305 (put 'org-yank 'delete-selection 'yank)
20307 ;; Make `flyspell-mode' delay after some commands
20308 (put 'org-self-insert-command 'flyspell-delayed t)
20309 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20310 (put 'org-delete-char 'flyspell-delayed t)
20311 (put 'org-delete-backward-char 'flyspell-delayed t)
20313 ;; Make pabbrev-mode expand after org-mode commands
20314 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20315 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20317 (defun org-remap (map &rest commands)
20318 "In MAP, remap the functions given in COMMANDS.
20319 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20320 (let (new old)
20321 (while commands
20322 (setq old (pop commands) new (pop commands))
20323 (if (fboundp 'command-remapping)
20324 (org-defkey map (vector 'remap old) new)
20325 (substitute-key-definition old new map global-map)))))
20327 (defun org-transpose-words ()
20328 "Transpose words for Org.
20329 This uses the `org-mode-transpose-word-syntax-table' syntax
20330 table, which interprets characters in `org-emphasis-alist' as
20331 word constituents."
20332 (interactive)
20333 (with-syntax-table org-mode-transpose-word-syntax-table
20334 (call-interactively 'transpose-words)))
20335 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20337 (when (eq org-enable-table-editor 'optimized)
20338 ;; If the user wants maximum table support, we need to hijack
20339 ;; some standard editing functions
20340 (org-remap org-mode-map
20341 'self-insert-command 'org-self-insert-command
20342 'delete-char 'org-delete-char
20343 'delete-backward-char 'org-delete-backward-char)
20344 (org-defkey org-mode-map "|" 'org-force-self-insert))
20346 (defvar org-ctrl-c-ctrl-c-hook nil
20347 "Hook for functions attaching themselves to `C-c C-c'.
20349 This can be used to add additional functionality to the C-c C-c
20350 key which executes context-dependent commands. This hook is run
20351 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20352 run after the last test.
20354 Each function will be called with no arguments. The function
20355 must check if the context is appropriate for it to act. If yes,
20356 it should do its thing and then return a non-nil value. If the
20357 context is wrong, just do nothing and return nil.")
20359 (defvar org-ctrl-c-ctrl-c-final-hook nil
20360 "Hook for functions attaching themselves to `C-c C-c'.
20362 This can be used to add additional functionality to the C-c C-c
20363 key which executes context-dependent commands. This hook is run
20364 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20365 before the first test.
20367 Each function will be called with no arguments. The function
20368 must check if the context is appropriate for it to act. If yes,
20369 it should do its thing and then return a non-nil value. If the
20370 context is wrong, just do nothing and return nil.")
20372 (defvar org-tab-first-hook nil
20373 "Hook for functions to attach themselves to TAB.
20374 See `org-ctrl-c-ctrl-c-hook' for more information.
20375 This hook runs as the first action when TAB is pressed, even before
20376 `org-cycle' messes around with the `outline-regexp' to cater for
20377 inline tasks and plain list item folding.
20378 If any function in this hook returns t, any other actions that
20379 would have been caused by TAB (such as table field motion or visibility
20380 cycling) will not occur.")
20382 (defvar org-tab-after-check-for-table-hook nil
20383 "Hook for functions to attach themselves to TAB.
20384 See `org-ctrl-c-ctrl-c-hook' for more information.
20385 This hook runs after it has been established that the cursor is not in a
20386 table, but before checking if the cursor is in a headline or if global cycling
20387 should be done.
20388 If any function in this hook returns t, not other actions like visibility
20389 cycling will be done.")
20391 (defvar org-tab-after-check-for-cycling-hook nil
20392 "Hook for functions to attach themselves to TAB.
20393 See `org-ctrl-c-ctrl-c-hook' for more information.
20394 This hook runs after it has been established that not table field motion and
20395 not visibility should be done because of current context. This is probably
20396 the place where a package like yasnippets can hook in.")
20398 (defvar org-tab-before-tab-emulation-hook nil
20399 "Hook for functions to attach themselves to TAB.
20400 See `org-ctrl-c-ctrl-c-hook' for more information.
20401 This hook runs after every other options for TAB have been exhausted, but
20402 before indentation and \t insertion takes place.")
20404 (defvar org-metaleft-hook nil
20405 "Hook for functions attaching themselves to `M-left'.
20406 See `org-ctrl-c-ctrl-c-hook' for more information.")
20407 (defvar org-metaright-hook nil
20408 "Hook for functions attaching themselves to `M-right'.
20409 See `org-ctrl-c-ctrl-c-hook' for more information.")
20410 (defvar org-metaup-hook nil
20411 "Hook for functions attaching themselves to `M-up'.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.")
20413 (defvar org-metadown-hook nil
20414 "Hook for functions attaching themselves to `M-down'.
20415 See `org-ctrl-c-ctrl-c-hook' for more information.")
20416 (defvar org-shiftmetaleft-hook nil
20417 "Hook for functions attaching themselves to `M-S-left'.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.")
20419 (defvar org-shiftmetaright-hook nil
20420 "Hook for functions attaching themselves to `M-S-right'.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.")
20422 (defvar org-shiftmetaup-hook nil
20423 "Hook for functions attaching themselves to `M-S-up'.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.")
20425 (defvar org-shiftmetadown-hook nil
20426 "Hook for functions attaching themselves to `M-S-down'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-metareturn-hook nil
20429 "Hook for functions attaching themselves to `M-RET'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftup-hook nil
20432 "Hook for functions attaching themselves to `S-up'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftup-final-hook nil
20435 "Hook for functions attaching themselves to `S-up'.
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.")
20438 (defvar org-shiftdown-hook nil
20439 "Hook for functions attaching themselves to `S-down'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftdown-final-hook nil
20442 "Hook for functions attaching themselves to `S-down'.
20443 This one runs after all other options except shift-select have been excluded.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-shiftleft-hook nil
20446 "Hook for functions attaching themselves to `S-left'.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-shiftleft-final-hook nil
20449 "Hook for functions attaching themselves to `S-left'.
20450 This one runs after all other options except shift-select have been excluded.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-shiftright-hook nil
20453 "Hook for functions attaching themselves to `S-right'.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-shiftright-final-hook nil
20456 "Hook for functions attaching themselves to `S-right'.
20457 This one runs after all other options except shift-select have been excluded.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defun org-modifier-cursor-error ()
20461 "Throw an error, a modified cursor command was applied in wrong context."
20462 (user-error "This command is active in special context like tables, headlines or items"))
20464 (defun org-shiftselect-error ()
20465 "Throw an error because Shift-Cursor command was applied in wrong context."
20466 (if (and (boundp 'shift-select-mode) shift-select-mode)
20467 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20468 (user-error "This command works only in special context like headlines or timestamps")))
20470 (defun org-call-for-shift-select (cmd)
20471 (let ((this-command-keys-shift-translated t))
20472 (call-interactively cmd)))
20474 (defun org-shifttab (&optional arg)
20475 "Global visibility cycling or move to previous table field.
20476 Call `org-table-previous-field' within a table.
20477 When ARG is nil, cycle globally through visibility states.
20478 When ARG is a numeric prefix, show contents of this level."
20479 (interactive "P")
20480 (cond
20481 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20482 ((integerp arg)
20483 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20484 (message "Content view to level: %d" arg)
20485 (org-content (prefix-numeric-value arg2))
20486 (org-cycle-show-empty-lines t)
20487 (setq org-cycle-global-status 'overview)))
20488 (t (call-interactively 'org-global-cycle))))
20490 (defun org-shiftmetaleft ()
20491 "Promote subtree or delete table column.
20492 Calls `org-promote-subtree', `org-outdent-item-tree', or
20493 `org-table-delete-column', depending on context. See the
20494 individual commands for more information."
20495 (interactive)
20496 (cond
20497 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20498 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20499 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20500 ((if (not (org-region-active-p)) (org-at-item-p)
20501 (save-excursion (goto-char (region-beginning))
20502 (org-at-item-p)))
20503 (call-interactively 'org-outdent-item-tree))
20504 (t (org-modifier-cursor-error))))
20506 (defun org-shiftmetaright ()
20507 "Demote subtree or insert table column.
20508 Calls `org-demote-subtree', `org-indent-item-tree', or
20509 `org-table-insert-column', depending on context. See the
20510 individual commands for more information."
20511 (interactive)
20512 (cond
20513 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20514 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20515 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20516 ((if (not (org-region-active-p)) (org-at-item-p)
20517 (save-excursion (goto-char (region-beginning))
20518 (org-at-item-p)))
20519 (call-interactively 'org-indent-item-tree))
20520 (t (org-modifier-cursor-error))))
20522 (defun org-shiftmetaup (&optional _arg)
20523 "Drag the line at point up.
20524 In a table, kill the current row.
20525 On a clock timestamp, update the value of the timestamp like `S-<up>'
20526 but also adjust the previous clocked item in the clock history.
20527 Everywhere else, drag the line at point up."
20528 (interactive "P")
20529 (cond
20530 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20531 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20532 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20533 (call-interactively 'org-timestamp-up)))
20534 (t (call-interactively 'org-drag-line-backward))))
20536 (defun org-shiftmetadown (&optional _arg)
20537 "Drag the line at point down.
20538 In a table, insert an empty row at the current line.
20539 On a clock timestamp, update the value of the timestamp like `S-<down>'
20540 but also adjust the previous clocked item in the clock history.
20541 Everywhere else, drag the line at point down."
20542 (interactive "P")
20543 (cond
20544 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20545 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20546 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20547 (call-interactively 'org-timestamp-down)))
20548 (t (call-interactively 'org-drag-line-forward))))
20550 (defsubst org-hidden-tree-error ()
20551 (user-error
20552 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20554 (defun org-metaleft (&optional _arg)
20555 "Promote heading, list item at point or move table column left.
20557 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20558 depending on context. With no specific context, calls the Emacs
20559 default `backward-word'. See the individual commands for more
20560 information.
20562 This function runs the hook `org-metaleft-hook' as a first step,
20563 and returns at first non-nil value."
20564 (interactive "P")
20565 (cond
20566 ((run-hook-with-args-until-success 'org-metaleft-hook))
20567 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20568 ((org-with-limited-levels
20569 (or (org-at-heading-p)
20570 (and (org-region-active-p)
20571 (save-excursion
20572 (goto-char (region-beginning))
20573 (org-at-heading-p)))))
20574 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20575 (call-interactively 'org-do-promote))
20576 ;; At an inline task.
20577 ((org-at-heading-p)
20578 (call-interactively 'org-inlinetask-promote))
20579 ((or (org-at-item-p)
20580 (and (org-region-active-p)
20581 (save-excursion
20582 (goto-char (region-beginning))
20583 (org-at-item-p))))
20584 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20585 (call-interactively 'org-outdent-item))
20586 (t (call-interactively 'backward-word))))
20588 (defun org-metaright (&optional _arg)
20589 "Demote heading, list item at point or move table column right.
20591 In front of a drawer or a block keyword, indent it correctly.
20593 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20594 `org-indnet-drawer' or `org-indent-block' depending on context.
20595 With no specific context, calls the Emacs default `forward-word'.
20596 See the individual commands for more information.
20598 This function runs the hook `org-metaright-hook' as a first step,
20599 and returns at first non-nil value."
20600 (interactive "P")
20601 (cond
20602 ((run-hook-with-args-until-success 'org-metaright-hook))
20603 ((org-at-table-p) (call-interactively 'org-table-move-column))
20604 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20605 ((org-at-block-p) (call-interactively 'org-indent-block))
20606 ((org-with-limited-levels
20607 (or (org-at-heading-p)
20608 (and (org-region-active-p)
20609 (save-excursion
20610 (goto-char (region-beginning))
20611 (org-at-heading-p)))))
20612 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20613 (call-interactively 'org-do-demote))
20614 ;; At an inline task.
20615 ((org-at-heading-p)
20616 (call-interactively 'org-inlinetask-demote))
20617 ((or (org-at-item-p)
20618 (and (org-region-active-p)
20619 (save-excursion
20620 (goto-char (region-beginning))
20621 (org-at-item-p))))
20622 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20623 (call-interactively 'org-indent-item))
20624 (t (call-interactively 'forward-word))))
20626 (defun org-check-for-hidden (what)
20627 "Check if there are hidden headlines/items in the current visual line.
20628 WHAT can be either `headlines' or `items'. If the current line is
20629 an outline or item heading and it has a folded subtree below it,
20630 this function returns t, nil otherwise."
20631 (let ((re (cond
20632 ((eq what 'headlines) org-outline-regexp-bol)
20633 ((eq what 'items) (org-item-beginning-re))
20634 (t (error "This should not happen"))))
20635 beg end)
20636 (save-excursion
20637 (catch 'exit
20638 (unless (org-region-active-p)
20639 (setq beg (point-at-bol))
20640 (beginning-of-line 2)
20641 (while (and (not (eobp)) ;; this is like `next-line'
20642 (get-char-property (1- (point)) 'invisible))
20643 (beginning-of-line 2))
20644 (setq end (point))
20645 (goto-char beg)
20646 (goto-char (point-at-eol))
20647 (setq end (max end (point)))
20648 (while (re-search-forward re end t)
20649 (when (get-char-property (match-beginning 0) 'invisible)
20650 (throw 'exit t))))
20651 nil))))
20653 (defun org-metaup (&optional _arg)
20654 "Move subtree up or move table row up.
20655 Calls `org-move-subtree-up' or `org-table-move-row' or
20656 `org-move-item-up', depending on context. See the individual commands
20657 for more information."
20658 (interactive "P")
20659 (cond
20660 ((run-hook-with-args-until-success 'org-metaup-hook))
20661 ((org-region-active-p)
20662 (let* ((a (min (region-beginning) (region-end)))
20663 (b (1- (max (region-beginning) (region-end))))
20664 (c (save-excursion (goto-char a)
20665 (move-beginning-of-line 0)))
20666 (d (save-excursion (goto-char a)
20667 (move-end-of-line 0) (point))))
20668 (transpose-regions a b c d)
20669 (goto-char c)))
20670 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20671 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20672 ((org-at-item-p) (call-interactively 'org-move-item-up))
20673 (t (org-drag-element-backward))))
20675 (defun org-metadown (&optional _arg)
20676 "Move subtree down or move table row down.
20677 Calls `org-move-subtree-down' or `org-table-move-row' or
20678 `org-move-item-down', depending on context. See the individual
20679 commands for more information."
20680 (interactive "P")
20681 (cond
20682 ((run-hook-with-args-until-success 'org-metadown-hook))
20683 ((org-region-active-p)
20684 (let* ((a (min (region-beginning) (region-end)))
20685 (b (max (region-beginning) (region-end)))
20686 (c (save-excursion (goto-char b)
20687 (move-beginning-of-line 1)))
20688 (d (save-excursion (goto-char b)
20689 (move-end-of-line 1) (1+ (point)))))
20690 (transpose-regions a b c d)
20691 (goto-char d)))
20692 ((org-at-table-p) (call-interactively 'org-table-move-row))
20693 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20694 ((org-at-item-p) (call-interactively 'org-move-item-down))
20695 (t (org-drag-element-forward))))
20697 (defun org-shiftup (&optional arg)
20698 "Increase item in timestamp or increase priority of current headline.
20699 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20700 depending on context. See the individual commands for more information."
20701 (interactive "P")
20702 (cond
20703 ((run-hook-with-args-until-success 'org-shiftup-hook))
20704 ((and org-support-shift-select (org-region-active-p))
20705 (org-call-for-shift-select 'previous-line))
20706 ((org-at-timestamp-p t)
20707 (call-interactively (if org-edit-timestamp-down-means-later
20708 'org-timestamp-down 'org-timestamp-up)))
20709 ((and (not (eq org-support-shift-select 'always))
20710 org-enable-priority-commands
20711 (org-at-heading-p))
20712 (call-interactively 'org-priority-up))
20713 ((and (not org-support-shift-select) (org-at-item-p))
20714 (call-interactively 'org-previous-item))
20715 ((org-clocktable-try-shift 'up arg))
20716 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20717 (org-support-shift-select
20718 (org-call-for-shift-select 'previous-line))
20719 (t (org-shiftselect-error))))
20721 (defun org-shiftdown (&optional arg)
20722 "Decrease item in timestamp or decrease priority of current headline.
20723 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20724 depending on context. See the individual commands for more information."
20725 (interactive "P")
20726 (cond
20727 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20728 ((and org-support-shift-select (org-region-active-p))
20729 (org-call-for-shift-select 'next-line))
20730 ((org-at-timestamp-p t)
20731 (call-interactively (if org-edit-timestamp-down-means-later
20732 'org-timestamp-up 'org-timestamp-down)))
20733 ((and (not (eq org-support-shift-select 'always))
20734 org-enable-priority-commands
20735 (org-at-heading-p))
20736 (call-interactively 'org-priority-down))
20737 ((and (not org-support-shift-select) (org-at-item-p))
20738 (call-interactively 'org-next-item))
20739 ((org-clocktable-try-shift 'down arg))
20740 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20741 (org-support-shift-select
20742 (org-call-for-shift-select 'next-line))
20743 (t (org-shiftselect-error))))
20745 (defun org-shiftright (&optional arg)
20746 "Cycle the thing at point or in the current line, depending on context.
20747 Depending on context, this does one of the following:
20749 - switch a timestamp at point one day into the future
20750 - on a headline, switch to the next TODO keyword.
20751 - on an item, switch entire list to the next bullet type
20752 - on a property line, switch to the next allowed value
20753 - on a clocktable definition line, move time block into the future"
20754 (interactive "P")
20755 (cond
20756 ((run-hook-with-args-until-success 'org-shiftright-hook))
20757 ((and org-support-shift-select (org-region-active-p))
20758 (org-call-for-shift-select 'forward-char))
20759 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20760 ((and (not (eq org-support-shift-select 'always))
20761 (org-at-heading-p))
20762 (let ((org-inhibit-logging
20763 (not org-treat-S-cursor-todo-selection-as-state-change))
20764 (org-inhibit-blocking
20765 (not org-treat-S-cursor-todo-selection-as-state-change)))
20766 (org-call-with-arg 'org-todo 'right)))
20767 ((or (and org-support-shift-select
20768 (not (eq org-support-shift-select 'always))
20769 (org-at-item-bullet-p))
20770 (and (not org-support-shift-select) (org-at-item-p)))
20771 (org-call-with-arg 'org-cycle-list-bullet nil))
20772 ((and (not (eq org-support-shift-select 'always))
20773 (org-at-property-p))
20774 (call-interactively 'org-property-next-allowed-value))
20775 ((org-clocktable-try-shift 'right arg))
20776 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20777 (org-support-shift-select
20778 (org-call-for-shift-select 'forward-char))
20779 (t (org-shiftselect-error))))
20781 (defun org-shiftleft (&optional arg)
20782 "Cycle the thing at point or in the current line, depending on context.
20783 Depending on context, this does one of the following:
20785 - switch a timestamp at point one day into the past
20786 - on a headline, switch to the previous TODO keyword.
20787 - on an item, switch entire list to the previous bullet type
20788 - on a property line, switch to the previous allowed value
20789 - on a clocktable definition line, move time block into the past"
20790 (interactive "P")
20791 (cond
20792 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20793 ((and org-support-shift-select (org-region-active-p))
20794 (org-call-for-shift-select 'backward-char))
20795 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20796 ((and (not (eq org-support-shift-select 'always))
20797 (org-at-heading-p))
20798 (let ((org-inhibit-logging
20799 (not org-treat-S-cursor-todo-selection-as-state-change))
20800 (org-inhibit-blocking
20801 (not org-treat-S-cursor-todo-selection-as-state-change)))
20802 (org-call-with-arg 'org-todo 'left)))
20803 ((or (and org-support-shift-select
20804 (not (eq org-support-shift-select 'always))
20805 (org-at-item-bullet-p))
20806 (and (not org-support-shift-select) (org-at-item-p)))
20807 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20808 ((and (not (eq org-support-shift-select 'always))
20809 (org-at-property-p))
20810 (call-interactively 'org-property-previous-allowed-value))
20811 ((org-clocktable-try-shift 'left arg))
20812 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20813 (org-support-shift-select
20814 (org-call-for-shift-select 'backward-char))
20815 (t (org-shiftselect-error))))
20817 (defun org-shiftcontrolright ()
20818 "Switch to next TODO set."
20819 (interactive)
20820 (cond
20821 ((and org-support-shift-select (org-region-active-p))
20822 (org-call-for-shift-select 'forward-word))
20823 ((and (not (eq org-support-shift-select 'always))
20824 (org-at-heading-p))
20825 (org-call-with-arg 'org-todo 'nextset))
20826 (org-support-shift-select
20827 (org-call-for-shift-select 'forward-word))
20828 (t (org-shiftselect-error))))
20830 (defun org-shiftcontrolleft ()
20831 "Switch to previous TODO set."
20832 (interactive)
20833 (cond
20834 ((and org-support-shift-select (org-region-active-p))
20835 (org-call-for-shift-select 'backward-word))
20836 ((and (not (eq org-support-shift-select 'always))
20837 (org-at-heading-p))
20838 (org-call-with-arg 'org-todo 'previousset))
20839 (org-support-shift-select
20840 (org-call-for-shift-select 'backward-word))
20841 (t (org-shiftselect-error))))
20843 (defun org-shiftcontrolup (&optional n)
20844 "Change timestamps synchronously up in CLOCK log lines.
20845 Optional argument N tells to change by that many units."
20846 (interactive "P")
20847 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20848 (let (org-support-shift-select)
20849 (org-clock-timestamps-up n))
20850 (user-error "Not at a clock log")))
20852 (defun org-shiftcontroldown (&optional n)
20853 "Change timestamps synchronously down in CLOCK log lines.
20854 Optional argument N tells to change by that many units."
20855 (interactive "P")
20856 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20857 (let (org-support-shift-select)
20858 (org-clock-timestamps-down n))
20859 (user-error "Not at a clock log")))
20861 (defun org-increase-number-at-point (&optional inc)
20862 "Increment the number at point.
20863 With an optional prefix numeric argument INC, increment using
20864 this numeric value."
20865 (interactive "p")
20866 (if (not (number-at-point))
20867 (user-error "Not on a number")
20868 (unless inc (setq inc 1))
20869 (let ((pos (point))
20870 (beg (skip-chars-backward "-+^/*0-9eE."))
20871 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20872 (setq nap (buffer-substring-no-properties
20873 (+ pos beg) (+ pos beg end)))
20874 (delete-region (+ pos beg) (+ pos beg end))
20875 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20876 (when (org-at-table-p)
20877 (org-table-align)
20878 (org-table-end-of-field 1))))
20880 (defun org-decrease-number-at-point (&optional inc)
20881 "Decrement the number at point.
20882 With an optional prefix numeric argument INC, decrement using
20883 this numeric value."
20884 (interactive "p")
20885 (org-increase-number-at-point (- (or inc 1))))
20887 (defun org-ctrl-c-ret ()
20888 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20889 (interactive)
20890 (cond
20891 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20892 (t (call-interactively 'org-insert-heading))))
20894 (defun org-find-visible ()
20895 (let ((s (point)))
20896 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20897 (get-char-property s 'invisible)))
20899 (defun org-find-invisible ()
20900 (let ((s (point)))
20901 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20902 (not (get-char-property s 'invisible))))
20905 (defun org-copy-visible (beg end)
20906 "Copy the visible parts of the region."
20907 (interactive "r")
20908 (let (snippets s)
20909 (save-excursion
20910 (save-restriction
20911 (narrow-to-region beg end)
20912 (setq s (goto-char (point-min)))
20913 (while (not (= (point) (point-max)))
20914 (goto-char (org-find-invisible))
20915 (push (buffer-substring s (point)) snippets)
20916 (setq s (goto-char (org-find-visible))))))
20917 (kill-new (apply 'concat (nreverse snippets)))))
20919 (defun org-copy-special ()
20920 "Copy region in table or copy current subtree.
20921 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20922 See the individual commands for more information."
20923 (interactive)
20924 (call-interactively
20925 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20927 (defun org-cut-special ()
20928 "Cut region in table or cut current subtree.
20929 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20930 See the individual commands for more information."
20931 (interactive)
20932 (call-interactively
20933 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20935 (defun org-paste-special (arg)
20936 "Paste rectangular region into table, or past subtree relative to level.
20937 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20938 See the individual commands for more information."
20939 (interactive "P")
20940 (if (org-at-table-p)
20941 (org-table-paste-rectangle)
20942 (org-paste-subtree arg)))
20944 (defsubst org-in-fixed-width-region-p ()
20945 "Is point in a fixed-width region?"
20946 (save-match-data
20947 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20949 (defun org-edit-special (&optional arg)
20950 "Call a special editor for the element at point.
20951 When at a table, call the formula editor with `org-table-edit-formulas'.
20952 When in a source code block, call `org-edit-src-code'.
20953 When in a fixed-width region, call `org-edit-fixed-width-region'.
20954 When in an export block, call `org-edit-export-block'.
20955 When at an #+INCLUDE keyword, visit the included file.
20956 When at a footnote reference, call `org-edit-footnote-reference'
20957 On a link, call `ffap' to visit the link at point.
20958 Otherwise, return a user error."
20959 (interactive "P")
20960 (let ((element (org-element-at-point)))
20961 (assert (not buffer-read-only) nil
20962 "Buffer is read-only: %s" (buffer-name))
20963 (pcase (org-element-type element)
20964 (`src-block
20965 (if (not arg) (org-edit-src-code)
20966 (let* ((info (org-babel-get-src-block-info))
20967 (lang (nth 0 info))
20968 (params (nth 2 info))
20969 (session (cdr (assq :session params))))
20970 (if (not session) (org-edit-src-code)
20971 ;; At a src-block with a session and function called with
20972 ;; an ARG: switch to the buffer related to the inferior
20973 ;; process.
20974 (switch-to-buffer
20975 (funcall (intern (concat "org-babel-prep-session:" lang))
20976 session params))))))
20977 (`keyword
20978 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20979 (org-open-link-from-string
20980 (format "[[%s]]"
20981 (expand-file-name
20982 (let ((value (org-element-property :value element)))
20983 (cond ((not (org-string-nw-p value))
20984 (user-error "No file to edit"))
20985 ((string-match "\\`\"\\(.*?\\)\"" value)
20986 (match-string 1 value))
20987 ((string-match "\\`[^ \t\"]\\S-*" value)
20988 (match-string 0 value))
20989 (t (user-error "No valid file specified")))))))
20990 (user-error "No special environment to edit here")))
20991 (`table
20992 (if (eq (org-element-property :type element) 'table.el)
20993 (org-edit-table.el)
20994 (call-interactively 'org-table-edit-formulas)))
20995 ;; Only Org tables contain `table-row' type elements.
20996 (`table-row (call-interactively 'org-table-edit-formulas))
20997 (`example-block (org-edit-src-code))
20998 (`export-block (org-edit-export-block))
20999 (`fixed-width (org-edit-fixed-width-region))
21001 ;; No notable element at point. Though, we may be at a link or
21002 ;; a footnote reference, which are objects. Thus, scan deeper.
21003 (let ((context (org-element-context element)))
21004 (pcase (org-element-type context)
21005 (`footnote-reference (org-edit-footnote-reference))
21006 (`inline-src-block (org-edit-inline-src-code))
21007 (`link (call-interactively #'ffap))
21008 (_ (user-error "No special environment to edit here"))))))))
21010 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21011 (defun org-ctrl-c-ctrl-c (&optional arg)
21012 "Set tags in headline, or update according to changed information at point.
21014 This command does many different things, depending on context:
21016 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21017 this is what we do.
21019 - If the cursor is on a statistics cookie, update it.
21021 - If the cursor is in a headline, prompt for tags and insert them
21022 into the current line, aligned to `org-tags-column'. When called
21023 with prefix arg, realign all tags in the current buffer.
21025 - If the cursor is in one of the special #+KEYWORD lines, this
21026 triggers scanning the buffer for these lines and updating the
21027 information.
21029 - If the cursor is inside a table, realign the table. This command
21030 works even if the automatic table editor has been turned off.
21032 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21033 the entire table.
21035 - If the cursor is at a footnote reference or definition, jump to
21036 the corresponding definition or references, respectively.
21038 - If the cursor is a the beginning of a dynamic block, update it.
21040 - If the current buffer is a capture buffer, close note and file it.
21042 - If the cursor is on a <<<target>>>, update radio targets and
21043 corresponding links in this buffer.
21045 - If the cursor is on a numbered item in a plain list, renumber the
21046 ordered list.
21048 - If the cursor is on a checkbox, toggle it.
21050 - If the cursor is on a code block, evaluate it. The variable
21051 `org-confirm-babel-evaluate' can be used to control prompting
21052 before code block evaluation, by default every code block
21053 evaluation requires confirmation. Code block evaluation can be
21054 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21055 (interactive "P")
21056 (cond
21057 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21058 org-occur-highlights)
21059 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21060 (org-remove-occur-highlights)
21061 (message "Temporary highlights/overlays removed from current buffer"))
21062 ((and (local-variable-p 'org-finish-function (current-buffer))
21063 (fboundp org-finish-function))
21064 (funcall org-finish-function))
21065 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21067 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21068 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21069 (user-error "C-c C-c can do nothing useful at this location"))
21070 (let* ((context (org-element-context))
21071 (type (org-element-type context)))
21072 (case type
21073 ;; When at a link, act according to the parent instead.
21074 (link (setq context (org-element-property :parent context))
21075 (setq type (org-element-type context)))
21076 ;; Unsupported object types: refer to the first supported
21077 ;; element or object containing it.
21078 ((bold code entity export-snippet inline-babel-call inline-src-block
21079 italic latex-fragment line-break macro strike-through subscript
21080 superscript underline verbatim)
21081 (setq context
21082 (org-element-lineage
21083 context '(radio-target paragraph verse-block table-cell)))))
21084 ;; For convenience: at the first line of a paragraph on the
21085 ;; same line as an item, apply function on that item instead.
21086 (when (eq type 'paragraph)
21087 (let ((parent (org-element-property :parent context)))
21088 (when (and (eq (org-element-type parent) 'item)
21089 (= (line-beginning-position)
21090 (org-element-property :begin parent)))
21091 (setq context parent type 'item))))
21092 ;; Act according to type of element or object at point.
21093 (case type
21094 (clock (org-clock-update-time-maybe))
21095 (dynamic-block
21096 (save-excursion
21097 (goto-char (org-element-property :post-affiliated context))
21098 (org-update-dblock)))
21099 (footnote-definition
21100 (goto-char (org-element-property :post-affiliated context))
21101 (call-interactively 'org-footnote-action))
21102 (footnote-reference (call-interactively 'org-footnote-action))
21103 ((headline inlinetask)
21104 (save-excursion (goto-char (org-element-property :begin context))
21105 (call-interactively 'org-set-tags)))
21106 (item
21107 ;; At an item: a double C-u set checkbox to "[-]"
21108 ;; unconditionally, whereas a single one will toggle its
21109 ;; presence. Without a universal argument, if the item
21110 ;; has a checkbox, toggle it. Otherwise repair the list.
21111 (let* ((box (org-element-property :checkbox context))
21112 (struct (org-element-property :structure context))
21113 (old-struct (copy-tree struct))
21114 (parents (org-list-parents-alist struct))
21115 (prevs (org-list-prevs-alist struct))
21116 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21117 (org-list-set-checkbox
21118 (org-element-property :begin context) struct
21119 (cond ((equal arg '(16)) "[-]")
21120 ((and (not box) (equal arg '(4))) "[ ]")
21121 ((or (not box) (equal arg '(4))) nil)
21122 ((eq box 'on) "[ ]")
21123 (t "[X]")))
21124 ;; Mimic `org-list-write-struct' but with grabbing
21125 ;; a return value from `org-list-struct-fix-box'.
21126 (org-list-struct-fix-ind struct parents 2)
21127 (org-list-struct-fix-item-end struct)
21128 (org-list-struct-fix-bul struct prevs)
21129 (org-list-struct-fix-ind struct parents)
21130 (let ((block-item
21131 (org-list-struct-fix-box struct parents prevs orderedp)))
21132 (if (and box (equal struct old-struct))
21133 (if (equal arg '(16))
21134 (message "Checkboxes already reset")
21135 (user-error "Cannot toggle this checkbox: %s"
21136 (if (eq box 'on)
21137 "all subitems checked"
21138 "unchecked subitems")))
21139 (org-list-struct-apply-struct struct old-struct)
21140 (org-update-checkbox-count-maybe))
21141 (when block-item
21142 (message "Checkboxes were removed due to empty box at line %d"
21143 (org-current-line block-item))))))
21144 (keyword
21145 (let ((org-inhibit-startup-visibility-stuff t)
21146 (org-startup-align-all-tables nil))
21147 (when (boundp 'org-table-coordinate-overlays)
21148 (mapc #'delete-overlay org-table-coordinate-overlays)
21149 (setq org-table-coordinate-overlays nil))
21150 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21151 (message "Local setup has been refreshed"))
21152 (plain-list
21153 ;; At a plain list, with a double C-u argument, set
21154 ;; checkboxes of each item to "[-]", whereas a single one
21155 ;; will toggle their presence according to the state of the
21156 ;; first item in the list. Without an argument, repair the
21157 ;; list.
21158 (let* ((begin (org-element-property :contents-begin context))
21159 (beginm (move-marker (make-marker) begin))
21160 (struct (org-element-property :structure context))
21161 (old-struct (copy-tree struct))
21162 (first-box (save-excursion
21163 (goto-char begin)
21164 (looking-at org-list-full-item-re)
21165 (match-string-no-properties 3)))
21166 (new-box (cond ((equal arg '(16)) "[-]")
21167 ((equal arg '(4)) (unless first-box "[ ]"))
21168 ((equal first-box "[X]") "[ ]")
21169 (t "[X]"))))
21170 (cond
21171 (arg
21172 (dolist (pos
21173 (org-list-get-all-items
21174 begin struct (org-list-prevs-alist struct)))
21175 (org-list-set-checkbox pos struct new-box)))
21176 ((and first-box (eq (point) begin))
21177 ;; For convenience, when point is at bol on the first
21178 ;; item of the list and no argument is provided, simply
21179 ;; toggle checkbox of that item, if any.
21180 (org-list-set-checkbox begin struct new-box)))
21181 (org-list-write-struct
21182 struct (org-list-parents-alist struct) old-struct)
21183 (org-update-checkbox-count-maybe)
21184 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21185 ((property-drawer node-property)
21186 (call-interactively 'org-property-action))
21187 ((radio-target target)
21188 (call-interactively 'org-update-radio-target-regexp))
21189 (statistics-cookie
21190 (call-interactively 'org-update-statistics-cookies))
21191 ((table table-cell table-row)
21192 ;; At a table, recalculate every field and align it. Also
21193 ;; send the table if necessary. If the table has
21194 ;; a `table.el' type, just give up. At a table row or
21195 ;; cell, maybe recalculate line but always align table.
21196 (if (eq (org-element-property :type context) 'table.el)
21197 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21198 Use \\[org-edit-special] to edit table.el tables"))
21199 (let ((org-enable-table-editor t))
21200 (if (or (eq type 'table)
21201 ;; Check if point is at a TBLFM line.
21202 (and (eq type 'table-row)
21203 (= (point) (org-element-property :end context))))
21204 (save-excursion
21205 (if (org-at-TBLFM-p)
21206 (progn (require 'org-table)
21207 (org-table-calc-current-TBLFM))
21208 (goto-char (org-element-property :contents-begin context))
21209 (org-call-with-arg 'org-table-recalculate (or arg t))
21210 (orgtbl-send-table 'maybe)))
21211 (org-table-maybe-eval-formula)
21212 (cond (arg (call-interactively 'org-table-recalculate))
21213 ((org-table-maybe-recalculate-line))
21214 (t (org-table-align)))))))
21215 (timestamp (org-timestamp-change 0 'day))
21216 (otherwise
21217 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21218 (user-error
21219 "C-c C-c can do nothing useful at this location")))))))))
21221 (defun org-mode-restart ()
21222 (interactive)
21223 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21224 (funcall major-mode)
21225 (hack-local-variables)
21226 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21227 (org-indent-mode -1)))
21228 (message "%s restarted" major-mode))
21230 (defun org-kill-note-or-show-branches ()
21231 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21232 (interactive)
21233 (if (not org-finish-function)
21234 (progn
21235 (outline-hide-subtree)
21236 (call-interactively 'outline-show-branches))
21237 (let ((org-note-abort t))
21238 (funcall org-finish-function))))
21240 (defun org-delete-indentation (&optional ARG)
21241 "Join current line to previous and fix whitespace at join.
21243 If previous line is a headline add to headline title. Otherwise
21244 the function calls `delete-indentation'.
21246 With argument, join this line to following line."
21247 (interactive "*P")
21248 (if (save-excursion
21249 (if ARG (beginning-of-line)
21250 (forward-line -1))
21251 (looking-at org-complex-heading-regexp))
21252 ;; At headline.
21253 (let ((tags-column (when (match-beginning 5)
21254 (save-excursion (goto-char (match-beginning 5))
21255 (current-column))))
21256 (string (concat " " (progn (when ARG (forward-line 1))
21257 (org-trim (delete-and-extract-region
21258 (line-beginning-position)
21259 (line-end-position)))))))
21260 (unless (bobp) (delete-region (point) (1- (point))))
21261 (goto-char (or (match-end 4)
21262 (match-beginning 5)
21263 (match-end 0)))
21264 (skip-chars-backward " \t")
21265 (save-excursion (insert string))
21266 ;; Adjust alignment of tags.
21267 (when tags-column
21268 (org-align-tags-here (if org-auto-align-tags
21269 org-tags-column
21270 tags-column))))
21271 (delete-indentation ARG)))
21273 (defun org-open-line (n)
21274 "Insert a new row in tables, call `open-line' elsewhere.
21275 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21276 (interactive "*p")
21277 (cond
21278 ((not org-special-ctrl-o)
21279 (open-line n))
21280 ((org-at-table-p)
21281 (org-table-insert-row))
21283 (open-line n))))
21285 (defun org-return (&optional indent)
21286 "Goto next table row or insert a newline.
21288 Calls `org-table-next-row' or `newline', depending on context.
21290 When optional INDENT argument is non-nil, call
21291 `newline-and-indent' instead of `newline'.
21293 When `org-return-follows-link' is non-nil and point is on
21294 a timestamp or a link, call `org-open-at-point'. However, it
21295 will not happen if point is in a table or on a \"dead\"
21296 object (e.g., within a comment). In these case, you need to use
21297 `org-open-at-point' directly."
21298 (interactive)
21299 (let ((context (if org-return-follows-link (org-element-context)
21300 (org-element-at-point))))
21301 (cond
21302 ;; In a table, call `org-table-next-row'.
21303 ((or (and (eq (org-element-type context) 'table)
21304 (>= (point) (org-element-property :contents-begin context))
21305 (< (point) (org-element-property :contents-end context)))
21306 (org-element-lineage context '(table-row table-cell) t))
21307 (org-table-justify-field-maybe)
21308 (call-interactively #'org-table-next-row))
21309 ;; On a link or a timestamp, call `org-open-at-point' if
21310 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21311 ;; locations, e.g., in a comment, as `org-open-at-point'.
21312 ((and org-return-follows-link
21313 (or (org-in-regexp org-ts-regexp-both nil t)
21314 (org-in-regexp org-tsr-regexp-both nil t)
21315 (org-in-regexp org-any-link-re nil t)))
21316 (call-interactively #'org-open-at-point))
21317 ;; Insert newline in heading, but preserve tags.
21318 ((and (not (bolp))
21319 (save-excursion (beginning-of-line)
21320 (looking-at org-complex-heading-regexp)))
21321 ;; At headline. Split line. However, if point is on keyword,
21322 ;; priority cookie or tags, do not break any of them: add
21323 ;; a newline after the headline instead.
21324 (let ((tags-column (and (match-beginning 5)
21325 (save-excursion (goto-char (match-beginning 5))
21326 (current-column))))
21327 (string
21328 (when (and (match-end 4)
21329 (>= (point)
21330 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21331 (<= (point) (match-end 4)))
21332 (delete-and-extract-region (point) (match-end 4)))))
21333 (when (and tags-column string) ; Adjust tag alignment.
21334 (org-align-tags-here
21335 (if org-auto-align-tags org-tags-column tags-column)))
21336 (end-of-line)
21337 (org-show-entry)
21338 (if indent (newline-and-indent) (newline))
21339 (when string (save-excursion (insert (org-trim string))))))
21340 ;; In a list, make sure indenting keeps trailing text within.
21341 ((and indent
21342 (not (eolp))
21343 (org-element-lineage context '(item)))
21344 (let ((trailing-data
21345 (delete-and-extract-region (point) (line-end-position))))
21346 (newline-and-indent)
21347 (save-excursion (insert trailing-data))))
21348 (t (if indent (newline-and-indent) (newline))))))
21350 (defun org-return-indent ()
21351 "Goto next table row or insert a newline and indent.
21352 Calls `org-table-next-row' or `newline-and-indent', depending on
21353 context. See the individual commands for more information."
21354 (interactive)
21355 (org-return t))
21357 (defun org-ctrl-c-star ()
21358 "Compute table, or change heading status of lines.
21359 Calls `org-table-recalculate' or `org-toggle-heading',
21360 depending on context."
21361 (interactive)
21362 (cond
21363 ((org-at-table-p)
21364 (call-interactively 'org-table-recalculate))
21366 ;; Convert all lines in region to list items
21367 (call-interactively 'org-toggle-heading))))
21369 (defun org-ctrl-c-minus ()
21370 "Insert separator line in table or modify bullet status of line.
21371 Also turns a plain line or a region of lines into list items.
21372 Calls `org-table-insert-hline', `org-toggle-item', or
21373 `org-cycle-list-bullet', depending on context."
21374 (interactive)
21375 (cond
21376 ((org-at-table-p)
21377 (call-interactively 'org-table-insert-hline))
21378 ((org-region-active-p)
21379 (call-interactively 'org-toggle-item))
21380 ((org-in-item-p)
21381 (call-interactively 'org-cycle-list-bullet))
21383 (call-interactively 'org-toggle-item))))
21385 (defun org-toggle-item (arg)
21386 "Convert headings or normal lines to items, items to normal lines.
21387 If there is no active region, only the current line is considered.
21389 If the first non blank line in the region is a headline, convert
21390 all headlines to items, shifting text accordingly.
21392 If it is an item, convert all items to normal lines.
21394 If it is normal text, change region into a list of items.
21395 With a prefix argument ARG, change the region in a single item."
21396 (interactive "P")
21397 (let ((shift-text
21398 (function
21399 ;; Shift text in current section to IND, from point to END.
21400 ;; The function leaves point to END line.
21401 (lambda (ind end)
21402 (let ((min-i 1000) (end (copy-marker end)))
21403 ;; First determine the minimum indentation (MIN-I) of
21404 ;; the text.
21405 (save-excursion
21406 (catch 'exit
21407 (while (< (point) end)
21408 (let ((i (org-get-indentation)))
21409 (cond
21410 ;; Skip blank lines and inline tasks.
21411 ((looking-at "^[ \t]*$"))
21412 ((looking-at org-outline-regexp-bol))
21413 ;; We can't find less than 0 indentation.
21414 ((zerop i) (throw 'exit (setq min-i 0)))
21415 ((< i min-i) (setq min-i i))))
21416 (forward-line))))
21417 ;; Then indent each line so that a line indented to
21418 ;; MIN-I becomes indented to IND. Ignore blank lines
21419 ;; and inline tasks in the process.
21420 (let ((delta (- ind min-i)))
21421 (while (< (point) end)
21422 (unless (or (looking-at "^[ \t]*$")
21423 (looking-at org-outline-regexp-bol))
21424 (org-indent-line-to (+ (org-get-indentation) delta)))
21425 (forward-line)))))))
21426 (skip-blanks
21427 (function
21428 ;; Return beginning of first non-blank line, starting from
21429 ;; line at POS.
21430 (lambda (pos)
21431 (save-excursion
21432 (goto-char pos)
21433 (skip-chars-forward " \r\t\n")
21434 (point-at-bol)))))
21435 beg end)
21436 ;; Determine boundaries of changes.
21437 (if (org-region-active-p)
21438 (setq beg (funcall skip-blanks (region-beginning))
21439 end (copy-marker (region-end)))
21440 (setq beg (funcall skip-blanks (point-at-bol))
21441 end (copy-marker (point-at-eol))))
21442 ;; Depending on the starting line, choose an action on the text
21443 ;; between BEG and END.
21444 (org-with-limited-levels
21445 (save-excursion
21446 (goto-char beg)
21447 (cond
21448 ;; Case 1. Start at an item: de-itemize. Note that it only
21449 ;; happens when a region is active: `org-ctrl-c-minus'
21450 ;; would call `org-cycle-list-bullet' otherwise.
21451 ((org-at-item-p)
21452 (while (< (point) end)
21453 (when (org-at-item-p)
21454 (skip-chars-forward " \t")
21455 (delete-region (point) (match-end 0)))
21456 (forward-line)))
21457 ;; Case 2. Start at an heading: convert to items.
21458 ((org-at-heading-p)
21459 (let* ((bul (org-list-bullet-string "-"))
21460 (bul-len (length bul))
21461 (done (org-entry-is-done-p))
21462 (todo (org-entry-is-todo-p))
21463 ;; Indentation of the first heading. It should be
21464 ;; relative to the indentation of its parent, if any.
21465 (start-ind (save-excursion
21466 (cond
21467 ((not org-adapt-indentation) 0)
21468 ((not (outline-previous-heading)) 0)
21469 (t (length (match-string 0))))))
21470 ;; Level of first heading. Further headings will be
21471 ;; compared to it to determine hierarchy in the list.
21472 (ref-level (org-reduced-level (org-outline-level))))
21473 (when (or done todo) (org-todo ""))
21474 (while (< (point) end)
21475 (let* ((level (org-reduced-level (org-outline-level)))
21476 (delta (max 0 (- level ref-level))))
21477 ;; If current headline is less indented than the first
21478 ;; one, set it as reference, in order to preserve
21479 ;; subtrees.
21480 (when (< level ref-level) (setq ref-level level))
21481 (replace-match bul t t)
21482 (org-indent-line-to (+ start-ind (* delta bul-len)))
21483 (when (or done todo)
21484 (let* ((struct (org-list-struct))
21485 (old (copy-tree struct)))
21486 (org-list-set-checkbox (line-beginning-position)
21487 struct
21488 (if done "[X]" "[ ]"))
21489 (org-list-write-struct struct
21490 (org-list-parents-alist struct)
21491 old)))
21492 ;; Ensure all text down to END (or SECTION-END) belongs
21493 ;; to the newly created item.
21494 (let ((section-end (save-excursion
21495 (or (outline-next-heading) (point)))))
21496 (forward-line)
21497 (funcall shift-text
21498 (+ start-ind (* (1+ delta) bul-len))
21499 (min end section-end)))))))
21500 ;; Case 3. Normal line with ARG: make the first line of region
21501 ;; an item, and shift indentation of others lines to
21502 ;; set them as item's body.
21503 (arg (let* ((bul (org-list-bullet-string "-"))
21504 (bul-len (length bul))
21505 (ref-ind (org-get-indentation)))
21506 (skip-chars-forward " \t")
21507 (insert bul)
21508 (forward-line)
21509 (while (< (point) end)
21510 ;; Ensure that lines less indented than first one
21511 ;; still get included in item body.
21512 (funcall shift-text
21513 (+ ref-ind bul-len)
21514 (min end (save-excursion (or (outline-next-heading)
21515 (point)))))
21516 (forward-line))))
21517 ;; Case 4. Normal line without ARG: turn each non-item line
21518 ;; into an item.
21520 (while (< (point) end)
21521 (unless (or (org-at-heading-p) (org-at-item-p))
21522 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21523 (replace-match
21524 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21525 (forward-line))))))))
21527 (defun org-toggle-heading (&optional nstars)
21528 "Convert headings to normal text, or items or text to headings.
21529 If there is no active region, only convert the current line.
21531 With a \\[universal-argument] prefix, convert the whole list at
21532 point into heading.
21534 In a region:
21536 - If the first non blank line is a headline, remove the stars
21537 from all headlines in the region.
21539 - If it is a normal line, turn each and every normal line (i.e.,
21540 not an heading or an item) in the region into headings. If you
21541 want to convert only the first line of this region, use one
21542 universal prefix argument.
21544 - If it is a plain list item, turn all plain list items into headings.
21546 When converting a line into a heading, the number of stars is chosen
21547 such that the lines become children of the current entry. However,
21548 when a numeric prefix argument is given, its value determines the
21549 number of stars to add."
21550 (interactive "P")
21551 (let ((skip-blanks
21552 (function
21553 ;; Return beginning of first non-blank line, starting from
21554 ;; line at POS.
21555 (lambda (pos)
21556 (save-excursion
21557 (goto-char pos)
21558 (while (org-at-comment-p) (forward-line))
21559 (skip-chars-forward " \r\t\n")
21560 (point-at-bol)))))
21561 beg end toggled)
21562 ;; Determine boundaries of changes. If a universal prefix has
21563 ;; been given, put the list in a region. If region ends at a bol,
21564 ;; do not consider the last line to be in the region.
21566 (when (and current-prefix-arg (org-at-item-p))
21567 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21568 (org-mark-element))
21570 (if (org-region-active-p)
21571 (setq beg (funcall skip-blanks (region-beginning))
21572 end (copy-marker (save-excursion
21573 (goto-char (region-end))
21574 (if (bolp) (point) (point-at-eol)))))
21575 (setq beg (funcall skip-blanks (point-at-bol))
21576 end (copy-marker (point-at-eol))))
21577 ;; Ensure inline tasks don't count as headings.
21578 (org-with-limited-levels
21579 (save-excursion
21580 (goto-char beg)
21581 (cond
21582 ;; Case 1. Started at an heading: de-star headings.
21583 ((org-at-heading-p)
21584 (while (< (point) end)
21585 (when (org-at-heading-p t)
21586 (looking-at org-outline-regexp) (replace-match "")
21587 (setq toggled t))
21588 (forward-line)))
21589 ;; Case 2. Started at an item: change items into headlines.
21590 ;; One star will be added by `org-list-to-subtree'.
21591 ((org-at-item-p)
21592 (while (< (point) end)
21593 (when (org-at-item-p)
21594 ;; Pay attention to cases when region ends before list.
21595 (let* ((struct (org-list-struct))
21596 (list-end
21597 (min (org-list-get-bottom-point struct) (1+ end))))
21598 (save-restriction
21599 (narrow-to-region (point) list-end)
21600 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21601 (setq toggled t))
21602 (forward-line)))
21603 ;; Case 3. Started at normal text: make every line an heading,
21604 ;; skipping headlines and items.
21605 (t (let* ((stars
21606 (make-string
21607 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21608 (add-stars
21609 (cond (nstars "") ; stars from prefix only
21610 ((equal stars "") "*") ; before first heading
21611 (org-odd-levels-only "**") ; inside heading, odd
21612 (t "*"))) ; inside heading, oddeven
21613 (rpl (concat stars add-stars " "))
21614 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21615 (while (< (point) (if (equal nstars '(4)) lend end))
21616 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21617 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21618 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21619 (forward-line)))))))
21620 (unless toggled (message "Cannot toggle heading from here"))))
21622 (defun org-meta-return (&optional _arg)
21623 "Insert a new heading or wrap a region in a table.
21624 Calls `org-insert-heading' or `org-table-wrap-region', depending
21625 on context. See the individual commands for more information."
21626 (interactive)
21627 (org-check-before-invisible-edit 'insert)
21628 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21629 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21630 #'org-insert-heading))))
21632 ;;; Menu entries
21634 (defsubst org-in-subtree-not-table-p ()
21635 "Are we in a subtree and not in a table?"
21636 (and (not (org-before-first-heading-p))
21637 (not (org-at-table-p))))
21639 ;; Define the Org-mode menus
21640 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21641 '("Tbl"
21642 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21643 ["Next Field" org-cycle (org-at-table-p)]
21644 ["Previous Field" org-shifttab (org-at-table-p)]
21645 ["Next Row" org-return (org-at-table-p)]
21646 "--"
21647 ["Blank Field" org-table-blank-field (org-at-table-p)]
21648 ["Edit Field" org-table-edit-field (org-at-table-p)]
21649 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21650 "--"
21651 ("Column"
21652 ["Move Column Left" org-metaleft (org-at-table-p)]
21653 ["Move Column Right" org-metaright (org-at-table-p)]
21654 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21655 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21656 ("Row"
21657 ["Move Row Up" org-metaup (org-at-table-p)]
21658 ["Move Row Down" org-metadown (org-at-table-p)]
21659 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21660 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21661 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21662 "--"
21663 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21664 ("Rectangle"
21665 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21666 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21667 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21668 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21669 "--"
21670 ("Calculate"
21671 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21672 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21673 ["Edit Formulas" org-edit-special (org-at-table-p)]
21674 "--"
21675 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21676 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21677 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21678 "--"
21679 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21680 "--"
21681 ["Sum Column/Rectangle" org-table-sum
21682 (or (org-at-table-p) (org-region-active-p))]
21683 ["Which Column?" org-table-current-column (org-at-table-p)])
21684 ["Debug Formulas"
21685 org-table-toggle-formula-debugger
21686 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21687 ["Show Col/Row Numbers"
21688 org-table-toggle-coordinate-overlays
21689 :style toggle
21690 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21691 "--"
21692 ["Create" org-table-create (and (not (org-at-table-p))
21693 org-enable-table-editor)]
21694 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21695 ["Import from File" org-table-import (not (org-at-table-p))]
21696 ["Export to File" org-table-export (org-at-table-p)]
21697 "--"
21698 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21699 "--"
21700 ("Plot"
21701 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21702 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21704 (easy-menu-define org-org-menu org-mode-map "Org menu"
21705 '("Org"
21706 ("Show/Hide"
21707 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21708 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21709 ["Sparse Tree..." org-sparse-tree t]
21710 ["Reveal Context" org-reveal t]
21711 ["Show All" outline-show-all t]
21712 "--"
21713 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21714 "--"
21715 ["New Heading" org-insert-heading t]
21716 ("Navigate Headings"
21717 ["Up" outline-up-heading t]
21718 ["Next" outline-next-visible-heading t]
21719 ["Previous" outline-previous-visible-heading t]
21720 ["Next Same Level" outline-forward-same-level t]
21721 ["Previous Same Level" outline-backward-same-level t]
21722 "--"
21723 ["Jump" org-goto t])
21724 ("Edit Structure"
21725 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21726 "--"
21727 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21728 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21729 "--"
21730 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21731 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21732 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21733 "--"
21734 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21735 "--"
21736 ["Copy visible text" org-copy-visible t]
21737 "--"
21738 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21739 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21740 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21741 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21742 "--"
21743 ["Sort Region/Children" org-sort t]
21744 "--"
21745 ["Convert to odd levels" org-convert-to-odd-levels t]
21746 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21747 ("Editing"
21748 ["Emphasis..." org-emphasize t]
21749 ["Edit Source Example" org-edit-special t]
21750 "--"
21751 ["Footnote new/jump" org-footnote-action t]
21752 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21753 ("Archive"
21754 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21755 "--"
21756 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21757 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21758 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21760 "--"
21761 ("Hyperlinks"
21762 ["Store Link (Global)" org-store-link t]
21763 ["Find existing link to here" org-occur-link-in-agenda-files t]
21764 ["Insert Link" org-insert-link t]
21765 ["Follow Link" org-open-at-point t]
21766 "--"
21767 ["Next link" org-next-link t]
21768 ["Previous link" org-previous-link t]
21769 "--"
21770 ["Descriptive Links"
21771 org-toggle-link-display
21772 :style radio
21773 :selected org-descriptive-links
21775 ["Literal Links"
21776 org-toggle-link-display
21777 :style radio
21778 :selected (not org-descriptive-links)])
21779 "--"
21780 ("TODO Lists"
21781 ["TODO/DONE/-" org-todo t]
21782 ("Select keyword"
21783 ["Next keyword" org-shiftright (org-at-heading-p)]
21784 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21785 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21786 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21787 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21788 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21789 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21790 "--"
21791 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21792 :selected org-enforce-todo-dependencies :style toggle :active t]
21793 "Settings for tree at point"
21794 ["Do Children sequentially" org-toggle-ordered-property :style radio
21795 :selected (org-entry-get nil "ORDERED")
21796 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21797 ["Do Children parallel" org-toggle-ordered-property :style radio
21798 :selected (not (org-entry-get nil "ORDERED"))
21799 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21800 "--"
21801 ["Set Priority" org-priority t]
21802 ["Priority Up" org-shiftup t]
21803 ["Priority Down" org-shiftdown t]
21804 "--"
21805 ["Get news from all feeds" org-feed-update-all t]
21806 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21807 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21808 ("TAGS and Properties"
21809 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21810 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21811 "--"
21812 ["Set property" org-set-property (not (org-before-first-heading-p))]
21813 ["Column view of properties" org-columns t]
21814 ["Insert Column View DBlock" org-insert-columns-dblock t])
21815 ("Dates and Scheduling"
21816 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21817 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21818 ("Change Date"
21819 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21820 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21821 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21822 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21823 ["Compute Time Range" org-evaluate-time-range t]
21824 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21825 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21826 "--"
21827 ["Custom time format" org-toggle-time-stamp-overlays
21828 :style radio :selected org-display-custom-times]
21829 "--"
21830 ["Goto Calendar" org-goto-calendar t]
21831 ["Date from Calendar" org-date-from-calendar t]
21832 "--"
21833 ["Start/Restart Timer" org-timer-start t]
21834 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21835 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21836 ["Insert Timer String" org-timer t]
21837 ["Insert Timer Item" org-timer-item t])
21838 ("Logging work"
21839 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21840 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21841 ["Clock out" org-clock-out t]
21842 ["Clock cancel" org-clock-cancel t]
21843 "--"
21844 ["Mark as default task" org-clock-mark-default-task t]
21845 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21846 ["Goto running clock" org-clock-goto t]
21847 "--"
21848 ["Display times" org-clock-display t]
21849 ["Create clock table" org-clock-report t]
21850 "--"
21851 ["Record DONE time"
21852 (progn (setq org-log-done (not org-log-done))
21853 (message "Switching to %s will %s record a timestamp"
21854 (car org-done-keywords)
21855 (if org-log-done "automatically" "not")))
21856 :style toggle :selected org-log-done])
21857 "--"
21858 ["Agenda Command..." org-agenda t]
21859 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21860 ("File List for Agenda")
21861 ("Special views current file"
21862 ["TODO Tree" org-show-todo-tree t]
21863 ["Check Deadlines" org-check-deadlines t]
21864 ["Timeline" org-timeline t]
21865 ["Tags/Property tree" org-match-sparse-tree t])
21866 "--"
21867 ["Export/Publish..." org-export-dispatch t]
21868 ("LaTeX"
21869 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21870 :selected org-cdlatex-mode]
21871 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21872 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21873 ["Modify math symbol" org-cdlatex-math-modify
21874 (org-inside-LaTeX-fragment-p)]
21875 ["Insert citation" org-reftex-citation t]
21876 "--"
21877 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21878 "--"
21879 ("MobileOrg"
21880 ["Push Files and Views" org-mobile-push t]
21881 ["Get Captured and Flagged" org-mobile-pull t]
21882 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21883 "--"
21884 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21885 "--"
21886 ("Documentation"
21887 ["Show Version" org-version t]
21888 ["Info Documentation" org-info t])
21889 ("Customize"
21890 ["Browse Org Group" org-customize t]
21891 "--"
21892 ["Expand This Menu" org-create-customize-menu
21893 (fboundp 'customize-menu-create)])
21894 ["Send bug report" org-submit-bug-report t]
21895 "--"
21896 ("Refresh/Reload"
21897 ["Refresh setup current buffer" org-mode-restart t]
21898 ["Reload Org (after update)" org-reload t]
21899 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21902 (defun org-info (&optional node)
21903 "Read documentation for Org-mode in the info system.
21904 With optional NODE, go directly to that node."
21905 (interactive)
21906 (info (format "(org)%s" (or node ""))))
21908 ;;;###autoload
21909 (defun org-submit-bug-report ()
21910 "Submit a bug report on Org-mode via mail.
21912 Don't hesitate to report any problems or inaccurate documentation.
21914 If you don't have setup sending mail from (X)Emacs, please copy the
21915 output buffer into your mail program, as it gives us important
21916 information about your Org-mode version and configuration."
21917 (interactive)
21918 (require 'reporter)
21919 (defvar reporter-prompt-for-summary-p)
21920 (org-load-modules-maybe)
21921 (org-require-autoloaded-modules)
21922 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21923 (reporter-submit-bug-report
21924 "emacs-orgmode@gnu.org"
21925 (org-version nil 'full)
21926 (let (list)
21927 (save-window-excursion
21928 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21929 (delete-other-windows)
21930 (erase-buffer)
21931 (insert "You are about to submit a bug report to the Org-mode mailing list.
21933 We would like to add your full Org-mode and Outline configuration to the
21934 bug report. This greatly simplifies the work of the maintainer and
21935 other experts on the mailing list.
21937 HOWEVER, some variables you have customized may contain private
21938 information. The names of customers, colleagues, or friends, might
21939 appear in the form of file names, tags, todo states, or search strings.
21940 If you answer yes to the prompt, you might want to check and remove
21941 such private information before sending the email.")
21942 (add-text-properties (point-min) (point-max) '(face org-warning))
21943 (when (yes-or-no-p "Include your Org-mode configuration ")
21944 (mapatoms
21945 (lambda (v)
21946 (and (boundp v)
21947 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21948 (or (and (symbol-value v)
21949 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21950 (and
21951 (get v 'custom-type) (get v 'standard-value)
21952 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21953 (push v list)))))
21954 (kill-buffer (get-buffer "*Warn about privacy*"))
21955 list))
21956 nil nil
21957 "Remember to cover the basics, that is, what you expected to happen and
21958 what in fact did happen. You don't know how to make a good report? See
21960 http://orgmode.org/manual/Feedback.html#Feedback
21962 Your bug report will be posted to the Org-mode mailing list.
21963 ------------------------------------------------------------------------")
21964 (save-excursion
21965 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21966 (replace-match "\\1Bug: \\3 [\\2]")))))
21969 (defun org-install-agenda-files-menu ()
21970 (let ((bl (buffer-list)))
21971 (save-excursion
21972 (while bl
21973 (set-buffer (pop bl))
21974 (when (derived-mode-p 'org-mode) (setq bl nil)))
21975 (when (derived-mode-p 'org-mode)
21976 (easy-menu-change
21977 '("Org") "File List for Agenda"
21978 (append
21979 (list
21980 ["Edit File List" (org-edit-agenda-file-list) t]
21981 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21982 ["Remove Current File from List" org-remove-file t]
21983 ["Cycle through agenda files" org-cycle-agenda-files t]
21984 ["Occur in all agenda files" org-occur-in-agenda-files t]
21985 "--")
21986 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21988 ;;;; Documentation
21990 (defun org-require-autoloaded-modules ()
21991 (interactive)
21992 (mapc #'require
21993 '(org-agenda org-archive org-attach org-clock org-colview org-id
21994 org-table org-timer)))
21996 ;;;###autoload
21997 (defun org-reload (&optional uncompiled)
21998 "Reload all org lisp files.
21999 With prefix arg UNCOMPILED, load the uncompiled versions."
22000 (interactive "P")
22001 (require 'loadhist)
22002 (let* ((org-dir (org-find-library-dir "org"))
22003 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22004 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22005 (remove-re (mapconcat 'identity
22006 (mapcar (lambda (f) (concat "^" f "$"))
22007 (list (if (featurep 'xemacs)
22008 "org-colview"
22009 "org-colview-xemacs")
22010 "org" "org-loaddefs" "org-version"))
22011 "\\|"))
22012 (feats (delete-dups
22013 (mapcar 'file-name-sans-extension
22014 (mapcar 'file-name-nondirectory
22015 (delq nil
22016 (mapcar 'feature-file
22017 features))))))
22018 (lfeat (append
22019 (sort
22020 (setq feats
22021 (delq nil (mapcar
22022 (lambda (f)
22023 (if (and (string-match feature-re f)
22024 (not (string-match remove-re f)))
22025 f nil))
22026 feats)))
22027 'string-lessp)
22028 (list "org-version" "org")))
22029 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22030 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22031 load-uncore load-misses)
22032 (setq load-misses
22033 (delq 't
22034 (mapcar (lambda (f)
22035 (or (org-load-noerror-mustsuffix (concat org-dir f))
22036 (and (string= org-dir contrib-dir)
22037 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22038 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22039 (add-to-list 'load-uncore f 'append)
22042 lfeat)))
22043 (when load-uncore
22044 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22045 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22046 (if load-misses
22047 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22048 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22049 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22051 ;;;###autoload
22052 (defun org-customize ()
22053 "Call the customize function with org as argument."
22054 (interactive)
22055 (org-load-modules-maybe)
22056 (org-require-autoloaded-modules)
22057 (customize-browse 'org))
22059 (defun org-create-customize-menu ()
22060 "Create a full customization menu for Org-mode, insert it into the menu."
22061 (interactive)
22062 (org-load-modules-maybe)
22063 (org-require-autoloaded-modules)
22064 (if (fboundp 'customize-menu-create)
22065 (progn
22066 (easy-menu-change
22067 '("Org") "Customize"
22068 `(["Browse Org group" org-customize t]
22069 "--"
22070 ,(customize-menu-create 'org)
22071 ["Set" Custom-set t]
22072 ["Save" Custom-save t]
22073 ["Reset to Current" Custom-reset-current t]
22074 ["Reset to Saved" Custom-reset-saved t]
22075 ["Reset to Standard Settings" Custom-reset-standard t]))
22076 (message "\"Org\"-menu now contains full customization menu"))
22077 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22079 ;;;; Miscellaneous stuff
22081 ;;; Generally useful functions
22083 (defsubst org-get-at-eol (property n)
22084 "Get text property PROPERTY at the end of line less N characters."
22085 (get-text-property (- (point-at-eol) n) property))
22087 (defun org-find-text-property-in-string (prop s)
22088 "Return the first non-nil value of property PROP in string S."
22089 (or (get-text-property 0 prop s)
22090 (get-text-property (or (next-single-property-change 0 prop s) 0)
22091 prop s)))
22093 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22094 "Display the given MESSAGE as a warning."
22095 (if (fboundp 'display-warning)
22096 (display-warning 'org message
22097 (if (featurep 'xemacs) 'warning :warning))
22098 (let ((buf (get-buffer-create "*Org warnings*")))
22099 (with-current-buffer buf
22100 (goto-char (point-max))
22101 (insert "Warning (Org): " message)
22102 (unless (bolp)
22103 (newline)))
22104 (display-buffer buf)
22105 (sit-for 0))))
22107 (defun org-eval (form)
22108 "Eval FORM and return result."
22109 (condition-case error
22110 (eval form)
22111 (error (format "%%![Error: %s]" error))))
22113 (defun org-in-clocktable-p ()
22114 "Check if the cursor is in a clocktable."
22115 (let ((pos (point)) start)
22116 (save-excursion
22117 (end-of-line 1)
22118 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22119 (setq start (match-beginning 0))
22120 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22121 (>= (match-end 0) pos)
22122 start))))
22124 (defun org-in-verbatim-emphasis ()
22125 (save-match-data
22126 (and (org-in-regexp org-emph-re 2)
22127 (>= (point) (match-beginning 3))
22128 (<= (point) (match-end 4))
22129 (member (match-string 3) '("=" "~")))))
22131 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22132 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22133 (if (and marker (marker-buffer marker)
22134 (buffer-live-p (marker-buffer marker)))
22135 (progn
22136 (org-pop-to-buffer-same-window (marker-buffer marker))
22137 (when (or (> marker (point-max)) (< marker (point-min)))
22138 (widen))
22139 (goto-char marker)
22140 (org-show-context 'org-goto))
22141 (if bookmark
22142 (bookmark-jump bookmark)
22143 (error "Cannot find location"))))
22145 (defun org-quote-csv-field (s)
22146 "Quote field for inclusion in CSV material."
22147 (if (string-match "[\",]" s)
22148 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22151 (defun org-force-self-insert (N)
22152 "Needed to enforce self-insert under remapping."
22153 (interactive "p")
22154 (self-insert-command N))
22156 (defun org-string-width (s)
22157 "Compute width of string, ignoring invisible characters.
22158 This ignores character with invisibility property `org-link', and also
22159 characters with property `org-cwidth', because these will become invisible
22160 upon the next fontification round."
22161 (let (b l)
22162 (when (or (eq t buffer-invisibility-spec)
22163 (assq 'org-link buffer-invisibility-spec))
22164 (while (setq b (text-property-any 0 (length s)
22165 'invisible 'org-link s))
22166 (setq s (concat (substring s 0 b)
22167 (substring s (or (next-single-property-change
22168 b 'invisible s)
22169 (length s)))))))
22170 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22171 (setq s (concat (substring s 0 b)
22172 (substring s (or (next-single-property-change
22173 b 'org-cwidth s)
22174 (length s))))))
22175 (setq l (string-width s) b -1)
22176 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22177 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22180 (defun org-shorten-string (s maxlength)
22181 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22182 If the string is shorter or has length MAXLENGTH, just return the
22183 original string. If it is longer, the functions finds a space in the
22184 string, breaks this string off at that locations and adds three dots
22185 as ellipsis. Including the ellipsis, the string will not be longer
22186 than MAXLENGTH. If finding a good breaking point in the string does
22187 not work, the string is just chopped off in the middle of a word
22188 if necessary."
22189 (if (<= (length s) maxlength)
22191 (let* ((n (max (- maxlength 4) 1))
22192 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22193 (if (string-match re s)
22194 (concat (match-string 1 s) "...")
22195 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22197 (defun org-get-indentation (&optional line)
22198 "Get the indentation of the current line, interpreting tabs.
22199 When LINE is given, assume it represents a line and compute its indentation."
22200 (if line
22201 (when (string-match "^ *" (org-remove-tabs line))
22202 (match-end 0))
22203 (save-excursion
22204 (beginning-of-line 1)
22205 (skip-chars-forward " \t")
22206 (current-column))))
22208 (defun org-get-string-indentation (s)
22209 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22210 (let ((n -1) (i 0) (w tab-width) c)
22211 (catch 'exit
22212 (while (< (setq n (1+ n)) (length s))
22213 (setq c (aref s n))
22214 (cond ((= c ?\ ) (setq i (1+ i)))
22215 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22216 (t (throw 'exit t)))))
22219 (defun org-remove-tabs (s &optional width)
22220 "Replace tabulators in S with spaces.
22221 Assumes that s is a single line, starting in column 0."
22222 (setq width (or width tab-width))
22223 (while (string-match "\t" s)
22224 (setq s (replace-match
22225 (make-string
22226 (- (* width (/ (+ (match-beginning 0) width) width))
22227 (match-beginning 0)) ?\ )
22228 t t s)))
22231 (defun org-fix-indentation (line ind)
22232 "Fix indentation in LINE.
22233 IND is a cons cell with target and minimum indentation.
22234 If the current indentation in LINE is smaller than the minimum,
22235 leave it alone. If it is larger than ind, set it to the target."
22236 (let* ((l (org-remove-tabs line))
22237 (i (org-get-indentation l))
22238 (i1 (car ind)) (i2 (cdr ind)))
22239 (when (>= i i2) (setq l (substring line i2)))
22240 (if (> i1 0)
22241 (concat (make-string i1 ?\ ) l)
22242 l)))
22244 (defun org-remove-indentation (code &optional n)
22245 "Remove maximum common indentation in string CODE and return it.
22246 N may optionally be the number of columns to remove. Return CODE
22247 as-is if removal failed."
22248 (with-temp-buffer
22249 (insert code)
22250 (if (org-do-remove-indentation n) (buffer-string) code)))
22252 (defun org-do-remove-indentation (&optional n)
22253 "Remove the maximum common indentation from the buffer.
22254 When optional argument N is a positive integer, remove exactly
22255 that much characters from indentation, if possible. Return nil
22256 if it fails."
22257 (catch :exit
22258 (goto-char (point-min))
22259 ;; Find maximum common indentation, if not specified.
22260 (let ((n (or n
22261 (let ((min-ind (point-max)))
22262 (save-excursion
22263 (while (re-search-forward "^[ \t]*\\S-" nil t)
22264 (let ((ind (1- (current-column))))
22265 (if (zerop ind) (throw :exit nil)
22266 (setq min-ind (min min-ind ind))))))
22267 min-ind))))
22268 (if (zerop n) (throw :exit nil)
22269 ;; Remove exactly N indentation, but give up if not possible.
22270 (while (not (eobp))
22271 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22272 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22273 ((< ind n) (throw :exit nil))
22274 (t (org-indent-line-to (- ind n))))
22275 (forward-line)))
22276 ;; Signal success.
22277 t))))
22279 (defun org-fill-template (template alist)
22280 "Find each %key of ALIST in TEMPLATE and replace it."
22281 (let ((case-fold-search nil))
22282 (dolist (entry (sort (copy-sequence alist)
22283 (lambda (a b) (< (length (car a)) (length (car b))))))
22284 (setq template
22285 (replace-regexp-in-string
22286 (concat "%" (regexp-quote (car entry)))
22287 (or (cdr entry) "") template t t)))
22288 template))
22290 (defun org-base-buffer (buffer)
22291 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22292 (if (not buffer)
22293 buffer
22294 (or (buffer-base-buffer buffer)
22295 buffer)))
22297 (defun org-wrap (string &optional width lines)
22298 "Wrap string to either a number of lines, or a width in characters.
22299 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22300 that costs. If there is a word longer than WIDTH, the text is actually
22301 wrapped to the length of that word.
22302 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22303 many lines, whatever width that takes.
22304 The return value is a list of lines, without newlines at the end."
22305 (let* ((words (org-split-string string "[ \t\n]+"))
22306 (maxword (apply 'max (mapcar 'org-string-width words)))
22307 w ll)
22308 (cond (width
22309 (org-do-wrap words (max maxword width)))
22310 (lines
22311 (setq w maxword)
22312 (setq ll (org-do-wrap words maxword))
22313 (if (<= (length ll) lines)
22315 (setq ll words)
22316 (while (> (length ll) lines)
22317 (setq w (1+ w))
22318 (setq ll (org-do-wrap words w)))
22319 ll))
22320 (t (error "Cannot wrap this")))))
22322 (defun org-do-wrap (words width)
22323 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22324 (let (lines line)
22325 (while words
22326 (setq line (pop words))
22327 (while (and words (< (+ (length line) (length (car words))) width))
22328 (setq line (concat line " " (pop words))))
22329 (setq lines (push line lines)))
22330 (nreverse lines)))
22332 (defun org-split-string (string &optional separators)
22333 "Splits STRING into substrings at SEPARATORS.
22334 SEPARATORS is a regular expression.
22335 No empty strings are returned if there are matches at the beginning
22336 and end of string."
22337 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22338 (let ((start 0) notfirst list)
22339 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22340 (if (and notfirst
22341 (= start (match-beginning 0))
22342 (< start (length string)))
22343 (1+ start) start))
22344 (< (match-beginning 0) (length string)))
22345 (setq notfirst t)
22346 (or (eq (match-beginning 0) 0)
22347 (and (eq (match-beginning 0) (match-end 0))
22348 (eq (match-beginning 0) start))
22349 (push (substring string start (match-beginning 0)) list))
22350 (setq start (match-end 0)))
22351 (or (eq start (length string))
22352 (push (substring string start) list))
22353 (nreverse list)))
22355 (defun org-quote-vert (s)
22356 "Replace \"|\" with \"\\vert\"."
22357 (while (string-match "|" s)
22358 (setq s (replace-match "\\vert" t t s)))
22361 (defun org-uuidgen-p (s)
22362 "Is S an ID created by UUIDGEN?"
22363 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22365 (defun org-in-src-block-p (&optional inside)
22366 "Whether point is in a code source block.
22367 When INSIDE is non-nil, don't consider we are within a src block
22368 when point is at #+BEGIN_SRC or #+END_SRC."
22369 (let ((case-fold-search t))
22370 (or (and (eq (get-char-property (point) 'src-block) t))
22371 (and (not inside)
22372 (save-match-data
22373 (save-excursion
22374 (beginning-of-line)
22375 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22377 (defun org-context ()
22378 "Return a list of contexts of the current cursor position.
22379 If several contexts apply, all are returned.
22380 Each context entry is a list with a symbol naming the context, and
22381 two positions indicating start and end of the context. Possible
22382 contexts are:
22384 :headline anywhere in a headline
22385 :headline-stars on the leading stars in a headline
22386 :todo-keyword on a TODO keyword (including DONE) in a headline
22387 :tags on the TAGS in a headline
22388 :priority on the priority cookie in a headline
22389 :item on the first line of a plain list item
22390 :item-bullet on the bullet/number of a plain list item
22391 :checkbox on the checkbox in a plain list item
22392 :table in an org-mode table
22393 :table-special on a special filed in a table
22394 :table-table in a table.el table
22395 :clocktable in a clocktable
22396 :src-block in a source block
22397 :link on a hyperlink
22398 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22399 :target on a <<target>>
22400 :radio-target on a <<<radio-target>>>
22401 :latex-fragment on a LaTeX fragment
22402 :latex-preview on a LaTeX fragment with overlaid preview image
22404 This function expects the position to be visible because it uses font-lock
22405 faces as a help to recognize the following contexts: :table-special, :link,
22406 and :keyword."
22407 (let* ((f (get-text-property (point) 'face))
22408 (faces (if (listp f) f (list f)))
22409 (case-fold-search t)
22410 (p (point)) clist o)
22411 ;; First the large context
22412 (cond
22413 ((org-at-heading-p t)
22414 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22415 (when (progn
22416 (beginning-of-line 1)
22417 (looking-at org-todo-line-tags-regexp))
22418 (push (org-point-in-group p 1 :headline-stars) clist)
22419 (push (org-point-in-group p 2 :todo-keyword) clist)
22420 (push (org-point-in-group p 4 :tags) clist))
22421 (goto-char p)
22422 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22423 (when (looking-at "\\[#[A-Z0-9]\\]")
22424 (push (org-point-in-group p 0 :priority) clist)))
22426 ((org-at-item-p)
22427 (push (org-point-in-group p 2 :item-bullet) clist)
22428 (push (list :item (point-at-bol)
22429 (save-excursion (org-end-of-item) (point)))
22430 clist)
22431 (and (org-at-item-checkbox-p)
22432 (push (org-point-in-group p 0 :checkbox) clist)))
22434 ((org-at-table-p)
22435 (push (list :table (org-table-begin) (org-table-end)) clist)
22436 (when (memq 'org-formula faces)
22437 (push (list :table-special
22438 (previous-single-property-change p 'face)
22439 (next-single-property-change p 'face)) clist)))
22440 ((org-at-table-p 'any)
22441 (push (list :table-table) clist)))
22442 (goto-char p)
22444 (let ((case-fold-search t))
22445 ;; New the "medium" contexts: clocktables, source blocks
22446 (cond ((org-in-clocktable-p)
22447 (push (list :clocktable
22448 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22449 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22450 (match-beginning 1))
22451 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22452 (match-end 0))) clist))
22453 ((org-in-src-block-p)
22454 (push (list :src-block
22455 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22456 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22457 (match-beginning 1))
22458 (and (search-forward "#+END_SRC" nil t)
22459 (match-beginning 0))) clist))))
22460 (goto-char p)
22462 ;; Now the small context
22463 (cond
22464 ((org-at-timestamp-p)
22465 (push (org-point-in-group p 0 :timestamp) clist))
22466 ((memq 'org-link faces)
22467 (push (list :link
22468 (previous-single-property-change p 'face)
22469 (next-single-property-change p 'face)) clist))
22470 ((memq 'org-special-keyword faces)
22471 (push (list :keyword
22472 (previous-single-property-change p 'face)
22473 (next-single-property-change p 'face)) clist))
22474 ((org-at-target-p)
22475 (push (org-point-in-group p 0 :target) clist)
22476 (goto-char (1- (match-beginning 0)))
22477 (when (looking-at org-radio-target-regexp)
22478 (push (org-point-in-group p 0 :radio-target) clist))
22479 (goto-char p))
22480 ((setq o (car (delq nil
22481 (mapcar
22482 (lambda (x)
22483 (when (memq x org-latex-fragment-image-overlays) x))
22484 (overlays-at (point))))))
22485 (push (list :latex-fragment
22486 (overlay-start o) (overlay-end o)) clist)
22487 (push (list :latex-preview
22488 (overlay-start o) (overlay-end o)) clist))
22489 ((org-inside-LaTeX-fragment-p)
22490 ;; FIXME: positions wrong.
22491 (push (list :latex-fragment (point) (point)) clist)))
22493 (setq clist (nreverse (delq nil clist)))
22494 clist))
22496 (defun org-in-regexp (regexp &optional nlines visually)
22497 "Check if point is inside a match of REGEXP.
22499 Normally only the current line is checked, but you can include
22500 NLINES extra lines around point into the search. If VISUALLY is
22501 set, require that the cursor is not after the match but really
22502 on, so that the block visually is on the match.
22504 Return nil or a cons cell (BEG . END) where BEG and END are,
22505 respectively, the positions at the beginning and the end of the
22506 match."
22507 (catch :exit
22508 (let ((pos (point))
22509 (eol (line-end-position (if nlines (1+ nlines) 1))))
22510 (save-excursion
22511 (beginning-of-line (- 1 (or nlines 0)))
22512 (while (and (re-search-forward regexp eol t)
22513 (<= (match-beginning 0) pos))
22514 (let ((end (match-end 0)))
22515 (when (or (> end pos) (and (= end pos) (not visually)))
22516 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22517 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22518 "Org mode 8.3")
22520 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22521 "Non-nil when point is between matches of START-RE and END-RE.
22523 Also return a non-nil value when point is on one of the matches.
22525 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22526 buffer positions. Default values are the positions of headlines
22527 surrounding the point.
22529 The functions returns a cons cell whose car (resp. cdr) is the
22530 position before START-RE (resp. after END-RE)."
22531 (save-match-data
22532 (let ((pos (point))
22533 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22534 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22535 beg end)
22536 (save-excursion
22537 ;; Point is on a block when on START-RE or if START-RE can be
22538 ;; found before it...
22539 (and (or (org-in-regexp start-re)
22540 (re-search-backward start-re limit-up t))
22541 (setq beg (match-beginning 0))
22542 ;; ... and END-RE after it...
22543 (goto-char (match-end 0))
22544 (re-search-forward end-re limit-down t)
22545 (> (setq end (match-end 0)) pos)
22546 ;; ... without another START-RE in-between.
22547 (goto-char (match-beginning 0))
22548 (not (re-search-backward start-re (1+ beg) t))
22549 ;; Return value.
22550 (cons beg end))))))
22552 (defun org-in-block-p (names)
22553 "Non-nil when point belongs to a block whose name belongs to NAMES.
22555 NAMES is a list of strings containing names of blocks.
22557 Return first block name matched, or nil. Beware that in case of
22558 nested blocks, the returned name may not belong to the closest
22559 block from point."
22560 (save-match-data
22561 (catch 'exit
22562 (let ((case-fold-search t)
22563 (lim-up (save-excursion (outline-previous-heading)))
22564 (lim-down (save-excursion (outline-next-heading))))
22565 (dolist (name names)
22566 (let ((n (regexp-quote name)))
22567 (when (org-between-regexps-p
22568 (concat "^[ \t]*#\\+begin_" n)
22569 (concat "^[ \t]*#\\+end_" n)
22570 lim-up lim-down)
22571 (throw 'exit n)))))
22572 nil)))
22574 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22575 "Call `multi-occur' with buffers for all agenda files."
22576 (interactive "sOrg-files matching: ")
22577 (let* ((files (org-agenda-files))
22578 (tnames (mapcar #'file-truename files))
22579 (extra org-agenda-text-search-extra-files))
22580 (when (eq (car extra) 'agenda-archives)
22581 (setq extra (cdr extra))
22582 (setq files (org-add-archive-files files)))
22583 (dolist (f extra)
22584 (unless (member (file-truename f) tnames)
22585 (unless (member f files) (setq files (append files (list f))))
22586 (setq tnames (append tnames (list (file-truename f))))))
22587 (multi-occur
22588 (mapcar (lambda (x)
22589 (with-current-buffer
22590 ;; FIXME: Why not just (find-file-noselect x)?
22591 ;; Is it to avoid the "revert buffer" prompt?
22592 (or (get-file-buffer x) (find-file-noselect x))
22593 (widen)
22594 (current-buffer)))
22595 files)
22596 regexp)))
22598 (if (boundp 'occur-mode-find-occurrence-hook)
22599 ;; Emacs 23
22600 (add-hook 'occur-mode-find-occurrence-hook
22601 (lambda ()
22602 (when (derived-mode-p 'org-mode)
22603 (org-reveal))))
22604 ;; Emacs 22
22605 (defadvice occur-mode-goto-occurrence
22606 (after org-occur-reveal activate)
22607 (and (derived-mode-p 'org-mode) (org-reveal)))
22608 (defadvice occur-mode-goto-occurrence-other-window
22609 (after org-occur-reveal activate)
22610 (and (derived-mode-p 'org-mode) (org-reveal)))
22611 (defadvice occur-mode-display-occurrence
22612 (after org-occur-reveal activate)
22613 (when (derived-mode-p 'org-mode)
22614 (let ((pos (occur-mode-find-occurrence)))
22615 (with-current-buffer (marker-buffer pos)
22616 (save-excursion
22617 (goto-char pos)
22618 (org-reveal)))))))
22620 (defun org-occur-link-in-agenda-files ()
22621 "Create a link and search for it in the agendas.
22622 The link is not stored in `org-stored-links', it is just created
22623 for the search purpose."
22624 (interactive)
22625 (let ((link (condition-case nil
22626 (org-store-link nil)
22627 (error "Unable to create a link to here"))))
22628 (org-occur-in-agenda-files (regexp-quote link))))
22630 (defun org-reverse-string (string)
22631 "Return the reverse of STRING."
22632 (apply 'string (reverse (string-to-list string))))
22634 ;; defsubst org-uniquify must be defined before first use
22636 (defun org-uniquify-alist (alist)
22637 "Merge elements of ALIST with the same key.
22639 For example, in this alist:
22641 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22642 => \\='((a 1 3) (b 2))
22644 merge (a 1) and (a 3) into (a 1 3).
22646 The function returns the new ALIST."
22647 (let (rtn)
22648 (dolist (e alist rtn)
22649 (let (n)
22650 (if (not (assoc (car e) rtn))
22651 (push e rtn)
22652 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22653 (setq rtn (assq-delete-all (car e) rtn))
22654 (push n rtn))))))
22656 (defun org-delete-all (elts list)
22657 "Remove all elements in ELTS from LIST."
22658 (while elts
22659 (setq list (delete (pop elts) list)))
22660 list)
22662 (defun org-back-over-empty-lines ()
22663 "Move backwards over whitespace, to the beginning of the first empty line.
22664 Returns the number of empty lines passed."
22665 (let ((pos (point)))
22666 (if (cdr (assoc 'heading org-blank-before-new-entry))
22667 (skip-chars-backward " \t\n\r")
22668 (unless (eobp)
22669 (forward-line -1)))
22670 (beginning-of-line 2)
22671 (goto-char (min (point) pos))
22672 (count-lines (point) pos)))
22674 (defun org-skip-whitespace ()
22675 (skip-chars-forward " \t\n\r"))
22677 (defun org-point-in-group (point group &optional context)
22678 "Check if POINT is in match-group GROUP.
22679 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22680 match. If the match group does not exist or point is not inside it,
22681 return nil."
22682 (and (match-beginning group)
22683 (>= point (match-beginning group))
22684 (<= point (match-end group))
22685 (if context
22686 (list context (match-beginning group) (match-end group))
22687 t)))
22689 (defun org-switch-to-buffer-other-window (&rest args)
22690 "Switch to buffer in a second window on the current frame.
22691 In particular, do not allow pop-up frames.
22692 Returns the newly created buffer."
22693 (org-no-popups
22694 (apply 'switch-to-buffer-other-window args)))
22696 (defun org-combine-plists (&rest plists)
22697 "Create a single property list from all plists in PLISTS.
22698 The process starts by copying the first list, and then setting properties
22699 from the other lists. Settings in the last list are the most significant
22700 ones and overrule settings in the other lists."
22701 (let ((rtn (copy-sequence (pop plists)))
22702 p v ls)
22703 (while plists
22704 (setq ls (pop plists))
22705 (while ls
22706 (setq p (pop ls) v (pop ls))
22707 (setq rtn (plist-put rtn p v))))
22708 rtn))
22710 (defun org-replace-escapes (string table)
22711 "Replace %-escapes in STRING with values in TABLE.
22712 TABLE is an association list with keys like \"%a\" and string values.
22713 The sequences in STRING may contain normal field width and padding information,
22714 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22715 so values can contain further %-escapes if they are define later in TABLE."
22716 (let ((tbl (copy-alist table))
22717 (case-fold-search nil)
22718 (pchg 0)
22719 re rpl)
22720 (dolist (e tbl)
22721 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22722 (when (and (cdr e) (string-match re (cdr e)))
22723 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22724 (safe "SREF"))
22725 (add-text-properties 0 3 (list 'sref sref) safe)
22726 (setcdr e (replace-match safe t t (cdr e)))))
22727 (while (string-match re string)
22728 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22729 (cdr e)))
22730 (setq string (replace-match rpl t t string))))
22731 (while (setq pchg (next-property-change pchg string))
22732 (let ((sref (get-text-property pchg 'sref string)))
22733 (when (and sref (string-match "SREF" string pchg))
22734 (setq string (replace-match sref t t string)))))
22735 string))
22737 (defun org-sublist (list start end)
22738 "Return a section of LIST, from START to END.
22740 Counting starts at 1."
22741 (cl-subseq list (1- start) end))
22742 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22744 (defun org-find-base-buffer-visiting (file)
22745 "Like `find-buffer-visiting' but always return the base buffer and
22746 not an indirect buffer."
22747 (let ((buf (or (get-file-buffer file)
22748 (find-buffer-visiting file))))
22749 (if buf
22750 (or (buffer-base-buffer buf) buf)
22751 nil)))
22753 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22754 "Org 9.0")
22756 ;;; TODO: Only called once, from ox-odt which should probably use
22757 ;;; org-export-inline-image-p or something.
22758 (defun org-file-image-p (file)
22759 "Return non-nil if FILE is an image."
22760 (save-match-data
22761 (string-match (image-file-name-regexp) file)))
22763 (defun org-get-cursor-date (&optional with-time)
22764 "Return the date at cursor in as a time.
22765 This works in the calendar and in the agenda, anywhere else it just
22766 returns the current time.
22767 If WITH-TIME is non-nil, returns the time of the event at point (in
22768 the agenda) or the current time of the day."
22769 (let (date day defd tp hod mod)
22770 (when with-time
22771 (setq tp (get-text-property (point) 'time))
22772 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22773 (setq hod (string-to-number (match-string 1 tp))
22774 mod (string-to-number (match-string 2 tp))))
22775 (or tp (let ((now (decode-time)))
22776 (setq hod (nth 2 now)
22777 mod (nth 1 now)))))
22778 (cond
22779 ((eq major-mode 'calendar-mode)
22780 (setq date (calendar-cursor-to-date)
22781 defd (encode-time 0 (or mod 0) (or hod 0)
22782 (nth 1 date) (nth 0 date) (nth 2 date))))
22783 ((eq major-mode 'org-agenda-mode)
22784 (setq day (get-text-property (point) 'day))
22785 (when day
22786 (setq date (calendar-gregorian-from-absolute day)
22787 defd (encode-time 0 (or mod 0) (or hod 0)
22788 (nth 1 date) (nth 0 date) (nth 2 date))))))
22789 (or defd (current-time))))
22791 (defun org-mark-subtree (&optional up)
22792 "Mark the current subtree.
22793 This puts point at the start of the current subtree, and mark at
22794 the end. If a numeric prefix UP is given, move up into the
22795 hierarchy of headlines by UP levels before marking the subtree."
22796 (interactive "P")
22797 (org-with-limited-levels
22798 (cond ((org-at-heading-p) (beginning-of-line))
22799 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22800 (t (outline-previous-visible-heading 1))))
22801 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22802 (if (org-called-interactively-p 'any)
22803 (call-interactively 'org-mark-element)
22804 (org-mark-element)))
22807 ;;; Indentation
22809 (defun org--get-expected-indentation (element contentsp)
22810 "Expected indentation column for current line, according to ELEMENT.
22811 ELEMENT is an element containing point. CONTENTSP is non-nil
22812 when indentation is to be computed according to contents of
22813 ELEMENT."
22814 (let ((type (org-element-type element))
22815 (start (org-element-property :begin element))
22816 (post-affiliated (org-element-property :post-affiliated element)))
22817 (org-with-wide-buffer
22818 (cond
22819 (contentsp
22820 (case type
22821 ((diary-sexp footnote-definition) 0)
22822 ((headline inlinetask nil)
22823 (if (not org-adapt-indentation) 0
22824 (let ((level (org-current-level)))
22825 (if level (1+ level) 0))))
22826 ((item plain-list) (org-list-item-body-column post-affiliated))
22828 (goto-char start)
22829 (org-get-indentation))))
22830 ((memq type '(headline inlinetask nil))
22831 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22832 (org--get-expected-indentation element t)
22834 ((memq type '(diary-sexp footnote-definition)) 0)
22835 ;; First paragraph of a footnote definition or an item.
22836 ;; Indent like parent.
22837 ((< (line-beginning-position) start)
22838 (org--get-expected-indentation
22839 (org-element-property :parent element) t))
22840 ;; At first line: indent according to previous sibling, if any,
22841 ;; ignoring footnote definitions and inline tasks, or parent's
22842 ;; contents.
22843 ((= (line-beginning-position) start)
22844 (catch 'exit
22845 (while t
22846 (if (= (point-min) start) (throw 'exit 0)
22847 (goto-char (1- start))
22848 (let* ((previous (org-element-at-point))
22849 (parent previous))
22850 (while (and parent (<= (org-element-property :end parent) start))
22851 (setq previous parent
22852 parent (org-element-property :parent parent)))
22853 (cond
22854 ((not previous) (throw 'exit 0))
22855 ((> (org-element-property :end previous) start)
22856 (throw 'exit (org--get-expected-indentation previous t)))
22857 ((memq (org-element-type previous)
22858 '(footnote-definition inlinetask))
22859 (setq start (org-element-property :begin previous)))
22860 (t (goto-char (org-element-property :begin previous))
22861 (throw 'exit
22862 (if (bolp) (org-get-indentation)
22863 ;; At first paragraph in an item or
22864 ;; a footnote definition.
22865 (org--get-expected-indentation
22866 (org-element-property :parent previous) t))))))))))
22867 ;; Otherwise, move to the first non-blank line above.
22869 (beginning-of-line)
22870 (let ((pos (point)))
22871 (skip-chars-backward " \r\t\n")
22872 (cond
22873 ;; Two blank lines end a footnote definition or a plain
22874 ;; list. When we indent an empty line after them, the
22875 ;; containing list or footnote definition is over, so it
22876 ;; qualifies as a previous sibling. Therefore, we indent
22877 ;; like its first line.
22878 ((and (memq type '(footnote-definition plain-list))
22879 (> (count-lines (point) pos) 2))
22880 (goto-char start)
22881 (org-get-indentation))
22882 ;; Line above is the first one of a paragraph at the
22883 ;; beginning of an item or a footnote definition. Indent
22884 ;; like parent.
22885 ((< (line-beginning-position) start)
22886 (org--get-expected-indentation
22887 (org-element-property :parent element) t))
22888 ;; Line above is the beginning of an element, i.e., point
22889 ;; was originally on the blank lines between element's start
22890 ;; and contents.
22891 ((= (line-beginning-position) post-affiliated)
22892 (org--get-expected-indentation element t))
22893 ;; POS is after contents in a greater element. Indent like
22894 ;; the beginning of the element.
22896 ;; As a special case, if point is at the end of a footnote
22897 ;; definition or an item, indent like the very last element
22898 ;; within.
22899 ((and (not (eq type 'paragraph))
22900 (let ((cend (org-element-property :contents-end element)))
22901 (and cend (<= cend pos))))
22902 (if (memq type '(footnote-definition item plain-list))
22903 (let ((last (org-element-at-point)))
22904 (org--get-expected-indentation
22905 last
22906 (memq (org-element-type last)
22907 '(footnote-definition item plain-list))))
22908 (goto-char start)
22909 (org-get-indentation)))
22910 ;; In any other case, indent like the current line.
22911 (t (org-get-indentation)))))))))
22913 (defun org--align-node-property ()
22914 "Align node property at point.
22915 Alignment is done according to `org-property-format', which see."
22916 (when (save-excursion
22917 (beginning-of-line)
22918 (looking-at org-property-re))
22919 (replace-match
22920 (concat (match-string 4)
22921 (org-trim
22922 (format org-property-format (match-string 1) (match-string 3))))
22923 t t)))
22925 (defun org-indent-line ()
22926 "Indent line depending on context.
22928 Indentation is done according to the following rules:
22930 - Footnote definitions, diary sexps, headlines and inline tasks
22931 have to start at column 0.
22933 - On the very first line of an element, consider, in order, the
22934 next rules until one matches:
22936 1. If there's a sibling element before, ignoring footnote
22937 definitions and inline tasks, indent like its first line.
22939 2. If element has a parent, indent like its contents. More
22940 precisely, if parent is an item, indent after the
22941 description part, if any, or the bullet (see
22942 `org-list-description-max-indent'). Else, indent like
22943 parent's first line.
22945 3. Otherwise, indent relatively to current level, if
22946 `org-adapt-indentation' is non-nil, or to left margin.
22948 - On a blank line at the end of an element, indent according to
22949 the type of the element. More precisely
22951 1. If element is a plain list, an item, or a footnote
22952 definition, indent like the very last element within.
22954 2. If element is a paragraph, indent like its last non blank
22955 line.
22957 3. Otherwise, indent like its very first line.
22959 - In the code part of a source block, use language major mode
22960 to indent current line if `org-src-tab-acts-natively' is
22961 non-nil. If it is nil, do nothing.
22963 - Otherwise, indent like the first non-blank line above.
22965 The function doesn't indent an item as it could break the whole
22966 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22967 \\[org-shiftmetaright].
22969 Also align node properties according to `org-property-format'."
22970 (interactive)
22971 (cond
22972 (orgstruct-is-++
22973 (let ((indent-line-function
22974 (cadadr (assq 'indent-line-function org-fb-vars))))
22975 (indent-according-to-mode)))
22976 ((org-at-heading-p) 'noindent)
22978 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22979 (type (org-element-type element)))
22980 (cond ((and (memq type '(plain-list item))
22981 (= (line-beginning-position)
22982 (org-element-property :post-affiliated element)))
22983 'noindent)
22984 ((and (eq type 'src-block)
22985 org-src-tab-acts-natively
22986 (> (line-beginning-position)
22987 (org-element-property :post-affiliated element))
22988 (< (line-beginning-position)
22989 (org-with-wide-buffer
22990 (goto-char (org-element-property :end element))
22991 (skip-chars-backward " \r\t\n")
22992 (line-beginning-position))))
22993 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22995 (let ((column (org--get-expected-indentation element nil)))
22996 ;; Preserve current column.
22997 (if (<= (current-column) (current-indentation))
22998 (org-indent-line-to column)
22999 (save-excursion (org-indent-line-to column))))
23000 ;; Align node property. Also preserve current column.
23001 (when (eq type 'node-property)
23002 (let ((column (current-column)))
23003 (org--align-node-property)
23004 (org-move-to-column column)))))))))
23006 (defun org-indent-region (start end)
23007 "Indent each non-blank line in the region.
23008 Called from a program, START and END specify the region to
23009 indent. The function will not indent contents of example blocks,
23010 verse blocks and export blocks as leading white spaces are
23011 assumed to be significant there."
23012 (interactive "r")
23013 (save-excursion
23014 (goto-char start)
23015 (skip-chars-forward " \r\t\n")
23016 (unless (eobp) (beginning-of-line))
23017 (let ((indent-to
23018 (lambda (ind pos)
23019 ;; Set IND as indentation for all lines between point and
23020 ;; POS. Blank lines are ignored. Leave point after POS
23021 ;; once done.
23022 (let ((limit (copy-marker pos)))
23023 (while (< (point) limit)
23024 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23025 (forward-line))
23026 (set-marker limit nil))))
23027 (end (copy-marker end)))
23028 (while (< (point) end)
23029 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23030 (let* ((element (org-element-at-point))
23031 (type (org-element-type element))
23032 (element-end (copy-marker (org-element-property :end element)))
23033 (ind (org--get-expected-indentation element nil)))
23034 (cond
23035 ((or (memq type '(paragraph table table-row))
23036 (not (or (org-element-property :contents-begin element)
23037 (memq type
23038 '(example-block export-block src-block)))))
23039 ;; Elements here are indented as a single block. Also
23040 ;; align node properties.
23041 (when (eq type 'node-property)
23042 (org--align-node-property)
23043 (beginning-of-line))
23044 (funcall indent-to ind (min element-end end)))
23046 ;; Elements in this category consist of three parts:
23047 ;; before the contents, the contents, and after the
23048 ;; contents. The contents are treated specially,
23049 ;; according to the element type, or not indented at
23050 ;; all. Other parts are indented as a single block.
23051 (let* ((post (copy-marker
23052 (org-element-property :post-affiliated element)))
23053 (cbeg
23054 (copy-marker
23055 (cond
23056 ((not (org-element-property :contents-begin element))
23057 ;; Fake contents for source blocks.
23058 (org-with-wide-buffer
23059 (goto-char post)
23060 (forward-line)
23061 (point)))
23062 ((memq type '(footnote-definition item plain-list))
23063 ;; Contents in these elements could start on
23064 ;; the same line as the beginning of the
23065 ;; element. Make sure we start indenting
23066 ;; from the second line.
23067 (org-with-wide-buffer
23068 (goto-char post)
23069 (end-of-line)
23070 (skip-chars-forward " \r\t\n")
23071 (if (eobp) (point) (line-beginning-position))))
23072 (t (org-element-property :contents-begin element)))))
23073 (cend (copy-marker
23074 (or (org-element-property :contents-end element)
23075 ;; Fake contents for source blocks.
23076 (org-with-wide-buffer
23077 (goto-char element-end)
23078 (skip-chars-backward " \r\t\n")
23079 (line-beginning-position)))
23080 t)))
23081 ;; Do not change items indentation individually as it
23082 ;; might break the list as a whole. On the other
23083 ;; hand, when at a plain list, indent it as a whole.
23084 (cond ((eq type 'plain-list)
23085 (let ((offset (- ind (org-get-indentation))))
23086 (unless (zerop offset)
23087 (indent-rigidly (org-element-property :begin element)
23088 (org-element-property :end element)
23089 offset))
23090 (goto-char cbeg)))
23091 ((eq type 'item) (goto-char cbeg))
23092 (t (funcall indent-to ind (min cbeg end))))
23093 (when (< (point) end)
23094 (case type
23095 ((example-block export-block verse-block))
23096 (src-block
23097 ;; In a source block, indent source code
23098 ;; according to language major mode, but only if
23099 ;; `org-src-tab-acts-natively' is non-nil.
23100 (when (and (< (point) end) org-src-tab-acts-natively)
23101 (ignore-errors
23102 (org-babel-do-in-edit-buffer
23103 (indent-region (point-min) (point-max))))))
23104 (t (org-indent-region (point) (min cend end))))
23105 (goto-char (min cend end))
23106 (when (< (point) end)
23107 (funcall indent-to ind (min element-end end))))
23108 (set-marker post nil)
23109 (set-marker cbeg nil)
23110 (set-marker cend nil))))
23111 (set-marker element-end nil))))
23112 (set-marker end nil))))
23114 (defun org-indent-drawer ()
23115 "Indent the drawer at point."
23116 (interactive)
23117 (unless (save-excursion
23118 (beginning-of-line)
23119 (org-looking-at-p org-drawer-regexp))
23120 (user-error "Not at a drawer"))
23121 (let ((element (org-element-at-point)))
23122 (unless (memq (org-element-type element) '(drawer property-drawer))
23123 (user-error "Not at a drawer"))
23124 (org-with-wide-buffer
23125 (org-indent-region (org-element-property :begin element)
23126 (org-element-property :end element))))
23127 (message "Drawer at point indented"))
23129 (defun org-indent-block ()
23130 "Indent the block at point."
23131 (interactive)
23132 (unless (save-excursion
23133 (beginning-of-line)
23134 (let ((case-fold-search t))
23135 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23136 (user-error "Not at a block"))
23137 (let ((element (org-element-at-point)))
23138 (unless (memq (org-element-type element)
23139 '(comment-block center-block dynamic-block example-block
23140 export-block quote-block special-block
23141 src-block verse-block))
23142 (user-error "Not at a block"))
23143 (org-with-wide-buffer
23144 (org-indent-region (org-element-property :begin element)
23145 (org-element-property :end element))))
23146 (message "Block at point indented"))
23149 ;;; Filling
23151 ;; We use our own fill-paragraph and auto-fill functions.
23153 ;; `org-fill-paragraph' relies on adaptive filling and context
23154 ;; checking. Appropriate `fill-prefix' is computed with
23155 ;; `org-adaptive-fill-function'.
23157 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23158 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23159 ;; `org-adaptive-fill-function' value. Internally,
23160 ;; `org-comment-line-break-function' breaks the line.
23162 ;; `org-setup-filling' installs filling and auto-filling related
23163 ;; variables during `org-mode' initialization.
23165 (defvar org-element-paragraph-separate) ; org-element.el
23166 (defun org-setup-filling ()
23167 (require 'org-element)
23168 ;; Prevent auto-fill from inserting unwanted new items.
23169 (when (boundp 'fill-nobreak-predicate)
23170 (setq-local
23171 fill-nobreak-predicate
23172 (org-uniquify
23173 (append fill-nobreak-predicate
23174 '(org-fill-line-break-nobreak-p
23175 org-fill-paragraph-with-timestamp-nobreak-p)))))
23176 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23177 (setq-local paragraph-start paragraph-ending)
23178 (setq-local paragraph-separate paragraph-ending))
23179 (setq-local fill-paragraph-function 'org-fill-paragraph)
23180 (setq-local auto-fill-inhibit-regexp nil)
23181 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23182 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23183 (setq-local comment-line-break-function 'org-comment-line-break-function))
23185 (defun org-fill-line-break-nobreak-p ()
23186 "Non-nil when a new line at point would create an Org line break."
23187 (save-excursion
23188 (skip-chars-backward "[ \t]")
23189 (skip-chars-backward "\\\\")
23190 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23192 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23193 "Non-nil when a new line at point would split a timestamp."
23194 (and (org-at-timestamp-p t)
23195 (not (looking-at org-ts-regexp-both))))
23197 (declare-function message-in-body-p "message" ())
23198 (defvar orgtbl-line-start-regexp) ; From org-table.el
23199 (defun org-adaptive-fill-function ()
23200 "Compute a fill prefix for the current line.
23201 Return fill prefix, as a string, or nil if current line isn't
23202 meant to be filled. For convenience, if `adaptive-fill-regexp'
23203 matches in paragraphs or comments, use it."
23204 (catch 'exit
23205 (when (derived-mode-p 'message-mode)
23206 (save-excursion
23207 (beginning-of-line)
23208 (cond ((not (message-in-body-p)) (throw 'exit nil))
23209 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23210 ((looking-at message-cite-prefix-regexp)
23211 (throw 'exit (match-string-no-properties 0)))
23212 ((looking-at org-outline-regexp)
23213 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23214 (org-with-wide-buffer
23215 (unless (org-at-heading-p)
23216 (let* ((p (line-beginning-position))
23217 (element (save-excursion
23218 (beginning-of-line)
23219 (org-element-at-point)))
23220 (type (org-element-type element))
23221 (post-affiliated (org-element-property :post-affiliated element)))
23222 (unless (< p post-affiliated)
23223 (case type
23224 (comment
23225 (save-excursion
23226 (beginning-of-line)
23227 (looking-at "[ \t]*")
23228 (concat (match-string 0) "# ")))
23229 (footnote-definition "")
23230 ((item plain-list)
23231 (make-string (org-list-item-body-column post-affiliated) ?\s))
23232 (paragraph
23233 ;; Fill prefix is usually the same as the current line,
23234 ;; unless the paragraph is at the beginning of an item.
23235 (let ((parent (org-element-property :parent element)))
23236 (save-excursion
23237 (beginning-of-line)
23238 (cond ((eq (org-element-type parent) 'item)
23239 (make-string (org-list-item-body-column
23240 (org-element-property :begin parent))
23241 ?\s))
23242 ((and adaptive-fill-regexp
23243 ;; Locally disable
23244 ;; `adaptive-fill-function' to let
23245 ;; `fill-context-prefix' handle
23246 ;; `adaptive-fill-regexp' variable.
23247 (let (adaptive-fill-function)
23248 (fill-context-prefix
23249 post-affiliated
23250 (org-element-property :end element)))))
23251 ((looking-at "[ \t]+") (match-string 0))
23252 (t "")))))
23253 (comment-block
23254 ;; Only fill contents if P is within block boundaries.
23255 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23256 (forward-line)
23257 (point)))
23258 (cend (save-excursion
23259 (goto-char (org-element-property :end element))
23260 (skip-chars-backward " \r\t\n")
23261 (line-beginning-position))))
23262 (when (and (>= p cbeg) (< p cend))
23263 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23264 (match-string 0)
23265 "")))))))))))
23267 (declare-function message-goto-body "message" ())
23268 (defvar message-cite-prefix-regexp) ; From message.el
23269 (defun org-fill-paragraph (&optional justify)
23270 "Fill element at point, when applicable.
23272 This function only applies to comment blocks, comments, example
23273 blocks and paragraphs. Also, as a special case, re-align table
23274 when point is at one.
23276 If JUSTIFY is non-nil (interactively, with prefix argument),
23277 justify as well. If `sentence-end-double-space' is non-nil, then
23278 period followed by one space does not end a sentence, so don't
23279 break a line there. The variable `fill-column' controls the
23280 width for filling.
23282 For convenience, when point is at a plain list, an item or
23283 a footnote definition, try to fill the first paragraph within."
23284 (interactive)
23285 (if (and (derived-mode-p 'message-mode)
23286 (or (not (message-in-body-p))
23287 (save-excursion (move-beginning-of-line 1)
23288 (looking-at message-cite-prefix-regexp))))
23289 ;; First ensure filling is correct in message-mode.
23290 (let ((fill-paragraph-function
23291 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23292 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23293 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23294 (paragraph-separate
23295 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23296 (fill-paragraph nil))
23297 (with-syntax-table org-mode-transpose-word-syntax-table
23298 ;; Move to end of line in order to get the first paragraph
23299 ;; within a plain list or a footnote definition.
23300 (let ((element (save-excursion
23301 (end-of-line)
23302 (or (ignore-errors (org-element-at-point))
23303 (user-error "An element cannot be parsed line %d"
23304 (line-number-at-pos (point)))))))
23305 ;; First check if point is in a blank line at the beginning of
23306 ;; the buffer. In that case, ignore filling.
23307 (case (org-element-type element)
23308 ;; Use major mode filling function is src blocks.
23309 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23310 ;; Align Org tables, leave table.el tables as-is.
23311 (table-row (org-table-align) t)
23312 (table
23313 (when (eq (org-element-property :type element) 'org)
23314 (save-excursion
23315 (goto-char (org-element-property :post-affiliated element))
23316 (org-table-align)))
23318 (paragraph
23319 ;; Paragraphs may contain `line-break' type objects.
23320 (let ((beg (max (point-min)
23321 (org-element-property :contents-begin element)))
23322 (end (min (point-max)
23323 (org-element-property :contents-end element))))
23324 ;; Do nothing if point is at an affiliated keyword.
23325 (if (< (line-end-position) beg) t
23326 (when (derived-mode-p 'message-mode)
23327 ;; In `message-mode', do not fill following citation
23328 ;; in current paragraph nor text before message body.
23329 (let ((body-start (save-excursion (message-goto-body))))
23330 (when body-start (setq beg (max body-start beg))))
23331 (when (save-excursion
23332 (re-search-forward
23333 (concat "^" message-cite-prefix-regexp) end t))
23334 (setq end (match-beginning 0))))
23335 ;; Fill paragraph, taking line breaks into account.
23336 (save-excursion
23337 (goto-char beg)
23338 (let ((cuts (list beg)))
23339 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23340 (when (eq 'line-break
23341 (org-element-type
23342 (save-excursion (backward-char)
23343 (org-element-context))))
23344 (push (point) cuts)))
23345 (dolist (c (delq end cuts))
23346 (fill-region-as-paragraph c end justify)
23347 (setq end c))))
23348 t)))
23349 ;; Contents of `comment-block' type elements should be
23350 ;; filled as plain text, but only if point is within block
23351 ;; markers.
23352 (comment-block
23353 (let* ((case-fold-search t)
23354 (beg (save-excursion
23355 (goto-char (org-element-property :begin element))
23356 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23357 (forward-line)
23358 (point)))
23359 (end (save-excursion
23360 (goto-char (org-element-property :end element))
23361 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23362 (line-beginning-position))))
23363 (if (or (< (point) beg) (> (point) end)) t
23364 (fill-region-as-paragraph
23365 (save-excursion (end-of-line)
23366 (re-search-backward "^[ \t]*$" beg 'move)
23367 (line-beginning-position))
23368 (save-excursion (beginning-of-line)
23369 (re-search-forward "^[ \t]*$" end 'move)
23370 (line-beginning-position))
23371 justify))))
23372 ;; Fill comments.
23373 (comment
23374 (let ((begin (org-element-property :post-affiliated element))
23375 (end (org-element-property :end element)))
23376 (when (and (>= (point) begin) (<= (point) end))
23377 (let ((begin (save-excursion
23378 (end-of-line)
23379 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23380 (progn (forward-line) (point))
23381 begin)))
23382 (end (save-excursion
23383 (end-of-line)
23384 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23385 (1- (line-beginning-position))
23386 (skip-chars-backward " \r\t\n")
23387 (line-end-position)))))
23388 ;; Do not fill comments when at a blank line.
23389 (when (> end begin)
23390 (let ((fill-prefix
23391 (save-excursion
23392 (beginning-of-line)
23393 (looking-at "[ \t]*#")
23394 (let ((comment-prefix (match-string 0)))
23395 (goto-char (match-end 0))
23396 (if (looking-at adaptive-fill-regexp)
23397 (concat comment-prefix (match-string 0))
23398 (concat comment-prefix " "))))))
23399 (save-excursion
23400 (fill-region-as-paragraph begin end justify))))))
23402 ;; Ignore every other element.
23403 (otherwise t))))))
23405 (defun org-auto-fill-function ()
23406 "Auto-fill function."
23407 ;; Check if auto-filling is meaningful.
23408 (let ((fc (current-fill-column)))
23409 (when (and fc (> (current-column) fc))
23410 (let* ((fill-prefix (org-adaptive-fill-function))
23411 ;; Enforce empty fill prefix, if required. Otherwise, it
23412 ;; will be computed again.
23413 (adaptive-fill-mode (not (equal fill-prefix ""))))
23414 (when fill-prefix (do-auto-fill))))))
23416 (defun org-comment-line-break-function (&optional soft)
23417 "Break line at point and indent, continuing comment if within one.
23418 The inserted newline is marked hard if variable
23419 `use-hard-newlines' is true, unless optional argument SOFT is
23420 non-nil."
23421 (if soft (insert-and-inherit ?\n) (newline 1))
23422 (save-excursion (forward-char -1) (delete-horizontal-space))
23423 (delete-horizontal-space)
23424 (indent-to-left-margin)
23425 (insert-before-markers-and-inherit fill-prefix))
23428 ;;; Fixed Width Areas
23430 (defun org-toggle-fixed-width ()
23431 "Toggle fixed-width markup.
23433 Add or remove fixed-width markup on current line, whenever it
23434 makes sense. Return an error otherwise.
23436 If a region is active and if it contains only fixed-width areas
23437 or blank lines, remove all fixed-width markup in it. If the
23438 region contains anything else, convert all non-fixed-width lines
23439 to fixed-width ones.
23441 Blank lines at the end of the region are ignored unless the
23442 region only contains such lines."
23443 (interactive)
23444 (if (not (org-region-active-p))
23445 ;; No region:
23447 ;; Remove fixed width marker only in a fixed-with element.
23449 ;; Add fixed width maker in paragraphs, in blank lines after
23450 ;; elements or at the beginning of a headline or an inlinetask,
23451 ;; and before any one-line elements (e.g., a clock).
23452 (progn
23453 (beginning-of-line)
23454 (let* ((element (org-element-at-point))
23455 (type (org-element-type element)))
23456 (cond
23457 ((and (eq type 'fixed-width)
23458 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23459 (replace-match
23460 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23461 ((and (memq type '(babel-call clock comment diary-sexp headline
23462 horizontal-rule keyword paragraph
23463 planning))
23464 (<= (org-element-property :post-affiliated element) (point)))
23465 (skip-chars-forward " \t")
23466 (insert ": "))
23467 ((and (org-looking-at-p "[ \t]*$")
23468 (or (eq type 'inlinetask)
23469 (save-excursion
23470 (skip-chars-forward " \r\t\n")
23471 (<= (org-element-property :end element) (point)))))
23472 (delete-region (point) (line-end-position))
23473 (org-indent-line)
23474 (insert ": "))
23475 (t (user-error "Cannot insert a fixed-width line here")))))
23476 ;; Region active.
23477 (let* ((begin (save-excursion
23478 (goto-char (region-beginning))
23479 (line-beginning-position)))
23480 (end (copy-marker
23481 (save-excursion
23482 (goto-char (region-end))
23483 (unless (eolp) (beginning-of-line))
23484 (if (save-excursion (re-search-backward "\\S-" begin t))
23485 (progn (skip-chars-backward " \r\t\n") (point))
23486 (point)))))
23487 (all-fixed-width-p
23488 (catch 'not-all-p
23489 (save-excursion
23490 (goto-char begin)
23491 (skip-chars-forward " \r\t\n")
23492 (when (eobp) (throw 'not-all-p nil))
23493 (while (< (point) end)
23494 (let ((element (org-element-at-point)))
23495 (if (eq (org-element-type element) 'fixed-width)
23496 (goto-char (org-element-property :end element))
23497 (throw 'not-all-p nil))))
23498 t))))
23499 (if all-fixed-width-p
23500 (save-excursion
23501 (goto-char begin)
23502 (while (< (point) end)
23503 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23504 (replace-match
23505 "" nil nil nil
23506 (if (= (line-end-position) (match-end 0)) 0 1)))
23507 (forward-line)))
23508 (let ((min-ind (point-max)))
23509 ;; Find minimum indentation across all lines.
23510 (save-excursion
23511 (goto-char begin)
23512 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23513 (setq min-ind 0)
23514 (catch 'zerop
23515 (while (< (point) end)
23516 (unless (org-looking-at-p "[ \t]*$")
23517 (let ((ind (org-get-indentation)))
23518 (setq min-ind (min min-ind ind))
23519 (when (zerop ind) (throw 'zerop t))))
23520 (forward-line)))))
23521 ;; Loop over all lines and add fixed-width markup everywhere
23522 ;; but in fixed-width lines.
23523 (save-excursion
23524 (goto-char begin)
23525 (while (< (point) end)
23526 (cond
23527 ((org-at-heading-p)
23528 (insert ": ")
23529 (forward-line)
23530 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23531 (insert ":")
23532 (forward-line)))
23533 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23534 (let* ((element (org-element-at-point))
23535 (element-end (org-element-property :end element)))
23536 (if (eq (org-element-type element) 'fixed-width)
23537 (progn (goto-char element-end)
23538 (skip-chars-backward " \r\t\n")
23539 (forward-line))
23540 (let ((limit (min end element-end)))
23541 (while (< (point) limit)
23542 (org-move-to-column min-ind t)
23543 (insert ": ")
23544 (forward-line))))))
23546 (org-move-to-column min-ind t)
23547 (insert ": ")
23548 (forward-line)))))))
23549 (set-marker end nil))))
23552 ;;; Comments
23554 ;; Org comments syntax is quite complex. It requires the entire line
23555 ;; to be just a comment. Also, even with the right syntax at the
23556 ;; beginning of line, some some elements (i.e. verse-block or
23557 ;; example-block) don't accept comments. Usual Emacs comment commands
23558 ;; cannot cope with those requirements. Therefore, Org replaces them.
23560 ;; Org still relies on `comment-dwim', but cannot trust
23561 ;; `comment-only-p'. So, `comment-region-function' and
23562 ;; `uncomment-region-function' both point
23563 ;; to`org-comment-or-uncomment-region'. Eventually,
23564 ;; `org-insert-comment' takes care of insertion of comments at the
23565 ;; beginning of line.
23567 ;; `org-setup-comments-handling' install comments related variables
23568 ;; during `org-mode' initialization.
23570 (defun org-setup-comments-handling ()
23571 (interactive)
23572 (setq-local comment-use-syntax nil)
23573 (setq-local comment-start "# ")
23574 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23575 (setq-local comment-insert-comment-function 'org-insert-comment)
23576 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23577 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23579 (defun org-insert-comment ()
23580 "Insert an empty comment above current line.
23581 If the line is empty, insert comment at its beginning. When
23582 point is within a source block, comment according to the related
23583 major mode."
23584 (if (let ((element (org-element-at-point)))
23585 (and (eq (org-element-type element) 'src-block)
23586 (< (save-excursion
23587 (goto-char (org-element-property :post-affiliated element))
23588 (line-end-position))
23589 (point))
23590 (> (save-excursion
23591 (goto-char (org-element-property :end element))
23592 (skip-chars-backward " \r\t\n")
23593 (line-beginning-position))
23594 (point))))
23595 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23596 (beginning-of-line)
23597 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23598 (open-line 1))
23599 (org-indent-line)
23600 (insert "# ")))
23602 (defvar comment-empty-lines) ; From newcomment.el.
23603 (defun org-comment-or-uncomment-region (beg end &rest _)
23604 "Comment or uncomment each non-blank line in the region.
23605 Uncomment each non-blank line between BEG and END if it only
23606 contains commented lines. Otherwise, comment them. If region is
23607 strictly within a source block, use appropriate comment syntax."
23608 (if (let ((element (org-element-at-point)))
23609 (and (eq (org-element-type element) 'src-block)
23610 (< (save-excursion
23611 (goto-char (org-element-property :post-affiliated element))
23612 (line-end-position))
23613 beg)
23614 (>= (save-excursion
23615 (goto-char (org-element-property :end element))
23616 (skip-chars-backward " \r\t\n")
23617 (line-beginning-position))
23618 end)))
23619 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23620 (save-restriction
23621 ;; Restrict region
23622 (narrow-to-region (save-excursion (goto-char beg)
23623 (skip-chars-forward " \r\t\n" end)
23624 (line-beginning-position))
23625 (save-excursion (goto-char end)
23626 (skip-chars-backward " \r\t\n" beg)
23627 (line-end-position)))
23628 (let ((uncommentp
23629 ;; UNCOMMENTP is non-nil when every non blank line between
23630 ;; BEG and END is a comment.
23631 (save-excursion
23632 (goto-char (point-min))
23633 (while (and (not (eobp))
23634 (let ((element (org-element-at-point)))
23635 (and (eq (org-element-type element) 'comment)
23636 (goto-char (min (point-max)
23637 (org-element-property
23638 :end element)))))))
23639 (eobp))))
23640 (if uncommentp
23641 ;; Only blank lines and comments in region: uncomment it.
23642 (save-excursion
23643 (goto-char (point-min))
23644 (while (not (eobp))
23645 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23646 (replace-match "" nil nil nil 1))
23647 (forward-line)))
23648 ;; Comment each line in region.
23649 (let ((min-indent (point-max)))
23650 ;; First find the minimum indentation across all lines.
23651 (save-excursion
23652 (goto-char (point-min))
23653 (while (and (not (eobp)) (not (zerop min-indent)))
23654 (unless (looking-at "[ \t]*$")
23655 (setq min-indent (min min-indent (current-indentation))))
23656 (forward-line)))
23657 ;; Then loop over all lines.
23658 (save-excursion
23659 (goto-char (point-min))
23660 (while (not (eobp))
23661 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23662 ;; Don't get fooled by invisible text (e.g. link path)
23663 ;; when moving to column MIN-INDENT.
23664 (let ((buffer-invisibility-spec nil))
23665 (org-move-to-column min-indent t))
23666 (insert comment-start))
23667 (forward-line)))))))))
23669 (defun org-comment-dwim (_arg)
23670 "Call `comment-dwim' within a source edit buffer if needed."
23671 (interactive "*P")
23672 (if (org-in-src-block-p)
23673 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23674 (call-interactively 'comment-dwim)))
23677 ;;; Timestamps API
23679 ;; This section contains tools to operate on timestamp objects, as
23680 ;; returned by, e.g. `org-element-context'.
23682 (defun org-timestamp--to-internal-time (timestamp &optional end)
23683 "Encode TIMESTAMP object into Emacs internal time.
23684 Use end of date range or time range when END is non-nil."
23685 (apply #'encode-time
23686 (cons 0
23687 (mapcar
23688 (lambda (prop) (or (org-element-property prop timestamp) 0))
23689 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23690 '(:minute-start :hour-start :day-start :month-start
23691 :year-start))))))
23693 (defun org-timestamp-has-time-p (timestamp)
23694 "Non-nil when TIMESTAMP has a time specified."
23695 (org-element-property :hour-start timestamp))
23697 (defun org-timestamp-format (timestamp format &optional end utc)
23698 "Format a TIMESTAMP object into a string.
23700 FORMAT is a format specifier to be passed to
23701 `format-time-string'.
23703 When optional argument END is non-nil, use end of date-range or
23704 time-range, if possible.
23706 When optional argument UTC is non-nil, time will be expressed as
23707 Universal Time."
23708 (format-time-string
23709 format (org-timestamp--to-internal-time timestamp end) utc))
23711 (defun org-timestamp-split-range (timestamp &optional end)
23712 "Extract a TIMESTAMP object from a date or time range.
23714 END, when non-nil, means extract the end of the range.
23715 Otherwise, extract its start.
23717 Return a new timestamp object."
23718 (let ((type (org-element-property :type timestamp)))
23719 (if (memq type '(active inactive diary)) timestamp
23720 (let ((split-ts (org-element-copy timestamp)))
23721 ;; Set new type.
23722 (org-element-put-property
23723 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23724 ;; Copy start properties over end properties if END is
23725 ;; non-nil. Otherwise, copy end properties over `start' ones.
23726 (let ((p-alist '((:minute-start . :minute-end)
23727 (:hour-start . :hour-end)
23728 (:day-start . :day-end)
23729 (:month-start . :month-end)
23730 (:year-start . :year-end))))
23731 (dolist (p-cell p-alist)
23732 (org-element-put-property
23733 split-ts
23734 (funcall (if end #'car #'cdr) p-cell)
23735 (org-element-property
23736 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23737 ;; Eventually refresh `:raw-value'.
23738 (org-element-put-property split-ts :raw-value nil)
23739 (org-element-put-property
23740 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23742 (defun org-timestamp-translate (timestamp &optional boundary)
23743 "Translate TIMESTAMP object to custom format.
23745 Format string is defined in `org-time-stamp-custom-formats',
23746 which see.
23748 When optional argument BOUNDARY is non-nil, it is either the
23749 symbol `start' or `end'. In this case, only translate the
23750 starting or ending part of TIMESTAMP if it is a date or time
23751 range. Otherwise, translate both parts.
23753 Return timestamp as-is if `org-display-custom-times' is nil or if
23754 it has a `diary' type."
23755 (let ((type (org-element-property :type timestamp)))
23756 (if (or (not org-display-custom-times) (eq type 'diary))
23757 (org-element-interpret-data timestamp)
23758 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23759 org-time-stamp-custom-formats)))
23760 (if (and (not boundary) (memq type '(active-range inactive-range)))
23761 (concat (org-timestamp-format timestamp fmt)
23762 "--"
23763 (org-timestamp-format timestamp fmt t))
23764 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23768 ;;; Other stuff.
23770 (defvar reftex-docstruct-symbol)
23771 (defvar reftex-cite-format)
23772 (defvar org--rds)
23774 (defun org-reftex-citation ()
23775 "Use reftex-citation to insert a citation into the buffer.
23776 This looks for a line like
23778 #+BIBLIOGRAPHY: foo plain option:-d
23780 and derives from it that foo.bib is the bibliography file relevant
23781 for this document. It then installs the necessary environment for RefTeX
23782 to work in this buffer and calls `reftex-citation' to insert a citation
23783 into the buffer.
23785 Export of such citations to both LaTeX and HTML is handled by the contributed
23786 package ox-bibtex by Taru Karttunen."
23787 (interactive)
23788 (let ((reftex-docstruct-symbol 'org--rds)
23789 (reftex-cite-format "\\cite{%l}")
23790 org--rds bib)
23791 (save-excursion
23792 (save-restriction
23793 (widen)
23794 (let ((case-fold-search t)
23795 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23796 (if (not (save-excursion
23797 (or (re-search-forward re nil t)
23798 (re-search-backward re nil t))))
23799 (user-error "No bibliography defined in file")
23800 (setq bib (concat (match-string 1) ".bib")
23801 org--rds (list (list 'bib bib)))))))
23802 (call-interactively 'reftex-citation)))
23804 ;;;; Functions extending outline functionality
23806 (defun org-beginning-of-line (&optional arg)
23807 "Go to the beginning of the current line. If that is invisible, continue
23808 to a visible line beginning. This makes the function of C-a more intuitive.
23809 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23810 first attempt, and only move to after the tags when the cursor is already
23811 beyond the end of the headline."
23812 (interactive "P")
23813 (let ((pos (point))
23814 (special (if (consp org-special-ctrl-a/e)
23815 (car org-special-ctrl-a/e)
23816 org-special-ctrl-a/e))
23817 deactivate-mark refpos)
23818 (if (org-bound-and-true-p visual-line-mode)
23819 (beginning-of-visual-line 1)
23820 (beginning-of-line 1))
23821 (if (and arg (fboundp 'move-beginning-of-line))
23822 (call-interactively 'move-beginning-of-line)
23823 (unless (bobp)
23824 (backward-char 1)
23825 (if (org-truely-invisible-p)
23826 (while (and (not (bobp)) (org-truely-invisible-p))
23827 (backward-char 1)
23828 (beginning-of-line 1))
23829 (forward-char 1))))
23830 (when special
23831 (cond
23832 ((and (looking-at org-complex-heading-regexp)
23833 (eq (char-after (match-end 1)) ?\s))
23834 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23835 (point-at-eol)))
23836 (goto-char
23837 (if (eq special t)
23838 (cond ((> pos refpos) refpos)
23839 ((= pos (point)) refpos)
23840 (t (point)))
23841 (cond ((> pos (point)) (point))
23842 ((not (eq last-command this-command)) (point))
23843 (t refpos)))))
23844 ((org-at-item-p)
23845 ;; Being at an item and not looking at an the item means point
23846 ;; was previously moved to beginning of a visual line, which
23847 ;; doesn't contain the item. Therefore, do nothing special,
23848 ;; just stay here.
23849 (when (looking-at org-list-full-item-re)
23850 ;; Set special position at first white space character after
23851 ;; bullet, and check-box, if any.
23852 (let ((after-bullet
23853 (let ((box (match-end 3)))
23854 (if (not box) (match-end 1)
23855 (let ((after (char-after box)))
23856 (if (and after (= after ? )) (1+ box) box))))))
23857 ;; Special case: Move point to special position when
23858 ;; currently after it or at beginning of line.
23859 (if (eq special t)
23860 (when (or (> pos after-bullet) (= (point) pos))
23861 (goto-char after-bullet))
23862 ;; Reversed case: Move point to special position when
23863 ;; point was already at beginning of line and command is
23864 ;; repeated.
23865 (when (and (= (point) pos) (eq last-command this-command))
23866 (goto-char after-bullet))))))))
23867 (org-no-warnings
23868 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23869 (setq disable-point-adjustment
23870 (or (not (invisible-p (point)))
23871 (not (invisible-p (max (point-min) (1- (point))))))))
23873 (defun org-end-of-line (&optional arg)
23874 "Go to the end of the line.
23875 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23876 tags on the first attempt, and only move to after the tags when
23877 the cursor is already beyond the end of the headline."
23878 (interactive "P")
23879 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23880 org-special-ctrl-a/e))
23881 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23882 'end-of-visual-line)
23883 ((fboundp 'move-end-of-line) 'move-end-of-line)
23884 (t 'end-of-line)))
23885 deactivate-mark)
23886 (if (or (not special) arg) (call-interactively move-fun)
23887 (let* ((element (save-excursion (beginning-of-line)
23888 (org-element-at-point)))
23889 (type (org-element-type element)))
23890 (cond
23891 ((memq type '(headline inlinetask))
23892 (let ((pos (point)))
23893 (beginning-of-line 1)
23894 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23895 (if (eq special t)
23896 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23897 (goto-char (match-beginning 1))
23898 (goto-char (match-end 0)))
23899 (if (or (< pos (match-end 0))
23900 (not (eq this-command last-command)))
23901 (goto-char (match-end 0))
23902 (goto-char (match-beginning 1))))
23903 (call-interactively move-fun))))
23904 ((outline-invisible-p (line-end-position))
23905 ;; If element is hidden, `move-end-of-line' would put point
23906 ;; after it. Use `end-of-line' to stay on current line.
23907 (call-interactively 'end-of-line))
23908 (t (call-interactively move-fun)))))
23909 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23910 (setq disable-point-adjustment
23911 (or (not (invisible-p (point)))
23912 (not (invisible-p (max (point-min) (1- (point))))))))
23914 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23915 (define-key org-mode-map "\C-e" 'org-end-of-line)
23917 (defun org-backward-sentence (&optional _arg)
23918 "Go to beginning of sentence, or beginning of table field.
23919 This will call `backward-sentence' or `org-table-beginning-of-field',
23920 depending on context."
23921 (interactive)
23922 (let* ((element (org-element-at-point))
23923 (contents-begin (org-element-property :contents-begin element))
23924 (table (org-element-lineage element '(table) t)))
23925 (if (and table
23926 (> (point) contents-begin)
23927 (<= (point) (org-element-property :contents-end table)))
23928 (call-interactively #'org-table-beginning-of-field)
23929 (save-restriction
23930 (when (and contents-begin
23931 (< (point-min) contents-begin)
23932 (> (point) contents-begin))
23933 (narrow-to-region contents-begin
23934 (org-element-property :contents-end element)))
23935 (call-interactively #'backward-sentence)))))
23937 (defun org-forward-sentence (&optional _arg)
23938 "Go to end of sentence, or end of table field.
23939 This will call `forward-sentence' or `org-table-end-of-field',
23940 depending on context."
23941 (interactive)
23942 (let* ((element (org-element-at-point))
23943 (contents-end (org-element-property :contents-end element))
23944 (table (org-element-lineage element '(table) t)))
23945 (if (and table
23946 (>= (point) (org-element-property :contents-begin table))
23947 (< (point) contents-end))
23948 (call-interactively #'org-table-end-of-field)
23949 (save-restriction
23950 (when (and contents-end
23951 (> (point-max) contents-end)
23952 ;; Skip blank lines between elements.
23953 (< (org-element-property :end element)
23954 (save-excursion (goto-char contents-end)
23955 (skip-chars-forward " \r\t\n"))))
23956 (narrow-to-region (org-element-property :contents-begin element)
23957 contents-end))
23958 (call-interactively #'forward-sentence)))))
23960 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23961 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23963 (defun org-kill-line (&optional _arg)
23964 "Kill line, to tags or end of line."
23965 (interactive)
23966 (cond
23967 ((or (not org-special-ctrl-k)
23968 (bolp)
23969 (not (org-at-heading-p)))
23970 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23971 org-ctrl-k-protect-subtree
23972 (or (eq org-ctrl-k-protect-subtree 'error)
23973 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23974 (user-error "C-k aborted as it would kill a hidden subtree"))
23975 (call-interactively
23976 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23977 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23978 (kill-region (point) (match-beginning 1))
23979 (org-set-tags nil t))
23980 (t (kill-region (point) (point-at-eol)))))
23982 (define-key org-mode-map "\C-k" 'org-kill-line)
23984 (defun org-yank (&optional arg)
23985 "Yank. If the kill is a subtree, treat it specially.
23986 This command will look at the current kill and check if is a single
23987 subtree, or a series of subtrees[1]. If it passes the test, and if the
23988 cursor is at the beginning of a line or after the stars of a currently
23989 empty headline, then the yank is handled specially. How exactly depends
23990 on the value of the following variables, both set by default.
23992 `org-yank-folded-subtrees'
23993 When set, the subtree(s) will be folded after insertion, but only
23994 if doing so would now swallow text after the yanked text.
23996 `org-yank-adjusted-subtrees'
23997 When set, the subtree will be promoted or demoted in order to
23998 fit into the local outline tree structure, which means that the
23999 level will be adjusted so that it becomes the smaller one of the
24000 two *visible* surrounding headings.
24002 Any prefix to this command will cause `yank' to be called directly with
24003 no special treatment. In particular, a simple \\[universal-argument] prefix \
24004 will just
24005 plainly yank the text as it is.
24007 \[1] The test checks if the first non-white line is a heading
24008 and if there are no other headings with fewer stars."
24009 (interactive "P")
24010 (org-yank-generic 'yank arg))
24012 (defun org-yank-generic (command arg)
24013 "Perform some yank-like command.
24015 This function implements the behavior described in the `org-yank'
24016 documentation. However, it has been generalized to work for any
24017 interactive command with similar behavior."
24019 ;; pretend to be command COMMAND
24020 (setq this-command command)
24022 (if arg
24023 (call-interactively command)
24025 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24026 (and (org-kill-is-subtree-p)
24027 (or (bolp)
24028 (and (looking-at "[ \t]*$")
24029 (string-match
24030 "\\`\\*+\\'"
24031 (buffer-substring (point-at-bol) (point)))))))
24032 swallowp)
24033 (cond
24034 ((and subtreep org-yank-folded-subtrees)
24035 (let ((beg (point))
24036 end)
24037 (if (and subtreep org-yank-adjusted-subtrees)
24038 (org-paste-subtree nil nil 'for-yank)
24039 (call-interactively command))
24041 (setq end (point))
24042 (goto-char beg)
24043 (when (and (bolp) subtreep
24044 (not (setq swallowp
24045 (org-yank-folding-would-swallow-text beg end))))
24046 (org-with-limited-levels
24047 (or (looking-at org-outline-regexp)
24048 (re-search-forward org-outline-regexp-bol end t))
24049 (while (and (< (point) end) (looking-at org-outline-regexp))
24050 (outline-hide-subtree)
24051 (org-cycle-show-empty-lines 'folded)
24052 (condition-case nil
24053 (outline-forward-same-level 1)
24054 (error (goto-char end))))))
24055 (when swallowp
24056 (message
24057 "Inserted text not folded because that would swallow text"))
24059 (goto-char end)
24060 (skip-chars-forward " \t\n\r")
24061 (beginning-of-line 1)
24062 (push-mark beg 'nomsg)))
24063 ((and subtreep org-yank-adjusted-subtrees)
24064 (let ((beg (point-at-bol)))
24065 (org-paste-subtree nil nil 'for-yank)
24066 (push-mark beg 'nomsg)))
24068 (call-interactively command))))))
24070 (defun org-yank-folding-would-swallow-text (beg end)
24071 "Would hide-subtree at BEG swallow any text after END?"
24072 (let (level)
24073 (org-with-limited-levels
24074 (save-excursion
24075 (goto-char beg)
24076 (when (or (looking-at org-outline-regexp)
24077 (re-search-forward org-outline-regexp-bol end t))
24078 (setq level (org-outline-level)))
24079 (goto-char end)
24080 (skip-chars-forward " \t\r\n\v\f")
24081 (not (or (eobp)
24082 (and (bolp) (looking-at-p org-outline-regexp)
24083 (<= (org-outline-level) level))))))))
24085 (define-key org-mode-map "\C-y" 'org-yank)
24087 (defun org-truely-invisible-p ()
24088 "Check if point is at a character currently not visible.
24089 This version does not only check the character property, but also
24090 `visible-mode'."
24091 ;; Early versions of noutline don't have `outline-invisible-p'.
24092 (unless (org-bound-and-true-p visible-mode)
24093 (outline-invisible-p)))
24095 (defun org-invisible-p2 ()
24096 "Check if point is at a character currently not visible."
24097 (save-excursion
24098 (when (and (eolp) (not (bobp))) (backward-char 1))
24099 ;; Early versions of noutline don't have `outline-invisible-p'.
24100 (outline-invisible-p)))
24102 (defun org-back-to-heading (&optional invisible-ok)
24103 "Call `outline-back-to-heading', but provide a better error message."
24104 (condition-case nil
24105 (outline-back-to-heading invisible-ok)
24106 (error (error "Before first headline at position %d in buffer %s"
24107 (point) (current-buffer)))))
24109 (defun org-before-first-heading-p ()
24110 "Before first heading?"
24111 (save-excursion
24112 (end-of-line)
24113 (null (re-search-backward org-outline-regexp-bol nil t))))
24115 (defun org-at-heading-p (&optional ignored)
24116 (outline-on-heading-p t))
24117 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24118 ;;; warning was only added in Org 9.0, which should be taken into
24119 ;;; account when deciding when to remove the alias.
24120 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24122 (defun org-in-commented-heading-p (&optional no-inheritance)
24123 "Non-nil if point is under a commented heading.
24124 This function also checks ancestors of the current headline,
24125 unless optional argument NO-INHERITANCE is non-nil."
24126 (cond
24127 ((org-before-first-heading-p) nil)
24128 ((let ((headline (nth 4 (org-heading-components))))
24129 (and headline
24130 (let ((case-fold-search nil))
24131 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24132 headline)))))
24133 (no-inheritance nil)
24135 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24137 (defun org-at-comment-p nil
24138 "Is cursor in a commented line?"
24139 (save-excursion
24140 (save-match-data
24141 (beginning-of-line)
24142 (looking-at "^[ \t]*# "))))
24144 (defun org-at-drawer-p nil
24145 "Is cursor at a drawer keyword?"
24146 (save-excursion
24147 (move-beginning-of-line 1)
24148 (looking-at org-drawer-regexp)))
24150 (defun org-at-block-p nil
24151 "Is cursor at a block keyword?"
24152 (save-excursion
24153 (move-beginning-of-line 1)
24154 (looking-at org-block-regexp)))
24156 (defun org-point-at-end-of-empty-headline ()
24157 "If point is at the end of an empty headline, return t, else nil.
24158 If the heading only contains a TODO keyword, it is still still considered
24159 empty."
24160 (and (looking-at "[ \t]*$")
24161 (when org-todo-line-regexp
24162 (save-excursion
24163 (beginning-of-line 1)
24164 (let ((case-fold-search nil))
24165 (looking-at org-todo-line-regexp)
24166 (string= (match-string 3) ""))))))
24168 (defun org-at-heading-or-item-p ()
24169 (or (org-at-heading-p) (org-at-item-p)))
24171 (defun org-at-target-p ()
24172 (or (org-in-regexp org-radio-target-regexp)
24173 (org-in-regexp org-target-regexp)))
24174 ;; Compatibility alias with Org versions < 7.8.03
24175 (defalias 'org-on-target-p 'org-at-target-p)
24177 (defun org-up-heading-all (arg)
24178 "Move to the heading line of which the present line is a subheading.
24179 This function considers both visible and invisible heading lines.
24180 With argument, move up ARG levels."
24181 (if (fboundp 'outline-up-heading-all)
24182 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24183 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24185 (defun org-up-heading-safe ()
24186 "Move to the heading line of which the present line is a subheading.
24187 This version will not throw an error. It will return the level of the
24188 headline found, or nil if no higher level is found.
24190 Also, this function will be a lot faster than `outline-up-heading',
24191 because it relies on stars being the outline starters. This can really
24192 make a significant difference in outlines with very many siblings."
24193 (when (ignore-errors (org-back-to-heading t))
24194 (let ((level-up (1- (funcall outline-level))))
24195 (and (> level-up 0)
24196 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24197 (funcall outline-level)))))
24199 (defun org-first-sibling-p ()
24200 "Is this heading the first child of its parents?"
24201 (interactive)
24202 (let ((re org-outline-regexp-bol)
24203 level l)
24204 (unless (org-at-heading-p t)
24205 (user-error "Not at a heading"))
24206 (setq level (funcall outline-level))
24207 (save-excursion
24208 (if (not (re-search-backward re nil t))
24210 (setq l (funcall outline-level))
24211 (< l level)))))
24213 (defun org-goto-sibling (&optional previous)
24214 "Goto the next sibling, even if it is invisible.
24215 When PREVIOUS is set, go to the previous sibling instead. Returns t
24216 when a sibling was found. When none is found, return nil and don't
24217 move point."
24218 (let ((fun (if previous 're-search-backward 're-search-forward))
24219 (pos (point))
24220 (re org-outline-regexp-bol)
24221 level l)
24222 (when (ignore-errors (org-back-to-heading t))
24223 (setq level (funcall outline-level))
24224 (catch 'exit
24225 (or previous (forward-char 1))
24226 (while (funcall fun re nil t)
24227 (setq l (funcall outline-level))
24228 (when (< l level) (goto-char pos) (throw 'exit nil))
24229 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24230 (goto-char pos)
24231 nil))))
24233 (defun org-show-siblings ()
24234 "Show all siblings of the current headline."
24235 (save-excursion
24236 (while (org-goto-sibling) (org-flag-heading nil)))
24237 (save-excursion
24238 (while (org-goto-sibling 'previous)
24239 (org-flag-heading nil))))
24241 (defun org-goto-first-child ()
24242 "Goto the first child, even if it is invisible.
24243 Return t when a child was found. Otherwise don't move point and
24244 return nil."
24245 (let (level (pos (point)) (re org-outline-regexp-bol))
24246 (when (ignore-errors (org-back-to-heading t))
24247 (setq level (outline-level))
24248 (forward-char 1)
24249 (if (and (re-search-forward re nil t) (> (outline-level) level))
24250 (progn (goto-char (match-beginning 0)) t)
24251 (goto-char pos) nil))))
24253 (defun org-show-hidden-entry ()
24254 "Show an entry where even the heading is hidden."
24255 (save-excursion
24256 (org-show-entry)))
24258 (defun org-flag-heading (flag &optional entry)
24259 "Flag the current heading. FLAG non-nil means make invisible.
24260 When ENTRY is non-nil, show the entire entry."
24261 (save-excursion
24262 (org-back-to-heading t)
24263 ;; Check if we should show the entire entry
24264 (if entry
24265 (progn
24266 (org-show-entry)
24267 (save-excursion
24268 (and (outline-next-heading)
24269 (org-flag-heading nil))))
24270 (outline-flag-region (max (point-min) (1- (point)))
24271 (save-excursion (outline-end-of-heading) (point))
24272 flag))))
24274 (defun org-get-next-sibling ()
24275 "Move to next heading of the same level, and return point.
24276 If there is no such heading, return nil.
24277 This is like outline-next-sibling, but invisible headings are ok."
24278 (let ((level (funcall outline-level)))
24279 (outline-next-heading)
24280 (while (and (not (eobp)) (> (funcall outline-level) level))
24281 (outline-next-heading))
24282 (unless (or (eobp) (< (funcall outline-level) level))
24283 (point))))
24285 (defun org-get-last-sibling ()
24286 "Move to previous heading of the same level, and return point.
24287 If there is no such heading, return nil."
24288 (let ((opoint (point))
24289 (level (funcall outline-level)))
24290 (outline-previous-heading)
24291 (when (and (/= (point) opoint) (outline-on-heading-p t))
24292 (while (and (> (funcall outline-level) level)
24293 (not (bobp)))
24294 (outline-previous-heading))
24295 (unless (< (funcall outline-level) level)
24296 (point)))))
24298 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24299 "Goto to the end of a subtree."
24300 ;; This contains an exact copy of the original function, but it uses
24301 ;; `org-back-to-heading', to make it work also in invisible
24302 ;; trees. And is uses an invisible-ok argument.
24303 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24304 ;; Furthermore, when used inside Org, finding the end of a large subtree
24305 ;; with many children and grandchildren etc, this can be much faster
24306 ;; than the outline version.
24307 (org-back-to-heading invisible-ok)
24308 (let ((first t)
24309 (level (funcall outline-level)))
24310 (if (and (derived-mode-p 'org-mode) (< level 1000))
24311 ;; A true heading (not a plain list item), in Org-mode
24312 ;; This means we can easily find the end by looking
24313 ;; only for the right number of stars. Using a regexp to do
24314 ;; this is so much faster than using a Lisp loop.
24315 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24316 (forward-char 1)
24317 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24318 ;; something else, do it the slow way
24319 (while (and (not (eobp))
24320 (or first (> (funcall outline-level) level)))
24321 (setq first nil)
24322 (outline-next-heading)))
24323 (unless to-heading
24324 (when (memq (preceding-char) '(?\n ?\^M))
24325 ;; Go to end of line before heading
24326 (forward-char -1)
24327 (when (memq (preceding-char) '(?\n ?\^M))
24328 ;; leave blank line before heading
24329 (forward-char -1)))))
24330 (point))
24332 (defun org-end-of-meta-data (&optional full)
24333 "Skip planning line and properties drawer in current entry.
24334 When optional argument FULL is non-nil, also skip empty lines,
24335 clocking lines and regular drawers at the beginning of the
24336 entry."
24337 (org-back-to-heading t)
24338 (forward-line)
24339 (when (org-looking-at-p org-planning-line-re) (forward-line))
24340 (when (looking-at org-property-drawer-re)
24341 (goto-char (match-end 0))
24342 (forward-line))
24343 (when (and full (not (org-at-heading-p)))
24344 (catch 'exit
24345 (let ((end (save-excursion (outline-next-heading) (point)))
24346 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24347 (while (not (eobp))
24348 (cond ((org-looking-at-p org-drawer-regexp)
24349 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24350 (forward-line)
24351 (throw 'exit t)))
24352 ((org-looking-at-p re) (forward-line))
24353 (t (throw 'exit t))))))))
24355 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24356 "Move forward to the ARG'th subheading at same level as this one.
24357 Stop at the first and last subheadings of a superior heading.
24358 Normally this only looks at visible headings, but when INVISIBLE-OK is
24359 non-nil it will also look at invisible ones."
24360 (interactive "p")
24361 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24362 (if (and arg (< arg 0))
24363 (goto-char (point-min))
24364 (outline-next-heading))
24365 (org-at-heading-p)
24366 (let ((level (- (match-end 0) (match-beginning 0) 1))
24367 (f (if (and arg (< arg 0))
24368 're-search-backward
24369 're-search-forward))
24370 (count (if arg (abs arg) 1))
24371 (result (point)))
24372 (while (and (prog1 (> count 0)
24373 (forward-char (if (and arg (< arg 0)) -1 1)))
24374 (funcall f org-outline-regexp-bol nil 'move))
24375 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24376 (cond ((< l level) (setq count 0))
24377 ((and (= l level)
24378 (or invisible-ok
24379 (progn
24380 (goto-char (line-beginning-position))
24381 (not (outline-invisible-p)))))
24382 (setq count (1- count))
24383 (when (eq l level)
24384 (setq result (point)))))))
24385 (goto-char result))
24386 (beginning-of-line 1)))
24388 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24389 "Move backward to the ARG'th subheading at same level as this one.
24390 Stop at the first and last subheadings of a superior heading."
24391 (interactive "p")
24392 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24394 (defun org-next-visible-heading (arg)
24395 "Move to the next visible heading.
24397 This function wraps `outline-next-visible-heading' with
24398 `org-with-limited-levels' in order to skip over inline tasks and
24399 respect customization of `org-odd-levels-only'."
24400 (interactive "p")
24401 (org-with-limited-levels
24402 (outline-next-visible-heading arg)))
24404 (defun org-previous-visible-heading (arg)
24405 "Move to the next visible heading.
24407 This function wraps `outline-previous-visible-heading' with
24408 `org-with-limited-levels' in order to skip over inline tasks and
24409 respect customization of `org-odd-levels-only'."
24410 (interactive "p")
24411 (org-with-limited-levels
24412 (outline-previous-visible-heading arg)))
24414 (defun org-next-block (arg &optional backward block-regexp)
24415 "Jump to the next block.
24417 With a prefix argument ARG, jump forward ARG many blocks.
24419 When BACKWARD is non-nil, jump to the previous block.
24421 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24422 Match data is set according to this regexp when the function
24423 returns.
24425 Return point at beginning of the opening line of found block.
24426 Throw an error if no block is found."
24427 (interactive "p")
24428 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24429 (case-fold-search t)
24430 (search-fn (if backward #'re-search-backward #'re-search-forward))
24431 (count (or arg 1))
24432 (origin (point))
24433 last-element)
24434 (if backward (beginning-of-line) (end-of-line))
24435 (while (and (> count 0) (funcall search-fn re nil t))
24436 (let ((element (save-excursion
24437 (goto-char (match-beginning 0))
24438 (save-match-data (org-element-at-point)))))
24439 (when (and (memq (org-element-type element)
24440 '(center-block comment-block dynamic-block
24441 example-block export-block quote-block
24442 special-block src-block verse-block))
24443 (<= (match-beginning 0)
24444 (org-element-property :post-affiliated element)))
24445 (setq last-element element)
24446 (decf count))))
24447 (if (= count 0)
24448 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24449 (save-match-data (org-show-context)))
24450 (goto-char origin)
24451 (user-error "No %s code blocks" (if backward "previous" "further")))))
24453 (defun org-previous-block (arg &optional block-regexp)
24454 "Jump to the previous block.
24455 With a prefix argument ARG, jump backward ARG many source blocks.
24456 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24457 (interactive "p")
24458 (org-next-block arg t block-regexp))
24460 (defun org-forward-paragraph ()
24461 "Move forward to beginning of next paragraph or equivalent.
24463 The function moves point to the beginning of the next visible
24464 structural element, which can be a paragraph, a table, a list
24465 item, etc. It also provides some special moves for convenience:
24467 - On an affiliated keyword, jump to the beginning of the
24468 relative element.
24469 - On an item or a footnote definition, move to the second
24470 element inside, if any.
24471 - On a table or a property drawer, jump after it.
24472 - On a verse or source block, stop after blank lines."
24473 (interactive)
24474 (when (eobp) (user-error "Cannot move further down"))
24475 (let* ((deactivate-mark nil)
24476 (element (org-element-at-point))
24477 (type (org-element-type element))
24478 (post-affiliated (org-element-property :post-affiliated element))
24479 (contents-begin (org-element-property :contents-begin element))
24480 (contents-end (org-element-property :contents-end element))
24481 (end (let ((end (org-element-property :end element)) (parent element))
24482 (while (and (setq parent (org-element-property :parent parent))
24483 (= (org-element-property :contents-end parent) end))
24484 (setq end (org-element-property :end parent)))
24485 end)))
24486 (cond ((not element)
24487 (skip-chars-forward " \r\t\n")
24488 (or (eobp) (beginning-of-line)))
24489 ;; On affiliated keywords, move to element's beginning.
24490 ((< (point) post-affiliated)
24491 (goto-char post-affiliated))
24492 ;; At a table row, move to the end of the table. Similarly,
24493 ;; at a node property, move to the end of the property
24494 ;; drawer.
24495 ((memq type '(node-property table-row))
24496 (goto-char (org-element-property
24497 :end (org-element-property :parent element))))
24498 ((memq type '(property-drawer table)) (goto-char end))
24499 ;; Consider blank lines as separators in verse and source
24500 ;; blocks to ease editing.
24501 ((memq type '(src-block verse-block))
24502 (when (eq type 'src-block)
24503 (setq contents-end
24504 (save-excursion (goto-char end)
24505 (skip-chars-backward " \r\t\n")
24506 (line-beginning-position))))
24507 (beginning-of-line)
24508 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24509 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24510 (goto-char end)
24511 (skip-chars-forward " \r\t\n")
24512 (if (= (point) contents-end) (goto-char end)
24513 (beginning-of-line))))
24514 ;; With no contents, just skip element.
24515 ((not contents-begin) (goto-char end))
24516 ;; If contents are invisible, skip the element altogether.
24517 ((outline-invisible-p (line-end-position))
24518 (case type
24519 (headline
24520 (org-with-limited-levels (outline-next-visible-heading 1)))
24521 ;; At a plain list, make sure we move to the next item
24522 ;; instead of skipping the whole list.
24523 (plain-list (forward-char)
24524 (org-forward-paragraph))
24525 (otherwise (goto-char end))))
24526 ((>= (point) contents-end) (goto-char end))
24527 ((>= (point) contents-begin)
24528 ;; This can only happen on paragraphs and plain lists.
24529 (case type
24530 (paragraph (goto-char end))
24531 ;; At a plain list, try to move to second element in
24532 ;; first item, if possible.
24533 (plain-list (end-of-line)
24534 (org-forward-paragraph))))
24535 ;; When contents start on the middle of a line (e.g. in
24536 ;; items and footnote definitions), try to reach first
24537 ;; element starting after current line.
24538 ((> (line-end-position) contents-begin)
24539 (end-of-line)
24540 (org-forward-paragraph))
24541 (t (goto-char contents-begin)))))
24543 (defun org-backward-paragraph ()
24544 "Move backward to start of previous paragraph or equivalent.
24546 The function moves point to the beginning of the current
24547 structural element, which can be a paragraph, a table, a list
24548 item, etc., or to the beginning of the previous visible one if
24549 point is already there. It also provides some special moves for
24550 convenience:
24552 - On an affiliated keyword, jump to the first one.
24553 - On a table or a property drawer, move to its beginning.
24554 - On a verse or source block, stop before blank lines."
24555 (interactive)
24556 (when (bobp) (user-error "Cannot move further up"))
24557 (let* ((deactivate-mark nil)
24558 (element (org-element-at-point))
24559 (type (org-element-type element))
24560 (contents-begin (org-element-property :contents-begin element))
24561 (contents-end (org-element-property :contents-end element))
24562 (post-affiliated (org-element-property :post-affiliated element))
24563 (begin (org-element-property :begin element)))
24564 (cond
24565 ((not element) (goto-char (point-min)))
24566 ((= (point) begin)
24567 (backward-char)
24568 (org-backward-paragraph))
24569 ((<= (point) post-affiliated) (goto-char begin))
24570 ((memq type '(node-property table-row))
24571 (goto-char (org-element-property
24572 :post-affiliated (org-element-property :parent element))))
24573 ((memq type '(property-drawer table)) (goto-char begin))
24574 ((memq type '(src-block verse-block))
24575 (when (eq type 'src-block)
24576 (setq contents-begin
24577 (save-excursion (goto-char begin) (forward-line) (point))))
24578 (if (= (point) contents-begin) (goto-char post-affiliated)
24579 ;; Inside a verse block, see blank lines as paragraph
24580 ;; separators.
24581 (let ((origin (point)))
24582 (skip-chars-backward " \r\t\n" contents-begin)
24583 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24584 (skip-chars-forward " \r\t\n" origin)
24585 (if (= (point) origin) (goto-char contents-begin)
24586 (beginning-of-line))))))
24587 ((not contents-begin) (goto-char (or post-affiliated begin)))
24588 ((eq type 'paragraph)
24589 (goto-char contents-begin)
24590 ;; When at first paragraph in an item or a footnote definition,
24591 ;; move directly to beginning of line.
24592 (let ((parent-contents
24593 (org-element-property
24594 :contents-begin (org-element-property :parent element))))
24595 (when (and parent-contents (= parent-contents contents-begin))
24596 (beginning-of-line))))
24597 ;; At the end of a greater element, move to the beginning of the
24598 ;; last element within.
24599 ((>= (point) contents-end)
24600 (goto-char (1- contents-end))
24601 (org-backward-paragraph))
24602 (t (goto-char (or post-affiliated begin))))
24603 ;; Ensure we never leave point invisible.
24604 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24606 (defun org-forward-element ()
24607 "Move forward by one element.
24608 Move to the next element at the same level, when possible."
24609 (interactive)
24610 (cond ((eobp) (user-error "Cannot move further down"))
24611 ((org-with-limited-levels (org-at-heading-p))
24612 (let ((origin (point)))
24613 (goto-char (org-end-of-subtree nil t))
24614 (unless (org-with-limited-levels (org-at-heading-p))
24615 (goto-char origin)
24616 (user-error "Cannot move further down"))))
24618 (let* ((elem (org-element-at-point))
24619 (end (org-element-property :end elem))
24620 (parent (org-element-property :parent elem)))
24621 (cond ((and parent (= (org-element-property :contents-end parent) end))
24622 (goto-char (org-element-property :end parent)))
24623 ((integer-or-marker-p end) (goto-char end))
24624 (t (message "No element at point")))))))
24626 (defun org-backward-element ()
24627 "Move backward by one element.
24628 Move to the previous element at the same level, when possible."
24629 (interactive)
24630 (cond ((bobp) (user-error "Cannot move further up"))
24631 ((org-with-limited-levels (org-at-heading-p))
24632 ;; At a headline, move to the previous one, if any, or stay
24633 ;; here.
24634 (let ((origin (point)))
24635 (org-with-limited-levels (org-backward-heading-same-level 1))
24636 ;; When current headline has no sibling above, move to its
24637 ;; parent.
24638 (when (= (point) origin)
24639 (or (org-with-limited-levels (org-up-heading-safe))
24640 (progn (goto-char origin)
24641 (user-error "Cannot move further up"))))))
24643 (let* ((elem (org-element-at-point))
24644 (beg (org-element-property :begin elem)))
24645 (cond
24646 ;; Move to beginning of current element if point isn't
24647 ;; there already.
24648 ((null beg) (message "No element at point"))
24649 ((/= (point) beg) (goto-char beg))
24650 (t (goto-char beg)
24651 (skip-chars-backward " \r\t\n")
24652 (unless (bobp)
24653 (let ((prev (org-element-at-point)))
24654 (goto-char (org-element-property :begin prev))
24655 (while (and (setq prev (org-element-property :parent prev))
24656 (<= (org-element-property :end prev) beg))
24657 (goto-char (org-element-property :begin prev)))))))))))
24659 (defun org-up-element ()
24660 "Move to upper element."
24661 (interactive)
24662 (if (org-with-limited-levels (org-at-heading-p))
24663 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24664 (let* ((elem (org-element-at-point))
24665 (parent (org-element-property :parent elem)))
24666 (if parent (goto-char (org-element-property :begin parent))
24667 (if (org-with-limited-levels (org-before-first-heading-p))
24668 (user-error "No surrounding element")
24669 (org-with-limited-levels (org-back-to-heading)))))))
24671 (defvar org-element-greater-elements)
24672 (defun org-down-element ()
24673 "Move to inner element."
24674 (interactive)
24675 (let ((element (org-element-at-point)))
24676 (cond
24677 ((memq (org-element-type element) '(plain-list table))
24678 (goto-char (org-element-property :contents-begin element))
24679 (forward-char))
24680 ((memq (org-element-type element) org-element-greater-elements)
24681 ;; If contents are hidden, first disclose them.
24682 (when (outline-invisible-p (line-end-position)) (org-cycle))
24683 (goto-char (or (org-element-property :contents-begin element)
24684 (user-error "No content for this element"))))
24685 (t (user-error "No inner element")))))
24687 (defun org-drag-element-backward ()
24688 "Move backward element at point."
24689 (interactive)
24690 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24691 (let* ((elem (org-element-at-point))
24692 (prev-elem
24693 (save-excursion
24694 (goto-char (org-element-property :begin elem))
24695 (skip-chars-backward " \r\t\n")
24696 (unless (bobp)
24697 (let* ((beg (org-element-property :begin elem))
24698 (prev (org-element-at-point))
24699 (up prev))
24700 (while (and (setq up (org-element-property :parent up))
24701 (<= (org-element-property :end up) beg))
24702 (setq prev up))
24703 prev)))))
24704 ;; Error out if no previous element or previous element is
24705 ;; a parent of the current one.
24706 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24707 (user-error "Cannot drag element backward")
24708 (let ((pos (point)))
24709 (org-element-swap-A-B prev-elem elem)
24710 (goto-char (+ (org-element-property :begin prev-elem)
24711 (- pos (org-element-property :begin elem)))))))))
24713 (defun org-drag-element-forward ()
24714 "Move forward element at point."
24715 (interactive)
24716 (let* ((pos (point))
24717 (elem (org-element-at-point)))
24718 (when (= (point-max) (org-element-property :end elem))
24719 (user-error "Cannot drag element forward"))
24720 (goto-char (org-element-property :end elem))
24721 (let ((next-elem (org-element-at-point)))
24722 (when (or (org-element-nested-p elem next-elem)
24723 (and (eq (org-element-type next-elem) 'headline)
24724 (not (eq (org-element-type elem) 'headline))))
24725 (goto-char pos)
24726 (user-error "Cannot drag element forward"))
24727 ;; Compute new position of point: it's shifted by NEXT-ELEM
24728 ;; body's length (without final blanks) and by the length of
24729 ;; blanks between ELEM and NEXT-ELEM.
24730 (let ((size-next (- (save-excursion
24731 (goto-char (org-element-property :end next-elem))
24732 (skip-chars-backward " \r\t\n")
24733 (forward-line)
24734 ;; Small correction if buffer doesn't end
24735 ;; with a newline character.
24736 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24737 (org-element-property :begin next-elem)))
24738 (size-blank (- (org-element-property :end elem)
24739 (save-excursion
24740 (goto-char (org-element-property :end elem))
24741 (skip-chars-backward " \r\t\n")
24742 (forward-line)
24743 (point)))))
24744 (org-element-swap-A-B elem next-elem)
24745 (goto-char (+ pos size-next size-blank))))))
24747 (defun org-drag-line-forward (arg)
24748 "Drag the line at point ARG lines forward."
24749 (interactive "p")
24750 (dotimes (_ (abs arg))
24751 (let ((c (current-column)))
24752 (if (< 0 arg)
24753 (progn
24754 (beginning-of-line 2)
24755 (transpose-lines 1)
24756 (beginning-of-line 0))
24757 (transpose-lines 1)
24758 (beginning-of-line -1))
24759 (org-move-to-column c))))
24761 (defun org-drag-line-backward (arg)
24762 "Drag the line at point ARG lines backward."
24763 (interactive "p")
24764 (org-drag-line-forward (- arg)))
24766 (defun org-mark-element ()
24767 "Put point at beginning of this element, mark at end.
24769 Interactively, if this command is repeated or (in Transient Mark
24770 mode) if the mark is active, it marks the next element after the
24771 ones already marked."
24772 (interactive)
24773 (let (deactivate-mark)
24774 (if (and (org-called-interactively-p 'any)
24775 (or (and (eq last-command this-command) (mark t))
24776 (and transient-mark-mode mark-active)))
24777 (set-mark
24778 (save-excursion
24779 (goto-char (mark))
24780 (goto-char (org-element-property :end (org-element-at-point)))))
24781 (let ((element (org-element-at-point)))
24782 (end-of-line)
24783 (push-mark (org-element-property :end element) t t)
24784 (goto-char (org-element-property :begin element))))))
24786 (defun org-narrow-to-element ()
24787 "Narrow buffer to current element."
24788 (interactive)
24789 (let ((elem (org-element-at-point)))
24790 (cond
24791 ((eq (car elem) 'headline)
24792 (narrow-to-region
24793 (org-element-property :begin elem)
24794 (org-element-property :end elem)))
24795 ((memq (car elem) org-element-greater-elements)
24796 (narrow-to-region
24797 (org-element-property :contents-begin elem)
24798 (org-element-property :contents-end elem)))
24800 (narrow-to-region
24801 (org-element-property :begin elem)
24802 (org-element-property :end elem))))))
24804 (defun org-transpose-element ()
24805 "Transpose current and previous elements, keeping blank lines between.
24806 Point is moved after both elements."
24807 (interactive)
24808 (org-skip-whitespace)
24809 (let ((end (org-element-property :end (org-element-at-point))))
24810 (org-drag-element-backward)
24811 (goto-char end)))
24813 (defun org-unindent-buffer ()
24814 "Un-indent the visible part of the buffer.
24815 Relative indentation (between items, inside blocks, etc.) isn't
24816 modified."
24817 (interactive)
24818 (unless (eq major-mode 'org-mode)
24819 (user-error "Cannot un-indent a buffer not in Org mode"))
24820 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24821 (unindent-tree
24822 (lambda (contents)
24823 (dolist (element (reverse contents))
24824 (if (memq (org-element-type element) '(headline section))
24825 (funcall unindent-tree (org-element-contents element))
24826 (save-excursion
24827 (save-restriction
24828 (narrow-to-region
24829 (org-element-property :begin element)
24830 (org-element-property :end element))
24831 (org-do-remove-indentation))))))))
24832 (funcall unindent-tree (org-element-contents parse-tree))))
24834 (defun org-show-children (&optional level)
24835 "Show all direct subheadings of this heading.
24836 Prefix arg LEVEL is how many levels below the current level
24837 should be shown. Default is enough to cause the following
24838 heading to appear."
24839 (interactive "p")
24840 ;; If `orgstruct-mode' is active, use the slower version.
24841 (if orgstruct-mode (call-interactively #'outline-show-children)
24842 (save-excursion
24843 (org-back-to-heading t)
24844 (let* ((current-level (funcall outline-level))
24845 (max-level (org-get-valid-level
24846 current-level
24847 (if level (prefix-numeric-value level) 1)))
24848 (end (save-excursion (org-end-of-subtree t t)))
24849 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24850 (past-first-child nil)
24851 ;; Make sure to skip inlinetasks.
24852 (re (format regexp-fmt
24853 current-level
24854 (cond
24855 ((not (featurep 'org-inlinetask)) "")
24856 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24858 (t (1- org-inlinetask-min-level))))))
24859 ;; Display parent heading.
24860 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24861 (forward-line)
24862 ;; Display children. First child may be deeper than expected
24863 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24864 ;; MAX-LEVEL accordingly.
24865 (while (re-search-forward re end t)
24866 (unless past-first-child
24867 (setq re (format regexp-fmt
24868 current-level
24869 (max (funcall outline-level) max-level)))
24870 (setq past-first-child t))
24871 (outline-flag-region
24872 (line-end-position 0) (line-end-position) nil))))))
24874 (defun org-show-subtree ()
24875 "Show everything after this heading at deeper levels."
24876 (interactive)
24877 (outline-flag-region
24878 (point)
24879 (save-excursion
24880 (org-end-of-subtree t t))
24881 nil))
24883 (defun org-show-entry ()
24884 "Show the body directly following this heading.
24885 Show the heading too, if it is currently invisible."
24886 (interactive)
24887 (save-excursion
24888 (ignore-errors
24889 (org-back-to-heading t)
24890 (outline-flag-region
24891 (max (point-min) (1- (point)))
24892 (save-excursion
24893 (if (re-search-forward
24894 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24895 (match-beginning 1)
24896 (point-max)))
24897 nil)
24898 (org-cycle-hide-drawers 'children))))
24900 (defun org-make-options-regexp (kwds &optional extra)
24901 "Make a regular expression for keyword lines.
24902 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24903 when non-nil, is a regexp matching keywords names."
24904 (concat "^[ \t]*#\\+\\("
24905 (regexp-opt kwds)
24906 (and extra (concat (and kwds "\\|") extra))
24907 "\\):[ \t]*\\(.*\\)"))
24909 ;; Make isearch reveal the necessary context
24910 (defun org-isearch-end ()
24911 "Reveal context after isearch exits."
24912 (when isearch-success ; only if search was successful
24913 (if (featurep 'xemacs)
24914 ;; Under XEmacs, the hook is run in the correct place,
24915 ;; we directly show the context.
24916 (org-show-context 'isearch)
24917 ;; In Emacs the hook runs *before* restoring the overlays.
24918 ;; So we have to use a one-time post-command-hook to do this.
24919 ;; (Emacs 22 has a special variable, see function `org-mode')
24920 (unless (and (boundp 'isearch-mode-end-hook-quit)
24921 isearch-mode-end-hook-quit)
24922 ;; Only when the isearch was not quitted.
24923 (org-add-hook 'post-command-hook 'org-isearch-post-command
24924 'append 'local)))))
24926 (defun org-isearch-post-command ()
24927 "Remove self from hook, and show context."
24928 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24929 (org-show-context 'isearch))
24932 ;;;; Integration with and fixes for other packages
24934 ;;; Imenu support
24936 (defvar-local org-imenu-markers nil
24937 "All markers currently used by Imenu.")
24939 (defun org-imenu-new-marker (&optional pos)
24940 "Return a new marker for use by Imenu, and remember the marker."
24941 (let ((m (make-marker)))
24942 (move-marker m (or pos (point)))
24943 (push m org-imenu-markers)
24946 (defun org-imenu-get-tree ()
24947 "Produce the index for Imenu."
24948 (dolist (x org-imenu-markers) (move-marker x nil))
24949 (setq org-imenu-markers nil)
24950 (let* ((n org-imenu-depth)
24951 (re (concat "^" (org-get-limited-outline-regexp)))
24952 (subs (make-vector (1+ n) nil))
24953 (last-level 0)
24954 m level head0 head)
24955 (save-excursion
24956 (save-restriction
24957 (widen)
24958 (goto-char (point-max))
24959 (while (re-search-backward re nil t)
24960 (setq level (org-reduced-level (funcall outline-level)))
24961 (when (and (<= level n)
24962 (looking-at org-complex-heading-regexp)
24963 (setq head0 (org-match-string-no-properties 4)))
24964 (setq head (org-link-display-format head0)
24965 m (org-imenu-new-marker))
24966 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24967 (if (>= level last-level)
24968 (push (cons head m) (aref subs level))
24969 (push (cons head (aref subs (1+ level))) (aref subs level))
24970 (loop for i from (1+ level) to n do (aset subs i nil)))
24971 (setq last-level level)))))
24972 (aref subs 1)))
24974 (eval-after-load "imenu"
24975 '(progn
24976 (add-hook 'imenu-after-jump-hook
24977 (lambda ()
24978 (when (derived-mode-p 'org-mode)
24979 (org-show-context 'org-goto))))))
24981 (defun org-link-display-format (link)
24982 "Replace a link with its the description.
24983 If there is no description, use the link target."
24984 (save-match-data
24985 (if (string-match org-bracket-link-analytic-regexp link)
24986 (replace-match (if (match-end 5)
24987 (match-string 5 link)
24988 (concat (match-string 1 link)
24989 (match-string 3 link)))
24990 nil t link)
24991 link)))
24993 (defun org-toggle-link-display ()
24994 "Toggle the literal or descriptive display of links."
24995 (interactive)
24996 (if org-descriptive-links
24997 (progn (org-remove-from-invisibility-spec '(org-link))
24998 (org-restart-font-lock)
24999 (setq org-descriptive-links nil))
25000 (progn (add-to-invisibility-spec '(org-link))
25001 (org-restart-font-lock)
25002 (setq org-descriptive-links t))))
25004 ;; Speedbar support
25006 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25007 "Overlay marking the agenda restriction line in speedbar.")
25008 (overlay-put org-speedbar-restriction-lock-overlay
25009 'face 'org-agenda-restriction-lock)
25010 (overlay-put org-speedbar-restriction-lock-overlay
25011 'help-echo "Agendas are currently limited to this item.")
25012 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25014 (defun org-speedbar-set-agenda-restriction ()
25015 "Restrict future agenda commands to the location at point in speedbar.
25016 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25017 (interactive)
25018 (require 'org-agenda)
25019 (let (p m tp np dir txt)
25020 (cond
25021 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25022 'org-imenu t))
25023 (setq m (get-text-property p 'org-imenu-marker))
25024 (with-current-buffer (marker-buffer m)
25025 (goto-char m)
25026 (org-agenda-set-restriction-lock 'subtree)))
25027 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25028 'speedbar-function 'speedbar-find-file))
25029 (setq tp (previous-single-property-change
25030 (1+ p) 'speedbar-function)
25031 np (next-single-property-change
25032 tp 'speedbar-function)
25033 dir (speedbar-line-directory)
25034 txt (buffer-substring-no-properties (or tp (point-min))
25035 (or np (point-max))))
25036 (with-current-buffer (find-file-noselect
25037 (let ((default-directory dir))
25038 (expand-file-name txt)))
25039 (unless (derived-mode-p 'org-mode)
25040 (user-error "Cannot restrict to non-Org-mode file"))
25041 (org-agenda-set-restriction-lock 'file)))
25042 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25043 (move-overlay org-speedbar-restriction-lock-overlay
25044 (point-at-bol) (point-at-eol))
25045 (setq current-prefix-arg nil)
25046 (org-agenda-maybe-redo)))
25048 (defvar speedbar-file-key-map)
25049 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25050 (eval-after-load "speedbar"
25051 '(progn
25052 (speedbar-add-supported-extension ".org")
25053 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25054 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25055 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25056 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25057 (add-hook 'speedbar-visiting-tag-hook
25058 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25060 ;;; Fixes and Hacks for problems with other packages
25062 (defun org--flyspell-object-check-p (element)
25063 "Non-nil when Flyspell can check object at point.
25064 ELEMENT is the element at point."
25065 (let ((object (save-excursion
25066 (when (org-looking-at-p "\\>") (backward-char))
25067 (org-element-context element))))
25068 (case (org-element-type object)
25069 ;; Prevent checks in links due to keybinding conflict with
25070 ;; Flyspell.
25071 ((code entity export-snippet inline-babel-call
25072 inline-src-block line-break latex-fragment link macro
25073 statistics-cookie target timestamp verbatim)
25074 nil)
25075 (footnote-reference
25076 ;; Only in inline footnotes, within the definition.
25077 (and (eq (org-element-property :type object) 'inline)
25078 (< (save-excursion
25079 (goto-char (org-element-property :begin object))
25080 (search-forward ":" nil t 2))
25081 (point))))
25082 (otherwise t))))
25084 (defun org-mode-flyspell-verify ()
25085 "Function used for `flyspell-generic-check-word-predicate'."
25086 (if (org-at-heading-p)
25087 ;; At a headline or an inlinetask, check title only. This is
25088 ;; faster than relying on `org-element-at-point'.
25089 (and (save-excursion (beginning-of-line)
25090 (and (let ((case-fold-search t))
25091 (not (looking-at "\\*+ END[ \t]*$")))
25092 (looking-at org-complex-heading-regexp)))
25093 (match-beginning 4)
25094 (>= (point) (match-beginning 4))
25095 (or (not (match-beginning 5))
25096 (< (point) (match-beginning 5))))
25097 (let* ((element (org-element-at-point))
25098 (post-affiliated (org-element-property :post-affiliated element)))
25099 (cond
25100 ;; Ignore checks in all affiliated keywords but captions.
25101 ((< (point) post-affiliated)
25102 (and (save-excursion
25103 (beginning-of-line)
25104 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25105 (> (point) (match-end 0))
25106 (org--flyspell-object-check-p element)))
25107 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25108 ((let ((log (org-log-into-drawer)))
25109 (and log
25110 (let ((drawer (org-element-lineage element '(drawer))))
25111 (and drawer
25112 (eq (compare-strings
25113 log nil nil
25114 (org-element-property :drawer-name drawer) nil nil t)
25115 t)))))
25116 nil)
25118 (case (org-element-type element)
25119 ((comment quote-section) t)
25120 (comment-block
25121 ;; Allow checks between block markers, not on them.
25122 (and (> (line-beginning-position) post-affiliated)
25123 (save-excursion
25124 (end-of-line)
25125 (skip-chars-forward " \r\t\n")
25126 (< (point) (org-element-property :end element)))))
25127 ;; Arbitrary list of keywords where checks are meaningful.
25128 ;; Make sure point is on the value part of the element.
25129 (keyword
25130 (and (member (org-element-property :key element)
25131 '("DESCRIPTION" "TITLE"))
25132 (save-excursion
25133 (search-backward ":" (line-beginning-position) t))))
25134 ;; Check is globally allowed in paragraphs verse blocks and
25135 ;; table rows (after affiliated keywords) but some objects
25136 ;; must not be affected.
25137 ((paragraph table-row verse-block)
25138 (let ((cbeg (org-element-property :contents-begin element))
25139 (cend (org-element-property :contents-end element)))
25140 (and cbeg (>= (point) cbeg) (< (point) cend)
25141 (org--flyspell-object-check-p element))))))))))
25142 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25144 (defun org-remove-flyspell-overlays-in (beg end)
25145 "Remove flyspell overlays in region."
25146 (and (org-bound-and-true-p flyspell-mode)
25147 (fboundp 'flyspell-delete-region-overlays)
25148 (flyspell-delete-region-overlays beg end)))
25150 (defvar flyspell-delayed-commands)
25151 (eval-after-load "flyspell"
25152 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25154 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25155 (eval-after-load "bookmark"
25156 '(if (boundp 'bookmark-after-jump-hook)
25157 ;; We can use the hook
25158 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25159 ;; Hook not available, use advice
25160 (defadvice bookmark-jump (after org-make-visible activate)
25161 "Make the position visible."
25162 (org-bookmark-jump-unhide))))
25164 ;; Make sure saveplace shows the location if it was hidden
25165 (eval-after-load "saveplace"
25166 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25167 "Make the position visible."
25168 (org-bookmark-jump-unhide)))
25170 ;; Make sure ecb shows the location if it was hidden
25171 (eval-after-load "ecb"
25172 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25173 "Make hierarchy visible when jumping into location from ECB tree buffer."
25174 (when (derived-mode-p 'org-mode)
25175 (org-show-context))))
25177 (defun org-bookmark-jump-unhide ()
25178 "Unhide the current position, to show the bookmark location."
25179 (and (derived-mode-p 'org-mode)
25180 (or (outline-invisible-p)
25181 (save-excursion (goto-char (max (point-min) (1- (point))))
25182 (outline-invisible-p)))
25183 (org-show-context 'bookmark-jump)))
25185 (defun org-mark-jump-unhide ()
25186 "Make the point visible with `org-show-context' after jumping to the mark."
25187 (when (and (derived-mode-p 'org-mode)
25188 (outline-invisible-p))
25189 (org-show-context 'mark-goto)))
25191 (eval-after-load "simple"
25192 '(defadvice pop-to-mark-command (after org-make-visible activate)
25193 "Make the point visible with `org-show-context'."
25194 (org-mark-jump-unhide)))
25196 (eval-after-load "simple"
25197 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25198 "Make the point visible with `org-show-context'."
25199 (org-mark-jump-unhide)))
25201 (eval-after-load "simple"
25202 '(defadvice pop-global-mark (after org-make-visible activate)
25203 "Make the point visible with `org-show-context'."
25204 (org-mark-jump-unhide)))
25206 ;; Make session.el ignore our circular variable
25207 (defvar session-globals-exclude)
25208 (eval-after-load "session"
25209 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25211 ;;;; Finish up
25213 (provide 'org)
25215 (run-hooks 'org-load-hook)
25217 ;;; org.el ends here