Fix (void-variable d) error
[org-mode/org-tableheadings.git] / lisp / org.el
blobcce4f3a4326229d3db3b6ba02c147d018e716c7a
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (&optional date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data &optional parent))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
139 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
140 (declare-function org-element-property "org-element" (property element))
141 (declare-function org-element-put-property "org-element" (element property value))
142 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
143 (declare-function org-element-type "org-element" (element))
144 (declare-function org-element-update-syntax "org-element" ())
145 (declare-function org-id-find-id-file "org-id" (id))
146 (declare-function org-id-get-create "org-id" (&optional force))
147 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
148 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
149 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
150 (declare-function org-plot/gnuplot "org-plot" (&optional params))
151 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-edit-field "org-table" (arg))
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
164 (declare-function org-table-next-row "org-table" ())
165 (declare-function org-table-paste-rectangle "org-table" ())
166 (declare-function org-table-wrap-region "org-table" (arg))
167 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
168 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
169 (declare-function orgtbl-mode "org-table" (&optional arg))
171 (defsubst org-uniquify (list)
172 "Non-destructively remove duplicate elements from LIST."
173 (let ((res (copy-sequence list))) (delete-dups res)))
175 (defsubst org-get-at-bol (property)
176 "Get text property PROPERTY at the beginning of line."
177 (get-text-property (point-at-bol) property))
179 (defsubst org-trim (s)
180 "Remove whitespace at the beginning and the end of string S."
181 (replace-regexp-in-string
182 "\\`[ \t\n\r]+" ""
183 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org-mode FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the org-mode file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org-mode buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Emacs Lisp" emacs-lisp)
258 (const :tag "Forth" forth)
259 (const :tag "Fortran" fortran)
260 (const :tag "Gnuplot" gnuplot)
261 (const :tag "Haskell" haskell)
262 (const :tag "IO" io)
263 (const :tag "J" J)
264 (const :tag "Java" java)
265 (const :tag "Javascript" js)
266 (const :tag "LaTeX" latex)
267 (const :tag "Ledger" ledger)
268 (const :tag "Lilypond" lilypond)
269 (const :tag "Lisp" lisp)
270 (const :tag "Makefile" makefile)
271 (const :tag "Maxima" maxima)
272 (const :tag "Matlab" matlab)
273 (const :tag "Mscgen" mscgen)
274 (const :tag "Ocaml" ocaml)
275 (const :tag "Octave" octave)
276 (const :tag "Org" org)
277 (const :tag "Perl" perl)
278 (const :tag "Pico Lisp" picolisp)
279 (const :tag "PlantUML" plantuml)
280 (const :tag "Python" python)
281 (const :tag "Ruby" ruby)
282 (const :tag "Sass" sass)
283 (const :tag "Scala" scala)
284 (const :tag "Scheme" scheme)
285 (const :tag "Screen" screen)
286 (const :tag "Shell Script" shell)
287 (const :tag "Shen" shen)
288 (const :tag "Sql" sql)
289 (const :tag "Sqlite" sqlite)
290 (const :tag "Stan" stan)
291 (const :tag "ebnf2ps" ebnf2ps))
292 :value-type (boolean :tag "Activate" :value t)))
294 ;;;; Customization variables
295 (defcustom org-clone-delete-id nil
296 "Remove ID property of clones of a subtree.
297 When non-nil, clones of a subtree don't inherit the ID property.
298 Otherwise they inherit the ID property with a new unique
299 identifier."
300 :type 'boolean
301 :version "24.1"
302 :group 'org-id)
304 ;;; Version
305 (org-check-version)
307 ;;;###autoload
308 (defun org-version (&optional here full message)
309 "Show the org-mode version.
310 Interactively, or when MESSAGE is non-nil, show it in echo area.
311 With prefix argument, or when HERE is non-nil, insert it at point.
312 In non-interactive uses, a reduced version string is output unless
313 FULL is given."
314 (interactive (list current-prefix-arg t (not current-prefix-arg)))
315 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
316 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
317 (load-suffixes (list ".el"))
318 (org-install-dir
319 (ignore-errors (org-find-library-dir "org-loaddefs"))))
320 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
321 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
322 (let* ((load-suffixes save-load-suffixes)
323 (release (org-release))
324 (git-version (org-git-version))
325 (version (format "Org-mode version %s (%s @ %s)"
326 release
327 git-version
328 (if org-install-dir
329 (if (string= org-dir org-install-dir)
330 org-install-dir
331 (concat "mixed installation! "
332 org-install-dir
333 " and "
334 org-dir))
335 "org-loaddefs.el can not be found!")))
336 (version1 (if full version release)))
337 (when here (insert version1))
338 (when message (message "%s" version1))
339 version1)))
341 (defconst org-version (org-version))
344 ;;; Syntax Constants
346 ;;;; Block
348 (defconst org-block-regexp
349 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
350 "Regular expression for hiding blocks.")
352 (defconst org-dblock-start-re
353 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
354 "Matches the start line of a dynamic block, with parameters.")
356 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
357 "Matches the end of a dynamic block.")
359 ;;;; Clock and Planning
361 (defconst org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item.")
364 (defvar org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry.")
367 (defvar org-deadline-string "DEADLINE:"
368 "String to mark deadline entries.
369 A deadline is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-deadline].")
373 (defvar org-scheduled-string "SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].")
379 (defconst org-ds-keyword-length
380 (+ 2
381 (apply #'max
382 (mapcar #'length
383 (list org-deadline-string org-scheduled-string
384 org-clock-string org-closed-string))))
385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
387 (defconst org-planning-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-closed-string org-deadline-string org-scheduled-string)
392 "Matches a line with planning info.
393 Matched keyword is in group 1.")
395 (defconst org-clock-line-re
396 (concat "^[ \t]*" org-clock-string)
397 "Matches a line with clock info.")
399 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
400 "Matches the DEADLINE keyword.")
402 (defconst org-deadline-time-regexp
403 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
404 "Matches the DEADLINE keyword together with a time stamp.")
406 (defconst org-deadline-time-hour-regexp
407 (concat "\\<" org-deadline-string
408 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
409 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
411 (defconst org-deadline-line-regexp
412 (concat "\\<\\(" org-deadline-string "\\).*")
413 "Matches the DEADLINE keyword and the rest of the line.")
415 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
416 "Matches the SCHEDULED keyword.")
418 (defconst org-scheduled-time-regexp
419 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
420 "Matches the SCHEDULED keyword together with a time stamp.")
422 (defconst org-scheduled-time-hour-regexp
423 (concat "\\<" org-scheduled-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
427 (defconst org-closed-time-regexp
428 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
429 "Matches the CLOSED keyword together with a time stamp.")
431 (defconst org-keyword-time-regexp
432 (concat "\\<"
433 (regexp-opt
434 (list org-scheduled-string org-deadline-string org-closed-string
435 org-clock-string)
437 " *[[<]\\([^]>]+\\)[]>]")
438 "Matches any of the 4 keywords, together with the time stamp.")
440 (defconst org-keyword-time-not-clock-regexp
441 (concat
442 "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string) t)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 3 keywords, together with the time stamp.")
448 (defconst org-maybe-keyword-time-regexp
449 (concat "\\(\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string
452 org-clock-string)
454 "\\)?"
455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
456 "\\|"
457 "<%%([^\r\n>]*>\\)")
458 "Matches a timestamp, possibly preceded by a keyword.")
460 (defconst org-all-time-keywords
461 (mapcar (lambda (w) (substring w 0 -1))
462 (list org-scheduled-string org-deadline-string
463 org-clock-string org-closed-string))
464 "List of time keywords.")
466 ;;;; Drawer
468 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
469 "Matches first or last line of a hidden block.
470 Group 1 contains drawer's name or \"END\".")
472 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
473 "Regular expression matching the first line of a property drawer.")
475 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
476 "Regular expression matching the last line of a property drawer.")
478 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
479 "Regular expression matching the first line of a clock drawer.")
481 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a clock drawer.")
484 (defconst org-property-drawer-re
485 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
486 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
487 "[ \t]*:END:[ \t]*$")
488 "Matches an entire property drawer.")
490 (defconst org-clock-drawer-re
491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
492 org-clock-drawer-end-re "\\)\n?")
493 "Matches an entire clock drawer.")
495 ;;;; Headline
497 (defconst org-heading-keyword-regexp-format
498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
499 "Printf format for a regexp matching a headline with some keyword.
500 This regexp will match the headline of any node which has the
501 exact keyword that is put into the format. The keyword isn't in
502 any group by default, but the stars and the body are.")
504 (defconst org-heading-keyword-maybe-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline, possibly with some keyword.
507 This regexp can match any headline with the specified keyword, or
508 without a keyword. The keyword isn't in any group by default,
509 but the stars and the body are.")
511 (defconst org-archive-tag "ARCHIVE"
512 "The tag that marks a subtree as archived.
513 An archived subtree does not open during visibility cycling, and does
514 not contribute to the agenda listings.")
516 (defconst org-comment-string "COMMENT"
517 "Entries starting with this keyword will never be exported.
518 An entry can be toggled between COMMENT and normal with
519 \\[org-toggle-comment].")
522 ;;;; LaTeX Environments and Fragments
524 (defconst org-latex-regexps
525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
533 "Regular expressions for matching embedded LaTeX.")
535 ;;;; Node Property
537 (defconst org-effort-property "Effort"
538 "The property that is being used to keep track of effort estimates.
539 Effort estimates given in this property need to have the format H:MM.")
541 ;;;; Table
543 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
544 "Detect an org-type or table-type table.")
546 (defconst org-table-line-regexp "^[ \t]*|"
547 "Detect an org-type table line.")
549 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
550 "Detect an org-type table line.")
552 (defconst org-table-hline-regexp "^[ \t]*|-"
553 "Detect an org-type table hline.")
555 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
556 "Detect a table-type table hline.")
558 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
559 "Detect the first line outside a table when searching from within it.
560 This works for both table types.")
562 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
563 "Detect a #+TBLFM line.")
565 ;;;; Timestamp
567 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
568 "Regular expression for fast time stamp matching.")
570 (defconst org-ts-regexp-inactive
571 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
572 "Regular expression for fast inactive time stamp matching.")
574 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp0
578 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
579 "Regular expression matching time strings for analysis.
580 This one does not require the space after the date, so it can be used
581 on a string that terminates immediately after the date.")
583 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
584 "Regular expression matching time strings for analysis.")
586 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
587 "Regular expression matching time stamps, with groups.")
589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
590 "Regular expression matching time stamps (also [..]), with groups.")
592 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tr-regexp-both
596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
600 org-ts-regexp "\\)?")
601 "Regular expression matching a time stamp or time stamp range.")
603 (defconst org-tsr-regexp-both
604 (concat org-ts-regexp-both "\\(--?-?"
605 org-ts-regexp-both "\\)?")
606 "Regular expression matching a time stamp or time stamp range.
607 The time stamps may be either active or inactive.")
609 (defconst org-repeat-re
610 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
611 "Regular expression for specifying repeated events.
612 After a match, group 1 contains the repeat expression.")
614 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
615 "Formats for `format-time-string' which are used for time stamps.")
618 ;;; The custom variables
620 (defgroup org nil
621 "Outline-based notes management and organizer."
622 :tag "Org"
623 :group 'outlines
624 :group 'calendar)
626 (defcustom org-mode-hook nil
627 "Mode hook for Org-mode, run after the mode was turned on."
628 :group 'org
629 :type 'hook)
631 (defcustom org-load-hook nil
632 "Hook that is run after org.el has been loaded."
633 :group 'org
634 :type 'hook)
636 (defcustom org-log-buffer-setup-hook nil
637 "Hook that is run after an Org log buffer is created."
638 :group 'org
639 :version "24.1"
640 :type 'hook)
642 (defvar org-modules) ; defined below
643 (defvar org-modules-loaded nil
644 "Have the modules been loaded already?")
646 (defun org-load-modules-maybe (&optional force)
647 "Load all extensions listed in `org-modules'."
648 (when (or force (not org-modules-loaded))
649 (dolist (ext org-modules)
650 (condition-case nil (require ext)
651 (error (message "Problems while trying to load feature `%s'" ext))))
652 (setq org-modules-loaded t)))
654 (defun org-set-modules (var value)
655 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
656 (set var value)
657 (when (featurep 'org)
658 (org-load-modules-maybe 'force)
659 (org-element-cache-reset 'all)))
661 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
662 "Modules that should always be loaded together with org.el.
664 If a description starts with <C>, the file is not part of Emacs
665 and loading it will require that you have downloaded and properly
666 installed the Org mode distribution.
668 You can also use this system to load external packages (i.e. neither Org
669 core modules, nor modules from the CONTRIB directory). Just add symbols
670 to the end of the list. If the package is called org-xyz.el, then you need
671 to add the symbol `xyz', and the package must have a call to:
673 (provide \\='org-xyz)
675 For export specific modules, see also `org-export-backends'."
676 :group 'org
677 :set 'org-set-modules
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type
681 '(set :greedy t
682 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
683 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
684 (const :tag " crypt: Encryption of subtrees" org-crypt)
685 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
686 (const :tag " docview: Links to doc-view buffers" org-docview)
687 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
688 (const :tag " habit: Track your consistency with habits" org-habit)
689 (const :tag " id: Global IDs for identifying entries" org-id)
690 (const :tag " info: Links to Info nodes" org-info)
691 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
692 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
693 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
694 (const :tag " mouse: Additional mouse support" org-mouse)
695 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
696 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
697 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
699 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
700 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
701 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
702 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
703 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
704 (const :tag "C collector: Collect properties into tables" org-collector)
705 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
706 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
707 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
708 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
709 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
710 (const :tag "C eval: Include command output as text" org-eval)
711 (const :tag "C eww: Store link to url of eww" org-eww)
712 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
713 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
714 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
715 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
716 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
717 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
718 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
719 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
720 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
721 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
722 (const :tag "C mew: Links to Mew folders/messages" org-mew)
723 (const :tag "C mtags: Support for muse-like tags" org-mtags)
724 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
725 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
726 (const :tag "C registry: A registry for Org-mode links" org-registry)
727 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
728 (const :tag "C secretary: Team management with org-mode" org-secretary)
729 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
730 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
731 (const :tag "C track: Keep up with Org-mode development" org-track)
732 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
733 (const :tag "C vm: Links to VM folders/messages" org-vm)
734 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
735 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
736 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
738 (defvar org-export-registered-backends) ; From ox.el.
739 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
740 (declare-function org-export-backend-name "ox" (backend))
741 (defcustom org-export-backends '(ascii html icalendar latex)
742 "List of export back-ends that should be always available.
744 If a description starts with <C>, the file is not part of Emacs
745 and loading it will require that you have downloaded and properly
746 installed the Org mode distribution.
748 Unlike to `org-modules', libraries in this list will not be
749 loaded along with Org, but only once the export framework is
750 needed.
752 This variable needs to be set before org.el is loaded. If you
753 need to make a change while Emacs is running, use the customize
754 interface or run the following code, where VAL stands for the new
755 value of the variable, after updating it:
757 (progn
758 (setq org-export-registered-backends
759 (cl-remove-if-not
760 (lambda (backend)
761 (let ((name (org-export-backend-name backend)))
762 (or (memq name val)
763 (catch \\='parentp
764 (dolist (b val)
765 (and (org-export-derived-backend-p b name)
766 (throw \\='parentp t)))))))
767 org-export-registered-backends))
768 (let ((new-list (mapcar #\\='org-export-backend-name
769 org-export-registered-backends)))
770 (dolist (backend val)
771 (cond
772 ((not (load (format \"ox-%s\" backend) t t))
773 (message \"Problems while trying to load export back-end \\=`%s\\='\"
774 backend))
775 ((not (memq backend new-list)) (push backend new-list))))
776 (set-default \\='org-export-backends new-list)))
778 Adding a back-end to this list will also pull the back-end it
779 depends on, if any."
780 :group 'org
781 :group 'org-export
782 :version "24.4"
783 :package-version '(Org . "8.0")
784 :initialize 'custom-initialize-set
785 :set (lambda (var val)
786 (if (not (featurep 'ox)) (set-default var val)
787 ;; Any back-end not required anymore (not present in VAL and not
788 ;; a parent of any back-end in the new value) is removed from the
789 ;; list of registered back-ends.
790 (setq org-export-registered-backends
791 (cl-remove-if-not
792 (lambda (backend)
793 (let ((name (org-export-backend-name backend)))
794 (or (memq name val)
795 (catch 'parentp
796 (dolist (b val)
797 (and (org-export-derived-backend-p b name)
798 (throw 'parentp t)))))))
799 org-export-registered-backends))
800 ;; Now build NEW-LIST of both new back-ends and required
801 ;; parents.
802 (let ((new-list (mapcar #'org-export-backend-name
803 org-export-registered-backends)))
804 (dolist (backend val)
805 (cond
806 ((not (load (format "ox-%s" backend) t t))
807 (message "Problems while trying to load export back-end `%s'"
808 backend))
809 ((not (memq backend new-list)) (push backend new-list))))
810 ;; Set VAR to that list with fixed dependencies.
811 (set-default var new-list))))
812 :type '(set :greedy t
813 (const :tag " ascii Export buffer to ASCII format" ascii)
814 (const :tag " beamer Export buffer to Beamer presentation" beamer)
815 (const :tag " html Export buffer to HTML format" html)
816 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
817 (const :tag " latex Export buffer to LaTeX format" latex)
818 (const :tag " man Export buffer to MAN format" man)
819 (const :tag " md Export buffer to Markdown format" md)
820 (const :tag " odt Export buffer to ODT format" odt)
821 (const :tag " org Export buffer to Org format" org)
822 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
823 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
824 (const :tag "C deck Export buffer to deck.js presentations" deck)
825 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
826 (const :tag "C groff Export buffer to Groff format" groff)
827 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
828 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
829 (const :tag "C s5 Export buffer to s5 presentations" s5)
830 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
832 (eval-after-load 'ox
833 '(dolist (backend org-export-backends)
834 (condition-case nil (require (intern (format "ox-%s" backend)))
835 (error (message "Problems while trying to load export back-end `%s'"
836 backend)))))
838 (defcustom org-support-shift-select nil
839 "Non-nil means make shift-cursor commands select text when possible.
840 \\<org-mode-map>\
842 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
843 start selecting a region, or enlarge regions started in this way.
844 In Org-mode, in special contexts, these same keys are used for
845 other purposes, important enough to compete with shift selection.
846 Org tries to balance these needs by supporting `shift-select-mode'
847 outside these special contexts, under control of this variable.
849 The default of this variable is nil, to avoid confusing behavior. Shifted
850 cursor keys will then execute Org commands in the following contexts:
851 - on a headline, changing TODO state (left/right) and priority (up/down)
852 - on a time stamp, changing the time
853 - in a plain list item, changing the bullet type
854 - in a property definition line, switching between allowed values
855 - in the BEGIN line of a clock table (changing the time block).
856 Outside these contexts, the commands will throw an error.
858 When this variable is t and the cursor is not in a special
859 context, Org-mode will support shift-selection for making and
860 enlarging regions. To make this more effective, the bullet
861 cycling will no longer happen anywhere in an item line, but only
862 if the cursor is exactly on the bullet.
864 If you set this variable to the symbol `always', then the keys
865 will not be special in headlines, property lines, and item lines,
866 to make shift selection work there as well. If this is what you
867 want, you can use the following alternative commands:
868 `\\[org-todo]' and `\\[org-priority]' \
869 to change TODO state and priority,
870 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
871 can be used to switch TODO sets,
872 `\\[org-ctrl-c-minus]' to cycle item bullet types,
873 and properties can be edited by hand or in column view.
875 However, when the cursor is on a timestamp, shift-cursor commands
876 will still edit the time stamp - this is just too good to give up.
878 XEmacs user should have this variable set to nil, because
879 `shift-select-mode' is in Emacs 23 or later only."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped."
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-indented nil
945 "Non-nil means turn on `org-indent-mode' on startup.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
949 #+STARTUP: indent
950 #+STARTUP: noindent"
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Not" nil)
954 (const :tag "Globally (slow on startup in large files)" t)))
956 (defcustom org-use-sub-superscripts t
957 "Non-nil means interpret \"_\" and \"^\" for display.
959 If you want to control how Org exports those characters, see
960 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
961 used to be an alias for `org-export-with-sub-superscripts' in
962 Org <8.0, it is not anymore.
964 When this option is turned on, you can use TeX-like syntax for
965 sub- and superscripts within the buffer. Several characters after
966 \"_\" or \"^\" will be considered as a single item - so grouping
967 with {} is normally not needed. For example, the following things
968 will be parsed as single sub- or superscripts:
970 10^24 or 10^tau several digits will be considered 1 item.
971 10^-12 or 10^-tau a leading sign with digits or a word
972 x^2-y^3 will be read as x^2 - y^3, because items are
973 terminated by almost any nonword/nondigit char.
974 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
976 Still, ambiguity is possible. So when in doubt, use {} to enclose
977 the sub/superscript. If you set this variable to the symbol `{}',
978 the braces are *required* in order to trigger interpretations as
979 sub/superscript. This can be helpful in documents that need \"_\"
980 frequently in plain text."
981 :group 'org-startup
982 :version "24.4"
983 :package-version '(Org . "8.0")
984 :type '(choice
985 (const :tag "Always interpret" t)
986 (const :tag "Only with braces" {})
987 (const :tag "Never interpret" nil)))
989 (defcustom org-startup-with-beamer-mode nil
990 "Non-nil means turn on `org-beamer-mode' on startup.
991 This can also be configured on a per-file basis by adding one of
992 the following lines anywhere in the buffer:
994 #+STARTUP: beamer"
995 :group 'org-startup
996 :version "24.1"
997 :type 'boolean)
999 (defcustom org-startup-align-all-tables nil
1000 "Non-nil means align all tables when visiting a file.
1001 This is useful when the column width in tables is forced with <N> cookies
1002 in table fields. Such tables will look correct only after the first re-align.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1005 #+STARTUP: align
1006 #+STARTUP: noalign"
1007 :group 'org-startup
1008 :type 'boolean)
1010 (defcustom org-startup-with-inline-images nil
1011 "Non-nil means show inline images when loading a new Org file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: inlineimages
1015 #+STARTUP: noinlineimages"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-with-latex-preview nil
1021 "Non-nil means preview LaTeX fragments when loading a new Org file.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: latexpreview
1026 #+STARTUP: nolatexpreview"
1027 :group 'org-startup
1028 :version "24.4"
1029 :package-version '(Org . "8.0")
1030 :type 'boolean)
1032 (defcustom org-insert-mode-line-in-empty-file nil
1033 "Non-nil means insert the first line setting Org-mode in empty files.
1034 When the function `org-mode' is called interactively in an empty file, this
1035 normally means that the file name does not automatically trigger Org-mode.
1036 To ensure that the file will always be in Org-mode in the future, a
1037 line enforcing Org-mode will be inserted into the buffer, if this option
1038 has been set."
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-replace-disputed-keys nil
1043 "Non-nil means use alternative key bindings for some keys.
1044 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1045 These keys are also used by other packages like shift-selection-mode'
1046 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1047 If you want to use Org-mode together with one of these other modes,
1048 or more generally if you would like to move some Org-mode commands to
1049 other keys, set this variable and configure the keys with the variable
1050 `org-disputed-keys'.
1052 This option is only relevant at load-time of Org-mode, and must be set
1053 *before* org.el is loaded. Changing it requires a restart of Emacs to
1054 become effective."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-use-extra-keys nil
1059 "Non-nil means use extra key sequence definitions for certain commands.
1060 This happens automatically if you run XEmacs or if `window-system'
1061 is nil. This variable lets you do the same manually. You must
1062 set it before loading org.
1064 Example: on Carbon Emacs 22 running graphically, with an external
1065 keyboard on a Powerbook, the default way of setting M-left might
1066 not work for either Alt or ESC. Setting this variable will make
1067 it work for ESC."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1073 (defcustom org-disputed-keys
1074 '(([(shift up)] . [(meta p)])
1075 ([(shift down)] . [(meta n)])
1076 ([(shift left)] . [(meta -)])
1077 ([(shift right)] . [(meta +)])
1078 ([(control shift right)] . [(meta shift +)])
1079 ([(control shift left)] . [(meta shift -)]))
1080 "Keys for which Org-mode and other modes compete.
1081 This is an alist, cars are the default keys, second element specifies
1082 the alternative to use when `org-replace-disputed-keys' is t.
1084 Keys can be specified in any syntax supported by `define-key'.
1085 The value of this option takes effect only at Org-mode's startup,
1086 therefore you'll have to restart Emacs to apply it after changing."
1087 :group 'org-startup
1088 :type 'alist)
1090 (defun org-key (key)
1091 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1092 Or return the original if not disputed.
1093 Also apply the translations defined in `org-xemacs-key-equivalents'."
1094 (when org-replace-disputed-keys
1095 (let* ((nkey (key-description key))
1096 (x (org-find-if (lambda (x)
1097 (equal (key-description (car x)) nkey))
1098 org-disputed-keys)))
1099 (setq key (if x (cdr x) key))))
1100 (when (featurep 'xemacs)
1101 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1102 key)
1104 (defun org-find-if (predicate seq)
1105 (catch 'exit
1106 (while seq
1107 (if (funcall predicate (car seq))
1108 (throw 'exit (car seq))
1109 (pop seq)))))
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org-mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1119 When a face, use the standard 3 dots, but with the specified face.
1120 The change affects only Org-mode (which will then use its own display table).
1121 Changing this requires executing \\[org-mode] in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (face :tag "Face" :value org-warning)
1126 (string :tag "String" :value "...#")))
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org-mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org-mode files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((isearch . lineage)
1155 (bookmark-jump . lineage)
1156 (default . ancestors))
1157 "Alist between context and visibility span when revealing a location.
1159 \\<org-mode-map>Some actions may move point into invisible
1160 locations. As a consequence, Org always expose a neighborhood
1161 around point. How much is shown depends on the initial action,
1162 or context. Valid contexts are
1164 agenda when exposing an entry from the agenda
1165 org-goto when using the command `org-goto' (\\[org-goto])
1166 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1167 tags-tree when constructing a sparse tree based on tags matches
1168 link-search when exposing search matches associated with a link
1169 mark-goto when exposing the jump goal of a mark
1170 bookmark-jump when exposing a bookmark location
1171 isearch when exiting from an incremental search
1172 default default for all contexts not set explicitly
1174 Allowed visibility spans are
1176 minimal show current headline; if point is not on headline,
1177 also show entry
1179 local show current headline, entry and next headline
1181 ancestors show current headline and its direct ancestors; if
1182 point is not on headline, also show entry
1184 lineage show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and first child
1188 tree show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and all children
1192 canonical show current headline, its direct ancestors along with
1193 their entries and children; if point is not located on
1194 the headline, also show current entry and all children
1196 As special cases, a nil or t value means show all contexts in
1197 `minimal' or `canonical' view, respectively.
1199 Some views can make displayed information very compact, but also
1200 make it harder to edit the location of the match. In such
1201 a case, use the command `org-reveal' (\\[org-reveal]) to show
1202 more context."
1203 :group 'org-reveal-location
1204 :version "25.1"
1205 :package-version '(Org . "8.3")
1206 :type '(choice
1207 (const :tag "Canonical" t)
1208 (const :tag "Minimal" nil)
1209 (repeat :greedy t :tag "Individual contexts"
1210 (cons
1211 (choice :tag "Context"
1212 (const agenda)
1213 (const org-goto)
1214 (const occur-tree)
1215 (const tags-tree)
1216 (const link-search)
1217 (const mark-goto)
1218 (const bookmark-jump)
1219 (const isearch)
1220 (const default))
1221 (choice :tag "Detail level"
1222 (const minimal)
1223 (const local)
1224 (const ancestors)
1225 (const lineage)
1226 (const tree)
1227 (const canonical))))))
1229 (defcustom org-indirect-buffer-display 'other-window
1230 "How should indirect tree buffers be displayed?
1231 This applies to indirect buffers created with the commands
1232 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1233 Valid values are:
1234 current-window Display in the current window
1235 other-window Just display in another window.
1236 dedicated-frame Create one new frame, and re-use it each time.
1237 new-frame Make a new frame each time. Note that in this case
1238 previously-made indirect buffers are kept, and you need to
1239 kill these buffers yourself."
1240 :group 'org-structure
1241 :group 'org-agenda-windows
1242 :type '(choice
1243 (const :tag "In current window" current-window)
1244 (const :tag "In current frame, other window" other-window)
1245 (const :tag "Each time a new frame" new-frame)
1246 (const :tag "One dedicated frame" dedicated-frame)))
1248 (defcustom org-use-speed-commands nil
1249 "Non-nil means activate single letter commands at beginning of a headline.
1250 This may also be a function to test for appropriate locations where speed
1251 commands should be active.
1253 For example, to activate speed commands when the point is on any
1254 star at the beginning of the headline, you can do this:
1256 (setq org-use-speed-commands
1257 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1258 :group 'org-structure
1259 :type '(choice
1260 (const :tag "Never" nil)
1261 (const :tag "At beginning of headline stars" t)
1262 (function)))
1264 (defcustom org-speed-commands-user nil
1265 "Alist of additional speed commands.
1266 This list will be checked before `org-speed-commands-default'
1267 when the variable `org-use-speed-commands' is non-nil
1268 and when the cursor is at the beginning of a headline.
1269 The car if each entry is a string with a single letter, which must
1270 be assigned to `self-insert-command' in the global map.
1271 The cdr is either a command to be called interactively, a function
1272 to be called, or a form to be evaluated.
1273 An entry that is just a list with a single string will be interpreted
1274 as a descriptive headline that will be added when listing the speed
1275 commands in the Help buffer using the `?' speed command."
1276 :group 'org-structure
1277 :type '(repeat :value ("k" . ignore)
1278 (choice :value ("k" . ignore)
1279 (list :tag "Descriptive Headline" (string :tag "Headline"))
1280 (cons :tag "Letter and Command"
1281 (string :tag "Command letter")
1282 (choice
1283 (function)
1284 (sexp))))))
1286 (defcustom org-bookmark-names-plist
1287 '(:last-capture "org-capture-last-stored"
1288 :last-refile "org-refile-last-stored"
1289 :last-capture-marker "org-capture-last-stored-marker")
1290 "Names for bookmarks automatically set by some Org commands.
1291 This can provide strings as names for a number of bookmarks Org sets
1292 automatically. The following keys are currently implemented:
1293 :last-capture
1294 :last-capture-marker
1295 :last-refile
1296 When a key does not show up in the property list, the corresponding bookmark
1297 is not set."
1298 :group 'org-structure
1299 :type 'plist)
1301 (defgroup org-cycle nil
1302 "Options concerning visibility cycling in Org-mode."
1303 :tag "Org Cycle"
1304 :group 'org-structure)
1306 (defcustom org-cycle-skip-children-state-if-no-children t
1307 "Non-nil means skip CHILDREN state in entries that don't have any."
1308 :group 'org-cycle
1309 :type 'boolean)
1311 (defcustom org-cycle-max-level nil
1312 "Maximum level which should still be subject to visibility cycling.
1313 Levels higher than this will, for cycling, be treated as text, not a headline.
1314 When `org-odd-levels-only' is set, a value of N in this variable actually
1315 means 2N-1 stars as the limiting headline.
1316 When nil, cycle all levels.
1317 Note that the limiting level of cycling is also influenced by
1318 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1319 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1320 than its value."
1321 :group 'org-cycle
1322 :type '(choice
1323 (const :tag "No limit" nil)
1324 (integer :tag "Maximum level")))
1326 (defcustom org-hide-block-startup nil
1327 "Non-nil means entering Org-mode will fold all blocks.
1328 This can also be set in on a per-file basis with
1330 #+STARTUP: hideblocks
1331 #+STARTUP: showblocks"
1332 :group 'org-startup
1333 :group 'org-cycle
1334 :type 'boolean)
1336 (defcustom org-cycle-global-at-bob nil
1337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1338 This makes it possible to do global cycling without having to use S-TAB or
1339 \\[universal-argument] TAB. For this special case to work, the first line
1340 of the buffer must not be a headline -- it may be empty or some other text.
1341 When used in this way, `org-cycle-hook' is disabled temporarily to make
1342 sure the cursor stays at the beginning of the buffer. When this option is
1343 nil, don't do anything special at the beginning of the buffer."
1344 :group 'org-cycle
1345 :type 'boolean)
1347 (defcustom org-cycle-level-after-item/entry-creation t
1348 "Non-nil means cycle entry level or item indentation in new empty entries.
1350 When the cursor is at the end of an empty headline, i.e., with only stars
1351 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1352 and then all possible ancestor states, before returning to the original state.
1353 This makes data entry extremely fast: M-RET to create a new headline,
1354 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1356 When the cursor is at the end of an empty plain list item, one TAB will
1357 make it a subitem, two or more tabs will back up to make this an item
1358 higher up in the item hierarchy."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-emulate-tab t
1363 "Where should `org-cycle' emulate TAB.
1364 nil Never
1365 white Only in completely white lines
1366 whitestart Only at the beginning of lines, before the first non-white char
1367 t Everywhere except in headlines
1368 exc-hl-bol Everywhere except at the start of a headline
1369 If TAB is used in a place where it does not emulate TAB, the current subtree
1370 visibility is cycled."
1371 :group 'org-cycle
1372 :type '(choice (const :tag "Never" nil)
1373 (const :tag "Only in completely white lines" white)
1374 (const :tag "Before first char in a line" whitestart)
1375 (const :tag "Everywhere except in headlines" t)
1376 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1378 (defcustom org-cycle-separator-lines 2
1379 "Number of empty lines needed to keep an empty line between collapsed trees.
1380 If you leave an empty line between the end of a subtree and the following
1381 headline, this empty line is hidden when the subtree is folded.
1382 Org-mode will leave (exactly) one empty line visible if the number of
1383 empty lines is equal or larger to the number given in this variable.
1384 So the default 2 means at least 2 empty lines after the end of a subtree
1385 are needed to produce free space between a collapsed subtree and the
1386 following headline.
1388 If the number is negative, and the number of empty lines is at least -N,
1389 all empty lines are shown.
1391 Special case: when 0, never leave empty lines in collapsed view."
1392 :group 'org-cycle
1393 :type 'integer)
1394 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1396 (defcustom org-pre-cycle-hook nil
1397 "Hook that is run before visibility cycling is happening.
1398 The function(s) in this hook must accept a single argument which indicates
1399 the new state that will be set right after running this hook. The
1400 argument is a symbol. Before a global state change, it can have the values
1401 `overview', `content', or `all'. Before a local state change, it can have
1402 the values `folded', `children', or `subtree'."
1403 :group 'org-cycle
1404 :type 'hook)
1406 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1407 org-cycle-hide-drawers
1408 org-cycle-show-empty-lines
1409 org-optimize-window-after-visibility-change)
1410 "Hook that is run after `org-cycle' has changed the buffer visibility.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that was set by the most recent `org-cycle' command. The
1413 argument is a symbol. After a global state change, it can have the values
1414 `overview', `contents', or `all'. After a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook
1418 :version "25.1"
1419 :package-version '(Org . "8.3"))
1421 (defgroup org-edit-structure nil
1422 "Options concerning structure editing in Org-mode."
1423 :tag "Org Edit Structure"
1424 :group 'org-structure)
1426 (defcustom org-odd-levels-only nil
1427 "Non-nil means skip even levels and only use odd levels for the outline.
1428 This has the effect that two stars are being added/taken away in
1429 promotion/demotion commands. It also influences how levels are
1430 handled by the exporters.
1431 Changing it requires restart of `font-lock-mode' to become effective
1432 for fontification also in regions already fontified.
1433 You may also set this on a per-file basis by adding one of the following
1434 lines to the buffer:
1436 #+STARTUP: odd
1437 #+STARTUP: oddeven"
1438 :group 'org-edit-structure
1439 :group 'org-appearance
1440 :type 'boolean)
1442 (defcustom org-adapt-indentation t
1443 "Non-nil means adapt indentation to outline node level.
1445 When this variable is set, Org assumes that you write outlines by
1446 indenting text in each node to align with the headline (after the
1447 stars). The following issues are influenced by this variable:
1449 - The indentation is increased by one space in a demotion
1450 command, and decreased by one in a promotion command. However,
1451 in the latter case, if shifting some line in the entry body
1452 would alter document structure (e.g., insert a new headline),
1453 indentation is not changed at all.
1455 - Property drawers and planning information is inserted indented
1456 when this variable is set. When nil, they will not be indented.
1458 - TAB indents a line relative to current level. The lines below
1459 a headline will be indented when this variable is set.
1461 Note that this is all about true indentation, by adding and
1462 removing space characters. See also `org-indent.el' which does
1463 level-dependent indentation in a virtual way, i.e. at display
1464 time in Emacs."
1465 :group 'org-edit-structure
1466 :type 'boolean)
1468 (defcustom org-special-ctrl-a/e nil
1469 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1471 When t, `C-a' will bring back the cursor to the beginning of the
1472 headline text, i.e. after the stars and after a possible TODO
1473 keyword. In an item, this will be the position after bullet and
1474 check-box, if any. When the cursor is already at that position,
1475 another `C-a' will bring it to the beginning of the line.
1477 `C-e' will jump to the end of the headline, ignoring the presence
1478 of tags in the headline. A second `C-e' will then jump to the
1479 true end of the line, after any tags. This also means that, when
1480 this variable is non-nil, `C-e' also will never jump beyond the
1481 end of the heading of a folded section, i.e. not after the
1482 ellipses.
1484 When set to the symbol `reversed', the first `C-a' or `C-e' works
1485 normally, going to the true line boundary first. Only a directly
1486 following, identical keypress will bring the cursor to the
1487 special positions.
1489 This may also be a cons cell where the behavior for `C-a' and
1490 `C-e' is set separately."
1491 :group 'org-edit-structure
1492 :type '(choice
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet and before tags first" t)
1495 (const :tag "reversed: true line boundary first" reversed)
1496 (cons :tag "Set C-a and C-e separately"
1497 (choice :tag "Special C-a"
1498 (const :tag "off" nil)
1499 (const :tag "on: after stars/bullet first" t)
1500 (const :tag "reversed: before stars/bullet first" reversed))
1501 (choice :tag "Special C-e"
1502 (const :tag "off" nil)
1503 (const :tag "on: before tags first" t)
1504 (const :tag "reversed: after tags first" reversed)))))
1505 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1507 (defcustom org-special-ctrl-k nil
1508 "Non-nil means `C-k' will behave specially in headlines.
1509 When nil, `C-k' will call the default `kill-line' command.
1510 When t, the following will happen while the cursor is in the headline:
1512 - When the cursor is at the beginning of a headline, kill the entire
1513 line and possible the folded subtree below the line.
1514 - When in the middle of the headline text, kill the headline up to the tags.
1515 - When after the headline text, kill the tags."
1516 :group 'org-edit-structure
1517 :type 'boolean)
1519 (defcustom org-ctrl-k-protect-subtree nil
1520 "Non-nil means, do not delete a hidden subtree with C-k.
1521 When set to the symbol `error', simply throw an error when C-k is
1522 used to kill (part-of) a headline that has hidden text behind it.
1523 Any other non-nil value will result in a query to the user, if it is
1524 OK to kill that hidden subtree. When nil, kill without remorse."
1525 :group 'org-edit-structure
1526 :version "24.1"
1527 :type '(choice
1528 (const :tag "Do not protect hidden subtrees" nil)
1529 (const :tag "Protect hidden subtrees with a security query" t)
1530 (const :tag "Never kill a hidden subtree with C-k" error)))
1532 (defcustom org-special-ctrl-o t
1533 "Non-nil means, make `C-o' insert a row in tables."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-catch-invisible-edits nil
1538 "Check if in invisible region before inserting or deleting a character.
1539 Valid values are:
1541 nil Do not check, so just do invisible edits.
1542 error Throw an error and do nothing.
1543 show Make point visible, and do the requested edit.
1544 show-and-error Make point visible, then throw an error and abort the edit.
1545 smart Make point visible, and do insertion/deletion if it is
1546 adjacent to visible text and the change feels predictable.
1547 Never delete a previously invisible character or add in the
1548 middle or right after an invisible region. Basically, this
1549 allows insertion and backward-delete right before ellipses.
1550 FIXME: maybe in this case we should not even show?"
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not check" nil)
1555 (const :tag "Throw error when trying to edit" error)
1556 (const :tag "Unhide, but do not do the edit" show-and-error)
1557 (const :tag "Show invisible part and do the edit" show)
1558 (const :tag "Be smart and do the right thing" smart)))
1560 (defcustom org-yank-folded-subtrees t
1561 "Non-nil means when yanking subtrees, fold them.
1562 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1563 it starts with a heading and all other headings in it are either children
1564 or siblings, then fold all the subtrees. However, do this only if no
1565 text after the yank would be swallowed into a folded tree by this action."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-yank-adjusted-subtrees nil
1570 "Non-nil means when yanking subtrees, adjust the level.
1571 With this setting, `org-paste-subtree' is used to insert the subtree, see
1572 this function for details."
1573 :group 'org-edit-structure
1574 :type 'boolean)
1576 (defcustom org-M-RET-may-split-line '((default . t))
1577 "Non-nil means M-RET will split the line at the cursor position.
1578 When nil, it will go to the end of the line before making a
1579 new line.
1580 You may also set this option in a different way for different
1581 contexts. Valid contexts are:
1583 headline when creating a new headline
1584 item when creating a new item
1585 table in a table field
1586 default the value to be used for all contexts not explicitly
1587 customized"
1588 :group 'org-structure
1589 :group 'org-table
1590 :type '(choice
1591 (const :tag "Always" t)
1592 (const :tag "Never" nil)
1593 (repeat :greedy t :tag "Individual contexts"
1594 (cons
1595 (choice :tag "Context"
1596 (const headline)
1597 (const item)
1598 (const table)
1599 (const default))
1600 (boolean)))))
1603 (defcustom org-insert-heading-respect-content nil
1604 "Non-nil means insert new headings after the current subtree.
1605 When nil, the new heading is created directly after the current line.
1606 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1607 this variable on for the duration of the command."
1608 :group 'org-structure
1609 :type 'boolean)
1611 (defcustom org-blank-before-new-entry '((heading . auto)
1612 (plain-list-item . auto))
1613 "Should `org-insert-heading' leave a blank line before new heading/item?
1614 The value is an alist, with `heading' and `plain-list-item' as CAR,
1615 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1616 which case Org will look at the surrounding headings/items and try to
1617 make an intelligent decision whether to insert a blank line or not."
1618 :group 'org-edit-structure
1619 :type '(list
1620 (cons (const heading)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))
1624 (cons (const plain-list-item)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))))
1629 (defcustom org-insert-heading-hook nil
1630 "Hook being run after inserting a new heading."
1631 :group 'org-edit-structure
1632 :type 'hook)
1634 (defcustom org-enable-fixed-width-editor t
1635 "Non-nil means lines starting with \":\" are treated as fixed-width.
1636 This currently only means they are never auto-wrapped.
1637 When nil, such lines will be treated like ordinary lines."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-goto-auto-isearch t
1642 "Non-nil means typing characters in `org-goto' starts incremental search.
1643 When nil, you can use these keybindings to navigate the buffer:
1645 q Quit the org-goto interface
1646 n Go to the next visible heading
1647 p Go to the previous visible heading
1648 f Go one heading forward on same level
1649 b Go one heading backward on same level
1650 u Go one heading up"
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org-mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1679 (defcustom org-occur-hook '(org-first-headline-recenter)
1680 "Hook that is run after `org-occur' has constructed a sparse tree.
1681 This can be used to recenter the window to show as much of the structure
1682 as possible."
1683 :group 'org-sparse-trees
1684 :type 'hook)
1686 (defgroup org-imenu-and-speedbar nil
1687 "Options concerning imenu and speedbar in Org-mode."
1688 :tag "Org Imenu and Speedbar"
1689 :group 'org-structure)
1691 (defcustom org-imenu-depth 2
1692 "The maximum level for Imenu access to Org-mode headlines.
1693 This also applied for speedbar access."
1694 :group 'org-imenu-and-speedbar
1695 :type 'integer)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org-mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-enable-table-editor 'optimized
1703 "Non-nil means lines starting with \"|\" are handled by the table editor.
1704 When nil, such lines will be treated like ordinary lines.
1706 When equal to the symbol `optimized', the table editor will be optimized to
1707 do the following:
1708 - Automatic overwrite mode in front of whitespace in table fields.
1709 This makes the structure of the table stay in tact as long as the edited
1710 field does not exceed the column width.
1711 - Minimize the number of realigns. Normally, the table is aligned each time
1712 TAB or RET are pressed to move to another field. With optimization this
1713 happens only if changes to a field might have changed the column width.
1714 Optimization requires replacing the functions `self-insert-command',
1715 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1716 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1717 very good at guessing when a re-align will be necessary, but you can always
1718 force one with \\[org-ctrl-c-ctrl-c].
1720 If you would like to use the optimized version in Org-mode, but the
1721 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1723 This variable can be used to turn on and off the table editor during a session,
1724 but in order to toggle optimization, a restart is required.
1726 See also the variable `org-table-auto-blank-field'."
1727 :group 'org-table
1728 :type '(choice
1729 (const :tag "off" nil)
1730 (const :tag "on" t)
1731 (const :tag "on, optimized" optimized)))
1733 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1734 (version<= emacs-version "24.1"))
1735 "Non-nil means cluster self-insert commands for undo when possible.
1736 If this is set, then, like in the Emacs command loop, 20 consecutive
1737 characters will be undone together.
1738 This is configurable, because there is some impact on typing performance."
1739 :group 'org-table
1740 :type 'boolean)
1742 (defcustom org-table-tab-recognizes-table.el t
1743 "Non-nil means TAB will automatically notice a table.el table.
1744 When it sees such a table, it moves point into it and - if necessary -
1745 calls `table-recognize-table'."
1746 :group 'org-table-editing
1747 :type 'boolean)
1749 (defgroup org-link nil
1750 "Options concerning links in Org-mode."
1751 :tag "Org Link"
1752 :group 'org)
1754 (defvar-local org-link-abbrev-alist-local nil
1755 "Buffer-local version of `org-link-abbrev-alist', which see.
1756 The value of this is taken from the #+LINK lines.")
1758 (defcustom org-link-abbrev-alist nil
1759 "Alist of link abbreviations.
1760 The car of each element is a string, to be replaced at the start of a link.
1761 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1762 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1764 [[linkkey:tag][description]]
1766 The `linkkey' must be a word word, starting with a letter, followed
1767 by letters, numbers, `-' or `_'.
1769 If REPLACE is a string, the tag will simply be appended to create the link.
1770 If the string contains \"%s\", the tag will be inserted there. If the string
1771 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1772 at that point (see the function `url-hexify-string'). If the string contains
1773 the specifier \"%(my-function)\", then the custom function `my-function' will
1774 be invoked: this function takes the tag as its only argument and must return
1775 a string.
1777 REPLACE may also be a function that will be called with the tag as the
1778 only argument to create the link, which should be returned as a string.
1780 See the manual for examples."
1781 :group 'org-link
1782 :type '(repeat
1783 (cons
1784 (string :tag "Protocol")
1785 (choice
1786 (string :tag "Format")
1787 (function)))))
1789 (defcustom org-descriptive-links t
1790 "Non-nil means Org will display descriptive links.
1791 E.g. [[http://orgmode.org][Org website]] will be displayed as
1792 \"Org Website\", hiding the link itself and just displaying its
1793 description. When set to nil, Org will display the full links
1794 literally.
1796 You can interactively set the value of this variable by calling
1797 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1798 :group 'org-link
1799 :type 'boolean)
1801 (defcustom org-link-file-path-type 'adaptive
1802 "How the path name in file links should be stored.
1803 Valid values are:
1805 relative Relative to the current directory, i.e. the directory of the file
1806 into which the link is being inserted.
1807 absolute Absolute path, if possible with ~ for home directory.
1808 noabbrev Absolute path, no abbreviation of home directory.
1809 adaptive Use relative path for files in the current directory and sub-
1810 directories of it. For other files, use an absolute path."
1811 :group 'org-link
1812 :type '(choice
1813 (const relative)
1814 (const absolute)
1815 (const noabbrev)
1816 (const adaptive)))
1818 (defvaralias 'org-activate-links 'org-highlight-links)
1819 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1820 "Types of links that should be highlighted in Org-mode files.
1822 This is a list of symbols, each one of them leading to the
1823 highlighting of a certain link type.
1825 You can still open links that are not highlighted.
1827 In principle, it does not hurt to turn on highlighting for all
1828 link types. There may be a small gain when turning off unused
1829 link types. The types are:
1831 bracket The recommended [[link][description]] or [[link]] links with hiding.
1832 angle Links in angular brackets that may contain whitespace like
1833 <bbdb:Carsten Dominik>.
1834 plain Plain links in normal text, no whitespace, like http://google.com.
1835 radio Text that is matched by a radio target, see manual for details.
1836 tag Tag settings in a headline (link to tag search).
1837 date Time stamps (link to calendar).
1838 footnote Footnote labels.
1840 If you set this variable during an Emacs session, use `org-mode-restart'
1841 in the Org buffer so that the change takes effect."
1842 :group 'org-link
1843 :group 'org-appearance
1844 :type '(set :greedy t
1845 (const :tag "Double bracket links" bracket)
1846 (const :tag "Angular bracket links" angle)
1847 (const :tag "Plain text links" plain)
1848 (const :tag "Radio target matches" radio)
1849 (const :tag "Tags" tag)
1850 (const :tag "Timestamps" date)
1851 (const :tag "Footnotes" footnote)))
1853 (defcustom org-make-link-description-function nil
1854 "Function to use for generating link descriptions from links.
1855 When nil, the link location will be used. This function must take
1856 two parameters: the first one is the link, the second one is the
1857 description generated by `org-insert-link'. The function should
1858 return the description to use."
1859 :group 'org-link
1860 :type '(choice (const nil) (function)))
1862 (defgroup org-link-store nil
1863 "Options concerning storing links in Org-mode."
1864 :tag "Org Store Link"
1865 :group 'org-link)
1867 (defcustom org-url-hexify-p t
1868 "When non-nil, hexify URL when creating a link."
1869 :type 'boolean
1870 :version "24.3"
1871 :group 'org-link-store)
1873 (defcustom org-email-link-description-format "Email %c: %.30s"
1874 "Format of the description part of a link to an email or usenet message.
1875 The following %-escapes will be replaced by corresponding information:
1877 %F full \"From\" field
1878 %f name, taken from \"From\" field, address if no name
1879 %T full \"To\" field
1880 %t first name in \"To\" field, address if no name
1881 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1882 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1883 %s subject
1884 %d date
1885 %m message-id.
1887 You may use normal field width specification between the % and the letter.
1888 This is for example useful to limit the length of the subject.
1890 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1891 :group 'org-link-store
1892 :type 'string)
1894 (defcustom org-from-is-user-regexp
1895 (let (r1 r2)
1896 (when (and user-mail-address (not (string= user-mail-address "")))
1897 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1898 (when (and user-full-name (not (string= user-full-name "")))
1899 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1900 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1901 "Regexp matched against the \"From:\" header of an email or usenet message.
1902 It should match if the message is from the user him/herself."
1903 :group 'org-link-store
1904 :type 'regexp)
1906 (defcustom org-context-in-file-links t
1907 "Non-nil means file links from `org-store-link' contain context.
1908 A search string will be added to the file name with :: as separator and
1909 used to find the context when the link is activated by the command
1910 `org-open-at-point'. When this option is t, the entire active region
1911 will be placed in the search string of the file link. If set to a
1912 positive integer, only the first n lines of context will be stored.
1914 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1915 negates this setting for the duration of the command."
1916 :group 'org-link-store
1917 :type '(choice boolean integer))
1919 (defcustom org-keep-stored-link-after-insertion nil
1920 "Non-nil means keep link in list for entire session.
1922 The command `org-store-link' adds a link pointing to the current
1923 location to an internal list. These links accumulate during a session.
1924 The command `org-insert-link' can be used to insert links into any
1925 Org-mode file (offering completion for all stored links). When this
1926 option is nil, every link which has been inserted once using \\[org-insert-link]
1927 will be removed from the list, to make completing the unused links
1928 more efficient."
1929 :group 'org-link-store
1930 :type 'boolean)
1932 (defgroup org-link-follow nil
1933 "Options concerning following links in Org-mode."
1934 :tag "Org Follow Link"
1935 :group 'org-link)
1937 (defcustom org-link-translation-function nil
1938 "Function to translate links with different syntax to Org syntax.
1939 This can be used to translate links created for example by the Planner
1940 or emacs-wiki packages to Org syntax.
1941 The function must accept two parameters, a TYPE containing the link
1942 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1943 which is everything after the link protocol. It should return a cons
1944 with possibly modified values of type and path.
1945 Org contains a function for this, so if you set this variable to
1946 `org-translate-link-from-planner', you should be able follow many
1947 links created by planner."
1948 :group 'org-link-follow
1949 :type '(choice (const nil) (function)))
1951 (defcustom org-follow-link-hook nil
1952 "Hook that is run after a link has been followed."
1953 :group 'org-link-follow
1954 :type 'hook)
1956 (defcustom org-tab-follows-link nil
1957 "Non-nil means on links TAB will follow the link.
1958 Needs to be set before org.el is loaded.
1959 This really should not be used, it does not make sense, and the
1960 implementation is bad."
1961 :group 'org-link-follow
1962 :type 'boolean)
1964 (defcustom org-return-follows-link nil
1965 "Non-nil means on links RET will follow the link.
1966 In tables, the special behavior of RET has precedence."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-mouse-1-follows-link
1971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1972 "Non-nil means mouse-1 on a link will follow the link.
1973 A longer mouse click will still set point. Does not work on XEmacs.
1974 Needs to be set before org.el is loaded."
1975 :group 'org-link-follow
1976 :version "24.4"
1977 :package-version '(Org . "8.3")
1978 :type '(choice
1979 (const :tag "A double click follows the link" double)
1980 (const :tag "Unconditionally follow the link with mouse-1" t)
1981 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1983 (defcustom org-mark-ring-length 4
1984 "Number of different positions to be recorded in the ring.
1985 Changing this requires a restart of Emacs to work correctly."
1986 :group 'org-link-follow
1987 :type 'integer)
1989 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1990 "Non-nil means internal links in Org files must exactly match a headline.
1991 When nil, the link search tries to match a phrase with all words
1992 in the search text."
1993 :group 'org-link-follow
1994 :version "24.1"
1995 :type '(choice
1996 (const :tag "Use fuzzy text search" nil)
1997 (const :tag "Match only exact headline" t)
1998 (const :tag "Match exact headline or query to create it"
1999 query-to-create)))
2001 (defcustom org-link-frame-setup
2002 '((vm . vm-visit-folder-other-frame)
2003 (vm-imap . vm-visit-imap-folder-other-frame)
2004 (gnus . org-gnus-no-new-news)
2005 (file . find-file-other-window)
2006 (wl . wl-other-frame))
2007 "Setup the frame configuration for following links.
2008 When following a link with Emacs, it may often be useful to display
2009 this link in another window or frame. This variable can be used to
2010 set this up for the different types of links.
2011 For VM, use any of
2012 `vm-visit-folder'
2013 `vm-visit-folder-other-window'
2014 `vm-visit-folder-other-frame'
2015 For Gnus, use any of
2016 `gnus'
2017 `gnus-other-frame'
2018 `org-gnus-no-new-news'
2019 For FILE, use any of
2020 `find-file'
2021 `find-file-other-window'
2022 `find-file-other-frame'
2023 For Wanderlust use any of
2024 `wl'
2025 `wl-other-frame'
2026 For the calendar, use the variable `calendar-setup'.
2027 For BBDB, it is currently only possible to display the matches in
2028 another window."
2029 :group 'org-link-follow
2030 :type '(list
2031 (cons (const vm)
2032 (choice
2033 (const vm-visit-folder)
2034 (const vm-visit-folder-other-window)
2035 (const vm-visit-folder-other-frame)))
2036 (cons (const vm-imap)
2037 (choice
2038 (const vm-visit-imap-folder)
2039 (const vm-visit-imap-folder-other-window)
2040 (const vm-visit-imap-folder-other-frame)))
2041 (cons (const gnus)
2042 (choice
2043 (const gnus)
2044 (const gnus-other-frame)
2045 (const org-gnus-no-new-news)))
2046 (cons (const file)
2047 (choice
2048 (const find-file)
2049 (const find-file-other-window)
2050 (const find-file-other-frame)))
2051 (cons (const wl)
2052 (choice
2053 (const wl)
2054 (const wl-other-frame)))))
2056 (defcustom org-display-internal-link-with-indirect-buffer nil
2057 "Non-nil means use indirect buffer to display infile links.
2058 Activating internal links (from one location in a file to another location
2059 in the same file) normally just jumps to the location. When the link is
2060 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2061 is displayed in
2062 another window. When this option is set, the other window actually displays
2063 an indirect buffer clone of the current buffer, to avoid any visibility
2064 changes to the current buffer."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-open-non-existing-files nil
2069 "Non-nil means `org-open-file' will open non-existing files.
2070 When nil, an error will be generated.
2071 This variable applies only to external applications because they
2072 might choke on non-existing files. If the link is to a file that
2073 will be opened in Emacs, the variable is ignored."
2074 :group 'org-link-follow
2075 :type 'boolean)
2077 (defcustom org-open-directory-means-index-dot-org nil
2078 "Non-nil means a link to a directory really means to index.org.
2079 When nil, following a directory link will run dired or open a finder/explorer
2080 window on that directory."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2085 "Non-nil means ask for confirmation before executing shell links.
2086 Shell links can be dangerous: just think about a link
2088 [[shell:rm -rf ~/*][Google Search]]
2090 This link would show up in your Org-mode document as \"Google Search\",
2091 but really it would remove your entire home directory.
2092 Therefore we advise against setting this variable to nil.
2093 Just change it to `y-or-n-p' if you want to confirm with a
2094 single keystroke rather than having to type \"yes\"."
2095 :group 'org-link-follow
2096 :type '(choice
2097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2098 (const :tag "with y-or-n (faster)" y-or-n-p)
2099 (const :tag "no confirmation (dangerous)" nil)))
2100 (put 'org-confirm-shell-link-function
2101 'safe-local-variable
2102 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2104 (defcustom org-confirm-shell-link-not-regexp ""
2105 "A regexp to skip confirmation for shell links."
2106 :group 'org-link-follow
2107 :version "24.1"
2108 :type 'regexp)
2110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2111 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2112 Elisp links can be dangerous: just think about a link
2114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2116 This link would show up in your Org-mode document as \"Google Search\",
2117 but really it would remove your entire home directory.
2118 Therefore we advise against setting this variable to nil.
2119 Just change it to `y-or-n-p' if you want to confirm with a
2120 single keystroke rather than having to type \"yes\"."
2121 :group 'org-link-follow
2122 :type '(choice
2123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2124 (const :tag "with y-or-n (faster)" y-or-n-p)
2125 (const :tag "no confirmation (dangerous)" nil)))
2126 (put 'org-confirm-shell-link-function
2127 'safe-local-variable
2128 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2130 (defcustom org-confirm-elisp-link-not-regexp ""
2131 "A regexp to skip confirmation for Elisp links."
2132 :group 'org-link-follow
2133 :version "24.1"
2134 :type 'regexp)
2136 (defconst org-file-apps-defaults-gnu
2137 '((remote . emacs)
2138 (system . mailcap)
2139 (t . mailcap))
2140 "Default file applications on a UNIX or GNU/Linux system.
2141 See `org-file-apps'.")
2143 (defconst org-file-apps-defaults-macosx
2144 '((remote . emacs)
2145 (system . "open %s")
2146 ("ps.gz" . "gv %s")
2147 ("eps.gz" . "gv %s")
2148 ("dvi" . "xdvi %s")
2149 ("fig" . "xfig %s")
2150 (t . "open %s"))
2151 "Default file applications on a MacOS X system.
2152 The system \"open\" is known as a default, but we use X11 applications
2153 for some files for which the OS does not have a good default.
2154 See `org-file-apps'.")
2156 (defconst org-file-apps-defaults-windowsnt
2157 (list '(remote . emacs)
2158 (cons 'system (lambda (file _path)
2159 (with-no-warnings (w32-shell-execute "open" file))))
2160 (cons t (lambda (file _path)
2161 (with-no-warnings (w32-shell-execute "open" file)))))
2162 "Default file applications on a Windows NT system.
2163 The system \"open\" is used for most files.
2164 See `org-file-apps'.")
2166 (defcustom org-file-apps
2167 '((auto-mode . emacs)
2168 ("\\.mm\\'" . default)
2169 ("\\.x?html?\\'" . default)
2170 ("\\.pdf\\'" . default))
2171 "External applications for opening `file:path' items in a document.
2172 \\<org-mode-map>\
2173 Org mode uses system defaults for different file types, but
2174 you can use this variable to set the application for a given file
2175 extension. The entries in this list are cons cells where the car identifies
2176 files and the cdr the corresponding command. Possible values for the
2177 file identifier are
2178 \"string\" A string as a file identifier can be interpreted in different
2179 ways, depending on its contents:
2181 - Alphanumeric characters only:
2182 Match links with this file extension.
2183 Example: (\"pdf\" . \"evince %s\")
2184 to open PDFs with evince.
2186 - Regular expression: Match links where the
2187 filename matches the regexp. If you want to
2188 use groups here, use shy groups.
2190 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2191 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2192 to open *.html and *.xhtml with firefox.
2194 - Regular expression which contains (non-shy) groups:
2195 Match links where the whole link, including \"::\", and
2196 anything after that, matches the regexp.
2197 In a custom command string, %1, %2, etc. are replaced with
2198 the parts of the link that were matched by the groups.
2199 For backwards compatibility, if a command string is given
2200 that does not use any of the group matches, this case is
2201 handled identically to the second one (i.e. match against
2202 file name only).
2203 In a custom function, you can access the group matches with
2204 \(match-string n link).
2206 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2207 to open [[file:document.pdf::5]] with evince at page 5.
2209 `directory' Matches a directory
2210 `remote' Matches a remote file, accessible through tramp or efs.
2211 Remote files most likely should be visited through Emacs
2212 because external applications cannot handle such paths.
2213 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2214 so all files Emacs knows how to handle. Using this with
2215 command `emacs' will open most files in Emacs. Beware that this
2216 will also open html files inside Emacs, unless you add
2217 \(\"html\" . default) to the list as well.
2218 `system' The system command to open files, like `open' on Windows
2219 and Mac OS X, and mailcap under GNU/Linux. This is the command
2220 that will be selected if you call \\[org-open-at-point] with a double
2221 \\[universal-argument] \\[universal-argument] prefix.
2222 t Default for files not matched by any of the other options.
2224 Possible values for the command are:
2225 `emacs' The file will be visited by the current Emacs process.
2226 `default' Use the default application for this file type, which is the
2227 association for t in the list, most likely in the system-specific
2228 part. This can be used to overrule an unwanted setting in the
2229 system-specific variable.
2230 `system' Use the system command for opening files, like \"open\".
2231 This command is specified by the entry whose car is `system'.
2232 Most likely, the system-specific version of this variable
2233 does define this command, but you can overrule/replace it
2234 here.
2235 `mailcap' Use command specified in the mailcaps.
2236 string A command to be executed by a shell; %s will be replaced
2237 by the path to the file.
2239 function A Lisp function, which will be called with two arguments:
2240 the file path and the original link string, without the
2241 \"file:\" prefix.
2243 For more examples, see the system specific constants
2244 `org-file-apps-defaults-macosx'
2245 `org-file-apps-defaults-windowsnt'
2246 `org-file-apps-defaults-gnu'."
2247 :group 'org-link-follow
2248 :type '(repeat
2249 (cons (choice :value ""
2250 (string :tag "Extension")
2251 (const :tag "System command to open files" system)
2252 (const :tag "Default for unrecognized files" t)
2253 (const :tag "Remote file" remote)
2254 (const :tag "Links to a directory" directory)
2255 (const :tag "Any files that have Emacs modes"
2256 auto-mode))
2257 (choice :value ""
2258 (const :tag "Visit with Emacs" emacs)
2259 (const :tag "Use default" default)
2260 (const :tag "Use the system command" system)
2261 (string :tag "Command")
2262 (function :tag "Function")))))
2264 (defcustom org-doi-server-url "http://dx.doi.org/"
2265 "The URL of the DOI server."
2266 :type 'string
2267 :version "24.3"
2268 :group 'org-link-follow)
2270 (defgroup org-refile nil
2271 "Options concerning refiling entries in Org-mode."
2272 :tag "Org Refile"
2273 :group 'org)
2275 (defcustom org-directory "~/org"
2276 "Directory with Org files.
2277 This is just a default location to look for Org files. There is no need
2278 at all to put your files into this directory. It is used in the
2279 following situations:
2281 1. When a capture template specifies a target file that is not an
2282 absolute path. The path will then be interpreted relative to
2283 `org-directory'
2284 2. When the value of variable `org-agenda-files' is a single file, any
2285 relative paths in this file will be taken as relative to
2286 `org-directory'."
2287 :group 'org-refile
2288 :group 'org-capture
2289 :type 'directory)
2291 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2292 "Default target for storing notes.
2293 Used as a fall back file for org-capture.el, for templates that
2294 do not specify a target file."
2295 :group 'org-refile
2296 :group 'org-capture
2297 :type 'file)
2299 (defcustom org-goto-interface 'outline
2300 "The default interface to be used for `org-goto'.
2301 Allowed values are:
2302 outline The interface shows an outline of the relevant file
2303 and the correct heading is found by moving through
2304 the outline or by searching with incremental search.
2305 outline-path-completion Headlines in the current buffer are offered via
2306 completion. This is the interface also used by
2307 the refile command."
2308 :group 'org-refile
2309 :type '(choice
2310 (const :tag "Outline" outline)
2311 (const :tag "Outline-path-completion" outline-path-completion)))
2313 (defcustom org-goto-max-level 5
2314 "Maximum target level when running `org-goto' with refile interface."
2315 :group 'org-refile
2316 :type 'integer)
2318 (defcustom org-reverse-note-order nil
2319 "Non-nil means store new notes at the beginning of a file or entry.
2320 When nil, new notes will be filed to the end of a file or entry.
2321 This can also be a list with cons cells of regular expressions that
2322 are matched against file names, and values."
2323 :group 'org-capture
2324 :group 'org-refile
2325 :type '(choice
2326 (const :tag "Reverse always" t)
2327 (const :tag "Reverse never" nil)
2328 (repeat :tag "By file name regexp"
2329 (cons regexp boolean))))
2331 (defcustom org-log-refile nil
2332 "Information to record when a task is refiled.
2334 Possible values are:
2336 nil Don't add anything
2337 time Add a time stamp to the task
2338 note Prompt for a note and add it with template `org-log-note-headings'
2340 This option can also be set with on a per-file-basis with
2342 #+STARTUP: nologrefile
2343 #+STARTUP: logrefile
2344 #+STARTUP: lognoterefile
2346 You can have local logging settings for a subtree by setting the LOGGING
2347 property to one or more of these keywords.
2349 When bulk-refiling from the agenda, the value `note' is forbidden and
2350 will temporarily be changed to `time'."
2351 :group 'org-refile
2352 :group 'org-progress
2353 :version "24.1"
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record timestamp" time)
2357 (const :tag "Record timestamp with note." note)))
2359 (defcustom org-refile-targets nil
2360 "Targets for refiling entries with \\[org-refile].
2361 This is a list of cons cells. Each cell contains:
2362 - a specification of the files to be considered, either a list of files,
2363 or a symbol whose function or variable value will be used to retrieve
2364 a file name or a list of file names. If you use `org-agenda-files' for
2365 that, all agenda files will be scanned for targets. Nil means consider
2366 headings in the current buffer.
2367 - A specification of how to find candidate refile targets. This may be
2368 any of:
2369 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2370 This tag has to be present in all target headlines, inheritance will
2371 not be considered.
2372 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2373 todo keyword.
2374 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2375 headlines that are refiling targets.
2376 - a cons cell (:level . N). Any headline of level N is considered a target.
2377 Note that, when `org-odd-levels-only' is set, level corresponds to
2378 order in hierarchy, not to the number of stars.
2379 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2383 Each element of this list generates a set of possible targets.
2384 The union of these sets is presented (with completion) to
2385 the user by `org-refile'.
2387 You can set the variable `org-refile-target-verify-function' to a function
2388 to verify each headline found by the simple criteria above.
2390 When this variable is nil, all top-level headlines in the current buffer
2391 are used, equivalent to the value `((nil . (:level . 1))'."
2392 :group 'org-refile
2393 :type '(repeat
2394 (cons
2395 (choice :value org-agenda-files
2396 (const :tag "All agenda files" org-agenda-files)
2397 (const :tag "Current buffer" nil)
2398 (function) (variable) (file))
2399 (choice :tag "Identify target headline by"
2400 (cons :tag "Specific tag" (const :value :tag) (string))
2401 (cons :tag "TODO keyword" (const :value :todo) (string))
2402 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2403 (cons :tag "Level number" (const :value :level) (integer))
2404 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2406 (defcustom org-refile-target-verify-function nil
2407 "Function to verify if the headline at point should be a refile target.
2408 The function will be called without arguments, with point at the
2409 beginning of the headline. It should return t and leave point
2410 where it is if the headline is a valid target for refiling.
2412 If the target should not be selected, the function must return nil.
2413 In addition to this, it may move point to a place from where the search
2414 should be continued. For example, the function may decide that the entire
2415 subtree of the current entry should be excluded and move point to the end
2416 of the subtree."
2417 :group 'org-refile
2418 :type '(choice
2419 (const nil)
2420 (function)))
2422 (defcustom org-refile-use-cache nil
2423 "Non-nil means cache refile targets to speed up the process.
2424 \\<org-mode-map>\
2425 The cache for a particular file will be updated automatically when
2426 the buffer has been killed, or when any of the marker used for flagging
2427 refile targets no longer points at a live buffer.
2428 If you have added new entries to a buffer that might themselves be targets,
2429 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2430 if you find that easier, \
2431 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2432 \\[org-refile]'."
2433 :group 'org-refile
2434 :version "24.1"
2435 :type 'boolean)
2437 (defcustom org-refile-use-outline-path nil
2438 "Non-nil means provide refile targets as paths.
2439 So a level 3 headline will be available as level1/level2/level3.
2441 When the value is `file', also include the file name (without directory)
2442 into the path. In this case, you can also stop the completion after
2443 the file name, to get entries inserted as top level in the file.
2445 When `full-file-path', include the full file path."
2446 :group 'org-refile
2447 :type '(choice
2448 (const :tag "Not" nil)
2449 (const :tag "Yes" t)
2450 (const :tag "Start with file name" file)
2451 (const :tag "Start with full file path" full-file-path)))
2453 (defcustom org-outline-path-complete-in-steps t
2454 "Non-nil means complete the outline path in hierarchical steps.
2455 When Org-mode uses the refile interface to select an outline path
2456 \(see variable `org-refile-use-outline-path'), the completion of
2457 the path can be done in a single go, or it can be done in steps down
2458 the headline hierarchy. Going in steps is probably the best if you
2459 do not use a special completion package like `ido' or `icicles'.
2460 However, when using these packages, going in one step can be very
2461 fast, while still showing the whole path to the entry."
2462 :group 'org-refile
2463 :type 'boolean)
2465 (defcustom org-refile-allow-creating-parent-nodes nil
2466 "Non-nil means allow the creation of new nodes as refile targets.
2467 New nodes are then created by adding \"/new node name\" to the completion
2468 of an existing node. When the value of this variable is `confirm',
2469 new node creation must be confirmed by the user (recommended).
2470 When nil, the completion must match an existing entry.
2472 Note that, if the new heading is not seen by the criteria
2473 listed in `org-refile-targets', multiple instances of the same
2474 heading would be created by trying again to file under the new
2475 heading."
2476 :group 'org-refile
2477 :type '(choice
2478 (const :tag "Never" nil)
2479 (const :tag "Always" t)
2480 (const :tag "Prompt for confirmation" confirm)))
2482 (defcustom org-refile-active-region-within-subtree nil
2483 "Non-nil means also refile active region within a subtree.
2485 By default `org-refile' doesn't allow refiling regions if they
2486 don't contain a set of subtrees, but it might be convenient to
2487 do so sometimes: in that case, the first line of the region is
2488 converted to a headline before refiling."
2489 :group 'org-refile
2490 :version "24.1"
2491 :type 'boolean)
2493 (defgroup org-todo nil
2494 "Options concerning TODO items in Org-mode."
2495 :tag "Org TODO"
2496 :group 'org)
2498 (defgroup org-progress nil
2499 "Options concerning Progress logging in Org-mode."
2500 :tag "Org Progress"
2501 :group 'org-time)
2503 (defvar org-todo-interpretation-widgets
2504 '((:tag "Sequence (cycling hits every state)" sequence)
2505 (:tag "Type (cycling directly to DONE)" type))
2506 "The available interpretation symbols for customizing `org-todo-keywords'.
2507 Interested libraries should add to this list.")
2509 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2510 "List of TODO entry keyword sequences and their interpretation.
2511 \\<org-mode-map>This is a list of sequences.
2513 Each sequence starts with a symbol, either `sequence' or `type',
2514 indicating if the keywords should be interpreted as a sequence of
2515 action steps, or as different types of TODO items. The first
2516 keywords are states requiring action - these states will select a headline
2517 for inclusion into the global TODO list Org-mode produces. If one of
2518 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2519 signify that no further action is necessary. If \"|\" is not found,
2520 the last keyword is treated as the only DONE state of the sequence.
2522 The command \\[org-todo] cycles an entry through these states, and one
2523 additional state where no keyword is present. For details about this
2524 cycling, see the manual.
2526 TODO keywords and interpretation can also be set on a per-file basis with
2527 the special #+SEQ_TODO and #+TYP_TODO lines.
2529 Each keyword can optionally specify a character for fast state selection
2530 \(in combination with the variable `org-use-fast-todo-selection')
2531 and specifiers for state change logging, using the same syntax that
2532 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2533 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2534 indicates to record a time stamp each time this state is selected.
2536 Each keyword may also specify if a timestamp or a note should be
2537 recorded when entering or leaving the state, by adding additional
2538 characters in the parenthesis after the keyword. This looks like this:
2539 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2540 record only the time of the state change. With X and Y being either
2541 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2542 Y when leaving the state if and only if the *target* state does not
2543 define X. You may omit any of the fast-selection key or X or /Y,
2544 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2546 For backward compatibility, this variable may also be just a list
2547 of keywords. In this case the interpretation (sequence or type) will be
2548 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice
2552 (repeat :tag "Old syntax, just keywords"
2553 (string :tag "Keyword"))
2554 (repeat :tag "New syntax"
2555 (cons
2556 (choice
2557 :tag "Interpretation"
2558 ;;Quick and dirty way to see
2559 ;;`org-todo-interpretations'. This takes the
2560 ;;place of item arguments
2561 :convert-widget
2562 (lambda (widget)
2563 (widget-put widget
2564 :args (mapcar
2565 (lambda (x)
2566 (widget-convert
2567 (cons 'const x)))
2568 org-todo-interpretation-widgets))
2569 widget))
2570 (repeat
2571 (string :tag "Keyword"))))))
2573 (defvar-local org-todo-keywords-1 nil
2574 "All TODO and DONE keywords active in a buffer.")
2575 (defvar org-todo-keywords-for-agenda nil)
2576 (defvar org-done-keywords-for-agenda nil)
2577 (defvar org-todo-keyword-alist-for-agenda nil)
2578 (defvar org-tag-alist-for-agenda nil
2579 "Alist of all tags from all agenda files.")
2580 (defvar org-tag-groups-alist-for-agenda nil
2581 "Alist of all groups tags from all current agenda files.")
2582 (defvar-local org-tag-groups-alist nil)
2583 (defvar org-agenda-contributing-files nil)
2584 (defvar-local org-not-done-keywords nil)
2585 (defvar-local org-done-keywords nil)
2586 (defvar-local org-todo-heads nil)
2587 (defvar-local org-todo-sets nil)
2588 (defvar-local org-todo-log-states nil)
2589 (defvar-local org-todo-kwd-alist nil)
2590 (defvar-local org-todo-key-alist nil)
2591 (defvar-local org-todo-key-trigger nil)
2593 (defcustom org-todo-interpretation 'sequence
2594 "Controls how TODO keywords are interpreted.
2595 This variable is in principle obsolete and is only used for
2596 backward compatibility, if the interpretation of todo keywords is
2597 not given already in `org-todo-keywords'. See that variable for
2598 more information."
2599 :group 'org-todo
2600 :group 'org-keywords
2601 :type '(choice (const sequence)
2602 (const type)))
2604 (defcustom org-use-fast-todo-selection t
2605 "\\<org-mode-map>\
2606 Non-nil means use the fast todo selection scheme with \\[org-todo].
2607 This variable describes if and under what circumstances the cycling
2608 mechanism for TODO keywords will be replaced by a single-key, direct
2609 selection scheme.
2611 When nil, fast selection is never used.
2613 When the symbol `prefix', it will be used when `org-todo' is called
2614 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2615 in an Org-mode buffer, and
2616 `\\[universal-argument] t' in an agenda buffer.
2618 When t, fast selection is used by default. In this case, the prefix
2619 argument forces cycling instead.
2621 In all cases, the special interface is only used if access keys have
2622 actually been assigned by the user, i.e. if keywords in the configuration
2623 are followed by a letter in parenthesis, like TODO(t)."
2624 :group 'org-todo
2625 :type '(choice
2626 (const :tag "Never" nil)
2627 (const :tag "By default" t)
2628 (const :tag "Only with C-u C-c C-t" prefix)))
2630 (defcustom org-provide-todo-statistics t
2631 "Non-nil means update todo statistics after insert and toggle.
2632 ALL-HEADLINES means update todo statistics by including headlines
2633 with no TODO keyword as well, counting them as not done.
2634 A list of TODO keywords means the same, but skip keywords that are
2635 not in this list.
2636 When set to a list of two lists, the first list contains keywords
2637 to consider as TODO keywords, the second list contains keywords
2638 to consider as DONE keywords.
2640 When this is set, todo statistics is updated in the parent of the
2641 current entry each time a todo state is changed."
2642 :group 'org-todo
2643 :type '(choice
2644 (const :tag "Yes, only for TODO entries" t)
2645 (const :tag "Yes, including all entries" all-headlines)
2646 (repeat :tag "Yes, for TODOs in this list"
2647 (string :tag "TODO keyword"))
2648 (list :tag "Yes, for TODOs and DONEs in these lists"
2649 (repeat (string :tag "TODO keyword"))
2650 (repeat (string :tag "DONE keyword")))
2651 (other :tag "No TODO statistics" nil)))
2653 (defcustom org-hierarchical-todo-statistics t
2654 "Non-nil means TODO statistics covers just direct children.
2655 When nil, all entries in the subtree are considered.
2656 This has only an effect if `org-provide-todo-statistics' is set.
2657 To set this to nil for only a single subtree, use a COOKIE_DATA
2658 property and include the word \"recursive\" into the value."
2659 :group 'org-todo
2660 :type 'boolean)
2662 (defcustom org-after-todo-state-change-hook nil
2663 "Hook which is run after the state of a TODO item was changed.
2664 The new state (a string with a TODO keyword, or nil) is available in the
2665 Lisp variable `org-state'."
2666 :group 'org-todo
2667 :type 'hook)
2669 (defvar org-blocker-hook nil
2670 "Hook for functions that are allowed to block a state change.
2672 Functions in this hook should not modify the buffer.
2673 Each function gets as its single argument a property list,
2674 see `org-trigger-hook' for more information about this list.
2676 If any of the functions in this hook returns nil, the state change
2677 is blocked.")
2679 (defvar org-trigger-hook nil
2680 "Hook for functions that are triggered by a state change.
2682 Each function gets as its single argument a property list with at
2683 least the following elements:
2685 (:type type-of-change :position pos-at-entry-start
2686 :from old-state :to new-state)
2688 Depending on the type, more properties may be present.
2690 This mechanism is currently implemented for:
2692 TODO state changes
2693 ------------------
2694 :type todo-state-change
2695 :from previous state (keyword as a string), or nil, or a symbol
2696 `todo' or `done', to indicate the general type of state.
2697 :to new state, like in :from")
2699 (defcustom org-enforce-todo-dependencies nil
2700 "Non-nil means undone TODO entries will block switching the parent to DONE.
2701 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2702 be blocked if any prior sibling is not yet done.
2703 Finally, if the parent is blocked because of ordered siblings of its own,
2704 the child will also be blocked."
2705 :set (lambda (var val)
2706 (set var val)
2707 (if val
2708 (add-hook 'org-blocker-hook
2709 'org-block-todo-from-children-or-siblings-or-parent)
2710 (remove-hook 'org-blocker-hook
2711 'org-block-todo-from-children-or-siblings-or-parent)))
2712 :group 'org-todo
2713 :type 'boolean)
2715 (defcustom org-enforce-todo-checkbox-dependencies nil
2716 "Non-nil means unchecked boxes will block switching the parent to DONE.
2717 When this is nil, checkboxes have no influence on switching TODO states.
2718 When non-nil, you first need to check off all check boxes before the TODO
2719 entry can be switched to DONE.
2720 This variable needs to be set before org.el is loaded, and you need to
2721 restart Emacs after a change to make the change effective. The only way
2722 to change is while Emacs is running is through the customize interface."
2723 :set (lambda (var val)
2724 (set var val)
2725 (if val
2726 (add-hook 'org-blocker-hook
2727 'org-block-todo-from-checkboxes)
2728 (remove-hook 'org-blocker-hook
2729 'org-block-todo-from-checkboxes)))
2730 :group 'org-todo
2731 :type 'boolean)
2733 (defcustom org-treat-insert-todo-heading-as-state-change nil
2734 "Non-nil means inserting a TODO heading is treated as state change.
2735 So when the command \\[org-insert-todo-heading] is used, state change
2736 logging will apply if appropriate. When nil, the new TODO item will
2737 be inserted directly, and no logging will take place."
2738 :group 'org-todo
2739 :type 'boolean)
2741 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2742 "Non-nil means switching TODO states with S-cursor counts as state change.
2743 This is the default behavior. However, setting this to nil allows a
2744 convenient way to select a TODO state and bypass any logging associated
2745 with that."
2746 :group 'org-todo
2747 :type 'boolean)
2749 (defcustom org-todo-state-tags-triggers nil
2750 "Tag changes that should be triggered by TODO state changes.
2751 This is a list. Each entry is
2753 (state-change (tag . flag) .......)
2755 State-change can be a string with a state, and empty string to indicate the
2756 state that has no TODO keyword, or it can be one of the symbols `todo'
2757 or `done', meaning any not-done or done state, respectively."
2758 :group 'org-todo
2759 :group 'org-tags
2760 :type '(repeat
2761 (cons (choice :tag "When changing to"
2762 (const :tag "Not-done state" todo)
2763 (const :tag "Done state" done)
2764 (string :tag "State"))
2765 (repeat
2766 (cons :tag "Tag action"
2767 (string :tag "Tag")
2768 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2770 (defcustom org-log-done nil
2771 "Information to record when a task moves to the DONE state.
2773 Possible values are:
2775 nil Don't add anything, just change the keyword
2776 time Add a time stamp to the task
2777 note Prompt for a note and add it with template `org-log-note-headings'
2779 This option can also be set with on a per-file-basis with
2781 #+STARTUP: nologdone
2782 #+STARTUP: logdone
2783 #+STARTUP: lognotedone
2785 You can have local logging settings for a subtree by setting the LOGGING
2786 property to one or more of these keywords."
2787 :group 'org-todo
2788 :group 'org-progress
2789 :type '(choice
2790 (const :tag "No logging" nil)
2791 (const :tag "Record CLOSED timestamp" time)
2792 (const :tag "Record CLOSED timestamp with note." note)))
2794 ;; Normalize old uses of org-log-done.
2795 (cond
2796 ((eq org-log-done t) (setq org-log-done 'time))
2797 ((and (listp org-log-done) (memq 'done org-log-done))
2798 (setq org-log-done 'note)))
2800 (defcustom org-log-reschedule nil
2801 "Information to record when the scheduling date of a tasks is modified.
2803 Possible values are:
2805 nil Don't add anything, just change the date
2806 time Add a time stamp to the task
2807 note Prompt for a note and add it with template `org-log-note-headings'
2809 This option can also be set with on a per-file-basis with
2811 #+STARTUP: nologreschedule
2812 #+STARTUP: logreschedule
2813 #+STARTUP: lognotereschedule"
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(choice
2817 (const :tag "No logging" nil)
2818 (const :tag "Record timestamp" time)
2819 (const :tag "Record timestamp with note." note)))
2821 (defcustom org-log-redeadline nil
2822 "Information to record when the deadline date of a tasks is modified.
2824 Possible values are:
2826 nil Don't add anything, just change the date
2827 time Add a time stamp to the task
2828 note Prompt for a note and add it with template `org-log-note-headings'
2830 This option can also be set with on a per-file-basis with
2832 #+STARTUP: nologredeadline
2833 #+STARTUP: logredeadline
2834 #+STARTUP: lognoteredeadline
2836 You can have local logging settings for a subtree by setting the LOGGING
2837 property to one or more of these keywords."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(choice
2841 (const :tag "No logging" nil)
2842 (const :tag "Record timestamp" time)
2843 (const :tag "Record timestamp with note." note)))
2845 (defcustom org-log-note-clock-out nil
2846 "Non-nil means record a note when clocking out of an item.
2847 This can also be configured on a per-file basis by adding one of
2848 the following lines anywhere in the buffer:
2850 #+STARTUP: lognoteclock-out
2851 #+STARTUP: nolognoteclock-out"
2852 :group 'org-todo
2853 :group 'org-progress
2854 :type 'boolean)
2856 (defcustom org-log-done-with-time t
2857 "Non-nil means the CLOSED time stamp will contain date and time.
2858 When nil, only the date will be recorded."
2859 :group 'org-progress
2860 :type 'boolean)
2862 (defcustom org-log-note-headings
2863 '((done . "CLOSING NOTE %t")
2864 (state . "State %-12s from %-12S %t")
2865 (note . "Note taken on %t")
2866 (reschedule . "Rescheduled from %S on %t")
2867 (delschedule . "Not scheduled, was %S on %t")
2868 (redeadline . "New deadline from %S on %t")
2869 (deldeadline . "Removed deadline, was %S on %t")
2870 (refile . "Refiled on %t")
2871 (clock-out . ""))
2872 "Headings for notes added to entries.
2874 The value is an alist, with the car being a symbol indicating the
2875 note context, and the cdr is the heading to be used. The heading
2876 may also be the empty string. The following placeholders can be
2877 used:
2879 %t a time stamp.
2880 %T an active time stamp instead the default inactive one
2881 %d a short-format time stamp.
2882 %D an active short-format time stamp.
2883 %s the new TODO state or time stamp (inactive), in double quotes.
2884 %S the old TODO state or time stamp (inactive), in double quotes.
2885 %u the user name.
2886 %U full user name.
2888 In fact, it is not a good idea to change the `state' entry,
2889 because Agenda Log mode depends on the format of these entries."
2890 :group 'org-todo
2891 :group 'org-progress
2892 :type '(list :greedy t
2893 (cons (const :tag "Heading when closing an item" done) string)
2894 (cons (const :tag
2895 "Heading when changing todo state (todo sequence only)"
2896 state) string)
2897 (cons (const :tag "Heading when just taking a note" note) string)
2898 (cons (const :tag "Heading when rescheduling" reschedule) string)
2899 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2900 (cons (const :tag "Heading when changing deadline" redeadline) string)
2901 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2902 (cons (const :tag "Heading when refiling" refile) string)
2903 (cons (const :tag "Heading when clocking out" clock-out) string)))
2905 (unless (assq 'note org-log-note-headings)
2906 (push '(note . "%t") org-log-note-headings))
2908 (defcustom org-log-into-drawer nil
2909 "Non-nil means insert state change notes and time stamps into a drawer.
2910 When nil, state changes notes will be inserted after the headline and
2911 any scheduling and clock lines, but not inside a drawer.
2913 The value of this variable should be the name of the drawer to use.
2914 LOGBOOK is proposed as the default drawer for this purpose, you can
2915 also set this to a string to define the drawer of your choice.
2917 A value of t is also allowed, representing \"LOGBOOK\".
2919 A value of t or nil can also be set with on a per-file-basis with
2921 #+STARTUP: logdrawer
2922 #+STARTUP: nologdrawer
2924 If this variable is set, `org-log-state-notes-insert-after-drawers'
2925 will be ignored.
2927 You can set the property LOG_INTO_DRAWER to overrule this setting for
2928 a subtree.
2930 Do not check directly this variable in a Lisp program. Call
2931 function `org-log-into-drawer' instead."
2932 :group 'org-todo
2933 :group 'org-progress
2934 :type '(choice
2935 (const :tag "Not into a drawer" nil)
2936 (const :tag "LOGBOOK" t)
2937 (string :tag "Other")))
2939 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2941 (defun org-log-into-drawer ()
2942 "Name of the log drawer, as a string, or nil.
2943 This is the value of `org-log-into-drawer'. However, if the
2944 current entry has or inherits a LOG_INTO_DRAWER property, it will
2945 be used instead of the default value."
2946 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2947 (cond ((equal p "nil") nil)
2948 ((equal p "t") "LOGBOOK")
2949 ((stringp p) p)
2950 (p "LOGBOOK")
2951 ((stringp org-log-into-drawer) org-log-into-drawer)
2952 (org-log-into-drawer "LOGBOOK"))))
2954 (defcustom org-log-state-notes-insert-after-drawers nil
2955 "Non-nil means insert state change notes after any drawers in entry.
2956 Only the drawers that *immediately* follow the headline and the
2957 deadline/scheduled line are skipped.
2958 When nil, insert notes right after the heading and perhaps the line
2959 with deadline/scheduling if present.
2961 This variable will have no effect if `org-log-into-drawer' is
2962 set."
2963 :group 'org-todo
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-states-order-reversed t
2968 "Non-nil means the latest state note will be directly after heading.
2969 When nil, the state change notes will be ordered according to time.
2971 This option can also be set with on a per-file-basis with
2973 #+STARTUP: logstatesreversed
2974 #+STARTUP: nologstatesreversed"
2975 :group 'org-todo
2976 :group 'org-progress
2977 :type 'boolean)
2979 (defcustom org-todo-repeat-to-state nil
2980 "The TODO state to which a repeater should return the repeating task.
2981 By default this is the first task in a TODO sequence, or the previous state
2982 in a TODO_TYP set. But you can specify another task here.
2983 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2984 :group 'org-todo
2985 :version "24.1"
2986 :type '(choice (const :tag "Head of sequence" nil)
2987 (string :tag "Specific state")))
2989 (defcustom org-log-repeat 'time
2990 "Non-nil means record moving through the DONE state when triggering repeat.
2991 An auto-repeating task is immediately switched back to TODO when
2992 marked DONE. If you are not logging state changes (by adding \"@\"
2993 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2994 record a closing note, there will be no record of the task moving
2995 through DONE. This variable forces taking a note anyway.
2997 nil Don't force a record
2998 time Record a time stamp
2999 note Prompt for a note and add it with template `org-log-note-headings'
3001 This option can also be set with on a per-file-basis with
3003 #+STARTUP: nologrepeat
3004 #+STARTUP: logrepeat
3005 #+STARTUP: lognoterepeat
3007 You can have local logging settings for a subtree by setting the LOGGING
3008 property to one or more of these keywords."
3009 :group 'org-todo
3010 :group 'org-progress
3011 :type '(choice
3012 (const :tag "Don't force a record" nil)
3013 (const :tag "Force recording the DONE state" time)
3014 (const :tag "Force recording a note with the DONE state" note)))
3017 (defgroup org-priorities nil
3018 "Priorities in Org-mode."
3019 :tag "Org Priorities"
3020 :group 'org-todo)
3022 (defcustom org-enable-priority-commands t
3023 "Non-nil means priority commands are active.
3024 When nil, these commands will be disabled, so that you never accidentally
3025 set a priority."
3026 :group 'org-priorities
3027 :type 'boolean)
3029 (defcustom org-highest-priority ?A
3030 "The highest priority of TODO items. A character like ?A, ?B etc.
3031 Must have a smaller ASCII number than `org-lowest-priority'."
3032 :group 'org-priorities
3033 :type 'character)
3035 (defcustom org-lowest-priority ?C
3036 "The lowest priority of TODO items. A character like ?A, ?B etc.
3037 Must have a larger ASCII number than `org-highest-priority'."
3038 :group 'org-priorities
3039 :type 'character)
3041 (defcustom org-default-priority ?B
3042 "The default priority of TODO items.
3043 This is the priority an item gets if no explicit priority is given.
3044 When starting to cycle on an empty priority the first step in the cycle
3045 depends on `org-priority-start-cycle-with-default'. The resulting first
3046 step priority must not exceed the range from `org-highest-priority' to
3047 `org-lowest-priority' which means that `org-default-priority' has to be
3048 in this range exclusive or inclusive the range boundaries. Else the
3049 first step refuses to set the default and the second will fall back
3050 to (depending on the command used) the highest or lowest priority."
3051 :group 'org-priorities
3052 :type 'character)
3054 (defcustom org-priority-start-cycle-with-default t
3055 "Non-nil means start with default priority when starting to cycle.
3056 When this is nil, the first step in the cycle will be (depending on the
3057 command used) one higher or lower than the default priority.
3058 See also `org-default-priority'."
3059 :group 'org-priorities
3060 :type 'boolean)
3062 (defcustom org-get-priority-function nil
3063 "Function to extract the priority from a string.
3064 The string is normally the headline. If this is nil Org computes the
3065 priority from the priority cookie like [#A] in the headline. It returns
3066 an integer, increasing by 1000 for each priority level.
3067 The user can set a different function here, which should take a string
3068 as an argument and return the numeric priority."
3069 :group 'org-priorities
3070 :version "24.1"
3071 :type '(choice
3072 (const nil)
3073 (function)))
3075 (defgroup org-time nil
3076 "Options concerning time stamps and deadlines in Org-mode."
3077 :tag "Org Time"
3078 :group 'org)
3080 (defcustom org-time-stamp-rounding-minutes '(0 5)
3081 "Number of minutes to round time stamps to.
3082 \\<org-mode-map>\
3083 These are two values, the first applies when first creating a time stamp.
3084 The second applies when changing it with the commands `S-up' and `S-down'.
3085 When changing the time stamp, this means that it will change in steps
3086 of N minutes, as given by the second value.
3088 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3089 numbers should be factors of 60, so for example 5, 10, 15.
3091 When this is larger than 1, you can still force an exact time stamp by using
3092 a double prefix argument to a time stamp command like \
3093 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3094 and by using a prefix arg to `S-up/down' to specify the exact number
3095 of minutes to shift."
3096 :group 'org-time
3097 :get (lambda (var) ; Make sure both elements are there
3098 (if (integerp (default-value var))
3099 (list (default-value var) 5)
3100 (default-value var)))
3101 :type '(list
3102 (integer :tag "when inserting times")
3103 (integer :tag "when modifying times")))
3105 ;; Normalize old customizations of this variable.
3106 (when (integerp org-time-stamp-rounding-minutes)
3107 (setq org-time-stamp-rounding-minutes
3108 (list org-time-stamp-rounding-minutes
3109 org-time-stamp-rounding-minutes)))
3111 (defcustom org-display-custom-times nil
3112 "Non-nil means overlay custom formats over all time stamps.
3113 The formats are defined through the variable `org-time-stamp-custom-formats'.
3114 To turn this on on a per-file basis, insert anywhere in the file:
3115 #+STARTUP: customtime"
3116 :group 'org-time
3117 :set 'set-default
3118 :type 'sexp)
3119 (make-variable-buffer-local 'org-display-custom-times)
3121 (defcustom org-time-stamp-custom-formats
3122 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3123 "Custom formats for time stamps. See `format-time-string' for the syntax.
3124 These are overlaid over the default ISO format if the variable
3125 `org-display-custom-times' is set. Time like %H:%M should be at the
3126 end of the second format. The custom formats are also honored by export
3127 commands, if custom time display is turned on at the time of export."
3128 :group 'org-time
3129 :type 'sexp)
3131 (defun org-time-stamp-format (&optional long inactive)
3132 "Get the right format for a time string."
3133 (let ((f (if long (cdr org-time-stamp-formats)
3134 (car org-time-stamp-formats))))
3135 (if inactive
3136 (concat "[" (substring f 1 -1) "]")
3137 f)))
3139 (defcustom org-time-clocksum-format
3140 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3141 "The format string used when creating CLOCKSUM lines.
3142 This is also used when Org mode generates a time duration.
3144 The value can be a single format string containing two
3145 %-sequences, which will be filled with the number of hours and
3146 minutes in that order.
3148 Alternatively, the value can be a plist associating any of the
3149 keys :years, :months, :weeks, :days, :hours or :minutes with
3150 format strings. The time duration is formatted using only the
3151 time components that are needed and concatenating the results.
3152 If a time unit in absent, it falls back to the next smallest
3153 unit.
3155 The keys :require-years, :require-months, :require-days,
3156 :require-weeks, :require-hours, :require-minutes are also
3157 meaningful. A non-nil value for these keys indicates that the
3158 corresponding time component should always be included, even if
3159 its value is 0.
3162 For example,
3164 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3165 :require-minutes t)
3167 means durations longer than a day will be expressed in days,
3168 hours and minutes, and durations less than a day will always be
3169 expressed in hours and minutes (even for durations less than an
3170 hour).
3172 The value
3174 (:days \"%dd\" :minutes \"%dm\")
3176 means durations longer than a day will be expressed in days and
3177 minutes, and durations less than a day will be expressed entirely
3178 in minutes (even for durations longer than an hour)."
3179 :group 'org-time
3180 :group 'org-clock
3181 :version "24.4"
3182 :package-version '(Org . "8.0")
3183 :type '(choice (string :tag "Format string")
3184 (set :tag "Plist"
3185 (group :inline t (const :tag "Years" :years)
3186 (string :tag "Format string"))
3187 (group :inline t
3188 (const :tag "Always show years" :require-years)
3189 (const t))
3190 (group :inline t (const :tag "Months" :months)
3191 (string :tag "Format string"))
3192 (group :inline t
3193 (const :tag "Always show months" :require-months)
3194 (const t))
3195 (group :inline t (const :tag "Weeks" :weeks)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show weeks" :require-weeks)
3199 (const t))
3200 (group :inline t (const :tag "Days" :days)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show days" :require-days)
3204 (const t))
3205 (group :inline t (const :tag "Hours" :hours)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show hours" :require-hours)
3209 (const t))
3210 (group :inline t (const :tag "Minutes" :minutes)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show minutes" :require-minutes)
3214 (const t)))))
3216 (defcustom org-time-clocksum-use-fractional nil
3217 "When non-nil, \\[org-clock-display] uses fractional times.
3218 See `org-time-clocksum-format' for more on time clock formats."
3219 :group 'org-time
3220 :group 'org-clock
3221 :version "24.3"
3222 :type 'boolean)
3224 (defcustom org-time-clocksum-use-effort-durations nil
3225 "When non-nil, \\[org-clock-display] uses effort durations.
3226 E.g. by default, one day is considered to be a 8 hours effort,
3227 so a task that has been clocked for 16 hours will be displayed
3228 as during 2 days in the clock display or in the clocktable.
3230 See `org-effort-durations' on how to set effort durations
3231 and `org-time-clocksum-format' for more on time clock formats."
3232 :group 'org-time
3233 :group 'org-clock
3234 :version "24.4"
3235 :package-version '(Org . "8.0")
3236 :type 'boolean)
3238 (defcustom org-time-clocksum-fractional-format "%.2f"
3239 "The format string used when creating CLOCKSUM lines,
3240 or when Org mode generates a time duration, if
3241 `org-time-clocksum-use-fractional' is enabled.
3243 The value can be a single format string containing one
3244 %-sequence, which will be filled with the number of hours as
3245 a float.
3247 Alternatively, the value can be a plist associating any of the
3248 keys :years, :months, :weeks, :days, :hours or :minutes with
3249 a format string. The time duration is formatted using the
3250 largest time unit which gives a non-zero integer part. If all
3251 specified formats have zero integer part, the smallest time unit
3252 is used."
3253 :group 'org-time
3254 :type '(choice (string :tag "Format string")
3255 (set (group :inline t (const :tag "Years" :years)
3256 (string :tag "Format string"))
3257 (group :inline t (const :tag "Months" :months)
3258 (string :tag "Format string"))
3259 (group :inline t (const :tag "Weeks" :weeks)
3260 (string :tag "Format string"))
3261 (group :inline t (const :tag "Days" :days)
3262 (string :tag "Format string"))
3263 (group :inline t (const :tag "Hours" :hours)
3264 (string :tag "Format string"))
3265 (group :inline t (const :tag "Minutes" :minutes)
3266 (string :tag "Format string")))))
3268 (defcustom org-deadline-warning-days 14
3269 "Number of days before expiration during which a deadline becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 When 0 or negative, it means use this number (the absolute value of it)
3272 even if a deadline has a different individual lead time specified.
3274 Custom commands can set this variable in the options section."
3275 :group 'org-time
3276 :group 'org-agenda-daily/weekly
3277 :type 'integer)
3279 (defcustom org-scheduled-delay-days 0
3280 "Number of days before a scheduled item becomes active.
3281 This variable governs the display in sparse trees and in the agenda.
3282 The default value (i.e. 0) means: don't delay scheduled item.
3283 When negative, it means use this number (the absolute value of it)
3284 even if a scheduled item has a different individual delay time
3285 specified.
3287 Custom commands can set this variable in the options section."
3288 :group 'org-time
3289 :group 'org-agenda-daily/weekly
3290 :version "24.4"
3291 :package-version '(Org . "8.0")
3292 :type 'integer)
3294 (defcustom org-read-date-prefer-future t
3295 "Non-nil means assume future for incomplete date input from user.
3296 This affects the following situations:
3297 1. The user gives a month but not a year.
3298 For example, if it is April and you enter \"feb 2\", this will be read
3299 as Feb 2, *next* year. \"May 5\", however, will be this year.
3300 2. The user gives a day, but no month.
3301 For example, if today is the 15th, and you enter \"3\", Org-mode will
3302 read this as the third of *next* month. However, if you enter \"17\",
3303 it will be considered as *this* month.
3305 If you set this variable to the symbol `time', then also the following
3306 will work:
3308 3. If the user gives a time.
3309 If the time is before now, it will be interpreted as tomorrow.
3311 Currently none of this works for ISO week specifications.
3313 When this option is nil, the current day, month and year will always be
3314 used as defaults.
3316 See also `org-agenda-jump-prefer-future'."
3317 :group 'org-time
3318 :type '(choice
3319 (const :tag "Never" nil)
3320 (const :tag "Check month and day" t)
3321 (const :tag "Check month, day, and time" time)))
3323 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3324 "Should the agenda jump command prefer the future for incomplete dates?
3325 The default is to do the same as configured in `org-read-date-prefer-future'.
3326 But you can also set a deviating value here.
3327 This may t or nil, or the symbol `org-read-date-prefer-future'."
3328 :group 'org-agenda
3329 :group 'org-time
3330 :version "24.1"
3331 :type '(choice
3332 (const :tag "Use org-read-date-prefer-future"
3333 org-read-date-prefer-future)
3334 (const :tag "Never" nil)
3335 (const :tag "Always" t)))
3337 (defcustom org-read-date-force-compatible-dates t
3338 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3340 Depending on the system Emacs is running on, certain dates cannot
3341 be represented with the type used internally to represent time.
3342 Dates between 1970-1-1 and 2038-1-1 can always be represented
3343 correctly. Some systems allow for earlier dates, some for later,
3344 some for both. One way to find out it to insert any date into an
3345 Org buffer, putting the cursor on the year and hitting S-up and
3346 S-down to test the range.
3348 When this variable is set to t, the date/time prompt will not let
3349 you specify dates outside the 1970-2037 range, so it is certain that
3350 these dates will work in whatever version of Emacs you are
3351 running, and also that you can move a file from one Emacs implementation
3352 to another. WHenever Org is forcing the year for you, it will display
3353 a message and beep.
3355 When this variable is nil, Org will check if the date is
3356 representable in the specific Emacs implementation you are using.
3357 If not, it will force a year, usually the current year, and beep
3358 to remind you. Currently this setting is not recommended because
3359 the likelihood that you will open your Org files in an Emacs that
3360 has limited date range is not negligible.
3362 A workaround for this problem is to use diary sexp dates for time
3363 stamps outside of this range."
3364 :group 'org-time
3365 :version "24.1"
3366 :type 'boolean)
3368 (defcustom org-read-date-display-live t
3369 "Non-nil means display current interpretation of date prompt live.
3370 This display will be in an overlay, in the minibuffer."
3371 :group 'org-time
3372 :type 'boolean)
3374 (defcustom org-read-date-popup-calendar t
3375 "Non-nil means pop up a calendar when prompting for a date.
3376 In the calendar, the date can be selected with mouse-1. However, the
3377 minibuffer will also be active, and you can simply enter the date as well.
3378 When nil, only the minibuffer will be available."
3379 :group 'org-time
3380 :type 'boolean)
3381 (org-defvaralias 'org-popup-calendar-for-date-prompt
3382 'org-read-date-popup-calendar)
3384 (make-obsolete-variable
3385 'org-read-date-minibuffer-setup-hook
3386 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3387 (defcustom org-read-date-minibuffer-setup-hook nil
3388 "Hook to be used to set up keys for the date/time interface.
3389 Add key definitions to `minibuffer-local-map', which will be a
3390 temporary copy.
3392 WARNING: This option is obsolete, you should use
3393 `org-read-date-minibuffer-local-map' to set up keys."
3394 :group 'org-time
3395 :type 'hook)
3397 (defcustom org-extend-today-until 0
3398 "The hour when your day really ends. Must be an integer.
3399 This has influence for the following applications:
3400 - When switching the agenda to \"today\". It it is still earlier than
3401 the time given here, the day recognized as TODAY is actually yesterday.
3402 - When a date is read from the user and it is still before the time given
3403 here, the current date and time will be assumed to be yesterday, 23:59.
3404 Also, timestamps inserted in capture templates follow this rule.
3406 IMPORTANT: This is a feature whose implementation is and likely will
3407 remain incomplete. Really, it is only here because past midnight seems to
3408 be the favorite working time of John Wiegley :-)"
3409 :group 'org-time
3410 :type 'integer)
3412 (defcustom org-use-effective-time nil
3413 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3414 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3415 \"effective time\" of any timestamps between midnight and 8am will be
3416 23:59 of the previous day."
3417 :group 'org-time
3418 :version "24.1"
3419 :type 'boolean)
3421 (defcustom org-use-last-clock-out-time-as-effective-time nil
3422 "When non-nil, use the last clock out time for `org-todo'.
3423 Note that this option has precedence over the combined use of
3424 `org-use-effective-time' and `org-extend-today-until'."
3425 :group 'org-time
3426 :version "24.4"
3427 :package-version '(Org . "8.0")
3428 :type 'boolean)
3430 (defcustom org-edit-timestamp-down-means-later nil
3431 "Non-nil means S-down will increase the time in a time stamp.
3432 When nil, S-up will increase."
3433 :group 'org-time
3434 :type 'boolean)
3436 (defcustom org-calendar-follow-timestamp-change t
3437 "Non-nil means make the calendar window follow timestamp changes.
3438 When a timestamp is modified and the calendar window is visible, it will be
3439 moved to the new date."
3440 :group 'org-time
3441 :type 'boolean)
3443 (defgroup org-tags nil
3444 "Options concerning tags in Org-mode."
3445 :tag "Org Tags"
3446 :group 'org)
3448 (defcustom org-tag-alist nil
3449 "List of tags allowed in Org-mode files.
3450 When this list is nil, Org-mode will base TAG input on what is already in the
3451 buffer.
3452 The value of this variable is an alist, the car of each entry must be a
3453 keyword as a string, the cdr may be a character that is used to select
3454 that tag through the fast-tag-selection interface.
3455 See the manual for details."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (list :tag "Start radio group"
3462 (const :startgroup)
3463 (option (string :tag "Group description")))
3464 (list :tag "Start tag group, non distinct"
3465 (const :startgrouptag)
3466 (option (string :tag "Group description")))
3467 (list :tag "Group tags delimiter"
3468 (const :grouptags))
3469 (list :tag "End radio group"
3470 (const :endgroup)
3471 (option (string :tag "Group description")))
3472 (list :tag "End tag group, non distinct"
3473 (const :endgrouptag)
3474 (option (string :tag "Group description")))
3475 (const :tag "New line" (:newline)))))
3477 (defcustom org-tag-persistent-alist nil
3478 "List of tags that will always appear in all Org-mode files.
3479 This is in addition to any in buffer settings or customizations
3480 of `org-tag-alist'.
3481 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3482 The value of this variable is an alist, the car of each entry must be a
3483 keyword as a string, the cdr may be a character that is used to select
3484 that tag through the fast-tag-selection interface.
3485 See the manual for details.
3486 To disable these tags on a per-file basis, insert anywhere in the file:
3487 #+STARTUP: noptag"
3488 :group 'org-tags
3489 :type '(repeat
3490 (choice
3491 (cons (string :tag "Tag name")
3492 (character :tag "Access char"))
3493 (const :tag "Start radio group" (:startgroup))
3494 (const :tag "Group tags delimiter" (:grouptags))
3495 (const :tag "End radio group" (:endgroup))
3496 (const :tag "New line" (:newline)))))
3498 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3499 "If non-nil, always offer completion for all tags of all agenda files.
3500 Instead of customizing this variable directly, you might want to
3501 set it locally for capture buffers, because there no list of
3502 tags in that file can be created dynamically (there are none).
3504 (add-hook \\='org-capture-mode-hook
3505 (lambda ()
3506 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3507 :group 'org-tags
3508 :version "24.1"
3509 :type 'boolean)
3511 (defvar org-file-tags nil
3512 "List of tags that can be inherited by all entries in the file.
3513 The tags will be inherited if the variable `org-use-tag-inheritance'
3514 says they should be.
3515 This variable is populated from #+FILETAGS lines.")
3517 (defcustom org-use-fast-tag-selection 'auto
3518 "Non-nil means use fast tag selection scheme.
3519 This is a special interface to select and deselect tags with single keys.
3520 When nil, fast selection is never used.
3521 When the symbol `auto', fast selection is used if and only if selection
3522 characters for tags have been configured, either through the variable
3523 `org-tag-alist' or through a #+TAGS line in the buffer.
3524 When t, fast selection is always used and selection keys are assigned
3525 automatically if necessary."
3526 :group 'org-tags
3527 :type '(choice
3528 (const :tag "Always" t)
3529 (const :tag "Never" nil)
3530 (const :tag "When selection characters are configured" auto)))
3532 (defcustom org-fast-tag-selection-single-key nil
3533 "Non-nil means fast tag selection exits after first change.
3534 When nil, you have to press RET to exit it.
3535 During fast tag selection, you can toggle this flag with `C-c'.
3536 This variable can also have the value `expert'. In this case, the window
3537 displaying the tags menu is not even shown, until you press C-c again."
3538 :group 'org-tags
3539 :type '(choice
3540 (const :tag "No" nil)
3541 (const :tag "Yes" t)
3542 (const :tag "Expert" expert)))
3544 (defvar org-fast-tag-selection-include-todo nil
3545 "Non-nil means fast tags selection interface will also offer TODO states.
3546 This is an undocumented feature, you should not rely on it.")
3548 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3549 "The column to which tags should be indented in a headline.
3550 If this number is positive, it specifies the column. If it is negative,
3551 it means that the tags should be flushright to that column. For example,
3552 -80 works well for a normal 80 character screen.
3553 When 0, place tags directly after headline text, with only one space in
3554 between."
3555 :group 'org-tags
3556 :type 'integer)
3558 (defcustom org-auto-align-tags t
3559 "Non-nil keeps tags aligned when modifying headlines.
3560 Some operations (i.e. demoting) change the length of a headline and
3561 therefore shift the tags around. With this option turned on, after
3562 each such operation the tags are again aligned to `org-tags-column'."
3563 :group 'org-tags
3564 :type 'boolean)
3566 (defcustom org-use-tag-inheritance t
3567 "Non-nil means tags in levels apply also for sublevels.
3568 When nil, only the tags directly given in a specific line apply there.
3569 This may also be a list of tags that should be inherited, or a regexp that
3570 matches tags that should be inherited. Additional control is possible
3571 with the variable `org-tags-exclude-from-inheritance' which gives an
3572 explicit list of tags to be excluded from inheritance, even if the value of
3573 `org-use-tag-inheritance' would select it for inheritance.
3575 If this option is t, a match early-on in a tree can lead to a large
3576 number of matches in the subtree when constructing the agenda or creating
3577 a sparse tree. If you only want to see the first match in a tree during
3578 a search, check out the variable `org-tags-match-list-sublevels'."
3579 :group 'org-tags
3580 :type '(choice
3581 (const :tag "Not" nil)
3582 (const :tag "Always" t)
3583 (repeat :tag "Specific tags" (string :tag "Tag"))
3584 (regexp :tag "Tags matched by regexp")))
3586 (defcustom org-tags-exclude-from-inheritance nil
3587 "List of tags that should never be inherited.
3588 This is a way to exclude a few tags from inheritance. For way to do
3589 the opposite, to actively allow inheritance for selected tags,
3590 see the variable `org-use-tag-inheritance'."
3591 :group 'org-tags
3592 :type '(repeat (string :tag "Tag")))
3594 (defun org-tag-inherit-p (tag)
3595 "Check if TAG is one that should be inherited."
3596 (cond
3597 ((member tag org-tags-exclude-from-inheritance) nil)
3598 ((eq org-use-tag-inheritance t) t)
3599 ((not org-use-tag-inheritance) nil)
3600 ((stringp org-use-tag-inheritance)
3601 (string-match org-use-tag-inheritance tag))
3602 ((listp org-use-tag-inheritance)
3603 (member tag org-use-tag-inheritance))
3604 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3606 (defcustom org-tags-match-list-sublevels t
3607 "Non-nil means list also sublevels of headlines matching a search.
3608 This variable applies to tags/property searches, and also to stuck
3609 projects because this search is based on a tags match as well.
3611 When set to the symbol `indented', sublevels are indented with
3612 leading dots.
3614 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3615 the sublevels of a headline matching a tag search often also match
3616 the same search. Listing all of them can create very long lists.
3617 Setting this variable to nil causes subtrees of a match to be skipped.
3619 This variable is semi-obsolete and probably should always be true. It
3620 is better to limit inheritance to certain tags using the variables
3621 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3622 :group 'org-tags
3623 :type '(choice
3624 (const :tag "No, don't list them" nil)
3625 (const :tag "Yes, do list them" t)
3626 (const :tag "List them, indented with leading dots" indented)))
3628 (defcustom org-tags-sort-function nil
3629 "When set, tags are sorted using this function as a comparator."
3630 :group 'org-tags
3631 :type '(choice
3632 (const :tag "No sorting" nil)
3633 (const :tag "Alphabetical" string<)
3634 (const :tag "Reverse alphabetical" string>)
3635 (function :tag "Custom function" nil)))
3637 (defvar org-tags-history nil
3638 "History of minibuffer reads for tags.")
3639 (defvar org-last-tags-completion-table nil
3640 "The last used completion table for tags.")
3641 (defvar org-after-tags-change-hook nil
3642 "Hook that is run after the tags in a line have changed.")
3644 (defgroup org-properties nil
3645 "Options concerning properties in Org-mode."
3646 :tag "Org Properties"
3647 :group 'org)
3649 (defcustom org-property-format "%-10s %s"
3650 "How property key/value pairs should be formatted by `indent-line'.
3651 When `indent-line' hits a property definition, it will format the line
3652 according to this format, mainly to make sure that the values are
3653 lined-up with respect to each other."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-properties-postprocess-alist nil
3658 "Alist of properties and functions to adjust inserted values.
3659 Elements of this alist must be of the form
3661 ([string] [function])
3663 where [string] must be a property name and [function] must be a
3664 lambda expression: this lambda expression must take one argument,
3665 the value to adjust, and return the new value as a string.
3667 For example, this element will allow the property \"Remaining\"
3668 to be updated wrt the relation between the \"Effort\" property
3669 and the clock summary:
3671 ((\"Remaining\" (lambda(value)
3672 (let ((clocksum (org-clock-sum-current-item))
3673 (effort (org-duration-string-to-minutes
3674 (org-entry-get (point) \"Effort\"))))
3675 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3676 :group 'org-properties
3677 :version "24.1"
3678 :type '(alist :key-type (string :tag "Property")
3679 :value-type (function :tag "Function")))
3681 (defcustom org-use-property-inheritance nil
3682 "Non-nil means properties apply also for sublevels.
3684 This setting is chiefly used during property searches. Turning it on can
3685 cause significant overhead when doing a search, which is why it is not
3686 on by default.
3688 When nil, only the properties directly given in the current entry count.
3689 When t, every property is inherited. The value may also be a list of
3690 properties that should have inheritance, or a regular expression matching
3691 properties that should be inherited.
3693 However, note that some special properties use inheritance under special
3694 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3695 and the properties ending in \"_ALL\" when they are used as descriptor
3696 for valid values of a property.
3698 Note for programmers:
3699 When querying an entry with `org-entry-get', you can control if inheritance
3700 should be used. By default, `org-entry-get' looks only at the local
3701 properties. You can request inheritance by setting the inherit argument
3702 to t (to force inheritance) or to `selective' (to respect the setting
3703 in this variable)."
3704 :group 'org-properties
3705 :type '(choice
3706 (const :tag "Not" nil)
3707 (const :tag "Always" t)
3708 (repeat :tag "Specific properties" (string :tag "Property"))
3709 (regexp :tag "Properties matched by regexp")))
3711 (defun org-property-inherit-p (property)
3712 "Check if PROPERTY is one that should be inherited."
3713 (cond
3714 ((eq org-use-property-inheritance t) t)
3715 ((not org-use-property-inheritance) nil)
3716 ((stringp org-use-property-inheritance)
3717 (string-match org-use-property-inheritance property))
3718 ((listp org-use-property-inheritance)
3719 (member property org-use-property-inheritance))
3720 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3722 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3723 "The default column format, if no other format has been defined.
3724 This variable can be set on the per-file basis by inserting a line
3726 #+COLUMNS: %25ITEM ....."
3727 :group 'org-properties
3728 :type 'string)
3730 (defcustom org-columns-ellipses ".."
3731 "The ellipses to be used when a field in column view is truncated.
3732 When this is the empty string, as many characters as possible are shown,
3733 but then there will be no visual indication that the field has been truncated.
3734 When this is a string of length N, the last N characters of a truncated
3735 field are replaced by this string. If the column is narrower than the
3736 ellipses string, only part of the ellipses string will be shown."
3737 :group 'org-properties
3738 :type 'string)
3740 (defcustom org-columns-modify-value-for-display-function nil
3741 "Function that modifies values for display in column view.
3742 For example, it can be used to cut out a certain part from a time stamp.
3743 The function must take 2 arguments:
3745 column-title The title of the column (*not* the property name)
3746 value The value that should be modified.
3748 The function should return the value that should be displayed,
3749 or nil if the normal value should be used."
3750 :group 'org-properties
3751 :type '(choice (const nil) (function)))
3753 (defconst org-global-properties-fixed
3754 '(("VISIBILITY_ALL" . "folded children content all")
3755 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3756 "List of property/value pairs that can be inherited by any entry.
3758 These are fixed values, for the preset properties. The user variable
3759 that can be used to add to this list is `org-global-properties'.
3761 The entries in this list are cons cells where the car is a property
3762 name and cdr is a string with the value. If the value represents
3763 multiple items like an \"_ALL\" property, separate the items by
3764 spaces.")
3766 (defcustom org-global-properties nil
3767 "List of property/value pairs that can be inherited by any entry.
3769 This list will be combined with the constant `org-global-properties-fixed'.
3771 The entries in this list are cons cells where the car is a property
3772 name and cdr is a string with the value.
3774 You can set buffer-local values for the same purpose in the variable
3775 `org-file-properties' this by adding lines like
3777 #+PROPERTY: NAME VALUE"
3778 :group 'org-properties
3779 :type '(repeat
3780 (cons (string :tag "Property")
3781 (string :tag "Value"))))
3783 (defvar-local org-file-properties nil
3784 "List of property/value pairs that can be inherited by any entry.
3785 Valid for the current buffer.
3786 This variable is populated from #+PROPERTY lines.")
3788 (defgroup org-agenda nil
3789 "Options concerning agenda views in Org-mode."
3790 :tag "Org Agenda"
3791 :group 'org)
3793 (defvar-local org-category nil
3794 "Variable used by org files to set a category for agenda display.
3795 Such files should use a file variable to set it, for example
3797 # -*- mode: org; org-category: \"ELisp\"
3799 or contain a special line
3801 #+CATEGORY: ELisp
3803 If the file does not specify a category, then file's base name
3804 is used instead.")
3805 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3807 (defcustom org-agenda-files nil
3808 "The files to be used for agenda display.
3809 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3810 \\[org-remove-file]. You can also use customize to edit the list.
3812 If an entry is a directory, all files in that directory that are matched by
3813 `org-agenda-file-regexp' will be part of the file list.
3815 If the value of the variable is not a list but a single file name, then
3816 the list of agenda files is actually stored and maintained in that file, one
3817 agenda file per line. In this file paths can be given relative to
3818 `org-directory'. Tilde expansion and environment variable substitution
3819 are also made."
3820 :group 'org-agenda
3821 :type '(choice
3822 (repeat :tag "List of files and directories" file)
3823 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3825 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3826 "Regular expression to match files for `org-agenda-files'.
3827 If any element in the list in that variable contains a directory instead
3828 of a normal file, all files in that directory that are matched by this
3829 regular expression will be included."
3830 :group 'org-agenda
3831 :type 'regexp)
3833 (defcustom org-agenda-text-search-extra-files nil
3834 "List of extra files to be searched by text search commands.
3835 These files will be searched in addition to the agenda files by the
3836 commands `org-search-view' (`\\[org-agenda] s') \
3837 and `org-occur-in-agenda-files'.
3838 Note that these files will only be searched for text search commands,
3839 not for the other agenda views like todo lists, tag searches or the weekly
3840 agenda. This variable is intended to list notes and possibly archive files
3841 that should also be searched by these two commands.
3842 In fact, if the first element in the list is the symbol `agenda-archives',
3843 then all archive files of all agenda files will be added to the search
3844 scope."
3845 :group 'org-agenda
3846 :type '(set :greedy t
3847 (const :tag "Agenda Archives" agenda-archives)
3848 (repeat :inline t (file))))
3850 (org-defvaralias 'org-agenda-multi-occur-extra-files
3851 'org-agenda-text-search-extra-files)
3853 (defcustom org-agenda-skip-unavailable-files nil
3854 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3855 A nil value means to remove them, after a query, from the list."
3856 :group 'org-agenda
3857 :type 'boolean)
3859 (defcustom org-calendar-to-agenda-key [?c]
3860 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3861 The command `org-calendar-goto-agenda' will be bound to this key. The
3862 default is the character `c' because then `c' can be used to switch back and
3863 forth between agenda and calendar."
3864 :group 'org-agenda
3865 :type 'sexp)
3867 (defcustom org-calendar-insert-diary-entry-key [?i]
3868 "The key to be installed in `calendar-mode-map' for adding diary entries.
3869 This option is irrelevant until `org-agenda-diary-file' has been configured
3870 to point to an Org-mode file. When that is the case, the command
3871 `org-agenda-diary-entry' will be bound to the key given here, by default
3872 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3873 if you want to continue doing this, you need to change this to a different
3874 key."
3875 :group 'org-agenda
3876 :type 'sexp)
3878 (defcustom org-agenda-diary-file 'diary-file
3879 "File to which to add new entries with the `i' key in agenda and calendar.
3880 When this is the symbol `diary-file', the functionality in the Emacs
3881 calendar will be used to add entries to the `diary-file'. But when this
3882 points to a file, `org-agenda-diary-entry' will be used instead."
3883 :group 'org-agenda
3884 :type '(choice
3885 (const :tag "The standard Emacs diary file" diary-file)
3886 (file :tag "Special Org file diary entries")))
3888 (eval-after-load "calendar"
3889 '(progn
3890 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3891 'org-calendar-goto-agenda)
3892 (add-hook 'calendar-mode-hook
3893 (lambda ()
3894 (unless (eq org-agenda-diary-file 'diary-file)
3895 (define-key calendar-mode-map
3896 org-calendar-insert-diary-entry-key
3897 'org-agenda-diary-entry))))))
3899 (defgroup org-latex nil
3900 "Options for embedding LaTeX code into Org-mode."
3901 :tag "Org LaTeX"
3902 :group 'org)
3904 (defcustom org-format-latex-options
3905 '(:foreground default :background default :scale 1.0
3906 :html-foreground "Black" :html-background "Transparent"
3907 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3908 "Options for creating images from LaTeX fragments.
3909 This is a property list with the following properties:
3910 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3911 `default' means use the foreground of the default face.
3912 `auto' means use the foreground from the text face.
3913 :background the background color, or \"Transparent\".
3914 `default' means use the background of the default face.
3915 `auto' means use the background from the text face.
3916 :scale a scaling factor for the size of the images, to get more pixels
3917 :html-foreground, :html-background, :html-scale
3918 the same numbers for HTML export.
3919 :matchers a list indicating which matchers should be used to
3920 find LaTeX fragments. Valid members of this list are:
3921 \"begin\" find environments
3922 \"$1\" find single characters surrounded by $.$
3923 \"$\" find math expressions surrounded by $...$
3924 \"$$\" find math expressions surrounded by $$....$$
3925 \"\\(\" find math expressions surrounded by \\(...\\)
3926 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3927 :group 'org-latex
3928 :type 'plist)
3930 (defcustom org-format-latex-signal-error t
3931 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3932 When nil, just push out a message."
3933 :group 'org-latex
3934 :version "24.1"
3935 :type 'boolean)
3937 (defcustom org-latex-to-mathml-jar-file nil
3938 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3939 Use this to specify additional executable file say a jar file.
3941 When using MathToWeb as the converter, specify the full-path to
3942 your mathtoweb.jar file."
3943 :group 'org-latex
3944 :version "24.1"
3945 :type '(choice
3946 (const :tag "None" nil)
3947 (file :tag "JAR file" :must-match t)))
3949 (defcustom org-latex-to-mathml-convert-command nil
3950 "Command to convert LaTeX fragments to MathML.
3951 Replace format-specifiers in the command as noted below and use
3952 `shell-command' to convert LaTeX to MathML.
3953 %j: Executable file in fully expanded form as specified by
3954 `org-latex-to-mathml-jar-file'.
3955 %I: Input LaTeX file in fully expanded form.
3956 %i: The latex fragment to be converted.
3957 %o: Output MathML file.
3959 This command is used by `org-create-math-formula'.
3961 When using MathToWeb as the converter, set this option to
3962 \"java -jar %j -unicode -force -df %o %I\".
3964 When using LaTeXML set this option to
3965 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3966 :group 'org-latex
3967 :version "24.1"
3968 :type '(choice
3969 (const :tag "None" nil)
3970 (string :tag "\nShell command")))
3972 (defcustom org-latex-create-formula-image-program 'dvipng
3973 "Program to convert LaTeX fragments with.
3975 dvipng Process the LaTeX fragments to dvi file, then convert
3976 dvi files to png files using dvipng.
3977 This will also include processing of non-math environments.
3978 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3979 to convert pdf files to png files"
3980 :group 'org-latex
3981 :version "24.1"
3982 :type '(choice
3983 (const :tag "dvipng" dvipng)
3984 (const :tag "imagemagick" imagemagick)))
3986 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3987 "Path to store latex preview images.
3988 A relative path here creates many directories relative to the
3989 processed org files paths. An absolute path puts all preview
3990 images at the same place."
3991 :group 'org-latex
3992 :version "24.3"
3993 :type 'string)
3995 (defun org-format-latex-mathml-available-p ()
3996 "Return t if `org-latex-to-mathml-convert-command' is usable."
3997 (save-match-data
3998 (when (and (boundp 'org-latex-to-mathml-convert-command)
3999 org-latex-to-mathml-convert-command)
4000 (let ((executable (car (split-string
4001 org-latex-to-mathml-convert-command))))
4002 (when (executable-find executable)
4003 (if (string-match
4004 "%j" org-latex-to-mathml-convert-command)
4005 (file-readable-p org-latex-to-mathml-jar-file)
4006 t))))))
4008 (defcustom org-format-latex-header "\\documentclass{article}
4009 \\usepackage[usenames]{color}
4010 \[PACKAGES]
4011 \[DEFAULT-PACKAGES]
4012 \\pagestyle{empty} % do not remove
4013 % The settings below are copied from fullpage.sty
4014 \\setlength{\\textwidth}{\\paperwidth}
4015 \\addtolength{\\textwidth}{-3cm}
4016 \\setlength{\\oddsidemargin}{1.5cm}
4017 \\addtolength{\\oddsidemargin}{-2.54cm}
4018 \\setlength{\\evensidemargin}{\\oddsidemargin}
4019 \\setlength{\\textheight}{\\paperheight}
4020 \\addtolength{\\textheight}{-\\headheight}
4021 \\addtolength{\\textheight}{-\\headsep}
4022 \\addtolength{\\textheight}{-\\footskip}
4023 \\addtolength{\\textheight}{-3cm}
4024 \\setlength{\\topmargin}{1.5cm}
4025 \\addtolength{\\topmargin}{-2.54cm}"
4026 "The document header used for processing LaTeX fragments.
4027 It is imperative that this header make sure that no page number
4028 appears on the page. The package defined in the variables
4029 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4030 will either replace the placeholder \"[PACKAGES]\" in this
4031 header, or they will be appended."
4032 :group 'org-latex
4033 :type 'string)
4035 (defun org-set-packages-alist (var val)
4036 "Set the packages alist and make sure it has 3 elements per entry."
4037 (set var (mapcar (lambda (x)
4038 (if (and (consp x) (= (length x) 2))
4039 (list (car x) (nth 1 x) t)
4041 val)))
4043 (defun org-get-packages-alist (var)
4044 "Get the packages alist and make sure it has 3 elements per entry."
4045 (mapcar (lambda (x)
4046 (if (and (consp x) (= (length x) 2))
4047 (list (car x) (nth 1 x) t)
4049 (default-value var)))
4051 (defcustom org-latex-default-packages-alist
4052 '(("AUTO" "inputenc" t ("pdflatex"))
4053 ("T1" "fontenc" t ("pdflatex"))
4054 ("" "graphicx" t)
4055 ("" "grffile" t)
4056 ("" "longtable" nil)
4057 ("" "wrapfig" nil)
4058 ("" "rotating" nil)
4059 ("normalem" "ulem" t)
4060 ("" "amsmath" t)
4061 ("" "textcomp" t)
4062 ("" "amssymb" t)
4063 ("" "capt-of" nil)
4064 ("" "hyperref" nil))
4065 "Alist of default packages to be inserted in the header.
4067 Change this only if one of the packages here causes an
4068 incompatibility with another package you are using.
4070 The packages in this list are needed by one part or another of
4071 Org mode to function properly:
4073 - inputenc, fontenc: for basic font and character selection
4074 - graphicx: for including images
4075 - grffile: allow periods and spaces in graphics file names
4076 - longtable: For multipage tables
4077 - wrapfig: for figure placement
4078 - rotating: for sideways figures and tables
4079 - ulem: for underline and strike-through
4080 - amsmath: for subscript and superscript and math environments
4081 - textcomp, amssymb: for various symbols used
4082 for interpreting the entities in `org-entities'. You can skip
4083 some of these packages if you don't use any of their symbols.
4084 - capt-of: for captions outside of floats
4085 - hyperref: for cross references
4087 Therefore you should not modify this variable unless you know
4088 what you are doing. The one reason to change it anyway is that
4089 you might be loading some other package that conflicts with one
4090 of the default packages. Each element is either a cell or
4091 a string.
4093 A cell is of the format
4095 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4097 If SNIPPET-FLAG is non-nil, the package also needs to be included
4098 when compiling LaTeX snippets into images for inclusion into
4099 non-LaTeX output. COMPILERS is a list of compilers that should
4100 include the package, see `org-latex-compiler'. If the document
4101 compiler is not in the list, and the list is non-nil, the package
4102 will not be inserted in the final document.
4104 A string will be inserted as-is in the header of the document."
4105 :group 'org-latex
4106 :group 'org-export-latex
4107 :set 'org-set-packages-alist
4108 :get 'org-get-packages-alist
4109 :version "25.1"
4110 :package-version '(Org . "8.3")
4111 :type '(repeat
4112 (choice
4113 (list :tag "options/package pair"
4114 (string :tag "options")
4115 (string :tag "package")
4116 (boolean :tag "Snippet"))
4117 (string :tag "A line of LaTeX"))))
4119 (defcustom org-latex-packages-alist nil
4120 "Alist of packages to be inserted in every LaTeX header.
4122 These will be inserted after `org-latex-default-packages-alist'.
4123 Each element is either a cell or a string.
4125 A cell is of the format:
4127 (\"options\" \"package\" SNIPPET-FLAG)
4129 SNIPPET-FLAG, when non-nil, indicates that this package is also
4130 needed when turning LaTeX snippets into images for inclusion into
4131 non-LaTeX output.
4133 A string will be inserted as-is in the header of the document.
4135 Make sure that you only list packages here which:
4137 - you want in every file;
4138 - do not conflict with the setup in `org-format-latex-header';
4139 - do not conflict with the default packages in
4140 `org-latex-default-packages-alist'."
4141 :group 'org-latex
4142 :group 'org-export-latex
4143 :set 'org-set-packages-alist
4144 :get 'org-get-packages-alist
4145 :type '(repeat
4146 (choice
4147 (list :tag "options/package pair"
4148 (string :tag "options")
4149 (string :tag "package")
4150 (boolean :tag "Snippet"))
4151 (string :tag "A line of LaTeX"))))
4153 (defgroup org-appearance nil
4154 "Settings for Org-mode appearance."
4155 :tag "Org Appearance"
4156 :group 'org)
4158 (defcustom org-level-color-stars-only nil
4159 "Non-nil means fontify only the stars in each headline.
4160 When nil, the entire headline is fontified.
4161 Changing it requires restart of `font-lock-mode' to become effective
4162 also in regions already fontified."
4163 :group 'org-appearance
4164 :type 'boolean)
4166 (defcustom org-hide-leading-stars nil
4167 "Non-nil means hide the first N-1 stars in a headline.
4168 This works by using the face `org-hide' for these stars. This
4169 face is white for a light background, and black for a dark
4170 background. You may have to customize the face `org-hide' to
4171 make this work.
4172 Changing it requires restart of `font-lock-mode' to become effective
4173 also in regions already fontified.
4174 You may also set this on a per-file basis by adding one of the following
4175 lines to the buffer:
4177 #+STARTUP: hidestars
4178 #+STARTUP: showstars"
4179 :group 'org-appearance
4180 :type 'boolean)
4182 (defcustom org-hidden-keywords nil
4183 "List of symbols corresponding to keywords to be hidden the org buffer.
4184 For example, a value \\='(title) for this list will make the document's title
4185 appear in the buffer without the initial #+TITLE: keyword."
4186 :group 'org-appearance
4187 :version "24.1"
4188 :type '(set (const :tag "#+AUTHOR" author)
4189 (const :tag "#+DATE" date)
4190 (const :tag "#+EMAIL" email)
4191 (const :tag "#+TITLE" title)))
4193 (defcustom org-custom-properties nil
4194 "List of properties (as strings) with a special meaning.
4195 The default use of these custom properties is to let the user
4196 hide them with `org-toggle-custom-properties-visibility'."
4197 :group 'org-properties
4198 :group 'org-appearance
4199 :version "24.3"
4200 :type '(repeat (string :tag "Property Name")))
4202 (defcustom org-fontify-done-headline nil
4203 "Non-nil means change the face of a headline if it is marked DONE.
4204 Normally, only the TODO/DONE keyword indicates the state of a headline.
4205 When this is non-nil, the headline after the keyword is set to the
4206 `org-headline-done' as an additional indication."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-fontify-emphasized-text t
4211 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4212 Changing this variable requires a restart of Emacs to take effect."
4213 :group 'org-appearance
4214 :type 'boolean)
4216 (defcustom org-fontify-whole-heading-line nil
4217 "Non-nil means fontify the whole line for headings.
4218 This is useful when setting a background color for the
4219 org-level-* faces."
4220 :group 'org-appearance
4221 :type 'boolean)
4223 (defcustom org-highlight-latex-and-related nil
4224 "Non-nil means highlight LaTeX related syntax in the buffer.
4225 When non nil, the value should be a list containing any of the
4226 following symbols:
4227 `latex' Highlight LaTeX snippets and environments.
4228 `script' Highlight subscript and superscript.
4229 `entities' Highlight entities."
4230 :group 'org-appearance
4231 :version "24.4"
4232 :package-version '(Org . "8.0")
4233 :type '(choice
4234 (const :tag "No highlighting" nil)
4235 (set :greedy t :tag "Highlight"
4236 (const :tag "LaTeX snippets and environments" latex)
4237 (const :tag "Subscript and superscript" script)
4238 (const :tag "Entities" entities))))
4240 (defcustom org-hide-emphasis-markers nil
4241 "Non-nil mean font-lock should hide the emphasis marker characters."
4242 :group 'org-appearance
4243 :type 'boolean)
4245 (defcustom org-hide-macro-markers nil
4246 "Non-nil mean font-lock should hide the brackets marking macro calls."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-pretty-entities nil
4251 "Non-nil means show entities as UTF8 characters.
4252 When nil, the \\name form remains in the buffer."
4253 :group 'org-appearance
4254 :version "24.1"
4255 :type 'boolean)
4257 (defcustom org-pretty-entities-include-sub-superscripts t
4258 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4259 :group 'org-appearance
4260 :version "24.1"
4261 :type 'boolean)
4263 (defvar org-emph-re nil
4264 "Regular expression for matching emphasis.
4265 After a match, the match groups contain these elements:
4266 0 The match of the full regular expression, including the characters
4267 before and after the proper match
4268 1 The character before the proper match, or empty at beginning of line
4269 2 The proper match, including the leading and trailing markers
4270 3 The leading marker like * or /, indicating the type of highlighting
4271 4 The text between the emphasis markers, not including the markers
4272 5 The character after the match, empty at the end of a line")
4273 (defvar org-verbatim-re nil
4274 "Regular expression for matching verbatim text.")
4275 (defvar org-emphasis-regexp-components) ; defined just below
4276 (defvar org-emphasis-alist) ; defined just below
4277 (defun org-set-emph-re (var val)
4278 "Set variable and compute the emphasis regular expression."
4279 (set var val)
4280 (when (and (boundp 'org-emphasis-alist)
4281 (boundp 'org-emphasis-regexp-components)
4282 org-emphasis-alist org-emphasis-regexp-components)
4283 (let* ((e org-emphasis-regexp-components)
4284 (pre (car e))
4285 (post (nth 1 e))
4286 (border (nth 2 e))
4287 (body (nth 3 e))
4288 (nl (nth 4 e))
4289 (body1 (concat body "*?"))
4290 (markers (mapconcat 'car org-emphasis-alist ""))
4291 (vmarkers (mapconcat
4292 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4293 org-emphasis-alist "")))
4294 ;; make sure special characters appear at the right position in the class
4295 (if (string-match "\\^" markers)
4296 (setq markers (concat (replace-match "" t t markers) "^")))
4297 (if (string-match "-" markers)
4298 (setq markers (concat (replace-match "" t t markers) "-")))
4299 (if (string-match "\\^" vmarkers)
4300 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4301 (if (string-match "-" vmarkers)
4302 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4303 (if (> nl 0)
4304 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4305 (int-to-string nl) "\\}")))
4306 ;; Make the regexp
4307 (setq org-emph-re
4308 (concat "\\([" pre "]\\|^\\)"
4309 "\\("
4310 "\\([" markers "]\\)"
4311 "\\("
4312 "[^" border "]\\|"
4313 "[^" border "]"
4314 body1
4315 "[^" border "]"
4316 "\\)"
4317 "\\3\\)"
4318 "\\([" post "]\\|$\\)"))
4319 (setq org-verbatim-re
4320 (concat "\\([" pre "]\\|^\\)"
4321 "\\("
4322 "\\([" vmarkers "]\\)"
4323 "\\("
4324 "[^" border "]\\|"
4325 "[^" border "]"
4326 body1
4327 "[^" border "]"
4328 "\\)"
4329 "\\3\\)"
4330 "\\([" post "]\\|$\\)")))))
4332 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4333 ;; set this option proved cumbersome. See this message/thread:
4334 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4335 (defvar org-emphasis-regexp-components
4336 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4337 "Components used to build the regular expression for emphasis.
4338 This is a list with five entries. Terminology: In an emphasis string
4339 like \" *strong word* \", we call the initial space PREMATCH, the final
4340 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4341 and \"trong wor\" is the body. The different components in this variable
4342 specify what is allowed/forbidden in each part:
4344 pre Chars allowed as prematch. Beginning of line will be allowed too.
4345 post Chars allowed as postmatch. End of line will be allowed too.
4346 border The chars *forbidden* as border characters.
4347 body-regexp A regexp like \".\" to match a body character. Don't use
4348 non-shy groups here, and don't allow newline here.
4349 newline The maximum number of newlines allowed in an emphasis exp.
4351 You need to reload Org or to restart Emacs after customizing this.")
4353 (defcustom org-emphasis-alist
4354 `(("*" bold)
4355 ("/" italic)
4356 ("_" underline)
4357 ("=" org-verbatim verbatim)
4358 ("~" org-code verbatim)
4359 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4360 "Alist of characters and faces to emphasize text.
4361 Text starting and ending with a special character will be emphasized,
4362 for example *bold*, _underlined_ and /italic/. This variable sets the
4363 marker characters and the face to be used by font-lock for highlighting
4364 in Org-mode Emacs buffers.
4366 You need to reload Org or to restart Emacs after customizing this."
4367 :group 'org-appearance
4368 :set 'org-set-emph-re
4369 :version "24.4"
4370 :package-version '(Org . "8.0")
4371 :type '(repeat
4372 (list
4373 (string :tag "Marker character")
4374 (choice
4375 (face :tag "Font-lock-face")
4376 (plist :tag "Face property list"))
4377 (option (const verbatim)))))
4379 (defvar org-protecting-blocks '("src" "example" "export")
4380 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4381 This is needed for font-lock setup.")
4383 ;;; Functions and variables from their packages
4384 ;; Declared here to avoid compiler warnings
4386 ;; XEmacs only
4387 (defvar outline-mode-menu-heading)
4388 (defvar outline-mode-menu-show)
4389 (defvar outline-mode-menu-hide)
4390 (defvar zmacs-regions) ; XEmacs regions
4392 ;; Emacs only
4393 (defvar mark-active)
4395 ;; Various packages
4396 (declare-function calc-eval "calc" (str &optional separator &rest args))
4397 (declare-function calendar-forward-day "cal-move" (arg))
4398 (declare-function calendar-goto-date "cal-move" (date))
4399 (declare-function calendar-goto-today "cal-move" ())
4400 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4401 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4402 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4403 (declare-function cdlatex-tab "ext:cdlatex" ())
4404 (declare-function dired-get-filename
4405 "dired"
4406 (&optional localp no-error-if-not-filep))
4407 (declare-function iswitchb-read-buffer
4408 "iswitchb"
4409 (prompt &optional default require-match start matches-set))
4410 (declare-function org-agenda-change-all-lines
4411 "org-agenda"
4412 (newhead hdmarker &optional fixface just-this))
4413 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4414 "org-agenda"
4415 (&optional end))
4416 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4417 (declare-function org-agenda-format-item
4418 "org-agenda"
4419 (extra txt &optional level category tags dotime noprefix
4420 remove-re habitp))
4421 (declare-function org-agenda-maybe-redo "org-agenda" ())
4422 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4423 (declare-function org-agenda-save-markers-for-cut-and-paste
4424 "org-agenda"
4425 (beg end))
4426 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4427 (declare-function org-agenda-skip "org-agenda" ())
4428 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4429 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4430 (declare-function org-indent-mode "org-indent" (&optional arg))
4431 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4432 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4433 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4434 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4435 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4436 (declare-function parse-time-string "parse-time" (string))
4437 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4438 (declare-function table--at-cell-p
4439 "table"
4440 (position &optional object at-column))
4442 (defvar align-mode-rules-list)
4443 (defvar calc-embedded-close-formula)
4444 (defvar calc-embedded-open-formula)
4445 (defvar calc-embedded-open-mode)
4446 (defvar font-lock-unfontify-region-function)
4447 (defvar iswitchb-temp-buflist)
4448 (defvar org-agenda-tags-todo-honor-ignore-options)
4449 (defvar remember-data-file)
4450 (defvar texmathp-why)
4452 ;;;###autoload
4453 (defun turn-on-orgtbl ()
4454 "Unconditionally turn on `orgtbl-mode'."
4455 (require 'org-table)
4456 (orgtbl-mode 1))
4458 (defun org-at-table-p (&optional table-type)
4459 "Non-nil if the cursor is inside an Org table.
4460 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4461 If `org-enable-table-editor' is nil, return nil unconditionally."
4462 (and
4463 org-enable-table-editor
4464 (save-excursion
4465 (beginning-of-line)
4466 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4467 (or (not (derived-mode-p 'org-mode))
4468 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4469 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4470 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4472 (defun org-at-table.el-p ()
4473 "Non-nil when point is at a table.el table."
4474 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4475 (let ((element (org-element-at-point)))
4476 (and (eq (org-element-type element) 'table)
4477 (eq (org-element-property :type element) 'table.el)))))
4479 (defun org-table-recognize-table.el ()
4480 "If there is a table.el table nearby, recognize it and move into it."
4481 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4482 (beginning-of-line)
4483 (unless (or (looking-at org-table-dataline-regexp)
4484 (not (looking-at org-table1-hline-regexp)))
4485 (forward-line)
4486 (when (looking-at org-table-any-border-regexp)
4487 (forward-line -2)))
4488 (if (re-search-forward "|" (org-table-end t) t)
4489 (progn
4490 (require 'table)
4491 (if (table--at-cell-p (point)) t
4492 (message "recognizing table.el table...")
4493 (table-recognize-table)
4494 (message "recognizing table.el table...done")))
4495 (error "This should not happen"))))
4496 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4497 (make-obsolete 'org-table-recognize-table.el
4498 "please notify the org mailing list if you use this function."
4499 "Org 9.0")
4501 (defun org-at-table-hline-p ()
4502 "Non-nil when point is inside a hline in a table.
4503 Assume point is already in a table. If `org-enable-table-editor'
4504 is nil, return nil unconditionally."
4505 (and org-enable-table-editor
4506 (save-excursion
4507 (beginning-of-line)
4508 (looking-at org-table-hline-regexp))))
4510 (defun org-table-map-tables (function &optional quietly)
4511 "Apply FUNCTION to the start of all tables in the buffer."
4512 (save-excursion
4513 (save-restriction
4514 (widen)
4515 (goto-char (point-min))
4516 (while (re-search-forward org-table-any-line-regexp nil t)
4517 (unless quietly
4518 (message "Mapping tables: %d%%"
4519 (floor (* 100.0 (point)) (buffer-size))))
4520 (beginning-of-line 1)
4521 (when (and (looking-at org-table-line-regexp)
4522 ;; Exclude tables in src/example/verbatim/clocktable blocks
4523 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4524 (save-excursion (funcall function))
4525 (or (looking-at org-table-line-regexp)
4526 (forward-char 1)))
4527 (re-search-forward org-table-any-border-regexp nil 1))))
4528 (unless quietly (message "Mapping tables: done")))
4530 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4531 (declare-function org-clock-update-mode-line "org-clock" ())
4532 (declare-function org-resolve-clocks "org-clock"
4533 (&optional also-non-dangling-p prompt last-valid))
4535 (defun org-at-TBLFM-p (&optional pos)
4536 "Non-nil when point (or POS) is in #+TBLFM line."
4537 (save-excursion
4538 (goto-char (or pos (point)))
4539 (beginning-of-line)
4540 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4541 (eq (org-element-type (org-element-at-point)) 'table))))
4543 (defvar org-clock-start-time)
4544 (defvar org-clock-marker (make-marker)
4545 "Marker recording the last clock-in.")
4546 (defvar org-clock-hd-marker (make-marker)
4547 "Marker recording the last clock-in, but the headline position.")
4548 (defvar org-clock-heading ""
4549 "The heading of the current clock entry.")
4550 (defun org-clock-is-active ()
4551 "Return the buffer where the clock is currently running.
4552 Return nil if no clock is running."
4553 (marker-buffer org-clock-marker))
4555 (defun org-check-running-clock ()
4556 "Check if the current buffer contains the running clock.
4557 If yes, offer to stop it and to save the buffer with the changes."
4558 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4559 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4560 (buffer-name))))
4561 (org-clock-out)
4562 (when (y-or-n-p "Save changed buffer?")
4563 (save-buffer))))
4565 (defun org-clocktable-try-shift (dir n)
4566 "Check if this line starts a clock table, if yes, shift the time block."
4567 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4568 (org-clocktable-shift dir n)))
4570 ;;;###autoload
4571 (defun org-clock-persistence-insinuate ()
4572 "Set up hooks for clock persistence."
4573 (require 'org-clock)
4574 (add-hook 'org-mode-hook 'org-clock-load)
4575 (add-hook 'kill-emacs-hook 'org-clock-save))
4577 (defgroup org-archive nil
4578 "Options concerning archiving in Org-mode."
4579 :tag "Org Archive"
4580 :group 'org-structure)
4582 (defcustom org-archive-location "%s_archive::"
4583 "The location where subtrees should be archived.
4585 The value of this variable is a string, consisting of two parts,
4586 separated by a double-colon. The first part is a filename and
4587 the second part is a headline.
4589 When the filename is omitted, archiving happens in the same file.
4590 %s in the filename will be replaced by the current file
4591 name (without the directory part). Archiving to a different file
4592 is useful to keep archived entries from contributing to the
4593 Org-mode Agenda.
4595 The archived entries will be filed as subtrees of the specified
4596 headline. When the headline is omitted, the subtrees are simply
4597 filed away at the end of the file, as top-level entries. Also in
4598 the heading you can use %s to represent the file name, this can be
4599 useful when using the same archive for a number of different files.
4601 Here are a few examples:
4602 \"%s_archive::\"
4603 If the current file is Projects.org, archive in file
4604 Projects.org_archive, as top-level trees. This is the default.
4606 \"::* Archived Tasks\"
4607 Archive in the current file, under the top-level headline
4608 \"* Archived Tasks\".
4610 \"~/org/archive.org::\"
4611 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4613 \"~/org/archive.org::* From %s\"
4614 Archive in file ~/org/archive.org (absolute path), under headlines
4615 \"From FILENAME\" where file name is the current file name.
4617 \"~/org/datetree.org::datetree/* Finished Tasks\"
4618 The \"datetree/\" string is special, signifying to archive
4619 items to the datetree. Items are placed in either the CLOSED
4620 date of the item, or the current date if there is no CLOSED date.
4621 The heading will be a subentry to the current date. There doesn't
4622 need to be a heading, but there always needs to be a slash after
4623 datetree. For example, to store archived items directly in the
4624 datetree, use \"~/org/datetree.org::datetree/\".
4626 \"basement::** Finished Tasks\"
4627 Archive in file ./basement (relative path), as level 3 trees
4628 below the level 2 heading \"** Finished Tasks\".
4630 You may set this option on a per-file basis by adding to the buffer a
4631 line like
4633 #+ARCHIVE: basement::** Finished Tasks
4635 You may also define it locally for a subtree by setting an ARCHIVE property
4636 in the entry. If such a property is found in an entry, or anywhere up
4637 the hierarchy, it will be used."
4638 :group 'org-archive
4639 :type 'string)
4641 (defcustom org-agenda-skip-archived-trees t
4642 "Non-nil means the agenda will skip any items located in archived trees.
4643 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4644 variable is no longer recommended, you should leave it at the value t.
4645 Instead, use the key `v' to cycle the archives-mode in the agenda."
4646 :group 'org-archive
4647 :group 'org-agenda-skip
4648 :type 'boolean)
4650 (defcustom org-columns-skip-archived-trees t
4651 "Non-nil means ignore archived trees when creating column view."
4652 :group 'org-archive
4653 :group 'org-properties
4654 :type 'boolean)
4656 (defcustom org-cycle-open-archived-trees nil
4657 "Non-nil means `org-cycle' will open archived trees.
4658 An archived tree is a tree marked with the tag ARCHIVE.
4659 When nil, archived trees will stay folded. You can still open them with
4660 normal outline commands like `show-all', but not with the cycling commands."
4661 :group 'org-archive
4662 :group 'org-cycle
4663 :type 'boolean)
4665 (defcustom org-sparse-tree-open-archived-trees nil
4666 "Non-nil means sparse tree construction shows matches in archived trees.
4667 When nil, matches in these trees are highlighted, but the trees are kept in
4668 collapsed state."
4669 :group 'org-archive
4670 :group 'org-sparse-trees
4671 :type 'boolean)
4673 (defcustom org-sparse-tree-default-date-type nil
4674 "The default date type when building a sparse tree.
4675 When this is nil, a date is a scheduled or a deadline timestamp.
4676 Otherwise, these types are allowed:
4678 all: all timestamps
4679 active: only active timestamps (<...>)
4680 inactive: only inactive timestamps ([...])
4681 scheduled: only scheduled timestamps
4682 deadline: only deadline timestamps"
4683 :type '(choice (const :tag "Scheduled or deadline" nil)
4684 (const :tag "All timestamps" all)
4685 (const :tag "Only active timestamps" active)
4686 (const :tag "Only inactive timestamps" inactive)
4687 (const :tag "Only scheduled timestamps" scheduled)
4688 (const :tag "Only deadline timestamps" deadline)
4689 (const :tag "Only closed timestamps" closed))
4690 :version "25.1"
4691 :package-version '(Org . "8.3")
4692 :group 'org-sparse-trees)
4694 (defun org-cycle-hide-archived-subtrees (state)
4695 "Re-hide all archived subtrees after a visibility state change."
4696 (when (and (not org-cycle-open-archived-trees)
4697 (not (memq state '(overview folded))))
4698 (save-excursion
4699 (let* ((globalp (memq state '(contents all)))
4700 (beg (if globalp (point-min) (point)))
4701 (end (if globalp (point-max) (org-end-of-subtree t))))
4702 (org-hide-archived-subtrees beg end)
4703 (goto-char beg)
4704 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4705 (message "%s" (substitute-command-keys
4706 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4708 (defun org-force-cycle-archived ()
4709 "Cycle subtree even if it is archived."
4710 (interactive)
4711 (setq this-command 'org-cycle)
4712 (let ((org-cycle-open-archived-trees t))
4713 (call-interactively 'org-cycle)))
4715 (defun org-hide-archived-subtrees (beg end)
4716 "Re-hide all archived subtrees after a visibility state change."
4717 (org-with-wide-buffer
4718 (let ((case-fold-search nil)
4719 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4720 (goto-char beg)
4721 ;; Include headline point is currently on.
4722 (beginning-of-line)
4723 (while (and (< (point) end) (re-search-forward re end t))
4724 (when (member org-archive-tag (org-get-tags))
4725 (org-flag-subtree t)
4726 (org-end-of-subtree t))))))
4728 (declare-function outline-end-of-heading "outline" ())
4729 (declare-function outline-flag-region "outline" (from to flag))
4730 (defun org-flag-subtree (flag)
4731 (save-excursion
4732 (org-back-to-heading t)
4733 (outline-end-of-heading)
4734 (outline-flag-region (point)
4735 (progn (org-end-of-subtree t) (point))
4736 flag)))
4738 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4740 ;; Declare Column View Code
4742 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4743 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4744 (declare-function org-columns-compute "org-colview" (property))
4746 ;; Declare ID code
4748 (declare-function org-id-store-link "org-id")
4749 (declare-function org-id-locations-load "org-id")
4750 (declare-function org-id-locations-save "org-id")
4751 (defvar org-id-track-globally)
4753 ;;; Variables for pre-computed regular expressions, all buffer local
4755 (defvar-local org-todo-regexp nil
4756 "Matches any of the TODO state keywords.")
4757 (defvar-local org-not-done-regexp nil
4758 "Matches any of the TODO state keywords except the last one.")
4759 (defvar-local org-not-done-heading-regexp nil
4760 "Matches a TODO headline that is not done.")
4761 (defvar-local org-todo-line-regexp nil
4762 "Matches a headline and puts TODO state into group 2 if present.")
4763 (defvar-local org-complex-heading-regexp nil
4764 "Matches a headline and puts everything into groups:
4765 group 1: the stars
4766 group 2: The todo keyword, maybe
4767 group 3: Priority cookie
4768 group 4: True headline
4769 group 5: Tags")
4770 (defvar-local org-complex-heading-regexp-format nil
4771 "Printf format to make regexp to match an exact headline.
4772 This regexp will match the headline of any node which has the
4773 exact headline text that is put into the format, but may have any
4774 TODO state, priority and tags.")
4775 (defvar-local org-todo-line-tags-regexp nil
4776 "Matches a headline and puts TODO state into group 2 if present.
4777 Also put tags into group 4 if tags are present.")
4779 (defconst org-plain-time-of-day-regexp
4780 (concat
4781 "\\(\\<[012]?[0-9]"
4782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4783 "\\(--?"
4784 "\\(\\<[012]?[0-9]"
4785 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4786 "\\)?")
4787 "Regular expression to match a plain time or time range.
4788 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4789 groups carry important information:
4790 0 the full match
4791 1 the first time, range or not
4792 8 the second time, if it is a range.")
4794 (defconst org-plain-time-extension-regexp
4795 (concat
4796 "\\(\\<[012]?[0-9]"
4797 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4798 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4799 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4800 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4801 groups carry important information:
4802 0 the full match
4803 7 hours of duration
4804 9 minutes of duration")
4806 (defconst org-stamp-time-of-day-regexp
4807 (concat
4808 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4809 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4810 "\\(--?"
4811 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4812 "Regular expression to match a timestamp time or time range.
4813 After a match, the following groups carry important information:
4814 0 the full match
4815 1 date plus weekday, for back referencing to make sure both times are on the same day
4816 2 the first time, range or not
4817 4 the second time, if it is a range.")
4819 (defconst org-startup-options
4820 '(("fold" org-startup-folded t)
4821 ("overview" org-startup-folded t)
4822 ("nofold" org-startup-folded nil)
4823 ("showall" org-startup-folded nil)
4824 ("showeverything" org-startup-folded showeverything)
4825 ("content" org-startup-folded content)
4826 ("indent" org-startup-indented t)
4827 ("noindent" org-startup-indented nil)
4828 ("hidestars" org-hide-leading-stars t)
4829 ("showstars" org-hide-leading-stars nil)
4830 ("odd" org-odd-levels-only t)
4831 ("oddeven" org-odd-levels-only nil)
4832 ("align" org-startup-align-all-tables t)
4833 ("noalign" org-startup-align-all-tables nil)
4834 ("inlineimages" org-startup-with-inline-images t)
4835 ("noinlineimages" org-startup-with-inline-images nil)
4836 ("latexpreview" org-startup-with-latex-preview t)
4837 ("nolatexpreview" org-startup-with-latex-preview nil)
4838 ("customtime" org-display-custom-times t)
4839 ("logdone" org-log-done time)
4840 ("lognotedone" org-log-done note)
4841 ("nologdone" org-log-done nil)
4842 ("lognoteclock-out" org-log-note-clock-out t)
4843 ("nolognoteclock-out" org-log-note-clock-out nil)
4844 ("logrepeat" org-log-repeat state)
4845 ("lognoterepeat" org-log-repeat note)
4846 ("logdrawer" org-log-into-drawer t)
4847 ("nologdrawer" org-log-into-drawer nil)
4848 ("logstatesreversed" org-log-states-order-reversed t)
4849 ("nologstatesreversed" org-log-states-order-reversed nil)
4850 ("nologrepeat" org-log-repeat nil)
4851 ("logreschedule" org-log-reschedule time)
4852 ("lognotereschedule" org-log-reschedule note)
4853 ("nologreschedule" org-log-reschedule nil)
4854 ("logredeadline" org-log-redeadline time)
4855 ("lognoteredeadline" org-log-redeadline note)
4856 ("nologredeadline" org-log-redeadline nil)
4857 ("logrefile" org-log-refile time)
4858 ("lognoterefile" org-log-refile note)
4859 ("nologrefile" org-log-refile nil)
4860 ("fninline" org-footnote-define-inline t)
4861 ("nofninline" org-footnote-define-inline nil)
4862 ("fnlocal" org-footnote-section nil)
4863 ("fnauto" org-footnote-auto-label t)
4864 ("fnprompt" org-footnote-auto-label nil)
4865 ("fnconfirm" org-footnote-auto-label confirm)
4866 ("fnplain" org-footnote-auto-label plain)
4867 ("fnadjust" org-footnote-auto-adjust t)
4868 ("nofnadjust" org-footnote-auto-adjust nil)
4869 ("constcgs" constants-unit-system cgs)
4870 ("constSI" constants-unit-system SI)
4871 ("noptag" org-tag-persistent-alist nil)
4872 ("hideblocks" org-hide-block-startup t)
4873 ("nohideblocks" org-hide-block-startup nil)
4874 ("beamer" org-startup-with-beamer-mode t)
4875 ("entitiespretty" org-pretty-entities t)
4876 ("entitiesplain" org-pretty-entities nil))
4877 "Variable associated with STARTUP options for org-mode.
4878 Each element is a list of three items: the startup options (as written
4879 in the #+STARTUP line), the corresponding variable, and the value to set
4880 this variable to if the option is found. An optional forth element PUSH
4881 means to push this value onto the list in the variable.")
4883 (defcustom org-group-tags t
4884 "When non-nil (the default), use group tags.
4885 This can be turned on/off through `org-toggle-tags-groups'."
4886 :group 'org-tags
4887 :group 'org-startup
4888 :type 'boolean)
4890 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4892 (defun org-toggle-tags-groups ()
4893 "Toggle support for group tags.
4894 Support for group tags is controlled by the option
4895 `org-group-tags', which is non-nil by default."
4896 (interactive)
4897 (setq org-group-tags (not org-group-tags))
4898 (cond ((and (derived-mode-p 'org-agenda-mode)
4899 org-group-tags)
4900 (org-agenda-redo))
4901 ((derived-mode-p 'org-mode)
4902 (let ((org-inhibit-startup t)) (org-mode))))
4903 (message "Groups tags support has been turned %s"
4904 (if org-group-tags "on" "off")))
4906 (defun org-set-regexps-and-options (&optional tags-only)
4907 "Precompute regular expressions used in the current buffer.
4908 When optional argument TAGS-ONLY is non-nil, only compute tags
4909 related expressions."
4910 (when (derived-mode-p 'org-mode)
4911 (let ((alist (org--setup-collect-keywords
4912 (org-make-options-regexp
4913 (append '("FILETAGS" "TAGS" "SETUPFILE")
4914 (and (not tags-only)
4915 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4916 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4917 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4918 (org--setup-process-tags
4919 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4920 (unless tags-only
4921 ;; File properties.
4922 (setq-local org-file-properties (cdr (assq 'property alist)))
4923 ;; Archive location.
4924 (let ((archive (cdr (assq 'archive alist))))
4925 (when archive (setq-local org-archive-location archive)))
4926 ;; Category.
4927 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4928 (when cat
4929 (setq-local org-category (intern cat))
4930 (setq-local org-file-properties
4931 (org--update-property-plist
4932 "CATEGORY" cat org-file-properties))))
4933 ;; Columns.
4934 (let ((column (cdr (assq 'columns alist))))
4935 (when column (setq-local org-columns-default-format column)))
4936 ;; Constants.
4937 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4938 ;; Link abbreviations.
4939 (let ((links (cdr (assq 'link alist))))
4940 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4941 ;; Priorities.
4942 (let ((priorities (cdr (assq 'priorities alist))))
4943 (when priorities
4944 (setq-local org-highest-priority (nth 0 priorities))
4945 (setq-local org-lowest-priority (nth 1 priorities))
4946 (setq-local org-default-priority (nth 2 priorities))))
4947 ;; Scripts.
4948 (let ((scripts (assq 'scripts alist)))
4949 (when scripts
4950 (setq-local org-use-sub-superscripts (cdr scripts))))
4951 ;; Startup options.
4952 (let ((startup (cdr (assq 'startup alist))))
4953 (dolist (option startup)
4954 (let ((entry (assoc-string option org-startup-options t)))
4955 (when entry
4956 (let ((var (nth 1 entry))
4957 (val (nth 2 entry)))
4958 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4959 (unless (listp (symbol-value var))
4960 (set (make-local-variable var) nil))
4961 (add-to-list var val)))))))
4962 ;; TODO keywords.
4963 (setq-local org-todo-kwd-alist nil)
4964 (setq-local org-todo-key-alist nil)
4965 (setq-local org-todo-key-trigger nil)
4966 (setq-local org-todo-keywords-1 nil)
4967 (setq-local org-done-keywords nil)
4968 (setq-local org-todo-heads nil)
4969 (setq-local org-todo-sets nil)
4970 (setq-local org-todo-log-states nil)
4971 (let ((todo-sequences
4972 (or (nreverse (cdr (assq 'todo alist)))
4973 (let ((d (default-value 'org-todo-keywords)))
4974 (if (not (stringp (car d))) d
4975 ;; XXX: Backward compatibility code.
4976 (list (cons org-todo-interpretation d)))))))
4977 (dolist (sequence todo-sequences)
4978 (let* ((sequence (or (run-hook-with-args-until-success
4979 'org-todo-setup-filter-hook sequence)
4980 sequence))
4981 (sequence-type (car sequence))
4982 (keywords (cdr sequence))
4983 (sep (member "|" keywords))
4984 names alist)
4985 (dolist (k (remove "|" keywords))
4986 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4988 (error "Invalid TODO keyword %s" k))
4989 (let ((name (match-string 1 k))
4990 (key (match-string 2 k))
4991 (log (org-extract-log-state-settings k)))
4992 (push name names)
4993 (push (cons name (and key (string-to-char key))) alist)
4994 (when log (push log org-todo-log-states))))
4995 (let* ((names (nreverse names))
4996 (done (if sep (org-remove-keyword-keys (cdr sep))
4997 (last names)))
4998 (head (car names))
4999 (tail (list sequence-type head (car done) (org-last done))))
5000 (add-to-list 'org-todo-heads head 'append)
5001 (push names org-todo-sets)
5002 (setq org-done-keywords (append org-done-keywords done nil))
5003 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5004 (setq org-todo-key-alist
5005 (append org-todo-key-alist
5006 (and alist
5007 (append '((:startgroup))
5008 (nreverse alist)
5009 '((:endgroup))))))
5010 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5011 (setq org-todo-sets (nreverse org-todo-sets)
5012 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5013 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5014 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5015 ;; Compute the regular expressions and other local variables.
5016 ;; Using `org-outline-regexp-bol' would complicate them much,
5017 ;; because of the fixed white space at the end of that string.
5018 (unless org-done-keywords
5019 (setq org-done-keywords
5020 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5021 (setq org-not-done-keywords
5022 (org-delete-all org-done-keywords
5023 (copy-sequence org-todo-keywords-1))
5024 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5025 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5026 org-not-done-heading-regexp
5027 (format org-heading-keyword-regexp-format org-not-done-regexp)
5028 org-todo-line-regexp
5029 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5030 org-complex-heading-regexp
5031 (concat "^\\(\\*+\\)"
5032 "\\(?: +" org-todo-regexp "\\)?"
5033 "\\(?: +\\(\\[#.\\]\\)\\)?"
5034 "\\(?: +\\(.*?\\)\\)??"
5035 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5036 "[ \t]*$")
5037 org-complex-heading-regexp-format
5038 (concat "^\\(\\*+\\)"
5039 "\\(?: +" org-todo-regexp "\\)?"
5040 "\\(?: +\\(\\[#.\\]\\)\\)?"
5041 "\\(?: +"
5042 ;; Stats cookies can be stuck to body.
5043 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5044 "\\(%s\\)"
5045 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5046 "\\)"
5047 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5048 "[ \t]*$")
5049 org-todo-line-tags-regexp
5050 (concat "^\\(\\*+\\)"
5051 "\\(?: +" org-todo-regexp "\\)?"
5052 "\\(?: +\\(.*?\\)\\)??"
5053 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5054 "[ \t]*$"))
5055 (org-compute-latex-and-related-regexp)))))
5057 (defun org--setup-collect-keywords (regexp &optional files alist)
5058 "Return setup keywords values as an alist.
5060 REGEXP matches a subset of setup keywords. FILES is a list of
5061 file names already visited. It is used to avoid circular setup
5062 files. ALIST, when non-nil, is the alist computed so far.
5064 Return value contains the following keys: `archive', `category',
5065 `columns', `constants', `filetags', `link', `priorities',
5066 `property', `scripts', `startup', `tags' and `todo'."
5067 (org-with-wide-buffer
5068 (goto-char (point-min))
5069 (let ((case-fold-search t))
5070 (while (re-search-forward regexp nil t)
5071 (let ((element (org-element-at-point)))
5072 (when (eq (org-element-type element) 'keyword)
5073 (let ((key (org-element-property :key element))
5074 (value (org-element-property :value element)))
5075 (cond
5076 ((equal key "ARCHIVE")
5077 (when (org-string-nw-p value)
5078 (push (cons 'archive value) alist)))
5079 ((equal key "CATEGORY") (push (cons 'category value) alist))
5080 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5081 ((equal key "CONSTANTS")
5082 (let* ((constants (assq 'constants alist))
5083 (store (cdr constants)))
5084 (dolist (pair (org-split-string value))
5085 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5086 pair)
5087 (let* ((name (match-string 1 pair))
5088 (value (match-string 2 pair))
5089 (old (assoc name store)))
5090 (if old (setcdr old value)
5091 (push (cons name value) store)))))
5092 (if constants (setcdr constants store)
5093 (push (cons 'constants store) alist))))
5094 ((equal key "FILETAGS")
5095 (when (org-string-nw-p value)
5096 (let ((old (assq 'filetags alist))
5097 (new (apply #'nconc
5098 (mapcar (lambda (x) (org-split-string x ":"))
5099 (org-split-string value)))))
5100 (if old (setcdr old (append new (cdr old)))
5101 (push (cons 'filetags new) alist)))))
5102 ((equal key "LINK")
5103 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5104 (let ((links (assq 'link alist))
5105 (pair (cons (org-match-string-no-properties 1 value)
5106 (org-match-string-no-properties 2 value))))
5107 (if links (push pair (cdr links))
5108 (push (list 'link pair) alist)))))
5109 ((equal key "OPTIONS")
5110 (when (and (org-string-nw-p value)
5111 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5112 (push (cons 'scripts (read (match-string 1 value))) alist)))
5113 ((equal key "PRIORITIES")
5114 (push (cons 'priorities
5115 (let ((prio (org-split-string value)))
5116 (if (< (length prio) 3) '(?A ?C ?B)
5117 (mapcar #'string-to-char prio))))
5118 alist))
5119 ((equal key "PROPERTY")
5120 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5121 (let* ((property (assq 'property alist))
5122 (value (org--update-property-plist
5123 (org-match-string-no-properties 1 value)
5124 (org-match-string-no-properties 2 value)
5125 (cdr property))))
5126 (if property (setcdr property value)
5127 (push (cons 'property value) alist)))))
5128 ((equal key "STARTUP")
5129 (let ((startup (assq 'startup alist)))
5130 (if startup
5131 (setcdr startup
5132 (append (cdr startup) (org-split-string value)))
5133 (push (cons 'startup (org-split-string value)) alist))))
5134 ((equal key "TAGS")
5135 (let ((tag-cell (assq 'tags alist)))
5136 (if tag-cell
5137 (setcdr tag-cell
5138 (append (cdr tag-cell)
5139 '("\\n")
5140 (org-split-string value)))
5141 (push (cons 'tags (org-split-string value)) alist))))
5142 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5143 (let ((todo (assq 'todo alist))
5144 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5145 (org-split-string value))))
5146 (if todo (push value (cdr todo))
5147 (push (list 'todo value) alist))))
5148 ((equal key "SETUPFILE")
5149 (unless buffer-read-only ; Do not check in Gnus messages.
5150 (let ((f (and (org-string-nw-p value)
5151 (expand-file-name
5152 (org-remove-double-quotes value)))))
5153 (when (and f (file-readable-p f) (not (member f files)))
5154 (with-temp-buffer
5155 (setq default-directory (file-name-directory f))
5156 (insert-file-contents f)
5157 (setq alist
5158 ;; Fake Org mode to benefit from cache
5159 ;; without recurring needlessly.
5160 (let ((major-mode 'org-mode))
5161 (org--setup-collect-keywords
5162 regexp (cons f files) alist)))))))))))))))
5163 alist)
5165 (defun org--setup-process-tags (tags filetags)
5166 "Precompute variables used for tags.
5167 TAGS is a list of tags and tag group symbols, as strings.
5168 FILETAGS is a list of tags, as strings."
5169 ;; Process the file tags.
5170 (setq-local org-file-tags
5171 (mapcar #'org-add-prop-inherited filetags))
5172 ;; Provide default tags if no local tags are found.
5173 (when (and (not tags) org-tag-alist)
5174 (setq tags
5175 (mapcar (lambda (tag)
5176 (cl-case (car tag)
5177 (:startgroup "{")
5178 (:endgroup "}")
5179 (:startgrouptag "[")
5180 (:endgrouptag "]")
5181 (:grouptags ":")
5182 (:newline "\\n")
5183 (otherwise (concat (car tag)
5184 (and (characterp (cdr tag))
5185 (format "(%c)" (cdr tag)))))))
5186 org-tag-alist)))
5187 ;; Process the tags.
5188 (setq-local org-tag-groups-alist nil)
5189 (setq-local org-tag-alist nil)
5190 (let (group-flag)
5191 (while tags
5192 (let ((e (car tags)))
5193 (setq tags (cdr tags))
5194 (cond
5195 ((equal e "{")
5196 (push '(:startgroup) org-tag-alist)
5197 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5198 ((equal e "}")
5199 (push '(:endgroup) org-tag-alist)
5200 (setq group-flag nil))
5201 ((equal e "[")
5202 (push '(:startgrouptag) org-tag-alist)
5203 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5204 ((equal e "]")
5205 (push '(:endgrouptag) org-tag-alist)
5206 (setq group-flag nil))
5207 ((equal e ":")
5208 (push '(:grouptags) org-tag-alist)
5209 (setq group-flag 'append))
5210 ((equal e "\\n") (push '(:newline) org-tag-alist))
5211 ((string-match
5212 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5213 "\\|{.+?}\\)" ; regular expression
5214 "\\(?:(\\(.\\))\\)?\\'")) e)
5215 (let ((tag (match-string 1 e))
5216 (key (and (match-beginning 2)
5217 (string-to-char (match-string 2 e)))))
5218 (cond ((eq group-flag 'append)
5219 (setcar org-tag-groups-alist
5220 (append (car org-tag-groups-alist) (list tag))))
5221 (group-flag (push (list tag) org-tag-groups-alist)))
5222 ;; Push all tags in groups, no matter if they already exist.
5223 (unless (and (not group-flag) (assoc tag org-tag-alist))
5224 (push (cons tag key) org-tag-alist))))))))
5225 (setq org-tag-alist (nreverse org-tag-alist)))
5227 (defun org-file-contents (file &optional noerror)
5228 "Return the contents of FILE, as a string."
5229 (if (and file (file-readable-p file))
5230 (with-temp-buffer
5231 (insert-file-contents file)
5232 (buffer-string))
5233 (funcall (if noerror 'message 'error)
5234 "Cannot read file \"%s\"%s"
5235 file
5236 (let ((from (buffer-file-name (buffer-base-buffer))))
5237 (if from (concat " (referenced in file \"" from "\")") "")))))
5239 (defun org-extract-log-state-settings (x)
5240 "Extract the log state setting from a TODO keyword string.
5241 This will extract info from a string like \"WAIT(w@/!)\"."
5242 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5243 (let ((kw (match-string 1 x))
5244 (log1 (and (match-end 3) (match-string 3 x)))
5245 (log2 (and (match-end 4) (match-string 4 x))))
5246 (and (or log1 log2)
5247 (list kw
5248 (and log1 (if (equal log1 "!") 'time 'note))
5249 (and log2 (if (equal log2 "!") 'time 'note)))))))
5251 (defun org-remove-keyword-keys (list)
5252 "Remove a pair of parenthesis at the end of each string in LIST."
5253 (mapcar (lambda (x)
5254 (if (string-match "(.*)$" x)
5255 (substring x 0 (match-beginning 0))
5257 list))
5259 (defun org-assign-fast-keys (alist)
5260 "Assign fast keys to a keyword-key alist.
5261 Respect keys that are already there."
5262 (let (new e (alt ?0))
5263 (while (setq e (pop alist))
5264 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5265 (cdr e)) ;; Key already assigned.
5266 (push e new)
5267 (let ((clist (string-to-list (downcase (car e))))
5268 (used (append new alist)))
5269 (when (= (car clist) ?@)
5270 (pop clist))
5271 (while (and clist (rassoc (car clist) used))
5272 (pop clist))
5273 (unless clist
5274 (while (rassoc alt used)
5275 (cl-incf alt)))
5276 (push (cons (car e) (or (car clist) alt)) new))))
5277 (nreverse new)))
5279 ;;; Some variables used in various places
5281 (defvar org-window-configuration nil
5282 "Used in various places to store a window configuration.")
5283 (defvar org-selected-window nil
5284 "Used in various places to store a window configuration.")
5285 (defvar org-finish-function nil
5286 "Function to be called when `C-c C-c' is used.
5287 This is for getting out of special buffers like capture.")
5288 (defvar org-last-state)
5290 ;; Defined somewhere in this file, but used before definition.
5291 (defvar org-entities) ;; defined in org-entities.el
5292 (defvar org-struct-menu)
5293 (defvar org-org-menu)
5294 (defvar org-tbl-menu)
5296 ;;;; Define the Org-mode
5298 ;; We use a before-change function to check if a table might need
5299 ;; an update.
5300 (defvar org-table-may-need-update t
5301 "Indicates that a table might need an update.
5302 This variable is set by `org-before-change-function'.
5303 `org-table-align' sets it back to nil.")
5304 (defun org-before-change-function (_beg _end)
5305 "Every change indicates that a table might need an update."
5306 (setq org-table-may-need-update t))
5307 (defvar org-mode-map)
5308 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5309 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5310 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5311 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5312 (defvar org-table-buffer-is-an nil)
5314 (defvar bidi-paragraph-direction)
5315 (defvar buffer-face-mode-face)
5317 (require 'outline)
5318 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5319 (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"))
5320 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5322 ;; Other stuff we need.
5323 (require 'time-date)
5324 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5325 (require 'easymenu)
5326 (autoload 'easy-menu-add "easymenu")
5327 (require 'overlay)
5329 ;; (require 'org-macs) moved higher up in the file before it is first used
5330 (require 'org-entities)
5331 ;; (require 'org-compat) moved higher up in the file before it is first used
5332 (require 'org-faces)
5333 (require 'org-list)
5334 (require 'org-pcomplete)
5335 (require 'org-src)
5336 (require 'org-footnote)
5337 (require 'org-macro)
5339 ;; babel
5340 (require 'ob)
5342 ;;;###autoload
5343 (define-derived-mode org-mode outline-mode "Org"
5344 "Outline-based notes management and organizer, alias
5345 \"Carsten's outline-mode for keeping track of everything.\"
5347 Org-mode develops organizational tasks around a NOTES file which
5348 contains information about projects as plain text. Org-mode is
5349 implemented on top of outline-mode, which is ideal to keep the content
5350 of large files well structured. It supports ToDo items, deadlines and
5351 time stamps, which magically appear in the diary listing of the Emacs
5352 calendar. Tables are easily created with a built-in table editor.
5353 Plain text URL-like links connect to websites, emails (VM), Usenet
5354 messages (Gnus), BBDB entries, and any files related to the project.
5355 For printing and sharing of notes, an Org-mode file (or a part of it)
5356 can be exported as a structured ASCII or HTML file.
5358 The following commands are available:
5360 \\{org-mode-map}"
5362 ;; Get rid of Outline menus, they are not needed
5363 ;; Need to do this here because define-derived-mode sets up
5364 ;; the keymap so late. Still, it is a waste to call this each time
5365 ;; we switch another buffer into org-mode.
5366 (if (featurep 'xemacs)
5367 (when (boundp 'outline-mode-menu-heading)
5368 ;; Assume this is Greg's port, it uses easymenu
5369 (easy-menu-remove outline-mode-menu-heading)
5370 (easy-menu-remove outline-mode-menu-show)
5371 (easy-menu-remove outline-mode-menu-hide))
5372 (define-key org-mode-map [menu-bar headings] 'undefined)
5373 (define-key org-mode-map [menu-bar hide] 'undefined)
5374 (define-key org-mode-map [menu-bar show] 'undefined))
5376 (org-load-modules-maybe)
5377 (when (featurep 'xemacs)
5378 (easy-menu-add org-org-menu)
5379 (easy-menu-add org-tbl-menu))
5380 (org-install-agenda-files-menu)
5381 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5382 (add-to-invisibility-spec '(org-cwidth))
5383 (add-to-invisibility-spec '(org-hide-block . t))
5384 (when (featurep 'xemacs)
5385 (setq-local line-move-ignore-invisible t))
5386 (setq-local outline-regexp org-outline-regexp)
5387 (setq-local outline-level 'org-outline-level)
5388 (setq bidi-paragraph-direction 'left-to-right)
5389 (when (and org-ellipsis
5390 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5391 (fboundp 'make-glyph-code))
5392 (unless org-display-table
5393 (setq org-display-table (make-display-table)))
5394 (set-display-table-slot
5395 org-display-table 4
5396 (vconcat (mapcar
5397 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5398 org-ellipsis)))
5399 (if (stringp org-ellipsis) org-ellipsis "..."))))
5400 (setq buffer-display-table org-display-table))
5401 (org-set-regexps-and-options)
5402 (org-set-font-lock-defaults)
5403 (when (and org-tag-faces (not org-tags-special-faces-re))
5404 ;; tag faces set outside customize.... force initialization.
5405 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5406 ;; Calc embedded
5407 (setq-local calc-embedded-open-mode "# ")
5408 ;; Modify a few syntax entries
5409 (modify-syntax-entry ?@ "w")
5410 (modify-syntax-entry ?\" "\"")
5411 (modify-syntax-entry ?\\ "_")
5412 (modify-syntax-entry ?~ "_")
5413 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5414 ;; Activate before-change-function
5415 (setq-local org-table-may-need-update t)
5416 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5417 ;; Check for running clock before killing a buffer
5418 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5419 ;; Initialize macros templates.
5420 (org-macro-initialize-templates)
5421 ;; Initialize radio targets.
5422 (org-update-radio-target-regexp)
5423 ;; Indentation.
5424 (setq-local indent-line-function 'org-indent-line)
5425 (setq-local indent-region-function 'org-indent-region)
5426 ;; Filling and auto-filling.
5427 (org-setup-filling)
5428 ;; Comments.
5429 (org-setup-comments-handling)
5430 ;; Initialize cache.
5431 (org-element-cache-reset)
5432 ;; Beginning/end of defun
5433 (setq-local beginning-of-defun-function 'org-backward-element)
5434 (setq-local end-of-defun-function
5435 (lambda ()
5436 (if (not (org-at-heading-p))
5437 (org-forward-element)
5438 (org-forward-element)
5439 (forward-char -1))))
5440 ;; Next error for sparse trees
5441 (setq-local next-error-function 'org-occur-next-match)
5442 ;; Make sure dependence stuff works reliably, even for users who set it
5443 ;; too late :-(
5444 (if org-enforce-todo-dependencies
5445 (add-hook 'org-blocker-hook
5446 'org-block-todo-from-children-or-siblings-or-parent)
5447 (remove-hook 'org-blocker-hook
5448 'org-block-todo-from-children-or-siblings-or-parent))
5449 (if org-enforce-todo-checkbox-dependencies
5450 (add-hook 'org-blocker-hook
5451 'org-block-todo-from-checkboxes)
5452 (remove-hook 'org-blocker-hook
5453 'org-block-todo-from-checkboxes))
5455 ;; Align options lines
5456 (setq-local
5457 align-mode-rules-list
5458 '((org-in-buffer-settings
5459 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5460 (modes . '(org-mode)))))
5462 ;; Imenu
5463 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5465 ;; Make isearch reveal context
5466 (setq-local outline-isearch-open-invisible-function
5467 (lambda (&rest _) (org-show-context 'isearch)))
5469 ;; Setup the pcomplete hooks
5470 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5471 (setq-local pcomplete-command-name-function 'org-command-at-point)
5472 (setq-local pcomplete-default-completion-function 'ignore)
5473 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5474 (setq-local pcomplete-termination-string "")
5475 (setq-local buffer-face-mode-face 'org-default)
5477 ;; If empty file that did not turn on Org mode automatically, make
5478 ;; it to.
5479 (when (and org-insert-mode-line-in-empty-file
5480 (org-called-interactively-p 'any)
5481 (= (point-min) (point-max)))
5482 (insert "# -*- mode: org -*-\n\n"))
5483 (unless org-inhibit-startup
5484 (org-unmodified
5485 (when org-startup-with-beamer-mode (org-beamer-mode))
5486 (when org-startup-align-all-tables
5487 (org-table-map-tables #'org-table-align t))
5488 (when org-startup-with-inline-images (org-display-inline-images))
5489 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5490 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5491 (when org-startup-truncated (setq truncate-lines t))
5492 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5493 (org-refresh-effort-properties)))
5494 ;; Try to set `org-hide' face correctly.
5495 (let ((foreground (org-find-invisible-foreground)))
5496 (when foreground
5497 (set-face-foreground 'org-hide foreground))))
5499 ;; Update `customize-package-emacs-version-alist'
5500 (add-to-list 'customize-package-emacs-version-alist
5501 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5502 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5503 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5505 (defvar org-mode-transpose-word-syntax-table
5506 (let ((st (make-syntax-table text-mode-syntax-table)))
5507 (dolist (c org-emphasis-alist st)
5508 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5510 (when (fboundp 'abbrev-table-put)
5511 (abbrev-table-put org-mode-abbrev-table
5512 :parents (list text-mode-abbrev-table)))
5514 (defun org-find-invisible-foreground ()
5515 (let ((candidates (remove
5516 "unspecified-bg"
5517 (nconc
5518 (list (face-background 'default)
5519 (face-background 'org-default))
5520 (mapcar
5521 (lambda (alist)
5522 (when (boundp alist)
5523 (cdr (assoc 'background-color (symbol-value alist)))))
5524 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5525 (list (face-foreground 'org-hide))))))
5526 (car (remove nil candidates))))
5528 (defun org-current-time (&optional rounding-minutes past)
5529 "Current time, possibly rounded to ROUNDING-MINUTES.
5530 When ROUNDING-MINUTES is not an integer, fall back on the car of
5531 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5532 the rounding returns a past time."
5533 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5534 (car org-time-stamp-rounding-minutes)))
5535 (time (decode-time)) res)
5536 (if (< r 1)
5537 (current-time)
5538 (setq res
5539 (apply 'encode-time
5540 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5541 (nthcdr 2 time))))
5542 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5543 (seconds-to-time (- (org-float-time res) (* r 60)))
5544 res))))
5546 (defun org-today ()
5547 "Return today date, considering `org-extend-today-until'."
5548 (time-to-days
5549 (time-subtract (current-time)
5550 (list 0 (* 3600 org-extend-today-until) 0))))
5552 ;;;; Font-Lock stuff, including the activators
5554 (defvar org-mouse-map (make-sparse-keymap))
5555 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5556 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5557 (when org-mouse-1-follows-link
5558 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5559 (when org-tab-follows-link
5560 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5561 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5563 (require 'font-lock)
5565 (defconst org-non-link-chars "]\t\n\r<>")
5566 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5567 "file+sys" "news" "shell" "elisp" "doi" "message"
5568 "help"))
5569 (defvar org-link-types-re nil
5570 "Matches a link that has a url-like prefix like \"http:\"")
5571 (defvar org-link-re-with-space nil
5572 "Matches a link with spaces, optional angular brackets around it.")
5573 (defvar org-link-re-with-space2 nil
5574 "Matches a link with spaces, optional angular brackets around it.")
5575 (defvar org-link-re-with-space3 nil
5576 "Matches a link with spaces, only for internal part in bracket links.")
5577 (defvar org-angle-link-re nil
5578 "Matches link with angular brackets, spaces are allowed.")
5579 (defvar org-plain-link-re nil
5580 "Matches plain link, without spaces.")
5581 (defvar org-bracket-link-regexp nil
5582 "Matches a link in double brackets.")
5583 (defvar org-bracket-link-analytic-regexp nil
5584 "Regular expression used to analyze links.
5585 Here is what the match groups contain after a match:
5586 1: http:
5587 2: http
5588 3: path
5589 4: [desc]
5590 5: desc")
5591 (defvar org-bracket-link-analytic-regexp++ nil
5592 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5593 (defvar org-any-link-re nil
5594 "Regular expression matching any link.")
5596 (defconst org-match-sexp-depth 3
5597 "Number of stacked braces for sub/superscript matching.")
5599 (defun org-create-multibrace-regexp (left right n)
5600 "Create a regular expression which will match a balanced sexp.
5601 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5602 as single character strings.
5603 The regexp returned will match the entire expression including the
5604 delimiters. It will also define a single group which contains the
5605 match except for the outermost delimiters. The maximum depth of
5606 stacked delimiters is N. Escaping delimiters is not possible."
5607 (let* ((nothing (concat "[^" left right "]*?"))
5608 (or "\\|")
5609 (re nothing)
5610 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5611 (while (> n 1)
5612 (setq n (1- n)
5613 re (concat re or next)
5614 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5615 (concat left "\\(" re "\\)" right)))
5617 (defconst org-match-substring-regexp
5618 (concat
5619 "\\(\\S-\\)\\([_^]\\)\\("
5620 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5621 "\\|"
5622 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5623 "\\|"
5624 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5625 "The regular expression matching a sub- or superscript.")
5627 (defconst org-match-substring-with-braces-regexp
5628 (concat
5629 "\\(\\S-\\)\\([_^]\\)"
5630 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5631 "The regular expression matching a sub- or superscript, forcing braces.")
5633 (defun org-make-link-regexps ()
5634 "Update the link regular expressions.
5635 This should be called after the variable `org-link-types' has changed."
5636 (let ((types-re (regexp-opt org-link-types t)))
5637 (setq org-link-types-re
5638 (concat "\\`" types-re ":")
5639 org-link-re-with-space
5640 (concat "<?" types-re ":"
5641 "\\([^" org-non-link-chars " ]"
5642 "[^" org-non-link-chars "]*"
5643 "[^" org-non-link-chars " ]\\)>?")
5644 org-link-re-with-space2
5645 (concat "<?" types-re ":"
5646 "\\([^" org-non-link-chars " ]"
5647 "[^\t\n\r]*"
5648 "[^" org-non-link-chars " ]\\)>?")
5649 org-link-re-with-space3
5650 (concat "<?" types-re ":"
5651 "\\([^" org-non-link-chars " ]"
5652 "[^\t\n\r]*\\)")
5653 org-angle-link-re
5654 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5655 types-re)
5656 org-plain-link-re
5657 (concat
5658 "\\<" types-re ":"
5659 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5660 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5661 org-bracket-link-regexp
5662 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5663 org-bracket-link-analytic-regexp
5664 (concat
5665 "\\[\\["
5666 "\\(" types-re ":\\)?"
5667 "\\([^]]+\\)"
5668 "\\]"
5669 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5670 "\\]")
5671 org-bracket-link-analytic-regexp++
5672 (concat
5673 "\\[\\["
5674 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5675 "\\([^]]+\\)"
5676 "\\]"
5677 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5678 "\\]")
5679 org-any-link-re
5680 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5681 org-angle-link-re "\\)\\|\\("
5682 org-plain-link-re "\\)"))))
5684 (org-make-link-regexps)
5686 (defvar org-emph-face nil)
5688 (defun org-do-emphasis-faces (limit)
5689 "Run through the buffer and emphasize strings."
5690 (let (rtn a)
5691 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5692 (let* ((border (char-after (match-beginning 3)))
5693 (bre (regexp-quote (char-to-string border))))
5694 (when (and (not (= border (char-after (match-beginning 4))))
5695 (not (string-match-p (concat bre ".*" bre)
5696 (replace-regexp-in-string
5697 "\n" " "
5698 (substring (match-string 2) 1 -1)))))
5699 (setq rtn t)
5700 (setq a (assoc (match-string 3) org-emphasis-alist))
5701 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5702 'face
5703 (nth 1 a))
5704 (and (nth 2 a)
5705 (org-remove-flyspell-overlays-in
5706 (match-beginning 0) (match-end 0)))
5707 (add-text-properties (match-beginning 2) (match-end 2)
5708 '(font-lock-multiline t org-emphasis t))
5709 (when org-hide-emphasis-markers
5710 (add-text-properties (match-end 4) (match-beginning 5)
5711 '(invisible org-link))
5712 (add-text-properties (match-beginning 3) (match-end 3)
5713 '(invisible org-link)))))
5714 (goto-char (1+ (match-beginning 0))))
5715 rtn))
5717 (defun org-emphasize (&optional char)
5718 "Insert or change an emphasis, i.e. a font like bold or italic.
5719 If there is an active region, change that region to a new emphasis.
5720 If there is no region, just insert the marker characters and position
5721 the cursor between them.
5722 CHAR should be the marker character. If it is a space, it means to
5723 remove the emphasis of the selected region.
5724 If CHAR is not given (for example in an interactive call) it will be
5725 prompted for."
5726 (interactive)
5727 (let ((erc org-emphasis-regexp-components)
5728 (string "") beg end move s)
5729 (if (org-region-active-p)
5730 (setq beg (region-beginning)
5731 end (region-end)
5732 string (buffer-substring beg end))
5733 (setq move t))
5735 (unless char
5736 (message "Emphasis marker or tag: [%s]"
5737 (mapconcat #'car org-emphasis-alist ""))
5738 (setq char (read-char-exclusive)))
5739 (if (equal char ?\s)
5740 (setq s ""
5741 move nil)
5742 (unless (assoc (char-to-string char) org-emphasis-alist)
5743 (user-error "No such emphasis marker: \"%c\"" char))
5744 (setq s (char-to-string char)))
5745 (while (and (> (length string) 1)
5746 (equal (substring string 0 1) (substring string -1))
5747 (assoc (substring string 0 1) org-emphasis-alist))
5748 (setq string (substring string 1 -1)))
5749 (setq string (concat s string s))
5750 (when beg (delete-region beg end))
5751 (unless (or (bolp)
5752 (string-match (concat "[" (nth 0 erc) "\n]")
5753 (char-to-string (char-before (point)))))
5754 (insert " "))
5755 (unless (or (eobp)
5756 (string-match (concat "[" (nth 1 erc) "\n]")
5757 (char-to-string (char-after (point)))))
5758 (insert " ") (backward-char 1))
5759 (insert string)
5760 (and move (backward-char 1))))
5762 (defconst org-nonsticky-props
5763 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5765 (defsubst org-rear-nonsticky-at (pos)
5766 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5768 (defun org-activate-plain-links (limit)
5769 "Add link properties for plain links."
5770 (when (and (re-search-forward org-plain-link-re limit t)
5771 (not (org-in-src-block-p)))
5772 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5773 'face))
5774 (link (org-match-string-no-properties 0)))
5775 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (add-text-properties (match-beginning 0) (match-end 0)
5778 (list 'mouse-face 'highlight
5779 'face 'org-link
5780 'htmlize-link `(:uri ,link)
5781 'keymap org-mouse-map))
5782 (org-rear-nonsticky-at (match-end 0))
5783 t))))
5785 (defun org-activate-code (limit)
5786 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5787 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5788 (remove-text-properties (match-beginning 0) (match-end 0)
5789 '(display t invisible t intangible t))
5792 (defcustom org-src-fontify-natively t
5793 "When non-nil, fontify code in code blocks."
5794 :type 'boolean
5795 :version "24.4"
5796 :package-version '(Org . "8.3")
5797 :group 'org-appearance
5798 :group 'org-babel)
5800 (defcustom org-allow-promoting-top-level-subtree nil
5801 "When non-nil, allow promoting a top level subtree.
5802 The leading star of the top level headline will be replaced
5803 by a #."
5804 :type 'boolean
5805 :version "24.1"
5806 :group 'org-appearance)
5808 (defun org-fontify-meta-lines-and-blocks (limit)
5809 (condition-case nil
5810 (org-fontify-meta-lines-and-blocks-1 limit)
5811 (error (message "org-mode fontification error"))))
5813 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5814 "Fontify #+ lines and blocks."
5815 (let ((case-fold-search t))
5816 (when (re-search-forward
5817 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5818 limit t)
5819 (let ((beg (match-beginning 0))
5820 (block-start (match-end 0))
5821 (block-end nil)
5822 (lang (match-string 7))
5823 (beg1 (line-beginning-position 2))
5824 (dc1 (downcase (match-string 2)))
5825 (dc3 (downcase (match-string 3)))
5826 end end1 quoting block-type)
5827 (cond
5828 ((and (match-end 4) (equal dc3 "+begin"))
5829 ;; Truly a block
5830 (setq block-type (downcase (match-string 5))
5831 quoting (member block-type org-protecting-blocks))
5832 (when (re-search-forward
5833 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5834 nil t) ;; on purpose, we look further than LIMIT
5835 (setq end (min (point-max) (match-end 0))
5836 end1 (min (point-max) (1- (match-beginning 0))))
5837 (setq block-end (match-beginning 0))
5838 (when quoting
5839 (org-remove-flyspell-overlays-in beg1 end1)
5840 (remove-text-properties beg end
5841 '(display t invisible t intangible t)))
5842 (add-text-properties
5843 beg end '(font-lock-fontified t font-lock-multiline t))
5844 (add-text-properties beg beg1 '(face org-meta-line))
5845 (org-remove-flyspell-overlays-in beg beg1)
5846 (add-text-properties ; For end_src
5847 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5848 (org-remove-flyspell-overlays-in end1 end)
5849 (cond
5850 ((and lang (not (string= lang "")) org-src-fontify-natively)
5851 (org-src-font-lock-fontify-block lang block-start block-end)
5852 (add-text-properties beg1 block-end '(src-block t)))
5853 (quoting
5854 (add-text-properties beg1 (min (point-max) (1+ end1))
5855 '(face org-block))) ; end of source block
5856 ((not org-fontify-quote-and-verse-blocks))
5857 ((string= block-type "quote")
5858 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5859 ((string= block-type "verse")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5861 (add-text-properties beg beg1 '(face org-block-begin-line))
5862 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5863 '(face org-block-end-line))
5865 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5866 (org-remove-flyspell-overlays-in
5867 (match-beginning 0)
5868 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5869 (add-text-properties
5870 beg (match-end 3)
5871 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5872 '(font-lock-fontified t invisible t)
5873 '(font-lock-fontified t face org-document-info-keyword)))
5874 (add-text-properties
5875 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5876 (if (string-equal dc1 "+title:")
5877 '(font-lock-fontified t face org-document-title)
5878 '(font-lock-fontified t face org-document-info))))
5879 ((equal dc1 "+caption:")
5880 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5881 (remove-text-properties (match-beginning 0) (match-end 0)
5882 '(display t invisible t intangible t))
5883 (add-text-properties (match-beginning 1) (match-end 3)
5884 '(font-lock-fontified t face org-meta-line))
5885 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5886 '(font-lock-fontified t face org-block))
5888 ((member dc3 '(" " ""))
5889 (org-remove-flyspell-overlays-in beg (match-end 0))
5890 (add-text-properties
5891 beg (match-end 0)
5892 '(font-lock-fontified t face font-lock-comment-face)))
5893 (t ;; just any other in-buffer setting, but not indented
5894 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5895 (remove-text-properties (match-beginning 0) (match-end 0)
5896 '(display t invisible t intangible t))
5897 (add-text-properties beg (match-end 0)
5898 '(font-lock-fontified t face org-meta-line))
5899 t))))))
5901 (defun org-fontify-drawers (limit)
5902 "Fontify drawers."
5903 (when (re-search-forward org-drawer-regexp limit t)
5904 (add-text-properties
5905 (match-beginning 0) (match-end 0)
5906 '(font-lock-fontified t face org-special-keyword))
5907 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (defun org-fontify-macros (limit)
5911 "Fontify macros."
5912 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5913 (add-text-properties
5914 (match-beginning 0) (match-end 0)
5915 '(font-lock-fontified t face org-macro))
5916 (when org-hide-macro-markers
5917 (add-text-properties (match-end 2) (match-beginning 2)
5918 '(invisible t))
5919 (add-text-properties (match-beginning 1) (match-end 1)
5920 '(invisible t)))
5921 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5924 (defun org-activate-angle-links (limit)
5925 "Add text properties for angle links."
5926 (when (and (re-search-forward org-angle-link-re limit t)
5927 (not (org-in-src-block-p)))
5928 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5929 (add-text-properties (match-beginning 0) (match-end 0)
5930 (list 'mouse-face 'highlight
5931 'keymap org-mouse-map
5932 'font-lock-multiline t))
5933 (org-rear-nonsticky-at (match-end 0))
5936 (defun org-activate-footnote-links (limit)
5937 "Add text properties for footnotes."
5938 (let ((fn (org-footnote-next-reference-or-definition limit)))
5939 (when fn
5940 (let* ((beg (nth 1 fn))
5941 (end (nth 2 fn))
5942 (label (car fn))
5943 (referencep (/= (line-beginning-position) beg)))
5944 (when (and referencep (nth 3 fn))
5945 (save-excursion
5946 (goto-char beg)
5947 (search-forward (or label "fn:"))
5948 (org-remove-flyspell-overlays-in beg (match-end 0))))
5949 (add-text-properties beg end
5950 (list 'mouse-face 'highlight
5951 'keymap org-mouse-map
5952 'help-echo
5953 (if referencep "Footnote reference"
5954 "Footnote definition")
5955 'font-lock-fontified t
5956 'font-lock-multiline t
5957 'face 'org-footnote))))))
5959 (defun org-activate-bracket-links (limit)
5960 "Add text properties for bracketed links."
5961 (when (and (re-search-forward org-bracket-link-regexp limit t)
5962 (not (org-in-src-block-p)))
5963 (let* ((hl (org-match-string-no-properties 1))
5964 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5965 (ip (org-maybe-intangible
5966 (list 'invisible 'org-link
5967 'keymap org-mouse-map 'mouse-face 'highlight
5968 'font-lock-multiline t 'help-echo help
5969 'htmlize-link `(:uri ,hl))))
5970 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5971 'font-lock-multiline t 'help-echo help
5972 'htmlize-link `(:uri ,hl))))
5973 ;; We need to remove the invisible property here. Table narrowing
5974 ;; may have made some of this invisible.
5975 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5976 (remove-text-properties (match-beginning 0) (match-end 0)
5977 '(invisible nil))
5978 (if (match-end 3)
5979 (progn
5980 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5981 (org-rear-nonsticky-at (match-beginning 3))
5982 (add-text-properties (match-beginning 3) (match-end 3) vp)
5983 (org-rear-nonsticky-at (match-end 3))
5984 (add-text-properties (match-end 3) (match-end 0) ip)
5985 (org-rear-nonsticky-at (match-end 0)))
5986 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5987 (org-rear-nonsticky-at (match-beginning 1))
5988 (add-text-properties (match-beginning 1) (match-end 1) vp)
5989 (org-rear-nonsticky-at (match-end 1))
5990 (add-text-properties (match-end 1) (match-end 0) ip)
5991 (org-rear-nonsticky-at (match-end 0)))
5992 t)))
5994 (defun org-activate-dates (limit)
5995 "Add text properties for dates."
5996 (when (and (re-search-forward org-tsr-regexp-both limit t)
5997 (not (equal (char-before (match-beginning 0)) 91)))
5998 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5999 (add-text-properties (match-beginning 0) (match-end 0)
6000 (list 'mouse-face 'highlight
6001 'keymap org-mouse-map))
6002 (org-rear-nonsticky-at (match-end 0))
6003 (when org-display-custom-times
6004 (if (match-end 3)
6005 (org-display-custom-time (match-beginning 3) (match-end 3))
6006 (org-display-custom-time (match-beginning 1) (match-end 1))))
6009 (defvar-local org-target-link-regexp nil
6010 "Regular expression matching radio targets in plain text.")
6012 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6013 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6014 border border border))
6015 "Regular expression matching a link target.")
6017 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6018 "Regular expression matching a radio target.")
6020 (defconst org-any-target-regexp
6021 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6022 "Regular expression matching any target.")
6024 (defun org-activate-target-links (limit)
6025 "Add text properties for target matches."
6026 (when org-target-link-regexp
6027 (let ((case-fold-search t))
6028 (when (re-search-forward org-target-link-regexp limit t)
6029 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6030 (add-text-properties (match-beginning 1) (match-end 1)
6031 (list 'mouse-face 'highlight
6032 'keymap org-mouse-map
6033 'help-echo "Radio target link"
6034 'org-linked-text t))
6035 (org-rear-nonsticky-at (match-end 1))
6036 t))))
6038 (defun org-update-radio-target-regexp ()
6039 "Find all radio targets in this file and update the regular expression.
6040 Also refresh fontification if needed."
6041 (interactive)
6042 (let ((old-regexp org-target-link-regexp)
6043 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6044 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6045 (targets
6046 (org-with-wide-buffer
6047 (goto-char (point-min))
6048 (let (rtn)
6049 (while (re-search-forward org-radio-target-regexp nil t)
6050 ;; Make sure point is really within the object.
6051 (backward-char)
6052 (let ((obj (org-element-context)))
6053 (when (eq (org-element-type obj) 'radio-target)
6054 (cl-pushnew (org-element-property :value obj) rtn
6055 :test #'equal))))
6056 rtn))))
6057 (setq org-target-link-regexp
6058 (and targets
6059 (concat before-re
6060 (mapconcat
6061 (lambda (x)
6062 (replace-regexp-in-string
6063 " +" "\\s-+" (regexp-quote x) t t))
6064 targets
6065 "\\|")
6066 after-re)))
6067 (unless (equal old-regexp org-target-link-regexp)
6068 ;; Clean-up cache.
6069 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6070 ((not org-target-link-regexp) old-regexp)
6072 (concat before-re
6073 (mapconcat
6074 (lambda (re)
6075 (substring re (length before-re)
6076 (- (length after-re))))
6077 (list old-regexp org-target-link-regexp)
6078 "\\|")
6079 after-re)))))
6080 (org-with-wide-buffer
6081 (goto-char (point-min))
6082 (while (re-search-forward regexp nil t)
6083 (org-element-cache-refresh (match-beginning 1)))))
6084 ;; Re fontify buffer.
6085 (when (memq 'radio org-highlight-links)
6086 (org-restart-font-lock)))))
6088 (defun org-hide-wide-columns (limit)
6089 (let (s e)
6090 (setq s (text-property-any (point) (or limit (point-max))
6091 'org-cwidth t))
6092 (when s
6093 (setq e (next-single-property-change s 'org-cwidth))
6094 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6095 (goto-char e)
6096 t)))
6098 (defvar org-latex-and-related-regexp nil
6099 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6101 (defun org-compute-latex-and-related-regexp ()
6102 "Compute regular expression for LaTeX, entities and sub/superscript.
6103 Result depends on variable `org-highlight-latex-and-related'."
6104 (setq-local
6105 org-latex-and-related-regexp
6106 (let* ((re-sub
6107 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6108 ((eq org-use-sub-superscripts '{})
6109 (list org-match-substring-with-braces-regexp))
6110 (org-use-sub-superscripts (list org-match-substring-regexp))))
6111 (re-latex
6112 (when (memq 'latex org-highlight-latex-and-related)
6113 (let ((matchers (plist-get org-format-latex-options :matchers)))
6114 (delq nil
6115 (mapcar (lambda (x)
6116 (and (member (car x) matchers) (nth 1 x)))
6117 org-latex-regexps)))))
6118 (re-entities
6119 (when (memq 'entities org-highlight-latex-and-related)
6120 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6121 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6123 (defun org-do-latex-and-related (limit)
6124 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6125 LIMIT bounds the search for syntax to highlight. Stop at first
6126 highlighted object, if any. Return t if some highlighting was
6127 done, nil otherwise."
6128 (when (org-string-nw-p org-latex-and-related-regexp)
6129 (catch 'found
6130 (while (re-search-forward org-latex-and-related-regexp limit t)
6131 (unless
6132 (cl-some
6133 (lambda (f)
6134 (memq f '(org-code org-verbatim underline org-special-keyword)))
6135 (save-excursion
6136 (goto-char (1+ (match-beginning 0)))
6137 (face-at-point nil t)))
6138 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6139 '(?_ ?^))
6141 0)))
6142 (font-lock-prepend-text-property
6143 (+ offset (match-beginning 0)) (match-end 0)
6144 'face 'org-latex-and-related)
6145 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6146 '(font-lock-multiline t)))
6147 (throw 'found t)))
6148 nil)))
6150 (defun org-restart-font-lock ()
6151 "Restart `font-lock-mode', to force refontification."
6152 (when (and (boundp 'font-lock-mode) font-lock-mode)
6153 (font-lock-mode -1)
6154 (font-lock-mode 1)))
6156 (defun org-activate-tags (limit)
6157 (when (re-search-forward
6158 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6159 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6160 (add-text-properties (match-beginning 1) (match-end 1)
6161 (list 'mouse-face 'highlight
6162 'keymap org-mouse-map))
6163 (org-rear-nonsticky-at (match-end 1))
6166 (defun org-outline-level ()
6167 "Compute the outline level of the heading at point.
6169 If this is called at a normal headline, the level is the number
6170 of stars. Use `org-reduced-level' to remove the effect of
6171 `org-odd-levels'. Unlike to `org-current-level', this function
6172 takes into consideration inlinetasks."
6173 (org-with-wide-buffer
6174 (end-of-line)
6175 (if (re-search-backward org-outline-regexp-bol nil t)
6176 (1- (- (match-end 0) (match-beginning 0)))
6177 0)))
6179 (defvar org-font-lock-keywords nil)
6181 (defsubst org-re-property (property &optional literal allow-null value)
6182 "Return a regexp matching a PROPERTY line.
6184 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6185 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6186 non-nil, match properties even without a value.
6188 Match group 3 is set to the value when it exists. If there is no
6189 value and ALLOW-NULL is non-nil, it is set to the empty string.
6191 With optional argument VALUE, match only property lines with
6192 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6193 unless LITERAL is non-nil."
6194 (concat
6195 "^\\(?4:[ \t]*\\)"
6196 (format "\\(?1::\\(?2:%s\\):\\)"
6197 (if literal property (regexp-quote property)))
6198 (cond (value
6199 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6200 (if literal value (regexp-quote value))))
6201 (allow-null
6202 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6204 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6206 (defconst org-property-re
6207 (org-re-property "\\S-+" 'literal t)
6208 "Regular expression matching a property line.
6209 There are four matching groups:
6210 1: :PROPKEY: including the leading and trailing colon,
6211 2: PROPKEY without the leading and trailing colon,
6212 3: PROPVAL without leading or trailing spaces,
6213 4: the indentation of the current line,
6214 5: trailing whitespace.")
6216 (defvar org-font-lock-hook nil
6217 "Functions to be called for special font lock stuff.")
6219 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6221 (defvar org-font-lock-set-keywords-hook nil
6222 "Functions that can manipulate `org-font-lock-extra-keywords'.
6223 This is called after `org-font-lock-extra-keywords' is defined, but before
6224 it is installed to be used by font lock. This can be useful if something
6225 needs to be inserted at a specific position in the font-lock sequence.")
6227 (defun org-font-lock-hook (limit)
6228 "Run `org-font-lock-hook' within LIMIT."
6229 (run-hook-with-args 'org-font-lock-hook limit))
6231 (defun org-set-font-lock-defaults ()
6232 "Set font lock defaults for the current buffer."
6233 (let* ((em org-fontify-emphasized-text)
6234 (lk org-highlight-links)
6235 (org-font-lock-extra-keywords
6236 (list
6237 ;; Call the hook
6238 '(org-font-lock-hook)
6239 ;; Headlines
6240 `(,(if org-fontify-whole-heading-line
6241 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6242 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6243 (1 (org-get-level-face 1))
6244 (2 (org-get-level-face 2))
6245 (3 (org-get-level-face 3)))
6246 ;; Table lines
6247 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6248 (1 'org-table t))
6249 ;; Table internals
6250 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6251 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6252 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6253 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6254 ;; Drawers
6255 '(org-fontify-drawers)
6256 ;; Properties
6257 (list org-property-re
6258 '(1 'org-special-keyword t)
6259 '(3 'org-property-value t))
6260 ;; Links
6261 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6262 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6263 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6264 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6265 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6266 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6267 (when (memq 'footnote lk) '(org-activate-footnote-links))
6268 ;; Targets.
6269 (list org-any-target-regexp '(0 'org-target t))
6270 ;; Diary sexps.
6271 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6272 ;; Macro
6273 '(org-fontify-macros)
6274 '(org-hide-wide-columns (0 nil append))
6275 ;; TODO keyword
6276 (list (format org-heading-keyword-regexp-format
6277 org-todo-regexp)
6278 '(2 (org-get-todo-face 2) t))
6279 ;; DONE
6280 (if org-fontify-done-headline
6281 (list (format org-heading-keyword-regexp-format
6282 (concat
6283 "\\(?:"
6284 (mapconcat 'regexp-quote org-done-keywords "\\|")
6285 "\\)"))
6286 '(2 'org-headline-done t))
6287 nil)
6288 ;; Priorities
6289 '(org-font-lock-add-priority-faces)
6290 ;; Tags
6291 '(org-font-lock-add-tag-faces)
6292 ;; Tags groups
6293 (when (and org-group-tags org-tag-groups-alist)
6294 (list (concat org-outline-regexp-bol ".+\\(:"
6295 (regexp-opt (mapcar 'car org-tag-groups-alist))
6296 ":\\).*$")
6297 '(1 'org-tag-group prepend)))
6298 ;; Special keywords
6299 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6300 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6301 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6302 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6303 ;; Emphasis
6304 (when em
6305 (if (featurep 'xemacs)
6306 '(org-do-emphasis-faces (0 nil append))
6307 '(org-do-emphasis-faces)))
6308 ;; Checkboxes
6309 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6310 1 'org-checkbox prepend)
6311 (when (cdr (assq 'checkbox org-list-automatic-rules))
6312 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6313 (0 (org-get-checkbox-statistics-face) t)))
6314 ;; Description list items
6315 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6316 1 'org-list-dt prepend)
6317 ;; ARCHIVEd headings
6318 (list (concat
6319 org-outline-regexp-bol
6320 "\\(.*:" org-archive-tag ":.*\\)")
6321 '(1 'org-archived prepend))
6322 ;; Specials
6323 '(org-do-latex-and-related)
6324 '(org-fontify-entities)
6325 '(org-raise-scripts)
6326 ;; Code
6327 '(org-activate-code (1 'org-code t))
6328 ;; COMMENT
6329 (list (format
6330 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6331 org-todo-regexp
6332 org-comment-string)
6333 '(9 'org-special-keyword t))
6334 ;; Blocks and meta lines
6335 '(org-fontify-meta-lines-and-blocks))))
6336 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6337 (run-hooks 'org-font-lock-set-keywords-hook)
6338 ;; Now set the full font-lock-keywords
6339 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6340 (setq-local font-lock-defaults
6341 '(org-font-lock-keywords t nil nil backward-paragraph))
6342 (kill-local-variable 'font-lock-keywords) nil))
6344 (defun org-toggle-pretty-entities ()
6345 "Toggle the composition display of entities as UTF8 characters."
6346 (interactive)
6347 (setq-local org-pretty-entities (not org-pretty-entities))
6348 (org-restart-font-lock)
6349 (if org-pretty-entities
6350 (message "Entities are now displayed as UTF8 characters")
6351 (save-restriction
6352 (widen)
6353 (org-decompose-region (point-min) (point-max))
6354 (message "Entities are now displayed as plain text"))))
6356 (defvar-local org-custom-properties-overlays nil
6357 "List of overlays used for custom properties.")
6359 (defun org-toggle-custom-properties-visibility ()
6360 "Display or hide properties in `org-custom-properties'."
6361 (interactive)
6362 (if org-custom-properties-overlays
6363 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6364 (setq org-custom-properties-overlays nil))
6365 (when org-custom-properties
6366 (org-with-wide-buffer
6367 (goto-char (point-min))
6368 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6369 (while (re-search-forward regexp nil t)
6370 (let ((end (cdr (save-match-data (org-get-property-block)))))
6371 (when (and end (< (point) end))
6372 ;; Hide first custom property in current drawer.
6373 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6374 (overlay-put o 'invisible t)
6375 (overlay-put o 'org-custom-property t)
6376 (push o org-custom-properties-overlays))
6377 ;; Hide additional custom properties in the same drawer.
6378 (while (re-search-forward regexp end t)
6379 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6380 (overlay-put o 'invisible t)
6381 (overlay-put o 'org-custom-property t)
6382 (push o org-custom-properties-overlays)))))
6383 ;; Each entry is limited to a single property drawer.
6384 (outline-next-heading)))))))
6386 (defun org-fontify-entities (limit)
6387 "Find an entity to fontify."
6388 (let (ee)
6389 (when org-pretty-entities
6390 (catch 'match
6391 ;; "\_ "-family is left out on purpose. Only the first one,
6392 ;; i.e., "\_ ", could be fontified anyway, and it would be
6393 ;; confusing when adding a second white space character.
6394 (while (re-search-forward
6395 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6396 limit t)
6397 (when (and (not (org-at-comment-p))
6398 (setq ee (org-entity-get (match-string 1)))
6399 (= (length (nth 6 ee)) 1))
6400 (let* ((end (if (equal (match-string 2) "{}")
6401 (match-end 2)
6402 (match-end 1))))
6403 (add-text-properties
6404 (match-beginning 0) end
6405 (list 'font-lock-fontified t))
6406 (compose-region (match-beginning 0) end
6407 (nth 6 ee) nil)
6408 (backward-char 1)
6409 (throw 'match t))))
6410 nil))))
6412 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6413 "Fontify string S like in Org-mode."
6414 (with-temp-buffer
6415 (insert s)
6416 (let ((org-odd-levels-only odd-levels))
6417 (org-mode)
6418 (org-font-lock-ensure)
6419 (buffer-string))))
6421 (defvar org-m nil)
6422 (defvar org-l nil)
6423 (defvar org-f nil)
6424 (defun org-get-level-face (n)
6425 "Get the right face for match N in font-lock matching of headlines."
6426 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6427 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6428 (if org-cycle-level-faces
6429 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6430 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6431 (cond
6432 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6433 ((eq n 2) org-f)
6434 (t (unless org-level-color-stars-only org-f))))
6436 (defun org-face-from-face-or-color (context inherit face-or-color)
6437 "Create a face list that inherits INHERIT, but sets the foreground color.
6438 When FACE-OR-COLOR is not a string, just return it."
6439 (if (stringp face-or-color)
6440 (list :inherit inherit
6441 (cdr (assoc context org-faces-easy-properties))
6442 face-or-color)
6443 face-or-color))
6445 (defun org-get-todo-face (kwd)
6446 "Get the right face for a TODO keyword KWD.
6447 If KWD is a number, get the corresponding match group."
6448 (when (numberp kwd) (setq kwd (match-string kwd)))
6449 (or (org-face-from-face-or-color
6450 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6451 (and (member kwd org-done-keywords) 'org-done)
6452 'org-todo))
6454 (defun org-get-priority-face (priority)
6455 "Get the right face for PRIORITY.
6456 PRIORITY is a character."
6457 (or (org-face-from-face-or-color
6458 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6459 'org-priority))
6461 (defun org-get-tag-face (tag)
6462 "Get the right face for TAG.
6463 If TAG is a number, get the corresponding match group."
6464 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6465 (or (org-face-from-face-or-color
6466 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6467 'org-tag)))
6469 (defun org-font-lock-add-priority-faces (limit)
6470 "Add the special priority faces."
6471 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6472 (add-text-properties
6473 (match-beginning 1) (match-end 1)
6474 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6475 'font-lock-fontified t))))
6477 (defun org-font-lock-add-tag-faces (limit)
6478 "Add the special tag faces."
6479 (when (and org-tag-faces org-tags-special-faces-re)
6480 (while (re-search-forward org-tags-special-faces-re limit t)
6481 (add-text-properties (match-beginning 1) (match-end 1)
6482 (list 'face (org-get-tag-face 1)
6483 'font-lock-fontified t))
6484 (backward-char 1))))
6486 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6487 "Remove fontification and activation overlays from links."
6488 (font-lock-default-unfontify-region beg end)
6489 (let* ((buffer-undo-list t)
6490 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6491 (inhibit-modification-hooks t)
6492 deactivate-mark buffer-file-name buffer-file-truename)
6493 (org-decompose-region beg end)
6494 (remove-text-properties beg end
6495 '(mouse-face t keymap t org-linked-text t
6496 invisible t intangible t
6497 org-emphasis t))
6498 (org-remove-font-lock-display-properties beg end)))
6500 (defconst org-script-display '(((raise -0.3) (height 0.7))
6501 ((raise 0.3) (height 0.7))
6502 ((raise -0.5))
6503 ((raise 0.5)))
6504 "Display properties for showing superscripts and subscripts.")
6506 (defun org-remove-font-lock-display-properties (beg end)
6507 "Remove specific display properties that have been added by font lock.
6508 The will remove the raise properties that are used to show superscripts
6509 and subscripts."
6510 (let (next prop)
6511 (while (< beg end)
6512 (setq next (next-single-property-change beg 'display nil end)
6513 prop (get-text-property beg 'display))
6514 (when (member prop org-script-display)
6515 (put-text-property beg next 'display nil))
6516 (setq beg next))))
6518 (defun org-raise-scripts (limit)
6519 "Add raise properties to sub/superscripts."
6520 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6521 (re-search-forward
6522 (if (eq org-use-sub-superscripts t)
6523 org-match-substring-regexp
6524 org-match-substring-with-braces-regexp)
6525 limit t))
6526 (let* ((pos (point)) table-p comment-p
6527 (mpos (match-beginning 3))
6528 (emph-p (get-text-property mpos 'org-emphasis))
6529 (link-p (get-text-property mpos 'mouse-face))
6530 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6531 (goto-char (point-at-bol))
6532 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6533 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6534 (goto-char pos)
6535 ;; Handle a_b^c
6536 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6537 (unless (or comment-p emph-p link-p keyw-p)
6538 (put-text-property (match-beginning 3) (match-end 0)
6539 'display
6540 (if (equal (char-after (match-beginning 2)) ?^)
6541 (nth (if table-p 3 1) org-script-display)
6542 (nth (if table-p 2 0) org-script-display)))
6543 (add-text-properties (match-beginning 2) (match-end 2)
6544 (list 'invisible t
6545 'org-dwidth t 'org-dwidth-n 1))
6546 (if (and (eq (char-after (match-beginning 3)) ?{)
6547 (eq (char-before (match-end 3)) ?}))
6548 (progn
6549 (add-text-properties
6550 (match-beginning 3) (1+ (match-beginning 3))
6551 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6552 (add-text-properties
6553 (1- (match-end 3)) (match-end 3)
6554 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6555 t)))
6557 ;;;; Visibility cycling, including org-goto and indirect buffer
6559 ;;; Cycling
6561 (defvar-local org-cycle-global-status nil)
6562 (put 'org-cycle-global-status 'org-state t)
6563 (defvar-local org-cycle-subtree-status nil)
6564 (put 'org-cycle-subtree-status 'org-state t)
6566 (defvar org-inlinetask-min-level)
6568 (defun org-unlogged-message (&rest args)
6569 "Display a message, but avoid logging it in the *Messages* buffer."
6570 (let ((message-log-max nil))
6571 (apply 'message args)))
6573 ;;;###autoload
6574 (defun org-cycle (&optional arg)
6575 "TAB-action and visibility cycling for Org-mode.
6577 This is the command invoked in Org-mode by the TAB key. Its main purpose
6578 is outline visibility cycling, but it also invokes other actions
6579 in special contexts.
6581 - When this function is called with a prefix argument, rotate the entire
6582 buffer through 3 states (global cycling)
6583 1. OVERVIEW: Show only top-level headlines.
6584 2. CONTENTS: Show all headlines of all levels, but no body text.
6585 3. SHOW ALL: Show everything.
6586 With a double \\[universal-argument] prefix argument, \
6587 switch to the startup visibility,
6588 determined by the variable `org-startup-folded', and by any VISIBILITY
6589 properties in the buffer.
6590 With a triple \\[universal-argument] prefix argument, \
6591 show the entire buffer, including any drawers.
6593 - When inside a table, re-align the table and move to the next field.
6595 - When point is at the beginning of a headline, rotate the subtree started
6596 by this line through 3 different states (local cycling)
6597 1. FOLDED: Only the main headline is shown.
6598 2. CHILDREN: The main headline and the direct children are shown.
6599 From this state, you can move to one of the children
6600 and zoom in further.
6601 3. SUBTREE: Show the entire subtree, including body text.
6602 If there is no subtree, switch directly from CHILDREN to FOLDED.
6604 - When point is at the beginning of an empty headline and the variable
6605 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6606 of the headline by demoting and promoting it to likely levels. This
6607 speeds up creation document structure by pressing TAB once or several
6608 times right after creating a new headline.
6610 - When there is a numeric prefix, go up to a heading with level ARG, do
6611 a `show-subtree' and return to the previous cursor position. If ARG
6612 is negative, go up that many levels.
6614 - When point is not at the beginning of a headline, execute the global
6615 binding for TAB, which is re-indenting the line. See the option
6616 `org-cycle-emulate-tab' for details.
6618 - Special case: if point is at the beginning of the buffer and there is
6619 no headline in line 1, this function will act as if called with prefix arg
6620 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6621 But only if also the variable `org-cycle-global-at-bob' is t."
6622 (interactive "P")
6623 (org-load-modules-maybe)
6624 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6625 (and org-cycle-level-after-item/entry-creation
6626 (or (org-cycle-level)
6627 (org-cycle-item-indentation))))
6628 (let* ((limit-level
6629 (or org-cycle-max-level
6630 (and (boundp 'org-inlinetask-min-level)
6631 org-inlinetask-min-level
6632 (1- org-inlinetask-min-level))))
6633 (nstars (and limit-level
6634 (if org-odd-levels-only
6635 (and limit-level (1- (* limit-level 2)))
6636 limit-level)))
6637 (org-outline-regexp
6638 (if (not (derived-mode-p 'org-mode))
6639 outline-regexp
6640 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6641 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6642 (not (looking-at org-outline-regexp))))
6643 (org-cycle-hook
6644 (if bob-special
6645 (delq 'org-optimize-window-after-visibility-change
6646 (copy-sequence org-cycle-hook))
6647 org-cycle-hook))
6648 (pos (point)))
6650 (when (or bob-special (equal arg '(4)))
6651 ;; special case: use global cycling
6652 (setq arg t))
6654 (cond
6656 ((equal arg '(16))
6657 (setq last-command 'dummy)
6658 (org-set-startup-visibility)
6659 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6661 ((equal arg '(64))
6662 (outline-show-all)
6663 (org-unlogged-message "Entire buffer visible, including drawers"))
6665 ;; Try cdlatex TAB completion
6666 ((org-try-cdlatex-tab))
6668 ;; Table: enter it or move to the next field.
6669 ((org-at-table-p 'any)
6670 (if (org-at-table.el-p)
6671 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6672 Use \\[org-edit-special] to edit table.el tables"))
6673 (if arg (org-table-edit-field t)
6674 (org-table-justify-field-maybe)
6675 (call-interactively 'org-table-next-field))))
6677 ((run-hook-with-args-until-success
6678 'org-tab-after-check-for-table-hook))
6680 ;; Global cycling: delegate to `org-cycle-internal-global'.
6681 ((eq arg t) (org-cycle-internal-global))
6683 ;; Drawers: delegate to `org-flag-drawer'.
6684 ((save-excursion
6685 (beginning-of-line 1)
6686 (looking-at org-drawer-regexp))
6687 (org-flag-drawer ; toggle block visibility
6688 (not (get-char-property (match-end 0) 'invisible))))
6690 ;; Show-subtree, ARG levels up from here.
6691 ((integerp arg)
6692 (save-excursion
6693 (org-back-to-heading)
6694 (outline-up-heading (if (< arg 0) (- arg)
6695 (- (funcall outline-level) arg)))
6696 (org-show-subtree)))
6698 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6699 ((and (featurep 'org-inlinetask)
6700 (org-inlinetask-at-task-p)
6701 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6702 (org-inlinetask-toggle-visibility))
6704 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6705 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6706 (save-excursion (move-beginning-of-line 1)
6707 (looking-at org-outline-regexp)))
6708 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6709 (org-cycle-internal-local))
6711 ;; From there: TAB emulation and template completion.
6712 (buffer-read-only (org-back-to-heading))
6714 ((run-hook-with-args-until-success
6715 'org-tab-after-check-for-cycling-hook))
6717 ((org-try-structure-completion))
6719 ((run-hook-with-args-until-success
6720 'org-tab-before-tab-emulation-hook))
6722 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6723 (or (not (bolp))
6724 (not (looking-at org-outline-regexp))))
6725 (call-interactively (global-key-binding "\t")))
6727 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6728 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6729 (or (and (eq org-cycle-emulate-tab 'white)
6730 (= (match-end 0) (point-at-eol)))
6731 (and (eq org-cycle-emulate-tab 'whitestart)
6732 (>= (match-end 0) pos))))
6734 (eq org-cycle-emulate-tab t))
6735 (call-interactively (global-key-binding "\t")))
6737 (t (save-excursion
6738 (org-back-to-heading)
6739 (org-cycle)))))))
6741 (defun org-cycle-internal-global ()
6742 "Do the global cycling action."
6743 ;; Hack to avoid display of messages for .org attachments in Gnus
6744 (let ((ga (string-match "\\*fontification" (buffer-name))))
6745 (cond
6746 ((and (eq last-command this-command)
6747 (eq org-cycle-global-status 'overview))
6748 ;; We just created the overview - now do table of contents
6749 ;; This can be slow in very large buffers, so indicate action
6750 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6751 (unless ga (org-unlogged-message "CONTENTS..."))
6752 (org-content)
6753 (unless ga (org-unlogged-message "CONTENTS...done"))
6754 (setq org-cycle-global-status 'contents)
6755 (run-hook-with-args 'org-cycle-hook 'contents))
6757 ((and (eq last-command this-command)
6758 (eq org-cycle-global-status 'contents))
6759 ;; We just showed the table of contents - now show everything
6760 (run-hook-with-args 'org-pre-cycle-hook 'all)
6761 (outline-show-all)
6762 (unless ga (org-unlogged-message "SHOW ALL"))
6763 (setq org-cycle-global-status 'all)
6764 (run-hook-with-args 'org-cycle-hook 'all))
6767 ;; Default action: go to overview
6768 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6769 (org-overview)
6770 (unless ga (org-unlogged-message "OVERVIEW"))
6771 (setq org-cycle-global-status 'overview)
6772 (run-hook-with-args 'org-cycle-hook 'overview)))))
6774 (defvar org-called-with-limited-levels nil
6775 "Non-nil when `org-with-limited-levels' is currently active.")
6777 (defun org-cycle-internal-local ()
6778 "Do the local cycling action."
6779 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6780 ;; First, determine end of headline (EOH), end of subtree or item
6781 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6782 (save-excursion
6783 (if (org-at-item-p)
6784 (progn
6785 (beginning-of-line)
6786 (setq struct (org-list-struct))
6787 (setq eoh (point-at-eol))
6788 (setq eos (org-list-get-item-end-before-blank (point) struct))
6789 (setq has-children (org-list-has-child-p (point) struct)))
6790 (org-back-to-heading)
6791 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6792 (setq eos (save-excursion (org-end-of-subtree t t)
6793 (when (bolp) (backward-char)) (point)))
6794 (setq has-children
6795 (or (save-excursion
6796 (let ((level (funcall outline-level)))
6797 (outline-next-heading)
6798 (and (org-at-heading-p t)
6799 (> (funcall outline-level) level))))
6800 (save-excursion
6801 (org-list-search-forward (org-item-beginning-re) eos t)))))
6802 ;; Determine end invisible part of buffer (EOL)
6803 (beginning-of-line 2)
6804 ;; XEmacs doesn't have `next-single-char-property-change'
6805 (if (featurep 'xemacs)
6806 (while (and (not (eobp)) ;; this is like `next-line'
6807 (get-char-property (1- (point)) 'invisible))
6808 (beginning-of-line 2))
6809 (while (and (not (eobp)) ;; this is like `next-line'
6810 (get-char-property (1- (point)) 'invisible))
6811 (goto-char (next-single-char-property-change (point) 'invisible))
6812 (and (eolp) (beginning-of-line 2))))
6813 (setq eol (point)))
6814 ;; Find out what to do next and set `this-command'
6815 (cond
6816 ((= eos eoh)
6817 ;; Nothing is hidden behind this heading
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6820 (org-unlogged-message "EMPTY ENTRY")
6821 (setq org-cycle-subtree-status nil)
6822 (save-excursion
6823 (goto-char eos)
6824 (outline-next-heading)
6825 (when (outline-invisible-p) (org-flag-heading nil))))
6826 ((and (or (>= eol eos)
6827 (not (string-match "\\S-" (buffer-substring eol eos))))
6828 (or has-children
6829 (not (setq children-skipped
6830 org-cycle-skip-children-state-if-no-children))))
6831 ;; Entire subtree is hidden in one line: children view
6832 (unless (org-before-first-heading-p)
6833 (run-hook-with-args 'org-pre-cycle-hook 'children))
6834 (if (org-at-item-p)
6835 (org-list-set-item-visibility (point-at-bol) struct 'children)
6836 (org-show-entry)
6837 (org-with-limited-levels (org-show-children))
6838 ;; FIXME: This slows down the func way too much.
6839 ;; How keep drawers hidden in subtree anyway?
6840 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6841 ;; (org-cycle-hide-drawers 'subtree))
6843 ;; Fold every list in subtree to top-level items.
6844 (when (eq org-cycle-include-plain-lists 'integrate)
6845 (save-excursion
6846 (org-back-to-heading)
6847 (while (org-list-search-forward (org-item-beginning-re) eos t)
6848 (beginning-of-line 1)
6849 (let* ((struct (org-list-struct))
6850 (prevs (org-list-prevs-alist struct))
6851 (end (org-list-get-bottom-point struct)))
6852 (dolist (e (org-list-get-all-items (point) struct prevs))
6853 (org-list-set-item-visibility e struct 'folded))
6854 (goto-char (if (< end eos) end eos)))))))
6855 (org-unlogged-message "CHILDREN")
6856 (save-excursion
6857 (goto-char eos)
6858 (outline-next-heading)
6859 (when (outline-invisible-p) (org-flag-heading nil)))
6860 (setq org-cycle-subtree-status 'children)
6861 (unless (org-before-first-heading-p)
6862 (run-hook-with-args 'org-cycle-hook 'children)))
6863 ((or children-skipped
6864 (and (eq last-command this-command)
6865 (eq org-cycle-subtree-status 'children)))
6866 ;; We just showed the children, or no children are there,
6867 ;; now show everything.
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6870 (outline-flag-region eoh eos nil)
6871 (org-unlogged-message
6872 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6873 (setq org-cycle-subtree-status 'subtree)
6874 (unless (org-before-first-heading-p)
6875 (run-hook-with-args 'org-cycle-hook 'subtree)))
6877 ;; Default action: hide the subtree.
6878 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6879 (outline-flag-region eoh eos t)
6880 (org-unlogged-message "FOLDED")
6881 (setq org-cycle-subtree-status 'folded)
6882 (unless (org-before-first-heading-p)
6883 (run-hook-with-args 'org-cycle-hook 'folded))))))
6885 ;;;###autoload
6886 (defun org-global-cycle (&optional arg)
6887 "Cycle the global visibility. For details see `org-cycle'.
6888 With \\[universal-argument] prefix arg, switch to startup visibility.
6889 With a numeric prefix, show all headlines up to that level."
6890 (interactive "P")
6891 (let ((org-cycle-include-plain-lists
6892 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6893 (cond
6894 ((integerp arg)
6895 (outline-show-all)
6896 (outline-hide-sublevels arg)
6897 (setq org-cycle-global-status 'contents))
6898 ((equal arg '(4))
6899 (org-set-startup-visibility)
6900 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6902 (org-cycle '(4))))))
6904 (defun org-set-startup-visibility ()
6905 "Set the visibility required by startup options and properties."
6906 (cond
6907 ((eq org-startup-folded t)
6908 (org-overview))
6909 ((eq org-startup-folded 'content)
6910 (org-content))
6911 ((or (eq org-startup-folded 'showeverything)
6912 (eq org-startup-folded nil))
6913 (outline-show-all)))
6914 (unless (eq org-startup-folded 'showeverything)
6915 (when org-hide-block-startup (org-hide-block-all))
6916 (org-set-visibility-according-to-property 'no-cleanup)
6917 (org-cycle-hide-archived-subtrees 'all)
6918 (org-cycle-hide-drawers 'all)
6919 (org-cycle-show-empty-lines t)))
6921 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6922 "Switch subtree visibilities according to :VISIBILITY: property."
6923 (interactive)
6924 (org-with-wide-buffer
6925 (goto-char (point-min))
6926 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6927 (if (not (org-at-property-p)) (outline-next-heading)
6928 (let ((state (match-string 3)))
6929 (save-excursion
6930 (org-back-to-heading t)
6931 (outline-hide-subtree)
6932 (org-reveal)
6933 (cond
6934 ((equal state "folded")
6935 (outline-hide-subtree))
6936 ((equal state "children")
6937 (org-show-hidden-entry)
6938 (org-show-children))
6939 ((equal state "content")
6940 (save-excursion
6941 (save-restriction
6942 (org-narrow-to-subtree)
6943 (org-content))))
6944 ((member state '("all" "showall"))
6945 (outline-show-subtree)))))))
6946 (unless no-cleanup
6947 (org-cycle-hide-archived-subtrees 'all)
6948 (org-cycle-hide-drawers 'all)
6949 (org-cycle-show-empty-lines 'all))))
6951 ;; This function uses outline-regexp instead of the more fundamental
6952 ;; org-outline-regexp so that org-cycle-global works outside of Org
6953 ;; buffers, where outline-regexp is needed.
6954 (defun org-overview ()
6955 "Switch to overview mode, showing only top-level headlines.
6956 This shows all headlines with a level equal or greater than the level
6957 of the first headline in the buffer. This is important, because if the
6958 first headline is not level one, then (hide-sublevels 1) gives confusing
6959 results."
6960 (interactive)
6961 (save-excursion
6962 (let ((level
6963 (save-excursion
6964 (goto-char (point-min))
6965 (when (re-search-forward (concat "^" outline-regexp) nil t)
6966 (goto-char (match-beginning 0))
6967 (funcall outline-level)))))
6968 (and level (outline-hide-sublevels level)))))
6970 (defun org-content (&optional arg)
6971 "Show all headlines in the buffer, like a table of contents.
6972 With numerical argument N, show content up to level N."
6973 (interactive "P")
6974 (org-overview)
6975 (save-excursion
6976 ;; Visit all headings and show their offspring
6977 (and (integerp arg) (org-overview))
6978 (goto-char (point-max))
6979 (catch 'exit
6980 (while (and (progn (condition-case nil
6981 (outline-previous-visible-heading 1)
6982 (error (goto-char (point-min))))
6984 (looking-at org-outline-regexp))
6985 (if (integerp arg)
6986 (org-show-children (1- arg))
6987 (outline-show-branches))
6988 (when (bobp) (throw 'exit nil))))))
6990 (defun org-optimize-window-after-visibility-change (state)
6991 "Adjust the window after a change in outline visibility.
6992 This function is the default value of the hook `org-cycle-hook'."
6993 (when (get-buffer-window (current-buffer))
6994 (cond
6995 ((eq state 'content) nil)
6996 ((eq state 'all) nil)
6997 ((eq state 'folded) nil)
6998 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6999 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7001 (defun org-remove-empty-overlays-at (pos)
7002 "Remove outline overlays that do not contain non-white stuff."
7003 (dolist (o (overlays-at pos))
7004 (and (eq 'outline (overlay-get o 'invisible))
7005 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7006 (overlay-end o))))
7007 (delete-overlay o))))
7009 (defun org-clean-visibility-after-subtree-move ()
7010 "Fix visibility issues after moving a subtree."
7011 ;; First, find a reasonable region to look at:
7012 ;; Start two siblings above, end three below
7013 (let* ((beg (save-excursion
7014 (and (org-get-last-sibling)
7015 (org-get-last-sibling))
7016 (point)))
7017 (end (save-excursion
7018 (and (org-get-next-sibling)
7019 (org-get-next-sibling)
7020 (org-get-next-sibling))
7021 (if (org-at-heading-p)
7022 (point-at-eol)
7023 (point))))
7024 (level (looking-at "\\*+"))
7025 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7026 (save-excursion
7027 (save-restriction
7028 (narrow-to-region beg end)
7029 (when re
7030 ;; Properly fold already folded siblings
7031 (goto-char (point-min))
7032 (while (re-search-forward re nil t)
7033 (when (and (not (outline-invisible-p))
7034 (save-excursion
7035 (goto-char (point-at-eol)) (outline-invisible-p)))
7036 (outline-hide-entry))))
7037 (org-cycle-show-empty-lines 'overview)
7038 (org-cycle-hide-drawers 'overview)))))
7040 (defun org-cycle-show-empty-lines (state)
7041 "Show empty lines above all visible headlines.
7042 The region to be covered depends on STATE when called through
7043 `org-cycle-hook'. Lisp program can use t for STATE to get the
7044 entire buffer covered. Note that an empty line is only shown if there
7045 are at least `org-cycle-separator-lines' empty lines before the headline."
7046 (when (/= org-cycle-separator-lines 0)
7047 (save-excursion
7048 (let* ((n (abs org-cycle-separator-lines))
7049 (re (cond
7050 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7051 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7052 (t (let ((ns (number-to-string (- n 2))))
7053 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7054 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7055 beg end)
7056 (cond
7057 ((memq state '(overview contents t))
7058 (setq beg (point-min) end (point-max)))
7059 ((memq state '(children folded))
7060 (setq beg (point)
7061 end (progn (org-end-of-subtree t t)
7062 (line-beginning-position 2)))))
7063 (when beg
7064 (goto-char beg)
7065 (while (re-search-forward re end t)
7066 (unless (get-char-property (match-end 1) 'invisible)
7067 (let ((e (match-end 1))
7068 (b (if (>= org-cycle-separator-lines 0)
7069 (match-beginning 1)
7070 (save-excursion
7071 (goto-char (match-beginning 0))
7072 (skip-chars-backward " \t\n")
7073 (line-end-position)))))
7074 (outline-flag-region b e nil))))))))
7075 ;; Never hide empty lines at the end of the file.
7076 (save-excursion
7077 (goto-char (point-max))
7078 (outline-previous-heading)
7079 (outline-end-of-heading)
7080 (when (and (looking-at "[ \t\n]+")
7081 (= (match-end 0) (point-max)))
7082 (outline-flag-region (point) (match-end 0) nil))))
7084 (defun org-show-empty-lines-in-parent ()
7085 "Move to the parent and re-show empty lines before visible headlines."
7086 (save-excursion
7087 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7088 (org-cycle-show-empty-lines context))))
7090 (defun org-files-list ()
7091 "Return `org-agenda-files' list, plus all open org-mode files.
7092 This is useful for operations that need to scan all of a user's
7093 open and agenda-wise Org files."
7094 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7095 (dolist (buf (buffer-list))
7096 (with-current-buffer buf
7097 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7098 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7099 files))
7101 (defsubst org-entry-beginning-position ()
7102 "Return the beginning position of the current entry."
7103 (save-excursion (org-back-to-heading t) (point)))
7105 (defsubst org-entry-end-position ()
7106 "Return the end position of the current entry."
7107 (save-excursion (outline-next-heading) (point)))
7109 (defun org-cycle-hide-drawers (state &optional exceptions)
7110 "Re-hide all drawers after a visibility state change.
7111 When non-nil, optional argument EXCEPTIONS is a list of strings
7112 specifying which drawers should not be hidden."
7113 (when (and (derived-mode-p 'org-mode)
7114 (not (memq state '(overview folded contents))))
7115 (save-excursion
7116 (let* ((globalp (memq state '(contents all)))
7117 (beg (if globalp (point-min) (point)))
7118 (end (if globalp (point-max)
7119 (if (eq state 'children)
7120 (save-excursion (outline-next-heading) (point))
7121 (org-end-of-subtree t)))))
7122 (goto-char beg)
7123 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7124 (unless (member-ignore-case (match-string 1) exceptions)
7125 (let ((drawer (org-element-at-point)))
7126 (when (memq (org-element-type drawer) '(drawer property-drawer))
7127 (org-flag-drawer t drawer)
7128 ;; Make sure to skip drawer entirely or we might flag
7129 ;; it another time when matching its ending line with
7130 ;; `org-drawer-regexp'.
7131 (goto-char (org-element-property :end drawer))))))))))
7133 (defun org-flag-drawer (flag &optional element)
7134 "When FLAG is non-nil, hide the drawer we are at.
7135 Otherwise make it visible. When optional argument ELEMENT is
7136 a parsed drawer, as returned by `org-element-at-point', hide or
7137 show that drawer instead."
7138 (when (save-excursion
7139 (beginning-of-line)
7140 (org-looking-at-p org-drawer-regexp))
7141 (let ((drawer (or element (org-element-at-point))))
7142 (when (memq (org-element-type drawer) '(drawer property-drawer))
7143 (let ((post (org-element-property :post-affiliated drawer)))
7144 (save-excursion
7145 (outline-flag-region
7146 (progn (goto-char post) (line-end-position))
7147 (progn (goto-char (org-element-property :end drawer))
7148 (skip-chars-backward " \r\t\n")
7149 (line-end-position))
7150 flag))
7151 ;; When the drawer is hidden away, make sure point lies in
7152 ;; a visible part of the buffer.
7153 (when (and flag (> (line-beginning-position) post))
7154 (goto-char post)))))))
7156 (defun org-subtree-end-visible-p ()
7157 "Is the end of the current subtree visible?"
7158 (pos-visible-in-window-p
7159 (save-excursion (org-end-of-subtree t) (point))))
7161 (defun org-first-headline-recenter ()
7162 "Move cursor to the first headline and recenter the headline."
7163 (goto-char (point-min))
7164 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7165 (set-window-start (selected-window) (point-at-bol))))
7167 ;;; Saving and restoring visibility
7169 (defun org-outline-overlay-data (&optional use-markers)
7170 "Return a list of the locations of all outline overlays.
7171 These are overlays with the `invisible' property value `outline'.
7172 The return value is a list of cons cells, with start and stop
7173 positions for each overlay.
7174 If USE-MARKERS is set, return the positions as markers."
7175 (let (beg end)
7176 (save-excursion
7177 (save-restriction
7178 (widen)
7179 (delq nil
7180 (mapcar (lambda (o)
7181 (when (eq (overlay-get o 'invisible) 'outline)
7182 (setq beg (overlay-start o)
7183 end (overlay-end o))
7184 (and beg end (> end beg)
7185 (if use-markers
7186 (cons (copy-marker beg)
7187 (copy-marker end t))
7188 (cons beg end)))))
7189 (overlays-in (point-min) (point-max))))))))
7191 (defun org-set-outline-overlay-data (data)
7192 "Create visibility overlays for all positions in DATA.
7193 DATA should have been made by `org-outline-overlay-data'."
7194 (org-with-wide-buffer
7195 (outline-show-all)
7196 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7198 ;;; Folding of blocks
7200 (defvar-local org-hide-block-overlays nil
7201 "Overlays hiding blocks.")
7203 (defun org-block-map (function &optional start end)
7204 "Call FUNCTION at the head of all source blocks in the current buffer.
7205 Optional arguments START and END can be used to limit the range."
7206 (let ((start (or start (point-min)))
7207 (end (or end (point-max))))
7208 (save-excursion
7209 (goto-char start)
7210 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7211 (save-excursion
7212 (save-match-data
7213 (goto-char (match-beginning 0))
7214 (funcall function)))))))
7216 (defun org-hide-block-toggle-all ()
7217 "Toggle the visibility of all blocks in the current buffer."
7218 (org-block-map 'org-hide-block-toggle))
7220 (defun org-hide-block-all ()
7221 "Fold all blocks in the current buffer."
7222 (interactive)
7223 (org-show-block-all)
7224 (org-block-map 'org-hide-block-toggle-maybe))
7226 (defun org-show-block-all ()
7227 "Unfold all blocks in the current buffer."
7228 (interactive)
7229 (mapc #'delete-overlay org-hide-block-overlays)
7230 (setq org-hide-block-overlays nil))
7232 (defun org-hide-block-toggle-maybe ()
7233 "Toggle visibility of block at point.
7234 Unlike to `org-hide-block-toggle', this function does not throw
7235 an error. Return a non-nil value when toggling is successful."
7236 (interactive)
7237 (ignore-errors (org-hide-block-toggle)))
7239 (defun org-hide-block-toggle (&optional force)
7240 "Toggle the visibility of the current block.
7241 When optional argument FORCE is `off', make block visible. If it
7242 is non-nil, hide it unconditionally. Throw an error when not at
7243 a block. Return a non-nil value when toggling is successful."
7244 (interactive)
7245 (let ((element (org-element-at-point)))
7246 (unless (memq (org-element-type element)
7247 '(center-block comment-block dynamic-block example-block
7248 export-block quote-block special-block
7249 src-block verse-block))
7250 (user-error "Not at a block"))
7251 (let* ((start (save-excursion
7252 (goto-char (org-element-property :post-affiliated element))
7253 (line-end-position)))
7254 (end (save-excursion
7255 (goto-char (org-element-property :end element))
7256 (skip-chars-backward " \r\t\n")
7257 (line-end-position)))
7258 (overlays (overlays-at start)))
7259 (cond
7260 ;; Do nothing when not before or at the block opening line or
7261 ;; at the block closing line.
7262 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7263 ((and (not (eq force 'off))
7264 (not (memq t (mapcar
7265 (lambda (o)
7266 (eq (overlay-get o 'invisible) 'org-hide-block))
7267 overlays))))
7268 (let ((ov (make-overlay start end)))
7269 (overlay-put ov 'invisible 'org-hide-block)
7270 ;; Make the block accessible to `isearch'.
7271 (overlay-put
7272 ov 'isearch-open-invisible
7273 (lambda (ov)
7274 (when (memq ov org-hide-block-overlays)
7275 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7276 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7277 (delete-overlay ov))))
7278 (push ov org-hide-block-overlays)
7279 ;; When the block is hidden away, make sure point is left in
7280 ;; a visible part of the buffer.
7281 (when (> (line-beginning-position) start)
7282 (goto-char start)
7283 (beginning-of-line))
7284 ;; Signal successful toggling.
7286 ((or (not force) (eq force 'off))
7287 (dolist (ov overlays t)
7288 (when (memq ov org-hide-block-overlays)
7289 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7290 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7291 (delete-overlay ov))))))))
7293 ;; org-tab-after-check-for-cycling-hook
7294 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7295 ;; Remove overlays when changing major mode
7296 (add-hook 'org-mode-hook
7297 (lambda () (org-add-hook 'change-major-mode-hook
7298 'org-show-block-all 'append 'local)))
7300 ;;; Org-goto
7302 (defvar org-goto-window-configuration nil)
7303 (defvar org-goto-marker nil)
7304 (defvar org-goto-map)
7305 (defun org-goto-map ()
7306 "Set the keymap `org-goto'."
7307 (setq org-goto-map
7308 (let ((map (make-sparse-keymap)))
7309 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7310 mouse-drag-region universal-argument org-occur)))
7311 (dolist (cmd cmds)
7312 (substitute-key-definition cmd cmd map global-map)))
7313 (suppress-keymap map)
7314 (org-defkey map "\C-m" 'org-goto-ret)
7315 (org-defkey map [(return)] 'org-goto-ret)
7316 (org-defkey map [(left)] 'org-goto-left)
7317 (org-defkey map [(right)] 'org-goto-right)
7318 (org-defkey map [(control ?g)] 'org-goto-quit)
7319 (org-defkey map "\C-i" 'org-cycle)
7320 (org-defkey map [(tab)] 'org-cycle)
7321 (org-defkey map [(down)] 'outline-next-visible-heading)
7322 (org-defkey map [(up)] 'outline-previous-visible-heading)
7323 (if org-goto-auto-isearch
7324 (if (fboundp 'define-key-after)
7325 (define-key-after map [t] 'org-goto-local-auto-isearch)
7326 nil)
7327 (org-defkey map "q" 'org-goto-quit)
7328 (org-defkey map "n" 'outline-next-visible-heading)
7329 (org-defkey map "p" 'outline-previous-visible-heading)
7330 (org-defkey map "f" 'outline-forward-same-level)
7331 (org-defkey map "b" 'outline-backward-same-level)
7332 (org-defkey map "u" 'outline-up-heading))
7333 (org-defkey map "/" 'org-occur)
7334 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7335 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7336 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7337 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7338 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7339 map)))
7341 (defconst org-goto-help
7342 "Browse buffer copy, to find location or copy text.%s
7343 RET=jump to location C-g=quit and return to previous location
7344 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7346 (defvar org-goto-start-pos) ; dynamically scoped parameter
7348 (defun org-goto (&optional alternative-interface)
7349 "Look up a different location in the current file, keeping current visibility.
7351 When you want look-up or go to a different location in a
7352 document, the fastest way is often to fold the entire buffer and
7353 then dive into the tree. This method has the disadvantage, that
7354 the previous location will be folded, which may not be what you
7355 want.
7357 This command works around this by showing a copy of the current
7358 buffer in an indirect buffer, in overview mode. You can dive
7359 into the tree in that copy, use org-occur and incremental search
7360 to find a location. When pressing RET or `Q', the command
7361 returns to the original buffer in which the visibility is still
7362 unchanged. After RET it will also jump to the location selected
7363 in the indirect buffer and expose the headline hierarchy above.
7365 With a prefix argument, use the alternative interface: e.g., if
7366 `org-goto-interface' is `outline' use `outline-path-completion'."
7367 (interactive "P")
7368 (org-goto-map)
7369 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7370 (org-refile-use-outline-path t)
7371 (org-refile-target-verify-function nil)
7372 (interface
7373 (if (not alternative-interface)
7374 org-goto-interface
7375 (if (eq org-goto-interface 'outline)
7376 'outline-path-completion
7377 'outline)))
7378 (org-goto-start-pos (point))
7379 (selected-point
7380 (if (eq interface 'outline)
7381 (car (org-get-location (current-buffer) org-goto-help))
7382 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7383 (org-refile-check-position pa)
7384 (nth 3 pa)))))
7385 (if selected-point
7386 (progn
7387 (org-mark-ring-push org-goto-start-pos)
7388 (goto-char selected-point)
7389 (when (or (outline-invisible-p) (org-invisible-p2))
7390 (org-show-context 'org-goto)))
7391 (message "Quit"))))
7393 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7394 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7395 (defvar org-goto-local-auto-isearch-map) ; defined below
7397 (defun org-get-location (_buf help)
7398 "Let the user select a location in current buffer.
7399 This function uses a recursive edit. It returns the selected position
7400 or nil."
7401 (org-no-popups
7402 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7403 (isearch-hide-immediately nil)
7404 (isearch-search-fun-function
7405 (lambda () 'org-goto-local-search-headings))
7406 (org-goto-selected-point org-goto-exit-command))
7407 (save-excursion
7408 (save-window-excursion
7409 (delete-other-windows)
7410 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7411 (org-pop-to-buffer-same-window
7412 (condition-case nil
7413 (make-indirect-buffer (current-buffer) "*org-goto*")
7414 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7415 (with-output-to-temp-buffer "*Org Help*"
7416 (princ (format help (if org-goto-auto-isearch
7417 " Just type for auto-isearch."
7418 " n/p/f/b/u to navigate, q to quit."))))
7419 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7420 (setq buffer-read-only nil)
7421 (let ((org-startup-truncated t)
7422 (org-startup-folded nil)
7423 (org-startup-align-all-tables nil))
7424 (org-mode)
7425 (org-overview))
7426 (setq buffer-read-only t)
7427 (if (and (boundp 'org-goto-start-pos)
7428 (integer-or-marker-p org-goto-start-pos))
7429 (progn (goto-char org-goto-start-pos)
7430 (when (outline-invisible-p)
7431 (org-show-set-visibility 'lineage)))
7432 (goto-char (point-min)))
7433 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7434 (message "Select location and press RET")
7435 (use-local-map org-goto-map)
7436 (recursive-edit)))
7437 (kill-buffer "*org-goto*")
7438 (cons org-goto-selected-point org-goto-exit-command))))
7440 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7441 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7442 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7443 (if (fboundp 'isearch-other-control-char)
7444 (progn
7445 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7446 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7447 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7448 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7449 (define-key org-goto-local-auto-isearch-map [return] nil))
7451 (defun org-goto-local-search-headings (string bound noerror)
7452 "Search and make sure that any matches are in headlines."
7453 (catch 'return
7454 (while (if isearch-forward
7455 (search-forward string bound noerror)
7456 (search-backward string bound noerror))
7457 (when (save-match-data
7458 (and (save-excursion
7459 (beginning-of-line)
7460 (looking-at org-complex-heading-regexp))
7461 (or (not (match-beginning 5))
7462 (< (point) (match-beginning 5)))))
7463 (throw 'return (point))))))
7465 (defun org-goto-local-auto-isearch ()
7466 "Start isearch."
7467 (interactive)
7468 (goto-char (point-min))
7469 (let ((keys (this-command-keys)))
7470 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7471 (isearch-mode t)
7472 (isearch-process-search-char (string-to-char keys)))))
7474 (defun org-goto-ret (&optional _arg)
7475 "Finish `org-goto' by going to the new location."
7476 (interactive "P")
7477 (setq org-goto-selected-point (point))
7478 (setq org-goto-exit-command 'return)
7479 (throw 'exit nil))
7481 (defun org-goto-left ()
7482 "Finish `org-goto' by going to the new location."
7483 (interactive)
7484 (if (org-at-heading-p)
7485 (progn
7486 (beginning-of-line 1)
7487 (setq org-goto-selected-point (point)
7488 org-goto-exit-command 'left)
7489 (throw 'exit nil))
7490 (user-error "Not on a heading")))
7492 (defun org-goto-right ()
7493 "Finish `org-goto' by going to the new location."
7494 (interactive)
7495 (if (org-at-heading-p)
7496 (progn
7497 (setq org-goto-selected-point (point)
7498 org-goto-exit-command 'right)
7499 (throw 'exit nil))
7500 (user-error "Not on a heading")))
7502 (defun org-goto-quit ()
7503 "Finish `org-goto' without cursor motion."
7504 (interactive)
7505 (setq org-goto-selected-point nil)
7506 (setq org-goto-exit-command 'quit)
7507 (throw 'exit nil))
7509 ;;; Indirect buffer display of subtrees
7511 (defvar org-indirect-dedicated-frame nil
7512 "This is the frame being used for indirect tree display.")
7513 (defvar org-last-indirect-buffer nil)
7515 (defun org-tree-to-indirect-buffer (&optional arg)
7516 "Create indirect buffer and narrow it to current subtree.
7517 With a numerical prefix ARG, go up to this level and then take that tree.
7518 If ARG is negative, go up that many levels.
7520 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7521 indirect buffer previously made with this command, to avoid proliferation of
7522 indirect buffers. However, when you call the command with a \
7523 \\[universal-argument] prefix, or
7524 when `org-indirect-buffer-display' is `new-frame', the last buffer
7525 is kept so that you can work with several indirect buffers at the same time.
7526 If `org-indirect-buffer-display' is `dedicated-frame', the \
7527 \\[universal-argument] prefix also
7528 requests that a new frame be made for the new buffer, so that the dedicated
7529 frame is not changed."
7530 (interactive "P")
7531 (let ((cbuf (current-buffer))
7532 (cwin (selected-window))
7533 (pos (point))
7534 beg end level heading ibuf)
7535 (save-excursion
7536 (org-back-to-heading t)
7537 (when (numberp arg)
7538 (setq level (org-outline-level))
7539 (when (< arg 0) (setq arg (+ level arg)))
7540 (while (> (setq level (org-outline-level)) arg)
7541 (org-up-heading-safe)))
7542 (setq beg (point)
7543 heading (org-get-heading 'no-tags))
7544 (org-end-of-subtree t t)
7545 (when (org-at-heading-p) (backward-char 1))
7546 (setq end (point)))
7547 (when (and (buffer-live-p org-last-indirect-buffer)
7548 (not (eq org-indirect-buffer-display 'new-frame))
7549 (not arg))
7550 (kill-buffer org-last-indirect-buffer))
7551 (setq ibuf (org-get-indirect-buffer cbuf heading)
7552 org-last-indirect-buffer ibuf)
7553 (cond
7554 ((or (eq org-indirect-buffer-display 'new-frame)
7555 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7556 (select-frame (make-frame))
7557 (delete-other-windows)
7558 (org-pop-to-buffer-same-window ibuf)
7559 (org-set-frame-title heading))
7560 ((eq org-indirect-buffer-display 'dedicated-frame)
7561 (raise-frame
7562 (select-frame (or (and org-indirect-dedicated-frame
7563 (frame-live-p org-indirect-dedicated-frame)
7564 org-indirect-dedicated-frame)
7565 (setq org-indirect-dedicated-frame (make-frame)))))
7566 (delete-other-windows)
7567 (org-pop-to-buffer-same-window ibuf)
7568 (org-set-frame-title (concat "Indirect: " heading)))
7569 ((eq org-indirect-buffer-display 'current-window)
7570 (org-pop-to-buffer-same-window ibuf))
7571 ((eq org-indirect-buffer-display 'other-window)
7572 (pop-to-buffer ibuf))
7573 (t (error "Invalid value")))
7574 (when (featurep 'xemacs)
7575 (save-excursion (org-mode) (turn-on-font-lock)))
7576 (narrow-to-region beg end)
7577 (outline-show-all)
7578 (goto-char pos)
7579 (run-hook-with-args 'org-cycle-hook 'all)
7580 (and (window-live-p cwin) (select-window cwin))))
7582 (defun org-get-indirect-buffer (&optional buffer heading)
7583 (setq buffer (or buffer (current-buffer)))
7584 (let ((n 1) (base (buffer-name buffer)) bname)
7585 (while (buffer-live-p
7586 (get-buffer
7587 (setq bname
7588 (concat base "-"
7589 (if heading (concat heading "-" (number-to-string n))
7590 (number-to-string n))))))
7591 (setq n (1+ n)))
7592 (condition-case nil
7593 (make-indirect-buffer buffer bname 'clone)
7594 (error (make-indirect-buffer buffer bname)))))
7596 (defun org-set-frame-title (title)
7597 "Set the title of the current frame to the string TITLE."
7598 ;; FIXME: how to name a single frame in XEmacs???
7599 (unless (featurep 'xemacs)
7600 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7602 ;;;; Structure editing
7604 ;;; Inserting headlines
7606 (defun org--line-empty-p (n)
7607 "Is the Nth next line empty?
7609 Counts the current line as N = 1 and the previous line as N = 0;
7610 see `beginning-of-line'."
7611 (save-excursion
7612 (and (not (bobp))
7613 (or (beginning-of-line n) t)
7614 (save-match-data
7615 (looking-at "[ \t]*$")))))
7617 (defun org-previous-line-empty-p ()
7618 "Is the previous line a blank line?
7619 When NEXT is non-nil, check the next line instead."
7620 (org--line-empty-p 0))
7622 (defun org-next-line-empty-p ()
7623 "Is the previous line a blank line?
7624 When NEXT is non-nil, check the next line instead."
7625 (org--line-empty-p 2))
7627 (defun org-insert-heading (&optional arg invisible-ok top)
7628 "Insert a new heading or an item with the same depth at point.
7630 If point is at the beginning of a heading or a list item, insert
7631 a new heading or a new item above the current one. If point is
7632 at the beginning of a normal line, turn the line into a heading.
7634 If point is in the middle of a headline or a list item, split the
7635 headline or the item and create a new headline/item with the text
7636 in the current line after point \(see `org-M-RET-may-split-line'
7637 on how to modify this behavior).
7639 With one universal prefix argument, set the user option
7640 `org-insert-heading-respect-content' to t for the duration of
7641 the command. This modifies the behavior described above in this
7642 ways: on list items and at the beginning of normal lines, force
7643 the insertion of a heading after the current subtree.
7645 With two universal prefix arguments, insert the heading at the
7646 end of the grandparent subtree. For example, if point is within
7647 a 2nd-level heading, then it will insert a 2nd-level heading at
7648 the end of the 1st-level parent heading.
7650 If point is at the beginning of a headline, insert a sibling
7651 before the current headline. If point is not at the beginning,
7652 split the line and create a new headline with the text in the
7653 current line after point \(see `org-M-RET-may-split-line' on how
7654 to modify this behavior).
7656 If point is at the beginning of a normal line, turn this line
7657 into a heading.
7659 When INVISIBLE-OK is set, stop at invisible headlines when going
7660 back. This is important for non-interactive uses of the
7661 command.
7663 When optional argument TOP is non-nil, insert a level 1 heading,
7664 unconditionally."
7665 (interactive "P")
7666 (when (org-called-interactively-p 'any) (org-reveal))
7667 (let ((itemp (and (not top) (org-in-item-p)))
7668 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7669 (respect-content (or org-insert-heading-respect-content
7670 (equal arg '(4))))
7671 (initial-content ""))
7673 (cond
7675 ((or (= (buffer-size) 0)
7676 (and (not (save-excursion
7677 (and (ignore-errors (org-back-to-heading invisible-ok))
7678 (org-at-heading-p))))
7679 (or arg (not itemp))))
7680 ;; At beginning of buffer or so high up that only a heading
7681 ;; makes sense.
7682 (cond ((and (bolp) (not respect-content)) (insert "* "))
7683 ((not respect-content)
7684 (unless may-split (end-of-line))
7685 (insert "\n* "))
7686 ((re-search-forward org-outline-regexp-bol nil t)
7687 (beginning-of-line)
7688 (insert "* \n")
7689 (backward-char))
7690 (t (goto-char (point-max))
7691 (insert "\n* ")))
7692 (run-hooks 'org-insert-heading-hook))
7694 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7697 ;; Maybe move at the end of the subtree
7698 (when (equal arg '(16))
7699 (org-up-heading-safe)
7700 (org-end-of-subtree t))
7701 ;; Insert a heading
7702 (save-restriction
7703 (widen)
7704 (let* ((level nil)
7705 (on-heading (org-at-heading-p))
7706 (empty-line-p (if on-heading
7707 (org-previous-line-empty-p)
7708 ;; We will decide later
7709 nil))
7710 ;; Get a level string to fall back on.
7711 (fix-level
7712 (if (org-before-first-heading-p) "*"
7713 (save-excursion
7714 (org-back-to-heading t)
7715 (when (org-previous-line-empty-p) (setq empty-line-p t))
7716 (looking-at org-outline-regexp)
7717 (make-string (1- (length (match-string 0))) ?*))))
7718 (stars
7719 (save-excursion
7720 (condition-case nil
7721 (if top "* "
7722 (org-back-to-heading invisible-ok)
7723 (when (and (not on-heading)
7724 (featurep 'org-inlinetask)
7725 (integerp org-inlinetask-min-level)
7726 (>= (length (match-string 0))
7727 org-inlinetask-min-level))
7728 ;; Find a heading level before the inline
7729 ;; task.
7730 (while (and (setq level (org-up-heading-safe))
7731 (>= level org-inlinetask-min-level)))
7732 (if (org-at-heading-p)
7733 (org-back-to-heading invisible-ok)
7734 (error "This should not happen")))
7735 (unless (and (save-excursion
7736 (save-match-data
7737 (org-backward-heading-same-level
7738 1 invisible-ok))
7739 (= (point) (match-beginning 0)))
7740 (not (org-next-line-empty-p)))
7741 (setq empty-line-p (or empty-line-p
7742 (org-previous-line-empty-p))))
7743 (match-string 0))
7744 (error (or fix-level "* ")))))
7745 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7746 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7748 ;; If we insert after content, move there and clean up
7749 ;; whitespace.
7750 (when (and respect-content
7751 (not (org-looking-at-p org-outline-regexp-bol)))
7752 (if (not (org-before-first-heading-p))
7753 (org-end-of-subtree nil t)
7754 (re-search-forward org-outline-regexp-bol)
7755 (beginning-of-line 0))
7756 (skip-chars-backward " \r\t\n")
7757 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7758 (looking-at "[ \t]+") (replace-match ""))
7759 (unless (eobp) (forward-char 1))
7760 (when (looking-at "^\\*")
7761 (unless (bobp) (backward-char 1))
7762 (insert "\n")))
7764 ;; If we are splitting, grab the text that should be moved
7765 ;; to the new headline.
7766 (when may-split
7767 (if (org-at-heading-p)
7768 ;; This is a heading: split intelligently (keeping
7769 ;; tags).
7770 (let ((pos (point)))
7771 (beginning-of-line)
7772 (unless (looking-at org-complex-heading-regexp)
7773 (error "This should not happen"))
7774 (when (and (match-beginning 4)
7775 (> pos (match-beginning 4))
7776 (< pos (match-end 4)))
7777 (setq initial-content (buffer-substring pos (match-end 4)))
7778 (goto-char pos)
7779 (delete-region (point) (match-end 4))
7780 (if (looking-at "[ \t]*$")
7781 (replace-match "")
7782 (insert (make-string (length initial-content) ?\s)))
7783 (setq initial-content (org-trim initial-content)))
7784 (goto-char pos))
7785 ;; A normal line.
7786 (setq initial-content
7787 (org-trim
7788 (delete-and-extract-region (point) (line-end-position))))))
7790 ;; If we are at the beginning of the line, insert before it.
7791 ;; Otherwise, after it.
7792 (cond
7793 ((and (bolp) (looking-at "[ \t]*$")))
7794 ((bolp) (save-excursion (insert "\n")))
7795 (t (end-of-line)
7796 (insert "\n")))
7798 ;; Insert the new heading
7799 (insert stars)
7800 (just-one-space)
7801 (insert initial-content)
7802 (unless (and blank (org-previous-line-empty-p))
7803 (org-N-empty-lines-before-current (if blank 1 0)))
7804 ;; Adjust visibility, which may be messed up if we removed
7805 ;; blank lines while previous entry was hidden.
7806 (let ((bol (line-beginning-position)))
7807 (dolist (o (overlays-at (1- bol)))
7808 (when (and (eq (overlay-get o 'invisible) 'outline)
7809 (eq (overlay-end o) bol))
7810 (move-overlay o (overlay-start o) (1- bol)))))
7811 (run-hooks 'org-insert-heading-hook)))))))
7813 (defun org-N-empty-lines-before-current (N)
7814 "Make the number of empty lines before current exactly N.
7815 So this will delete or add empty lines."
7816 (save-excursion
7817 (beginning-of-line)
7818 (let ((p (point)))
7819 (skip-chars-backward " \r\t\n")
7820 (unless (bolp) (forward-line))
7821 (delete-region (point) p))
7822 (when (> N 0) (insert (make-string N ?\n)))))
7824 (defun org-get-heading (&optional no-tags no-todo)
7825 "Return the heading of the current entry, without the stars.
7826 When NO-TAGS is non-nil, don't include tags.
7827 When NO-TODO is non-nil, don't include TODO keywords."
7828 (save-excursion
7829 (org-back-to-heading t)
7830 (cond
7831 ((and no-tags no-todo)
7832 (looking-at org-complex-heading-regexp)
7833 (match-string 4))
7834 (no-tags
7835 (looking-at (concat org-outline-regexp
7836 "\\(.*?\\)"
7837 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7838 (match-string 1))
7839 (no-todo
7840 (looking-at org-todo-line-regexp)
7841 (match-string 3))
7842 (t (looking-at org-heading-regexp)
7843 (match-string 2)))))
7845 (defvar orgstruct-mode) ; defined below
7847 (defun org-heading-components ()
7848 "Return the components of the current heading.
7849 This is a list with the following elements:
7850 - the level as an integer
7851 - the reduced level, different if `org-odd-levels-only' is set.
7852 - the TODO keyword, or nil
7853 - the priority character, like ?A, or nil if no priority is given
7854 - the headline text itself, or the tags string if no headline text
7855 - the tags string, or nil."
7856 (save-excursion
7857 (org-back-to-heading t)
7858 (when (let (case-fold-search)
7859 (looking-at
7860 (if orgstruct-mode
7861 org-heading-regexp
7862 org-complex-heading-regexp)))
7863 (if orgstruct-mode
7864 (list (length (match-string 1))
7865 (org-reduced-level (length (match-string 1)))
7868 (match-string 2)
7869 nil)
7870 (list (length (match-string 1))
7871 (org-reduced-level (length (match-string 1)))
7872 (org-match-string-no-properties 2)
7873 (and (match-end 3) (aref (match-string 3) 2))
7874 (org-match-string-no-properties 4)
7875 (org-match-string-no-properties 5))))))
7877 (defun org-get-entry ()
7878 "Get the entry text, after heading, entire subtree."
7879 (save-excursion
7880 (org-back-to-heading t)
7881 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7883 (defun org-insert-heading-after-current ()
7884 "Insert a new heading with same level as current, after current subtree."
7885 (interactive)
7886 (org-back-to-heading)
7887 (org-insert-heading)
7888 (org-move-subtree-down)
7889 (end-of-line 1))
7891 (defun org-insert-heading-respect-content (&optional invisible-ok)
7892 "Insert heading with `org-insert-heading-respect-content' set to t."
7893 (interactive)
7894 (org-insert-heading '(4) invisible-ok))
7896 (defun org-insert-todo-heading-respect-content (&optional force-state)
7897 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7898 (interactive)
7899 (org-insert-todo-heading force-state '(4)))
7901 (defun org-insert-todo-heading (arg &optional force-heading)
7902 "Insert a new heading with the same level and TODO state as current heading.
7903 If the heading has no TODO state, or if the state is DONE, use the first
7904 state (TODO by default). Also with one prefix arg, force first state. With
7905 two prefix args, force inserting at the end of the parent subtree."
7906 (interactive "P")
7907 (when (or force-heading (not (org-insert-item 'checkbox)))
7908 (org-insert-heading (or (and (equal arg '(16)) '(16))
7909 force-heading))
7910 (save-excursion
7911 (org-back-to-heading)
7912 (outline-previous-heading)
7913 (looking-at org-todo-line-regexp))
7914 (let*
7915 ((new-mark-x
7916 (if (or (equal arg '(4))
7917 (not (match-beginning 2))
7918 (member (match-string 2) org-done-keywords))
7919 (car org-todo-keywords-1)
7920 (match-string 2)))
7921 (new-mark
7923 (run-hook-with-args-until-success
7924 'org-todo-get-default-hook new-mark-x nil)
7925 new-mark-x)))
7926 (beginning-of-line 1)
7927 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7928 (if org-treat-insert-todo-heading-as-state-change
7929 (org-todo new-mark)
7930 (insert new-mark " "))))
7931 (when org-provide-todo-statistics
7932 (org-update-parent-todo-statistics))))
7934 (defun org-insert-subheading (arg)
7935 "Insert a new subheading and demote it.
7936 Works for outline headings and for plain lists alike."
7937 (interactive "P")
7938 (org-insert-heading arg)
7939 (cond
7940 ((org-at-heading-p) (org-do-demote))
7941 ((org-at-item-p) (org-indent-item))))
7943 (defun org-insert-todo-subheading (arg)
7944 "Insert a new subheading with TODO keyword or checkbox and demote it.
7945 Works for outline headings and for plain lists alike."
7946 (interactive "P")
7947 (org-insert-todo-heading arg)
7948 (cond
7949 ((org-at-heading-p) (org-do-demote))
7950 ((org-at-item-p) (org-indent-item))))
7952 ;;; Promotion and Demotion
7954 (defvar org-after-demote-entry-hook nil
7955 "Hook run after an entry has been demoted.
7956 The cursor will be at the beginning of the entry.
7957 When a subtree is being demoted, the hook will be called for each node.")
7959 (defvar org-after-promote-entry-hook nil
7960 "Hook run after an entry has been promoted.
7961 The cursor will be at the beginning of the entry.
7962 When a subtree is being promoted, the hook will be called for each node.")
7964 (defun org-promote-subtree ()
7965 "Promote the entire subtree.
7966 See also `org-promote'."
7967 (interactive)
7968 (save-excursion
7969 (org-with-limited-levels (org-map-tree 'org-promote)))
7970 (org-fix-position-after-promote))
7972 (defun org-demote-subtree ()
7973 "Demote the entire subtree.
7974 See `org-demote' and `org-promote'."
7975 (interactive)
7976 (save-excursion
7977 (org-with-limited-levels (org-map-tree 'org-demote)))
7978 (org-fix-position-after-promote))
7980 (defun org-do-promote ()
7981 "Promote the current heading higher up the tree.
7982 If the region is active in `transient-mark-mode', promote all
7983 headings in the region."
7984 (interactive)
7985 (save-excursion
7986 (if (org-region-active-p)
7987 (org-map-region 'org-promote (region-beginning) (region-end))
7988 (org-promote)))
7989 (org-fix-position-after-promote))
7991 (defun org-do-demote ()
7992 "Demote the current heading lower down the tree.
7993 If the region is active in `transient-mark-mode', demote all
7994 headings in the region."
7995 (interactive)
7996 (save-excursion
7997 (if (org-region-active-p)
7998 (org-map-region 'org-demote (region-beginning) (region-end))
7999 (org-demote)))
8000 (org-fix-position-after-promote))
8002 (defun org-fix-position-after-promote ()
8003 "Fix cursor position and indentation after demoting/promoting."
8004 (let ((pos (point)))
8005 (when (save-excursion
8006 (beginning-of-line 1)
8007 (looking-at org-todo-line-regexp)
8008 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8009 (cond ((eobp) (insert " "))
8010 ((eolp) (insert " "))
8011 ((equal (char-after) ?\ ) (forward-char 1))))))
8013 (defun org-current-level ()
8014 "Return the level of the current entry, or nil if before the first headline.
8015 The level is the number of stars at the beginning of the
8016 headline. Use `org-reduced-level' to remove the effect of
8017 `org-odd-levels'. Unlike to `org-outline-level', this function
8018 ignores inlinetasks."
8019 (let ((level (org-with-limited-levels (org-outline-level))))
8020 (and (> level 0) level)))
8022 (defun org-get-previous-line-level ()
8023 "Return the outline depth of the last headline before the current line.
8024 Returns 0 for the first headline in the buffer, and nil if before the
8025 first headline."
8026 (and (org-current-level)
8027 (or (and (/= (line-beginning-position) (point-min))
8028 (save-excursion (beginning-of-line 0) (org-current-level)))
8029 0)))
8031 (defun org-reduced-level (l)
8032 "Compute the effective level of a heading.
8033 This takes into account the setting of `org-odd-levels-only'."
8034 (cond
8035 ((zerop l) 0)
8036 (org-odd-levels-only (1+ (floor (/ l 2))))
8037 (t l)))
8039 (defun org-level-increment ()
8040 "Return the number of stars that will be added or removed at a
8041 time to headlines when structure editing, based on the value of
8042 `org-odd-levels-only'."
8043 (if org-odd-levels-only 2 1))
8045 (defun org-get-valid-level (level &optional change)
8046 "Rectify a level change under the influence of `org-odd-levels-only'
8047 LEVEL is a current level, CHANGE is by how much the level should be
8048 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8049 even level numbers will become the next higher odd number."
8050 (if org-odd-levels-only
8051 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8052 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8053 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8054 (max 1 (+ level (or change 0)))))
8055 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8057 (defun org-promote ()
8058 "Promote the current heading higher up the tree."
8059 (org-with-wide-buffer
8060 (org-back-to-heading t)
8061 (let* ((after-change-functions (remq 'flyspell-after-change-function
8062 after-change-functions))
8063 (level (save-match-data (funcall outline-level)))
8064 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8065 (diff (abs (- level (length up-head) -1))))
8066 (cond
8067 ((and (= level 1) org-allow-promoting-top-level-subtree)
8068 (replace-match "# " nil t))
8069 ((= level 1)
8070 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8071 (t (replace-match up-head nil t)))
8072 (unless (= level 1)
8073 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8074 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8075 (run-hooks 'org-after-promote-entry-hook))))
8077 (defun org-demote ()
8078 "Demote the current heading lower down the tree."
8079 (org-with-wide-buffer
8080 (org-back-to-heading t)
8081 (let* ((after-change-functions (remq 'flyspell-after-change-function
8082 after-change-functions))
8083 (level (save-match-data (funcall outline-level)))
8084 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8085 (diff (abs (- level (length down-head) -1))))
8086 (replace-match down-head nil t)
8087 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8088 (when org-adapt-indentation (org-fixup-indentation diff))
8089 (run-hooks 'org-after-demote-entry-hook))))
8091 (defun org-cycle-level ()
8092 "Cycle the level of an empty headline through possible states.
8093 This goes first to child, then to parent, level, then up the hierarchy.
8094 After top level, it switches back to sibling level."
8095 (interactive)
8096 (let ((org-adapt-indentation nil))
8097 (when (org-point-at-end-of-empty-headline)
8098 (setq this-command 'org-cycle-level) ; Only needed for caching
8099 (let ((cur-level (org-current-level))
8100 (prev-level (org-get-previous-line-level)))
8101 (cond
8102 ;; If first headline in file, promote to top-level.
8103 ((= prev-level 0)
8104 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8105 do (org-do-promote)))
8106 ;; If same level as prev, demote one.
8107 ((= prev-level cur-level)
8108 (org-do-demote))
8109 ;; If parent is top-level, promote to top level if not already.
8110 ((= prev-level 1)
8111 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8112 do (org-do-promote)))
8113 ;; If top-level, return to prev-level.
8114 ((= cur-level 1)
8115 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8116 do (org-do-demote)))
8117 ;; If less than prev-level, promote one.
8118 ((< cur-level prev-level)
8119 (org-do-promote))
8120 ;; If deeper than prev-level, promote until higher than
8121 ;; prev-level.
8122 ((> cur-level prev-level)
8123 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8124 do (org-do-promote))))
8125 t))))
8127 (defun org-map-tree (fun)
8128 "Call FUN for every heading underneath the current one."
8129 (org-back-to-heading)
8130 (let ((level (funcall outline-level)))
8131 (save-excursion
8132 (funcall fun)
8133 (while (and (progn
8134 (outline-next-heading)
8135 (> (funcall outline-level) level))
8136 (not (eobp)))
8137 (funcall fun)))))
8139 (defun org-map-region (fun beg end)
8140 "Call FUN for every heading between BEG and END."
8141 (let ((org-ignore-region t))
8142 (save-excursion
8143 (setq end (copy-marker end))
8144 (goto-char beg)
8145 (when (and (re-search-forward org-outline-regexp-bol nil t)
8146 (< (point) end))
8147 (funcall fun))
8148 (while (and (progn
8149 (outline-next-heading)
8150 (< (point) end))
8151 (not (eobp)))
8152 (funcall fun)))))
8154 (defun org-fixup-indentation (diff)
8155 "Change the indentation in the current entry by DIFF.
8157 DIFF is an integer. Indentation is done according to the
8158 following rules:
8160 - Planning information and property drawers are always indented
8161 according to the new level of the headline;
8163 - Footnote definitions and their contents are ignored;
8165 - Inlinetasks' boundaries are not shifted;
8167 - Empty lines are ignored;
8169 - Other lines' indentation are shifted by DIFF columns, unless
8170 it would introduce a structural change in the document, in
8171 which case no shifting is done at all.
8173 Assume point is at a heading or an inlinetask beginning."
8174 (org-with-wide-buffer
8175 (narrow-to-region (line-beginning-position)
8176 (save-excursion
8177 (if (org-with-limited-levels (org-at-heading-p))
8178 (org-with-limited-levels (outline-next-heading))
8179 (org-inlinetask-goto-end))
8180 (point)))
8181 (forward-line)
8182 ;; Indent properly planning info and property drawer.
8183 (when (org-looking-at-p org-planning-line-re)
8184 (org-indent-line)
8185 (forward-line))
8186 (when (looking-at org-property-drawer-re)
8187 (goto-char (match-end 0))
8188 (forward-line)
8189 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8190 (catch 'no-shift
8191 (when (zerop diff) (throw 'no-shift nil))
8192 ;; If DIFF is negative, first check if a shift is possible at all
8193 ;; (e.g., it doesn't break structure). This can only happen if
8194 ;; some contents are not properly indented.
8195 (let ((case-fold-search t))
8196 (when (< diff 0)
8197 (let ((diff (- diff))
8198 (forbidden-re (concat org-outline-regexp
8199 "\\|"
8200 (substring org-footnote-definition-re 1))))
8201 (save-excursion
8202 (while (not (eobp))
8203 (cond
8204 ((org-looking-at-p "[ \t]*$") (forward-line))
8205 ((and (org-looking-at-p org-footnote-definition-re)
8206 (let ((e (org-element-at-point)))
8207 (and (eq (org-element-type e) 'footnote-definition)
8208 (goto-char (org-element-property :end e))))))
8209 ((org-looking-at-p org-outline-regexp) (forward-line))
8210 ;; Give up if shifting would move before column 0 or
8211 ;; if it would introduce a headline or a footnote
8212 ;; definition.
8214 (skip-chars-forward " \t")
8215 (let ((ind (current-column)))
8216 (when (or (< ind diff)
8217 (and (= ind diff) (org-looking-at-p forbidden-re)))
8218 (throw 'no-shift nil)))
8219 ;; Ignore contents of example blocks and source
8220 ;; blocks if their indentation is meant to be
8221 ;; preserved. Jump to block's closing line.
8222 (beginning-of-line)
8223 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8224 (let ((e (org-element-at-point)))
8225 (and (memq (org-element-type e)
8226 '(example-block src-block))
8227 (or org-src-preserve-indentation
8228 (org-element-property :preserve-indent e))
8229 (goto-char (org-element-property :end e))
8230 (progn (skip-chars-backward " \r\t\n")
8231 (beginning-of-line)
8232 t))))
8233 (forward-line))))))))
8234 ;; Shift lines but footnote definitions, inlinetasks boundaries
8235 ;; by DIFF. Also skip contents of source or example blocks
8236 ;; when indentation is meant to be preserved.
8237 (while (not (eobp))
8238 (cond
8239 ((and (org-looking-at-p org-footnote-definition-re)
8240 (let ((e (org-element-at-point)))
8241 (and (eq (org-element-type e) 'footnote-definition)
8242 (goto-char (org-element-property :end e))))))
8243 ((org-looking-at-p org-outline-regexp) (forward-line))
8244 ((org-looking-at-p "[ \t]*$") (forward-line))
8246 (org-indent-line-to (+ (org-get-indentation) diff))
8247 (beginning-of-line)
8248 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8249 (let ((e (org-element-at-point)))
8250 (and (memq (org-element-type e)
8251 '(example-block src-block))
8252 (or org-src-preserve-indentation
8253 (org-element-property :preserve-indent e))
8254 (goto-char (org-element-property :end e))
8255 (progn (skip-chars-backward " \r\t\n")
8256 (beginning-of-line)
8257 t))))
8258 (forward-line)))))))))
8260 (defun org-convert-to-odd-levels ()
8261 "Convert an org-mode file with all levels allowed to one with odd levels.
8262 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8263 level 5 etc."
8264 (interactive)
8265 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8266 (let ((outline-level 'org-outline-level)
8267 (org-odd-levels-only nil) n)
8268 (save-excursion
8269 (goto-char (point-min))
8270 (while (re-search-forward "^\\*\\*+ " nil t)
8271 (setq n (- (length (match-string 0)) 2))
8272 (while (>= (setq n (1- n)) 0)
8273 (org-demote))
8274 (end-of-line 1))))))
8276 (defun org-convert-to-oddeven-levels ()
8277 "Convert an org-mode file with only odd levels to one with odd/even levels.
8278 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8279 file contains a section with an even level, conversion would
8280 destroy the structure of the file. An error is signaled in this
8281 case."
8282 (interactive)
8283 (goto-char (point-min))
8284 ;; First check if there are no even levels
8285 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8286 (org-show-set-visibility 'canonical)
8287 (error "Not all levels are odd in this file. Conversion not possible"))
8288 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8289 (let ((outline-regexp org-outline-regexp)
8290 (outline-level 'org-outline-level)
8291 (org-odd-levels-only nil) n)
8292 (save-excursion
8293 (goto-char (point-min))
8294 (while (re-search-forward "^\\*\\*+ " nil t)
8295 (setq n (/ (1- (length (match-string 0))) 2))
8296 (while (>= (setq n (1- n)) 0)
8297 (org-promote))
8298 (end-of-line 1))))))
8300 (defun org-tr-level (n)
8301 "Make N odd if required."
8302 (if org-odd-levels-only (1+ (/ n 2)) n))
8304 ;;; Vertical tree motion, cutting and pasting of subtrees
8306 (defun org-move-subtree-up (&optional arg)
8307 "Move the current subtree up past ARG headlines of the same level."
8308 (interactive "p")
8309 (org-move-subtree-down (- (prefix-numeric-value arg))))
8311 (defun org-move-subtree-down (&optional arg)
8312 "Move the current subtree down past ARG headlines of the same level."
8313 (interactive "p")
8314 (setq arg (prefix-numeric-value arg))
8315 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8316 'org-get-last-sibling))
8317 (ins-point (make-marker))
8318 (cnt (abs arg))
8319 (col (current-column))
8320 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8321 ;; Select the tree
8322 (org-back-to-heading)
8323 (setq beg0 (point))
8324 (save-excursion
8325 (setq ne-beg (org-back-over-empty-lines))
8326 (setq beg (point)))
8327 (save-match-data
8328 (save-excursion (outline-end-of-heading)
8329 (setq folded (outline-invisible-p)))
8330 (progn (org-end-of-subtree nil t)
8331 (unless (eobp) (backward-char))))
8332 (outline-next-heading)
8333 (setq ne-end (org-back-over-empty-lines))
8334 (setq end (point))
8335 (goto-char beg0)
8336 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8337 ;; include less whitespace
8338 (save-excursion
8339 (goto-char beg)
8340 (forward-line (- ne-beg ne-end))
8341 (setq beg (point))))
8342 ;; Find insertion point, with error handling
8343 (while (> cnt 0)
8344 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8345 (progn (goto-char beg0)
8346 (user-error "Cannot move past superior level or buffer limit")))
8347 (setq cnt (1- cnt)))
8348 (when (> arg 0)
8349 ;; Moving forward - still need to move over subtree
8350 (org-end-of-subtree t t)
8351 (save-excursion
8352 (org-back-over-empty-lines)
8353 (or (bolp) (newline))))
8354 (setq ne-ins (org-back-over-empty-lines))
8355 (move-marker ins-point (point))
8356 (setq txt (buffer-substring beg end))
8357 (org-save-markers-in-region beg end)
8358 (delete-region beg end)
8359 (org-remove-empty-overlays-at beg)
8360 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8361 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8362 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8363 (let ((bbb (point)))
8364 (insert-before-markers txt)
8365 (org-reinstall-markers-in-region bbb)
8366 (move-marker ins-point bbb))
8367 (or (bolp) (insert "\n"))
8368 (setq ins-end (point))
8369 (goto-char ins-point)
8370 (org-skip-whitespace)
8371 (when (and (< arg 0)
8372 (org-first-sibling-p)
8373 (> ne-ins ne-beg))
8374 ;; Move whitespace back to beginning
8375 (save-excursion
8376 (goto-char ins-end)
8377 (let ((kill-whole-line t))
8378 (kill-line (- ne-ins ne-beg)) (point)))
8379 (insert (make-string (- ne-ins ne-beg) ?\n)))
8380 (move-marker ins-point nil)
8381 (if folded
8382 (outline-hide-subtree)
8383 (org-show-entry)
8384 (org-show-children)
8385 (org-cycle-hide-drawers 'children))
8386 (org-clean-visibility-after-subtree-move)
8387 ;; move back to the initial column we were at
8388 (move-to-column col)))
8390 (defvar org-subtree-clip ""
8391 "Clipboard for cut and paste of subtrees.
8392 This is actually only a copy of the kill, because we use the normal kill
8393 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8395 (defvar org-subtree-clip-folded nil
8396 "Was the last copied subtree folded?
8397 This is used to fold the tree back after pasting.")
8399 (defun org-cut-subtree (&optional n)
8400 "Cut the current subtree into the clipboard.
8401 With prefix arg N, cut this many sequential subtrees.
8402 This is a short-hand for marking the subtree and then cutting it."
8403 (interactive "p")
8404 (org-copy-subtree n 'cut))
8406 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8407 "Copy the current subtree it in the clipboard.
8408 With prefix arg N, copy this many sequential subtrees.
8409 This is a short-hand for marking the subtree and then copying it.
8410 If CUT is non-nil, actually cut the subtree.
8411 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8412 of some markers in the region, even if CUT is non-nil. This is
8413 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8414 (interactive "p")
8415 (let (beg end folded (beg0 (point)))
8416 (if (org-called-interactively-p 'any)
8417 (org-back-to-heading nil) ; take what looks like a subtree
8418 (org-back-to-heading t)) ; take what is really there
8419 (setq beg (point))
8420 (skip-chars-forward " \t\r\n")
8421 (save-match-data
8422 (if nosubtrees
8423 (outline-next-heading)
8424 (save-excursion (outline-end-of-heading)
8425 (setq folded (outline-invisible-p)))
8426 (ignore-errors (org-forward-heading-same-level (1- n) t))
8427 (org-end-of-subtree t t)))
8428 ;; Include the end of an inlinetask
8429 (when (and (featurep 'org-inlinetask)
8430 (looking-at-p (concat (org-inlinetask-outline-regexp)
8431 "END[ \t]*$")))
8432 (end-of-line))
8433 (setq end (point))
8434 (goto-char beg0)
8435 (when (> end beg)
8436 (setq org-subtree-clip-folded folded)
8437 (when (or cut force-store-markers)
8438 (org-save-markers-in-region beg end))
8439 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8440 (setq org-subtree-clip (current-kill 0))
8441 (message "%s: Subtree(s) with %d characters"
8442 (if cut "Cut" "Copied")
8443 (length org-subtree-clip)))))
8445 (defun org-paste-subtree (&optional level tree for-yank remove)
8446 "Paste the clipboard as a subtree, with modification of headline level.
8447 The entire subtree is promoted or demoted in order to match a new headline
8448 level.
8450 If the cursor is at the beginning of a headline, the same level as
8451 that headline is used to paste the tree.
8453 If not, the new level is derived from the *visible* headings
8454 before and after the insertion point, and taken to be the inferior headline
8455 level of the two. So if the previous visible heading is level 3 and the
8456 next is level 4 (or vice versa), level 4 will be used for insertion.
8457 This makes sure that the subtree remains an independent subtree and does
8458 not swallow low level entries.
8460 You can also force a different level, either by using a numeric prefix
8461 argument, or by inserting the heading marker by hand. For example, if the
8462 cursor is after \"*****\", then the tree will be shifted to level 5.
8464 If optional TREE is given, use this text instead of the kill ring.
8466 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8467 move back over whitespace before inserting, and move point to the end of
8468 the inserted text when done.
8470 When REMOVE is non-nil, remove the subtree from the clipboard."
8471 (interactive "P")
8472 (setq tree (or tree (and kill-ring (current-kill 0))))
8473 (unless (org-kill-is-subtree-p tree)
8474 (user-error "%s"
8475 (substitute-command-keys
8476 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8477 (org-with-limited-levels
8478 (let* ((visp (not (outline-invisible-p)))
8479 (txt tree)
8480 (^re_ "\\(\\*+\\)[ \t]*")
8481 (old-level (if (string-match org-outline-regexp-bol txt)
8482 (- (match-end 0) (match-beginning 0) 1)
8483 -1))
8484 (force-level (cond (level (prefix-numeric-value level))
8485 ((and (looking-at "[ \t]*$")
8486 (string-match
8487 "^\\*+$" (buffer-substring
8488 (point-at-bol) (point))))
8489 (- (match-end 0) (match-beginning 0)))
8490 ((and (bolp)
8491 (looking-at org-outline-regexp))
8492 (- (match-end 0) (point) 1))))
8493 (previous-level (save-excursion
8494 (condition-case nil
8495 (progn
8496 (outline-previous-visible-heading 1)
8497 (if (looking-at ^re_)
8498 (- (match-end 0) (match-beginning 0) 1)
8500 (error 1))))
8501 (next-level (save-excursion
8502 (condition-case nil
8503 (progn
8504 (or (looking-at org-outline-regexp)
8505 (outline-next-visible-heading 1))
8506 (if (looking-at ^re_)
8507 (- (match-end 0) (match-beginning 0) 1)
8509 (error 1))))
8510 (new-level (or force-level (max previous-level next-level)))
8511 (shift (if (or (= old-level -1)
8512 (= new-level -1)
8513 (= old-level new-level))
8515 (- new-level old-level)))
8516 (delta (if (> shift 0) -1 1))
8517 (func (if (> shift 0) 'org-demote 'org-promote))
8518 (org-odd-levels-only nil)
8519 beg end newend)
8520 ;; Remove the forced level indicator
8521 (when force-level
8522 (delete-region (point-at-bol) (point)))
8523 ;; Paste
8524 (beginning-of-line (if (bolp) 1 2))
8525 (setq beg (point))
8526 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8527 (insert-before-markers txt)
8528 (unless (string-match "\n\\'" txt) (insert "\n"))
8529 (setq newend (point))
8530 (org-reinstall-markers-in-region beg)
8531 (setq end (point))
8532 (goto-char beg)
8533 (skip-chars-forward " \t\n\r")
8534 (setq beg (point))
8535 (when (and (outline-invisible-p) visp)
8536 (save-excursion (outline-show-heading)))
8537 ;; Shift if necessary
8538 (unless (= shift 0)
8539 (save-restriction
8540 (narrow-to-region beg end)
8541 (while (not (= shift 0))
8542 (org-map-region func (point-min) (point-max))
8543 (setq shift (+ delta shift)))
8544 (goto-char (point-min))
8545 (setq newend (point-max))))
8546 (when (or (org-called-interactively-p 'interactive) for-yank)
8547 (message "Clipboard pasted as level %d subtree" new-level))
8548 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8549 kill-ring
8550 (eq org-subtree-clip (current-kill 0))
8551 org-subtree-clip-folded)
8552 ;; The tree was folded before it was killed/copied
8553 (outline-hide-subtree))
8554 (and for-yank (goto-char newend))
8555 (and remove (setq kill-ring (cdr kill-ring))))))
8557 (defun org-kill-is-subtree-p (&optional txt)
8558 "Check if the current kill is an outline subtree, or a set of trees.
8559 Returns nil if kill does not start with a headline, or if the first
8560 headline level is not the largest headline level in the tree.
8561 So this will actually accept several entries of equal levels as well,
8562 which is OK for `org-paste-subtree'.
8563 If optional TXT is given, check this string instead of the current kill."
8564 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8565 (re (org-get-limited-outline-regexp))
8566 (^re (concat "^" re))
8567 (start-level (and kill
8568 (string-match
8569 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8570 kill)
8571 (- (match-end 2) (match-beginning 2) 1)))
8572 (start (1+ (or (match-beginning 2) -1))))
8573 (if (not start-level)
8574 (progn
8575 nil) ;; does not even start with a heading
8576 (catch 'exit
8577 (while (setq start (string-match ^re kill (1+ start)))
8578 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8579 (throw 'exit nil)))
8580 t))))
8582 (defvar org-markers-to-move nil
8583 "Markers that should be moved with a cut-and-paste operation.
8584 Those markers are stored together with their positions relative to
8585 the start of the region.")
8587 (defun org-save-markers-in-region (beg end)
8588 "Check markers in region.
8589 If these markers are between BEG and END, record their position relative
8590 to BEG, so that after moving the block of text, we can put the markers back
8591 into place.
8592 This function gets called just before an entry or tree gets cut from the
8593 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8594 called immediately, to move the markers with the entries."
8595 (setq org-markers-to-move nil)
8596 (when (featurep 'org-clock)
8597 (org-clock-save-markers-for-cut-and-paste beg end))
8598 (when (featurep 'org-agenda)
8599 (org-agenda-save-markers-for-cut-and-paste beg end)))
8601 (defun org-check-and-save-marker (marker beg end)
8602 "Check if MARKER is between BEG and END.
8603 If yes, remember the marker and the distance to BEG."
8604 (when (and (marker-buffer marker)
8605 (equal (marker-buffer marker) (current-buffer))
8606 (>= marker beg) (< marker end))
8607 (push (cons marker (- marker beg)) org-markers-to-move)))
8609 (defun org-reinstall-markers-in-region (beg)
8610 "Move all remembered markers to their position relative to BEG."
8611 (dolist (x org-markers-to-move)
8612 (move-marker (car x) (+ beg (cdr x))))
8613 (setq org-markers-to-move nil))
8615 (defun org-narrow-to-subtree ()
8616 "Narrow buffer to the current subtree."
8617 (interactive)
8618 (save-excursion
8619 (save-match-data
8620 (org-with-limited-levels
8621 (narrow-to-region
8622 (progn (org-back-to-heading t) (point))
8623 (progn (org-end-of-subtree t t)
8624 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8625 (point)))))))
8627 (defun org-narrow-to-block ()
8628 "Narrow buffer to the current block."
8629 (interactive)
8630 (let* ((case-fold-search t)
8631 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8632 "^[ \t]*#\\+end_.*")))
8633 (if blockp
8634 (narrow-to-region (car blockp) (cdr blockp))
8635 (user-error "Not in a block"))))
8637 (defun org-clone-subtree-with-time-shift (n &optional shift)
8638 "Clone the task (subtree) at point N times.
8639 The clones will be inserted as siblings.
8641 In interactive use, the user will be prompted for the number of
8642 clones to be produced. If the entry has a timestamp, the user
8643 will also be prompted for a time shift, which may be a repeater
8644 as used in time stamps, for example `+3d'. To disable this,
8645 you can call the function with a universal prefix argument.
8647 When a valid repeater is given and the entry contains any time
8648 stamps, the clones will become a sequence in time, with time
8649 stamps in the subtree shifted for each clone produced. If SHIFT
8650 is nil or the empty string, time stamps will be left alone. The
8651 ID property of the original subtree is removed.
8653 If the original subtree did contain time stamps with a repeater,
8654 the following will happen:
8655 - the repeater will be removed in each clone
8656 - an additional clone will be produced, with the current, unshifted
8657 date(s) in the entry.
8658 - the original entry will be placed *after* all the clones, with
8659 repeater intact.
8660 - the start days in the repeater in the original entry will be shifted
8661 to past the last clone.
8662 In this way you can spell out a number of instances of a repeating task,
8663 and still retain the repeater to cover future instances of the task.
8665 As described above, N+1 clones are produced when the original
8666 subtree has a repeater. Setting N to 0, then, can be used to
8667 remove the repeater from a subtree and create a shifted clone
8668 with the original repeater."
8669 (interactive "nNumber of clones to produce: ")
8670 (let ((shift
8671 (or shift
8672 (if (and (not (equal current-prefix-arg '(4)))
8673 (save-excursion
8674 (re-search-forward org-ts-regexp-both
8675 (save-excursion
8676 (org-end-of-subtree t)
8677 (point)) t)))
8678 (read-from-minibuffer
8679 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8680 ""))) ;; No time shift
8681 (n-no-remove -1)
8682 (drawer-re org-drawer-regexp)
8683 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8684 beg end template task idprop
8685 shift-n shift-what doshift nmin nmax)
8686 (unless (wholenump n)
8687 (user-error "Invalid number of replications %s" n))
8688 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8689 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8690 shift)))
8691 (user-error "Invalid shift specification %s" shift))
8692 (when doshift
8693 (setq shift-n (string-to-number (match-string 1 shift))
8694 shift-what (cdr (assoc (match-string 2 shift)
8695 '(("d" . day) ("w" . week)
8696 ("m" . month) ("y" . year))))))
8697 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8698 (setq nmin 1 nmax n)
8699 (org-back-to-heading t)
8700 (setq beg (point))
8701 (setq idprop (org-entry-get nil "ID"))
8702 (org-end-of-subtree t t)
8703 (or (bolp) (insert "\n"))
8704 (setq end (point))
8705 (setq template (buffer-substring beg end))
8706 (when (and doshift
8707 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8708 (delete-region beg end)
8709 (setq end beg)
8710 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8711 (goto-char end)
8712 (cl-loop for n from nmin to nmax do
8713 ;; prepare clone
8714 (with-temp-buffer
8715 (insert template)
8716 (org-mode)
8717 (goto-char (point-min))
8718 (org-show-subtree)
8719 (and idprop (if org-clone-delete-id
8720 (org-entry-delete nil "ID")
8721 (org-id-get-create t)))
8722 (unless (= n 0)
8723 (while (re-search-forward org-clock-re nil t)
8724 (kill-whole-line))
8725 (goto-char (point-min))
8726 (while (re-search-forward drawer-re nil t)
8727 (org-remove-empty-drawer-at (point))))
8728 (goto-char (point-min))
8729 (when doshift
8730 (while (re-search-forward org-ts-regexp-both nil t)
8731 (org-timestamp-change (* n shift-n) shift-what))
8732 (unless (= n n-no-remove)
8733 (goto-char (point-min))
8734 (while (re-search-forward org-ts-regexp nil t)
8735 (save-excursion
8736 (goto-char (match-beginning 0))
8737 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8738 (delete-region (match-beginning 1) (match-end 1)))))))
8739 (setq task (buffer-string)))
8740 (insert task))
8741 (goto-char beg)))
8743 ;;; Outline Sorting
8745 (defun org-sort (with-case)
8746 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8747 Optional argument WITH-CASE means sort case-sensitively."
8748 (interactive "P")
8749 (cond
8750 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8751 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8753 (org-call-with-arg 'org-sort-entries with-case))))
8755 (defun org-sort-remove-invisible (s)
8756 "Remove invisible links from string S."
8757 (remove-text-properties 0 (length s) org-rm-props s)
8758 (while (string-match org-bracket-link-regexp s)
8759 (setq s (replace-match (if (match-end 2)
8760 (match-string 3 s)
8761 (match-string 1 s))
8762 t t s)))
8763 (let ((st (format " %s " s)))
8764 (while (string-match org-emph-re st)
8765 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8766 (setq s (substring st 1 -1)))
8769 (defvar org-priority-regexp) ; defined later in the file
8771 (defvar org-after-sorting-entries-or-items-hook nil
8772 "Hook that is run after a bunch of entries or items have been sorted.
8773 When children are sorted, the cursor is in the parent line when this
8774 hook gets called. When a region or a plain list is sorted, the cursor
8775 will be in the first entry of the sorted region/list.")
8777 (defun org-sort-entries
8778 (&optional with-case sorting-type getkey-func compare-func property)
8779 "Sort entries on a certain level of an outline tree.
8780 If there is an active region, the entries in the region are sorted.
8781 Else, if the cursor is before the first entry, sort the top-level items.
8782 Else, the children of the entry at point are sorted.
8784 Sorting can be alphabetically, numerically, by date/time as given by
8785 a time stamp, by a property, by priority order, or by a custom function.
8787 The command prompts for the sorting type unless it has been given to the
8788 function through the SORTING-TYPE argument, which needs to be a character,
8789 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8790 the precise meaning of each character:
8792 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8793 c By creation time, which is assumed to be the first inactive time stamp
8794 at the beginning of a line.
8795 d By deadline date/time.
8796 k By clocking time.
8797 n Numerically, by converting the beginning of the entry/item to a number.
8798 o By order of TODO keywords.
8799 p By priority according to the cookie.
8800 r By the value of a property.
8801 s By scheduled date/time.
8802 t By date/time, either the first active time stamp in the entry, or, if
8803 none exist, by the first inactive one.
8805 Capital letters will reverse the sort order.
8807 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8808 called with point at the beginning of the record. It must return either
8809 a string or a number that should serve as the sorting key for that record.
8811 Comparing entries ignores case by default. However, with an optional argument
8812 WITH-CASE, the sorting considers case as well.
8814 Sorting is done against the visible part of the headlines, it ignores hidden
8815 links.
8817 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8818 (interactive "P")
8819 (let ((case-func (if with-case 'identity 'downcase))
8820 (cmstr
8821 ;; The clock marker is lost when using `sort-subr', let's
8822 ;; store the clocking string.
8823 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8824 (save-excursion
8825 (goto-char org-clock-marker)
8826 (buffer-substring-no-properties (line-beginning-position)
8827 (point)))))
8828 start beg end stars re re2
8829 txt what tmp)
8830 ;; Find beginning and end of region to sort
8831 (cond
8832 ((org-region-active-p)
8833 ;; we will sort the region
8834 (setq end (region-end)
8835 what "region")
8836 (goto-char (region-beginning))
8837 (unless (org-at-heading-p) (outline-next-heading))
8838 (setq start (point)))
8839 ((or (org-at-heading-p)
8840 (ignore-errors (progn (org-back-to-heading) t)))
8841 ;; we will sort the children of the current headline
8842 (org-back-to-heading)
8843 (setq start (point)
8844 end (progn (org-end-of-subtree t t)
8845 (or (bolp) (insert "\n"))
8846 (when (>= (org-back-over-empty-lines) 1)
8847 (forward-line 1))
8848 (point))
8849 what "children")
8850 (goto-char start)
8851 (outline-show-subtree)
8852 (outline-next-heading))
8854 ;; we will sort the top-level entries in this file
8855 (goto-char (point-min))
8856 (or (org-at-heading-p) (outline-next-heading))
8857 (setq start (point))
8858 (goto-char (point-max))
8859 (beginning-of-line 1)
8860 (when (looking-at ".*?\\S-")
8861 ;; File ends in a non-white line
8862 (end-of-line 1)
8863 (insert "\n"))
8864 (setq end (point-max))
8865 (setq what "top-level")
8866 (goto-char start)
8867 (outline-show-all)))
8869 (setq beg (point))
8870 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8872 (looking-at "\\(\\*+\\)")
8873 (setq stars (match-string 1)
8874 re (concat "^" (regexp-quote stars) " +")
8875 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8876 txt (buffer-substring beg end))
8877 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8878 (when (and (not (equal stars "*")) (string-match re2 txt))
8879 (user-error "Region to sort contains a level above the first entry"))
8881 (unless sorting-type
8882 (message
8883 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8884 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8885 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8886 what)
8887 (setq sorting-type (read-char-exclusive))
8889 (unless getkey-func
8890 (and (= (downcase sorting-type) ?f)
8891 (setq getkey-func
8892 (completing-read "Sort using function: "
8893 obarray 'fboundp t nil nil))
8894 (setq getkey-func (intern getkey-func))))
8896 (and (= (downcase sorting-type) ?r)
8897 (not property)
8898 (setq property
8899 (completing-read "Property: "
8900 (mapcar #'list (org-buffer-property-keys t))
8901 nil t))))
8903 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8904 (message "Sorting entries...")
8906 (save-restriction
8907 (narrow-to-region start end)
8908 (let ((dcst (downcase sorting-type))
8909 (case-fold-search nil)
8910 (now (current-time)))
8911 (sort-subr
8912 (/= dcst sorting-type)
8913 ;; This function moves to the beginning character of the "record" to
8914 ;; be sorted.
8915 (lambda nil
8916 (if (re-search-forward re nil t)
8917 (goto-char (match-beginning 0))
8918 (goto-char (point-max))))
8919 ;; This function moves to the last character of the "record" being
8920 ;; sorted.
8921 (lambda nil
8922 (save-match-data
8923 (condition-case nil
8924 (outline-forward-same-level 1)
8925 (error
8926 (goto-char (point-max))))))
8927 ;; This function returns the value that gets sorted against.
8928 (lambda nil
8929 (cond
8930 ((= dcst ?n)
8931 (if (looking-at org-complex-heading-regexp)
8932 (string-to-number (org-sort-remove-invisible (match-string 4)))
8933 nil))
8934 ((= dcst ?a)
8935 (if (looking-at org-complex-heading-regexp)
8936 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8937 nil))
8938 ((= dcst ?k)
8939 (or (get-text-property (point) :org-clock-minutes) 0))
8940 ((= dcst ?t)
8941 (let ((end (save-excursion (outline-next-heading) (point))))
8942 (if (or (re-search-forward org-ts-regexp end t)
8943 (re-search-forward org-ts-regexp-both end t))
8944 (org-time-string-to-seconds (match-string 0))
8945 (org-float-time now))))
8946 ((= dcst ?c)
8947 (let ((end (save-excursion (outline-next-heading) (point))))
8948 (if (re-search-forward
8949 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8950 end t)
8951 (org-time-string-to-seconds (match-string 0))
8952 (org-float-time now))))
8953 ((= dcst ?s)
8954 (let ((end (save-excursion (outline-next-heading) (point))))
8955 (if (re-search-forward org-scheduled-time-regexp end t)
8956 (org-time-string-to-seconds (match-string 1))
8957 (org-float-time now))))
8958 ((= dcst ?d)
8959 (let ((end (save-excursion (outline-next-heading) (point))))
8960 (if (re-search-forward org-deadline-time-regexp end t)
8961 (org-time-string-to-seconds (match-string 1))
8962 (org-float-time now))))
8963 ((= dcst ?p)
8964 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8965 (string-to-char (match-string 2))
8966 org-default-priority))
8967 ((= dcst ?r)
8968 (or (org-entry-get nil property) ""))
8969 ((= dcst ?o)
8970 (when (looking-at org-complex-heading-regexp)
8971 (let* ((m (match-string 2))
8972 (s (if (member m org-done-keywords) '- '+)))
8973 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8974 ((= dcst ?f)
8975 (if getkey-func
8976 (progn
8977 (setq tmp (funcall getkey-func))
8978 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8979 tmp)
8980 (error "Invalid key function `%s'" getkey-func)))
8981 (t (error "Invalid sorting type `%c'" sorting-type))))
8983 (cond
8984 ((= dcst ?a) 'string<)
8985 ((= dcst ?f) compare-func)
8986 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8987 (run-hooks 'org-after-sorting-entries-or-items-hook)
8988 ;; Reset the clock marker if needed
8989 (when cmstr
8990 (save-excursion
8991 (goto-char start)
8992 (search-forward cmstr nil t)
8993 (move-marker org-clock-marker (point))))
8994 (message "Sorting entries...done")))
8996 ;;; The orgstruct minor mode
8998 ;; Define a minor mode which can be used in other modes in order to
8999 ;; integrate the org-mode structure editing commands.
9001 ;; This is really a hack, because the org-mode structure commands use
9002 ;; keys which normally belong to the major mode. Here is how it
9003 ;; works: The minor mode defines all the keys necessary to operate the
9004 ;; structure commands, but wraps the commands into a function which
9005 ;; tests if the cursor is currently at a headline or a plain list
9006 ;; item. If that is the case, the structure command is used,
9007 ;; temporarily setting many Org-mode variables like regular
9008 ;; expressions for filling etc. However, when any of those keys is
9009 ;; used at a different location, function uses `key-binding' to look
9010 ;; up if the key has an associated command in another currently active
9011 ;; keymap (minor modes, major mode, global), and executes that
9012 ;; command. There might be problems if any of the keys is otherwise
9013 ;; used as a prefix key.
9015 (defcustom orgstruct-heading-prefix-regexp ""
9016 "Regexp that matches the custom prefix of Org headlines in
9017 orgstruct(++)-mode."
9018 :group 'org
9019 :version "24.4"
9020 :package-version '(Org . "8.3")
9021 :type 'regexp)
9022 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9024 (defcustom orgstruct-setup-hook nil
9025 "Hook run after orgstruct-mode-map is filled."
9026 :group 'org
9027 :version "24.4"
9028 :package-version '(Org . "8.0")
9029 :type 'hook)
9031 (defvar orgstruct-initialized nil)
9033 (defvar org-local-vars nil
9034 "List of local variables, for use by `orgstruct-mode'.")
9036 ;;;###autoload
9037 (define-minor-mode orgstruct-mode
9038 "Toggle the minor mode `orgstruct-mode'.
9039 This mode is for using Org-mode structure commands in other
9040 modes. The following keys behave as if Org-mode were active, if
9041 the cursor is on a headline, or on a plain list item (both as
9042 defined by Org-mode)."
9043 nil " OrgStruct" (make-sparse-keymap)
9044 (funcall (if orgstruct-mode
9045 'add-to-invisibility-spec
9046 'remove-from-invisibility-spec)
9047 '(outline . t))
9048 (when orgstruct-mode
9049 (org-load-modules-maybe)
9050 (unless orgstruct-initialized
9051 (orgstruct-setup)
9052 (setq orgstruct-initialized t))))
9054 ;;;###autoload
9055 (defun turn-on-orgstruct ()
9056 "Unconditionally turn on `orgstruct-mode'."
9057 (orgstruct-mode 1))
9059 (defvar-local orgstruct-is-++ nil
9060 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9061 (defvar-local org-fb-vars nil)
9062 (defun orgstruct++-mode (&optional arg)
9063 "Toggle `orgstruct-mode', the enhanced version of it.
9064 In addition to setting orgstruct-mode, this also exports all
9065 indentation and autofilling variables from org-mode into the
9066 buffer. It will also recognize item context in multiline items."
9067 (interactive "P")
9068 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9069 (if (< arg 1)
9070 (progn (orgstruct-mode -1)
9071 (dolist (v org-fb-vars)
9072 (set (make-local-variable (car v))
9073 (if (eq (car-safe (cadr v)) 'quote)
9074 (cl-cadadr v)
9075 (nth 1 v)))))
9076 (orgstruct-mode 1)
9077 (setq org-fb-vars nil)
9078 (unless org-local-vars
9079 (setq org-local-vars (org-get-local-variables)))
9080 (let (var val)
9081 (dolist (x org-local-vars)
9082 (when (string-match
9083 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9084 \\|fill-prefix\\|indent-\\)"
9085 (symbol-name (car x)))
9086 (setq var (car x) val (nth 1 x))
9087 (push (list var `(quote ,(eval var))) org-fb-vars)
9088 (set (make-local-variable var)
9089 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9090 (setq-local orgstruct-is-++ t))))
9092 ;;;###autoload
9093 (defun turn-on-orgstruct++ ()
9094 "Unconditionally turn on `orgstruct++-mode'."
9095 (orgstruct++-mode 1))
9097 (defun orgstruct-error ()
9098 "Error when there is no default binding for a structure key."
9099 (interactive)
9100 (funcall (if (fboundp 'user-error)
9101 'user-error
9102 'error)
9103 "This key has no function outside structure elements"))
9105 (defun orgstruct-setup ()
9106 "Setup orgstruct keymap."
9107 (dolist (cell '((org-demote . t)
9108 (org-metaleft . t)
9109 (org-metaright . t)
9110 (org-promote . t)
9111 (org-shiftmetaleft . t)
9112 (org-shiftmetaright . t)
9113 org-backward-element
9114 org-backward-heading-same-level
9115 org-ctrl-c-ret
9116 org-ctrl-c-minus
9117 org-ctrl-c-star
9118 org-cycle
9119 org-forward-heading-same-level
9120 org-insert-heading
9121 org-insert-heading-respect-content
9122 org-kill-note-or-show-branches
9123 org-mark-subtree
9124 org-meta-return
9125 org-metadown
9126 org-metaup
9127 org-narrow-to-subtree
9128 org-promote-subtree
9129 org-reveal
9130 org-shiftdown
9131 org-shiftleft
9132 org-shiftmetadown
9133 org-shiftmetaup
9134 org-shiftright
9135 org-shifttab
9136 org-shifttab
9137 org-shiftup
9138 org-show-children
9139 org-show-subtree
9140 org-sort
9141 org-up-element
9142 outline-demote
9143 outline-next-visible-heading
9144 outline-previous-visible-heading
9145 outline-promote
9146 outline-up-heading))
9147 (let ((f (or (car-safe cell) cell))
9148 (disable-when-heading-prefix (cdr-safe cell)))
9149 (when (fboundp f)
9150 (let ((new-bindings))
9151 (dolist (binding (nconc (where-is-internal f org-mode-map)
9152 (where-is-internal f outline-mode-map)))
9153 (push binding new-bindings)
9154 ;; TODO use local-function-key-map
9155 (dolist (rep '(("<tab>" . "TAB")
9156 ("<return>" . "RET")
9157 ("<escape>" . "ESC")
9158 ("<delete>" . "DEL")))
9159 (setq binding (read-kbd-macro
9160 (let ((case-fold-search))
9161 (replace-regexp-in-string
9162 (regexp-quote (cdr rep))
9163 (car rep)
9164 (key-description binding)))))
9165 (cl-pushnew binding new-bindings :test 'equal)))
9166 (dolist (binding new-bindings)
9167 (let ((key (lookup-key orgstruct-mode-map binding)))
9168 (when (or (not key) (numberp key))
9169 (ignore-errors
9170 (org-defkey orgstruct-mode-map
9171 binding
9172 (orgstruct-make-binding
9173 f binding disable-when-heading-prefix))))))))))
9174 (run-hooks 'orgstruct-setup-hook))
9176 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9177 "Create a function for binding in the structure minor mode.
9178 FUN is the command to call inside a table. KEY is the key that
9179 should be checked in for a command to execute outside of tables.
9180 Non-nil `disable-when-heading-prefix' means to disable the command
9181 if `orgstruct-heading-prefix-regexp' is not empty."
9182 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9183 (let ((nname name)
9184 (i 0))
9185 (while (fboundp (intern nname))
9186 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9187 (setq name (intern nname)))
9188 (eval
9189 (let ((bindings '((org-heading-regexp
9190 (concat "^"
9191 orgstruct-heading-prefix-regexp
9192 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9193 (org-outline-regexp
9194 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9195 (org-outline-regexp-bol
9196 (concat "^" org-outline-regexp))
9197 (outline-regexp org-outline-regexp)
9198 (outline-heading-end-regexp "\n")
9199 (outline-level 'org-outline-level)
9200 (outline-heading-alist))))
9201 `(defun ,name (arg)
9202 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9203 "Outside of structure, run the binding of `"
9204 (key-description key) "'."
9205 (when disable-when-heading-prefix
9206 (concat
9207 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9208 "back to the default binding due to limitations of Org's implementation of\n"
9209 "`" (symbol-name fun) "'.")))
9210 (interactive "p")
9211 (let* ((disable
9212 ,(and disable-when-heading-prefix
9213 '(not (string= orgstruct-heading-prefix-regexp ""))))
9214 (fallback
9215 (or disable
9216 (not
9217 (let* ,bindings
9218 (org-context-p 'headline 'item
9219 ,(when (memq fun
9220 '(org-insert-heading
9221 org-insert-heading-respect-content
9222 org-meta-return))
9223 '(when orgstruct-is-++
9224 'item-body))))))))
9225 (if fallback
9226 (let* ((orgstruct-mode)
9227 (binding
9228 (let ((key ,key))
9229 (catch 'exit
9230 (dolist
9231 (rep
9232 '(nil
9233 ("<\\([^>]*\\)tab>" . "\\1TAB")
9234 ("<\\([^>]*\\)return>" . "\\1RET")
9235 ("<\\([^>]*\\)escape>" . "\\1ESC")
9236 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9237 nil)
9238 (when rep
9239 (setq key (read-kbd-macro
9240 (let ((case-fold-search))
9241 (replace-regexp-in-string
9242 (car rep)
9243 (cdr rep)
9244 (key-description key))))))
9245 (when (key-binding key)
9246 (throw 'exit (key-binding key))))))))
9247 (if (keymapp binding)
9248 (org-set-transient-map binding)
9249 (let ((func (or binding
9250 (unless disable
9251 'orgstruct-error))))
9252 (when func
9253 (call-interactively func)))))
9254 (org-run-like-in-org-mode
9255 (lambda ()
9256 (interactive)
9257 (let* ,bindings
9258 (call-interactively ',fun)))))))))
9259 name))
9261 (defun org-contextualize-keys (alist contexts)
9262 "Return valid elements in ALIST depending on CONTEXTS.
9264 `org-agenda-custom-commands' or `org-capture-templates' are the
9265 values used for ALIST, and `org-agenda-custom-commands-contexts'
9266 or `org-capture-templates-contexts' are the associated contexts
9267 definitions."
9268 (let ((contexts
9269 ;; normalize contexts
9270 (mapcar
9271 (lambda(c) (cond ((listp (cadr c))
9272 (list (car c) (car c) (nth 1 c)))
9273 ((string= "" (cadr c))
9274 (list (car c) (car c) (nth 2 c)))
9275 (t c)))
9276 contexts))
9277 (a alist) r s)
9278 ;; loop over all commands or templates
9279 (dolist (c a)
9280 (let (vrules repl)
9281 (cond
9282 ((not (assoc (car c) contexts))
9283 (push c r))
9284 ((and (assoc (car c) contexts)
9285 (setq vrules (org-contextualize-validate-key
9286 (car c) contexts)))
9287 (mapc (lambda (vr)
9288 (unless (equal (car vr) (cadr vr))
9289 (setq repl vr)))
9290 vrules)
9291 (if (not repl) (push c r)
9292 (push (cadr repl) s)
9293 (push
9294 (cons (car c)
9295 (cdr (or (assoc (cadr repl) alist)
9296 (error "Undefined key `%s' as contextual replacement for `%s'"
9297 (cadr repl) (car c)))))
9298 r))))))
9299 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9300 (delq
9302 (delete-dups
9303 (mapcar (lambda (x)
9304 (let ((tpl (car x)))
9305 (unless (delq
9307 (mapcar (lambda (y)
9308 (equal y tpl))
9310 x)))
9311 (reverse r))))))
9313 (defun org-contextualize-validate-key (key contexts)
9314 "Check CONTEXTS for agenda or capture KEY."
9315 (let (res)
9316 (dolist (r contexts)
9317 (dolist (rr (car (last r)))
9318 (when
9319 (and (equal key (car r))
9320 (if (functionp rr) (funcall rr)
9321 (or (and (eq (car rr) 'in-file)
9322 (buffer-file-name)
9323 (string-match (cdr rr) (buffer-file-name)))
9324 (and (eq (car rr) 'in-mode)
9325 (string-match (cdr rr) (symbol-name major-mode)))
9326 (and (eq (car rr) 'in-buffer)
9327 (string-match (cdr rr) (buffer-name)))
9328 (when (and (eq (car rr) 'not-in-file)
9329 (buffer-file-name))
9330 (not (string-match (cdr rr) (buffer-file-name))))
9331 (when (eq (car rr) 'not-in-mode)
9332 (not (string-match (cdr rr) (symbol-name major-mode))))
9333 (when (eq (car rr) 'not-in-buffer)
9334 (not (string-match (cdr rr) (buffer-name)))))))
9335 (push r res))))
9336 (delete-dups (delq nil res))))
9338 (defun org-context-p (&rest contexts)
9339 "Check if local context is any of CONTEXTS.
9340 Possible values in the list of contexts are `table', `headline', and `item'."
9341 (let ((pos (point)))
9342 (goto-char (point-at-bol))
9343 (prog1 (or (and (memq 'table contexts)
9344 (looking-at "[ \t]*|"))
9345 (and (memq 'headline contexts)
9346 (looking-at org-outline-regexp))
9347 (and (memq 'item contexts)
9348 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9349 (and (memq 'item-body contexts)
9350 (org-in-item-p)))
9351 (goto-char pos))))
9353 (defconst org-unique-local-variables
9354 '(org-element--cache
9355 org-element--cache-objects
9356 org-element--cache-sync-keys
9357 org-element--cache-sync-requests
9358 org-element--cache-sync-timer)
9359 "List of local variables that cannot be transferred to another buffer.")
9361 (defun org-get-local-variables ()
9362 "Return a list of all local variables in an Org mode buffer."
9363 (delq nil
9364 (mapcar
9365 (lambda (x)
9366 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9367 (name (car binding)))
9368 (and (not (get name 'org-state))
9369 (not (memq name org-unique-local-variables))
9370 (string-match-p
9371 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9372 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9373 (symbol-name name))
9374 binding)))
9375 (with-temp-buffer
9376 (org-mode)
9377 (buffer-local-variables)))))
9379 (defun org-clone-local-variables (from-buffer &optional regexp)
9380 "Clone local variables from FROM-BUFFER.
9381 Optional argument REGEXP selects variables to clone."
9382 (dolist (pair (buffer-local-variables from-buffer))
9383 (let ((name (car pair)))
9384 (when (and (symbolp name)
9385 (not (memq name org-unique-local-variables))
9386 (or (null regexp) (string-match regexp (symbol-name name))))
9387 (set (make-local-variable name) (cdr pair))))))
9389 ;;;###autoload
9390 (defun org-run-like-in-org-mode (cmd)
9391 "Run a command, pretending that the current buffer is in Org-mode.
9392 This will temporarily bind local variables that are typically bound in
9393 Org-mode to the values they have in Org-mode, and then interactively
9394 call CMD."
9395 (org-load-modules-maybe)
9396 (unless org-local-vars
9397 (setq org-local-vars (org-get-local-variables)))
9398 (let (binds)
9399 (dolist (var org-local-vars)
9400 (when (or (not (boundp (car var)))
9401 (eq (symbol-value (car var))
9402 (default-value (car var))))
9403 (push (list (car var) `(quote ,(cadr var))) binds)))
9404 (eval `(let ,binds
9405 (call-interactively (quote ,cmd))))))
9407 (defun org-get-category (&optional pos force-refresh)
9408 "Get the category applying to position POS."
9409 (save-match-data
9410 (when force-refresh (org-refresh-category-properties))
9411 (let ((pos (or pos (point))))
9412 (or (get-text-property pos 'org-category)
9413 (progn (org-refresh-category-properties)
9414 (get-text-property pos 'org-category))))))
9416 ;;; Refresh properties
9418 (defun org-refresh-properties (dprop tprop)
9419 "Refresh buffer text properties.
9420 DPROP is the drawer property and TPROP is either the
9421 corresponding text property to set, or an alist with each element
9422 being a text property (as a symbol) and a function to apply to
9423 the value of the drawer property."
9424 (let ((case-fold-search t)
9425 (inhibit-read-only t))
9426 (org-with-silent-modifications
9427 (save-excursion
9428 (save-restriction
9429 (widen)
9430 (goto-char (point-min))
9431 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9432 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9434 (defun org-refresh-property (tprop p)
9435 "Refresh the buffer text property TPROP from the drawer property P.
9436 The refresh happens only for the current tree (not subtree)."
9437 (unless (org-before-first-heading-p)
9438 (save-excursion
9439 (org-back-to-heading t)
9440 (if (symbolp tprop)
9441 ;; TPROP is a text property symbol
9442 (put-text-property
9443 (point) (or (outline-next-heading) (point-max)) tprop p)
9444 ;; TPROP is an alist with (properties . function) elements
9445 (dolist (al tprop)
9446 (save-excursion
9447 (put-text-property
9448 (line-beginning-position) (or (outline-next-heading) (point-max))
9449 (car al)
9450 (funcall (cdr al) p))))))))
9452 (defun org-refresh-category-properties ()
9453 "Refresh category text properties in the buffer."
9454 (let ((case-fold-search t)
9455 (inhibit-read-only t)
9456 (default-category
9457 (cond ((null org-category)
9458 (if buffer-file-name
9459 (file-name-sans-extension
9460 (file-name-nondirectory buffer-file-name))
9461 "???"))
9462 ((symbolp org-category) (symbol-name org-category))
9463 (t org-category))))
9464 (org-with-silent-modifications
9465 (org-with-wide-buffer
9466 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9467 ;; This is the default category for the buffer. If none is
9468 ;; found, fall-back to `org-category' or buffer file name.
9469 (put-text-property
9470 (point-min) (point-max)
9471 'org-category
9472 (catch 'buffer-category
9473 (goto-char (point-max))
9474 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9475 (let ((element (org-element-at-point)))
9476 (when (eq (org-element-type element) 'keyword)
9477 (throw 'buffer-category
9478 (org-element-property :value element)))))
9479 default-category))
9480 ;; Set sub-tree specific categories.
9481 (goto-char (point-min))
9482 (let ((regexp (org-re-property "CATEGORY")))
9483 (while (re-search-forward regexp nil t)
9484 (let ((value (org-match-string-no-properties 3)))
9485 (when (org-at-property-p)
9486 (put-text-property
9487 (save-excursion (org-back-to-heading t) (point))
9488 (save-excursion (org-end-of-subtree t t) (point))
9489 'org-category
9490 value)))))))))
9492 (defun org-refresh-stats-properties ()
9493 "Refresh stats text properties in the buffer."
9494 (let (stats)
9495 (org-with-silent-modifications
9496 (save-excursion
9497 (save-restriction
9498 (widen)
9499 (goto-char (point-min))
9500 (while (re-search-forward
9501 (concat org-outline-regexp-bol ".*"
9502 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9503 nil t)
9504 (setq stats (cond ((equal (match-string 3) "0") 0)
9505 ((match-string 2)
9506 (/ (* (string-to-number (match-string 2)) 100)
9507 (string-to-number (match-string 3))))
9508 (t (string-to-number (match-string 1)))))
9509 (org-back-to-heading t)
9510 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9511 'org-stats stats)))))))
9513 (defun org-refresh-effort-properties ()
9514 "Refresh effort properties"
9515 (org-refresh-properties
9516 org-effort-property
9517 '((effort . identity)
9518 (effort-minutes . org-duration-string-to-minutes))))
9520 ;;;; Link Stuff
9522 ;;; Link abbreviations
9524 (defun org-link-expand-abbrev (link)
9525 "Apply replacements as defined in `org-link-abbrev-alist'."
9526 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9527 (let* ((key (match-string 1 link))
9528 (as (or (assoc key org-link-abbrev-alist-local)
9529 (assoc key org-link-abbrev-alist)))
9530 (tag (and (match-end 2) (match-string 3 link)))
9531 rpl)
9532 (if (not as)
9533 link
9534 (setq rpl (cdr as))
9535 (cond
9536 ((symbolp rpl) (funcall rpl tag))
9537 ((string-match "%(\\([^)]+\\))" rpl)
9538 (replace-match
9539 (save-match-data
9540 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9541 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9542 ((string-match "%h" rpl)
9543 (replace-match (url-hexify-string (or tag "")) t t rpl))
9544 (t (concat rpl tag)))))
9545 link))
9547 ;;; Storing and inserting links
9549 (defvar org-insert-link-history nil
9550 "Minibuffer history for links inserted with `org-insert-link'.")
9552 (defvar org-stored-links nil
9553 "Contains the links stored with `org-store-link'.")
9555 (defvar org-store-link-plist nil
9556 "Plist with info about the most recently link created with `org-store-link'.")
9558 (defvar org-link-protocols nil
9559 "Link protocols added to Org-mode using `org-add-link-type'.")
9561 (defvar org-store-link-functions nil
9562 "List of functions that are called to create and store a link.
9563 Each function will be called in turn until one returns a non-nil
9564 value. Each function should check if it is responsible for creating
9565 this link (for example by looking at the major mode).
9566 If not, it must exit and return nil.
9567 If yes, it should return a non-nil value after a calling
9568 `org-store-link-props' with a list of properties and values.
9569 Special properties are:
9571 :type The link prefix, like \"http\". This must be given.
9572 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9573 This is obligatory as well.
9574 :description Optional default description for the second pair
9575 of brackets in an Org-mode link. The user can still change
9576 this when inserting this link into an Org-mode buffer.
9578 In addition to these, any additional properties can be specified
9579 and then used in capture templates.")
9581 (defun org-add-link-type (type &optional follow export)
9582 "Add TYPE to the list of `org-link-types'.
9583 Re-compute all regular expressions depending on `org-link-types'
9585 FOLLOW and EXPORT are two functions.
9587 FOLLOW should take the link path as the single argument and do whatever
9588 is necessary to follow the link, for example find a file or display
9589 a mail message.
9591 EXPORT should format the link path for export to one of the export formats.
9592 It should be a function accepting three arguments:
9594 path the path of the link, the text after the prefix (like \"http:\")
9595 desc the description of the link, if any
9596 format the export format, a symbol like `html' or `latex' or `ascii'.
9598 The function may use the FORMAT information to return different values
9599 depending on the format. The return value will be put literally into
9600 the exported file. If the return value is nil, this means Org should
9601 do what it normally does with links which do not have EXPORT defined.
9603 Org mode has a built-in default for exporting links. If you are happy with
9604 this default, there is no need to define an export function for the link
9605 type. For a simple example of an export function, see `org-bbdb.el'."
9606 (add-to-list 'org-link-types type t)
9607 (org-make-link-regexps)
9608 (org-element-update-syntax)
9609 (if (assoc type org-link-protocols)
9610 (setcdr (assoc type org-link-protocols) (list follow export))
9611 (push (list type follow export) org-link-protocols)))
9613 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9614 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9616 ;;;###autoload
9617 (defun org-store-link (arg)
9618 "\\<org-mode-map>Store an org-link to the current location.
9619 This link is added to `org-stored-links' and can later be inserted
9620 into an Org buffer with \\[org-insert-link].
9622 For some link types, a prefix ARG is interpreted.
9623 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9624 For file links, ARG negates `org-context-in-file-links'.
9626 A double prefix ARG force skipping storing functions that are not
9627 part of Org's core.
9629 A triple prefix ARG force storing a link for each line in the
9630 active region."
9631 (interactive "P")
9632 (org-load-modules-maybe)
9633 (if (and (equal arg '(64)) (org-region-active-p))
9634 (save-excursion
9635 (let ((end (region-end)))
9636 (goto-char (region-beginning))
9637 (set-mark (point))
9638 (while (< (point-at-eol) end)
9639 (move-end-of-line 1) (activate-mark)
9640 (let (current-prefix-arg)
9641 (call-interactively 'org-store-link))
9642 (move-beginning-of-line 2)
9643 (set-mark (point)))))
9644 (org-with-limited-levels
9645 (setq org-store-link-plist nil)
9646 (let (link cpltxt desc description search
9647 txt custom-id agenda-link sfuns sfunsn)
9648 (cond
9650 ;; Store a link using an external link type
9651 ((and (not (equal arg '(16)))
9652 (setq sfuns
9653 (delq
9654 nil (mapcar (lambda (f)
9655 (let (fs) (if (funcall f) (push f fs))))
9656 org-store-link-functions))
9657 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9658 (or (and (cdr sfuns)
9659 (funcall (intern
9660 (completing-read
9661 "Which function for creating the link? "
9662 sfunsn nil t (car sfunsn)))))
9663 (funcall (caar sfuns)))
9664 (setq link (plist-get org-store-link-plist :link)
9665 desc (or (plist-get org-store-link-plist
9666 :description)
9667 link))))
9669 ;; Store a link from a source code buffer.
9670 ((org-src-edit-buffer-p)
9671 (cond
9672 ((save-excursion
9673 (beginning-of-line)
9674 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9675 "[ \t]*$")))
9676 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9677 ((org-called-interactively-p 'any)
9678 (let (label)
9679 (while (or (not label)
9680 (org-with-wide-buffer
9681 (goto-char (point-min))
9682 (re-search-forward
9683 (regexp-quote (format org-coderef-label-format label))
9684 nil t)))
9685 (when label (message "Label exists already") (sit-for 2))
9686 (setq label (read-string "Code line label: " label)))
9687 (end-of-line)
9688 (setq link (format org-coderef-label-format label))
9689 (let ((gc (- 79 (length link))))
9690 (if (< (current-column) gc) (org-move-to-column gc t)
9691 (insert " ")))
9692 (insert link)
9693 (setq link (concat "(" label ")") desc nil)))
9694 (t (setq link nil))))
9696 ;; We are in the agenda, link to referenced location
9697 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9698 (let ((m (or (get-text-property (point) 'org-hd-marker)
9699 (get-text-property (point) 'org-marker))))
9700 (when m
9701 (org-with-point-at m
9702 (setq agenda-link
9703 (if (org-called-interactively-p 'any)
9704 (call-interactively 'org-store-link)
9705 (org-store-link nil)))))))
9707 ((eq major-mode 'calendar-mode)
9708 (let ((cd (calendar-cursor-to-date)))
9709 (setq link
9710 (format-time-string
9711 (car org-time-stamp-formats)
9712 (apply 'encode-time
9713 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9714 nil nil nil))))
9715 (org-store-link-props :type "calendar" :date cd)))
9717 ((eq major-mode 'help-mode)
9718 (setq link (concat "help:" (save-excursion
9719 (goto-char (point-min))
9720 (looking-at "^[^ ]+")
9721 (match-string 0))))
9722 (org-store-link-props :type "help"))
9724 ((eq major-mode 'w3-mode)
9725 (setq cpltxt (if (and (buffer-name)
9726 (not (string-match "Untitled" (buffer-name))))
9727 (buffer-name)
9728 (url-view-url t))
9729 link (url-view-url t))
9730 (org-store-link-props :type "w3" :url (url-view-url t)))
9732 ((eq major-mode 'image-mode)
9733 (setq cpltxt (concat "file:"
9734 (abbreviate-file-name buffer-file-name))
9735 link cpltxt)
9736 (org-store-link-props :type "image" :file buffer-file-name))
9738 ;; In dired, store a link to the file of the current line
9739 ((derived-mode-p 'dired-mode)
9740 (let ((file (dired-get-filename nil t)))
9741 (setq file (if file
9742 (abbreviate-file-name
9743 (expand-file-name (dired-get-filename nil t)))
9744 ;; otherwise, no file so use current directory.
9745 default-directory))
9746 (setq cpltxt (concat "file:" file)
9747 link cpltxt)))
9749 ((setq search (run-hook-with-args-until-success
9750 'org-create-file-search-functions))
9751 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9752 "::" search))
9753 (setq cpltxt (or description link)))
9755 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9756 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9757 (cond
9758 ;; Store a link using the target at point
9759 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9760 (setq cpltxt
9761 (concat "file:"
9762 (abbreviate-file-name
9763 (buffer-file-name (buffer-base-buffer)))
9764 "::" (match-string 1))
9765 link cpltxt))
9766 ((and (featurep 'org-id)
9767 (or (eq org-id-link-to-org-use-id t)
9768 (and (org-called-interactively-p 'any)
9769 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9770 (and (eq org-id-link-to-org-use-id
9771 'create-if-interactive-and-no-custom-id)
9772 (not custom-id))))
9773 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9774 ;; Store a link using the ID at point
9775 (setq link (condition-case nil
9776 (prog1 (org-id-store-link)
9777 (setq desc (or (plist-get org-store-link-plist
9778 :description)
9779 "")))
9780 (error
9781 ;; Probably before first headline, link only to file
9782 (concat "file:"
9783 (abbreviate-file-name
9784 (buffer-file-name (buffer-base-buffer))))))))
9786 ;; Just link to current headline
9787 (setq cpltxt (concat "file:"
9788 (abbreviate-file-name
9789 (buffer-file-name (buffer-base-buffer)))))
9790 ;; Add a context search string
9791 (when (org-xor org-context-in-file-links arg)
9792 (let* ((ee (org-element-at-point))
9793 (et (org-element-type ee))
9794 (ev (plist-get (cadr ee) :value))
9795 (ek (plist-get (cadr ee) :key))
9796 (eok (and (stringp ek) (string-match "name" ek))))
9797 (setq txt (cond
9798 ((org-at-heading-p) nil)
9799 ((and (eq et 'keyword) eok) ev)
9800 ((org-region-active-p)
9801 (buffer-substring (region-beginning) (region-end)))))
9802 (when (or (null txt) (string-match "\\S-" txt))
9803 (setq cpltxt
9804 (concat cpltxt "::"
9805 (condition-case nil
9806 (org-make-org-heading-search-string txt)
9807 (error "")))
9808 desc (or (and (eq et 'keyword) eok ev)
9809 (nth 4 (ignore-errors (org-heading-components)))
9810 "NONE")))))
9811 (when (string-match "::\\'" cpltxt)
9812 (setq cpltxt (substring cpltxt 0 -2)))
9813 (setq link cpltxt))))
9815 ((buffer-file-name (buffer-base-buffer))
9816 ;; Just link to this file here.
9817 (setq cpltxt (concat "file:"
9818 (abbreviate-file-name
9819 (buffer-file-name (buffer-base-buffer)))))
9820 ;; Add a context string.
9821 (when (org-xor org-context-in-file-links arg)
9822 (setq txt (if (org-region-active-p)
9823 (buffer-substring (region-beginning) (region-end))
9824 (buffer-substring (point-at-bol) (point-at-eol))))
9825 ;; Only use search option if there is some text.
9826 (when (string-match "\\S-" txt)
9827 (setq cpltxt
9828 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9829 desc "NONE")))
9830 (setq link cpltxt))
9832 ((org-called-interactively-p 'interactive)
9833 (user-error "No method for storing a link from this buffer"))
9835 (t (setq link nil)))
9837 ;; We're done setting link and desc, clean up
9838 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9839 (setq link (or link cpltxt)
9840 desc (or desc cpltxt))
9841 (cond ((equal desc "NONE") (setq desc nil))
9842 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9843 (let ((d0 (match-string 3 desc))
9844 (p0 (match-string 5 desc)))
9845 (setq desc
9846 (replace-regexp-in-string
9847 org-bracket-link-regexp
9848 (concat (or p0 d0)
9849 (if (equal (length (match-string 0 desc))
9850 (length desc)) "*" "")) desc)))))
9852 ;; Return the link
9853 (if (not (and (or (org-called-interactively-p 'any)
9854 executing-kbd-macro)
9855 link))
9856 (or agenda-link (and link (org-make-link-string link desc)))
9857 (push (list link desc) org-stored-links)
9858 (message "Stored: %s" (or desc link))
9859 (when custom-id
9860 (setq link (concat "file:" (abbreviate-file-name
9861 (buffer-file-name)) "::#" custom-id))
9862 (push (list link desc) org-stored-links))
9863 (car org-stored-links))))))
9865 (defun org-store-link-props (&rest plist)
9866 "Store link properties, extract names, addresses and dates."
9867 (let ((x (plist-get plist :from)))
9868 (when x
9869 (let ((adr (mail-extract-address-components x)))
9870 (setq plist (plist-put plist :fromname (car adr)))
9871 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9872 (let ((x (plist-get plist :to)))
9873 (when x
9874 (let ((adr (mail-extract-address-components x)))
9875 (setq plist (plist-put plist :toname (car adr)))
9876 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9877 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9878 (when x
9879 (setq plist (plist-put plist :date-timestamp
9880 (format-time-string
9881 (org-time-stamp-format t) x)))
9882 (setq plist (plist-put plist :date-timestamp-inactive
9883 (format-time-string
9884 (org-time-stamp-format t t) x)))))
9885 (let ((from (plist-get plist :from))
9886 (to (plist-get plist :to)))
9887 (when (and from to org-from-is-user-regexp)
9888 (setq plist
9889 (plist-put plist :fromto
9890 (if (string-match org-from-is-user-regexp from)
9891 (concat "to %t")
9892 (concat "from %f"))))))
9893 (setq org-store-link-plist plist))
9895 (defun org-add-link-props (&rest plist)
9896 "Add these properties to the link property list."
9897 (let (key value)
9898 (while plist
9899 (setq key (pop plist) value (pop plist))
9900 (setq org-store-link-plist
9901 (plist-put org-store-link-plist key value)))))
9903 (defun org-email-link-description (&optional fmt)
9904 "Return the description part of an email link.
9905 This takes information from `org-store-link-plist' and formats it
9906 according to FMT (default from `org-email-link-description-format')."
9907 (setq fmt (or fmt org-email-link-description-format))
9908 (let* ((p org-store-link-plist)
9909 (to (plist-get p :toaddress))
9910 (from (plist-get p :fromaddress))
9911 (table
9912 (list
9913 (cons "%c" (plist-get p :fromto))
9914 (cons "%F" (plist-get p :from))
9915 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9916 (cons "%T" (plist-get p :to))
9917 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9918 (cons "%s" (plist-get p :subject))
9919 (cons "%d" (plist-get p :date))
9920 (cons "%m" (plist-get p :message-id)))))
9921 (when (string-match "%c" fmt)
9922 ;; Check if the user wrote this message
9923 (if (and org-from-is-user-regexp from to
9924 (save-match-data (string-match org-from-is-user-regexp from)))
9925 (setq fmt (replace-match "to %t" t t fmt))
9926 (setq fmt (replace-match "from %f" t t fmt))))
9927 (org-replace-escapes fmt table)))
9929 (defun org-make-org-heading-search-string (&optional string)
9930 "Make search string for the current headline or STRING."
9931 (let ((s (or string
9932 (and (derived-mode-p 'org-mode)
9933 (save-excursion
9934 (org-back-to-heading t)
9935 (org-element-property :raw-value (org-element-at-point))))))
9936 (lines org-context-in-file-links))
9937 (or string (setq s (concat "*" s))) ; Add * for headlines
9938 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9939 (when (and string (integerp lines) (> lines 0))
9940 (let ((slines (org-split-string s "\n")))
9941 (when (< lines (length slines))
9942 (setq s (mapconcat
9943 'identity
9944 (reverse (nthcdr (- (length slines) lines)
9945 (reverse slines))) "\n")))))
9946 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9948 (defun org-make-link-string (link &optional description)
9949 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9950 (unless (org-string-nw-p link) (error "Empty link"))
9951 (let ((uri (cond ((string-match org-link-types-re link)
9952 (concat (match-string 1 link)
9953 (org-link-escape (substring link (match-end 1)))))
9954 ;; For readability, url-encode internal links only
9955 ;; when absolutely needed (i.e, when they contain
9956 ;; square brackets). File links however, are
9957 ;; encoded since, e.g., spaces are significant.
9958 ((or (file-name-absolute-p link)
9959 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
9960 (org-link-escape link))
9961 (t link)))
9962 (description
9963 (and (org-string-nw-p description)
9964 ;; Remove brackets from description, as they are fatal.
9965 (replace-regexp-in-string
9966 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9967 (org-trim description)))))
9968 (format "[[%s]%s]"
9970 (if description (format "[%s]" description) ""))))
9972 (defconst org-link-escape-chars
9973 ;;%20 %5B %5D %25
9974 '(?\s ?\[ ?\] ?%)
9975 "List of characters that should be escaped in a link when stored to Org.
9976 This is the list that is used for internal purposes.")
9978 (defconst org-link-escape-chars-browser
9979 ;;%20 %22
9980 '(?\s ?\")
9981 "List of characters to be escaped before handing over to the browser.
9982 If you consider using this constant then you probably want to use
9983 the function `org-link-escape-browser' instead. See there why
9984 this constant is a candidate to be removed once Org drops support
9985 for Emacs 24.1 and 24.2.")
9987 (defun org-link-escape (text &optional table merge)
9988 "Return percent escaped representation of TEXT.
9989 TEXT is a string with the text to escape.
9990 Optional argument TABLE is a list with characters that should be
9991 escaped. When nil, `org-link-escape-chars' is used.
9992 If optional argument MERGE is set, merge TABLE into
9993 `org-link-escape-chars'."
9994 (let ((characters-to-encode
9995 (cond ((null table) org-link-escape-chars)
9996 (merge (append org-link-escape-chars table))
9997 (t table))))
9998 (mapconcat
9999 (lambda (c)
10000 (if (or (memq c characters-to-encode)
10001 (and org-url-hexify-p (or (< c 32) (> c 126))))
10002 (mapconcat (lambda (e) (format "%%%.2X" e))
10003 (or (encode-coding-char c 'utf-8)
10004 (error "Unable to percent escape character: %c" c))
10006 (char-to-string c)))
10007 text "")))
10009 (defun org-link-escape-browser (text)
10010 "Escape some characters before handing over to the browser.
10011 This function is a candidate to be removed together with the
10012 constant `org-link-escape-chars-browser' once Org drops support
10013 for Emacs 24.1 and 24.2. All calls to this function will have to
10014 be replaced with `url-encode-url' which is available since Emacs
10015 24.3.1."
10016 ;; Example with the Org link
10017 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10018 ;; to open the browser with +subject:"Release 8.2" filled into the
10019 ;; query field: In this case the variable TEXT contains the
10020 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10021 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10022 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10023 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10024 (if (fboundp 'url-encode-url)
10025 (url-encode-url text)
10026 (if (org-string-match-p
10027 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10028 text)
10029 (org-link-escape text org-link-escape-chars-browser)
10030 text)))
10032 (defun org-link-unescape (str)
10033 "Unhex hexified Unicode parts in string STR.
10034 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10035 reciprocal of `org-link-escape', which see."
10036 (if (org-string-nw-p str)
10037 (replace-regexp-in-string
10038 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10039 str))
10041 (defun org-link-unescape-compound (hex)
10042 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10043 Note: this function also decodes single byte encodings like
10044 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10045 (save-match-data
10046 (let* ((bytes (cdr (split-string hex "%")))
10047 (ret "")
10048 (eat 0)
10049 (sum 0))
10050 (while bytes
10051 (let* ((val (string-to-number (pop bytes) 16))
10052 (shift-xor
10053 (if (= 0 eat)
10054 (cond
10055 ((>= val 252) (cons 6 252))
10056 ((>= val 248) (cons 5 248))
10057 ((>= val 240) (cons 4 240))
10058 ((>= val 224) (cons 3 224))
10059 ((>= val 192) (cons 2 192))
10060 (t (cons 0 0)))
10061 (cons 6 128))))
10062 (when (>= val 192) (setq eat (car shift-xor)))
10063 (setq val (logxor val (cdr shift-xor)))
10064 (setq sum (+ (lsh sum (car shift-xor)) val))
10065 (when (> eat 0) (setq eat (- eat 1)))
10066 (cond
10067 ((= 0 eat) ;multi byte
10068 (setq ret (concat ret (org-char-to-string sum)))
10069 (setq sum 0))
10070 ((not bytes) ; single byte(s)
10071 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10072 ret)))
10074 (defun org-link-unescape-single-byte-sequence (hex)
10075 "Unhexify hex-encoded single byte character sequences."
10076 (mapconcat (lambda (byte)
10077 (char-to-string (string-to-number byte 16)))
10078 (cdr (split-string hex "%")) ""))
10080 (defun org-xor (a b)
10081 "Exclusive or."
10082 (if a (not b) b))
10084 (defun org-fixup-message-id-for-http (s)
10085 "Replace special characters in a message id, so it can be used in an http query."
10086 (when (string-match "%" s)
10087 (setq s (mapconcat (lambda (c)
10088 (if (eq c ?%)
10089 "%25"
10090 (char-to-string c)))
10091 s "")))
10092 (while (string-match "<" s)
10093 (setq s (replace-match "%3C" t t s)))
10094 (while (string-match ">" s)
10095 (setq s (replace-match "%3E" t t s)))
10096 (while (string-match "@" s)
10097 (setq s (replace-match "%40" t t s)))
10100 (defun org-link-prettify (link)
10101 "Return a human-readable representation of LINK.
10102 The car of LINK must be a raw link.
10103 The cdr of LINK must be either a link description or nil."
10104 (let ((desc (or (cadr link) "<no description>")))
10105 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10106 "<" (car link) ">")))
10108 ;;;###autoload
10109 (defun org-insert-link-global ()
10110 "Insert a link like Org-mode does.
10111 This command can be called in any mode to insert a link in Org-mode syntax."
10112 (interactive)
10113 (org-load-modules-maybe)
10114 (org-run-like-in-org-mode 'org-insert-link))
10116 (defun org-insert-all-links (arg &optional pre post)
10117 "Insert all links in `org-stored-links'.
10118 When a universal prefix, do not delete the links from `org-stored-links'.
10119 When `ARG' is a number, insert the last N link(s).
10120 `PRE' and `POST' are optional arguments to define a string to
10121 prepend or to append."
10122 (interactive "P")
10123 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10124 (links (copy-sequence org-stored-links))
10125 (pr (or pre "- "))
10126 (po (or post "\n"))
10127 (cnt 1) l)
10128 (if (null org-stored-links)
10129 (message "No link to insert")
10130 (while (and (or (listp arg) (>= arg cnt))
10131 (setq l (if (listp arg)
10132 (pop links)
10133 (pop org-stored-links))))
10134 (setq cnt (1+ cnt))
10135 (insert pr)
10136 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10137 (insert po)))))
10139 (defun org-insert-last-stored-link (arg)
10140 "Insert the last link stored in `org-stored-links'."
10141 (interactive "p")
10142 (org-insert-all-links arg "" "\n"))
10144 (defun org-link-fontify-links-to-this-file ()
10145 "Fontify links to the current file in `org-stored-links'."
10146 (let ((f (buffer-file-name)) a b)
10147 (setq a (mapcar (lambda(l)
10148 (let ((ll (car l)))
10149 (when (and (string-match "^file:\\(.+\\)::" ll)
10150 (equal f (expand-file-name (match-string 1 ll))))
10151 ll)))
10152 org-stored-links))
10153 (when (featurep 'org-id)
10154 (setq b (mapcar (lambda(l)
10155 (let ((ll (car l)))
10156 (when (and (string-match "^id:\\(.+\\)$" ll)
10157 (equal f (expand-file-name
10158 (or (org-id-find-id-file
10159 (match-string 1 ll)) ""))))
10160 ll)))
10161 org-stored-links)))
10162 (mapcar (lambda(l)
10163 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10164 (delq nil (append a b)))))
10166 (defvar org--links-history nil)
10167 (defun org-insert-link (&optional complete-file link-location default-description)
10168 "Insert a link. At the prompt, enter the link.
10170 Completion can be used to insert any of the link protocol prefixes like
10171 http or ftp in use.
10173 The history can be used to select a link previously stored with
10174 `org-store-link'. When the empty string is entered (i.e. if you just
10175 press RET at the prompt), the link defaults to the most recently
10176 stored link. As SPC triggers completion in the minibuffer, you need to
10177 use M-SPC or C-q SPC to force the insertion of a space character.
10179 You will also be prompted for a description, and if one is given, it will
10180 be displayed in the buffer instead of the link.
10182 If there is already a link at point, this command will allow you to edit link
10183 and description parts.
10185 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10186 be selected using completion. The path to the file will be relative to the
10187 current directory if the file is in the current directory or a subdirectory.
10188 Otherwise, the link will be the absolute path as completed in the minibuffer
10189 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10190 option `org-link-file-path-type'.
10192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10193 the current directory or below.
10195 With three \\[universal-argument] prefixes, negate the meaning of
10196 `org-keep-stored-link-after-insertion'.
10198 If `org-make-link-description-function' is non-nil, this function will be
10199 called with the link target, and the result will be the default
10200 link description.
10202 If the LINK-LOCATION parameter is non-nil, this value will be
10203 used as the link location instead of reading one interactively.
10205 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10206 be used as the default description."
10207 (interactive "P")
10208 (let* ((wcf (current-window-configuration))
10209 (origbuf (current-buffer))
10210 (region (when (org-region-active-p)
10211 (buffer-substring (region-beginning) (region-end))))
10212 (remove (and region (list (region-beginning) (region-end))))
10213 (desc region)
10214 (link link-location)
10215 (abbrevs org-link-abbrev-alist-local)
10216 entry all-prefixes auto-desc)
10217 (cond
10218 (link-location) ; specified by arg, just use it.
10219 ((org-in-regexp org-bracket-link-regexp 1)
10220 ;; We do have a link at point, and we are going to edit it.
10221 (setq remove (list (match-beginning 0) (match-end 0)))
10222 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10223 (setq link (read-string "Link: "
10224 (org-link-unescape
10225 (org-match-string-no-properties 1)))))
10226 ((or (org-in-regexp org-angle-link-re)
10227 (org-in-regexp org-plain-link-re))
10228 ;; Convert to bracket link
10229 (setq remove (list (match-beginning 0) (match-end 0))
10230 link (read-string "Link: "
10231 (org-remove-angle-brackets (match-string 0)))))
10232 ((member complete-file '((4) (16)))
10233 ;; Completing read for file names.
10234 (setq link (org-file-complete-link complete-file)))
10236 ;; Read link, with completion for stored links.
10237 (org-link-fontify-links-to-this-file)
10238 (org-switch-to-buffer-other-window "*Org Links*")
10239 (with-current-buffer "*Org Links*"
10240 (erase-buffer)
10241 (insert "Insert a link.
10242 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10243 (when org-stored-links
10244 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10245 (insert (mapconcat 'org-link-prettify
10246 (reverse org-stored-links) "\n")))
10247 (goto-char (point-min)))
10248 (let ((cw (selected-window)))
10249 (select-window (get-buffer-window "*Org Links*" 'visible))
10250 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10251 (unless (pos-visible-in-window-p (point-max))
10252 (org-fit-window-to-buffer))
10253 (and (window-live-p cw) (select-window cw)))
10254 (setq all-prefixes (append (mapcar 'car abbrevs)
10255 (mapcar 'car org-link-abbrev-alist)
10256 org-link-types))
10257 (unwind-protect
10258 ;; Fake a link history, containing the stored links.
10259 (let ((org--links-history
10260 (append (mapcar #'car org-stored-links)
10261 org-insert-link-history)))
10262 (setq link
10263 (org-completing-read
10264 "Link: "
10265 (append
10266 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10267 (mapcar #'car org-stored-links))
10268 nil nil nil
10269 'org--links-history
10270 (caar org-stored-links)))
10271 (unless (org-string-nw-p link) (user-error "No link selected"))
10272 (dolist (l org-stored-links)
10273 (when (equal link (cadr l))
10274 (setq link (car l))
10275 (setq auto-desc t)))
10276 (when (or (member link all-prefixes)
10277 (and (equal ":" (substring link -1))
10278 (member (substring link 0 -1) all-prefixes)
10279 (setq link (substring link 0 -1))))
10280 (setq link (with-current-buffer origbuf
10281 (org-link-try-special-completion link)))))
10282 (set-window-configuration wcf)
10283 (kill-buffer "*Org Links*"))
10284 (setq entry (assoc link org-stored-links))
10285 (or entry (push link org-insert-link-history))
10286 (setq desc (or desc (nth 1 entry)))))
10288 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10289 (not org-keep-stored-link-after-insertion))
10290 (setq org-stored-links (delq (assoc link org-stored-links)
10291 org-stored-links)))
10293 (when (and (string-match org-plain-link-re link)
10294 (not (string-match org-ts-regexp link)))
10295 ;; URL-like link, normalize the use of angular brackets.
10296 (setq link (org-remove-angle-brackets link)))
10298 ;; Check if we are linking to the current file with a search
10299 ;; option If yes, simplify the link by using only the search
10300 ;; option.
10301 (when (and buffer-file-name
10302 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10303 (let* ((path (match-string 1 link))
10304 (case-fold-search nil)
10305 (search (match-string 2 link)))
10306 (save-match-data
10307 (when (equal (file-truename buffer-file-name) (file-truename path))
10308 ;; We are linking to this same file, with a search option
10309 (setq link search)))))
10311 ;; Check if we can/should use a relative path. If yes, simplify the link
10312 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10313 (let* ((type (match-string 1 link))
10314 (path (match-string 2 link))
10315 (origpath path)
10316 (case-fold-search nil))
10317 (cond
10318 ((or (eq org-link-file-path-type 'absolute)
10319 (equal complete-file '(16)))
10320 (setq path (abbreviate-file-name (expand-file-name path))))
10321 ((eq org-link-file-path-type 'noabbrev)
10322 (setq path (expand-file-name path)))
10323 ((eq org-link-file-path-type 'relative)
10324 (setq path (file-relative-name path)))
10326 (save-match-data
10327 (if (string-match (concat "^" (regexp-quote
10328 (expand-file-name
10329 (file-name-as-directory
10330 default-directory))))
10331 (expand-file-name path))
10332 ;; We are linking a file with relative path name.
10333 (setq path (substring (expand-file-name path)
10334 (match-end 0)))
10335 (setq path (abbreviate-file-name (expand-file-name path)))))))
10336 (setq link (concat type path))
10337 (when (equal desc origpath)
10338 (setq desc path))))
10340 (if org-make-link-description-function
10341 (setq desc
10342 (or (condition-case nil
10343 (funcall org-make-link-description-function link desc)
10344 (error (progn (message "Can't get link description from `%s'"
10345 (symbol-name org-make-link-description-function))
10346 (sit-for 2) nil)))
10347 (read-string "Description: " default-description)))
10348 (if default-description (setq desc default-description)
10349 (setq desc (or (and auto-desc desc)
10350 (read-string "Description: " desc)))))
10352 (unless (string-match "\\S-" desc) (setq desc nil))
10353 (when remove (apply 'delete-region remove))
10354 (insert (org-make-link-string link desc))
10355 ;; Redisplay so as the new link has proper invisible characters.
10356 (sit-for 0)))
10358 (defun org-link-try-special-completion (type)
10359 "If there is completion support for link type TYPE, offer it."
10360 (let ((fun (intern (concat "org-" type "-complete-link"))))
10361 (if (functionp fun)
10362 (funcall fun)
10363 (read-string "Link (no completion support): " (concat type ":")))))
10365 (defun org-file-complete-link (&optional arg)
10366 "Create a file link using completion."
10367 (let ((file (read-file-name "File: "))
10368 (pwd (file-name-as-directory (expand-file-name ".")))
10369 (pwd1 (file-name-as-directory (abbreviate-file-name
10370 (expand-file-name ".")))))
10371 (cond ((equal arg '(16))
10372 (concat "file:"
10373 (abbreviate-file-name (expand-file-name file))))
10374 ((string-match
10375 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10376 (concat "file:" (match-string 1 file)))
10377 ((string-match
10378 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10379 (expand-file-name file))
10380 (concat "file:"
10381 (match-string 1 (expand-file-name file))))
10382 (t (concat "file:" file)))))
10384 (defun org-completing-read (&rest args)
10385 "Completing-read with SPACE being a normal character."
10386 (let ((enable-recursive-minibuffers t)
10387 (minibuffer-local-completion-map
10388 (copy-keymap minibuffer-local-completion-map)))
10389 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10390 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10391 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10392 'org-time-stamp-inactive)
10393 (apply #'completing-read args)))
10395 (define-obsolete-function-alias
10396 'org-completing-read-no-i 'completing-read "Org 9.0")
10397 (define-obsolete-function-alias
10398 'org-icompleting-read 'completing-read "Org 9.0")
10399 (define-obsolete-function-alias
10400 'org-iread-file-name 'read-file-name "Org 9.0")
10402 ;;; Opening/following a link
10404 (defvar org-link-search-failed nil)
10406 (defvar org-open-link-functions nil
10407 "Hook for functions finding a plain text link.
10408 These functions must take a single argument, the link content.
10409 They will be called for links that look like [[link text][description]]
10410 when LINK TEXT does not have a protocol like \"http:\" and does not look
10411 like a filename (e.g. \"./blue.png\").
10413 These functions will be called *before* Org attempts to resolve the
10414 link by doing text searches in the current buffer - so if you want a
10415 link \"[[target]]\" to still find \"<<target>>\", your function should
10416 handle this as a special case.
10418 When the function does handle the link, it must return a non-nil value.
10419 If it decides that it is not responsible for this link, it must return
10420 nil to indicate that that Org-mode can continue with other options
10421 like exact and fuzzy text search.")
10423 (defun org-next-link (&optional search-backward)
10424 "Move forward to the next link.
10425 If the link is in hidden text, expose it."
10426 (interactive "P")
10427 (when (and org-link-search-failed (eq this-command last-command))
10428 (goto-char (point-min))
10429 (message "Link search wrapped back to beginning of buffer"))
10430 (setq org-link-search-failed nil)
10431 (let* ((pos (point))
10432 (ct (org-context))
10433 (a (assoc :link ct))
10434 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10435 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10436 ((looking-at org-any-link-re)
10437 ;; Don't stay stuck at link without an org-link face
10438 (forward-char (if search-backward -1 1))))
10439 (if (funcall srch-fun org-any-link-re nil t)
10440 (progn
10441 (goto-char (match-beginning 0))
10442 (when (outline-invisible-p) (org-show-context)))
10443 (goto-char pos)
10444 (setq org-link-search-failed t)
10445 (message "No further link found"))))
10447 (defun org-previous-link ()
10448 "Move backward to the previous link.
10449 If the link is in hidden text, expose it."
10450 (interactive)
10451 (funcall 'org-next-link t))
10453 (defun org-translate-link (s)
10454 "Translate a link string if a translation function has been defined."
10455 (with-temp-buffer
10456 (insert (org-trim s))
10457 (org-trim (org-element-interpret-data (org-element-context)))))
10459 (defun org-translate-link-from-planner (type path)
10460 "Translate a link from Emacs Planner syntax so that Org can follow it.
10461 This is still an experimental function, your mileage may vary."
10462 (cond
10463 ((member type '("http" "https" "news" "ftp"))
10464 ;; standard Internet links are the same.
10465 nil)
10466 ((and (equal type "irc") (string-match "^//" path))
10467 ;; Planner has two / at the beginning of an irc link, we have 1.
10468 ;; We should have zero, actually....
10469 (setq path (substring path 1)))
10470 ((and (equal type "lisp") (string-match "^/" path))
10471 ;; Planner has a slash, we do not.
10472 (setq type "elisp" path (substring path 1)))
10473 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10474 ;; A typical message link. Planner has the id after the final slash,
10475 ;; we separate it with a hash mark
10476 (setq path (concat (match-string 1 path) "#"
10477 (org-remove-angle-brackets (match-string 2 path))))))
10478 (cons type path))
10480 (defun org-find-file-at-mouse (ev)
10481 "Open file link or URL at mouse."
10482 (interactive "e")
10483 (mouse-set-point ev)
10484 (org-open-at-point 'in-emacs))
10486 (defun org-open-at-mouse (ev)
10487 "Open file link or URL at mouse.
10488 See the docstring of `org-open-file' for details."
10489 (interactive "e")
10490 (mouse-set-point ev)
10491 (when (eq major-mode 'org-agenda-mode)
10492 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10493 (org-open-at-point))
10495 (defvar org-window-config-before-follow-link nil
10496 "The window configuration before following a link.
10497 This is saved in case the need arises to restore it.")
10499 ;;;###autoload
10500 (defun org-open-at-point-global ()
10501 "Follow a link like Org-mode does.
10502 This command can be called in any mode to follow a link that has
10503 Org-mode syntax."
10504 (interactive)
10505 (org-run-like-in-org-mode 'org-open-at-point))
10507 ;;;###autoload
10508 (defun org-open-link-from-string (s &optional arg reference-buffer)
10509 "Open a link in the string S, as if it was in Org-mode."
10510 (interactive "sLink: \nP")
10511 (let ((reference-buffer (or reference-buffer (current-buffer))))
10512 (with-temp-buffer
10513 (let ((org-inhibit-startup (not reference-buffer)))
10514 (org-mode)
10515 (insert s)
10516 (goto-char (point-min))
10517 (when reference-buffer
10518 (setq org-link-abbrev-alist-local
10519 (with-current-buffer reference-buffer
10520 org-link-abbrev-alist-local)))
10521 (org-open-at-point arg reference-buffer)))))
10523 (defvar org-open-at-point-functions nil
10524 "Hook that is run when following a link at point.
10526 Functions in this hook must return t if they identify and follow
10527 a link at point. If they don't find anything interesting at point,
10528 they must return nil.")
10530 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10531 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10532 (defun org-open-at-point (&optional arg reference-buffer)
10533 "Open link, timestamp, footnote or tags at point.
10535 When point is on a link, follow it. Normally, files will be
10536 opened by an appropriate application. If the optional prefix
10537 argument ARG is non-nil, Emacs will visit the file. With
10538 a double prefix argument, try to open outside of Emacs, in the
10539 application the system uses for this file type.
10541 When point is on a timestamp, open the agenda at the day
10542 specified.
10544 When point is a footnote definition, move to the first reference
10545 found. If it is on a reference, move to the associated
10546 definition.
10548 When point is on a headline, display a list of every link in the
10549 entry, so it is possible to pick one, or all, of them. If point
10550 is on a tag, call `org-tags-view' instead.
10552 When optional argument REFERENCE-BUFFER is non-nil, it should
10553 specify a buffer from where the link search should happen. This
10554 is used internally by `org-open-link-from-string'.
10556 On top of syntactically correct links, this function will open
10557 the link at point in comments or comment blocks and the first
10558 link in a property drawer line."
10559 (interactive "P")
10560 ;; On a code block, open block's results.
10561 (unless (call-interactively 'org-babel-open-src-block-result)
10562 (org-load-modules-maybe)
10563 (setq org-window-config-before-follow-link (current-window-configuration))
10564 (org-remove-occur-highlights nil nil t)
10565 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10566 (let* ((context
10567 ;; Only consider supported types, even if they are not
10568 ;; the closest one.
10569 (org-element-lineage
10570 (org-element-context)
10571 '(clock comment comment-block footnote-definition
10572 footnote-reference headline inlinetask keyword link
10573 node-property timestamp)
10575 (type (org-element-type context))
10576 (value (org-element-property :value context)))
10577 (cond
10578 ((not context) (user-error "No link found"))
10579 ;; Exception: open timestamps and links in properties
10580 ;; drawers, keywords and comments.
10581 ((memq type '(comment comment-block keyword node-property))
10582 (cond ((org-in-regexp org-any-link-re)
10583 (org-open-link-from-string (match-string-no-properties 0)))
10584 ((or (org-in-regexp org-ts-regexp-both nil t)
10585 (org-in-regexp org-tsr-regexp-both nil t))
10586 (org-follow-timestamp-link))
10587 (t (user-error "No link found"))))
10588 ;; On a headline or an inlinetask, but not on a timestamp,
10589 ;; a link, a footnote reference or on tags.
10590 ((and (memq type '(headline inlinetask))
10591 ;; Not on tags.
10592 (progn (save-excursion (beginning-of-line)
10593 (looking-at org-complex-heading-regexp))
10594 (or (not (match-beginning 5))
10595 (< (point) (match-beginning 5)))))
10596 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10597 (links (car data))
10598 (links-end (cdr data)))
10599 (if links
10600 (dolist (link (if (stringp links) (list links) links))
10601 (search-forward link nil links-end)
10602 (goto-char (match-beginning 0))
10603 (org-open-at-point))
10604 (require 'org-attach)
10605 (org-attach-reveal 'if-exists))))
10606 ;; On a clock line, make sure point is on the timestamp
10607 ;; before opening it.
10608 ((and (eq type 'clock)
10609 value
10610 (>= (point) (org-element-property :begin value))
10611 (<= (point) (org-element-property :end value)))
10612 (org-follow-timestamp-link))
10613 ;; Do nothing on white spaces after an object.
10614 ((>= (point)
10615 (save-excursion
10616 (goto-char (org-element-property :end context))
10617 (skip-chars-backward " \t")
10618 (point)))
10619 (user-error "No link found"))
10620 ((eq type 'timestamp) (org-follow-timestamp-link))
10621 ;; On tags within a headline or an inlinetask.
10622 ((and (memq type '(headline inlinetask))
10623 (progn (save-excursion (beginning-of-line)
10624 (looking-at org-complex-heading-regexp))
10625 (and (match-beginning 5)
10626 (>= (point) (match-beginning 5)))))
10627 (org-tags-view arg (substring (match-string 5) 0 -1)))
10628 ((eq type 'link)
10629 ;; When link is located within the description of another
10630 ;; link (e.g., an inline image), always open the parent
10631 ;; link.
10632 (let*((link (let ((up (org-element-property :parent context)))
10633 (if (eq (org-element-type up) 'link) up context)))
10634 (type (org-element-property :type link))
10635 (path (org-link-unescape (org-element-property :path link))))
10636 ;; Switch back to REFERENCE-BUFFER needed when called in
10637 ;; a temporary buffer through `org-open-link-from-string'.
10638 (with-current-buffer (or reference-buffer (current-buffer))
10639 (cond
10640 ((equal type "file")
10641 (if (string-match "[*?{]" (file-name-nondirectory path))
10642 (dired path)
10643 ;; Look into `org-link-protocols' in order to find
10644 ;; a DEDICATED-FUNCTION to open file. The function
10645 ;; will be applied on raw link instead of parsed
10646 ;; link due to the limitation in `org-add-link-type'
10647 ;; ("open" function called with a single argument).
10648 ;; If no such function is found, fallback to
10649 ;; `org-open-file'.
10651 ;; Note : "file+emacs" and "file+sys" types are
10652 ;; hard-coded in order to escape the previous
10653 ;; limitation.
10654 (let* ((option (org-element-property :search-option link))
10655 (app (org-element-property :application link))
10656 (dedicated-function
10657 (nth 1 (assoc app org-link-protocols))))
10658 (if dedicated-function
10659 (funcall dedicated-function
10660 (concat path
10661 (and option (concat "::" option))))
10662 (apply #'org-open-file
10663 path
10664 (cond (arg)
10665 ((equal app "emacs") 'emacs)
10666 ((equal app "sys") 'system))
10667 (cond ((not option) nil)
10668 ((org-string-match-p "\\`[0-9]+\\'" option)
10669 (list (string-to-number option)))
10670 (t (list nil
10671 (org-link-unescape option)))))))))
10672 ((assoc type org-link-protocols)
10673 (funcall (nth 1 (assoc type org-link-protocols)) path))
10674 ((equal type "help")
10675 (let ((f-or-v (intern path)))
10676 (cond ((fboundp f-or-v) (describe-function f-or-v))
10677 ((boundp f-or-v) (describe-variable f-or-v))
10678 (t (error "Not a known function or variable")))))
10679 ((member type '("http" "https" "ftp" "mailto" "news"))
10680 (browse-url (org-link-escape-browser (concat type ":" path))))
10681 ((equal type "doi")
10682 (browse-url
10683 (org-link-escape-browser (concat org-doi-server-url path))))
10684 ((equal type "message") (browse-url (concat type ":" path)))
10685 ((equal type "shell")
10686 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10687 (cmd path))
10688 (if (or (and (org-string-nw-p
10689 org-confirm-shell-link-not-regexp)
10690 (string-match
10691 org-confirm-shell-link-not-regexp cmd))
10692 (not org-confirm-shell-link-function)
10693 (funcall org-confirm-shell-link-function
10694 (format "Execute \"%s\" in shell? "
10695 (org-add-props cmd nil
10696 'face 'org-warning))))
10697 (progn
10698 (message "Executing %s" cmd)
10699 (shell-command cmd buf)
10700 (when (featurep 'midnight)
10701 (setq clean-buffer-list-kill-buffer-names
10702 (cons (buffer-name buf)
10703 clean-buffer-list-kill-buffer-names))))
10704 (user-error "Abort"))))
10705 ((equal type "elisp")
10706 (let ((cmd path))
10707 (if (or (and (org-string-nw-p
10708 org-confirm-elisp-link-not-regexp)
10709 (org-string-match-p
10710 org-confirm-elisp-link-not-regexp cmd))
10711 (not org-confirm-elisp-link-function)
10712 (funcall org-confirm-elisp-link-function
10713 (format "Execute \"%s\" as elisp? "
10714 (org-add-props cmd nil
10715 'face 'org-warning))))
10716 (message "%s => %s" cmd
10717 (if (eq (string-to-char cmd) ?\()
10718 (eval (read cmd))
10719 (call-interactively (read cmd))))
10720 (user-error "Abort"))))
10721 ((equal type "id")
10722 (require 'org-id)
10723 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10724 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10725 (unless (run-hook-with-args-until-success
10726 'org-open-link-functions path)
10727 (if (not arg) (org-mark-ring-push)
10728 (switch-to-buffer-other-window
10729 (org-get-buffer-for-internal-link (current-buffer))))
10730 (let ((destination
10731 (org-with-wide-buffer
10732 (if (equal type "radio")
10733 (org-search-radio-target
10734 (org-element-property :path link))
10735 (org-link-search
10736 (if (member type '("custom-id" "coderef"))
10737 (org-element-property :raw-link link)
10738 path)
10739 ;; Prevent fuzzy links from matching
10740 ;; themselves.
10741 (and (equal type "fuzzy")
10742 (+ 2 (org-element-property :begin link)))))
10743 (point))))
10744 (unless (and (<= (point-min) destination)
10745 (>= (point-max) destination))
10746 (widen))
10747 (goto-char destination))))
10748 (t (browse-url-at-point))))))
10749 ;; On a footnote reference or at a footnote definition's label.
10750 ((or (eq type 'footnote-reference)
10751 (and (eq type 'footnote-definition)
10752 (save-excursion
10753 ;; Do not validate action when point is on the
10754 ;; spaces right after the footnote label, in
10755 ;; order to be on par with behaviour on links.
10756 (skip-chars-forward " \t")
10757 (let ((begin
10758 (org-element-property :contents-begin context)))
10759 (if begin (< (point) begin)
10760 (= (org-element-property :post-affiliated context)
10761 (line-beginning-position)))))))
10762 (org-footnote-action))
10763 (t (user-error "No link found")))))
10764 (run-hook-with-args 'org-follow-link-hook)))
10766 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10767 "Offer links in the current entry and return the selected link.
10768 If there is only one link, return it.
10769 If NTH is an integer, return the NTH link found.
10770 If ZERO is a string, check also this string for a link, and if
10771 there is one, return it."
10772 (with-current-buffer buffer
10773 (save-excursion
10774 (save-restriction
10775 (widen)
10776 (goto-char marker)
10777 (let ((cnt ?0)
10778 have-zero end links link c)
10779 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10780 (push (match-string 0 zero) links)
10781 (setq cnt (1- cnt) have-zero t))
10782 (save-excursion
10783 (org-back-to-heading t)
10784 (setq end (save-excursion (outline-next-heading) (point)))
10785 (while (re-search-forward org-any-link-re end t)
10786 (push (match-string 0) links))
10787 (setq links (org-uniquify (reverse links))))
10788 (cond
10789 ((null links)
10790 (message "No links"))
10791 ((equal (length links) 1)
10792 (setq link (car links)))
10793 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10794 (setq link (nth (if have-zero nth (1- nth)) links)))
10795 (t ; we have to select a link
10796 (save-excursion
10797 (save-window-excursion
10798 (delete-other-windows)
10799 (with-output-to-temp-buffer "*Select Link*"
10800 (dolist (l links)
10801 (cond
10802 ((not (string-match org-bracket-link-regexp l))
10803 (princ (format "[%c] %s\n" (cl-incf cnt)
10804 (org-remove-angle-brackets l))))
10805 ((match-end 3)
10806 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10807 (match-string 3 l) (match-string 1 l))))
10808 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10809 (match-string 1 l)))))))
10810 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10811 (message "Select link to open, RET to open all:")
10812 (setq c (read-char-exclusive))
10813 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10814 (when (equal c ?q) (user-error "Abort"))
10815 (if (equal c ?\C-m)
10816 (setq link links)
10817 (setq nth (- c ?0))
10818 (when have-zero (setq nth (1+ nth)))
10819 (unless (and (integerp nth) (>= (length links) nth))
10820 (user-error "Invalid link selection"))
10821 (setq link (nth (1- nth) links)))))
10822 (cons link end))))))
10824 ;; TODO: These functions are deprecated since `org-open-at-point'
10825 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10826 (defun org-open-file-with-system (path)
10827 "Open file at PATH using the system way of opening it."
10828 (org-open-file path 'system))
10829 (defun org-open-file-with-emacs (path)
10830 "Open file at PATH in Emacs."
10831 (org-open-file path 'emacs))
10834 ;;; File search
10836 (defvar org-create-file-search-functions nil
10837 "List of functions to construct the right search string for a file link.
10838 These functions are called in turn with point at the location to
10839 which the link should point.
10841 A function in the hook should first test if it would like to
10842 handle this file type, for example by checking the `major-mode'
10843 or the file extension. If it decides not to handle this file, it
10844 should just return nil to give other functions a chance. If it
10845 does handle the file, it must return the search string to be used
10846 when following the link. The search string will be part of the
10847 file link, given after a double colon, and `org-open-at-point'
10848 will automatically search for it. If special measures must be
10849 taken to make the search successful, another function should be
10850 added to the companion hook `org-execute-file-search-functions',
10851 which see.
10853 A function in this hook may also use `setq' to set the variable
10854 `description' to provide a suggestion for the descriptive text to
10855 be used for this link when it gets inserted into an Org-mode
10856 buffer with \\[org-insert-link].")
10858 (defvar org-execute-file-search-functions nil
10859 "List of functions to execute a file search triggered by a link.
10861 Functions added to this hook must accept a single argument, the
10862 search string that was part of the file link, the part after the
10863 double colon. The function must first check if it would like to
10864 handle this search, for example by checking the `major-mode' or
10865 the file extension. If it decides not to handle this search, it
10866 should just return nil to give other functions a chance. If it
10867 does handle the search, it must return a non-nil value to keep
10868 other functions from trying.
10870 Each function can access the current prefix argument through the
10871 variable `current-prefix-arg'. Note that a single prefix is used
10872 to force opening a link in Emacs, so it may be good to only use a
10873 numeric or double prefix to guide the search function.
10875 In case this is needed, a function in this hook can also restore
10876 the window configuration before `org-open-at-point' was called using:
10878 \(set-window-configuration org-window-config-before-follow-link)")
10880 (defun org-search-radio-target (target)
10881 "Search a radio target matching TARGET in current buffer.
10882 White spaces are not significant."
10883 (let ((re (format "<<<%s>>>"
10884 (mapconcat #'regexp-quote
10885 (org-split-string target "[ \t\n]+")
10886 "[ \t]+\\(?:\n[ \t]*\\)?")))
10887 (origin (point)))
10888 (goto-char (point-min))
10889 (catch :radio-match
10890 (while (re-search-forward re nil t)
10891 (backward-char)
10892 (let ((object (org-element-context)))
10893 (when (eq (org-element-type object) 'radio-target)
10894 (goto-char (org-element-property :begin object))
10895 (org-show-context 'link-search)
10896 (throw :radio-match nil))))
10897 (goto-char origin)
10898 (user-error "No match for radio target: %s" target))))
10900 (defun org-link-search (s &optional avoid-pos stealth)
10901 "Search for a search string S.
10903 If S starts with \"#\", it triggers a custom ID search.
10905 If S is enclosed within parenthesis, it initiates a coderef
10906 search.
10908 If S is surrounded by forward slashes, it is interpreted as
10909 a regular expression. In Org mode files, this will create an
10910 `org-occur' sparse tree. In ordinary files, `occur' will be used
10911 to list matches. If the current buffer is in `dired-mode', grep
10912 will be used to search in all files.
10914 When AVOID-POS is given, ignore matches near that position.
10916 When optional argument STEALTH is non-nil, do not modify
10917 visibility around point, thus ignoring `org-show-context-detail'
10918 variable.
10920 Search is case-insensitive and ignores white spaces. Return type
10921 of matched result, with is either `dedicated' or `fuzzy'."
10922 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10923 (let* ((case-fold-search t)
10924 (origin (point))
10925 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10926 (words (org-split-string s "[ \t\n]+"))
10927 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10928 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10929 type)
10930 (cond
10931 ;; Check if there are any special search functions.
10932 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10933 ((eq (string-to-char s) ?#)
10934 ;; Look for a custom ID S if S starts with "#".
10935 (let* ((id (substring normalized 1))
10936 (match (org-find-property "CUSTOM_ID" id)))
10937 (if match (progn (goto-char match) (setf type 'dedicated))
10938 (error "No match for custom ID: %s" id))))
10939 ((string-match "\\`(\\(.*\\))\\'" normalized)
10940 ;; Look for coderef targets if S is enclosed within parenthesis.
10941 (let ((coderef (match-string-no-properties 1 normalized))
10942 (re (substring s-single-re 1 -1)))
10943 (goto-char (point-min))
10944 (catch :coderef-match
10945 (while (re-search-forward re nil t)
10946 (let ((element (org-element-at-point)))
10947 (when (and (memq (org-element-type element)
10948 '(example-block src-block))
10949 ;; Build proper regexp according to current
10950 ;; block's label format.
10951 (let ((label-fmt
10952 (regexp-quote
10953 (or (org-element-property :label-fmt element)
10954 org-coderef-label-format))))
10955 (save-excursion
10956 (beginning-of-line)
10957 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10958 (format label-fmt coderef))))))
10959 (setq type 'dedicated)
10960 (goto-char (match-beginning 1))
10961 (throw :coderef-match nil))))
10962 (goto-char origin)
10963 (error "No match for coderef: %s" coderef))))
10964 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10965 ;; Look for a regular expression.
10966 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10967 (match-string 1 s)))
10968 ;; Fuzzy links.
10970 (let ((starred (eq (string-to-char normalized) ?*)))
10971 (cond
10972 ;; Look for targets, only if not in a headline search.
10973 ((and (not starred)
10974 (let ((target (format "<<%s>>" s-multi-re)))
10975 (catch :target-match
10976 (goto-char (point-min))
10977 (while (re-search-forward target nil t)
10978 (backward-char)
10979 (let ((context (org-element-context)))
10980 (when (eq (org-element-type context) 'target)
10981 (setq type 'dedicated)
10982 (goto-char (org-element-property :begin context))
10983 (throw :target-match t))))
10984 nil))))
10985 ;; Look for elements named after S, only if not in a headline
10986 ;; search.
10987 ((and (not starred)
10988 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10989 (catch :name-match
10990 (goto-char (point-min))
10991 (while (re-search-forward name nil t)
10992 (let ((element (org-element-at-point)))
10993 (when (equal (org-split-string
10994 (org-element-property :name element)
10995 "[ \t]+")
10996 words)
10997 (setq type 'dedicated)
10998 (beginning-of-line)
10999 (throw :name-match t))))
11000 nil))))
11001 ;; Regular text search. Prefer headlines in Org mode
11002 ;; buffers.
11003 ((and (derived-mode-p 'org-mode)
11004 (let* ((wspace "[ \t]")
11005 (wspaceopt (concat wspace "*"))
11006 (cookie (concat "\\(?:"
11007 wspaceopt
11008 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11009 wspaceopt
11010 "\\)"))
11011 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11012 (re (concat
11013 org-outline-regexp-bol
11014 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11015 "\\(?:\\[#.\\][ \t]+\\)?"
11016 "\\(?:" org-comment-string "[ \t]+\\)?"
11017 sep "?"
11018 (let ((title (mapconcat #'regexp-quote
11019 words
11020 sep)))
11021 (if starred (substring title 1) title))
11022 sep "?"
11023 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11024 "[ \t]*$")))
11025 (goto-char (point-min))
11026 (re-search-forward re nil t)))
11027 (goto-char (match-beginning 0))
11028 (setq type 'dedicated))
11029 ;; Offer to create non-existent headline depending on
11030 ;; `org-link-search-must-match-exact-headline'.
11031 ((and (derived-mode-p 'org-mode)
11032 (not org-link-search-inhibit-query)
11033 (eq org-link-search-must-match-exact-headline 'query-to-create)
11034 (yes-or-no-p "No match - create this as a new heading? "))
11035 (goto-char (point-max))
11036 (unless (bolp) (newline))
11037 (org-insert-heading nil t t)
11038 (insert s "\n")
11039 (beginning-of-line 0))
11040 ;; Only headlines are looked after. No need to process
11041 ;; further: throw an error.
11042 ((and (derived-mode-p 'org-mode)
11043 (or starred org-link-search-must-match-exact-headline))
11044 (goto-char origin)
11045 (error "No match for fuzzy expression: %s" normalized))
11046 ;; Regular text search.
11047 ((catch :fuzzy-match
11048 (goto-char (point-min))
11049 (while (re-search-forward s-multi-re nil t)
11050 ;; Skip match if it contains AVOID-POS or it is included
11051 ;; in a link with a description but outside the
11052 ;; description.
11053 (unless (or (and avoid-pos
11054 (<= (match-beginning 0) avoid-pos)
11055 (> (match-end 0) avoid-pos))
11056 (and (save-match-data
11057 (org-in-regexp org-bracket-link-regexp))
11058 (match-beginning 3)
11059 (or (> (match-beginning 3) (point))
11060 (<= (match-end 3) (point)))
11061 (org-element-lineage
11062 (save-match-data (org-element-context))
11063 '(link) t)))
11064 (goto-char (match-beginning 0))
11065 (setq type 'fuzzy)
11066 (throw :fuzzy-match t)))
11067 nil))
11068 ;; All failed. Throw an error.
11069 (t (goto-char origin)
11070 (error "No match for fuzzy expression: %s" normalized))))))
11071 ;; Disclose surroundings of match, if appropriate.
11072 (when (and (derived-mode-p 'org-mode) (not stealth))
11073 (org-show-context 'link-search))
11074 type))
11076 (defun org-get-buffer-for-internal-link (buffer)
11077 "Return a buffer to be used for displaying the link target of internal links."
11078 (cond
11079 ((not org-display-internal-link-with-indirect-buffer)
11080 buffer)
11081 ((string-match "(Clone)$" (buffer-name buffer))
11082 (message "Buffer is already a clone, not making another one")
11083 ;; we also do not modify visibility in this case
11084 buffer)
11085 (t ; make a new indirect buffer for displaying the link
11086 (let* ((bn (buffer-name buffer))
11087 (ibn (concat bn "(Clone)"))
11088 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11089 (with-current-buffer ib (org-overview))
11090 ib))))
11092 (defun org-do-occur (regexp &optional cleanup)
11093 "Call the Emacs command `occur'.
11094 If CLEANUP is non-nil, remove the printout of the regular expression
11095 in the *Occur* buffer. This is useful if the regex is long and not useful
11096 to read."
11097 (occur regexp)
11098 (when cleanup
11099 (let ((cwin (selected-window)) win beg end)
11100 (when (setq win (get-buffer-window "*Occur*"))
11101 (select-window win))
11102 (goto-char (point-min))
11103 (when (re-search-forward "match[a-z]+" nil t)
11104 (setq beg (match-end 0))
11105 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11106 (setq end (1- (match-beginning 0)))))
11107 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11108 (goto-char (point-min))
11109 (select-window cwin))))
11111 ;;; The mark ring for links jumps
11113 (defvar org-mark-ring nil
11114 "Mark ring for positions before jumps in Org-mode.")
11115 (defvar org-mark-ring-last-goto nil
11116 "Last position in the mark ring used to go back.")
11117 ;; Fill and close the ring
11118 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11119 (dotimes (_ org-mark-ring-length)
11120 (push (make-marker) org-mark-ring))
11121 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11122 org-mark-ring)
11124 (defun org-mark-ring-push (&optional pos buffer)
11125 "Put the current position or POS into the mark ring and rotate it."
11126 (interactive)
11127 (setq pos (or pos (point)))
11128 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11129 (move-marker (car org-mark-ring)
11130 (or pos (point))
11131 (or buffer (current-buffer)))
11132 (message "%s"
11133 (substitute-command-keys
11134 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11136 (defun org-mark-ring-goto (&optional n)
11137 "Jump to the previous position in the mark ring.
11138 With prefix arg N, jump back that many stored positions. When
11139 called several times in succession, walk through the entire ring.
11140 Org-mode commands jumping to a different position in the current file,
11141 or to another Org-mode file, automatically push the old position
11142 onto the ring."
11143 (interactive "p")
11144 (let (p m)
11145 (if (eq last-command this-command)
11146 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11147 (setq p org-mark-ring))
11148 (setq org-mark-ring-last-goto p)
11149 (setq m (car p))
11150 (org-pop-to-buffer-same-window (marker-buffer m))
11151 (goto-char m)
11152 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11154 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11155 ;;; Emacs 24.4+
11156 (defun org-remove-angle-brackets (s)
11157 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11158 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11160 (defun org-add-angle-brackets (s)
11161 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11162 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11164 (defun org-remove-double-quotes (s)
11165 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11166 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11169 ;;; Following specific links
11171 (defvar org-agenda-buffer-tmp-name)
11172 (defvar org-agenda-start-on-weekday)
11173 (defun org-follow-timestamp-link ()
11174 "Open an agenda view for the time-stamp date/range at point."
11175 (cond
11176 ((org-at-date-range-p t)
11177 (let ((org-agenda-start-on-weekday)
11178 (t1 (match-string 1))
11179 (t2 (match-string 2)) tt1 tt2)
11180 (setq tt1 (time-to-days (org-time-string-to-time t1))
11181 tt2 (time-to-days (org-time-string-to-time t2)))
11182 (let ((org-agenda-buffer-tmp-name
11183 (format "*Org Agenda(a:%s)"
11184 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11185 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11186 ((org-at-timestamp-p t)
11187 (let ((org-agenda-buffer-tmp-name
11188 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11189 (org-agenda-list nil (time-to-days (org-time-string-to-time
11190 (substring (match-string 1) 0 10)))
11191 1)))
11192 (t (error "This should not happen"))))
11195 ;;; Following file links
11196 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11197 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11198 (declare-function mailcap-mime-info
11199 "mailcap" (string &optional request no-decode))
11200 (defvar org-wait nil)
11201 (defun org-open-file (path &optional in-emacs line search)
11202 "Open the file at PATH.
11203 First, this expands any special file name abbreviations. Then the
11204 configuration variable `org-file-apps' is checked if it contains an
11205 entry for this file type, and if yes, the corresponding command is launched.
11207 If no application is found, Emacs simply visits the file.
11209 With optional prefix argument IN-EMACS, Emacs will visit the file.
11210 With a double \\[universal-argument] \\[universal-argument] \
11211 prefix arg, Org tries to avoid opening in Emacs
11212 and to use an external application to visit the file.
11214 Optional LINE specifies a line to go to, optional SEARCH a string
11215 to search for. If LINE or SEARCH is given, the file will be
11216 opened in Emacs, unless an entry from org-file-apps that makes
11217 use of groups in a regexp matches.
11219 If you want to change the way frames are used when following a
11220 link, please customize `org-link-frame-setup'.
11222 If the file does not exist, an error is thrown."
11223 (let* ((file (if (equal path "")
11224 buffer-file-name
11225 (substitute-in-file-name (expand-file-name path))))
11226 (file-apps (append org-file-apps (org-default-apps)))
11227 (apps (cl-remove-if
11228 'org-file-apps-entry-match-against-dlink-p file-apps))
11229 (apps-dlink (cl-remove-if-not
11230 'org-file-apps-entry-match-against-dlink-p file-apps))
11231 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11232 (dirp (unless remp (file-directory-p file)))
11233 (file (if (and dirp org-open-directory-means-index-dot-org)
11234 (concat (file-name-as-directory file) "index.org")
11235 file))
11236 (a-m-a-p (assq 'auto-mode apps))
11237 (dfile (downcase file))
11238 ;; Reconstruct the original link from the PATH, LINE and
11239 ;; SEARCH args.
11240 (link (cond (line (concat file "::" (number-to-string line)))
11241 (search (concat file "::" search))
11242 (t file)))
11243 (dlink (downcase link))
11244 (old-buffer (current-buffer))
11245 (old-pos (point))
11246 (old-mode major-mode)
11247 (ext
11248 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11249 (match-string 1 dfile)))
11250 cmd link-match-data)
11251 (cond
11252 ((member in-emacs '((16) system))
11253 (setq cmd (cdr (assq 'system apps))))
11254 (in-emacs (setq cmd 'emacs))
11256 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11257 (and dirp (cdr (assq 'directory apps)))
11258 ;; First, try matching against apps-dlink if we
11259 ;; get a match here, store the match data for
11260 ;; later.
11261 (let ((match (assoc-default dlink apps-dlink
11262 'string-match)))
11263 (if match
11264 (progn (setq link-match-data (match-data))
11265 match)
11266 (progn (setq in-emacs (or in-emacs line search))
11267 nil))) ; if we have no match in apps-dlink,
11268 ; always open the file in emacs if line or search
11269 ; is given (for backwards compatibility)
11270 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11271 'string-match)
11272 (cdr (assoc ext apps))
11273 (cdr (assq t apps))))))
11274 (when (eq cmd 'system)
11275 (setq cmd (cdr (assoc 'system apps))))
11276 (when (eq cmd 'default)
11277 (setq cmd (cdr (assoc t apps))))
11278 (when (eq cmd 'mailcap)
11279 (require 'mailcap)
11280 (mailcap-parse-mailcaps)
11281 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11282 (command (mailcap-mime-info mime-type)))
11283 (if (stringp command)
11284 (setq cmd command)
11285 (setq cmd 'emacs))))
11286 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11287 (not (file-exists-p file))
11288 (not org-open-non-existing-files))
11289 (user-error "No such file: %s" file))
11290 (cond
11291 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11292 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11293 (while (string-match "['\"]%s['\"]" cmd)
11294 (setq cmd (replace-match "%s" t t cmd)))
11295 (while (string-match "%s" cmd)
11296 (setq cmd (replace-match
11297 (save-match-data
11298 (shell-quote-argument
11299 (convert-standard-filename file)))
11300 t t cmd)))
11302 ;; Replace "%1", "%2" etc. in command with group matches from regex
11303 (save-match-data
11304 (let ((match-index 1)
11305 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11306 (set-match-data link-match-data)
11307 (while (<= match-index number-of-groups)
11308 (let ((regex (concat "%" (number-to-string match-index)))
11309 (replace-with (match-string match-index dlink)))
11310 (while (string-match regex cmd)
11311 (setq cmd (replace-match replace-with t t cmd))))
11312 (setq match-index (+ match-index 1)))))
11314 (save-window-excursion
11315 (message "Running %s...done" cmd)
11316 (start-process-shell-command cmd nil cmd)
11317 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11318 ((or (stringp cmd)
11319 (eq cmd 'emacs))
11320 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11321 (widen)
11322 (cond (line (org-goto-line line)
11323 (when (derived-mode-p 'org-mode) (org-reveal)))
11324 (search (org-link-search search))))
11325 ((functionp cmd)
11326 (save-match-data
11327 (set-match-data link-match-data)
11328 (funcall cmd file link)))
11329 ((consp cmd)
11330 ;; FIXME: Remove this check when most default installations of
11331 ;; Emacs have at least Org 9.0.
11332 ;; Heads-up instead of silently fall back to
11333 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11334 ;; with sexp instead of a function for `cmd'.
11335 (user-error
11336 "Please see Org News for version 9.0 about `org-file-apps'"))
11337 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11338 (and (derived-mode-p 'org-mode)
11339 (eq old-mode 'org-mode)
11340 (or (not (eq old-buffer (current-buffer)))
11341 (not (eq old-pos (point))))
11342 (org-mark-ring-push old-pos old-buffer))))
11344 (defun org-file-apps-entry-match-against-dlink-p (entry)
11345 "This function returns non-nil if `entry' uses a regular
11346 expression which should be matched against the whole link by
11347 org-open-file.
11349 It assumes that is the case when the entry uses a regular
11350 expression which has at least one grouping construct and the
11351 action is either a lisp form or a command string containing
11352 `%1', i.e. using at least one subexpression match as a
11353 parameter."
11354 (let ((selector (car entry))
11355 (action (cdr entry)))
11356 (if (stringp selector)
11357 (and (> (regexp-opt-depth selector) 0)
11358 (or (and (stringp action)
11359 (string-match "%[0-9]" action))
11360 (consp action)))
11361 nil)))
11363 (defun org-default-apps ()
11364 "Return the default applications for this operating system."
11365 (cond
11366 ((eq system-type 'darwin)
11367 org-file-apps-defaults-macosx)
11368 ((eq system-type 'windows-nt)
11369 org-file-apps-defaults-windowsnt)
11370 (t org-file-apps-defaults-gnu)))
11372 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11373 "Convert extensions to regular expressions in the cars of LIST.
11374 Also, weed out any non-string entries, because the return value is used
11375 only for regexp matching.
11376 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11377 point to the symbol `emacs', indicating that the file should
11378 be opened in Emacs."
11379 (append
11380 (delq nil
11381 (mapcar (lambda (x)
11382 (unless (not (stringp (car x)))
11383 (if (string-match "\\W" (car x))
11385 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11386 list))
11387 (when add-auto-mode
11388 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11390 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11391 (defun org-file-remote-p (file)
11392 "Test whether FILE specifies a location on a remote system.
11393 Return non-nil if the location is indeed remote.
11395 For example, the filename \"/user@host:/foo\" specifies a location
11396 on the system \"/user@host:\"."
11397 (cond ((fboundp 'file-remote-p)
11398 (file-remote-p file))
11399 ((fboundp 'tramp-handle-file-remote-p)
11400 (tramp-handle-file-remote-p file))
11401 ((and (boundp 'ange-ftp-name-format)
11402 (string-match (car ange-ftp-name-format) file))
11403 t)))
11406 ;;;; Refiling
11408 (defun org-get-org-file ()
11409 "Read a filename, with default directory `org-directory'."
11410 (let ((default (or org-default-notes-file remember-data-file)))
11411 (read-file-name (format "File name [%s]: " default)
11412 (file-name-as-directory org-directory)
11413 default)))
11415 (defun org-notes-order-reversed-p ()
11416 "Check if the current file should receive notes in reversed order."
11417 (cond
11418 ((not org-reverse-note-order) nil)
11419 ((eq t org-reverse-note-order) t)
11420 ((not (listp org-reverse-note-order)) nil)
11421 (t (catch 'exit
11422 (dolist (entry org-reverse-note-order)
11423 (when (string-match (car entry) buffer-file-name)
11424 (throw 'exit (cdr entry))))))))
11426 (defvar org-refile-target-table nil
11427 "The list of refile targets, created by `org-refile'.")
11429 (defvar org-agenda-new-buffers nil
11430 "Buffers created to visit agenda files.")
11432 (defvar org-refile-cache nil
11433 "Cache for refile targets.")
11435 (defvar org-refile-markers nil
11436 "All the markers used for caching refile locations.")
11438 (defun org-refile-marker (pos)
11439 "Get a new refile marker, but only if caching is in use."
11440 (if (not org-refile-use-cache)
11442 (let ((m (make-marker)))
11443 (move-marker m pos)
11444 (push m org-refile-markers)
11445 m)))
11447 (defun org-refile-cache-clear ()
11448 "Clear the refile cache and disable all the markers."
11449 (dolist (m org-refile-markers) (move-marker m nil))
11450 (setq org-refile-markers nil)
11451 (setq org-refile-cache nil)
11452 (message "Refile cache has been cleared"))
11454 (defun org-refile-cache-check-set (set)
11455 "Check if all the markers in the cache still have live buffers."
11456 (let (marker)
11457 (catch 'exit
11458 (while (and set (setq marker (nth 3 (pop set))))
11459 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11460 (when (and marker (null (marker-buffer marker)))
11461 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11462 (sit-for 3)
11463 (throw 'exit nil)))
11464 t)))
11466 (defun org-refile-cache-put (set &rest identifiers)
11467 "Push the refile targets SET into the cache, under IDENTIFIERS."
11468 (let* ((key (sha1 (prin1-to-string identifiers)))
11469 (entry (assoc key org-refile-cache)))
11470 (if entry
11471 (setcdr entry set)
11472 (push (cons key set) org-refile-cache))))
11474 (defun org-refile-cache-get (&rest identifiers)
11475 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11476 (cond
11477 ((not org-refile-cache) nil)
11478 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11480 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11481 org-refile-cache))))
11482 (and set (org-refile-cache-check-set set) set)))))
11484 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11485 "Produce a table with refile targets."
11486 (let ((case-fold-search nil)
11487 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11488 (entries (or org-refile-targets '((nil . (:level . 1)))))
11489 targets tgs txt re files desc descre fast-path-p level pos0)
11490 (message "Getting targets...")
11491 (with-current-buffer (or default-buffer (current-buffer))
11492 (dolist (entry entries)
11493 (setq files (car entry) desc (cdr entry))
11494 (setq fast-path-p nil)
11495 (cond
11496 ((null files) (setq files (list (current-buffer))))
11497 ((eq files 'org-agenda-files)
11498 (setq files (org-agenda-files 'unrestricted)))
11499 ((and (symbolp files) (fboundp files))
11500 (setq files (funcall files)))
11501 ((and (symbolp files) (boundp files))
11502 (setq files (symbol-value files))))
11503 (when (stringp files) (setq files (list files)))
11504 (cond
11505 ((eq (car desc) :tag)
11506 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11507 ((eq (car desc) :todo)
11508 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11509 ((eq (car desc) :regexp)
11510 (setq descre (cdr desc)))
11511 ((eq (car desc) :level)
11512 (setq descre (concat "^\\*\\{" (number-to-string
11513 (if org-odd-levels-only
11514 (1- (* 2 (cdr desc)))
11515 (cdr desc)))
11516 "\\}[ \t]")))
11517 ((eq (car desc) :maxlevel)
11518 (setq fast-path-p t)
11519 (setq descre (concat "^\\*\\{1," (number-to-string
11520 (if org-odd-levels-only
11521 (1- (* 2 (cdr desc)))
11522 (cdr desc)))
11523 "\\}[ \t]")))
11524 (t (error "Bad refiling target description %s" desc)))
11525 (dolist (f files)
11526 (with-current-buffer
11527 (if (bufferp f) f (org-get-agenda-file-buffer f))
11529 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11530 (progn
11531 (when (bufferp f) (setq f (buffer-file-name
11532 (buffer-base-buffer f))))
11533 (setq f (and f (expand-file-name f)))
11534 (when (eq org-refile-use-outline-path 'file)
11535 (push (list (file-name-nondirectory f) f nil nil) tgs))
11536 (save-excursion
11537 (save-restriction
11538 (widen)
11539 (goto-char (point-min))
11540 (while (re-search-forward descre nil t)
11541 (goto-char (setq pos0 (point-at-bol)))
11542 (catch 'next
11543 (when org-refile-target-verify-function
11544 (save-match-data
11545 (or (funcall org-refile-target-verify-function)
11546 (throw 'next t))))
11547 (when (and (looking-at org-complex-heading-regexp)
11548 (not (member (match-string 4) excluded-entries))
11549 (match-string 4))
11550 (setq level (org-reduced-level
11551 (- (match-end 1) (match-beginning 1)))
11552 txt (org-link-display-format (match-string 4))
11553 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11554 re (format org-complex-heading-regexp-format
11555 (regexp-quote (match-string 4))))
11556 (when org-refile-use-outline-path
11557 (setq txt (mapconcat
11558 'org-protect-slash
11559 (append
11560 (if (eq org-refile-use-outline-path
11561 'file)
11562 (list (file-name-nondirectory
11563 (buffer-file-name
11564 (buffer-base-buffer))))
11565 (when (eq org-refile-use-outline-path
11566 'full-file-path)
11567 (list (buffer-file-name
11568 (buffer-base-buffer)))))
11569 (org-get-outline-path fast-path-p
11570 level txt)
11571 (list txt))
11572 "/")))
11573 (push (list txt f re (org-refile-marker (point)))
11574 tgs)))
11575 (when (= (point) pos0)
11576 ;; verification function has not moved point
11577 (goto-char (point-at-eol))))))))
11578 (when org-refile-use-cache
11579 (org-refile-cache-put tgs (buffer-file-name) descre))
11580 (setq targets (append tgs targets))))))
11581 (message "Getting targets...done")
11582 (nreverse targets)))
11584 (defun org-protect-slash (s)
11585 (while (string-match "/" s)
11586 (setq s (replace-match "\\" t t s)))
11589 (defvar org-olpa (make-vector 20 nil))
11591 (defun org-get-outline-path (&optional fastp level heading)
11592 "Return the outline path to the current entry, as a list.
11594 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11595 routine which makes outline path derivations for an entire file,
11596 avoiding backtracing. Refile target collection makes use of that."
11597 (if fastp
11598 (progn
11599 (when (> level 19)
11600 (error "Outline path failure, more than 19 levels"))
11601 (cl-loop for i from level upto 19 do
11602 (aset org-olpa i nil))
11603 (prog1
11604 (delq nil (append org-olpa nil))
11605 (aset org-olpa level heading)))
11606 (let (rtn case-fold-search)
11607 (save-excursion
11608 (save-restriction
11609 (widen)
11610 (while (org-up-heading-safe)
11611 (when (looking-at org-complex-heading-regexp)
11612 (push (org-trim
11613 (replace-regexp-in-string
11614 ;; Remove statistical/checkboxes cookies
11615 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11616 (org-match-string-no-properties 4)))
11617 rtn)))
11618 rtn)))))
11620 (defun org-format-outline-path (path &optional width prefix separator)
11621 "Format the outline path PATH for display.
11622 WIDTH is the maximum number of characters that is available.
11623 PREFIX is a prefix to be included in the returned string,
11624 such as the file name.
11625 SEPARATOR is inserted between the different parts of the path,
11626 the default is \"/\"."
11627 (setq width (or width 79))
11628 (setq path (delq nil path))
11629 (unless (> width 0)
11630 (user-error "Argument `width' must be positive"))
11631 (setq separator (or separator "/"))
11632 (let* ((org-odd-levels-only nil)
11633 (fpath (concat
11634 prefix (and prefix path separator)
11635 (mapconcat
11636 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11637 (cl-loop for head in path
11638 for n from 0
11639 collect (org-add-props
11640 head nil 'face
11641 (nth (% n org-n-level-faces) org-level-faces)))
11642 separator))))
11643 (when (> (length fpath) width)
11644 (if (< width 7)
11645 ;; It's unlikely that `width' will be this small, but don't
11646 ;; waste characters by adding ".." if it is.
11647 (setq fpath (substring fpath 0 width))
11648 (setf (substring fpath (- width 2)) "..")))
11649 fpath))
11651 (defun org-display-outline-path (&optional file current separator just-return-string)
11652 "Display the current outline path in the echo area.
11654 If FILE is non-nil, prepend the output with the file name.
11655 If CURRENT is non-nil, append the current heading to the output.
11656 SEPARATOR is passed through to `org-format-outline-path'. It separates
11657 the different parts of the path and defaults to \"/\".
11658 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11659 (interactive "P")
11660 (let* (case-fold-search
11661 (bfn (buffer-file-name (buffer-base-buffer)))
11662 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11663 res)
11664 (when current (setq path (append path
11665 (save-excursion
11666 (org-back-to-heading t)
11667 (when (looking-at org-complex-heading-regexp)
11668 (list (match-string 4)))))))
11669 (setq res
11670 (org-format-outline-path
11671 path
11672 (1- (frame-width))
11673 (and file bfn (concat (file-name-nondirectory bfn) separator))
11674 separator))
11675 (if just-return-string
11676 (org-no-properties res)
11677 (org-unlogged-message "%s" res))))
11679 (defvar org-refile-history nil
11680 "History for refiling operations.")
11682 (defvar org-after-refile-insert-hook nil
11683 "Hook run after `org-refile' has inserted its stuff at the new location.
11684 Note that this is still *before* the stuff will be removed from
11685 the *old* location.")
11687 (defvar org-capture-last-stored-marker)
11688 (defvar org-refile-keep nil
11689 "Non-nil means `org-refile' will copy instead of refile.")
11691 (defun org-copy ()
11692 "Like `org-refile', but copy."
11693 (interactive)
11694 (let ((org-refile-keep t))
11695 (funcall 'org-refile nil nil nil "Copy")))
11697 (defun org-refile (&optional arg default-buffer rfloc msg)
11698 "Move the entry or entries at point to another heading.
11699 The list of target headings is compiled using the information in
11700 `org-refile-targets', which see.
11702 At the target location, the entry is filed as a subitem of the
11703 target heading. Depending on `org-reverse-note-order', the new
11704 subitem will either be the first or the last subitem.
11706 If there is an active region, all entries in that region will be
11707 refiled. However, the region must fulfill the requirement that
11708 the first heading sets the top-level of the moved text.
11710 With prefix arg ARG, the command will only visit the target
11711 location and not actually move anything.
11713 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11714 refiling operation has put the subtree.
11716 With a numeric prefix argument of `2', refile to the running clock.
11718 With a numeric prefix argument of `3', emulate `org-refile-keep'
11719 being set to t and copy to the target location, don't move it.
11720 Beware that keeping refiled entries may result in duplicated ID
11721 properties.
11723 RFLOC can be a refile location obtained in a different way.
11725 MSG is a string to replace \"Refile\" in the default prompt with
11726 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11728 See also `org-refile-use-outline-path'.
11730 If you are using target caching (see `org-refile-use-cache'), you
11731 have to clear the target cache in order to find new targets.
11732 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11733 prefix argument (`C-u C-u C-u C-c C-w')."
11734 (interactive "P")
11735 (if (member arg '(0 (64)))
11736 (org-refile-cache-clear)
11737 (let* ((actionmsg (cond (msg msg)
11738 ((equal arg 3) "Refile (and keep)")
11739 (t "Refile")))
11740 (regionp (org-region-active-p))
11741 (region-start (and regionp (region-beginning)))
11742 (region-end (and regionp (region-end)))
11743 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11744 pos it nbuf file level reversed)
11745 (setq last-command nil)
11746 (when regionp
11747 (goto-char region-start)
11748 (or (bolp) (goto-char (point-at-bol)))
11749 (setq region-start (point))
11750 (unless (or (org-kill-is-subtree-p
11751 (buffer-substring region-start region-end))
11752 (prog1 org-refile-active-region-within-subtree
11753 (let ((s (point-at-eol)))
11754 (org-toggle-heading)
11755 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11756 (user-error "The region is not a (sequence of) subtree(s)")))
11757 (if (equal arg '(16))
11758 (org-refile-goto-last-stored)
11759 (when (or
11760 (and (equal arg 2)
11761 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11762 (prog1
11763 (setq it (list (or org-clock-heading "running clock")
11764 (buffer-file-name
11765 (marker-buffer org-clock-hd-marker))
11767 (marker-position org-clock-hd-marker)))
11768 (setq arg nil)))
11769 (setq it (or rfloc
11770 (let (heading-text)
11771 (save-excursion
11772 (unless (and arg (listp arg))
11773 (org-back-to-heading t)
11774 (setq heading-text
11775 (replace-regexp-in-string
11776 org-bracket-link-regexp
11777 "\\3"
11778 (nth 4 (org-heading-components)))))
11779 (org-refile-get-location
11780 (cond ((and arg (listp arg)) "Goto")
11781 (regionp (concat actionmsg " region to"))
11782 (t (concat actionmsg " subtree \""
11783 heading-text "\" to")))
11784 default-buffer
11785 (and (not (equal '(4) arg))
11786 org-refile-allow-creating-parent-nodes)
11787 arg))))))
11788 (setq file (nth 1 it)
11789 pos (nth 3 it))
11790 (when (and (not arg)
11792 (equal (buffer-file-name) file)
11793 (if regionp
11794 (and (>= pos region-start)
11795 (<= pos region-end))
11796 (and (>= pos (point))
11797 (< pos (save-excursion
11798 (org-end-of-subtree t t))))))
11799 (error "Cannot refile to position inside the tree or region"))
11800 (setq nbuf (or (find-buffer-visiting file)
11801 (find-file-noselect file)))
11802 (if (and arg (not (equal arg 3)))
11803 (progn
11804 (org-pop-to-buffer-same-window nbuf)
11805 (goto-char pos)
11806 (org-show-context 'org-goto))
11807 (if regionp
11808 (progn
11809 (org-kill-new (buffer-substring region-start region-end))
11810 (org-save-markers-in-region region-start region-end))
11811 (org-copy-subtree 1 nil t))
11812 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11813 (find-file-noselect file)))
11814 (setq reversed (org-notes-order-reversed-p))
11815 (save-excursion
11816 (save-restriction
11817 (widen)
11818 (if pos
11819 (progn
11820 (goto-char pos)
11821 (looking-at org-outline-regexp)
11822 (setq level (org-get-valid-level (funcall outline-level) 1))
11823 (goto-char
11824 (if reversed
11825 (or (outline-next-heading) (point-max))
11826 (or (save-excursion (org-get-next-sibling))
11827 (org-end-of-subtree t t)
11828 (point-max)))))
11829 (setq level 1)
11830 (if (not reversed)
11831 (goto-char (point-max))
11832 (goto-char (point-min))
11833 (or (outline-next-heading) (goto-char (point-max)))))
11834 (unless (bolp) (newline))
11835 (org-paste-subtree level nil nil t)
11836 (when org-log-refile
11837 (org-add-log-setup 'refile nil nil org-log-refile)
11838 (unless (eq org-log-refile 'note)
11839 (save-excursion (org-add-log-note))))
11840 (and org-auto-align-tags
11841 (let ((org-loop-over-headlines-in-active-region nil))
11842 (org-set-tags nil t)))
11843 (let ((bookmark-name (plist-get org-bookmark-names-plist
11844 :last-refile)))
11845 (when bookmark-name
11846 (with-demoted-errors
11847 (bookmark-set bookmark-name))))
11848 ;; If we are refiling for capture, make sure that the
11849 ;; last-capture pointers point here
11850 (when (org-bound-and-true-p org-capture-is-refiling)
11851 (let ((bookmark-name (plist-get org-bookmark-names-plist
11852 :last-capture-marker)))
11853 (when bookmark-name
11854 (with-demoted-errors
11855 (bookmark-set bookmark-name))))
11856 (move-marker org-capture-last-stored-marker (point)))
11857 (when (fboundp 'deactivate-mark) (deactivate-mark))
11858 (run-hooks 'org-after-refile-insert-hook))))
11859 (unless org-refile-keep
11860 (if regionp
11861 (delete-region (point) (+ (point) (- region-end region-start)))
11862 (delete-region
11863 (and (org-back-to-heading t) (point))
11864 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11865 (when (featurep 'org-inlinetask)
11866 (org-inlinetask-remove-END-maybe))
11867 (setq org-markers-to-move nil)
11868 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11870 (defun org-refile-goto-last-stored ()
11871 "Go to the location where the last refile was stored."
11872 (interactive)
11873 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11874 (message "This is the location of the last refile"))
11876 (defun org-refile--get-location (refloc tbl)
11877 "When user refile to REFLOC, find the associated target in TBL.
11878 Also check `org-refile-target-table'."
11879 (car (delq
11881 (mapcar
11882 (lambda (r) (or (assoc r tbl)
11883 (assoc r org-refile-target-table)))
11884 (list (replace-regexp-in-string "/$" "" refloc)
11885 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11887 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11888 no-exclude)
11889 "Prompt the user for a refile location, using PROMPT.
11890 PROMPT should not be suffixed with a colon and a space, because
11891 this function appends the default value from
11892 `org-refile-history' automatically, if that is not empty.
11893 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11894 this is used for the GOTO interface."
11895 (let ((org-refile-targets org-refile-targets)
11896 (org-refile-use-outline-path org-refile-use-outline-path)
11897 excluded-entries)
11898 (when (and (derived-mode-p 'org-mode)
11899 (not org-refile-use-cache)
11900 (not no-exclude))
11901 (org-map-tree
11902 (lambda()
11903 (setq excluded-entries
11904 (append excluded-entries (list (org-get-heading t t)))))))
11905 (setq org-refile-target-table
11906 (org-refile-get-targets default-buffer excluded-entries)))
11907 (unless org-refile-target-table
11908 (user-error "No refile targets"))
11909 (let* ((cbuf (current-buffer))
11910 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11911 (cfunc (if (and org-refile-use-outline-path
11912 org-outline-path-complete-in-steps)
11913 #'org-olpath-completing-read
11914 #'completing-read))
11915 (extra (if org-refile-use-outline-path "/" ""))
11916 (cbnex (concat (buffer-name) extra))
11917 (filename (and cfn (expand-file-name cfn)))
11918 (tbl (mapcar
11919 (lambda (x)
11920 (if (and (not (member org-refile-use-outline-path
11921 '(file full-file-path)))
11922 (not (equal filename (nth 1 x))))
11923 (cons (concat (car x) extra " ("
11924 (file-name-nondirectory (nth 1 x)) ")")
11925 (cdr x))
11926 (cons (concat (car x) extra) (cdr x))))
11927 org-refile-target-table))
11928 (completion-ignore-case t)
11929 cdef
11930 (prompt (concat prompt
11931 (or (and (car org-refile-history)
11932 (concat " (default " (car org-refile-history) ")"))
11933 (and (assoc cbnex tbl) (setq cdef cbnex)
11934 (concat " (default " cbnex ")"))) ": "))
11935 pa answ parent-target child parent old-hist)
11936 (setq old-hist org-refile-history)
11937 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11938 nil 'org-refile-history (or cdef (car org-refile-history))))
11939 (if (setq pa (org-refile--get-location answ tbl))
11940 (progn
11941 (org-refile-check-position pa)
11942 (when (or (not org-refile-history)
11943 (not (eq old-hist org-refile-history))
11944 (not (equal (car pa) (car org-refile-history))))
11945 (setq org-refile-history
11946 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11947 org-refile-history
11948 (cdr org-refile-history))))
11949 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11950 (pop org-refile-history)))
11952 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11953 (progn
11954 (setq parent (match-string 1 answ)
11955 child (match-string 2 answ))
11956 (setq parent-target (org-refile--get-location parent tbl))
11957 (when (and parent-target
11958 (or (eq new-nodes t)
11959 (and (eq new-nodes 'confirm)
11960 (y-or-n-p (format "Create new node \"%s\"? "
11961 child)))))
11962 (org-refile-new-child parent-target child)))
11963 (user-error "Invalid target location")))))
11965 (declare-function org-string-nw-p "org-macs" (s))
11966 (defun org-refile-check-position (refile-pointer)
11967 "Check if the refile pointer matches the headline to which it points."
11968 (let* ((file (nth 1 refile-pointer))
11969 (re (nth 2 refile-pointer))
11970 (pos (nth 3 refile-pointer))
11971 buffer)
11972 (if (and (not (markerp pos)) (not file))
11973 (user-error "Please indicate a target file in the refile path")
11974 (when (org-string-nw-p re)
11975 (setq buffer (if (markerp pos)
11976 (marker-buffer pos)
11977 (or (find-buffer-visiting file)
11978 (find-file-noselect file))))
11979 (with-current-buffer buffer
11980 (save-excursion
11981 (save-restriction
11982 (widen)
11983 (goto-char pos)
11984 (beginning-of-line 1)
11985 (unless (org-looking-at-p re)
11986 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11988 (defun org-refile-new-child (parent-target child)
11989 "Use refile target PARENT-TARGET to add new CHILD below it."
11990 (unless parent-target
11991 (error "Cannot find parent for new node"))
11992 (let ((file (nth 1 parent-target))
11993 (pos (nth 3 parent-target))
11994 level)
11995 (with-current-buffer (or (find-buffer-visiting file)
11996 (find-file-noselect file))
11997 (save-excursion
11998 (save-restriction
11999 (widen)
12000 (if pos
12001 (goto-char pos)
12002 (goto-char (point-max))
12003 (unless (bolp) (newline)))
12004 (when (looking-at org-outline-regexp)
12005 (setq level (funcall outline-level))
12006 (org-end-of-subtree t t))
12007 (org-back-over-empty-lines)
12008 (insert "\n" (make-string
12009 (if pos (org-get-valid-level level 1) 1) ?*)
12010 " " child "\n")
12011 (beginning-of-line 0)
12012 (list (concat (car parent-target) "/" child) file "" (point)))))))
12014 (defun org-olpath-completing-read (prompt collection &rest args)
12015 "Read an outline path like a file name."
12016 (let ((thetable collection))
12017 (apply #'completing-read
12018 prompt
12019 (lambda (string predicate &optional flag)
12020 (cond
12021 ((eq flag nil) (try-completion string thetable))
12022 ((eq flag t)
12023 (let ((l (length string)))
12024 (mapcar (lambda (x)
12025 (let ((r (substring x l))
12026 (f (if (string-match " ([^)]*)$" x)
12027 (match-string 0 x)
12028 "")))
12029 (if (string-match "/" r)
12030 (concat string (substring r 0 (match-end 0)) f)
12031 x)))
12032 (all-completions string thetable predicate))))
12033 ;; Exact match?
12034 ((eq flag 'lambda) (assoc string thetable))))
12035 args)))
12037 ;;;; Dynamic blocks
12039 (defun org-find-dblock (name)
12040 "Find the first dynamic block with name NAME in the buffer.
12041 If not found, stay at current position and return nil."
12042 (let ((case-fold-search t) pos)
12043 (save-excursion
12044 (goto-char (point-min))
12045 (setq pos (and (re-search-forward
12046 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12047 (match-beginning 0))))
12048 (when pos (goto-char pos))
12049 pos))
12051 (defun org-create-dblock (plist)
12052 "Create a dynamic block section, with parameters taken from PLIST.
12053 PLIST must contain a :name entry which is used as the name of the block."
12054 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12055 (end-of-line 1)
12056 (newline))
12057 (let ((col (current-column))
12058 (name (plist-get plist :name)))
12059 (insert "#+BEGIN: " name)
12060 (while plist
12061 (if (eq (car plist) :name)
12062 (setq plist (cddr plist))
12063 (insert " " (prin1-to-string (pop plist)))))
12064 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12065 (beginning-of-line -2)))
12067 (defun org-prepare-dblock ()
12068 "Prepare dynamic block for refresh.
12069 This empties the block, puts the cursor at the insert position and returns
12070 the property list including an extra property :name with the block name."
12071 (unless (looking-at org-dblock-start-re)
12072 (user-error "Not at a dynamic block"))
12073 (let* ((begdel (1+ (match-end 0)))
12074 (name (org-no-properties (match-string 1)))
12075 (params (append (list :name name)
12076 (read (concat "(" (match-string 3) ")")))))
12077 (save-excursion
12078 (beginning-of-line 1)
12079 (skip-chars-forward " \t")
12080 (setq params (plist-put params :indentation-column (current-column))))
12081 (unless (re-search-forward org-dblock-end-re nil t)
12082 (error "Dynamic block not terminated"))
12083 (setq params
12084 (append params
12085 (list :content (buffer-substring
12086 begdel (match-beginning 0)))))
12087 (delete-region begdel (match-beginning 0))
12088 (goto-char begdel)
12089 (open-line 1)
12090 params))
12092 (defun org-map-dblocks (&optional command)
12093 "Apply COMMAND to all dynamic blocks in the current buffer.
12094 If COMMAND is not given, use `org-update-dblock'."
12095 (let ((cmd (or command 'org-update-dblock)))
12096 (save-excursion
12097 (goto-char (point-min))
12098 (while (re-search-forward org-dblock-start-re nil t)
12099 (goto-char (match-beginning 0))
12100 (save-excursion
12101 (condition-case nil
12102 (funcall cmd)
12103 (error (message "Error during update of dynamic block"))))
12104 (unless (re-search-forward org-dblock-end-re nil t)
12105 (error "Dynamic block not terminated"))))))
12107 (defun org-dblock-update (&optional arg)
12108 "User command for updating dynamic blocks.
12109 Update the dynamic block at point. With prefix ARG, update all dynamic
12110 blocks in the buffer."
12111 (interactive "P")
12112 (if arg
12113 (org-update-all-dblocks)
12114 (or (looking-at org-dblock-start-re)
12115 (org-beginning-of-dblock))
12116 (org-update-dblock)))
12118 (defun org-update-dblock ()
12119 "Update the dynamic block at point.
12120 This means to empty the block, parse for parameters and then call
12121 the correct writing function."
12122 (interactive)
12123 (save-excursion
12124 (let* ((win (selected-window))
12125 (pos (point))
12126 (line (org-current-line))
12127 (params (org-prepare-dblock))
12128 (name (plist-get params :name))
12129 (indent (plist-get params :indentation-column))
12130 (cmd (intern (concat "org-dblock-write:" name))))
12131 (message "Updating dynamic block `%s' at line %d..." name line)
12132 (funcall cmd params)
12133 (message "Updating dynamic block `%s' at line %d...done" name line)
12134 (goto-char pos)
12135 (when (and indent (> indent 0))
12136 (setq indent (make-string indent ?\ ))
12137 (save-excursion
12138 (select-window win)
12139 (org-beginning-of-dblock)
12140 (forward-line 1)
12141 (while (not (looking-at org-dblock-end-re))
12142 (insert indent)
12143 (beginning-of-line 2))
12144 (when (looking-at org-dblock-end-re)
12145 (and (looking-at "[ \t]+")
12146 (replace-match ""))
12147 (insert indent)))))))
12149 (defun org-beginning-of-dblock ()
12150 "Find the beginning of the dynamic block at point.
12151 Error if there is no such block at point."
12152 (let ((pos (point))
12153 beg)
12154 (end-of-line 1)
12155 (if (and (re-search-backward org-dblock-start-re nil t)
12156 (setq beg (match-beginning 0))
12157 (re-search-forward org-dblock-end-re nil t)
12158 (> (match-end 0) pos))
12159 (goto-char beg)
12160 (goto-char pos)
12161 (error "Not in a dynamic block"))))
12163 (defun org-update-all-dblocks ()
12164 "Update all dynamic blocks in the buffer.
12165 This function can be used in a hook."
12166 (interactive)
12167 (when (derived-mode-p 'org-mode)
12168 (org-map-dblocks 'org-update-dblock)))
12171 ;;;; Completion
12173 (declare-function org-export-backend-name "org-export" (cl-x))
12174 (declare-function org-export-backend-options "org-export" (cl-x))
12175 (defun org-get-export-keywords ()
12176 "Return a list of all currently understood export keywords.
12177 Export keywords include options, block names, attributes and
12178 keywords relative to each registered export back-end."
12179 (let (keywords)
12180 (dolist (backend
12181 (org-bound-and-true-p org-export-registered-backends)
12182 (delq nil keywords))
12183 ;; Back-end name (for keywords, like #+LATEX:)
12184 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12185 (dolist (option-entry (org-export-backend-options backend))
12186 ;; Back-end options.
12187 (push (nth 1 option-entry) keywords)))))
12189 (defconst org-options-keywords
12190 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12191 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12192 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12193 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12194 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12196 (defcustom org-structure-template-alist
12197 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12198 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12199 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12200 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12201 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12202 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12203 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12204 ("L" "#+LaTeX: ")
12205 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12206 ("H" "#+HTML: ")
12207 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12208 ("A" "#+ASCII: ")
12209 ("i" "#+INDEX: ?")
12210 ("I" "#+INCLUDE: %file ?"))
12211 "Structure completion elements.
12212 This is a list of abbreviation keys and values. The value gets inserted
12213 if you type `<' followed by the key and then press the completion key,
12214 usually `TAB'. %file will be replaced by a file name after prompting
12215 for the file using completion. The cursor will be placed at the position
12216 of the `?' in the template.
12217 There are two templates for each key, the first uses the original Org syntax,
12218 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12219 the default when the /org-mtags.el/ module has been loaded. See also the
12220 variable `org-mtags-prefer-muse-templates'."
12221 :group 'org-completion
12222 :type '(repeat
12223 (list
12224 (string :tag "Key")
12225 (string :tag "Template")))
12226 :version "25.1"
12227 :package-version '(Org . "8.3"))
12229 (defun org-try-structure-completion ()
12230 "Try to complete a structure template before point.
12231 This looks for strings like \"<e\" on an otherwise empty line and
12232 expands them."
12233 (let ((l (buffer-substring (point-at-bol) (point)))
12235 (when (and (looking-at "[ \t]*$")
12236 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12237 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12238 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12239 (match-beginning 1)) a)
12240 t)))
12242 (defun org-complete-expand-structure-template (start cell)
12243 "Expand a structure template."
12244 (let ((rpl (nth 1 cell))
12245 (ind ""))
12246 (delete-region start (point))
12247 (when (string-match "\\`[ \t]*#\\+" rpl)
12248 (cond
12249 ((bolp))
12250 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12251 (setq ind (buffer-substring (point-at-bol) (point))))
12252 (t (newline))))
12253 (setq start (point))
12254 (when (string-match "%file" rpl)
12255 (setq rpl (replace-match
12256 (concat
12257 "\""
12258 (save-match-data
12259 (abbreviate-file-name (read-file-name "Include file: ")))
12260 "\"")
12261 t t rpl)))
12262 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12263 (concat "\n" ind)))
12264 (insert rpl)
12265 (when (re-search-backward "\\?" start t) (delete-char 1))))
12267 ;;;; TODO, DEADLINE, Comments
12269 (defun org-toggle-comment ()
12270 "Change the COMMENT state of an entry."
12271 (interactive)
12272 (save-excursion
12273 (org-back-to-heading)
12274 (looking-at org-complex-heading-regexp)
12275 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12276 (skip-chars-forward " \t")
12277 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12278 (if (org-in-commented-heading-p t)
12279 (delete-region (point)
12280 (progn (search-forward " " (line-end-position) 'move)
12281 (skip-chars-forward " \t")
12282 (point)))
12283 (insert org-comment-string)
12284 (unless (eolp) (insert " ")))))
12286 (defvar org-last-todo-state-is-todo nil
12287 "This is non-nil when the last TODO state change led to a TODO state.
12288 If the last change removed the TODO tag or switched to DONE, then
12289 this is nil.")
12291 (defvar org-setting-tags nil) ; dynamically skipped
12293 (defvar org-todo-setup-filter-hook nil
12294 "Hook for functions that pre-filter todo specs.
12295 Each function takes a todo spec and returns either nil or the spec
12296 transformed into canonical form." )
12298 (defvar org-todo-get-default-hook nil
12299 "Hook for functions that get a default item for todo.
12300 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12301 nil or a string to be used for the todo mark." )
12303 (defvar org-agenda-headline-snapshot-before-repeat)
12305 (defun org-current-effective-time ()
12306 "Return current time adjusted for `org-extend-today-until' variable."
12307 (let* ((ct (org-current-time))
12308 (dct (decode-time ct))
12309 (ct1
12310 (cond
12311 (org-use-last-clock-out-time-as-effective-time
12312 (or (org-clock-get-last-clock-out-time) ct))
12313 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12314 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12315 (t ct))))
12316 ct1))
12318 (defun org-todo-yesterday (&optional arg)
12319 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12320 (interactive "P")
12321 (if (eq major-mode 'org-agenda-mode)
12322 (apply 'org-agenda-todo-yesterday arg)
12323 (let* ((org-use-effective-time t)
12324 (hour (nth 2 (decode-time (org-current-time))))
12325 (org-extend-today-until (1+ hour)))
12326 (org-todo arg))))
12328 (defvar org-block-entry-blocking ""
12329 "First entry preventing the TODO state change.")
12331 (defun org-cancel-repeater ()
12332 "Cancel a repeater by setting its numeric value to zero."
12333 (interactive)
12334 (save-excursion
12335 (org-back-to-heading t)
12336 (let ((bound1 (point))
12337 (bound0 (save-excursion (outline-next-heading) (point))))
12338 (when (and (re-search-forward
12339 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12340 org-deadline-time-regexp "\\)\\|\\("
12341 org-ts-regexp "\\)")
12342 bound0 t)
12343 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12344 bound1 t))
12345 (replace-match "0" t nil nil 1)))))
12347 (defvar org-state) ;; dynamically scoped into this function
12348 (defun org-todo (&optional arg)
12349 "Change the TODO state of an item.
12350 The state of an item is given by a keyword at the start of the heading,
12351 like
12352 *** TODO Write paper
12353 *** DONE Call mom
12355 The different keywords are specified in the variable `org-todo-keywords'.
12356 By default the available states are \"TODO\" and \"DONE\".
12357 So for this example: when the item starts with TODO, it is changed to DONE.
12358 When it starts with DONE, the DONE is removed. And when neither TODO nor
12359 DONE are present, add TODO at the beginning of the heading.
12361 With \\[universal-argument] prefix arg, use completion to determine the new \
12362 state.
12363 With numeric prefix arg, switch to that state.
12364 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12365 keywords (nextset).
12366 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12367 With a numeric prefix arg of 0, inhibit note taking for the change.
12368 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12370 When called through ELisp, arg is also interpreted in the following way:
12371 `none' -> empty state
12372 \"\"(empty string) -> switch to empty state
12373 `done' -> switch to DONE
12374 `nextset' -> switch to the next set of keywords
12375 `previousset' -> switch to the previous set of keywords
12376 \"WAITING\" -> switch to the specified keyword, but only if it
12377 really is a member of `org-todo-keywords'."
12378 (interactive "P")
12379 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12380 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12381 'region-start-level 'region))
12382 org-loop-over-headlines-in-active-region)
12383 (org-map-entries
12384 `(org-todo ,arg)
12385 org-loop-over-headlines-in-active-region
12386 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12387 (when (equal arg '(16)) (setq arg 'nextset))
12388 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12389 (let ((org-blocker-hook org-blocker-hook)
12390 commentp
12391 case-fold-search)
12392 (when (equal arg '(64))
12393 (setq arg nil org-blocker-hook nil))
12394 (when (and org-blocker-hook
12395 (or org-inhibit-blocking
12396 (org-entry-get nil "NOBLOCKING")))
12397 (setq org-blocker-hook nil))
12398 (save-excursion
12399 (catch 'exit
12400 (org-back-to-heading t)
12401 (when (org-in-commented-heading-p t)
12402 (org-toggle-comment)
12403 (setq commentp t))
12404 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12405 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12406 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12407 (let* ((match-data (match-data))
12408 (startpos (point-at-bol))
12409 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12410 (org-log-done org-log-done)
12411 (org-log-repeat org-log-repeat)
12412 (org-todo-log-states org-todo-log-states)
12413 (org-inhibit-logging
12414 (if (equal arg 0)
12415 (progn (setq arg nil) 'note) org-inhibit-logging))
12416 (this (match-string 1))
12417 (hl-pos (match-beginning 0))
12418 (head (org-get-todo-sequence-head this))
12419 (ass (assoc head org-todo-kwd-alist))
12420 (interpret (nth 1 ass))
12421 (done-word (nth 3 ass))
12422 (final-done-word (nth 4 ass))
12423 (org-last-state (or this ""))
12424 (completion-ignore-case t)
12425 (member (member this org-todo-keywords-1))
12426 (tail (cdr member))
12427 (org-state (cond
12428 ((and org-todo-key-trigger
12429 (or (and (equal arg '(4))
12430 (eq org-use-fast-todo-selection 'prefix))
12431 (and (not arg) org-use-fast-todo-selection
12432 (not (eq org-use-fast-todo-selection
12433 'prefix)))))
12434 ;; Use fast selection
12435 (org-fast-todo-selection))
12436 ((and (equal arg '(4))
12437 (or (not org-use-fast-todo-selection)
12438 (not org-todo-key-trigger)))
12439 ;; Read a state with completion
12440 (completing-read
12441 "State: " (mapcar #'list org-todo-keywords-1)
12442 nil t))
12443 ((eq arg 'right)
12444 (if this
12445 (if tail (car tail) nil)
12446 (car org-todo-keywords-1)))
12447 ((eq arg 'left)
12448 (unless (equal member org-todo-keywords-1)
12449 (if this
12450 (nth (- (length org-todo-keywords-1)
12451 (length tail) 2)
12452 org-todo-keywords-1)
12453 (org-last org-todo-keywords-1))))
12454 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12455 (setq arg nil))) ; hack to fall back to cycling
12456 (arg
12457 ;; user or caller requests a specific state
12458 (cond
12459 ((equal arg "") nil)
12460 ((eq arg 'none) nil)
12461 ((eq arg 'done) (or done-word (car org-done-keywords)))
12462 ((eq arg 'nextset)
12463 (or (car (cdr (member head org-todo-heads)))
12464 (car org-todo-heads)))
12465 ((eq arg 'previousset)
12466 (let ((org-todo-heads (reverse org-todo-heads)))
12467 (or (car (cdr (member head org-todo-heads)))
12468 (car org-todo-heads))))
12469 ((car (member arg org-todo-keywords-1)))
12470 ((stringp arg)
12471 (user-error "State `%s' not valid in this file" arg))
12472 ((nth (1- (prefix-numeric-value arg))
12473 org-todo-keywords-1))))
12474 ((null member) (or head (car org-todo-keywords-1)))
12475 ((equal this final-done-word) nil) ;; -> make empty
12476 ((null tail) nil) ;; -> first entry
12477 ((memq interpret '(type priority))
12478 (if (eq this-command last-command)
12479 (car tail)
12480 (if (> (length tail) 0)
12481 (or done-word (car org-done-keywords))
12482 nil)))
12484 (car tail))))
12485 (org-state (or
12486 (run-hook-with-args-until-success
12487 'org-todo-get-default-hook org-state org-last-state)
12488 org-state))
12489 (next (if org-state (concat " " org-state " ") " "))
12490 (change-plist (list :type 'todo-state-change :from this :to org-state
12491 :position startpos))
12492 dolog now-done-p)
12493 (when org-blocker-hook
12494 (setq org-last-todo-state-is-todo
12495 (not (member this org-done-keywords)))
12496 (unless (save-excursion
12497 (save-match-data
12498 (org-with-wide-buffer
12499 (run-hook-with-args-until-failure
12500 'org-blocker-hook change-plist))))
12501 (if (org-called-interactively-p 'interactive)
12502 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12503 this org-state org-block-entry-blocking)
12504 ;; fail silently
12505 (message "TODO state change from %s to %s blocked (by \"%s\")"
12506 this org-state org-block-entry-blocking)
12507 (throw 'exit nil))))
12508 (store-match-data match-data)
12509 (replace-match next t t)
12510 (cond ((equal this org-state)
12511 (message "TODO state was already %s" (org-trim next)))
12512 ((pos-visible-in-window-p hl-pos)
12513 (message "TODO state changed to %s" (org-trim next))))
12514 (unless head
12515 (setq head (org-get-todo-sequence-head org-state)
12516 ass (assoc head org-todo-kwd-alist)
12517 interpret (nth 1 ass)
12518 done-word (nth 3 ass)
12519 final-done-word (nth 4 ass)))
12520 (when (memq arg '(nextset previousset))
12521 (message "Keyword-Set %d/%d: %s"
12522 (- (length org-todo-sets) -1
12523 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12524 (length org-todo-sets)
12525 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12526 (setq org-last-todo-state-is-todo
12527 (not (member org-state org-done-keywords)))
12528 (setq now-done-p (and (member org-state org-done-keywords)
12529 (not (member this org-done-keywords))))
12530 (and logging (org-local-logging logging))
12531 (when (and (or org-todo-log-states org-log-done)
12532 (not (eq org-inhibit-logging t))
12533 (not (memq arg '(nextset previousset))))
12534 ;; we need to look at recording a time and note
12535 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12536 (nth 2 (assoc this org-todo-log-states))))
12537 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12538 (setq dolog 'time))
12539 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12540 (and org-state
12541 (member org-state org-not-done-keywords)
12542 (not (member this org-not-done-keywords))))
12543 ;; This is now a todo state and was not one before
12544 ;; If there was a CLOSED time stamp, get rid of it.
12545 (org-add-planning-info nil nil 'closed))
12546 (when (and now-done-p org-log-done)
12547 ;; It is now done, and it was not done before
12548 (org-add-planning-info 'closed (org-current-effective-time))
12549 (when (and (not dolog) (eq 'note org-log-done))
12550 (org-add-log-setup 'done org-state this 'note)))
12551 (when (and org-state dolog)
12552 ;; This is a non-nil state, and we need to log it
12553 (org-add-log-setup 'state org-state this dolog)))
12554 ;; Fixup tag positioning
12555 (org-todo-trigger-tag-changes org-state)
12556 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12557 (when org-provide-todo-statistics
12558 (org-update-parent-todo-statistics))
12559 (run-hooks 'org-after-todo-state-change-hook)
12560 (when (and arg (not (member org-state org-done-keywords)))
12561 (setq head (org-get-todo-sequence-head org-state)))
12562 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12563 ;; Do we need to trigger a repeat?
12564 (when now-done-p
12565 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12566 ;; This is for the agenda, take a snapshot of the headline.
12567 (save-match-data
12568 (setq org-agenda-headline-snapshot-before-repeat
12569 (org-get-heading))))
12570 (org-auto-repeat-maybe org-state))
12571 ;; Fixup cursor location if close to the keyword
12572 (when (and (outline-on-heading-p)
12573 (not (bolp))
12574 (save-excursion (beginning-of-line 1)
12575 (looking-at org-todo-line-regexp))
12576 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12577 (goto-char (or (match-end 2) (match-end 1)))
12578 (and (looking-at " ") (just-one-space)))
12579 (when org-trigger-hook
12580 (save-excursion
12581 (run-hook-with-args 'org-trigger-hook change-plist)))
12582 (when commentp (org-toggle-comment))))))))
12584 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12585 "Block turning an entry into a TODO, using the hierarchy.
12586 This checks whether the current task should be blocked from state
12587 changes. Such blocking occurs when:
12589 1. The task has children which are not all in a completed state.
12591 2. A task has a parent with the property :ORDERED:, and there
12592 are siblings prior to the current task with incomplete
12593 status.
12595 3. The parent of the task is blocked because it has siblings that should
12596 be done first, or is child of a block grandparent TODO entry."
12598 (if (not org-enforce-todo-dependencies)
12599 t ; if locally turned off don't block
12600 (catch 'dont-block
12601 ;; If this is not a todo state change, or if this entry is already DONE,
12602 ;; do not block
12603 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12604 (member (plist-get change-plist :from)
12605 (cons 'done org-done-keywords))
12606 (member (plist-get change-plist :to)
12607 (cons 'todo org-not-done-keywords))
12608 (not (plist-get change-plist :to)))
12609 (throw 'dont-block t))
12610 ;; If this task has children, and any are undone, it's blocked
12611 (save-excursion
12612 (org-back-to-heading t)
12613 (let ((this-level (funcall outline-level)))
12614 (outline-next-heading)
12615 (let ((child-level (funcall outline-level)))
12616 (while (and (not (eobp))
12617 (> child-level this-level))
12618 ;; this todo has children, check whether they are all
12619 ;; completed
12620 (when (and (not (org-entry-is-done-p))
12621 (org-entry-is-todo-p))
12622 (setq org-block-entry-blocking (org-get-heading))
12623 (throw 'dont-block nil))
12624 (outline-next-heading)
12625 (setq child-level (funcall outline-level))))))
12626 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12627 ;; any previous siblings are undone, it's blocked
12628 (save-excursion
12629 (org-back-to-heading t)
12630 (let* ((pos (point))
12631 (parent-pos (and (org-up-heading-safe) (point))))
12632 (unless parent-pos (throw 'dont-block t)) ; no parent
12633 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12634 (forward-line 1)
12635 (re-search-forward org-not-done-heading-regexp pos t))
12636 (setq org-block-entry-blocking (match-string 0))
12637 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12638 ;; Search further up the hierarchy, to see if an ancestor is blocked
12639 (while t
12640 (goto-char parent-pos)
12641 (unless (looking-at org-not-done-heading-regexp)
12642 (throw 'dont-block t)) ; do not block, parent is not a TODO
12643 (setq pos (point))
12644 (setq parent-pos (and (org-up-heading-safe) (point)))
12645 (unless parent-pos (throw 'dont-block t)) ; no parent
12646 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12647 (forward-line 1)
12648 (re-search-forward org-not-done-heading-regexp pos t)
12649 (setq org-block-entry-blocking (org-get-heading)))
12650 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12652 (defcustom org-track-ordered-property-with-tag nil
12653 "Should the ORDERED property also be shown as a tag?
12654 The ORDERED property decides if an entry should require subtasks to be
12655 completed in sequence. Since a property is not very visible, setting
12656 this option means that toggling the ORDERED property with the command
12657 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12658 not relevant for the behavior, but it makes things more visible.
12660 Note that toggling the tag with tags commands will not change the property
12661 and therefore not influence behavior!
12663 This can be t, meaning the tag ORDERED should be used, It can also be a
12664 string to select a different tag for this task."
12665 :group 'org-todo
12666 :type '(choice
12667 (const :tag "No tracking" nil)
12668 (const :tag "Track with ORDERED tag" t)
12669 (string :tag "Use other tag")))
12671 (defun org-toggle-ordered-property ()
12672 "Toggle the ORDERED property of the current entry.
12673 For better visibility, you can track the value of this property with a tag.
12674 See variable `org-track-ordered-property-with-tag'."
12675 (interactive)
12676 (let* ((t1 org-track-ordered-property-with-tag)
12677 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12678 (save-excursion
12679 (org-back-to-heading)
12680 (if (org-entry-get nil "ORDERED")
12681 (progn
12682 (org-delete-property "ORDERED")
12683 (and tag (org-toggle-tag tag 'off))
12684 (message "Subtasks can be completed in arbitrary order"))
12685 (org-entry-put nil "ORDERED" "t")
12686 (and tag (org-toggle-tag tag 'on))
12687 (message "Subtasks must be completed in sequence")))))
12689 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12690 (defun org-block-todo-from-checkboxes (change-plist)
12691 "Block turning an entry into a TODO, using checkboxes.
12692 This checks whether the current task should be blocked from state
12693 changes because there are unchecked boxes in this entry."
12694 (if (not org-enforce-todo-checkbox-dependencies)
12695 t ; if locally turned off don't block
12696 (catch 'dont-block
12697 ;; If this is not a todo state change, or if this entry is already DONE,
12698 ;; do not block
12699 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12700 (member (plist-get change-plist :from)
12701 (cons 'done org-done-keywords))
12702 (member (plist-get change-plist :to)
12703 (cons 'todo org-not-done-keywords))
12704 (not (plist-get change-plist :to)))
12705 (throw 'dont-block t))
12706 ;; If this task has checkboxes that are not checked, it's blocked
12707 (save-excursion
12708 (org-back-to-heading t)
12709 (let ((beg (point)) end)
12710 (outline-next-heading)
12711 (setq end (point))
12712 (goto-char beg)
12713 (when (org-list-search-forward
12714 (concat (org-item-beginning-re)
12715 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12716 "\\[[- ]\\]")
12717 end t)
12718 (when (boundp 'org-blocked-by-checkboxes)
12719 (setq org-blocked-by-checkboxes t))
12720 (throw 'dont-block nil))))
12721 t))) ; do not block
12723 (defun org-entry-blocked-p ()
12724 "Non-nil if entry at point is blocked."
12725 (and (not (org-entry-get nil "NOBLOCKING"))
12726 (member (org-entry-get nil "TODO") org-not-done-keywords)
12727 (not (run-hook-with-args-until-failure
12728 'org-blocker-hook
12729 (list :type 'todo-state-change
12730 :position (point)
12731 :from 'todo
12732 :to 'done)))))
12734 (defun org-update-statistics-cookies (all)
12735 "Update the statistics cookie, either from TODO or from checkboxes.
12736 This should be called with the cursor in a line with a statistics cookie."
12737 (interactive "P")
12738 (if all
12739 (progn
12740 (org-update-checkbox-count 'all)
12741 (org-map-entries 'org-update-parent-todo-statistics))
12742 (if (not (org-at-heading-p))
12743 (org-update-checkbox-count)
12744 (let ((pos (point-marker))
12745 end l1 l2)
12746 (ignore-errors (org-back-to-heading t))
12747 (if (not (org-at-heading-p))
12748 (org-update-checkbox-count)
12749 (setq l1 (org-outline-level))
12750 (setq end (save-excursion
12751 (outline-next-heading)
12752 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12753 (point)))
12754 (if (and (save-excursion
12755 (re-search-forward
12756 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12757 (not (save-excursion (re-search-forward
12758 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12759 (org-update-checkbox-count)
12760 (if (and l2 (> l2 l1))
12761 (progn
12762 (goto-char end)
12763 (org-update-parent-todo-statistics))
12764 (goto-char pos)
12765 (beginning-of-line 1)
12766 (while (re-search-forward
12767 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12768 (point-at-eol) t)
12769 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12770 (goto-char pos)
12771 (move-marker pos nil)))))
12773 (defvar org-entry-property-inherited-from) ;; defined below
12774 (defun org-update-parent-todo-statistics ()
12775 "Update any statistics cookie in the parent of the current headline.
12776 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12777 the entire subtree and this will travel up the hierarchy and update
12778 statistics everywhere."
12779 (let* ((prop (save-excursion (org-up-heading-safe)
12780 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12781 (recursive (or (not org-hierarchical-todo-statistics)
12782 (and prop (string-match "\\<recursive\\>" prop))))
12783 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12785 (first t)
12786 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12787 level ltoggle l1 new ndel
12788 (cnt-all 0) (cnt-done 0) is-percent kwd
12789 checkbox-beg ov ovs ove cookie-present)
12790 (catch 'exit
12791 (save-excursion
12792 (beginning-of-line 1)
12793 (setq ltoggle (funcall outline-level))
12794 ;; Three situations are to consider:
12796 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12797 ;; to the top-level ancestor on the headline;
12799 ;; 2. If parent has "recursive" property, repeat up to the
12800 ;; headline setting that property, taking inheritance into
12801 ;; account;
12803 ;; 3. Else, move up to direct parent and proceed only once.
12804 (while (and (setq level (org-up-heading-safe))
12805 (or recursive first)
12806 (>= (point) lim))
12807 (setq first nil cookie-present nil)
12808 (unless (and level
12809 (not (string-match
12810 "\\<checkbox\\>"
12811 (downcase (or (org-entry-get nil "COOKIE_DATA")
12812 "")))))
12813 (throw 'exit nil))
12814 (while (re-search-forward box-re (point-at-eol) t)
12815 (setq cnt-all 0 cnt-done 0 cookie-present t)
12816 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12817 (save-match-data
12818 (unless (outline-next-heading) (throw 'exit nil))
12819 (while (and (looking-at org-complex-heading-regexp)
12820 (> (setq l1 (length (match-string 1))) level))
12821 (setq kwd (and (or recursive (= l1 ltoggle))
12822 (match-string 2)))
12823 (if (or (eq org-provide-todo-statistics 'all-headlines)
12824 (and (eq org-provide-todo-statistics t)
12825 (or (member kwd org-done-keywords)))
12826 (and (listp org-provide-todo-statistics)
12827 (stringp (car org-provide-todo-statistics))
12828 (or (member kwd org-provide-todo-statistics)
12829 (member kwd org-done-keywords)))
12830 (and (listp org-provide-todo-statistics)
12831 (listp (car org-provide-todo-statistics))
12832 (or (member kwd (car org-provide-todo-statistics))
12833 (and (member kwd org-done-keywords)
12834 (member kwd (cadr org-provide-todo-statistics))))))
12835 (setq cnt-all (1+ cnt-all))
12836 (and (eq org-provide-todo-statistics t)
12838 (setq cnt-all (1+ cnt-all))))
12839 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12840 (member kwd org-done-keywords))
12841 (and (listp org-provide-todo-statistics)
12842 (listp (car org-provide-todo-statistics))
12843 (member kwd org-done-keywords)
12844 (member kwd (cadr org-provide-todo-statistics)))
12845 (and (listp org-provide-todo-statistics)
12846 (stringp (car org-provide-todo-statistics))
12847 (member kwd org-done-keywords)))
12848 (setq cnt-done (1+ cnt-done)))
12849 (outline-next-heading)))
12850 (setq new
12851 (if is-percent
12852 (format "[%d%%]" (floor (* 100.0 cnt-done)
12853 (max 1 cnt-all)))
12854 (format "[%d/%d]" cnt-done cnt-all))
12855 ndel (- (match-end 0) checkbox-beg))
12856 ;; handle overlays when updating cookie from column view
12857 (when (setq ov (car (overlays-at checkbox-beg)))
12858 (setq ovs (overlay-start ov) ove (overlay-end ov))
12859 (delete-overlay ov))
12860 (goto-char checkbox-beg)
12861 (insert new)
12862 (delete-region (point) (+ (point) ndel))
12863 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12864 (when ov (move-overlay ov ovs ove)))
12865 (when cookie-present
12866 (run-hook-with-args 'org-after-todo-statistics-hook
12867 cnt-done (- cnt-all cnt-done))))))
12868 (run-hooks 'org-todo-statistics-hook)))
12870 (defvar org-after-todo-statistics-hook nil
12871 "Hook that is called after a TODO statistics cookie has been updated.
12872 Each function is called with two arguments: the number of not-done entries
12873 and the number of done entries.
12875 For example, the following function, when added to this hook, will switch
12876 an entry to DONE when all children are done, and back to TODO when new
12877 entries are set to a TODO status. Note that this hook is only called
12878 when there is a statistics cookie in the headline!
12880 \(defun org-summary-todo (n-done n-not-done)
12881 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12882 \(let (org-log-done org-log-states) ; turn off logging
12883 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12886 (defvar org-todo-statistics-hook nil
12887 "Hook that is run whenever Org thinks TODO statistics should be updated.
12888 This hook runs even if there is no statistics cookie present, in which case
12889 `org-after-todo-statistics-hook' would not run.")
12891 (defun org-todo-trigger-tag-changes (state)
12892 "Apply the changes defined in `org-todo-state-tags-triggers'."
12893 (let ((l org-todo-state-tags-triggers)
12894 changes)
12895 (when (or (not state) (equal state ""))
12896 (setq changes (append changes (cdr (assoc "" l)))))
12897 (when (and (stringp state) (> (length state) 0))
12898 (setq changes (append changes (cdr (assoc state l)))))
12899 (when (member state org-not-done-keywords)
12900 (setq changes (append changes (cdr (assoc 'todo l)))))
12901 (when (member state org-done-keywords)
12902 (setq changes (append changes (cdr (assoc 'done l)))))
12903 (dolist (c changes)
12904 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12906 (defun org-local-logging (value)
12907 "Get logging settings from a property VALUE."
12908 ;; Directly set the variables, they are already local.
12909 (setq org-log-done nil
12910 org-log-repeat nil
12911 org-todo-log-states nil)
12912 (dolist (w (org-split-string value))
12913 (let (a)
12914 (cond
12915 ((setq a (assoc w org-startup-options))
12916 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12917 (set (nth 1 a) (nth 2 a))))
12918 ((setq a (org-extract-log-state-settings w))
12919 (and (member (car a) org-todo-keywords-1)
12920 (push a org-todo-log-states)))))))
12922 (defun org-get-todo-sequence-head (kwd)
12923 "Return the head of the TODO sequence to which KWD belongs.
12924 If KWD is not set, check if there is a text property remembering the
12925 right sequence."
12926 (let (p)
12927 (cond
12928 ((not kwd)
12929 (or (get-text-property (point-at-bol) 'org-todo-head)
12930 (progn
12931 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12932 nil (point-at-eol)))
12933 (get-text-property p 'org-todo-head))))
12934 ((not (member kwd org-todo-keywords-1))
12935 (car org-todo-keywords-1))
12936 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12938 (defun org-fast-todo-selection ()
12939 "Fast TODO keyword selection with single keys.
12940 Returns the new TODO keyword, or nil if no state change should occur."
12941 (let* ((fulltable org-todo-key-alist)
12942 (done-keywords org-done-keywords) ;; needed for the faces.
12943 (maxlen (apply 'max (mapcar
12944 (lambda (x)
12945 (if (stringp (car x)) (string-width (car x)) 0))
12946 fulltable)))
12947 (expert nil)
12948 (fwidth (+ maxlen 3 1 3))
12949 (ncol (/ (- (window-width) 4) fwidth))
12950 tg cnt e c tbl
12951 groups ingroup)
12952 (save-excursion
12953 (save-window-excursion
12954 (if expert
12955 (set-buffer (get-buffer-create " *Org todo*"))
12956 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12957 (erase-buffer)
12958 (setq-local org-done-keywords done-keywords)
12959 (setq tbl fulltable cnt 0)
12960 (while (setq e (pop tbl))
12961 (cond
12962 ((equal e '(:startgroup))
12963 (push '() groups) (setq ingroup t)
12964 (unless (= cnt 0)
12965 (setq cnt 0)
12966 (insert "\n"))
12967 (insert "{ "))
12968 ((equal e '(:endgroup))
12969 (setq ingroup nil cnt 0)
12970 (insert "}\n"))
12971 ((equal e '(:newline))
12972 (unless (= cnt 0)
12973 (setq cnt 0)
12974 (insert "\n")
12975 (setq e (car tbl))
12976 (while (equal (car tbl) '(:newline))
12977 (insert "\n")
12978 (setq tbl (cdr tbl)))))
12980 (setq tg (car e) c (cdr e))
12981 (when ingroup (push tg (car groups)))
12982 (setq tg (org-add-props tg nil 'face
12983 (org-get-todo-face tg)))
12984 (when (and (= cnt 0) (not ingroup)) (insert " "))
12985 (insert "[" c "] " tg (make-string
12986 (- fwidth 4 (length tg)) ?\ ))
12987 (when (= (setq cnt (1+ cnt)) ncol)
12988 (insert "\n")
12989 (when ingroup (insert " "))
12990 (setq cnt 0)))))
12991 (insert "\n")
12992 (goto-char (point-min))
12993 (unless expert (org-fit-window-to-buffer))
12994 (message "[a-z..]:Set [SPC]:clear")
12995 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12996 (cond
12997 ((or (= c ?\C-g)
12998 (and (= c ?q) (not (rassoc c fulltable))))
12999 (setq quit-flag t))
13000 ((= c ?\ ) nil)
13001 ((setq e (rassoc c fulltable) tg (car e))
13003 (t (setq quit-flag t)))))))
13005 (defun org-entry-is-todo-p ()
13006 (member (org-get-todo-state) org-not-done-keywords))
13008 (defun org-entry-is-done-p ()
13009 (member (org-get-todo-state) org-done-keywords))
13011 (defun org-get-todo-state ()
13012 "Return the TODO keyword of the current subtree."
13013 (save-excursion
13014 (org-back-to-heading t)
13015 (and (looking-at org-todo-line-regexp)
13016 (match-end 2)
13017 (match-string 2))))
13019 (defun org-at-date-range-p (&optional inactive-ok)
13020 "Non-nil if point is inside a date range.
13022 When optional argument INACTIVE-OK is non-nil, also consider
13023 inactive time ranges.
13025 When this function returns a non-nil value, match data is set
13026 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13027 on INACTIVE-OK."
13028 (interactive)
13029 (save-excursion
13030 (catch 'exit
13031 (let ((pos (point)))
13032 (skip-chars-backward "^[<\r\n")
13033 (skip-chars-backward "<[")
13034 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13035 (>= (match-end 0) pos)
13036 (throw 'exit t))
13037 (skip-chars-backward "^<[\r\n")
13038 (skip-chars-backward "<[")
13039 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13040 (>= (match-end 0) pos)
13041 (throw 'exit t)))
13042 nil)))
13044 (defun org-get-repeat (&optional tagline)
13045 "Check if there is a deadline/schedule with repeater in this entry."
13046 (save-match-data
13047 (save-excursion
13048 (org-back-to-heading t)
13049 (and (re-search-forward (if tagline
13050 (concat tagline "\\s-*" org-repeat-re)
13051 org-repeat-re)
13052 (org-entry-end-position) t)
13053 (match-string-no-properties 1)))))
13055 (defvar org-last-changed-timestamp)
13056 (defvar org-last-inserted-timestamp)
13057 (defvar org-log-post-message)
13058 (defvar org-log-note-purpose)
13059 (defvar org-log-note-how nil)
13060 (defvar org-log-note-extra)
13061 (defun org-auto-repeat-maybe (done-word)
13062 "Check if the current headline contains a repeated time-stamp.
13064 If yes, set TODO state back to what it was and change the base date
13065 of repeating deadline/scheduled time stamps to new date.
13067 This function is run automatically after each state change to a DONE state."
13068 (let* ((repeat (org-get-repeat))
13069 (aa (assoc org-last-state org-todo-kwd-alist))
13070 (interpret (nth 1 aa))
13071 (head (nth 2 aa))
13072 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13073 (msg "Entry repeats: ")
13074 (org-log-done nil)
13075 (org-todo-log-states nil))
13076 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13077 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13078 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13079 org-todo-repeat-to-state)))
13080 (unless (and to-state (member to-state org-todo-keywords-1))
13081 (setq to-state (if (eq interpret 'type) org-last-state head)))
13082 (org-todo to-state))
13083 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13084 (org-entry-put nil "LAST_REPEAT" (format-time-string
13085 (org-time-stamp-format t t))))
13086 (when org-log-repeat
13087 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13088 (memq 'org-add-log-note post-command-hook))
13089 ;; We are already setup for some record.
13090 (when (eq org-log-repeat 'note)
13091 ;; Make sure we take a note, not only a time stamp.
13092 (setq org-log-note-how 'note))
13093 ;; Set up for taking a record.
13094 (org-add-log-setup 'state
13095 (or done-word (car org-done-keywords))
13096 org-last-state
13097 org-log-repeat)))
13098 (org-back-to-heading t)
13099 (org-add-planning-info nil nil 'closed)
13100 (let ((end (save-excursion (outline-next-heading) (point))))
13101 (while (re-search-forward org-ts-regexp end t)
13102 (when (save-match-data
13103 (or (org-at-planning-p)
13104 (org-at-property-p)
13105 (eq (org-element-type (save-excursion
13106 (backward-char)
13107 (org-element-context)))
13108 'timestamp)))
13109 (let ((type (cond ((match-end 1) org-scheduled-string)
13110 ((match-end 3) org-deadline-string)
13111 (t "Plain:")))
13112 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13113 (cond
13114 ((not
13115 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13116 ;; Time-stamps without a repeater are usually skipped.
13117 ;; However, a SCHEDULED time-stamp without one is
13118 ;; removed, as it is considered as no longer relevant.
13119 (when (equal type org-scheduled-string)
13120 (org-remove-timestamp-with-keyword type)))
13122 (let ((n (string-to-number (match-string 2 ts)))
13123 (what (match-string 3 ts)))
13124 (when (equal what "w") (setq n (* n 7) what "d"))
13125 (when (and (equal what "h")
13126 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13127 ts)))
13128 (user-error
13129 "Cannot repeat in Repeat in %d hour(s) because no hour \
13130 has been set"
13132 ;; Preparation, see if we need to modify the start
13133 ;; date for the change.
13134 (when (match-end 1)
13135 (let ((time (save-match-data (org-time-string-to-time ts))))
13136 (cond
13137 ((equal (match-string 1 ts) ".")
13138 ;; Shift starting date to today
13139 (org-timestamp-change
13140 (- (org-today) (time-to-days time))
13141 'day))
13142 ((equal (match-string 1 ts) "+")
13143 (let ((nshiftmax 10)
13144 (nshift 0))
13145 (while (or (= nshift 0)
13146 (<= (time-to-days time)
13147 (time-to-days (current-time))))
13148 (when (= (cl-incf nshift) nshiftmax)
13149 (or (y-or-n-p
13150 (format "%d repeater intervals were not \
13151 enough to shift date past today. Continue? "
13152 nshift))
13153 (user-error "Abort")))
13154 (org-timestamp-change n (cdr (assoc what whata)))
13155 (org-at-timestamp-p t)
13156 (setq ts (match-string 1))
13157 (setq time
13158 (save-match-data
13159 (org-time-string-to-time ts)))))
13160 (org-timestamp-change (- n) (cdr (assoc what whata)))
13161 ;; Rematch, so that we have everything in
13162 ;; place for the real shift.
13163 (org-at-timestamp-p t)
13164 (setq ts (match-string 1))
13165 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13166 ts)))))
13167 (save-excursion
13168 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13169 (setq msg
13170 (concat
13171 msg type " " org-last-changed-timestamp " ")))))))))
13172 (setq org-log-post-message msg)
13173 (message "%s" msg))))
13175 (defun org-show-todo-tree (arg)
13176 "Make a compact tree which shows all headlines marked with TODO.
13177 The tree will show the lines where the regexp matches, and all higher
13178 headlines above the match.
13179 With a \\[universal-argument] prefix, prompt for a regexp to match.
13180 With a numeric prefix N, construct a sparse tree for the Nth element
13181 of `org-todo-keywords-1'."
13182 (interactive "P")
13183 (let ((case-fold-search nil)
13184 (kwd-re
13185 (cond ((null arg) org-not-done-regexp)
13186 ((equal arg '(4))
13187 (let ((kwd
13188 (completing-read "Keyword (or KWD1|KWD2|...): "
13189 (mapcar #'list org-todo-keywords-1))))
13190 (concat "\\("
13191 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13192 "\\)\\>")))
13193 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13194 (regexp-quote (nth (1- (prefix-numeric-value arg))
13195 org-todo-keywords-1)))
13196 (t (user-error "Invalid prefix argument: %s" arg)))))
13197 (message "%d TODO entries found"
13198 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13200 (defun org-deadline (arg &optional time)
13201 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13202 With one universal prefix argument, remove any deadline from the item.
13203 With two universal prefix arguments, prompt for a warning delay.
13204 With argument TIME, set the deadline at the corresponding date. TIME
13205 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13206 (interactive "P")
13207 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13208 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13209 'region-start-level 'region))
13210 org-loop-over-headlines-in-active-region)
13211 (org-map-entries
13212 `(org-deadline ',arg ,time)
13213 org-loop-over-headlines-in-active-region
13214 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13215 (let* ((old-date (org-entry-get nil "DEADLINE"))
13216 (old-date-time (when old-date (org-time-string-to-time old-date)))
13217 (repeater (and old-date
13218 (string-match
13219 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13220 old-date)
13221 (match-string 1 old-date))))
13222 (cond
13223 ((equal arg '(4))
13224 (when (and old-date org-log-redeadline)
13225 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13226 (org-remove-timestamp-with-keyword org-deadline-string)
13227 (message "Item no longer has a deadline."))
13228 ((equal arg '(16))
13229 (save-excursion
13230 (org-back-to-heading t)
13231 (if (re-search-forward
13232 org-deadline-time-regexp
13233 (save-excursion (outline-next-heading) (point)) t)
13234 (let* ((rpl0 (match-string 1))
13235 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13236 (replace-match
13237 (concat org-deadline-string
13238 " <" rpl
13239 (format " -%dd"
13240 (abs
13241 (- (time-to-days
13242 (save-match-data
13243 (org-read-date nil t nil "Warn starting from" old-date-time)))
13244 (time-to-days old-date-time))))
13245 ">") t t))
13246 (user-error "No deadline information to update"))))
13248 (org-add-planning-info 'deadline time 'closed)
13249 (when (and old-date
13250 org-log-redeadline
13251 (not (equal old-date org-last-inserted-timestamp)))
13252 (org-add-log-setup
13253 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13254 (when repeater
13255 (save-excursion
13256 (org-back-to-heading t)
13257 (when (re-search-forward (concat org-deadline-string " "
13258 org-last-inserted-timestamp)
13259 (save-excursion
13260 (outline-next-heading) (point)) t)
13261 (goto-char (1- (match-end 0)))
13262 (insert " " repeater)
13263 (setq org-last-inserted-timestamp
13264 (concat (substring org-last-inserted-timestamp 0 -1)
13265 " " repeater
13266 (substring org-last-inserted-timestamp -1))))))
13267 (message "Deadline on %s" org-last-inserted-timestamp))))))
13269 (defun org-schedule (arg &optional time)
13270 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13271 With one universal prefix argument, remove any scheduling date from the item.
13272 With two universal prefix arguments, prompt for a delay cookie.
13273 With argument TIME, scheduled at the corresponding date. TIME can
13274 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13275 (interactive "P")
13276 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13277 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13278 'region-start-level 'region))
13279 org-loop-over-headlines-in-active-region)
13280 (org-map-entries
13281 `(org-schedule ',arg ,time)
13282 org-loop-over-headlines-in-active-region
13283 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13284 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13285 (old-date-time (when old-date (org-time-string-to-time old-date)))
13286 (repeater (and old-date
13287 (string-match
13288 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13289 old-date)
13290 (match-string 1 old-date))))
13291 (cond
13292 ((equal arg '(4))
13293 (progn
13294 (when (and old-date org-log-reschedule)
13295 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13296 (org-remove-timestamp-with-keyword org-scheduled-string)
13297 (message "Item is no longer scheduled.")))
13298 ((equal arg '(16))
13299 (save-excursion
13300 (org-back-to-heading t)
13301 (if (re-search-forward
13302 org-scheduled-time-regexp
13303 (save-excursion (outline-next-heading) (point)) t)
13304 (let* ((rpl0 (match-string 1))
13305 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13306 (replace-match
13307 (concat org-scheduled-string
13308 " <" rpl
13309 (format " -%dd"
13310 (abs
13311 (- (time-to-days
13312 (save-match-data
13313 (org-read-date nil t nil "Delay until" old-date-time)))
13314 (time-to-days old-date-time))))
13315 ">") t t))
13316 (user-error "No scheduled information to update"))))
13318 (org-add-planning-info 'scheduled time 'closed)
13319 (when (and old-date
13320 org-log-reschedule
13321 (not (equal old-date org-last-inserted-timestamp)))
13322 (org-add-log-setup
13323 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13324 (when repeater
13325 (save-excursion
13326 (org-back-to-heading t)
13327 (when (re-search-forward (concat org-scheduled-string " "
13328 org-last-inserted-timestamp)
13329 (save-excursion
13330 (outline-next-heading) (point)) t)
13331 (goto-char (1- (match-end 0)))
13332 (insert " " repeater)
13333 (setq org-last-inserted-timestamp
13334 (concat (substring org-last-inserted-timestamp 0 -1)
13335 " " repeater
13336 (substring org-last-inserted-timestamp -1))))))
13337 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13339 (defun org-get-scheduled-time (pom &optional inherit)
13340 "Get the scheduled time as a time tuple, of a format suitable
13341 for calling org-schedule with, or if there is no scheduling,
13342 returns nil."
13343 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13344 (when time
13345 (apply 'encode-time (org-parse-time-string time)))))
13347 (defun org-get-deadline-time (pom &optional inherit)
13348 "Get the deadline as a time tuple, of a format suitable for
13349 calling org-deadline with, or if there is no scheduling, returns
13350 nil."
13351 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13352 (when time
13353 (apply 'encode-time (org-parse-time-string time)))))
13355 (defun org-remove-timestamp-with-keyword (keyword)
13356 "Remove all time stamps with KEYWORD in the current entry."
13357 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13358 beg)
13359 (save-excursion
13360 (org-back-to-heading t)
13361 (setq beg (point))
13362 (outline-next-heading)
13363 (while (re-search-backward re beg t)
13364 (replace-match "")
13365 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13366 (equal (char-before) ?\ ))
13367 (backward-delete-char 1)
13368 (when (string-match "^[ \t]*$" (buffer-substring
13369 (point-at-bol) (point-at-eol)))
13370 (delete-region (point-at-bol)
13371 (min (point-max) (1+ (point-at-eol))))))))))
13373 (defvar org-time-was-given) ; dynamically scoped parameter
13374 (defvar org-end-time-was-given) ; dynamically scoped parameter
13376 (defun org-at-planning-p ()
13377 "Non-nil when point is on a planning info line."
13378 ;; This is as accurate and faster than `org-element-at-point' since
13379 ;; planning info location is fixed in the section.
13380 (org-with-wide-buffer
13381 (beginning-of-line)
13382 (and (org-looking-at-p org-planning-line-re)
13383 (eq (point)
13384 (ignore-errors
13385 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13386 (org-back-to-heading t)
13387 (org-with-limited-levels (org-back-to-heading t)))
13388 (line-beginning-position 2))))))
13390 (defun org-add-planning-info (what &optional time &rest remove)
13391 "Insert new timestamp with keyword in the planning line.
13392 WHAT indicates what kind of time stamp to add. It is a symbol
13393 among `closed', `deadline', `scheduled' and nil. TIME indicates
13394 the time to use. If none is given, the user is prompted for
13395 a date. REMOVE indicates what kind of entries to remove. An old
13396 WHAT entry will also be removed."
13397 (let (org-time-was-given org-end-time-was-given default-time default-input)
13398 (catch 'exit
13399 (when (and (memq what '(scheduled deadline))
13400 (or (not time)
13401 (and (stringp time)
13402 (string-match "^[-+]+[0-9]" time))))
13403 ;; Try to get a default date/time from existing timestamp
13404 (save-excursion
13405 (org-back-to-heading t)
13406 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13407 (when (re-search-forward (if (eq what 'scheduled)
13408 org-scheduled-time-regexp
13409 org-deadline-time-regexp)
13410 end t)
13411 (setq ts (match-string 1)
13412 default-time (apply 'encode-time (org-parse-time-string ts))
13413 default-input (and ts (org-get-compact-tod ts)))))))
13414 (when what
13415 (setq time
13416 (if (stringp time)
13417 ;; This is a string (relative or absolute), set
13418 ;; proper date.
13419 (apply #'encode-time
13420 (org-read-date-analyze
13421 time default-time (decode-time default-time)))
13422 ;; If necessary, get the time from the user
13423 (or time (org-read-date nil 'to-time nil nil
13424 default-time default-input)))))
13426 (org-with-wide-buffer
13427 (org-back-to-heading t)
13428 (forward-line)
13429 (unless (bolp) (insert "\n"))
13430 (cond ((org-looking-at-p org-planning-line-re)
13431 ;; Move to current indentation.
13432 (skip-chars-forward " \t")
13433 ;; Check if we have to remove something.
13434 (dolist (type (if what (cons what remove) remove))
13435 (save-excursion
13436 (when (re-search-forward
13437 (cl-case type
13438 (closed org-closed-time-regexp)
13439 (deadline org-deadline-time-regexp)
13440 (scheduled org-scheduled-time-regexp)
13441 (otherwise
13442 (error "Invalid planning type: %s" type)))
13443 (line-end-position) t)
13444 ;; Delete until next keyword or end of line.
13445 (delete-region
13446 (match-beginning 0)
13447 (if (re-search-forward org-keyword-time-not-clock-regexp
13448 (line-end-position)
13450 (match-beginning 0)
13451 (line-end-position))))))
13452 ;; If there is nothing more to add and no more keyword
13453 ;; is left, remove the line completely.
13454 (if (and (org-looking-at-p "[ \t]*$") (not what))
13455 (delete-region (line-beginning-position)
13456 (line-beginning-position 2))
13457 ;; If we removed last keyword, do not leave trailing
13458 ;; white space at the end of line.
13459 (let ((p (point)))
13460 (save-excursion
13461 (end-of-line)
13462 (unless (= (skip-chars-backward " \t" p) 0)
13463 (delete-region (point) (line-end-position)))))))
13464 ((not what) (throw 'exit nil)) ; Nothing to do.
13465 (t (insert-before-markers "\n")
13466 (backward-char 1)
13467 (when org-adapt-indentation
13468 (org-indent-to-column (1+ (org-outline-level))))))
13469 (when what
13470 ;; Insert planning keyword.
13471 (insert (cl-case what
13472 (closed org-closed-string)
13473 (deadline org-deadline-string)
13474 (scheduled org-scheduled-string)
13475 (otherwise (error "Invalid planning type: %s" what)))
13476 " ")
13477 ;; Insert associated timestamp.
13478 (let ((ts (org-insert-time-stamp
13479 time
13480 (or org-time-was-given
13481 (and (eq what 'closed) org-log-done-with-time))
13482 (eq what 'closed)
13483 nil nil (list org-end-time-was-given))))
13484 (unless (eolp) (insert " "))
13485 ts))))))
13487 (defvar org-log-note-marker (make-marker)
13488 "Marker pointing at the entry where the note is to be inserted.")
13489 (defvar org-log-note-purpose nil)
13490 (defvar org-log-note-state nil)
13491 (defvar org-log-note-previous-state nil)
13492 (defvar org-log-note-extra nil)
13493 (defvar org-log-note-window-configuration nil)
13494 (defvar org-log-note-return-to (make-marker))
13495 (defvar org-log-note-effective-time nil
13496 "Remembered current time so that dynamically scoped
13497 `org-extend-today-until' affects timestamps in state change log")
13499 (defvar org-log-post-message nil
13500 "Message to be displayed after a log note has been stored.
13501 The auto-repeater uses this.")
13503 (defun org-add-note ()
13504 "Add a note to the current entry.
13505 This is done in the same way as adding a state change note."
13506 (interactive)
13507 (org-add-log-setup 'note))
13509 (defun org-log-beginning (&optional create)
13510 "Return expected start of log notes in current entry.
13511 When optional argument CREATE is non-nil, the function creates
13512 a drawer to store notes, if necessary. Returned position ignores
13513 narrowing."
13514 (org-with-wide-buffer
13515 (let ((drawer (org-log-into-drawer)))
13516 (cond
13517 (drawer
13518 (org-end-of-meta-data)
13519 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13520 (end (if (org-at-heading-p) (point)
13521 (save-excursion (outline-next-heading) (point))))
13522 (case-fold-search t))
13523 (catch 'exit
13524 ;; Try to find existing drawer.
13525 (while (re-search-forward regexp end t)
13526 (let ((element (org-element-at-point)))
13527 (when (eq (org-element-type element) 'drawer)
13528 (let ((cend (org-element-property :contents-end element)))
13529 (when (and (not org-log-states-order-reversed) cend)
13530 (goto-char cend)))
13531 (throw 'exit nil))))
13532 ;; No drawer found. Create one, if permitted.
13533 (when create
13534 (unless (bolp) (insert "\n"))
13535 (let ((beg (point)))
13536 (insert ":" drawer ":\n:END:\n")
13537 (org-indent-region beg (point)))
13538 (end-of-line -1)))))
13540 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13541 (skip-chars-forward " \t\n")
13542 (beginning-of-line)
13543 (unless org-log-states-order-reversed
13544 (org-skip-over-state-notes)
13545 (skip-chars-backward " \t\n")
13546 (forward-line)))))
13547 (if (bolp) (point) (line-beginning-position 2))))
13549 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13550 "Set up the post command hook to take a note.
13551 If this is about to TODO state change, the new state is expected in STATE.
13552 HOW is an indicator what kind of note should be created.
13553 EXTRA is additional text that will be inserted into the notes buffer."
13554 (move-marker org-log-note-marker (point))
13555 (setq org-log-note-purpose purpose
13556 org-log-note-state state
13557 org-log-note-previous-state prev-state
13558 org-log-note-how how
13559 org-log-note-extra extra
13560 org-log-note-effective-time (org-current-effective-time))
13561 (add-hook 'post-command-hook 'org-add-log-note 'append))
13563 (defun org-skip-over-state-notes ()
13564 "Skip past the list of State notes in an entry."
13565 (when (ignore-errors (goto-char (org-in-item-p)))
13566 (let* ((struct (org-list-struct))
13567 (prevs (org-list-prevs-alist struct))
13568 (regexp
13569 (concat "[ \t]*- +"
13570 (replace-regexp-in-string
13571 " +" " +"
13572 (org-replace-escapes
13573 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13574 `(("%d" . ,org-ts-regexp-inactive)
13575 ("%D" . ,org-ts-regexp)
13576 ("%s" . "\"\\S-+\"")
13577 ("%S" . "\"\\S-+\"")
13578 ("%t" . ,org-ts-regexp-inactive)
13579 ("%T" . ,org-ts-regexp)
13580 ("%u" . ".*?")
13581 ("%U" . ".*?")))))))
13582 (while (org-looking-at-p regexp)
13583 (goto-char (or (org-list-get-next-item (point) struct prevs)
13584 (org-list-get-item-end (point) struct)))))))
13586 (defun org-add-log-note (&optional _purpose)
13587 "Pop up a window for taking a note, and add this note later."
13588 (remove-hook 'post-command-hook 'org-add-log-note)
13589 (setq org-log-note-window-configuration (current-window-configuration))
13590 (delete-other-windows)
13591 (move-marker org-log-note-return-to (point))
13592 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13593 (goto-char org-log-note-marker)
13594 (org-switch-to-buffer-other-window "*Org Note*")
13595 (erase-buffer)
13596 (if (memq org-log-note-how '(time state))
13597 (let (current-prefix-arg) (org-store-log-note))
13598 (let ((org-inhibit-startup t)) (org-mode))
13599 (insert (format "# Insert note for %s.
13600 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13601 (cond
13602 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13603 ((eq org-log-note-purpose 'done) "closed todo item")
13604 ((eq org-log-note-purpose 'state)
13605 (format "state change from \"%s\" to \"%s\""
13606 (or org-log-note-previous-state "")
13607 (or org-log-note-state "")))
13608 ((eq org-log-note-purpose 'reschedule)
13609 "rescheduling")
13610 ((eq org-log-note-purpose 'delschedule)
13611 "no longer scheduled")
13612 ((eq org-log-note-purpose 'redeadline)
13613 "changing deadline")
13614 ((eq org-log-note-purpose 'deldeadline)
13615 "removing deadline")
13616 ((eq org-log-note-purpose 'refile)
13617 "refiling")
13618 ((eq org-log-note-purpose 'note)
13619 "this entry")
13620 (t (error "This should not happen")))))
13621 (when org-log-note-extra (insert org-log-note-extra))
13622 (setq-local org-finish-function 'org-store-log-note)
13623 (run-hooks 'org-log-buffer-setup-hook)))
13625 (defvar org-note-abort nil) ; dynamically scoped
13626 (defun org-store-log-note ()
13627 "Finish taking a log note, and insert it to where it belongs."
13628 (let ((txt (prog1 (buffer-string)
13629 (kill-buffer)))
13630 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13631 lines)
13632 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13633 (setq txt (replace-match "" t t txt)))
13634 (when (string-match "\\s-+\\'" txt)
13635 (setq txt (replace-match "" t t txt)))
13636 (setq lines (org-split-string txt "\n"))
13637 (when (org-string-nw-p note)
13638 (setq note
13639 (org-replace-escapes
13640 note
13641 (list (cons "%u" (user-login-name))
13642 (cons "%U" user-full-name)
13643 (cons "%t" (format-time-string
13644 (org-time-stamp-format 'long 'inactive)
13645 org-log-note-effective-time))
13646 (cons "%T" (format-time-string
13647 (org-time-stamp-format 'long nil)
13648 org-log-note-effective-time))
13649 (cons "%d" (format-time-string
13650 (org-time-stamp-format nil 'inactive)
13651 org-log-note-effective-time))
13652 (cons "%D" (format-time-string
13653 (org-time-stamp-format nil nil)
13654 org-log-note-effective-time))
13655 (cons "%s" (cond
13656 ((not org-log-note-state) "")
13657 ((org-string-match-p org-ts-regexp
13658 org-log-note-state)
13659 (format "\"[%s]\""
13660 (substring org-log-note-state 1 -1)))
13661 (t (format "\"%s\"" org-log-note-state))))
13662 (cons "%S"
13663 (cond
13664 ((not org-log-note-previous-state) "")
13665 ((org-string-match-p org-ts-regexp
13666 org-log-note-previous-state)
13667 (format "\"[%s]\""
13668 (substring
13669 org-log-note-previous-state 1 -1)))
13670 (t (format "\"%s\""
13671 org-log-note-previous-state)))))))
13672 (when lines (setq note (concat note " \\\\")))
13673 (push note lines))
13674 (when (and lines (not (or current-prefix-arg org-note-abort)))
13675 (with-current-buffer (marker-buffer org-log-note-marker)
13676 (org-with-wide-buffer
13677 ;; Find location for the new note.
13678 (goto-char org-log-note-marker)
13679 (set-marker org-log-note-marker nil)
13680 (goto-char (org-log-beginning t))
13681 ;; Make sure point is at the beginning of an empty line.
13682 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13683 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13684 ;; In an existing list, add a new item at the top level.
13685 ;; Otherwise, indent line like a regular one.
13686 (let ((itemp (org-in-item-p)))
13687 (if itemp
13688 (org-indent-line-to
13689 (let ((struct (save-excursion
13690 (goto-char itemp) (org-list-struct))))
13691 (org-list-get-ind (org-list-get-top-point struct) struct)))
13692 (org-indent-line)))
13693 (insert (org-list-bullet-string "-") (pop lines))
13694 (let ((ind (org-list-item-body-column (line-beginning-position))))
13695 (dolist (line lines)
13696 (insert "\n")
13697 (org-indent-line-to ind)
13698 (insert line)))
13699 (message "Note stored")
13700 (org-back-to-heading t)
13701 (org-cycle-hide-drawers 'children))
13702 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13703 ;; from within `org-add-log-note' because `buffer-undo-list'
13704 ;; is then modified outside of `org-with-remote-undo'.
13705 (when (eq this-command 'org-agenda-todo)
13706 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13707 ;; Don't add undo information when called from `org-agenda-todo'.
13708 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13709 (set-window-configuration org-log-note-window-configuration)
13710 (with-current-buffer (marker-buffer org-log-note-return-to)
13711 (goto-char org-log-note-return-to))
13712 (move-marker org-log-note-return-to nil)
13713 (when org-log-post-message (message "%s" org-log-post-message))))
13715 (defun org-remove-empty-drawer-at (pos)
13716 "Remove an empty drawer at position POS.
13717 POS may also be a marker."
13718 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13719 (org-with-wide-buffer
13720 (goto-char pos)
13721 (let ((drawer (org-element-at-point)))
13722 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13723 (not (org-element-property :contents-begin drawer)))
13724 (delete-region (org-element-property :begin drawer)
13725 (progn (goto-char (org-element-property :end drawer))
13726 (skip-chars-backward " \r\t\n")
13727 (forward-line)
13728 (point))))))))
13730 (defvar org-ts-type nil)
13731 (defun org-sparse-tree (&optional arg type)
13732 "Create a sparse tree, prompt for the details.
13733 This command can create sparse trees. You first need to select the type
13734 of match used to create the tree:
13736 t Show all TODO entries.
13737 T Show entries with a specific TODO keyword.
13738 m Show entries selected by a tags/property match.
13739 p Enter a property name and its value (both with completion on existing
13740 names/values) and show entries with that property.
13741 r Show entries matching a regular expression (`/' can be used as well).
13742 b Show deadlines and scheduled items before a date.
13743 a Show deadlines and scheduled items after a date.
13744 d Show deadlines due within `org-deadline-warning-days'.
13745 D Show deadlines and scheduled items between a date range."
13746 (interactive "P")
13747 (setq type (or type org-sparse-tree-default-date-type))
13748 (setq org-ts-type type)
13749 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13750 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13751 \[c]ycle through date types: %s"
13752 (cl-case type
13753 (all "all timestamps")
13754 (scheduled "only scheduled")
13755 (deadline "only deadline")
13756 (active "only active timestamps")
13757 (inactive "only inactive timestamps")
13758 (closed "with a closed time-stamp")
13759 (otherwise "scheduled/deadline")))
13760 (let ((answer (read-char-exclusive)))
13761 (cl-case answer
13763 (org-sparse-tree
13765 (cadr
13766 (memq type '(nil all scheduled deadline active inactive closed)))))
13767 (?d (call-interactively 'org-check-deadlines))
13768 (?b (call-interactively 'org-check-before-date))
13769 (?a (call-interactively 'org-check-after-date))
13770 (?D (call-interactively 'org-check-dates-range))
13771 (?t (call-interactively 'org-show-todo-tree))
13772 (?T (org-show-todo-tree '(4)))
13773 (?m (call-interactively 'org-match-sparse-tree))
13774 ((?p ?P)
13775 (let* ((kwd (completing-read
13776 "Property: " (mapcar #'list (org-buffer-property-keys))))
13777 (value (completing-read
13778 "Value: " (mapcar #'list (org-property-values kwd)))))
13779 (unless (string-match "\\`{.*}\\'" value)
13780 (setq value (concat "\"" value "\"")))
13781 (org-match-sparse-tree arg (concat kwd "=" value))))
13782 ((?r ?R ?/) (call-interactively 'org-occur))
13783 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13785 (defvar-local org-occur-highlights nil
13786 "List of overlays used for occur matches.")
13787 (defvar-local org-occur-parameters nil
13788 "Parameters of the active org-occur calls.
13789 This is a list, each call to org-occur pushes as cons cell,
13790 containing the regular expression and the callback, onto the list.
13791 The list can contain several entries if `org-occur' has been called
13792 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13793 will only contain one set of parameters. When the highlights are
13794 removed (for example with `C-c C-c', or with the next edit (depending
13795 on `org-remove-highlights-with-change'), this variable is emptied
13796 as well.")
13798 (defun org-occur (regexp &optional keep-previous callback)
13799 "Make a compact tree which shows all matches of REGEXP.
13800 The tree will show the lines where the regexp matches, and all higher
13801 headlines above the match. It will also show the heading after the match,
13802 to make sure editing the matching entry is easy.
13803 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13804 call to `org-occur' will be kept, to allow stacking of calls to this
13805 command.
13806 If CALLBACK is non-nil, it is a function which is called to confirm
13807 that the match should indeed be shown."
13808 (interactive "sRegexp: \nP")
13809 (when (equal regexp "")
13810 (user-error "Regexp cannot be empty"))
13811 (unless keep-previous
13812 (org-remove-occur-highlights nil nil t))
13813 (push (cons regexp callback) org-occur-parameters)
13814 (let ((cnt 0))
13815 (save-excursion
13816 (goto-char (point-min))
13817 (when (or (not keep-previous) ; do not want to keep
13818 (not org-occur-highlights)) ; no previous matches
13819 ;; hide everything
13820 (org-overview))
13821 (while (re-search-forward regexp nil t)
13822 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13823 (when (or (not callback)
13824 (save-match-data (funcall callback)))
13825 (setq cnt (1+ cnt))
13826 (when org-highlight-sparse-tree-matches
13827 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13828 (org-show-context 'occur-tree))))
13829 (when org-remove-highlights-with-change
13830 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13831 nil 'local))
13832 (unless org-sparse-tree-open-archived-trees
13833 (org-hide-archived-subtrees (point-min) (point-max)))
13834 (run-hooks 'org-occur-hook)
13835 (when (org-called-interactively-p 'interactive)
13836 (message "%d match(es) for regexp %s" cnt regexp))
13837 cnt))
13839 (defun org-occur-next-match (&optional n _reset)
13840 "Function for `next-error-function' to find sparse tree matches.
13841 N is the number of matches to move, when negative move backwards.
13842 This function always goes back to the starting point when no
13843 match is found."
13844 (let* ((limit (if (< n 0) (point-min) (point-max)))
13845 (search-func (if (< n 0)
13846 'previous-single-char-property-change
13847 'next-single-char-property-change))
13848 (n (abs n))
13849 (pos (point))
13851 (catch 'exit
13852 (while (setq p1 (funcall search-func (point) 'org-type))
13853 (when (equal p1 limit)
13854 (goto-char pos)
13855 (user-error "No more matches"))
13856 (when (equal (get-char-property p1 'org-type) 'org-occur)
13857 (setq n (1- n))
13858 (when (= n 0)
13859 (goto-char p1)
13860 (throw 'exit (point))))
13861 (goto-char p1))
13862 (goto-char p1)
13863 (user-error "No more matches"))))
13865 (defun org-show-context (&optional key)
13866 "Make sure point and context are visible.
13867 Optional argument KEY, when non-nil, is a symbol. See
13868 `org-show-context-detail' for allowed values and how much is to
13869 be shown."
13870 (org-show-set-visibility
13871 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13872 ((cdr (assq key org-show-context-detail)))
13873 (t (cdr (assq 'default org-show-context-detail))))))
13875 (defun org-show-set-visibility (detail)
13876 "Set visibility around point according to DETAIL.
13877 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13878 `tree', `canonical' or t. See `org-show-context-detail' for more
13879 information."
13880 (unless (org-before-first-heading-p)
13881 ;; Show current heading and possibly its entry, following headline
13882 ;; or all children.
13883 (if (and (org-at-heading-p) (not (eq detail 'local)))
13884 (org-flag-heading nil)
13885 (org-show-entry)
13886 (org-with-limited-levels
13887 (cl-case detail
13888 ((tree canonical t) (org-show-children))
13889 ((nil minimal ancestors))
13890 (t (save-excursion
13891 (outline-next-heading)
13892 (org-flag-heading nil))))))
13893 ;; Show all siblings.
13894 (when (eq detail 'lineage) (org-show-siblings))
13895 ;; Show ancestors, possibly with their children.
13896 (when (memq detail '(ancestors lineage tree canonical t))
13897 (save-excursion
13898 (while (org-up-heading-safe)
13899 (org-flag-heading nil)
13900 (when (memq detail '(canonical t)) (org-show-entry))
13901 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13903 (defvar org-reveal-start-hook nil
13904 "Hook run before revealing a location.")
13906 (defun org-reveal (&optional siblings)
13907 "Show current entry, hierarchy above it, and the following headline.
13909 This can be used to show a consistent set of context around
13910 locations exposed with `org-show-context'.
13912 With optional argument SIBLINGS, on each level of the hierarchy all
13913 siblings are shown. This repairs the tree structure to what it would
13914 look like when opened with hierarchical calls to `org-cycle'.
13916 With double optional argument \\[universal-argument] \\[universal-argument], \
13917 go to the parent and show the
13918 entire tree."
13919 (interactive "P")
13920 (run-hooks 'org-reveal-start-hook)
13921 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13922 ((equal siblings '(16))
13923 (save-excursion
13924 (when (org-up-heading-safe)
13925 (org-show-subtree)
13926 (run-hook-with-args 'org-cycle-hook 'subtree))))
13927 (t (org-show-set-visibility 'lineage))))
13929 (defun org-highlight-new-match (beg end)
13930 "Highlight from BEG to END and mark the highlight is an occur headline."
13931 (let ((ov (make-overlay beg end)))
13932 (overlay-put ov 'face 'secondary-selection)
13933 (overlay-put ov 'org-type 'org-occur)
13934 (push ov org-occur-highlights)))
13936 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13937 "Remove the occur highlights from the buffer.
13938 BEG and END are ignored. If NOREMOVE is nil, remove this function
13939 from the `before-change-functions' in the current buffer."
13940 (interactive)
13941 (unless org-inhibit-highlight-removal
13942 (mapc #'delete-overlay org-occur-highlights)
13943 (setq org-occur-highlights nil)
13944 (setq org-occur-parameters nil)
13945 (unless noremove
13946 (remove-hook 'before-change-functions
13947 'org-remove-occur-highlights 'local))))
13949 ;;;; Priorities
13951 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13952 "Regular expression matching the priority indicator.")
13954 (defvar org-remove-priority-next-time nil)
13956 (defun org-priority-up ()
13957 "Increase the priority of the current item."
13958 (interactive)
13959 (org-priority 'up))
13961 (defun org-priority-down ()
13962 "Decrease the priority of the current item."
13963 (interactive)
13964 (org-priority 'down))
13966 (defun org-priority (&optional action _show)
13967 "Change the priority of an item.
13968 ACTION can be `set', `up', `down', or a character."
13969 (interactive "P")
13970 (if (equal action '(4))
13971 (org-show-priority)
13972 (unless org-enable-priority-commands
13973 (user-error "Priority commands are disabled"))
13974 (setq action (or action 'set))
13975 (let (current new news have remove)
13976 (save-excursion
13977 (org-back-to-heading t)
13978 (when (looking-at org-priority-regexp)
13979 (setq current (string-to-char (match-string 2))
13980 have t))
13981 (cond
13982 ((eq action 'remove)
13983 (setq remove t new ?\ ))
13984 ((or (eq action 'set)
13985 (if (featurep 'xemacs) (characterp action) (integerp action)))
13986 (if (not (eq action 'set))
13987 (setq new action)
13988 (message "Priority %c-%c, SPC to remove: "
13989 org-highest-priority org-lowest-priority)
13990 (save-match-data
13991 (setq new (read-char-exclusive))))
13992 (when (and (= (upcase org-highest-priority) org-highest-priority)
13993 (= (upcase org-lowest-priority) org-lowest-priority))
13994 (setq new (upcase new)))
13995 (cond ((equal new ?\ ) (setq remove t))
13996 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13997 (user-error "Priority must be between `%c' and `%c'"
13998 org-highest-priority org-lowest-priority))))
13999 ((eq action 'up)
14000 (setq new (if have
14001 (1- current) ; normal cycling
14002 ;; last priority was empty
14003 (if (eq last-command this-command)
14004 org-lowest-priority ; wrap around empty to lowest
14005 ;; default
14006 (if org-priority-start-cycle-with-default
14007 org-default-priority
14008 (1- org-default-priority))))))
14009 ((eq action 'down)
14010 (setq new (if have
14011 (1+ current) ; normal cycling
14012 ;; last priority was empty
14013 (if (eq last-command this-command)
14014 org-highest-priority ; wrap around empty to highest
14015 ;; default
14016 (if org-priority-start-cycle-with-default
14017 org-default-priority
14018 (1+ org-default-priority))))))
14019 (t (user-error "Invalid action")))
14020 (when (or (< (upcase new) org-highest-priority)
14021 (> (upcase new) org-lowest-priority))
14022 (if (and (memq action '(up down))
14023 (not have) (not (eq last-command this-command)))
14024 ;; `new' is from default priority
14025 (error
14026 "The default can not be set, see `org-default-priority' why")
14027 ;; normal cycling: `new' is beyond highest/lowest priority
14028 ;; and is wrapped around to the empty priority
14029 (setq remove t)))
14030 (setq news (format "%c" new))
14031 (if have
14032 (if remove
14033 (replace-match "" t t nil 1)
14034 (replace-match news t t nil 2))
14035 (if remove
14036 (user-error "No priority cookie found in line")
14037 (let ((case-fold-search nil))
14038 (looking-at org-todo-line-regexp))
14039 (if (match-end 2)
14040 (progn
14041 (goto-char (match-end 2))
14042 (insert " [#" news "]"))
14043 (goto-char (match-beginning 3))
14044 (insert "[#" news "] "))))
14045 (org-set-tags nil 'align))
14046 (if remove
14047 (message "Priority removed")
14048 (message "Priority of current item set to %s" news)))))
14050 (defun org-show-priority ()
14051 "Show the priority of the current item.
14052 This priority is composed of the main priority given with the [#A] cookies,
14053 and by additional input from the age of a schedules or deadline entry."
14054 (interactive)
14055 (let ((pri (if (eq major-mode 'org-agenda-mode)
14056 (org-get-at-bol 'priority)
14057 (save-excursion
14058 (save-match-data
14059 (beginning-of-line)
14060 (and (looking-at org-heading-regexp)
14061 (org-get-priority (match-string 0))))))))
14062 (message "Priority is %d" (if pri pri -1000))))
14064 (defun org-get-priority (s)
14065 "Find priority cookie and return priority."
14066 (save-match-data
14067 (if (functionp org-get-priority-function)
14068 (funcall org-get-priority-function)
14069 (if (not (string-match org-priority-regexp s))
14070 (* 1000 (- org-lowest-priority org-default-priority))
14071 (* 1000 (- org-lowest-priority
14072 (string-to-char (match-string 2 s))))))))
14074 ;;;; Tags
14076 (defvar org-agenda-archives-mode)
14077 (defvar org-map-continue-from nil
14078 "Position from where mapping should continue.
14079 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14081 (defvar org-scanner-tags nil
14082 "The current tag list while the tags scanner is running.")
14084 (defvar org-trust-scanner-tags nil
14085 "Should `org-get-tags-at' use the tags for the scanner.
14086 This is for internal dynamical scoping only.
14087 When this is non-nil, the function `org-get-tags-at' will return the value
14088 of `org-scanner-tags' instead of building the list by itself. This
14089 can lead to large speed-ups when the tags scanner is used in a file with
14090 many entries, and when the list of tags is retrieved, for example to
14091 obtain a list of properties. Building the tags list for each entry in such
14092 a file becomes an N^2 operation - but with this variable set, it scales
14093 as N.")
14095 (defvar org--matcher-tags-todo-only nil)
14097 (defun org-scan-tags (action matcher todo-only &optional start-level)
14098 "Scan headline tags with inheritance and produce output ACTION.
14100 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14101 or `agenda' to produce an entry list for an agenda view. It can also be
14102 a Lisp form or a function that should be called at each matched headline, in
14103 this case the return value is a list of all return values from these calls.
14105 MATCHER is a function accepting three arguments, returning
14106 a non-nil value whenever a given set of tags qualifies a headline
14107 for inclusion. See `org-make-tags-matcher' for more information.
14108 As a special case, it can also be set to t (respectively nil) in
14109 order to match all (respectively none) headline.
14111 When TODO-ONLY is non-nil, only lines with a not-done TODO
14112 keyword are included in the output.
14114 START-LEVEL can be a string with asterisks, reducing the scope to
14115 headlines matching this string."
14116 (require 'org-agenda)
14117 (let* ((re (concat "^"
14118 (if start-level
14119 ;; Get the correct level to match
14120 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14121 org-outline-regexp)
14122 " *\\(\\<\\("
14123 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14124 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14125 (props (list 'face 'default
14126 'done-face 'org-agenda-done
14127 'undone-face 'default
14128 'mouse-face 'highlight
14129 'org-not-done-regexp org-not-done-regexp
14130 'org-todo-regexp org-todo-regexp
14131 'org-complex-heading-regexp org-complex-heading-regexp
14132 'help-echo
14133 (format "mouse-2 or RET jump to org file %s"
14134 (abbreviate-file-name
14135 (or (buffer-file-name (buffer-base-buffer))
14136 (buffer-name (buffer-base-buffer)))))))
14137 (org-map-continue-from nil)
14138 lspos tags tags-list
14139 (tags-alist (list (cons 0 org-file-tags)))
14140 (llast 0) rtn rtn1 level category i txt
14141 todo marker entry priority
14142 ts-date ts-date-type ts-date-pair)
14143 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14144 (setq action (list 'lambda nil action)))
14145 (save-excursion
14146 (goto-char (point-min))
14147 (when (eq action 'sparse-tree)
14148 (org-overview)
14149 (org-remove-occur-highlights))
14150 (while (let (case-fold-search)
14151 (re-search-forward re nil t))
14152 (setq org-map-continue-from nil)
14153 (catch :skip
14154 (setq todo
14155 ;; TODO: is the 1-2 difference a bug?
14156 (when (match-end 1) (org-match-string-no-properties 2))
14157 tags (when (match-end 4) (org-match-string-no-properties 4)))
14158 (goto-char (setq lspos (match-beginning 0)))
14159 (setq level (org-reduced-level (org-outline-level))
14160 category (org-get-category))
14161 (when (eq action 'agenda)
14162 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14163 ts-date (car ts-date-pair)
14164 ts-date-type (cdr ts-date-pair)))
14165 (setq i llast llast level)
14166 ;; remove tag lists from same and sublevels
14167 (while (>= i level)
14168 (when (setq entry (assoc i tags-alist))
14169 (setq tags-alist (delete entry tags-alist)))
14170 (setq i (1- i)))
14171 ;; add the next tags
14172 (when tags
14173 (setq tags (org-split-string tags ":")
14174 tags-alist
14175 (cons (cons level tags) tags-alist)))
14176 ;; compile tags for current headline
14177 (setq tags-list
14178 (if org-use-tag-inheritance
14179 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14180 tags)
14181 org-scanner-tags tags-list)
14182 (when org-use-tag-inheritance
14183 (setcdr (car tags-alist)
14184 (mapcar (lambda (x)
14185 (setq x (copy-sequence x))
14186 (org-add-prop-inherited x))
14187 (cdar tags-alist))))
14188 (when (and tags org-use-tag-inheritance
14189 (or (not (eq t org-use-tag-inheritance))
14190 org-tags-exclude-from-inheritance))
14191 ;; Selective inheritance, remove uninherited ones.
14192 (setcdr (car tags-alist)
14193 (org-remove-uninherited-tags (cdar tags-alist))))
14194 (when (and
14196 ;; eval matcher only when the todo condition is OK
14197 (and (or (not todo-only) (member todo org-not-done-keywords))
14198 (if (functionp matcher)
14199 (let ((case-fold-search t) (org-trust-scanner-tags t))
14200 (funcall matcher todo tags-list level))
14201 matcher))
14203 ;; Call the skipper, but return t if it does not
14204 ;; skip, so that the `and' form continues evaluating.
14205 (progn
14206 (unless (eq action 'sparse-tree) (org-agenda-skip))
14209 ;; Check if timestamps are deselecting this entry
14210 (or (not todo-only)
14211 (and (member todo org-not-done-keywords)
14212 (or (not org-agenda-tags-todo-honor-ignore-options)
14213 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14215 ;; select this headline
14216 (cond
14217 ((eq action 'sparse-tree)
14218 (and org-highlight-sparse-tree-matches
14219 (org-get-heading) (match-end 0)
14220 (org-highlight-new-match
14221 (match-beginning 1) (match-end 1)))
14222 (org-show-context 'tags-tree))
14223 ((eq action 'agenda)
14224 (setq txt (org-agenda-format-item
14226 (concat
14227 (if (eq org-tags-match-list-sublevels 'indented)
14228 (make-string (1- level) ?.) "")
14229 (org-get-heading))
14230 (make-string level ?\s)
14231 category
14232 tags-list)
14233 priority (org-get-priority txt))
14234 (goto-char lspos)
14235 (setq marker (org-agenda-new-marker))
14236 (org-add-props txt props
14237 'org-marker marker 'org-hd-marker marker 'org-category category
14238 'todo-state todo
14239 'ts-date ts-date
14240 'priority priority
14241 'type (concat "tagsmatch" ts-date-type))
14242 (push txt rtn))
14243 ((functionp action)
14244 (setq org-map-continue-from nil)
14245 (save-excursion
14246 (setq rtn1 (funcall action))
14247 (push rtn1 rtn)))
14248 (t (user-error "Invalid action")))
14250 ;; if we are to skip sublevels, jump to end of subtree
14251 (unless org-tags-match-list-sublevels
14252 (org-end-of-subtree t)
14253 (backward-char 1))))
14254 ;; Get the correct position from where to continue
14255 (if org-map-continue-from
14256 (goto-char org-map-continue-from)
14257 (and (= (point) lspos) (end-of-line 1)))))
14258 (when (and (eq action 'sparse-tree)
14259 (not org-sparse-tree-open-archived-trees))
14260 (org-hide-archived-subtrees (point-min) (point-max)))
14261 (nreverse rtn)))
14263 (defun org-remove-uninherited-tags (tags)
14264 "Remove all tags that are not inherited from the list TAGS."
14265 (cond
14266 ((eq org-use-tag-inheritance t)
14267 (if org-tags-exclude-from-inheritance
14268 (org-delete-all org-tags-exclude-from-inheritance tags)
14269 tags))
14270 ((not org-use-tag-inheritance) nil)
14271 ((stringp org-use-tag-inheritance)
14272 (delq nil (mapcar
14273 (lambda (x)
14274 (if (and (string-match org-use-tag-inheritance x)
14275 (not (member x org-tags-exclude-from-inheritance)))
14276 x nil))
14277 tags)))
14278 ((listp org-use-tag-inheritance)
14279 (delq nil (mapcar
14280 (lambda (x)
14281 (if (member x org-use-tag-inheritance) x nil))
14282 tags)))))
14284 (defun org-match-sparse-tree (&optional todo-only match)
14285 "Create a sparse tree according to tags string MATCH.
14286 MATCH can contain positive and negative selection of tags, like
14287 \"+WORK+URGENT-WITHBOSS\".
14288 If optional argument TODO-ONLY is non-nil, only select lines that are
14289 also TODO lines."
14290 (interactive "P")
14291 (org-agenda-prepare-buffers (list (current-buffer)))
14292 (let ((org--matcher-tags-todo-only todo-only))
14293 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14294 org--matcher-tags-todo-only)))
14296 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14298 (defvar org-cached-props nil)
14299 (defun org-cached-entry-get (pom property)
14300 (if (or (eq t org-use-property-inheritance)
14301 (and (stringp org-use-property-inheritance)
14302 (let ((case-fold-search t))
14303 (org-string-match-p org-use-property-inheritance property)))
14304 (and (listp org-use-property-inheritance)
14305 (member-ignore-case property org-use-property-inheritance)))
14306 ;; Caching is not possible, check it directly.
14307 (org-entry-get pom property 'inherit)
14308 ;; Get all properties, so we can do complicated checks easily.
14309 (cdr (assoc-string property
14310 (or org-cached-props
14311 (setq org-cached-props (org-entry-properties pom)))
14312 t))))
14314 (defun org-global-tags-completion-table (&optional files)
14315 "Return the list of all tags in all agenda buffer/files.
14316 Optional FILES argument is a list of files which can be used
14317 instead of the agenda files."
14318 (save-excursion
14319 (org-uniquify
14320 (delq nil
14321 (apply 'append
14322 (mapcar
14323 (lambda (file)
14324 (set-buffer (find-file-noselect file))
14325 (append (org-get-buffer-tags)
14326 (mapcar (lambda (x) (if (stringp (car-safe x))
14327 (list (car-safe x)) nil))
14328 org-tag-alist)))
14329 (if (and files (car files))
14330 files
14331 (org-agenda-files))))))))
14333 (defun org-make-tags-matcher (match)
14334 "Create the TAGS/TODO matcher form for the selection string MATCH.
14336 Returns a cons of the selection string MATCH and a function
14337 implementing the matcher.
14339 The matcher is to be called at an Org entry, with point on the
14340 headline, and returns non-nil if the entry matches the selection
14341 string MATCH. It must be called with three arguments: the TODO
14342 keyword at the entry (or nil if none), the list of all tags at
14343 the entry including inherited ones and the reduced level of the
14344 headline. Additionally, the category of the entry, if any, must
14345 be specified as the text property `org-category' on the headline.
14347 This function sets the variable `org--matcher-tags-todo-only' to
14348 a non-nil value if the matcher restricts matching to TODO
14349 entries, otherwise it is not touched.
14351 See also `org-scan-tags'."
14352 (unless match
14353 ;; Get a new match request, with completion against the global
14354 ;; tags table and the local tags in current buffer.
14355 (let ((org-last-tags-completion-table
14356 (org-uniquify
14357 (delq nil (append (org-get-buffer-tags)
14358 (org-global-tags-completion-table))))))
14359 (setq match
14360 (completing-read
14361 "Match: "
14362 'org-tags-completion-function nil nil nil 'org-tags-history))))
14364 (let ((match0 match)
14365 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14366 (start 0)
14367 tagsmatch todomatch tagsmatcher todomatcher)
14369 ;; Expand group tags.
14370 (setq match (org-tags-expand match))
14372 ;; Check if there is a TODO part of this match, which would be the
14373 ;; part after a "/". To make sure that this slash is not part of
14374 ;; a property value to be matched against, we also check that
14375 ;; there is no / after that slash. First, find the last slash.
14376 (let ((s 0))
14377 (while (string-match "/+" match s)
14378 (setq start (match-beginning 0))
14379 (setq s (match-end 0))))
14380 (if (and (string-match "/+" match start)
14381 (not (string-match-p "\"" match start)))
14382 ;; Match contains also a TODO-matching request.
14383 (progn
14384 (setq tagsmatch (substring match 0 (match-beginning 0)))
14385 (setq todomatch (substring match (match-end 0)))
14386 (when (string-match "\\`!" todomatch)
14387 (setq org--matcher-tags-todo-only t)
14388 (setq todomatch (substring todomatch 1)))
14389 (when (string-match "\\`\\s-*\\'" todomatch)
14390 (setq todomatch nil)))
14391 ;; Only matching tags.
14392 (setq tagsmatch match)
14393 (setq todomatch nil))
14395 ;; Make the tags matcher.
14396 (when (org-string-nw-p tagsmatch)
14397 (let ((orlist nil)
14398 (orterms (org-split-string tagsmatch "|"))
14399 term)
14400 (while (setq term (pop orterms))
14401 (while (and (equal (substring term -1) "\\") orterms)
14402 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14403 (while (string-match re term)
14404 (let* ((rest (substring term (match-end 0)))
14405 (minus (and (match-end 1)
14406 (equal (match-string 1 term) "-")))
14407 (tag (save-match-data
14408 (replace-regexp-in-string
14409 "\\\\-" "-" (match-string 2 term))))
14410 (regexp (eq (string-to-char tag) ?{))
14411 (levelp (match-end 4))
14412 (propp (match-end 5))
14414 (cond
14415 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14416 (levelp
14417 `(,(org-op-to-function (match-string 3 term))
14418 level
14419 ,(string-to-number (match-string 4 term))))
14420 (propp
14421 (let* ((gv (pcase (upcase (match-string 5 term))
14422 ("CATEGORY"
14423 '(get-text-property (point) 'org-category))
14424 ("TODO" 'todo)
14425 (p `(org-cached-entry-get nil ,p))))
14426 (pv (match-string 7 term))
14427 (regexp (eq (string-to-char pv) ?{))
14428 (strp (eq (string-to-char pv) ?\"))
14429 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14430 (po (org-op-to-function (match-string 6 term)
14431 (if timep 'time strp))))
14432 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14433 (when timep (setq pv (org-matcher-time pv)))
14434 (cond ((and regexp (eq po 'org<>))
14435 `(not (string-match ,pv (or ,gv ""))))
14436 (regexp `(string-match ,pv (or ,gv "")))
14437 (strp `(,po (or ,gv "") ,pv))
14439 `(,po
14440 (string-to-number (or ,gv ""))
14441 ,(string-to-number pv))))))
14442 (t `(member ,tag tags-list)))))
14443 (push (if minus `(not ,mm) mm) tagsmatcher)
14444 (setq term rest)))
14445 (push `(and ,@tagsmatcher) orlist)
14446 (setq tagsmatcher nil))
14447 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14449 ;; Make the TODO matcher.
14450 (when (org-string-nw-p todomatch)
14451 (let ((orlist nil))
14452 (dolist (term (org-split-string todomatch "|"))
14453 (while (string-match re term)
14454 (let* ((minus (and (match-end 1)
14455 (equal (match-string 1 term) "-")))
14456 (kwd (match-string 2 term))
14457 (regexp (eq (string-to-char kwd) ?{))
14458 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14459 `(equal todo ,kwd))))
14460 (push (if minus `(not ,mm) mm) todomatcher))
14461 (setq term (substring term (match-end 0))))
14462 (push (if (> (length todomatcher) 1)
14463 (cons 'and todomatcher)
14464 (car todomatcher))
14465 orlist)
14466 (setq todomatcher nil))
14467 (setq todomatcher (cons 'or orlist))))
14469 ;; Return the string and function of the matcher. If no
14470 ;; tags-specific or todo-specific matcher exists, match
14471 ;; everything.
14472 (let ((matcher (if (and tagsmatcher todomatcher)
14473 `(and ,tagsmatcher ,todomatcher)
14474 (or tagsmatcher todomatcher t))))
14475 (when org--matcher-tags-todo-only
14476 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14477 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14479 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14480 "Expand group tags in MATCH.
14482 This replaces every group tag in MATCH with a regexp tag search.
14483 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14484 will be replaced like this:
14486 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14487 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14488 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14490 Replacing by a regexp preserves the structure of the match.
14491 E.g., this expansion
14493 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14495 will match anything tagged with \"Lab\" and \"Home\", or tagged
14496 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14498 A group tag in MATCH can contain regular expressions of its own.
14499 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14500 will be replaced like this:
14502 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14504 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14505 assumed to be a single group tag, and the function will return
14506 the list of tags in this group.
14508 When DOWNCASE is non-nil, expand downcased TAGS."
14509 (if org-group-tags
14510 (let* ((case-fold-search t)
14511 (stable org-mode-syntax-table)
14512 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14513 (taggroups (if downcased
14514 (mapcar (lambda (tg) (mapcar #'downcase tg))
14515 taggroups)
14516 taggroups))
14517 (taggroups-keys (mapcar #'car taggroups))
14518 (return-match (if downcased (downcase match) match))
14519 (count 0)
14520 (work-already-expanded tags-already-expanded)
14521 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14522 ;; @ and _ are allowed as word-components in tags.
14523 (modify-syntax-entry ?@ "w" stable)
14524 (modify-syntax-entry ?_ "w" stable)
14525 ;; Temporarily replace regexp-expressions in the match-expression.
14526 (while (string-match "{.+?}" return-match)
14527 (cl-incf count)
14528 (push (match-string 0 return-match) regexps-in-match)
14529 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14530 (while (and taggroups-keys
14531 (with-syntax-table stable
14532 (string-match
14533 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14534 (regexp-opt taggroups-keys) "\\>\\)")
14535 return-match)))
14536 (let* ((dir (match-string 1 return-match))
14537 (tag (match-string 2 return-match))
14538 (tag (if downcased (downcase tag) tag)))
14539 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14540 (member tag work-already-expanded))
14541 (setq tags-in-group (assoc tag taggroups))
14542 (push tag work-already-expanded)
14543 ;; Recursively expand each tag in the group, if the tag hasn't
14544 ;; already been expanded. Restore the match-data after all recursive calls.
14545 (save-match-data
14546 (let (tags-expanded)
14547 (dolist (x (cdr tags-in-group))
14548 (if (and (member x taggroups-keys)
14549 (not (member x work-already-expanded)))
14550 (setq tags-expanded
14551 (delete-dups
14552 (append
14553 (org-tags-expand x t downcased
14554 work-already-expanded)
14555 tags-expanded)))
14556 (setq tags-expanded
14557 (append (list x) tags-expanded)))
14558 (setq work-already-expanded
14559 (delete-dups
14560 (append tags-expanded
14561 work-already-expanded))))
14562 (setq tags-in-group
14563 (delete-dups (cons (car tags-in-group)
14564 tags-expanded)))))
14565 ;; Filter tag-regexps from tags.
14566 (setq regexp-in-group-escaped
14567 (delq nil (mapcar (lambda (x)
14568 (if (stringp x)
14569 (and (equal "{" (substring x 0 1))
14570 (equal "}" (substring x -1))
14573 tags-in-group))
14574 regexp-in-group
14575 (mapcar (lambda (x)
14576 (substring x 1 -1))
14577 regexp-in-group-escaped)
14578 tags-in-group
14579 (delq nil (mapcar (lambda (x)
14580 (if (stringp x)
14581 (and (not (equal "{" (substring x 0 1)))
14582 (not (equal "}" (substring x -1)))
14585 tags-in-group)))
14586 ;; If single-as-list, do no more in the while-loop.
14587 (if (not single-as-list)
14588 (progn
14589 (when regexp-in-group
14590 (setq regexp-in-group
14591 (concat "\\|"
14592 (mapconcat 'identity regexp-in-group
14593 "\\|"))))
14594 (setq tags-in-group
14595 (concat dir
14596 "{\\<"
14597 (regexp-opt tags-in-group)
14598 "\\>"
14599 regexp-in-group
14600 "}"))
14601 (when (stringp tags-in-group)
14602 (org-add-props tags-in-group '(grouptag t)))
14603 (setq return-match
14604 (replace-match tags-in-group t t return-match)))
14605 (setq tags-in-group
14606 (append regexp-in-group-escaped tags-in-group))))
14607 (setq taggroups-keys (delete tag taggroups-keys))))
14608 ;; Add the regular expressions back into the match-expression again.
14609 (while regexps-in-match
14610 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14611 (pop regexps-in-match)
14612 return-match t t))
14613 (cl-decf count))
14614 (if single-as-list
14615 (if tags-in-group tags-in-group (list return-match))
14616 return-match))
14617 (if single-as-list
14618 (list (if downcased (downcase match) match))
14619 match)))
14621 (defun org-op-to-function (op &optional stringp)
14622 "Turn an operator into the appropriate function."
14623 (setq op
14624 (cond
14625 ((equal op "<" ) '(< string< org-time<))
14626 ((equal op ">" ) '(> org-string> org-time>))
14627 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14628 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14629 ((member op '("=" "==")) '(= string= org-time=))
14630 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14631 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14633 (defun org<> (a b) (not (= a b)))
14634 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14635 (defun org-string>= (a b) (not (string< a b)))
14636 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14637 (defun org-string<> (a b) (not (string= a b)))
14638 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14639 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14640 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14641 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14642 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14643 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14644 (defun org-2ft (s)
14645 "Convert S to a floating point time.
14646 If S is already a number, just return it. If it is a string, parse
14647 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14648 (cond
14649 ((numberp s) s)
14650 ((stringp s)
14651 (condition-case nil
14652 (float-time (apply 'encode-time (org-parse-time-string s)))
14653 (error 0.)))
14654 (t 0.)))
14656 (defun org-time-today ()
14657 "Time in seconds today at 0:00.
14658 Returns the float number of seconds since the beginning of the
14659 epoch to the beginning of today (00:00)."
14660 (float-time (apply 'encode-time
14661 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14663 (defun org-matcher-time (s)
14664 "Interpret a time comparison value."
14665 (save-match-data
14666 (cond
14667 ((string= s "<now>") (float-time))
14668 ((string= s "<today>") (org-time-today))
14669 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14670 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14671 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14672 (+ (org-time-today)
14673 (* (string-to-number (match-string 1 s))
14674 (cdr (assoc (match-string 2 s)
14675 '(("d" . 86400.0) ("w" . 604800.0)
14676 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14677 (t (org-2ft s)))))
14679 (defun org-match-any-p (re list)
14680 "Does re match any element of list?"
14681 (setq list (mapcar (lambda (x) (string-match re x)) list))
14682 (delq nil list))
14684 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14685 (defvar org-tags-overlay (make-overlay 1 1))
14686 (org-detach-overlay org-tags-overlay)
14688 (defun org-get-local-tags-at (&optional pos)
14689 "Get a list of tags defined in the current headline."
14690 (org-get-tags-at pos 'local))
14692 (defun org-get-local-tags ()
14693 "Get a list of tags defined in the current headline."
14694 (org-get-tags-at nil 'local))
14696 (defun org-get-tags-at (&optional pos local)
14697 "Get a list of all headline tags applicable at POS.
14698 POS defaults to point. If tags are inherited, the list contains
14699 the targets in the same sequence as the headlines appear, i.e.
14700 the tags of the current headline come last.
14701 When LOCAL is non-nil, only return tags from the current headline,
14702 ignore inherited ones."
14703 (interactive)
14704 (if (and org-trust-scanner-tags
14705 (or (not pos) (equal pos (point)))
14706 (not local))
14707 org-scanner-tags
14708 (let (tags ltags lastpos parent)
14709 (save-excursion
14710 (save-restriction
14711 (widen)
14712 (goto-char (or pos (point)))
14713 (save-match-data
14714 (catch 'done
14715 (condition-case nil
14716 (progn
14717 (org-back-to-heading t)
14718 (while (not (equal lastpos (point)))
14719 (setq lastpos (point))
14720 (when (looking-at
14721 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14722 (setq ltags (org-split-string
14723 (org-match-string-no-properties 1) ":"))
14724 (when parent
14725 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14726 (setq tags (append
14727 (if parent
14728 (org-remove-uninherited-tags ltags)
14729 ltags)
14730 tags)))
14731 (or org-use-tag-inheritance (throw 'done t))
14732 (when local (throw 'done t))
14733 (or (org-up-heading-safe) (error nil))
14734 (setq parent t)))
14735 (error nil)))))
14736 (if local
14737 tags
14738 (reverse (delete-dups
14739 (reverse (append
14740 (org-remove-uninherited-tags
14741 org-file-tags)
14742 tags)))))))))
14744 (defun org-add-prop-inherited (s)
14745 (add-text-properties 0 (length s) '(inherited t) s)
14748 (defun org-toggle-tag (tag &optional onoff)
14749 "Toggle the tag TAG for the current line.
14750 If ONOFF is `on' or `off', don't toggle but set to this state."
14751 (let (res current)
14752 (save-excursion
14753 (org-back-to-heading t)
14754 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14755 (point-at-eol) t)
14756 (progn
14757 (setq current (match-string 1))
14758 (replace-match ""))
14759 (setq current ""))
14760 (setq current (nreverse (org-split-string current ":")))
14761 (cond
14762 ((eq onoff 'on)
14763 (setq res t)
14764 (or (member tag current) (push tag current)))
14765 ((eq onoff 'off)
14766 (or (not (member tag current)) (setq current (delete tag current))))
14767 (t (if (member tag current)
14768 (setq current (delete tag current))
14769 (setq res t)
14770 (push tag current))))
14771 (end-of-line 1)
14772 (if current
14773 (progn
14774 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14775 (org-set-tags nil t))
14776 (delete-horizontal-space))
14777 (run-hooks 'org-after-tags-change-hook))
14778 res))
14780 (defun org-align-tags-here (to-col)
14781 ;; Assumes that this is a headline
14782 "Align tags on the current headline to TO-COL."
14783 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14784 (beginning-of-line 1)
14785 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14786 (< pos (match-beginning 2)))
14787 (progn
14788 (setq tags-l (- (match-end 2) (match-beginning 2)))
14789 (goto-char (match-beginning 1))
14790 (insert " ")
14791 (delete-region (point) (1+ (match-beginning 2)))
14792 (setq ncol (max (current-column)
14793 (1+ col)
14794 (if (> to-col 0)
14795 to-col
14796 (- (abs to-col) tags-l))))
14797 (setq p (point))
14798 (insert (make-string (- ncol (current-column)) ?\ ))
14799 (setq ncol (current-column))
14800 (when indent-tabs-mode (tabify p (point-at-eol)))
14801 (org-move-to-column (min ncol col)))
14802 (goto-char pos))))
14804 (defun org-set-tags-command (&optional arg just-align)
14805 "Call the set-tags command for the current entry."
14806 (interactive "P")
14807 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14808 (org-set-tags arg just-align)
14809 (save-excursion
14810 (unless (and (org-region-active-p)
14811 org-loop-over-headlines-in-active-region)
14812 (org-back-to-heading t))
14813 (org-set-tags arg just-align))))
14815 (defun org-set-tags-to (data)
14816 "Set the tags of the current entry to DATA, replacing the current tags.
14817 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14818 If DATA is nil or the empty string, any tags will be removed."
14819 (interactive "sTags: ")
14820 (setq data
14821 (cond
14822 ((eq data nil) "")
14823 ((equal data "") "")
14824 ((stringp data)
14825 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14826 ":"))
14827 ((listp data)
14828 (concat ":" (mapconcat 'identity data ":") ":"))))
14829 (when data
14830 (save-excursion
14831 (org-back-to-heading t)
14832 (when (looking-at org-complex-heading-regexp)
14833 (if (match-end 5)
14834 (progn
14835 (goto-char (match-beginning 5))
14836 (insert data)
14837 (delete-region (point) (point-at-eol))
14838 (org-set-tags nil 'align))
14839 (goto-char (point-at-eol))
14840 (insert " " data)
14841 (org-set-tags nil 'align)))
14842 (beginning-of-line 1)
14843 (when (looking-at ".*?\\([ \t]+\\)$")
14844 (delete-region (match-beginning 1) (match-end 1))))))
14846 (defun org-align-all-tags ()
14847 "Align the tags i all headings."
14848 (interactive)
14849 (save-excursion
14850 (or (ignore-errors (org-back-to-heading t))
14851 (outline-next-heading))
14852 (if (org-at-heading-p)
14853 (org-set-tags t)
14854 (message "No headings"))))
14856 (defvar org-indent-indentation-per-level)
14857 (defun org-set-tags (&optional arg just-align)
14858 "Set the tags for the current headline.
14859 With prefix ARG, realign all tags in headings in the current buffer.
14860 When JUST-ALIGN is non-nil, only align tags."
14861 (interactive "P")
14862 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14863 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14864 'region-start-level
14865 'region))
14866 org-loop-over-headlines-in-active-region)
14867 (org-map-entries
14868 ;; We don't use ARG and JUST-ALIGN here because these args
14869 ;; are not useful when looping over headlines.
14870 #'org-set-tags
14871 org-loop-over-headlines-in-active-region
14873 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14874 (let ((org-setting-tags t))
14875 (if arg
14876 (save-excursion
14877 (goto-char (point-min))
14878 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14879 (while (re-search-forward org-outline-regexp-bol nil t)
14880 (org-set-tags nil t)
14881 (end-of-line)))
14882 (message "All tags realigned to column %d" org-tags-column))
14883 (let* ((current (org-get-tags-string))
14884 (col (current-column))
14885 (tags
14886 (if just-align current
14887 ;; Get a new set of tags from the user.
14888 (save-excursion
14889 (let* ((table
14890 (setq
14891 org-last-tags-completion-table
14892 (append
14893 org-tag-persistent-alist
14894 (or org-tag-alist (org-get-buffer-tags))
14895 (and
14896 org-complete-tags-always-offer-all-agenda-tags
14897 (org-global-tags-completion-table
14898 (org-agenda-files))))))
14899 (current-tags (org-split-string current ":"))
14900 (inherited-tags
14901 (nreverse (nthcdr (length current-tags)
14902 (nreverse (org-get-tags-at))))))
14903 (replace-regexp-in-string
14904 "\\([-+&]+\\|,\\)"
14906 (if (or (eq t org-use-fast-tag-selection)
14907 (and org-use-fast-tag-selection
14908 (delq nil (mapcar #'cdr table))))
14909 (org-fast-tag-selection
14910 current-tags inherited-tags table
14911 (and org-fast-tag-selection-include-todo
14912 org-todo-key-alist))
14913 (let ((org-add-colon-after-tag-completion
14914 (< 1 (length table))))
14915 (org-trim
14916 (completing-read
14917 "Tags: "
14918 #'org-tags-completion-function
14919 nil nil current 'org-tags-history))))))))))
14921 (when org-tags-sort-function
14922 (setq tags
14923 (mapconcat
14924 #'identity
14925 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14926 org-tags-sort-function)
14927 ":")))
14929 (if (not (org-string-nw-p tags)) (setq tags "")
14930 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14931 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14933 ;; Insert new tags at the correct column
14934 (beginning-of-line)
14935 (let ((level (if (looking-at org-outline-regexp)
14936 (- (match-end 0) (point) 1)
14937 1)))
14938 (cond
14939 ((and (equal current "") (equal tags "")))
14940 ((re-search-forward
14941 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14942 (line-end-position)
14944 (if (equal tags "") (replace-match "" t t)
14945 (goto-char (match-beginning 0))
14946 (let* ((c0 (current-column))
14947 ;; Compute offset for the case of org-indent-mode
14948 ;; active.
14949 (di (if (org-bound-and-true-p org-indent-mode)
14950 (* (1- org-indent-indentation-per-level)
14951 (1- level))
14953 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14954 (tc (+ org-tags-column
14955 (if (> org-tags-column 0) (- di) di)))
14956 (c1 (max (1+ c0)
14957 (if (> tc 0) tc
14958 (- (- tc) (string-width tags)))))
14959 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14960 (replace-match rpl t t)
14961 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14962 (tabify p0 (point))))))
14963 (t (error "Tags alignment failed"))))
14964 (org-move-to-column col))
14965 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14967 (defun org-change-tag-in-region (beg end tag off)
14968 "Add or remove TAG for each entry in the region.
14969 This works in the agenda, and also in an org-mode buffer."
14970 (interactive
14971 (list (region-beginning) (region-end)
14972 (let ((org-last-tags-completion-table
14973 (if (derived-mode-p 'org-mode)
14974 (org-uniquify
14975 (delq nil (append (org-get-buffer-tags)
14976 (org-global-tags-completion-table))))
14977 (org-global-tags-completion-table))))
14978 (completing-read
14979 "Tag: " 'org-tags-completion-function nil nil nil
14980 'org-tags-history))
14981 (progn
14982 (message "[s]et or [r]emove? ")
14983 (equal (read-char-exclusive) ?r))))
14984 (when (fboundp 'deactivate-mark) (deactivate-mark))
14985 (let ((agendap (equal major-mode 'org-agenda-mode))
14986 l1 l2 m buf pos newhead (cnt 0))
14987 (goto-char end)
14988 (setq l2 (1- (org-current-line)))
14989 (goto-char beg)
14990 (setq l1 (org-current-line))
14991 (cl-loop for l from l1 to l2 do
14992 (org-goto-line l)
14993 (setq m (get-text-property (point) 'org-hd-marker))
14994 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14995 (and agendap m))
14996 (setq buf (if agendap (marker-buffer m) (current-buffer))
14997 pos (if agendap m (point)))
14998 (with-current-buffer buf
14999 (save-excursion
15000 (save-restriction
15001 (goto-char pos)
15002 (setq cnt (1+ cnt))
15003 (org-toggle-tag tag (if off 'off 'on))
15004 (setq newhead (org-get-heading)))))
15005 (and agendap (org-agenda-change-all-lines newhead m))))
15006 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15008 (defun org-tags-completion-function (string _predicate &optional flag)
15009 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15010 (confirm (lambda (x) (stringp (car x)))))
15011 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15012 (setq s1 (match-string 1 string)
15013 s2 (match-string 2 string))
15014 (setq s1 "" s2 string))
15015 (cond
15016 ((eq flag nil)
15017 ;; try completion
15018 (setq rtn (try-completion s2 ctable confirm))
15019 (when (stringp rtn)
15020 (setq rtn
15021 (concat s1 s2 (substring rtn (length s2))
15022 (if (and org-add-colon-after-tag-completion
15023 (assoc rtn ctable))
15024 ":" ""))))
15025 rtn)
15026 ((eq flag t)
15027 ;; all-completions
15028 (all-completions s2 ctable confirm))
15029 ((eq flag 'lambda)
15030 ;; exact match?
15031 (assoc s2 ctable)))))
15033 (defun org-fast-tag-insert (kwd tags face &optional end)
15034 "Insert KDW, and the TAGS, the latter with face FACE.
15035 Also insert END."
15036 (insert (format "%-12s" (concat kwd ":"))
15037 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15038 (or end "")))
15040 (defun org-fast-tag-show-exit (flag)
15041 (save-excursion
15042 (org-goto-line 3)
15043 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15044 (replace-match ""))
15045 (when flag
15046 (end-of-line 1)
15047 (org-move-to-column (- (window-width) 19) t)
15048 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15050 (defun org-set-current-tags-overlay (current prefix)
15051 "Add an overlay to CURRENT tag with PREFIX."
15052 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15053 (if (featurep 'xemacs)
15054 (org-overlay-display org-tags-overlay (concat prefix s)
15055 'secondary-selection)
15056 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15057 (org-overlay-display org-tags-overlay (concat prefix s)))))
15059 (defvar org-last-tag-selection-key nil)
15060 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15061 "Fast tag selection with single keys.
15062 CURRENT is the current list of tags in the headline, INHERITED is the
15063 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15064 possibly with grouping information. TODO-TABLE is a similar table with
15065 TODO keywords, should these have keys assigned to them.
15066 If the keys are nil, a-z are automatically assigned.
15067 Returns the new tags string, or nil to not change the current settings."
15068 (let* ((fulltable (append table todo-table))
15069 (maxlen (apply 'max (mapcar
15070 (lambda (x)
15071 (if (stringp (car x)) (string-width (car x)) 0))
15072 fulltable)))
15073 (buf (current-buffer))
15074 (expert (eq org-fast-tag-selection-single-key 'expert))
15075 (buffer-tags nil)
15076 (fwidth (+ maxlen 3 1 3))
15077 (ncol (/ (- (window-width) 4) fwidth))
15078 (i-face 'org-done)
15079 (c-face 'org-todo)
15080 tg cnt e c char c1 c2 ntable tbl rtn
15081 ov-start ov-end ov-prefix
15082 (exit-after-next org-fast-tag-selection-single-key)
15083 (done-keywords org-done-keywords)
15084 groups ingroup intaggroup)
15085 (save-excursion
15086 (beginning-of-line 1)
15087 (if (looking-at
15088 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15089 (setq ov-start (match-beginning 1)
15090 ov-end (match-end 1)
15091 ov-prefix "")
15092 (setq ov-start (1- (point-at-eol))
15093 ov-end (1+ ov-start))
15094 (skip-chars-forward "^\n\r")
15095 (setq ov-prefix
15096 (concat
15097 (buffer-substring (1- (point)) (point))
15098 (if (> (current-column) org-tags-column)
15100 (make-string (- org-tags-column (current-column)) ?\ ))))))
15101 (move-overlay org-tags-overlay ov-start ov-end)
15102 (save-window-excursion
15103 (if expert
15104 (set-buffer (get-buffer-create " *Org tags*"))
15105 (delete-other-windows)
15106 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15107 (org-switch-to-buffer-other-window " *Org tags*"))
15108 (erase-buffer)
15109 (setq-local org-done-keywords done-keywords)
15110 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15111 (org-fast-tag-insert "Current" current c-face "\n\n")
15112 (org-fast-tag-show-exit exit-after-next)
15113 (org-set-current-tags-overlay current ov-prefix)
15114 (setq tbl fulltable char ?a cnt 0)
15115 (while (setq e (pop tbl))
15116 (cond
15117 ((eq (car e) :startgroup)
15118 (push '() groups) (setq ingroup t)
15119 (unless (zerop cnt)
15120 (setq cnt 0)
15121 (insert "\n"))
15122 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15123 ((eq (car e) :endgroup)
15124 (setq ingroup nil cnt 0)
15125 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15126 ((eq (car e) :startgrouptag)
15127 (setq intaggroup t)
15128 (unless (zerop cnt)
15129 (setq cnt 0)
15130 (insert "\n"))
15131 (insert "[ "))
15132 ((eq (car e) :endgrouptag)
15133 (setq intaggroup nil cnt 0)
15134 (insert "]\n"))
15135 ((equal e '(:newline))
15136 (unless (zerop cnt)
15137 (setq cnt 0)
15138 (insert "\n")
15139 (setq e (car tbl))
15140 (while (equal (car tbl) '(:newline))
15141 (insert "\n")
15142 (setq tbl (cdr tbl)))))
15143 ((equal e '(:grouptags)) (insert " : "))
15145 (setq tg (copy-sequence (car e)) c2 nil)
15146 (if (cdr e)
15147 (setq c (cdr e))
15148 ;; automatically assign a character.
15149 (setq c1 (string-to-char
15150 (downcase (substring
15151 tg (if (= (string-to-char tg) ?@) 1 0)))))
15152 (if (or (rassoc c1 ntable) (rassoc c1 table))
15153 (while (or (rassoc char ntable) (rassoc char table))
15154 (setq char (1+ char)))
15155 (setq c2 c1))
15156 (setq c (or c2 char)))
15157 (when ingroup (push tg (car groups)))
15158 (setq tg (org-add-props tg nil 'face
15159 (cond
15160 ((not (assoc tg table))
15161 (org-get-todo-face tg))
15162 ((member tg current) c-face)
15163 ((member tg inherited) i-face))))
15164 (when (equal (caar tbl) :grouptags)
15165 (org-add-props tg nil 'face 'org-tag-group))
15166 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15167 (insert "[" c "] " tg (make-string
15168 (- fwidth 4 (length tg)) ?\ ))
15169 (push (cons tg c) ntable)
15170 (when (= (cl-incf cnt) ncol)
15171 (insert "\n")
15172 (when (or ingroup intaggroup) (insert " "))
15173 (setq cnt 0)))))
15174 (setq ntable (nreverse ntable))
15175 (insert "\n")
15176 (goto-char (point-min))
15177 (unless expert (org-fit-window-to-buffer))
15178 (setq rtn
15179 (catch 'exit
15180 (while t
15181 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15182 (if (not groups) "no " "")
15183 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15184 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15185 (setq org-last-tag-selection-key c)
15186 (cond
15187 ((= c ?\r) (throw 'exit t))
15188 ((= c ?!)
15189 (setq groups (not groups))
15190 (goto-char (point-min))
15191 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15192 ((= c ?\C-c)
15193 (if (not expert)
15194 (org-fast-tag-show-exit
15195 (setq exit-after-next (not exit-after-next)))
15196 (setq expert nil)
15197 (delete-other-windows)
15198 (set-window-buffer (split-window-vertically) " *Org tags*")
15199 (org-switch-to-buffer-other-window " *Org tags*")
15200 (org-fit-window-to-buffer)))
15201 ((or (= c ?\C-g)
15202 (and (= c ?q) (not (rassoc c ntable))))
15203 (org-detach-overlay org-tags-overlay)
15204 (setq quit-flag t))
15205 ((= c ?\ )
15206 (setq current nil)
15207 (when exit-after-next (setq exit-after-next 'now)))
15208 ((= c ?\t)
15209 (condition-case nil
15210 (setq tg (completing-read
15211 "Tag: "
15212 (or buffer-tags
15213 (with-current-buffer buf
15214 (setq buffer-tags
15215 (org-get-buffer-tags))))))
15216 (quit (setq tg "")))
15217 (when (string-match "\\S-" tg)
15218 (cl-pushnew (list tg) buffer-tags :test #'equal)
15219 (if (member tg current)
15220 (setq current (delete tg current))
15221 (push tg current)))
15222 (when exit-after-next (setq exit-after-next 'now)))
15223 ((setq e (rassoc c todo-table) tg (car e))
15224 (with-current-buffer buf
15225 (save-excursion (org-todo tg)))
15226 (when exit-after-next (setq exit-after-next 'now)))
15227 ((setq e (rassoc c ntable) tg (car e))
15228 (if (member tg current)
15229 (setq current (delete tg current))
15230 (cl-loop for g in groups do
15231 (when (member tg g)
15232 (dolist (x g) (setq current (delete x current)))))
15233 (push tg current))
15234 (when exit-after-next (setq exit-after-next 'now))))
15236 ;; Create a sorted list
15237 (setq current
15238 (sort current
15239 (lambda (a b)
15240 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15241 (when (eq exit-after-next 'now) (throw 'exit t))
15242 (goto-char (point-min))
15243 (beginning-of-line 2)
15244 (delete-region (point) (point-at-eol))
15245 (org-fast-tag-insert "Current" current c-face)
15246 (org-set-current-tags-overlay current ov-prefix)
15247 (while (re-search-forward
15248 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15249 (setq tg (match-string 1))
15250 (add-text-properties
15251 (match-beginning 1) (match-end 1)
15252 (list 'face
15253 (cond
15254 ((member tg current) c-face)
15255 ((member tg inherited) i-face)
15256 (t (get-text-property (match-beginning 1) 'face))))))
15257 (goto-char (point-min)))))
15258 (org-detach-overlay org-tags-overlay)
15259 (if rtn
15260 (mapconcat 'identity current ":")
15261 nil))))
15263 (defun org-get-tags-string ()
15264 "Get the TAGS string in the current headline."
15265 (unless (org-at-heading-p t)
15266 (user-error "Not on a heading"))
15267 (save-excursion
15268 (beginning-of-line 1)
15269 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15270 (org-match-string-no-properties 1)
15271 "")))
15273 (defun org-get-tags ()
15274 "Get the list of tags specified in the current headline."
15275 (org-split-string (org-get-tags-string) ":"))
15277 (defun org-get-buffer-tags ()
15278 "Get a table of all tags used in the buffer, for completion."
15279 (org-with-wide-buffer
15280 (goto-char (point-min))
15281 (let ((tag-re (concat org-outline-regexp-bol
15282 "\\(?:.*?[ \t]\\)?"
15283 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15284 tags)
15285 (while (re-search-forward tag-re nil t)
15286 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15287 (push tag tags)))
15288 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15290 ;;;; The mapping API
15292 (defvar org-agenda-skip-comment-trees)
15293 (defvar org-agenda-skip-function)
15294 (defun org-map-entries (func &optional match scope &rest skip)
15295 "Call FUNC at each headline selected by MATCH in SCOPE.
15297 FUNC is a function or a lisp form. The function will be called without
15298 arguments, with the cursor positioned at the beginning of the headline.
15299 The return values of all calls to the function will be collected and
15300 returned as a list.
15302 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15303 does not need to preserve point. After evaluation, the cursor will be
15304 moved to the end of the line (presumably of the headline of the
15305 processed entry) and search continues from there. Under some
15306 circumstances, this may not produce the wanted results. For example,
15307 if you have removed (e.g. archived) the current (sub)tree it could
15308 mean that the next entry will be skipped entirely. In such cases, you
15309 can specify the position from where search should continue by making
15310 FUNC set the variable `org-map-continue-from' to the desired buffer
15311 position.
15313 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15314 Only headlines that are matched by this query will be considered during
15315 the iteration. When MATCH is nil or t, all headlines will be
15316 visited by the iteration.
15318 SCOPE determines the scope of this command. It can be any of:
15320 nil The current buffer, respecting the restriction if any
15321 tree The subtree started with the entry at point
15322 region The entries within the active region, if any
15323 region-start-level
15324 The entries within the active region, but only those at
15325 the same level than the first one.
15326 file The current buffer, without restriction
15327 file-with-archives
15328 The current buffer, and any archives associated with it
15329 agenda All agenda files
15330 agenda-with-archives
15331 All agenda files with any archive files associated with them
15332 \(file1 file2 ...)
15333 If this is a list, all files in the list will be scanned
15335 The remaining args are treated as settings for the skipping facilities of
15336 the scanner. The following items can be given here:
15338 archive skip trees with the archive tag
15339 comment skip trees with the COMMENT keyword
15340 function or Emacs Lisp form:
15341 will be used as value for `org-agenda-skip-function', so
15342 whenever the function returns a position, FUNC will not be
15343 called for that entry and search will continue from the
15344 position returned
15346 If your function needs to retrieve the tags including inherited tags
15347 at the *current* entry, you can use the value of the variable
15348 `org-scanner-tags' which will be much faster than getting the value
15349 with `org-get-tags-at'. If your function gets properties with
15350 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15351 to t around the call to `org-entry-properties' to get the same speedup.
15352 Note that if your function moves around to retrieve tags and properties at
15353 a *different* entry, you cannot use these techniques."
15354 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15355 (not (org-region-active-p)))
15356 (let* ((org-agenda-archives-mode nil) ; just to make sure
15357 (org-agenda-skip-archived-trees (memq 'archive skip))
15358 (org-agenda-skip-comment-trees (memq 'comment skip))
15359 (org-agenda-skip-function
15360 (car (org-delete-all '(comment archive) skip)))
15361 (org-tags-match-list-sublevels t)
15362 (start-level (eq scope 'region-start-level))
15363 matcher res
15364 org-todo-keywords-for-agenda
15365 org-done-keywords-for-agenda
15366 org-todo-keyword-alist-for-agenda
15367 org-tag-alist-for-agenda
15368 org--matcher-tags-todo-only)
15370 (cond
15371 ((eq match t) (setq matcher t))
15372 ((eq match nil) (setq matcher t))
15373 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15375 (save-excursion
15376 (save-restriction
15377 (cond ((eq scope 'tree)
15378 (org-back-to-heading t)
15379 (org-narrow-to-subtree)
15380 (setq scope nil))
15381 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15382 (org-region-active-p))
15383 ;; If needed, set start-level to a string like "2"
15384 (when start-level
15385 (save-excursion
15386 (goto-char (region-beginning))
15387 (unless (org-at-heading-p) (outline-next-heading))
15388 (setq start-level (org-current-level))))
15389 (narrow-to-region (region-beginning)
15390 (save-excursion
15391 (goto-char (region-end))
15392 (unless (and (bolp) (org-at-heading-p))
15393 (outline-next-heading))
15394 (point)))
15395 (setq scope nil)))
15397 (if (not scope)
15398 (progn
15399 (org-agenda-prepare-buffers
15400 (and buffer-file-name (list buffer-file-name)))
15401 (setq res
15402 (org-scan-tags
15403 func matcher org--matcher-tags-todo-only start-level)))
15404 ;; Get the right scope
15405 (cond
15406 ((and scope (listp scope) (symbolp (car scope)))
15407 (setq scope (eval scope)))
15408 ((eq scope 'agenda)
15409 (setq scope (org-agenda-files t)))
15410 ((eq scope 'agenda-with-archives)
15411 (setq scope (org-agenda-files t))
15412 (setq scope (org-add-archive-files scope)))
15413 ((eq scope 'file)
15414 (setq scope (and buffer-file-name (list buffer-file-name))))
15415 ((eq scope 'file-with-archives)
15416 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15417 (org-agenda-prepare-buffers scope)
15418 (dolist (file scope)
15419 (with-current-buffer (org-find-base-buffer-visiting file)
15420 (save-excursion
15421 (save-restriction
15422 (widen)
15423 (goto-char (point-min))
15424 (setq res
15425 (append
15427 (org-scan-tags
15428 func matcher org--matcher-tags-todo-only))))))))))
15429 res)))
15431 ;;; Properties API
15433 (defconst org-special-properties
15434 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15435 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15436 "The special properties valid in Org mode.
15437 These are properties that are not defined in the property drawer,
15438 but in some other way.")
15440 (defconst org-default-properties
15441 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15442 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15443 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15444 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15445 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15446 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15447 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15448 "Some properties that are used by Org mode for various purposes.
15449 Being in this list makes sure that they are offered for completion.")
15451 (defun org--valid-property-p (property)
15452 "Non nil when string PROPERTY is a valid property name."
15453 (not
15454 (or (equal property "")
15455 (org-string-match-p "\\s-" property))))
15457 (defun org--update-property-plist (key val props)
15458 "Associate KEY to VAL in alist PROPS.
15459 Modifications are made by side-effect. Return new alist."
15460 (let* ((appending (string= (substring key -1) "+"))
15461 (key (if appending (substring key 0 -1) key))
15462 (old (assoc-string key props t)))
15463 (if (not old) (cons (cons key val) props)
15464 (setcdr old (if appending (concat (cdr old) " " val) val))
15465 props)))
15467 (defun org-get-property-block (&optional beg force)
15468 "Return the (beg . end) range of the body of the property drawer.
15469 BEG is the beginning of the current subtree, or of the part
15470 before the first headline. If it is not given, it will be found.
15471 If the drawer does not exist, create it if FORCE is non-nil, or
15472 return nil."
15473 (org-with-wide-buffer
15474 (when beg (goto-char beg))
15475 (unless (org-before-first-heading-p)
15476 (let ((beg (cond (beg)
15477 ((or (not (featurep 'org-inlinetask))
15478 (org-inlinetask-in-task-p))
15479 (org-back-to-heading t))
15480 (t (org-with-limited-levels (org-back-to-heading t))))))
15481 (forward-line)
15482 (when (org-looking-at-p org-planning-line-re) (forward-line))
15483 (cond ((looking-at org-property-drawer-re)
15484 (forward-line)
15485 (cons (point) (progn (goto-char (match-end 0))
15486 (line-beginning-position))))
15487 (force
15488 (goto-char beg)
15489 (org-insert-property-drawer)
15490 (let ((pos (save-excursion (search-forward ":END:")
15491 (line-beginning-position))))
15492 (cons pos pos))))))))
15494 (defun org-at-property-p ()
15495 "Non-nil when point is inside a property drawer.
15496 See `org-property-re' for match data, if applicable."
15497 (save-excursion
15498 (beginning-of-line)
15499 (and (looking-at org-property-re)
15500 (let ((property-drawer (save-match-data (org-get-property-block))))
15501 (and property-drawer
15502 (>= (point) (car property-drawer))
15503 (< (point) (cdr property-drawer)))))))
15505 (defun org-property-action ()
15506 "Do an action on properties."
15507 (interactive)
15508 (unless (org-at-property-p) (user-error "Not at a property"))
15509 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15510 (let ((c (read-char-exclusive)))
15511 (cl-case c
15512 (?s (call-interactively #'org-set-property))
15513 (?d (call-interactively #'org-delete-property))
15514 (?D (call-interactively #'org-delete-property-globally))
15515 (?c (call-interactively #'org-compute-property-at-point))
15516 (otherwise (user-error "No such property action %c" c)))))
15518 (defun org-inc-effort ()
15519 "Increment the value of the effort property in the current entry."
15520 (interactive)
15521 (org-set-effort nil t))
15523 (defvar org-clock-effort) ; Defined in org-clock.el.
15524 (defvar org-clock-current-task) ; Defined in org-clock.el.
15525 (defun org-set-effort (&optional value increment)
15526 "Set the effort property of the current entry.
15527 With numerical prefix arg, use the nth allowed value, 0 stands for the
15528 10th allowed value.
15530 When INCREMENT is non-nil, set the property to the next allowed value."
15531 (interactive "P")
15532 (when (equal value 0) (setq value 10))
15533 (let* ((completion-ignore-case t)
15534 (prop org-effort-property)
15535 (cur (org-entry-get nil prop))
15536 (allowed (org-property-get-allowed-values nil prop 'table))
15537 (existing (mapcar 'list (org-property-values prop)))
15538 (heading (nth 4 (org-heading-components)))
15540 (val (cond
15541 ((stringp value) value)
15542 ((and allowed (integerp value))
15543 (or (car (nth (1- value) allowed))
15544 (car (org-last allowed))))
15545 ((and allowed increment)
15546 (or (cl-caadr (member (list cur) allowed))
15547 (user-error "Allowed effort values are not set")))
15548 (allowed
15549 (message "Select 1-9,0, [RET%s]: %s"
15550 (if cur (concat "=" cur) "")
15551 (mapconcat 'car allowed " "))
15552 (setq rpl (read-char-exclusive))
15553 (if (equal rpl ?\r)
15555 (setq rpl (- rpl ?0))
15556 (when (equal rpl 0) (setq rpl 10))
15557 (if (and (> rpl 0) (<= rpl (length allowed)))
15558 (car (nth (1- rpl) allowed))
15559 (org-completing-read "Effort: " allowed nil))))
15561 (org-completing-read
15562 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15563 (concat "[" cur "]") "")
15564 ": ")
15565 existing nil nil "" nil cur)))))
15566 (unless (equal (org-entry-get nil prop) val)
15567 (org-entry-put nil prop val))
15568 (org-refresh-property
15569 '((effort . identity)
15570 (effort-minutes . org-duration-string-to-minutes))
15571 val)
15572 (when (string= heading org-clock-current-task)
15573 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15574 (org-clock-update-mode-line))
15575 (message "%s is now %s" prop val)))
15577 (defun org-entry-properties (&optional pom which)
15578 "Get all properties of the current entry.
15580 When POM is a buffer position, get all properties from the entry
15581 there instead.
15583 This includes the TODO keyword, the tags, time strings for
15584 deadline, scheduled, and clocking, and any additional properties
15585 defined in the entry.
15587 If WHICH is nil or `all', get all properties. If WHICH is
15588 `special' or `standard', only get that subclass. If WHICH is
15589 a string, only get that property.
15591 Return value is an alist. Keys are properties, as upcased
15592 strings."
15593 (org-with-point-at pom
15594 (when (and (derived-mode-p 'org-mode)
15595 (ignore-errors (org-back-to-heading t)))
15596 (catch 'exit
15597 (let* ((beg (point))
15598 (specific (and (stringp which) (upcase which)))
15599 (which (cond ((not specific) which)
15600 ((member specific org-special-properties) 'special)
15601 (t 'standard)))
15602 props)
15603 ;; Get the special properties, like TODO and TAGS.
15604 (when (memq which '(nil all special))
15605 (when (or (not specific) (string= specific "CLOCKSUM"))
15606 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15607 (when clocksum
15608 (push (cons "CLOCKSUM"
15609 (org-columns-number-to-string
15610 (/ (float clocksum) 60.) 'add_times))
15611 props)))
15612 (when specific (throw 'exit props)))
15613 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15614 (let ((clocksumt (get-text-property (point)
15615 :org-clock-minutes-today)))
15616 (when clocksumt
15617 (push (cons "CLOCKSUM_T"
15618 (org-columns-number-to-string
15619 (/ (float clocksumt) 60.) 'add_times))
15620 props)))
15621 (when specific (throw 'exit props)))
15622 (when (or (not specific) (string= specific "ITEM"))
15623 (when (looking-at org-complex-heading-regexp)
15624 (push (cons "ITEM"
15625 (let ((title (match-string-no-properties 4)))
15626 (if (org-string-nw-p title)
15627 (org-remove-tabs title)
15628 "")))
15629 props))
15630 (when specific (throw 'exit props)))
15631 (when (or (not specific) (string= specific "TODO"))
15632 (let ((case-fold-search nil))
15633 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15634 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15635 (when specific (throw 'exit props)))
15636 (when (or (not specific) (string= specific "PRIORITY"))
15637 (push (cons "PRIORITY"
15638 (if (looking-at org-priority-regexp)
15639 (org-match-string-no-properties 2)
15640 (char-to-string org-default-priority)))
15641 props)
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific) (string= specific "FILE"))
15644 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15645 props)
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "TAGS"))
15648 (let ((value (org-string-nw-p (org-get-tags-string))))
15649 (when value (push (cons "TAGS" value) props)))
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "ALLTAGS"))
15652 (let ((value (org-get-tags-at)))
15653 (when value
15654 (push (cons "ALLTAGS"
15655 (format ":%s:" (mapconcat #'identity value ":")))
15656 props)))
15657 (when specific (throw 'exit props)))
15658 (when (or (not specific) (string= specific "BLOCKED"))
15659 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15660 (when specific (throw 'exit props)))
15661 (when (or (not specific)
15662 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15663 (forward-line)
15664 (when (org-looking-at-p org-planning-line-re)
15665 (end-of-line)
15666 (let ((bol (line-beginning-position))
15667 ;; Backward compatibility: time keywords used to
15668 ;; be configurable (before 8.3). Make sure we
15669 ;; get the correct keyword.
15670 (key-assoc `(("CLOSED" . ,org-closed-string)
15671 ("DEADLINE" . ,org-deadline-string)
15672 ("SCHEDULED" . ,org-scheduled-string))))
15673 (dolist (pair (if specific (list (assoc specific key-assoc))
15674 key-assoc))
15675 (save-excursion
15676 (when (search-backward (cdr pair) bol t)
15677 (goto-char (match-end 0))
15678 (skip-chars-forward " \t")
15679 (and (looking-at org-ts-regexp-both)
15680 (push (cons (car pair)
15681 (org-match-string-no-properties 0))
15682 props)))))))
15683 (when specific (throw 'exit props)))
15684 (when (or (not specific)
15685 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15686 (let ((find-ts
15687 (lambda (end ts)
15688 ;; Fix next time-stamp before END. TS is the
15689 ;; list of time-stamps found so far.
15690 (let ((ts ts)
15691 (regexp (cond
15692 ((string= specific "TIMESTAMP")
15693 org-ts-regexp)
15694 ((string= specific "TIMESTAMP_IA")
15695 org-ts-regexp-inactive)
15696 ((assoc "TIMESTAMP_IA" ts)
15697 org-ts-regexp)
15698 ((assoc "TIMESTAMP" ts)
15699 org-ts-regexp-inactive)
15700 (t org-ts-regexp-both))))
15701 (catch 'next
15702 (while (re-search-forward regexp end t)
15703 (backward-char)
15704 (let ((object (org-element-context)))
15705 ;; Accept to match timestamps in node
15706 ;; properties, too.
15707 (when (memq (org-element-type object)
15708 '(node-property timestamp))
15709 (let ((type
15710 (org-element-property :type object)))
15711 (cond
15712 ((and (memq type '(active active-range))
15713 (not (equal specific "TIMESTAMP_IA")))
15714 (unless (assoc "TIMESTAMP" ts)
15715 (push (cons "TIMESTAMP"
15716 (org-element-property
15717 :raw-value object))
15719 (when specific (throw 'exit ts))))
15720 ((and (memq type '(inactive inactive-range))
15721 (not (string= specific "TIMESTAMP")))
15722 (unless (assoc "TIMESTAMP_IA" ts)
15723 (push (cons "TIMESTAMP_IA"
15724 (org-element-property
15725 :raw-value object))
15727 (when specific (throw 'exit ts))))))
15728 ;; Both timestamp types are found,
15729 ;; move to next part.
15730 (when (= (length ts) 2) (throw 'next ts)))))
15731 ts)))))
15732 (goto-char beg)
15733 ;; First look for timestamps within headline.
15734 (let ((ts (funcall find-ts (line-end-position) nil)))
15735 (if (= (length ts) 2) (setq props (nconc ts props))
15736 (forward-line)
15737 ;; Then find timestamps in the section, skipping
15738 ;; planning line.
15739 (when (org-looking-at-p org-planning-line-re)
15740 (forward-line))
15741 (let ((end (save-excursion (outline-next-heading))))
15742 (setq props (nconc (funcall find-ts end ts) props))))))))
15743 ;; Get the standard properties, like :PROP:.
15744 (when (memq which '(nil all standard))
15745 ;; If we are looking after a specific property, delegate
15746 ;; to `org-entry-get', which is faster. However, make an
15747 ;; exception for "CATEGORY", since it can be also set
15748 ;; through keywords (i.e. #+CATEGORY).
15749 (if (and specific (not (equal specific "CATEGORY")))
15750 (let ((value (org-entry-get beg specific nil t)))
15751 (throw 'exit (and value (list (cons specific value)))))
15752 (let ((range (org-get-property-block beg)))
15753 (when range
15754 (let ((end (cdr range)) seen-base)
15755 (goto-char (car range))
15756 ;; Unlike to `org--update-property-plist', we
15757 ;; handle the case where base values is found
15758 ;; after its extension. We also forbid standard
15759 ;; properties to be named as special properties.
15760 (while (re-search-forward org-property-re end t)
15761 (let* ((key (upcase (org-match-string-no-properties 2)))
15762 (extendp (org-string-match-p "\\+\\'" key))
15763 (key-base (if extendp (substring key 0 -1) key))
15764 (value (org-match-string-no-properties 3)))
15765 (cond
15766 ((member-ignore-case key-base org-special-properties))
15767 (extendp
15768 (setq props
15769 (org--update-property-plist key value props)))
15770 ((member key seen-base))
15771 (t (push key seen-base)
15772 (let ((p (assoc-string key props t)))
15773 (if p (setcdr p (concat value " " (cdr p)))
15774 (push (cons key value) props))))))))))))
15775 (unless (assoc "CATEGORY" props)
15776 (push (cons "CATEGORY" (org-get-category beg)) props)
15777 (when (string= specific "CATEGORY") (throw 'exit props)))
15778 ;; Return value.
15779 props)))))
15781 (defun org-property--local-values (property literal-nil)
15782 "Return value for PROPERTY in current entry.
15783 Value is a list whose care is the base value for PROPERTY and cdr
15784 a list of accumulated values. Return nil if neither is found in
15785 the entry. Also return nil when PROPERTY is set to \"nil\",
15786 unless LITERAL-NIL is non-nil."
15787 (let ((range (org-get-property-block)))
15788 (when range
15789 (goto-char (car range))
15790 (let* ((case-fold-search t)
15791 (end (cdr range))
15792 (value
15793 ;; Base value.
15794 (save-excursion
15795 (let ((v (and (re-search-forward
15796 (org-re-property property nil t) end t)
15797 (org-match-string-no-properties 3))))
15798 (list (if literal-nil v (org-not-nil v)))))))
15799 ;; Find additional values.
15800 (let* ((property+ (org-re-property (concat property "+") nil t)))
15801 (while (re-search-forward property+ end t)
15802 (push (org-match-string-no-properties 3) value)))
15803 ;; Return final values.
15804 (and (not (equal value '(nil))) (nreverse value))))))
15806 (defun org-entry-get (pom property &optional inherit literal-nil)
15807 "Get value of PROPERTY for entry or content at point-or-marker POM.
15809 If INHERIT is non-nil and the entry does not have the property,
15810 then also check higher levels of the hierarchy. If INHERIT is
15811 the symbol `selective', use inheritance only if the setting in
15812 `org-use-property-inheritance' selects PROPERTY for inheritance.
15814 If the property is present but empty, the return value is the
15815 empty string. If the property is not present at all, nil is
15816 returned. In any other case, return the value as a string.
15817 Search is case-insensitive.
15819 If LITERAL-NIL is set, return the string value \"nil\" as
15820 a string, do not interpret it as the list atom nil. This is used
15821 for inheritance when a \"nil\" value can supersede a non-nil
15822 value higher up the hierarchy."
15823 (org-with-point-at pom
15824 (cond
15825 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15826 ;; We need a special property. Use `org-entry-properties' to
15827 ;; retrieve it, but specify the wanted property.
15828 (cdr (assoc-string property (org-entry-properties nil property))))
15829 ((and inherit
15830 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15831 (org-entry-get-with-inheritance property literal-nil))
15833 (let* ((local (org-property--local-values property literal-nil))
15834 (value (and local (mapconcat #'identity (delq nil local) " "))))
15835 (if literal-nil value (org-not-nil value)))))))
15837 (defun org-property-or-variable-value (var &optional inherit)
15838 "Check if there is a property fixing the value of VAR.
15839 If yes, return this value. If not, return the current value of the variable."
15840 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15841 (if (and prop (stringp prop) (string-match "\\S-" prop))
15842 (read prop)
15843 (symbol-value var))))
15845 (defun org-entry-delete (pom property)
15846 "Delete PROPERTY from entry at point-or-marker POM.
15847 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15848 non-nil when a property was removed."
15849 (unless (member property org-special-properties)
15850 (org-with-point-at pom
15851 (let ((range (org-get-property-block)))
15852 (when range
15853 (let* ((begin (car range))
15854 (origin (cdr range))
15855 (end (copy-marker origin))
15856 (re (org-re-property
15857 (concat (regexp-quote property) "\\+?") t t)))
15858 (goto-char begin)
15859 (while (re-search-forward re end t)
15860 (delete-region (match-beginning 0) (line-beginning-position 2)))
15861 ;; If drawer is empty, remove it altogether.
15862 (when (= begin end)
15863 (delete-region (line-beginning-position 0)
15864 (line-beginning-position 2)))
15865 ;; Return non-nil if some property was removed.
15866 (prog1 (/= end origin) (set-marker end nil))))))))
15868 ;; Multi-values properties are properties that contain multiple values
15869 ;; These values are assumed to be single words, separated by whitespace.
15870 (defun org-entry-add-to-multivalued-property (pom property value)
15871 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15872 (let* ((old (org-entry-get pom property))
15873 (values (and old (org-split-string old "[ \t]"))))
15874 (setq value (org-entry-protect-space value))
15875 (unless (member value values)
15876 (setq values (append values (list value)))
15877 (org-entry-put pom property
15878 (mapconcat 'identity values " ")))))
15880 (defun org-entry-remove-from-multivalued-property (pom property value)
15881 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15882 (let* ((old (org-entry-get pom property))
15883 (values (and old (org-split-string old "[ \t]"))))
15884 (setq value (org-entry-protect-space value))
15885 (when (member value values)
15886 (setq values (delete value values))
15887 (org-entry-put pom property
15888 (mapconcat 'identity values " ")))))
15890 (defun org-entry-member-in-multivalued-property (pom property value)
15891 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15892 (let* ((old (org-entry-get pom property))
15893 (values (and old (org-split-string old "[ \t]"))))
15894 (setq value (org-entry-protect-space value))
15895 (member value values)))
15897 (defun org-entry-get-multivalued-property (pom property)
15898 "Return a list of values in a multivalued property."
15899 (let* ((value (org-entry-get pom property))
15900 (values (and value (org-split-string value "[ \t]"))))
15901 (mapcar 'org-entry-restore-space values)))
15903 (defun org-entry-put-multivalued-property (pom property &rest values)
15904 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15905 VALUES should be a list of strings. Spaces will be protected."
15906 (org-entry-put pom property
15907 (mapconcat 'org-entry-protect-space values " "))
15908 (let* ((value (org-entry-get pom property))
15909 (values (and value (org-split-string value "[ \t]"))))
15910 (mapcar 'org-entry-restore-space values)))
15912 (defun org-entry-protect-space (s)
15913 "Protect spaces and newline in string S."
15914 (while (string-match " " s)
15915 (setq s (replace-match "%20" t t s)))
15916 (while (string-match "\n" s)
15917 (setq s (replace-match "%0A" t t s)))
15920 (defun org-entry-restore-space (s)
15921 "Restore spaces and newline in string S."
15922 (while (string-match "%20" s)
15923 (setq s (replace-match " " t t s)))
15924 (while (string-match "%0A" s)
15925 (setq s (replace-match "\n" t t s)))
15928 (defvar org-entry-property-inherited-from (make-marker)
15929 "Marker pointing to the entry from where a property was inherited.
15930 Each call to `org-entry-get-with-inheritance' will set this marker to the
15931 location of the entry where the inheritance search matched. If there was
15932 no match, the marker will point nowhere.
15933 Note that also `org-entry-get' calls this function, if the INHERIT flag
15934 is set.")
15936 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15937 "Get PROPERTY of entry or content at point, search higher levels if needed.
15938 The search will stop at the first ancestor which has the property defined.
15939 If the value found is \"nil\", return nil to show that the property
15940 should be considered as undefined (this is the meaning of nil here).
15941 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15942 (move-marker org-entry-property-inherited-from nil)
15943 (org-with-wide-buffer
15944 (let (value)
15945 (catch 'exit
15946 (while t
15947 (let ((v (org-property--local-values property literal-nil)))
15948 (when v
15949 (setq value
15950 (concat (mapconcat #'identity (delq nil v) " ")
15951 (and value " ")
15952 value)))
15953 (cond
15954 ((car v)
15955 (org-back-to-heading t)
15956 (move-marker org-entry-property-inherited-from (point))
15957 (throw 'exit nil))
15958 ((org-up-heading-safe))
15960 (let ((global
15961 (cdr (or (assoc-string property org-file-properties t)
15962 (assoc-string property org-global-properties t)
15963 (assoc-string property org-global-properties-fixed t)))))
15964 (cond ((not global))
15965 (value (setq value (concat global " " value)))
15966 (t (setq value global))))
15967 (throw 'exit nil))))))
15968 (if literal-nil value (org-not-nil value)))))
15970 (defvar org-property-changed-functions nil
15971 "Hook called when the value of a property has changed.
15972 Each hook function should accept two arguments, the name of the property
15973 and the new value.")
15975 (defun org-entry-put (pom property value)
15976 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15978 If the value is nil, it is converted to the empty string. If it
15979 is not a string, an error is raised. Also raise an error on
15980 invalid property names.
15982 PROPERTY can be any regular property (see
15983 `org-special-properties'). It can also be \"TODO\",
15984 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15986 For the last two properties, VALUE may have any of the special
15987 values \"earlier\" and \"later\". The function then increases or
15988 decreases scheduled or deadline date by one day."
15989 (cond ((null value) (setq value ""))
15990 ((not (stringp value)) (error "Properties values should be strings"))
15991 ((not (org--valid-property-p property))
15992 (user-error "Invalid property name: \"%s\"" property)))
15993 (org-with-point-at pom
15994 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15995 (org-back-to-heading t)
15996 (org-with-limited-levels (org-back-to-heading t)))
15997 (let ((beg (point)))
15998 (cond
15999 ((equal property "TODO")
16000 (cond ((not (org-string-nw-p value)) (setq value 'none))
16001 ((not (member value org-todo-keywords-1))
16002 (user-error "\"%s\" is not a valid TODO state" value)))
16003 (org-todo value)
16004 (org-set-tags nil 'align))
16005 ((equal property "PRIORITY")
16006 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16007 (org-set-tags nil 'align))
16008 ((equal property "SCHEDULED")
16009 (forward-line)
16010 (if (and (org-looking-at-p org-planning-line-re)
16011 (re-search-forward
16012 org-scheduled-time-regexp (line-end-position) t))
16013 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16014 ((string= value "later") (org-timestamp-change 1 'day))
16015 ((string= value "") (org-schedule '(4)))
16016 (t (org-schedule nil value)))
16017 (if (member value '("earlier" "later" ""))
16018 (call-interactively #'org-schedule)
16019 (org-schedule nil value))))
16020 ((equal property "DEADLINE")
16021 (forward-line)
16022 (if (and (org-looking-at-p org-planning-line-re)
16023 (re-search-forward
16024 org-deadline-time-regexp (line-end-position) t))
16025 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16026 ((string= value "later") (org-timestamp-change 1 'day))
16027 ((string= value "") (org-deadline '(4)))
16028 (t (org-deadline nil value)))
16029 (if (member value '("earlier" "later" ""))
16030 (call-interactively #'org-deadline)
16031 (org-deadline nil value))))
16032 ((member property org-special-properties)
16033 (error "The %s property cannot be set with `org-entry-put'" property))
16035 (let* ((range (org-get-property-block beg 'force))
16036 (end (cdr range))
16037 (case-fold-search t))
16038 (goto-char (car range))
16039 (if (re-search-forward (org-re-property property nil t) end t)
16040 (progn (delete-region (match-beginning 0) (match-end 0))
16041 (goto-char (match-beginning 0)))
16042 (goto-char end)
16043 (insert "\n")
16044 (backward-char))
16045 (insert ":" property ":")
16046 (when value (insert " " value))
16047 (org-indent-line)))))
16048 (run-hook-with-args 'org-property-changed-functions property value)))
16050 (defun org-buffer-property-keys
16051 (&optional specials defaults columns ignore-malformed)
16052 "Get all property keys in the current buffer.
16054 When SPECIALS is non-nil, also list the special properties that
16055 reflect things like tags and TODO state.
16057 When DEFAULTS is non-nil, also include properties that has
16058 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16059 DESCRIPTION, LOCATION, and LOGGING and others.
16061 When COLUMNS in non-nil, also include property names given in
16062 COLUMN formats in the current buffer.
16064 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16065 automatically performed, such drawers will be silently ignored."
16066 (let ((case-fold-search t)
16067 (props (append
16068 (and specials org-special-properties)
16069 (and defaults (cons org-effort-property org-default-properties))
16070 nil)))
16071 (org-with-wide-buffer
16072 (goto-char (point-min))
16073 (while (re-search-forward org-property-start-re nil t)
16074 (let ((range (org-get-property-block)))
16075 (catch 'skip
16076 (unless range
16077 (when (and (not ignore-malformed)
16078 (not (org-before-first-heading-p))
16079 (y-or-n-p (format "Malformed drawer at %d, repair?"
16080 (line-beginning-position))))
16081 (org-get-property-block nil t))
16082 (throw 'skip nil))
16083 (goto-char (car range))
16084 (let ((begin (car range))
16085 (end (cdr range)))
16086 ;; Make sure that found property block is not located
16087 ;; before current point, as it would generate an infloop.
16088 ;; It can happen, for example, in the following
16089 ;; situation:
16091 ;; * Headline
16092 ;; :PROPERTIES:
16093 ;; ...
16094 ;; :END:
16095 ;; *************** Inlinetask
16096 ;; #+BEGIN_EXAMPLE
16097 ;; :PROPERTIES:
16098 ;; #+END_EXAMPLE
16100 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16101 (while (< (point) end)
16102 (let ((p (progn (looking-at org-property-re)
16103 (org-match-string-no-properties 2))))
16104 ;; Only add true property name, not extension symbol.
16105 (push (if (not (org-string-match-p "\\+\\'" p)) p
16106 (substring p 0 -1))
16107 props))
16108 (forward-line))))
16109 (outline-next-heading)))
16110 (when columns
16111 (goto-char (point-min))
16112 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16113 (let ((element (org-element-at-point)))
16114 (when (memq (org-element-type element) '(keyword node-property))
16115 (let ((value (org-element-property :value element))
16116 (start 0))
16117 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16118 (setq start (match-end 0))
16119 (let ((p (org-match-string-no-properties 1 value)))
16120 (unless (member-ignore-case p org-special-properties)
16121 (push p props))))))))))
16122 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16124 (defun org-property-values (key)
16125 "List all non-nil values of property KEY in current buffer."
16126 (org-with-wide-buffer
16127 (goto-char (point-min))
16128 (let ((case-fold-search t)
16129 (re (org-re-property key))
16130 values)
16131 (while (re-search-forward re nil t)
16132 (push (org-entry-get (point) key) values))
16133 (delete-dups values))))
16135 (defun org-insert-property-drawer ()
16136 "Insert a property drawer into the current entry."
16137 (org-with-wide-buffer
16138 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16139 (org-back-to-heading t)
16140 (org-with-limited-levels (org-back-to-heading t)))
16141 (forward-line)
16142 (when (org-looking-at-p org-planning-line-re) (forward-line))
16143 (unless (org-looking-at-p org-property-drawer-re)
16144 ;; Make sure we start editing a line from current entry, not from
16145 ;; next one. It prevents extending text properties or overlays
16146 ;; belonging to the latter.
16147 (when (bolp) (backward-char))
16148 (let ((begin (1+ (point)))
16149 (inhibit-read-only t))
16150 (insert "\n:PROPERTIES:\n:END:")
16151 (when (eobp) (insert "\n"))
16152 (org-indent-region begin (point))))))
16154 (defun org-insert-drawer (&optional arg drawer)
16155 "Insert a drawer at point.
16157 When optional argument ARG is non-nil, insert a property drawer.
16159 Optional argument DRAWER, when non-nil, is a string representing
16160 drawer's name. Otherwise, the user is prompted for a name.
16162 If a region is active, insert the drawer around that region
16163 instead.
16165 Point is left between drawer's boundaries."
16166 (interactive "P")
16167 (let* ((drawer (if arg "PROPERTIES"
16168 (or drawer (read-from-minibuffer "Drawer: ")))))
16169 (cond
16170 ;; With C-u, fall back on `org-insert-property-drawer'
16171 (arg (org-insert-property-drawer))
16172 ;; Check validity of suggested drawer's name.
16173 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16174 (user-error "Invalid drawer name"))
16175 ;; With an active region, insert a drawer at point.
16176 ((not (org-region-active-p))
16177 (progn
16178 (unless (bolp) (insert "\n"))
16179 (insert (format ":%s:\n\n:END:\n" drawer))
16180 (forward-line -2)))
16181 ;; Otherwise, insert the drawer at point
16183 (let ((rbeg (region-beginning))
16184 (rend (copy-marker (region-end))))
16185 (unwind-protect
16186 (progn
16187 (goto-char rbeg)
16188 (beginning-of-line)
16189 (when (save-excursion
16190 (re-search-forward org-outline-regexp-bol rend t))
16191 (user-error "Drawers cannot contain headlines"))
16192 ;; Position point at the beginning of the first
16193 ;; non-blank line in region. Insert drawer's opening
16194 ;; there, then indent it.
16195 (org-skip-whitespace)
16196 (beginning-of-line)
16197 (insert ":" drawer ":\n")
16198 (forward-line -1)
16199 (indent-for-tab-command)
16200 ;; Move point to the beginning of the first blank line
16201 ;; after the last non-blank line in region. Insert
16202 ;; drawer's closing, then indent it.
16203 (goto-char rend)
16204 (skip-chars-backward " \r\t\n")
16205 (insert "\n:END:")
16206 (deactivate-mark t)
16207 (indent-for-tab-command)
16208 (unless (eolp) (insert "\n")))
16209 ;; Clear marker, whatever the outcome of insertion is.
16210 (set-marker rend nil)))))))
16212 (defvar org-property-set-functions-alist nil
16213 "Property set function alist.
16214 Each entry should have the following format:
16216 (PROPERTY . READ-FUNCTION)
16218 The read function will be called with the same argument as
16219 `org-completing-read'.")
16221 (defun org-set-property-function (property)
16222 "Get the function that should be used to set PROPERTY.
16223 This is computed according to `org-property-set-functions-alist'."
16224 (or (cdr (assoc property org-property-set-functions-alist))
16225 'org-completing-read))
16227 (defun org-read-property-value (property)
16228 "Read PROPERTY value from user."
16229 (let* ((completion-ignore-case t)
16230 (allowed (org-property-get-allowed-values nil property 'table))
16231 (cur (org-entry-get nil property))
16232 (prompt (concat property " value"
16233 (if (and cur (string-match "\\S-" cur))
16234 (concat " [" cur "]") "") ": "))
16235 (set-function (org-set-property-function property))
16236 (val (if allowed
16237 (funcall set-function prompt allowed nil
16238 (not (get-text-property 0 'org-unrestricted
16239 (caar allowed))))
16240 (funcall set-function prompt
16241 (mapcar 'list (org-property-values property))
16242 nil nil "" nil cur))))
16243 (org-trim val)))
16245 (defvar org-last-set-property nil)
16246 (defvar org-last-set-property-value nil)
16247 (defun org-read-property-name ()
16248 "Read a property name."
16249 (let ((completion-ignore-case t)
16250 (default-prop (or (and (org-at-property-p)
16251 (org-match-string-no-properties 2))
16252 org-last-set-property)))
16253 (org-completing-read
16254 (concat "Property"
16255 (if default-prop (concat " [" default-prop "]") "")
16256 ": ")
16257 (mapcar #'list (org-buffer-property-keys nil t t))
16258 nil nil nil nil default-prop)))
16260 (defun org-set-property-and-value (use-last)
16261 "Allow to set [PROPERTY]: [value] direction from prompt.
16262 When use-default, don't even ask, just use the last
16263 \"[PROPERTY]: [value]\" string from the history."
16264 (interactive "P")
16265 (let* ((completion-ignore-case t)
16266 (pv (or (and use-last org-last-set-property-value)
16267 (org-completing-read
16268 "Enter a \"[Property]: [value]\" pair: "
16269 nil nil nil nil nil
16270 org-last-set-property-value)))
16271 prop val)
16272 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16273 (setq prop (match-string 1 pv)
16274 val (match-string 2 pv))
16275 (org-set-property prop val))))
16277 (defun org-set-property (property value)
16278 "In the current entry, set PROPERTY to VALUE.
16280 When called interactively, this will prompt for a property name, offering
16281 completion on existing and default properties. And then it will prompt
16282 for a value, offering completion either on allowed values (via an inherited
16283 xxx_ALL property) or on existing values in other instances of this property
16284 in the current file.
16286 Throw an error when trying to set a property with an invalid name."
16287 (interactive (list nil nil))
16288 (let ((property (or property (org-read-property-name))))
16289 ;; `org-entry-put' also makes the following check, but this one
16290 ;; avoids polluting `org-last-set-property' and
16291 ;; `org-last-set-property-value' needlessly.
16292 (unless (org--valid-property-p property)
16293 (user-error "Invalid property name: \"%s\"" property))
16294 (let ((value (or value (org-read-property-value property)))
16295 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16296 (setq org-last-set-property property)
16297 (setq org-last-set-property-value (concat property ": " value))
16298 ;; Possibly postprocess the inserted value:
16299 (when fn (setq value (funcall fn value)))
16300 (unless (equal (org-entry-get nil property) value)
16301 (org-entry-put nil property value)))))
16303 (defun org-find-property (property &optional value)
16304 "Find first entry in buffer that sets PROPERTY.
16306 When optional argument VALUE is non-nil, only consider an entry
16307 if it contains PROPERTY set to this value. If PROPERTY should be
16308 explicitly set to nil, use string \"nil\" for VALUE.
16310 Return position where the entry begins, or nil if there is no
16311 such entry. If narrowing is in effect, only search the visible
16312 part of the buffer."
16313 (save-excursion
16314 (goto-char (point-min))
16315 (let ((case-fold-search t)
16316 (re (org-re-property property nil (not value) value)))
16317 (catch 'exit
16318 (while (re-search-forward re nil t)
16319 (when (if value (org-at-property-p)
16320 (org-entry-get (point) property nil t))
16321 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16323 (defun org-delete-property (property)
16324 "In the current entry, delete PROPERTY."
16325 (interactive
16326 (let* ((completion-ignore-case t)
16327 (cat (org-entry-get (point) "CATEGORY"))
16328 (props0 (org-entry-properties nil 'standard))
16329 (props (if cat props0
16330 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16331 (prop (if (< 1 (length props))
16332 (completing-read "Property: " props nil t)
16333 (caar props))))
16334 (list prop)))
16335 (if (not property)
16336 (message "No property to delete in this entry")
16337 (org-entry-delete nil property)
16338 (message "Property \"%s\" deleted" property)))
16340 (defun org-delete-property-globally (property)
16341 "Remove PROPERTY globally, from all entries.
16342 This function ignores narrowing, if any."
16343 (interactive
16344 (let* ((completion-ignore-case t)
16345 (prop (completing-read
16346 "Globally remove property: "
16347 (mapcar #'list (org-buffer-property-keys)))))
16348 (list prop)))
16349 (org-with-wide-buffer
16350 (goto-char (point-min))
16351 (let ((count 0)
16352 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16353 (while (re-search-forward re nil t)
16354 (when (org-entry-delete (point) property) (cl-incf count)))
16355 (message "Property \"%s\" removed from %d entries" property count))))
16357 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16359 (defun org-compute-property-at-point ()
16360 "Compute the property at point.
16361 This looks for an enclosing column format, extracts the operator and
16362 then applies it to the property in the column format's scope."
16363 (interactive)
16364 (unless (org-at-property-p)
16365 (user-error "Not at a property"))
16366 (let ((prop (org-match-string-no-properties 2)))
16367 (org-columns-get-format-and-top-level)
16368 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16369 (user-error "No operator defined for property %s" prop))
16370 (org-columns-compute prop)))
16372 (defvar org-property-allowed-value-functions nil
16373 "Hook for functions supplying allowed values for a specific property.
16374 The functions must take a single argument, the name of the property, and
16375 return a flat list of allowed values. If \":ETC\" is one of
16376 the values, this means that these values are intended as defaults for
16377 completion, but that other values should be allowed too.
16378 The functions must return nil if they are not responsible for this
16379 property.")
16381 (defun org-property-get-allowed-values (pom property &optional table)
16382 "Get allowed values for the property PROPERTY.
16383 When TABLE is non-nil, return an alist that can directly be used for
16384 completion."
16385 (let (vals)
16386 (cond
16387 ((equal property "TODO")
16388 (setq vals (org-with-point-at pom
16389 (append org-todo-keywords-1 '("")))))
16390 ((equal property "PRIORITY")
16391 (let ((n org-lowest-priority))
16392 (while (>= n org-highest-priority)
16393 (push (char-to-string n) vals)
16394 (setq n (1- n)))))
16395 ((equal property "CATEGORY"))
16396 ((member property org-special-properties))
16397 ((setq vals (run-hook-with-args-until-success
16398 'org-property-allowed-value-functions property)))
16400 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16401 (when (and vals (string-match "\\S-" vals))
16402 (setq vals (car (read-from-string (concat "(" vals ")"))))
16403 (setq vals (mapcar (lambda (x)
16404 (cond ((stringp x) x)
16405 ((numberp x) (number-to-string x))
16406 ((symbolp x) (symbol-name x))
16407 (t "???")))
16408 vals)))))
16409 (when (member ":ETC" vals)
16410 (setq vals (remove ":ETC" vals))
16411 (org-add-props (car vals) '(org-unrestricted t)))
16412 (if table (mapcar 'list vals) vals)))
16414 (defun org-property-previous-allowed-value (&optional _previous)
16415 "Switch to the next allowed value for this property."
16416 (interactive)
16417 (org-property-next-allowed-value t))
16419 (defun org-property-next-allowed-value (&optional previous)
16420 "Switch to the next allowed value for this property."
16421 (interactive)
16422 (unless (org-at-property-p)
16423 (user-error "Not at a property"))
16424 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16425 (key (match-string 2))
16426 (value (match-string 3))
16427 (allowed (or (org-property-get-allowed-values (point) key)
16428 (and (member value '("[ ]" "[-]" "[X]"))
16429 '("[ ]" "[X]"))))
16430 (heading (save-match-data (nth 4 (org-heading-components))))
16431 nval)
16432 (unless allowed
16433 (user-error "Allowed values for this property have not been defined"))
16434 (when previous (setq allowed (reverse allowed)))
16435 (when (member value allowed)
16436 (setq nval (car (cdr (member value allowed)))))
16437 (setq nval (or nval (car allowed)))
16438 (when (equal nval value)
16439 (user-error "Only one allowed value for this property"))
16440 (org-at-property-p)
16441 (replace-match (concat " :" key ": " nval) t t)
16442 (org-indent-line)
16443 (beginning-of-line 1)
16444 (skip-chars-forward " \t")
16445 (when (equal prop org-effort-property)
16446 (org-refresh-property
16447 '((effort . identity)
16448 (effort-minutes . org-duration-string-to-minutes))
16449 nval)
16450 (when (string= org-clock-current-task heading)
16451 (setq org-clock-effort nval)
16452 (org-clock-update-mode-line)))
16453 (run-hook-with-args 'org-property-changed-functions key nval)))
16455 (defun org-find-olp (path &optional this-buffer)
16456 "Return a marker pointing to the entry at outline path OLP.
16457 If anything goes wrong, throw an error.
16458 You can wrap this call to catch the error like this:
16460 \(condition-case msg
16461 \(org-mobile-locate-entry (match-string 4))
16462 \(error (nth 1 msg)))
16464 The return value will then be either a string with the error message,
16465 or a marker if everything is OK.
16467 If THIS-BUFFER is set, the outline path does not contain a file,
16468 only headings."
16469 (let* ((file (if this-buffer buffer-file-name (pop path)))
16470 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16471 (level 1)
16472 (lmin 1)
16473 (lmax 1)
16474 end found flevel)
16475 (unless buffer (error "File not found :%s" file))
16476 (with-current-buffer buffer
16477 (org-with-wide-buffer
16478 (goto-char (point-min))
16479 (dolist (heading path)
16480 (let ((re (format org-complex-heading-regexp-format
16481 (regexp-quote heading)))
16482 (cnt 0))
16483 (while (re-search-forward re end t)
16484 (setq level (- (match-end 1) (match-beginning 1)))
16485 (when (and (>= level lmin) (<= level lmax))
16486 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16487 (when (= cnt 0)
16488 (error "Heading not found on level %d: %s" lmax heading))
16489 (when (> cnt 1)
16490 (error "Heading not unique on level %d: %s" lmax heading))
16491 (goto-char found)
16492 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16493 (setq end (save-excursion (org-end-of-subtree t t)))))
16494 (when (org-at-heading-p)
16495 (point-marker))))))
16497 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16498 "Find node HEADING in BUFFER.
16499 Return a marker to the heading if it was found, or nil if not.
16500 If POS-ONLY is set, return just the position instead of a marker.
16502 The heading text must match exact, but it may have a TODO keyword,
16503 a priority cookie and tags in the standard locations."
16504 (with-current-buffer (or buffer (current-buffer))
16505 (save-excursion
16506 (save-restriction
16507 (widen)
16508 (goto-char (point-min))
16509 (let (case-fold-search)
16510 (when (re-search-forward
16511 (format org-complex-heading-regexp-format
16512 (regexp-quote heading)) nil t)
16513 (if pos-only
16514 (match-beginning 0)
16515 (move-marker (make-marker) (match-beginning 0)))))))))
16517 (defun org-find-exact-heading-in-directory (heading &optional dir)
16518 "Find Org node headline HEADING in all .org files in directory DIR.
16519 When the target headline is found, return a marker to this location."
16520 (let ((files (directory-files (or dir default-directory)
16521 t "\\`[^.#].*\\.org\\'"))
16522 visiting m buffer)
16523 (catch 'found
16524 (dolist (file files)
16525 (message "trying %s" file)
16526 (setq visiting (org-find-base-buffer-visiting file))
16527 (setq buffer (or visiting (find-file-noselect file)))
16528 (setq m (org-find-exact-headline-in-buffer
16529 heading buffer))
16530 (when (and (not m) (not visiting)) (kill-buffer buffer))
16531 (and m (throw 'found m))))))
16533 (defun org-find-entry-with-id (ident)
16534 "Locate the entry that contains the ID property with exact value IDENT.
16535 IDENT can be a string, a symbol or a number, this function will search for
16536 the string representation of it.
16537 Return the position where this entry starts, or nil if there is no such entry."
16538 (interactive "sID: ")
16539 (let ((id (cond
16540 ((stringp ident) ident)
16541 ((symbolp ident) (symbol-name ident))
16542 ((numberp ident) (number-to-string ident))
16543 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16544 (org-with-wide-buffer (org-find-property "ID" id))))
16546 ;;;; Timestamps
16548 (defvar org-last-changed-timestamp nil)
16549 (defvar org-last-inserted-timestamp nil
16550 "The last time stamp inserted with `org-insert-time-stamp'.")
16551 (defvar org-ts-what) ; dynamically scoped parameter
16553 (defun org-time-stamp (arg &optional inactive)
16554 "Prompt for a date/time and insert a time stamp.
16556 If the user specifies a time like HH:MM or if this command is
16557 called with at least one prefix argument, the time stamp contains
16558 the date and the time. Otherwise, only the date is included.
16560 All parts of a date not specified by the user are filled in from
16561 the timestamp at point, if any, or the current date/time
16562 otherwise.
16564 If there is already a timestamp at the cursor, it is replaced.
16566 With two universal prefix arguments, insert an active timestamp
16567 with the current time without prompting the user.
16569 When called from lisp, the timestamp is inactive if INACTIVE is
16570 non-nil."
16571 (interactive "P")
16572 (let* ((ts (cond
16573 ((org-at-date-range-p t)
16574 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16575 ((org-at-timestamp-p t) (match-string 0))))
16576 ;; Default time is either the timestamp at point or today.
16577 ;; When entering a range, only the range start is considered.
16578 (default-time (if (not ts) (current-time)
16579 (apply #'encode-time (org-parse-time-string ts))))
16580 (default-input (and ts (org-get-compact-tod ts)))
16581 (repeater (and ts
16582 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16583 (match-string 0 ts)))
16584 org-time-was-given
16585 org-end-time-was-given
16586 (time
16587 (and (if (equal arg '(16)) (current-time)
16588 ;; Preserve `this-command' and `last-command'.
16589 (let ((this-command this-command)
16590 (last-command last-command))
16591 (org-read-date
16592 arg 'totime nil nil default-time default-input
16593 inactive))))))
16594 (cond
16595 ((and ts
16596 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16597 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16598 (insert "--")
16599 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16601 ;; Make sure we're on a timestamp. When in the middle of a date
16602 ;; range, move arbitrarily to range end.
16603 (unless (org-at-timestamp-p t)
16604 (skip-chars-forward "-")
16605 (org-at-timestamp-p t))
16606 (replace-match "")
16607 (setq org-last-changed-timestamp
16608 (org-insert-time-stamp
16609 time (or org-time-was-given arg)
16610 inactive nil nil (list org-end-time-was-given)))
16611 (when repeater
16612 (backward-char)
16613 (insert " " repeater)
16614 (setq org-last-changed-timestamp
16615 (concat (substring org-last-inserted-timestamp 0 -1)
16616 " " repeater ">")))
16617 (message "Timestamp updated"))
16618 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16619 (t (org-insert-time-stamp
16620 time (or org-time-was-given arg) inactive nil nil
16621 (list org-end-time-was-given))))))
16623 ;; FIXME: can we use this for something else, like computing time differences?
16624 (defun org-get-compact-tod (s)
16625 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16626 (let* ((t1 (match-string 1 s))
16627 (h1 (string-to-number (match-string 2 s)))
16628 (m1 (string-to-number (match-string 3 s)))
16629 (t2 (and (match-end 4) (match-string 5 s)))
16630 (h2 (and t2 (string-to-number (match-string 6 s))))
16631 (m2 (and t2 (string-to-number (match-string 7 s))))
16632 dh dm)
16633 (if (not t2)
16635 (setq dh (- h2 h1) dm (- m2 m1))
16636 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16637 (concat t1 "+" (number-to-string dh)
16638 (and (/= 0 dm) (format ":%02d" dm)))))))
16640 (defun org-time-stamp-inactive (&optional arg)
16641 "Insert an inactive time stamp.
16642 An inactive time stamp is enclosed in square brackets instead of angle
16643 brackets. It is inactive in the sense that it does not trigger agenda entries,
16644 does not link to the calendar and cannot be changed with the S-cursor keys.
16645 So these are more for recording a certain time/date."
16646 (interactive "P")
16647 (org-time-stamp arg 'inactive))
16649 (defvar org-date-ovl (make-overlay 1 1))
16650 (overlay-put org-date-ovl 'face 'org-date-selected)
16651 (org-detach-overlay org-date-ovl)
16653 (defvar org-ans1) ; dynamically scoped parameter
16654 (defvar org-ans2) ; dynamically scoped parameter
16656 (defvar org-plain-time-of-day-regexp) ; defined below
16658 (defvar org-overriding-default-time nil) ; dynamically scoped
16659 (defvar org-read-date-overlay nil)
16660 (defvar org-dcst nil) ; dynamically scoped
16661 (defvar org-read-date-history nil)
16662 (defvar org-read-date-final-answer nil)
16663 (defvar org-read-date-analyze-futurep nil)
16664 (defvar org-read-date-analyze-forced-year nil)
16665 (defvar org-read-date-inactive)
16667 (defvar org-read-date-minibuffer-local-map
16668 (let* ((map (make-sparse-keymap)))
16669 (set-keymap-parent map minibuffer-local-map)
16670 (org-defkey map (kbd ".")
16671 (lambda () (interactive)
16672 ;; Are we at the beginning of the prompt?
16673 (if (org-looking-back "^[^:]+: "
16674 (let ((inhibit-field-text-motion t))
16675 (line-beginning-position)))
16676 (org-eval-in-calendar '(calendar-goto-today))
16677 (insert "."))))
16678 (org-defkey map (kbd "C-.")
16679 (lambda () (interactive)
16680 (org-eval-in-calendar '(calendar-goto-today))))
16681 (org-defkey map [(meta shift left)]
16682 (lambda () (interactive)
16683 (org-eval-in-calendar '(calendar-backward-month 1))))
16684 (org-defkey map [(meta shift right)]
16685 (lambda () (interactive)
16686 (org-eval-in-calendar '(calendar-forward-month 1))))
16687 (org-defkey map [(meta shift up)]
16688 (lambda () (interactive)
16689 (org-eval-in-calendar '(calendar-backward-year 1))))
16690 (org-defkey map [(meta shift down)]
16691 (lambda () (interactive)
16692 (org-eval-in-calendar '(calendar-forward-year 1))))
16693 (org-defkey map [?\e (shift left)]
16694 (lambda () (interactive)
16695 (org-eval-in-calendar '(calendar-backward-month 1))))
16696 (org-defkey map [?\e (shift right)]
16697 (lambda () (interactive)
16698 (org-eval-in-calendar '(calendar-forward-month 1))))
16699 (org-defkey map [?\e (shift up)]
16700 (lambda () (interactive)
16701 (org-eval-in-calendar '(calendar-backward-year 1))))
16702 (org-defkey map [?\e (shift down)]
16703 (lambda () (interactive)
16704 (org-eval-in-calendar '(calendar-forward-year 1))))
16705 (org-defkey map [(shift up)]
16706 (lambda () (interactive)
16707 (org-eval-in-calendar '(calendar-backward-week 1))))
16708 (org-defkey map [(shift down)]
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(calendar-forward-week 1))))
16711 (org-defkey map [(shift left)]
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(calendar-backward-day 1))))
16714 (org-defkey map [(shift right)]
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-forward-day 1))))
16717 (org-defkey map "!"
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(diary-view-entries))
16720 (message "")))
16721 (org-defkey map ">"
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-scroll-left 1))))
16724 (org-defkey map "<"
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-scroll-right 1))))
16727 (org-defkey map "\C-v"
16728 (lambda () (interactive)
16729 (org-eval-in-calendar
16730 '(calendar-scroll-left-three-months 1))))
16731 (org-defkey map "\M-v"
16732 (lambda () (interactive)
16733 (org-eval-in-calendar
16734 '(calendar-scroll-right-three-months 1))))
16735 map)
16736 "Keymap for minibuffer commands when using `org-read-date'.")
16738 (defvar org-def)
16739 (defvar org-defdecode)
16740 (defvar org-with-time)
16742 (defvar calendar-setup) ; Dynamically scoped.
16743 (defun org-read-date (&optional with-time to-time from-string prompt
16744 default-time default-input inactive)
16745 "Read a date, possibly a time, and make things smooth for the user.
16746 The prompt will suggest to enter an ISO date, but you can also enter anything
16747 which will at least partially be understood by `parse-time-string'.
16748 Unrecognized parts of the date will default to the current day, month, year,
16749 hour and minute. If this command is called to replace a timestamp at point,
16750 or to enter the second timestamp of a range, the default time is taken
16751 from the existing stamp. Furthermore, the command prefers the future,
16752 so if you are giving a date where the year is not given, and the day-month
16753 combination is already past in the current year, it will assume you
16754 mean next year. For details, see the manual. A few examples:
16756 3-2-5 --> 2003-02-05
16757 feb 15 --> currentyear-02-15
16758 2/15 --> currentyear-02-15
16759 sep 12 9 --> 2009-09-12
16760 12:45 --> today 12:45
16761 22 sept 0:34 --> currentyear-09-22 0:34
16762 12 --> currentyear-currentmonth-12
16763 Fri --> nearest Friday after today
16764 -Tue --> last Tuesday
16765 etc.
16767 Furthermore you can specify a relative date by giving, as the *first* thing
16768 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16769 change in days weeks, months, years.
16770 With a single plus or minus, the date is relative to today. With a double
16771 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16772 +4d --> four days from today
16773 +4 --> same as above
16774 +2w --> two weeks from today
16775 ++5 --> five days from default date
16777 The function understands only English month and weekday abbreviations.
16779 While prompting, a calendar is popped up - you can also select the
16780 date with the mouse (button 1). The calendar shows a period of three
16781 months. To scroll it to other months, use the keys `>' and `<'.
16782 If you don't like the calendar, turn it off with
16783 (setq org-read-date-popup-calendar nil)
16785 With optional argument TO-TIME, the date will immediately be converted
16786 to an internal time.
16787 With an optional argument WITH-TIME, the prompt will suggest to
16788 also insert a time. Note that when WITH-TIME is not set, you can
16789 still enter a time, and this function will inform the calling routine
16790 about this change. The calling routine may then choose to change the
16791 format used to insert the time stamp into the buffer to include the time.
16792 With optional argument FROM-STRING, read from this string instead from
16793 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16794 the time/date that is used for everything that is not specified by the
16795 user."
16796 (require 'parse-time)
16797 (let* ((org-with-time with-time)
16798 (org-time-stamp-rounding-minutes
16799 (if (equal org-with-time '(16))
16800 '(0 0)
16801 org-time-stamp-rounding-minutes))
16802 (org-dcst org-display-custom-times)
16803 (ct (org-current-time))
16804 (org-def (or org-overriding-default-time default-time ct))
16805 (org-defdecode (decode-time org-def))
16806 (cur-frame (selected-frame))
16807 (mouse-autoselect-window nil) ; Don't let the mouse jump
16808 (calendar-setup
16809 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16810 (calendar-move-hook nil)
16811 (calendar-view-diary-initially-flag nil)
16812 (calendar-view-holidays-initially-flag nil)
16813 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16814 ;; Rationalize `org-def' and `org-defdecode', if required.
16815 (when (< (nth 2 org-defdecode) org-extend-today-until)
16816 (setf (nth 2 org-defdecode) -1)
16817 (setf (nth 1 org-defdecode) 59)
16818 (setq org-def (apply #'encode-time org-defdecode))
16819 (setq org-defdecode (decode-time org-def)))
16820 (let* ((timestr (format-time-string
16821 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16822 org-def))
16823 (prompt (concat (if prompt (concat prompt " ") "")
16824 (format "Date+time [%s]: " timestr))))
16825 (cond
16826 (from-string (setq ans from-string))
16827 (org-read-date-popup-calendar
16828 (save-excursion
16829 (save-window-excursion
16830 (calendar)
16831 (when (eq calendar-setup 'calendar-only)
16832 (setq cal-frame
16833 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16834 (select-frame cal-frame))
16835 (org-eval-in-calendar '(setq cursor-type nil) t)
16836 (unwind-protect
16837 (progn
16838 (calendar-forward-day (- (time-to-days org-def)
16839 (calendar-absolute-from-gregorian
16840 (calendar-current-date))))
16841 (org-eval-in-calendar nil t)
16842 (let* ((old-map (current-local-map))
16843 (map (copy-keymap calendar-mode-map))
16844 (minibuffer-local-map
16845 (copy-keymap org-read-date-minibuffer-local-map)))
16846 (org-defkey map (kbd "RET") 'org-calendar-select)
16847 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16848 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16849 (unwind-protect
16850 (progn
16851 (use-local-map map)
16852 (setq org-read-date-inactive inactive)
16853 (add-hook 'post-command-hook 'org-read-date-display)
16854 (setq org-ans0
16855 (read-string prompt
16856 default-input
16857 'org-read-date-history
16858 nil))
16859 ;; org-ans0: from prompt
16860 ;; org-ans1: from mouse click
16861 ;; org-ans2: from calendar motion
16862 (setq ans
16863 (concat org-ans0 " " (or org-ans1 org-ans2))))
16864 (remove-hook 'post-command-hook 'org-read-date-display)
16865 (use-local-map old-map)
16866 (when org-read-date-overlay
16867 (delete-overlay org-read-date-overlay)
16868 (setq org-read-date-overlay nil)))))
16869 (bury-buffer "*Calendar*")
16870 (when cal-frame
16871 (delete-frame cal-frame)
16872 (select-frame-set-input-focus cur-frame))))))
16874 (t ; Naked prompt only
16875 (unwind-protect
16876 (setq ans (read-string prompt default-input
16877 'org-read-date-history timestr))
16878 (when org-read-date-overlay
16879 (delete-overlay org-read-date-overlay)
16880 (setq org-read-date-overlay nil))))))
16882 (setq final (org-read-date-analyze ans org-def org-defdecode))
16884 (when org-read-date-analyze-forced-year
16885 (message "Year was forced into %s"
16886 (if org-read-date-force-compatible-dates
16887 "compatible range (1970-2037)"
16888 "range representable on this machine"))
16889 (ding))
16891 ;; One round trip to get rid of 34th of August and stuff like that....
16892 (setq final (decode-time (apply 'encode-time final)))
16894 (setq org-read-date-final-answer ans)
16896 (if to-time
16897 (apply 'encode-time final)
16898 (if (and (boundp 'org-time-was-given) org-time-was-given)
16899 (format "%04d-%02d-%02d %02d:%02d"
16900 (nth 5 final) (nth 4 final) (nth 3 final)
16901 (nth 2 final) (nth 1 final))
16902 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16904 (defun org-read-date-display ()
16905 "Display the current date prompt interpretation in the minibuffer."
16906 (when org-read-date-display-live
16907 (when org-read-date-overlay
16908 (delete-overlay org-read-date-overlay))
16909 (when (minibufferp (current-buffer))
16910 (save-excursion
16911 (end-of-line 1)
16912 (while (not (equal (buffer-substring
16913 (max (point-min) (- (point) 4)) (point))
16914 " "))
16915 (insert " ")))
16916 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16917 " " (or org-ans1 org-ans2)))
16918 (org-end-time-was-given nil)
16919 (f (org-read-date-analyze ans org-def org-defdecode))
16920 (fmts (if org-dcst
16921 org-time-stamp-custom-formats
16922 org-time-stamp-formats))
16923 (fmt (if (or org-with-time
16924 (and (boundp 'org-time-was-given) org-time-was-given))
16925 (cdr fmts)
16926 (car fmts)))
16927 (txt (format-time-string fmt (apply 'encode-time f)))
16928 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16929 (txt (concat "=> " txt)))
16930 (when (and org-end-time-was-given
16931 (string-match org-plain-time-of-day-regexp txt))
16932 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16933 org-end-time-was-given
16934 (substring txt (match-end 0)))))
16935 (when org-read-date-analyze-futurep
16936 (setq txt (concat txt " (=>F)")))
16937 (setq org-read-date-overlay
16938 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16939 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16941 (defun org-read-date-analyze (ans def defdecode)
16942 "Analyze the combined answer of the date prompt."
16943 ;; FIXME: cleanup and comment
16944 ;; Pass `current-time' result to `decode-time' (instead of calling
16945 ;; without arguments) so that only `current-time' has to be
16946 ;; overriden in tests.
16947 (let ((org-def def)
16948 (org-defdecode defdecode)
16949 (nowdecode (decode-time (current-time)))
16950 delta deltan deltaw deltadef year month day
16951 hour minute second wday pm h2 m2 tl wday1
16952 iso-year iso-weekday iso-week iso-date futurep kill-year)
16953 (setq org-read-date-analyze-futurep nil
16954 org-read-date-analyze-forced-year nil)
16955 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16956 (setq ans "+0"))
16958 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16959 (setq ans (replace-match "" t t ans)
16960 deltan (car delta)
16961 deltaw (nth 1 delta)
16962 deltadef (nth 2 delta)))
16964 ;; Check if there is an iso week date in there. If yes, store the
16965 ;; info and postpone interpreting it until the rest of the parsing
16966 ;; is done.
16967 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16968 (setq iso-year (when (match-end 1)
16969 (org-small-year-to-year
16970 (string-to-number (match-string 1 ans))))
16971 iso-weekday (when (match-end 3)
16972 (string-to-number (match-string 3 ans)))
16973 iso-week (string-to-number (match-string 2 ans)))
16974 (setq ans (replace-match "" t t ans)))
16976 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16977 (when (string-match
16978 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16979 (setq year (if (match-end 2)
16980 (string-to-number (match-string 2 ans))
16981 (progn (setq kill-year t)
16982 (string-to-number (format-time-string "%Y"))))
16983 month (string-to-number (match-string 3 ans))
16984 day (string-to-number (match-string 4 ans)))
16985 (when (< year 100) (setq year (+ 2000 year)))
16986 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16987 t nil ans)))
16989 ;; Help matching dotted european dates
16990 (when (string-match
16991 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16992 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16993 (setq kill-year t)
16994 (string-to-number (format-time-string "%Y")))
16995 day (string-to-number (match-string 1 ans))
16996 month (string-to-number (match-string 2 ans))
16997 ans (replace-match (format "%04d-%02d-%02d" year month day)
16998 t nil ans)))
17000 ;; Help matching american dates, like 5/30 or 5/30/7
17001 (when (string-match
17002 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17003 (setq year (if (match-end 4)
17004 (string-to-number (match-string 4 ans))
17005 (progn (setq kill-year t)
17006 (string-to-number (format-time-string "%Y"))))
17007 month (string-to-number (match-string 1 ans))
17008 day (string-to-number (match-string 2 ans)))
17009 (when (< year 100) (setq year (+ 2000 year)))
17010 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17011 t nil ans)))
17012 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17013 ;; If there is a time with am/pm, and *no* time without it, we convert
17014 ;; so that matching will be successful.
17015 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17016 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17017 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17018 (setq hour (string-to-number (match-string 1 ans))
17019 minute (if (match-end 3)
17020 (string-to-number (match-string 3 ans))
17022 pm (equal ?p
17023 (string-to-char (downcase (match-string 4 ans)))))
17024 (if (and (= hour 12) (not pm))
17025 (setq hour 0)
17026 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17027 (setq ans (replace-match (format "%02d:%02d" hour minute)
17028 t t ans))))
17030 ;; Check if a time range is given as a duration
17031 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17032 (setq hour (string-to-number (match-string 1 ans))
17033 h2 (+ hour (string-to-number (match-string 3 ans)))
17034 minute (string-to-number (match-string 2 ans))
17035 m2 (+ minute (if (match-end 5) (string-to-number
17036 (match-string 5 ans))0)))
17037 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17038 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17039 t t ans)))
17041 ;; Check if there is a time range
17042 (when (boundp 'org-end-time-was-given)
17043 (setq org-time-was-given nil)
17044 (when (and (string-match org-plain-time-of-day-regexp ans)
17045 (match-end 8))
17046 (setq org-end-time-was-given (match-string 8 ans))
17047 (setq ans (concat (substring ans 0 (match-beginning 7))
17048 (substring ans (match-end 7))))))
17050 (setq tl (parse-time-string ans)
17051 day (or (nth 3 tl) (nth 3 org-defdecode))
17052 month
17053 (cond ((nth 4 tl))
17054 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17055 ;; Day was specified. Make sure DAY+MONTH
17056 ;; combination happens in the future.
17057 ((nth 3 tl)
17058 (setq futurep t)
17059 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17060 (nth 4 nowdecode)))
17061 (t (nth 4 org-defdecode)))
17062 year
17063 (cond ((and (not kill-year) (nth 5 tl)))
17064 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17065 ;; Month was guessed in the future and is at least
17066 ;; equal to NOWDECODE's. Fix year accordingly.
17067 (futurep
17068 (if (or (> month (nth 4 nowdecode))
17069 (>= day (nth 3 nowdecode)))
17070 (nth 5 nowdecode)
17071 (1+ (nth 5 nowdecode))))
17072 ;; Month was specified. Make sure MONTH+YEAR
17073 ;; combination happens in the future.
17074 ((nth 4 tl)
17075 (setq futurep t)
17076 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17077 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17078 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17079 (t (nth 5 nowdecode))))
17080 (t (nth 5 org-defdecode)))
17081 hour (or (nth 2 tl) (nth 2 org-defdecode))
17082 minute (or (nth 1 tl) (nth 1 org-defdecode))
17083 second (or (nth 0 tl) 0)
17084 wday (nth 6 tl))
17086 (when (and (eq org-read-date-prefer-future 'time)
17087 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17088 (equal day (nth 3 nowdecode))
17089 (equal month (nth 4 nowdecode))
17090 (equal year (nth 5 nowdecode))
17091 (nth 2 tl)
17092 (or (< (nth 2 tl) (nth 2 nowdecode))
17093 (and (= (nth 2 tl) (nth 2 nowdecode))
17094 (nth 1 tl)
17095 (< (nth 1 tl) (nth 1 nowdecode)))))
17096 (setq day (1+ day)
17097 futurep t))
17099 ;; Special date definitions below
17100 (cond
17101 (iso-week
17102 ;; There was an iso week
17103 (require 'cal-iso)
17104 (setq futurep nil)
17105 (setq year (or iso-year year)
17106 day (or iso-weekday wday 1)
17107 wday nil ; to make sure that the trigger below does not match
17108 iso-date (calendar-gregorian-from-absolute
17109 (calendar-iso-to-absolute
17110 (list iso-week day year))))
17111 ; FIXME: Should we also push ISO weeks into the future?
17112 ; (when (and org-read-date-prefer-future
17113 ; (not iso-year)
17114 ; (< (calendar-absolute-from-gregorian iso-date)
17115 ; (time-to-days (current-time))))
17116 ; (setq year (1+ year)
17117 ; iso-date (calendar-gregorian-from-absolute
17118 ; (calendar-iso-to-absolute
17119 ; (list iso-week day year)))))
17120 (setq month (car iso-date)
17121 year (nth 2 iso-date)
17122 day (nth 1 iso-date)))
17123 (deltan
17124 (setq futurep nil)
17125 (unless deltadef
17126 ;; Pass `current-time' result to `decode-time' (instead of
17127 ;; calling without arguments) so that only `current-time' has
17128 ;; to be overriden in tests.
17129 (let ((now (decode-time (current-time))))
17130 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17131 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17132 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17133 ((equal deltaw "m") (setq month (+ month deltan)))
17134 ((equal deltaw "y") (setq year (+ year deltan)))))
17135 ((and wday (not (nth 3 tl)))
17136 ;; Weekday was given, but no day, so pick that day in the week
17137 ;; on or after the derived date.
17138 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17139 (unless (equal wday wday1)
17140 (setq day (+ day (% (- wday wday1 -7) 7))))))
17141 (when (and (boundp 'org-time-was-given)
17142 (nth 2 tl))
17143 (setq org-time-was-given t))
17144 (when (< year 100) (setq year (+ 2000 year)))
17145 ;; Check of the date is representable
17146 (if org-read-date-force-compatible-dates
17147 (progn
17148 (when (< year 1970)
17149 (setq year 1970 org-read-date-analyze-forced-year t))
17150 (when (> year 2037)
17151 (setq year 2037 org-read-date-analyze-forced-year t)))
17152 (condition-case nil
17153 (ignore (encode-time second minute hour day month year))
17154 (error
17155 (setq year (nth 5 org-defdecode))
17156 (setq org-read-date-analyze-forced-year t))))
17157 (setq org-read-date-analyze-futurep futurep)
17158 (list second minute hour day month year)))
17160 (defvar parse-time-weekdays)
17161 (defun org-read-date-get-relative (s today default)
17162 "Check string S for special relative date string.
17163 TODAY and DEFAULT are internal times, for today and for a default.
17164 Return shift list (N what def-flag)
17165 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17166 N is the number of WHATs to shift.
17167 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17168 the DEFAULT date rather than TODAY."
17169 (require 'parse-time)
17170 (when (and
17171 (string-match
17172 (concat
17173 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17174 "\\([0-9]+\\)?"
17175 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17176 "\\([ \t]\\|$\\)") s)
17177 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17178 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17179 (string-to-char (substring (match-string 1 s) -1))
17180 ?+))
17181 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17182 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17183 (what (if (match-end 3) (match-string 3 s) "d"))
17184 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17185 (date (if rel default today))
17186 (wday (nth 6 (decode-time date)))
17187 delta)
17188 (if wday1
17189 (progn
17190 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17191 (when (= delta 0) (setq delta 7))
17192 (when (= dir ?-)
17193 (setq delta (- delta 7))
17194 (when (= delta 0) (setq delta -7)))
17195 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17196 (list delta "d" rel))
17197 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17199 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17200 "Turn a user-specified date into the internal representation.
17201 The internal representation needed by the calendar is (month day year).
17202 This is a wrapper to handle the brain-dead convention in calendar that
17203 user function argument order change dependent on argument order."
17204 (if (boundp 'calendar-date-style)
17205 (cond
17206 ((eq calendar-date-style 'american)
17207 (list arg1 arg2 arg3))
17208 ((eq calendar-date-style 'european)
17209 (list arg2 arg1 arg3))
17210 ((eq calendar-date-style 'iso)
17211 (list arg2 arg3 arg1)))
17212 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17213 (if (org-bound-and-true-p european-calendar-style)
17214 (list arg2 arg1 arg3)
17215 (list arg1 arg2 arg3)))))
17217 (defun org-eval-in-calendar (form &optional keepdate)
17218 "Eval FORM in the calendar window and return to current window.
17219 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17220 otherwise stick to the current value of `org-ans2'."
17221 (let ((sf (selected-frame))
17222 (sw (selected-window)))
17223 (select-window (get-buffer-window "*Calendar*" t))
17224 (eval form)
17225 (when (and (not keepdate) (calendar-cursor-to-date))
17226 (let* ((date (calendar-cursor-to-date))
17227 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17228 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17229 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17230 (select-window sw)
17231 (org-select-frame-set-input-focus sf)))
17233 (defun org-calendar-select ()
17234 "Return to `org-read-date' with the date currently selected.
17235 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17236 (interactive)
17237 (when (calendar-cursor-to-date)
17238 (let* ((date (calendar-cursor-to-date))
17239 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17240 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17241 (when (active-minibuffer-window) (exit-minibuffer))))
17243 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17244 "Insert a date stamp for the date given by the internal TIME.
17245 See `format-time-string' for the format of TIME.
17246 WITH-HM means use the stamp format that includes the time of the day.
17247 INACTIVE means use square brackets instead of angular ones, so that the
17248 stamp will not contribute to the agenda.
17249 PRE and POST are optional strings to be inserted before and after the
17250 stamp.
17251 The command returns the inserted time stamp."
17252 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17253 stamp)
17254 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17255 (insert-before-markers (or pre ""))
17256 (when (listp extra)
17257 (setq extra (car extra))
17258 (if (and (stringp extra)
17259 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17260 (setq extra (format "-%02d:%02d"
17261 (string-to-number (match-string 1 extra))
17262 (string-to-number (match-string 2 extra))))
17263 (setq extra nil)))
17264 (when extra
17265 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17266 (insert-before-markers (setq stamp (format-time-string fmt time)))
17267 (insert-before-markers (or post ""))
17268 (setq org-last-inserted-timestamp stamp)))
17270 (defun org-toggle-time-stamp-overlays ()
17271 "Toggle the use of custom time stamp formats."
17272 (interactive)
17273 (setq org-display-custom-times (not org-display-custom-times))
17274 (unless org-display-custom-times
17275 (let ((p (point-min)) (bmp (buffer-modified-p)))
17276 (while (setq p (next-single-property-change p 'display))
17277 (when (and (get-text-property p 'display)
17278 (eq (get-text-property p 'face) 'org-date))
17279 (remove-text-properties
17280 p (setq p (next-single-property-change p 'display))
17281 '(display t))))
17282 (set-buffer-modified-p bmp)))
17283 (when (featurep 'xemacs)
17284 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17285 (org-restart-font-lock)
17286 (setq org-table-may-need-update t)
17287 (if org-display-custom-times
17288 (message "Time stamps are overlaid with custom format")
17289 (message "Time stamp overlays removed")))
17291 (defun org-display-custom-time (beg end)
17292 "Overlay modified time stamp format over timestamp between BEG and END."
17293 (let* ((ts (buffer-substring beg end))
17294 t1 w1 with-hm tf time str w2 (off 0))
17295 (save-match-data
17296 (setq t1 (org-parse-time-string ts t))
17297 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17298 (setq off (- (match-end 0) (match-beginning 0)))))
17299 (setq end (- end off))
17300 (setq w1 (- end beg)
17301 with-hm (and (nth 1 t1) (nth 2 t1))
17302 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17303 time (org-fix-decoded-time t1)
17304 str (org-add-props
17305 (format-time-string
17306 (substring tf 1 -1) (apply 'encode-time time))
17307 nil 'mouse-face 'highlight)
17308 w2 (length str))
17309 (unless (= w2 w1)
17310 (add-text-properties (1+ beg) (+ 2 beg)
17311 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17312 (if (featurep 'xemacs)
17313 (progn
17314 (put-text-property beg end 'invisible t)
17315 (put-text-property beg end 'end-glyph (make-glyph str)))
17316 (put-text-property beg end 'display str))))
17318 (defun org-fix-decoded-time (time)
17319 "Set 0 instead of nil for the first 6 elements of time.
17320 Don't touch the rest."
17321 (let ((n 0))
17322 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17324 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17326 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17327 "Difference between TIMESTAMP-STRING and now in days.
17328 If SECONDS is non-nil, return the difference in seconds."
17329 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17330 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17331 (funcall fdiff (current-time)))))
17333 (defun org-deadline-close (timestamp-string &optional ndays)
17334 "Is the time in TIMESTAMP-STRING close to the current date?"
17335 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17336 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17337 (not (org-entry-is-done-p))))
17339 (defun org-get-wdays (ts &optional delay zero-delay)
17340 "Get the deadline lead time appropriate for timestring TS.
17341 When DELAY is non-nil, get the delay time for scheduled items
17342 instead of the deadline lead time. When ZERO-DELAY is non-nil
17343 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17344 don't try to find the delay cookie in the scheduled timestamp."
17345 (let ((tv (if delay org-scheduled-delay-days
17346 org-deadline-warning-days)))
17347 (cond
17348 ((or (and delay (< tv 0))
17349 (and delay zero-delay (<= tv 0))
17350 (and (not delay) (<= tv 0)))
17351 ;; Enforce this value no matter what
17352 (- tv))
17353 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17354 ;; lead time is specified.
17355 (floor (* (string-to-number (match-string 1 ts))
17356 (cdr (assoc (match-string 2 ts)
17357 '(("d" . 1) ("w" . 7)
17358 ("m" . 30.4) ("y" . 365.25)
17359 ("h" . 0.041667)))))))
17360 ;; go for the default.
17361 (t tv))))
17363 (defun org-calendar-select-mouse (ev)
17364 "Return to `org-read-date' with the date currently selected.
17365 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17366 (interactive "e")
17367 (mouse-set-point ev)
17368 (when (calendar-cursor-to-date)
17369 (let* ((date (calendar-cursor-to-date))
17370 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17371 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17372 (when (active-minibuffer-window) (exit-minibuffer))))
17374 (defun org-check-deadlines (ndays)
17375 "Check if there are any deadlines due or past due.
17376 A deadline is considered due if it happens within `org-deadline-warning-days'
17377 days from today's date. If the deadline appears in an entry marked DONE,
17378 it is not shown. The prefix arg NDAYS can be used to test that many
17379 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17380 (interactive "P")
17381 (let* ((org-warn-days
17382 (cond
17383 ((equal ndays '(4)) 100000)
17384 (ndays (prefix-numeric-value ndays))
17385 (t (abs org-deadline-warning-days))))
17386 (case-fold-search nil)
17387 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17388 (callback
17389 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17390 (message "%d deadlines past-due or due within %d days"
17391 (org-occur regexp nil callback)
17392 org-warn-days)))
17394 (defsubst org-re-timestamp (type)
17395 "Return a regexp for timestamp TYPE.
17396 Allowed values for TYPE are:
17398 all: all timestamps
17399 active: only active timestamps (<...>)
17400 inactive: only inactive timestamps ([...])
17401 scheduled: only scheduled timestamps
17402 deadline: only deadline timestamps
17403 closed: only closed time-stamps
17405 When TYPE is nil, fall back on returning a regexp that matches
17406 both scheduled and deadline timestamps."
17407 (cl-case type
17408 (all org-ts-regexp-both)
17409 (active org-ts-regexp)
17410 (inactive org-ts-regexp-inactive)
17411 (scheduled org-scheduled-time-regexp)
17412 (deadline org-deadline-time-regexp)
17413 (closed org-closed-time-regexp)
17414 (otherwise
17415 (concat "\\<"
17416 (regexp-opt (list org-deadline-string org-scheduled-string))
17417 " *<\\([^>]+\\)>"))))
17419 (defun org-check-before-date (d)
17420 "Check if there are deadlines or scheduled entries before date D."
17421 (interactive (list (org-read-date)))
17422 (let* ((case-fold-search nil)
17423 (regexp (org-re-timestamp org-ts-type))
17424 (ts-type org-ts-type)
17425 (callback
17426 (lambda ()
17427 (let ((match (match-string 1)))
17428 (and (if (memq ts-type '(active inactive all))
17429 (eq (org-element-type (org-element-context)) 'timestamp)
17430 (org-at-planning-p))
17431 (time-less-p
17432 (org-time-string-to-time match)
17433 (org-time-string-to-time d)))))))
17434 (message "%d entries before %s"
17435 (org-occur regexp nil callback)
17436 d)))
17438 (defun org-check-after-date (d)
17439 "Check if there are deadlines or scheduled entries after date D."
17440 (interactive (list (org-read-date)))
17441 (let* ((case-fold-search nil)
17442 (regexp (org-re-timestamp org-ts-type))
17443 (ts-type org-ts-type)
17444 (callback
17445 (lambda ()
17446 (let ((match (match-string 1)))
17447 (and (if (memq ts-type '(active inactive all))
17448 (eq (org-element-type (org-element-context)) 'timestamp)
17449 (org-at-planning-p))
17450 (not (time-less-p
17451 (org-time-string-to-time match)
17452 (org-time-string-to-time d))))))))
17453 (message "%d entries after %s"
17454 (org-occur regexp nil callback)
17455 d)))
17457 (defun org-check-dates-range (start-date end-date)
17458 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17459 (interactive (list (org-read-date nil nil nil "Range starts")
17460 (org-read-date nil nil nil "Range end")))
17461 (let ((case-fold-search nil)
17462 (regexp (org-re-timestamp org-ts-type))
17463 (callback
17464 `(lambda ()
17465 (let ((match (match-string 1)))
17466 (and
17467 ,(if (memq org-ts-type '(active inactive all))
17468 '(eq (org-element-type (org-element-context)) 'timestamp)
17469 '(org-at-planning-p))
17470 (not (time-less-p
17471 (org-time-string-to-time match)
17472 (org-time-string-to-time start-date)))
17473 (time-less-p
17474 (org-time-string-to-time match)
17475 (org-time-string-to-time end-date)))))))
17476 (message "%d entries between %s and %s"
17477 (org-occur regexp nil callback) start-date end-date)))
17479 (defun org-evaluate-time-range (&optional to-buffer)
17480 "Evaluate a time range by computing the difference between start and end.
17481 Normally the result is just printed in the echo area, but with prefix arg
17482 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17483 If the time range is actually in a table, the result is inserted into the
17484 next column.
17485 For time difference computation, a year is assumed to be exactly 365
17486 days in order to avoid rounding problems."
17487 (interactive "P")
17489 (org-clock-update-time-maybe)
17490 (save-excursion
17491 (unless (org-at-date-range-p t)
17492 (goto-char (point-at-bol))
17493 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17494 (unless (org-at-date-range-p t)
17495 (user-error "Not at a time-stamp range, and none found in current line")))
17496 (let* ((ts1 (match-string 1))
17497 (ts2 (match-string 2))
17498 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17499 (match-end (match-end 0))
17500 (time1 (org-time-string-to-time ts1))
17501 (time2 (org-time-string-to-time ts2))
17502 (t1 (org-float-time time1))
17503 (t2 (org-float-time time2))
17504 (diff (abs (- t2 t1)))
17505 (negative (< (- t2 t1) 0))
17506 ;; (ys (floor (* 365 24 60 60)))
17507 (ds (* 24 60 60))
17508 (hs (* 60 60))
17509 (fy "%dy %dd %02d:%02d")
17510 (fy1 "%dy %dd")
17511 (fd "%dd %02d:%02d")
17512 (fd1 "%dd")
17513 (fh "%02d:%02d")
17514 y d h m align)
17515 (if havetime
17516 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17518 d (floor (/ diff ds)) diff (mod diff ds)
17519 h (floor (/ diff hs)) diff (mod diff hs)
17520 m (floor (/ diff 60)))
17521 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17523 d (floor (+ (/ diff ds) 0.5))
17524 h 0 m 0))
17525 (if (not to-buffer)
17526 (message "%s" (org-make-tdiff-string y d h m))
17527 (if (org-at-table-p)
17528 (progn
17529 (goto-char match-end)
17530 (setq align t)
17531 (and (looking-at " *|") (goto-char (match-end 0))))
17532 (goto-char match-end))
17533 (when (looking-at
17534 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17535 (replace-match ""))
17536 (when negative (insert " -"))
17537 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17538 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17539 (insert " " (format fh h m))))
17540 (when align (org-table-align))
17541 (message "Time difference inserted")))))
17543 (defun org-make-tdiff-string (y d h m)
17544 (let ((fmt "")
17545 (l nil))
17546 (when (> y 0)
17547 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17548 (push y l))
17549 (when (> d 0)
17550 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17551 (push d l))
17552 (when (> h 0)
17553 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17554 (push h l))
17555 (when (> m 0)
17556 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17557 (push m l))
17558 (apply 'format fmt (nreverse l))))
17560 (defun org-time-string-to-time (s &optional buffer pos)
17561 "Convert a timestamp string into internal time."
17562 (condition-case errdata
17563 (apply 'encode-time (org-parse-time-string s))
17564 (error (error "Bad timestamp `%s'%s\nError was: %s"
17565 s (if (not (and buffer pos))
17567 (format-message " at %d in buffer `%s'" pos buffer))
17568 (cdr errdata)))))
17570 (defun org-time-string-to-seconds (s)
17571 "Convert a timestamp string to a number of seconds."
17572 (org-float-time (org-time-string-to-time s)))
17574 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17576 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17577 "Convert time stamp S to an absolute day number.
17579 If DAYNR in non-nil, and there is a specifier for a cyclic time
17580 stamp, get the closest date to DAYNR. If PREFER is
17581 `past' (respectively `future') return a date past (respectively
17582 after) or equal to DAYNR.
17584 POS is the location of time stamp S, as a buffer position in
17585 BUFFER.
17587 Diary sexp timestamps are matched against DAYNR, when non-nil.
17588 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17589 signalled."
17590 (cond
17591 ((string-match "\\`%%\\((.*)\\)" s)
17592 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17593 ;; only able to match individual dates. If it fails, raise an
17594 ;; error.
17595 (if (and daynr
17596 (org-diary-sexp-entry
17597 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17598 daynr
17599 (signal 'org-diary-sexp-no-match (list s))))
17600 ((and daynr show-all) (org-closest-date s daynr prefer))
17601 (t (time-to-days
17602 (condition-case errdata
17603 (apply #'encode-time (org-parse-time-string s))
17604 (error (error "Bad timestamp `%s'%s\nError was: %s"
17606 (if (not (and buffer pos)) ""
17607 (format-message " at %d in buffer `%s'" pos buffer))
17608 (cdr errdata))))))))
17610 (defun org-days-to-iso-week (days)
17611 "Return the iso week number."
17612 (require 'cal-iso)
17613 (car (calendar-iso-from-absolute days)))
17615 (defun org-small-year-to-year (year)
17616 "Convert 2-digit years into 4-digit years.
17617 YEAR is expanded into one of the 30 next years, if possible, or
17618 into a past one. Any year larger than 99 is returned unchanged."
17619 (if (>= year 100) year
17620 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17621 (century (/ current 100))
17622 (offset (- year (% current 100))))
17623 (cond ((> offset 30) (+ (* (1- century) 100) year))
17624 ((> offset -70) (+ (* century 100) year))
17625 (t (+ (* (1+ century) 100) year))))))
17627 (defun org-time-from-absolute (d)
17628 "Return the time corresponding to date D.
17629 D may be an absolute day number, or a calendar-type list (month day year)."
17630 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17631 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17633 (defun org-calendar-holiday ()
17634 "List of holidays, for Diary display in Org mode."
17635 (declare (special date))
17636 (require 'holidays)
17637 (let ((hl (calendar-check-holidays date)))
17638 (and hl (mapconcat #'identity hl "; "))))
17640 (defun org-diary-sexp-entry (sexp entry d)
17641 "Process a SEXP diary ENTRY for date D."
17642 (require 'diary-lib)
17643 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17644 ;; dynamically.
17645 (let* ((sexp `(let ((entry ,entry)
17646 (date ',d))
17647 ,(car (read-from-string sexp))))
17648 (result (if calendar-debug-sexp (eval sexp)
17649 (condition-case nil
17650 (eval sexp)
17651 (error
17652 (beep)
17653 (message "Bad sexp at line %d in %s: %s"
17654 (org-current-line)
17655 (buffer-file-name) sexp)
17656 (sleep-for 2))))))
17657 (cond ((stringp result) (split-string result "; "))
17658 ((and (consp result)
17659 (not (consp (cdr result)))
17660 (stringp (cdr result))) (cdr result))
17661 ((and (consp result)
17662 (stringp (car result))) result)
17663 (result entry))))
17665 (defun org-diary-to-ical-string (frombuf)
17666 "Get iCalendar entries from diary entries in buffer FROMBUF.
17667 This uses the icalendar.el library."
17668 (let* ((tmpdir (if (featurep 'xemacs)
17669 (temp-directory)
17670 temporary-file-directory))
17671 (tmpfile (make-temp-name
17672 (expand-file-name "orgics" tmpdir)))
17673 buf rtn b e)
17674 (with-current-buffer frombuf
17675 (icalendar-export-region (point-min) (point-max) tmpfile)
17676 (setq buf (find-buffer-visiting tmpfile))
17677 (set-buffer buf)
17678 (goto-char (point-min))
17679 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17680 (setq b (match-beginning 0)))
17681 (goto-char (point-max))
17682 (when (re-search-backward "^END:VEVENT" nil t)
17683 (setq e (match-end 0)))
17684 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17685 (kill-buffer buf)
17686 (delete-file tmpfile)
17687 rtn))
17689 (defun org-closest-date (start current prefer)
17690 "Return closest date to CURRENT starting from START.
17692 CURRENT and START are both time stamps.
17694 When PREFER is `past', return a date that is either CURRENT or
17695 past. When PREFER is `future', return a date that is either
17696 CURRENT or future.
17698 Only time stamps with a repeater are modified. Any other time
17699 stamp stay unchanged. In any case, return value is an absolute
17700 day number."
17701 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17702 ;; No repeater. Do not shift time stamp.
17703 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17704 (let ((value (string-to-number (match-string 1 start)))
17705 (type (match-string 2 start)))
17706 (if (= 0 value)
17707 ;; Repeater with a 0-value is considered as void.
17708 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17709 (let* ((base (org-date-to-gregorian start))
17710 (target (org-date-to-gregorian current))
17711 (sday (calendar-absolute-from-gregorian base))
17712 (cday (calendar-absolute-from-gregorian target))
17713 n1 n2)
17714 ;; If START is already past CURRENT, just return START.
17715 (if (<= cday sday) sday
17716 ;; Compute closest date before (N1) and closest date past
17717 ;; (N2) CURRENT.
17718 (pcase type
17719 ("h"
17720 (let ((missing-hours
17721 (mod (+ (- (* 24 (- cday sday))
17722 (nth 2 (org-parse-time-string start)))
17723 org-extend-today-until)
17724 value)))
17725 (setf n1 (if (= missing-hours 0) cday
17726 (- cday (1+ (/ missing-hours 24)))))
17727 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17728 ((or "d" "w")
17729 (let ((value (if (equal type "w") (* 7 value) value)))
17730 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17731 (setf n2 (+ n1 value))))
17732 ("m"
17733 (let* ((add-months
17734 (lambda (d n)
17735 ;; Add N months to gregorian date D, i.e.,
17736 ;; a list (MONTH DAY YEAR). Return a valid
17737 ;; gregorian date.
17738 (let ((m (+ (nth 0 d) n)))
17739 (list (mod m 12)
17740 (nth 1 d)
17741 (+ (/ m 12) (nth 2 d))))))
17742 (months ; Complete months to TARGET.
17743 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17744 (- (nth 0 target) (nth 0 base))
17745 ;; If START's day is greater than
17746 ;; TARGET's, remove incomplete month.
17747 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17748 value)
17749 value))
17750 (before (funcall add-months base months)))
17751 (setf n1 (calendar-absolute-from-gregorian before))
17752 (setf n2
17753 (calendar-absolute-from-gregorian
17754 (funcall add-months before value)))))
17756 (let* ((d (nth 1 base))
17757 (m (nth 0 base))
17758 (y (nth 2 base))
17759 (years ; Complete years to TARGET.
17760 (* (/ (- (nth 2 target)
17762 ;; If START's month and day are
17763 ;; greater than TARGET's, remove
17764 ;; incomplete year.
17765 (if (or (> (nth 0 target) m)
17766 (and (= (nth 0 target) m)
17767 (> (nth 1 target) d)))
17770 value)
17771 value))
17772 (before (list m d (+ y years))))
17773 (setf n1 (calendar-absolute-from-gregorian before))
17774 (setf n2 (calendar-absolute-from-gregorian
17775 (list m d (+ (nth 2 before) value)))))))
17776 ;; Handle PREFER parameter, if any.
17777 (cond
17778 ((eq prefer 'past) (if (= cday n2) n2 n1))
17779 ((eq prefer 'future) (if (= cday n1) n1 n2))
17780 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17782 (defun org-date-to-gregorian (d)
17783 "Turn any specification of date D into a Gregorian date for the calendar."
17784 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17785 ((and (listp d) (= (length d) 3)) d)
17786 ((stringp d)
17787 (let ((d (org-parse-time-string d)))
17788 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17789 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17791 (defun org-parse-time-string (s &optional nodefault)
17792 "Parse the standard Org-mode time string.
17793 This should be a lot faster than the normal `parse-time-string'.
17794 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17795 hour and minute fields will be nil if not given."
17796 (cond ((string-match org-ts-regexp0 s)
17797 (list 0
17798 (when (or (match-beginning 8) (not nodefault))
17799 (string-to-number (or (match-string 8 s) "0")))
17800 (when (or (match-beginning 7) (not nodefault))
17801 (string-to-number (or (match-string 7 s) "0")))
17802 (string-to-number (match-string 4 s))
17803 (string-to-number (match-string 3 s))
17804 (string-to-number (match-string 2 s))
17805 nil nil nil))
17806 ((string-match "^<[^>]+>$" s)
17807 (decode-time (seconds-to-time (org-matcher-time s))))
17808 (t (error "Not a standard Org-mode time string: %s" s))))
17810 (defun org-timestamp-up (&optional arg)
17811 "Increase the date item at the cursor by one.
17812 If the cursor is on the year, change the year. If it is on the month,
17813 the day or the time, change that.
17814 With prefix ARG, change by that many units."
17815 (interactive "p")
17816 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17818 (defun org-timestamp-down (&optional arg)
17819 "Decrease the date item at the cursor by one.
17820 If the cursor is on the year, change the year. If it is on the month,
17821 the day or the time, change that.
17822 With prefix ARG, change by that many units."
17823 (interactive "p")
17824 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17826 (defun org-timestamp-up-day (&optional arg)
17827 "Increase the date in the time stamp by one day.
17828 With prefix ARG, change that many days."
17829 (interactive "p")
17830 (if (and (not (org-at-timestamp-p t))
17831 (org-at-heading-p))
17832 (org-todo 'up)
17833 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17835 (defun org-timestamp-down-day (&optional arg)
17836 "Decrease the date in the time stamp by one day.
17837 With prefix ARG, change that many days."
17838 (interactive "p")
17839 (if (and (not (org-at-timestamp-p t))
17840 (org-at-heading-p))
17841 (org-todo 'down)
17842 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17844 (defun org-at-timestamp-p (&optional inactive-ok)
17845 "Non-nil if point is inside a timestamp.
17847 When optional argument INACTIVE-OK is non-nil, also consider
17848 inactive timestamps.
17850 When this function returns a non-nil value, match data is set
17851 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17852 INACTIVE-OK."
17853 (interactive)
17854 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17855 (pos (point))
17856 (ans (or (looking-at tsr)
17857 (save-excursion
17858 (skip-chars-backward "^[<\n\r\t")
17859 (when (> (point) (point-min)) (backward-char 1))
17860 (and (looking-at tsr)
17861 (> (- (match-end 0) pos) -1))))))
17862 (and ans
17863 (boundp 'org-ts-what)
17864 (setq org-ts-what
17865 (cond
17866 ((= pos (match-beginning 0)) 'bracket)
17867 ;; Point is considered to be "on the bracket" whether
17868 ;; it's really on it or right after it.
17869 ((= pos (1- (match-end 0))) 'bracket)
17870 ((= pos (match-end 0)) 'after)
17871 ((org-pos-in-match-range pos 2) 'year)
17872 ((org-pos-in-match-range pos 3) 'month)
17873 ((org-pos-in-match-range pos 7) 'hour)
17874 ((org-pos-in-match-range pos 8) 'minute)
17875 ((or (org-pos-in-match-range pos 4)
17876 (org-pos-in-match-range pos 5)) 'day)
17877 ((and (> pos (or (match-end 8) (match-end 5)))
17878 (< pos (match-end 0)))
17879 (- pos (or (match-end 8) (match-end 5))))
17880 (t 'day))))
17881 ans))
17883 (defun org-toggle-timestamp-type ()
17884 "Toggle the type (<active> or [inactive]) of a time stamp."
17885 (interactive)
17886 (when (org-at-timestamp-p t)
17887 (let ((beg (match-beginning 0)) (end (match-end 0))
17888 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17889 (save-excursion
17890 (goto-char beg)
17891 (while (re-search-forward "[][<>]" end t)
17892 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17893 t t)))
17894 (message "Timestamp is now %sactive"
17895 (if (equal (char-after beg) ?<) "" "in")))))
17897 (defun org-at-clock-log-p nil
17898 "Is the cursor on the clock log line?"
17899 (save-excursion
17900 (move-beginning-of-line 1)
17901 (looking-at org-clock-line-re)))
17903 (defvar org-clock-history) ; defined in org-clock.el
17904 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17905 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17906 "Change the date in the time stamp at point.
17907 The date will be changed by N times WHAT. WHAT can be `day', `month',
17908 `year', `minute', `second'. If WHAT is not given, the cursor position
17909 in the timestamp determines what will be changed.
17910 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17911 (let ((origin (point)) origin-cat
17912 with-hm inactive
17913 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17914 org-ts-what
17915 extra rem
17916 ts time time0 fixnext clrgx)
17917 (unless (org-at-timestamp-p t)
17918 (user-error "Not at a timestamp"))
17919 (if (and (not what) (eq org-ts-what 'bracket))
17920 (org-toggle-timestamp-type)
17921 ;; Point isn't on brackets. Remember the part of the time-stamp
17922 ;; the point was in. Indeed, size of time-stamps may change,
17923 ;; but point must be kept in the same category nonetheless.
17924 (setq origin-cat org-ts-what)
17925 (when (and (not what) (not (eq org-ts-what 'day))
17926 org-display-custom-times
17927 (get-text-property (point) 'display)
17928 (not (get-text-property (1- (point)) 'display)))
17929 (setq org-ts-what 'day))
17930 (setq org-ts-what (or what org-ts-what)
17931 inactive (= (char-after (match-beginning 0)) ?\[)
17932 ts (match-string 0))
17933 (replace-match "")
17934 (when (string-match
17935 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17937 (setq extra (match-string 1 ts))
17938 (when suppress-tmp-delay
17939 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17940 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17941 (setq with-hm t))
17942 (setq time0 (org-parse-time-string ts))
17943 (when (and updown
17944 (eq org-ts-what 'minute)
17945 (not current-prefix-arg))
17946 ;; This looks like s-up and s-down. Change by one rounding step.
17947 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17948 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17949 (setcar (cdr time0) (+ (nth 1 time0)
17950 (if (> n 0) (- rem) (- dm rem))))))
17951 (setq time
17952 (encode-time (or (car time0) 0)
17953 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17954 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17955 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17956 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17957 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17958 (nthcdr 6 time0)))
17959 (when (and (member org-ts-what '(hour minute))
17960 extra
17961 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17962 (setq extra (org-modify-ts-extra
17963 extra
17964 (if (eq org-ts-what 'hour) 2 5)
17965 n dm)))
17966 (when (integerp org-ts-what)
17967 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17968 (when (eq what 'calendar)
17969 (let ((cal-date (org-get-date-from-calendar)))
17970 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17971 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17972 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17973 (setcar time0 (or (car time0) 0))
17974 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17975 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17976 (setq time (apply 'encode-time time0))))
17977 ;; Insert the new time-stamp, and ensure point stays in the same
17978 ;; category as before (i.e. not after the last position in that
17979 ;; category).
17980 (let ((pos (point)))
17981 ;; Stay before inserted string. `save-excursion' is of no use.
17982 (setq org-last-changed-timestamp
17983 (org-insert-time-stamp time with-hm inactive nil nil extra))
17984 (goto-char pos))
17985 (save-match-data
17986 (looking-at org-ts-regexp3)
17987 (goto-char (cond
17988 ;; `day' category ends before `hour' if any, or at
17989 ;; the end of the day name.
17990 ((eq origin-cat 'day)
17991 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17992 ((eq origin-cat 'hour) (min (match-end 7) origin))
17993 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17994 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17995 ;; `year' and `month' have both fixed size: point
17996 ;; couldn't have moved into another part.
17997 (t origin))))
17998 ;; Update clock if on a CLOCK line.
17999 (org-clock-update-time-maybe)
18000 ;; Maybe adjust the closest clock in `org-clock-history'
18001 (when org-clock-adjust-closest
18002 (if (not (and (org-at-clock-log-p)
18003 (< 1 (length (delq nil (mapcar 'marker-position
18004 org-clock-history))))))
18005 (message "No clock to adjust")
18006 (cond ((save-excursion ; fix previous clock?
18007 (re-search-backward org-ts-regexp0 nil t)
18008 (org-looking-back (concat org-clock-string " \\[")
18009 (line-beginning-position)))
18010 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18011 ((save-excursion ; fix next clock?
18012 (re-search-backward org-ts-regexp0 nil t)
18013 (looking-at (concat org-ts-regexp0 "\\] =>")))
18014 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18015 (save-window-excursion
18016 ;; Find closest clock to point, adjust the previous/next one in history
18017 (let* ((p (save-excursion (org-back-to-heading t)))
18018 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18019 (clfixnth
18020 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18021 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18022 (if (not clfixpos)
18023 (message "No clock to adjust")
18024 (save-excursion
18025 (org-goto-marker-or-bmk clfixpos)
18026 (org-show-subtree)
18027 (when (re-search-forward clrgx nil t)
18028 (goto-char (match-beginning 1))
18029 (let (org-clock-adjust-closest)
18030 (org-timestamp-change n org-ts-what updown))
18031 (message "Clock adjusted in %s for heading: %s"
18032 (file-name-nondirectory (buffer-file-name))
18033 (org-get-heading t t)))))))))
18034 ;; Try to recenter the calendar window, if any.
18035 (when (and org-calendar-follow-timestamp-change
18036 (get-buffer-window "*Calendar*" t)
18037 (memq org-ts-what '(day month year)))
18038 (org-recenter-calendar (time-to-days time))))))
18040 (defun org-modify-ts-extra (s pos n dm)
18041 "Change the different parts of the lead-time and repeat fields in timestamp."
18042 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18043 ng h m new rem)
18044 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18045 (cond
18046 ((or (org-pos-in-match-range pos 2)
18047 (org-pos-in-match-range pos 3))
18048 (setq m (string-to-number (match-string 3 s))
18049 h (string-to-number (match-string 2 s)))
18050 (if (org-pos-in-match-range pos 2)
18051 (setq h (+ h n))
18052 (setq n (* dm (org-no-warnings (signum n))))
18053 (unless (= 0 (setq rem (% m dm)))
18054 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18055 (setq m (+ m n)))
18056 (when (< m 0) (setq m (+ m 60) h (1- h)))
18057 (when (> m 59) (setq m (- m 60) h (1+ h)))
18058 (setq h (mod h 24))
18059 (setq ng 1 new (format "-%02d:%02d" h m)))
18060 ((org-pos-in-match-range pos 6)
18061 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18062 ((org-pos-in-match-range pos 5)
18063 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18065 ((org-pos-in-match-range pos 9)
18066 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18067 ((org-pos-in-match-range pos 8)
18068 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18070 (when ng
18071 (setq s (concat
18072 (substring s 0 (match-beginning ng))
18074 (substring s (match-end ng))))))
18077 (defun org-recenter-calendar (d)
18078 "If the calendar is visible, recenter it to date D."
18079 (let ((cwin (get-buffer-window "*Calendar*" t)))
18080 (when cwin
18081 (let ((calendar-move-hook nil))
18082 (with-selected-window cwin
18083 (calendar-goto-date
18084 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18086 (defun org-goto-calendar (&optional arg)
18087 "Go to the Emacs calendar at the current date.
18088 If there is a time stamp in the current line, go to that date.
18089 A prefix ARG can be used to force the current date."
18090 (interactive "P")
18091 (let ((tsr org-ts-regexp) diff
18092 (calendar-move-hook nil)
18093 (calendar-view-holidays-initially-flag nil)
18094 (calendar-view-diary-initially-flag nil))
18095 (when (or (org-at-timestamp-p)
18096 (save-excursion
18097 (beginning-of-line 1)
18098 (looking-at (concat ".*" tsr))))
18099 (let ((d1 (time-to-days (current-time)))
18100 (d2 (time-to-days
18101 (org-time-string-to-time (match-string 1)))))
18102 (setq diff (- d2 d1))))
18103 (calendar)
18104 (calendar-goto-today)
18105 (when (and diff (not arg)) (calendar-forward-day diff))))
18107 (defun org-get-date-from-calendar ()
18108 "Return a list (month day year) of date at point in calendar."
18109 (with-current-buffer "*Calendar*"
18110 (save-match-data
18111 (calendar-cursor-to-date))))
18113 (defun org-date-from-calendar ()
18114 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18115 If there is already a time stamp at the cursor position, update it."
18116 (interactive)
18117 (if (org-at-timestamp-p t)
18118 (org-timestamp-change 0 'calendar)
18119 (let ((cal-date (org-get-date-from-calendar)))
18120 (org-insert-time-stamp
18121 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18123 (defcustom org-effort-durations
18124 `(("min" . 1)
18125 ("h" . 60)
18126 ("d" . ,(* 60 8))
18127 ("w" . ,(* 60 8 5))
18128 ("m" . ,(* 60 8 5 4))
18129 ("y" . ,(* 60 8 5 40)))
18130 "Conversion factor to minutes for an effort modifier.
18132 Each entry has the form (MODIFIER . MINUTES).
18134 In an effort string, a number followed by MODIFIER is multiplied
18135 by the specified number of MINUTES to obtain an effort in
18136 minutes.
18138 For example, if the value of this variable is ((\"hours\" . 60)), then an
18139 effort string \"2hours\" is equivalent to 120 minutes."
18140 :group 'org-agenda
18141 :version "25.1"
18142 :package-version '(Org . "8.3")
18143 :type '(alist :key-type (string :tag "Modifier")
18144 :value-type (number :tag "Minutes")))
18146 (defun org-minutes-to-clocksum-string (m)
18147 "Format number of minutes as a clocksum string.
18148 The format is determined by `org-time-clocksum-format',
18149 `org-time-clocksum-use-fractional' and
18150 `org-time-clocksum-fractional-format' and
18151 `org-time-clocksum-use-effort-durations'."
18152 (let ((clocksum "")
18153 (m (round m)) ; Don't allow fractions of minutes
18154 h d w mo y fmt n)
18155 (setq h (if org-time-clocksum-use-effort-durations
18156 (cdr (assoc "h" org-effort-durations)) 60)
18157 d (if org-time-clocksum-use-effort-durations
18158 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18159 w (if org-time-clocksum-use-effort-durations
18160 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18161 mo (if org-time-clocksum-use-effort-durations
18162 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18163 y (if org-time-clocksum-use-effort-durations
18164 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18165 ;; fractional format
18166 (if org-time-clocksum-use-fractional
18167 (cond
18168 ;; single format string
18169 ((stringp org-time-clocksum-fractional-format)
18170 (format org-time-clocksum-fractional-format (/ m (float h))))
18171 ;; choice of fractional formats for different time units
18172 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18173 (> (/ (truncate m) (* y d h)) 0))
18174 (format fmt (/ m (* y d (float h)))))
18175 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18176 (> (/ (truncate m) (* mo d h)) 0))
18177 (format fmt (/ m (* mo d (float h)))))
18178 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18179 (> (/ (truncate m) (* w d h)) 0))
18180 (format fmt (/ m (* w d (float h)))))
18181 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18182 (> (/ (truncate m) (* d h)) 0))
18183 (format fmt (/ m (* d (float h)))))
18184 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18185 (> (/ (truncate m) h) 0))
18186 (format fmt (/ m (float h))))
18187 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18188 (format fmt m))
18189 ;; fall back to smallest time unit with a format
18190 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18191 (format fmt (/ m (float h))))
18192 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18193 (format fmt (/ m (* d (float h)))))
18194 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18195 (format fmt (/ m (* w d (float h)))))
18196 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18197 (format fmt (/ m (* mo d (float h)))))
18198 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18199 (format fmt (/ m (* y d (float h))))))
18200 ;; standard (non-fractional) format, with single format string
18201 (if (stringp org-time-clocksum-format)
18202 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18203 ;; separate formats components
18204 (and (setq fmt (plist-get org-time-clocksum-format :years))
18205 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18206 (plist-get org-time-clocksum-format :require-years))
18207 (setq clocksum (concat clocksum (format fmt n))
18208 m (- m (* n y d h))))
18209 (and (setq fmt (plist-get org-time-clocksum-format :months))
18210 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18211 (plist-get org-time-clocksum-format :require-months))
18212 (setq clocksum (concat clocksum (format fmt n))
18213 m (- m (* n mo d h))))
18214 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18215 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18216 (plist-get org-time-clocksum-format :require-weeks))
18217 (setq clocksum (concat clocksum (format fmt n))
18218 m (- m (* n w d h))))
18219 (and (setq fmt (plist-get org-time-clocksum-format :days))
18220 (or (> (setq n (/ (truncate m) (* d h))) 0)
18221 (plist-get org-time-clocksum-format :require-days))
18222 (setq clocksum (concat clocksum (format fmt n))
18223 m (- m (* n d h))))
18224 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18225 (or (> (setq n (/ (truncate m) h)) 0)
18226 (plist-get org-time-clocksum-format :require-hours))
18227 (setq clocksum (concat clocksum (format fmt n))
18228 m (- m (* n h))))
18229 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18230 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18231 (setq clocksum (concat clocksum (format fmt m))))
18232 ;; return formatted time duration
18233 clocksum))))
18235 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18236 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18237 "Org mode version 8.0")
18239 (defun org-hours-to-clocksum-string (n)
18240 (org-minutes-to-clocksum-string (* n 60)))
18242 (defun org-hh:mm-string-to-minutes (s)
18243 "Convert a string H:MM to a number of minutes.
18244 If the string is just a number, interpret it as minutes.
18245 In fact, the first hh:mm or number in the string will be taken,
18246 there can be extra stuff in the string.
18247 If no number is found, the return value is 0."
18248 (cond
18249 ((integerp s) s)
18250 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18251 (+ (* (string-to-number (match-string 1 s)) 60)
18252 (string-to-number (match-string 2 s))))
18253 ((string-match "\\([0-9]+\\)" s)
18254 (string-to-number (match-string 1 s)))
18255 (t 0)))
18257 (defcustom org-image-actual-width t
18258 "Should we use the actual width of images when inlining them?
18260 When set to t, always use the image width.
18262 When set to a number, use imagemagick (when available) to set
18263 the image's width to this value.
18265 When set to a number in a list, try to get the width from any
18266 #+ATTR.* keyword if it matches a width specification like
18268 #+ATTR_HTML: :width 300px
18270 and fall back on that number if none is found.
18272 When set to nil, try to get the width from an #+ATTR.* keyword
18273 and fall back on the original width if none is found.
18275 This requires Emacs >= 24.1, build with imagemagick support."
18276 :group 'org-appearance
18277 :version "24.4"
18278 :package-version '(Org . "8.0")
18279 :type '(choice
18280 (const :tag "Use the image width" t)
18281 (integer :tag "Use a number of pixels")
18282 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18283 (const :tag "Use #+ATTR* or don't resize" nil)))
18285 (defcustom org-agenda-inhibit-startup nil
18286 "Inhibit startup when preparing agenda buffers.
18287 When this variable is t, the initialization of the Org agenda
18288 buffers is inhibited: e.g. the visibility state is not set, the
18289 tables are not re-aligned, etc."
18290 :type 'boolean
18291 :version "24.3"
18292 :group 'org-agenda)
18294 (define-obsolete-variable-alias
18295 'org-agenda-ignore-drawer-properties
18296 'org-agenda-ignore-properties "25.1")
18298 (defcustom org-agenda-ignore-properties nil
18299 "Avoid updating text properties when building the agenda.
18300 Properties are used to prepare buffers for effort estimates,
18301 appointments, statistics and subtree-local categories.
18302 If you don't use these in the agenda, you can add them to this
18303 list and agenda building will be a bit faster.
18304 The value is a list, with zero or more of the symbols `effort', `appt',
18305 `stats' or `category'."
18306 :type '(set :greedy t
18307 (const effort)
18308 (const appt)
18309 (const stats)
18310 (const category))
18311 :version "25.1"
18312 :package-version '(Org . "8.3")
18313 :group 'org-agenda)
18315 (defun org-duration-string-to-minutes (s &optional output-to-string)
18316 "Convert a duration string S to minutes.
18318 A bare number is interpreted as minutes, modifiers can be set by
18319 customizing `org-effort-durations' (which see).
18321 Entries containing a colon are interpreted as H:MM by
18322 `org-hh:mm-string-to-minutes'."
18323 (let ((result 0)
18324 (re (concat "\\([0-9.]+\\) *\\("
18325 (regexp-opt (mapcar 'car org-effort-durations))
18326 "\\)")))
18327 (while (string-match re s)
18328 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18329 (string-to-number (match-string 1 s))))
18330 (setq s (replace-match "" nil t s)))
18331 (setq result (floor result))
18332 (cl-incf result (org-hh:mm-string-to-minutes s))
18333 (if output-to-string (number-to-string result) result)))
18335 ;;;; Files
18337 (defun org-save-all-org-buffers ()
18338 "Save all Org-mode buffers without user confirmation."
18339 (interactive)
18340 (message "Saving all Org-mode buffers...")
18341 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18342 (when (featurep 'org-id) (org-id-locations-save))
18343 (message "Saving all Org-mode buffers... done"))
18345 (defun org-revert-all-org-buffers ()
18346 "Revert all Org-mode buffers.
18347 Prompt for confirmation when there are unsaved changes.
18348 Be sure you know what you are doing before letting this function
18349 overwrite your changes.
18351 This function is useful in a setup where one tracks org files
18352 with a version control system, to revert on one machine after pulling
18353 changes from another. I believe the procedure must be like this:
18355 1. M-x org-save-all-org-buffers
18356 2. Pull changes from the other machine, resolve conflicts
18357 3. M-x org-revert-all-org-buffers"
18358 (interactive)
18359 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18360 (user-error "Abort"))
18361 (save-excursion
18362 (save-window-excursion
18363 (dolist (b (buffer-list))
18364 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18365 (with-current-buffer b buffer-file-name))
18366 (org-pop-to-buffer-same-window b)
18367 (revert-buffer t 'no-confirm)))
18368 (when (and (featurep 'org-id) org-id-track-globally)
18369 (org-id-locations-load)))))
18371 ;;;; Agenda files
18373 ;;;###autoload
18374 (defun org-switchb (&optional arg)
18375 "Switch between Org buffers.
18377 With \\[universal-argument] prefix, restrict available buffers to files.
18379 With \\[universal-argument] \\[universal-argument] \
18380 prefix, restrict available buffers to agenda files."
18381 (interactive "P")
18382 (let ((blist (org-buffer-list
18383 (cond ((equal arg '(4)) 'files)
18384 ((equal arg '(16)) 'agenda)))))
18385 (org-pop-to-buffer-same-window
18386 (completing-read "Org buffer: "
18387 (mapcar #'list (mapcar #'buffer-name blist))
18388 nil t))))
18390 (defun org-buffer-list (&optional predicate exclude-tmp)
18391 "Return a list of Org buffers.
18392 PREDICATE can be `export', `files' or `agenda'.
18394 export restrict the list to Export buffers.
18395 files restrict the list to buffers visiting Org files.
18396 agenda restrict the list to buffers visiting agenda files.
18398 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18399 (let* ((bfn nil)
18400 (agenda-files (and (eq predicate 'agenda)
18401 (mapcar 'file-truename (org-agenda-files t))))
18402 (filter
18403 (cond
18404 ((eq predicate 'files)
18405 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18406 ((eq predicate 'export)
18407 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18408 ((eq predicate 'agenda)
18409 (lambda (b)
18410 (with-current-buffer b
18411 (and (derived-mode-p 'org-mode)
18412 (setq bfn (buffer-file-name b))
18413 (member (file-truename bfn) agenda-files)))))
18414 (t (lambda (b) (with-current-buffer b
18415 (or (derived-mode-p 'org-mode)
18416 (string-match "\\*Org .*Export"
18417 (buffer-name b)))))))))
18418 (delq nil
18419 (mapcar
18420 (lambda(b)
18421 (if (and (funcall filter b)
18422 (or (not exclude-tmp)
18423 (not (string-match "tmp" (buffer-name b)))))
18425 nil))
18426 (buffer-list)))))
18428 (defun org-agenda-files (&optional unrestricted archives)
18429 "Get the list of agenda files.
18430 Optional UNRESTRICTED means return the full list even if a restriction
18431 is currently in place.
18432 When ARCHIVES is t, include all archive files that are really being
18433 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18434 `org-agenda-archives-mode' is t."
18435 (let ((files
18436 (cond
18437 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18438 ((stringp org-agenda-files) (org-read-agenda-file-list))
18439 ((listp org-agenda-files) org-agenda-files)
18440 (t (error "Invalid value of `org-agenda-files'")))))
18441 (setq files (apply 'append
18442 (mapcar (lambda (f)
18443 (if (file-directory-p f)
18444 (directory-files
18445 f t org-agenda-file-regexp)
18446 (list f)))
18447 files)))
18448 (when org-agenda-skip-unavailable-files
18449 (setq files (delq nil
18450 (mapcar (function
18451 (lambda (file)
18452 (and (file-readable-p file) file)))
18453 files))))
18454 (when (or (eq archives t)
18455 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18456 (setq files (org-add-archive-files files)))
18457 files))
18459 (defun org-agenda-file-p (&optional file)
18460 "Return non-nil, if FILE is an agenda file.
18461 If FILE is omitted, use the file associated with the current
18462 buffer."
18463 (let ((fname (or file (buffer-file-name))))
18464 (and fname
18465 (member (file-truename fname)
18466 (mapcar #'file-truename (org-agenda-files t))))))
18468 (defun org-edit-agenda-file-list ()
18469 "Edit the list of agenda files.
18470 Depending on setup, this either uses customize to edit the variable
18471 `org-agenda-files', or it visits the file that is holding the list. In the
18472 latter case, the buffer is set up in a way that saving it automatically kills
18473 the buffer and restores the previous window configuration."
18474 (interactive)
18475 (if (stringp org-agenda-files)
18476 (let ((cw (current-window-configuration)))
18477 (find-file org-agenda-files)
18478 (setq-local org-window-configuration cw)
18479 (org-add-hook 'after-save-hook
18480 (lambda ()
18481 (set-window-configuration
18482 (prog1 org-window-configuration
18483 (kill-buffer (current-buffer))))
18484 (org-install-agenda-files-menu)
18485 (message "New agenda file list installed"))
18486 nil 'local)
18487 (message "%s" (substitute-command-keys
18488 "Edit list and finish with \\[save-buffer]")))
18489 (customize-variable 'org-agenda-files)))
18491 (defun org-store-new-agenda-file-list (list)
18492 "Set new value for the agenda file list and save it correctly."
18493 (if (stringp org-agenda-files)
18494 (let ((fe (org-read-agenda-file-list t)) b u)
18495 (while (setq b (find-buffer-visiting org-agenda-files))
18496 (kill-buffer b))
18497 (with-temp-file org-agenda-files
18498 (insert
18499 (mapconcat
18500 (lambda (f) ;; Keep un-expanded entries.
18501 (if (setq u (assoc f fe))
18502 (cdr u)
18504 list "\n")
18505 "\n")))
18506 (let ((org-mode-hook nil) (org-inhibit-startup t)
18507 (org-insert-mode-line-in-empty-file nil))
18508 (setq org-agenda-files list)
18509 (customize-save-variable 'org-agenda-files org-agenda-files))))
18511 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18512 "Read the list of agenda files from a file.
18513 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18514 filenames, used by `org-store-new-agenda-file-list' to write back
18515 un-expanded file names."
18516 (when (file-directory-p org-agenda-files)
18517 (error "`org-agenda-files' cannot be a single directory"))
18518 (when (stringp org-agenda-files)
18519 (with-temp-buffer
18520 (insert-file-contents org-agenda-files)
18521 (mapcar
18522 (lambda (f)
18523 (let ((e (expand-file-name (substitute-in-file-name f)
18524 org-directory)))
18525 (if pair-with-expansion
18526 (cons e f)
18527 e)))
18528 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18530 ;;;###autoload
18531 (defun org-cycle-agenda-files ()
18532 "Cycle through the files in `org-agenda-files'.
18533 If the current buffer visits an agenda file, find the next one in the list.
18534 If the current buffer does not, find the first agenda file."
18535 (interactive)
18536 (let* ((fs (or (org-agenda-files t)
18537 (user-error "No agenda files")))
18538 (files (copy-sequence fs))
18539 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18540 file)
18541 (when tcf
18542 (while (and (setq file (pop files))
18543 (not (equal (file-truename file) tcf)))))
18544 (find-file (car (or files fs)))
18545 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18547 (defun org-agenda-file-to-front (&optional to-end)
18548 "Move/add the current file to the top of the agenda file list.
18549 If the file is not present in the list, it is added to the front. If it is
18550 present, it is moved there. With optional argument TO-END, add/move to the
18551 end of the list."
18552 (interactive "P")
18553 (let ((org-agenda-skip-unavailable-files nil)
18554 (file-alist (mapcar (lambda (x)
18555 (cons (file-truename x) x))
18556 (org-agenda-files t)))
18557 (ctf (file-truename
18558 (or buffer-file-name
18559 (user-error "Please save the current buffer to a file"))))
18560 x had)
18561 (setq x (assoc ctf file-alist) had x)
18563 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18564 (if to-end
18565 (setq file-alist (append (delq x file-alist) (list x)))
18566 (setq file-alist (cons x (delq x file-alist))))
18567 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18568 (org-install-agenda-files-menu)
18569 (message "File %s to %s of agenda file list"
18570 (if had "moved" "added") (if to-end "end" "front"))))
18572 (defun org-remove-file (&optional file)
18573 "Remove current file from the list of files in variable `org-agenda-files'.
18574 These are the files which are being checked for agenda entries.
18575 Optional argument FILE means use this file instead of the current."
18576 (interactive)
18577 (let* ((org-agenda-skip-unavailable-files nil)
18578 (file (or file buffer-file-name
18579 (user-error "Current buffer does not visit a file")))
18580 (true-file (file-truename file))
18581 (afile (abbreviate-file-name file))
18582 (files (delq nil (mapcar
18583 (lambda (x)
18584 (unless (equal true-file
18585 (file-truename x))
18587 (org-agenda-files t)))))
18588 (if (not (= (length files) (length (org-agenda-files t))))
18589 (progn
18590 (org-store-new-agenda-file-list files)
18591 (org-install-agenda-files-menu)
18592 (message "Removed from Org Agenda list: %s" afile))
18593 (message "File was not in list: %s (not removed)" afile))))
18595 (defun org-file-menu-entry (file)
18596 (vector file (list 'find-file file) t))
18598 (defun org-check-agenda-file (file)
18599 "Make sure FILE exists. If not, ask user what to do."
18600 (unless (file-exists-p file)
18601 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18602 (abbreviate-file-name file))
18603 (let ((r (downcase (read-char-exclusive))))
18604 (cond
18605 ((equal r ?r)
18606 (org-remove-file file)
18607 (throw 'nextfile t))
18608 (t (user-error "Abort"))))))
18610 (defun org-get-agenda-file-buffer (file)
18611 "Get an agenda buffer visiting FILE.
18612 If the buffer needs to be created, add it to the list of buffers
18613 which might be released later."
18614 (let ((buf (org-find-base-buffer-visiting file)))
18615 (if buf
18616 buf ; just return it
18617 ;; Make a new buffer and remember it
18618 (setq buf (find-file-noselect file))
18619 (when buf (push buf org-agenda-new-buffers))
18620 buf)))
18622 (defun org-release-buffers (blist)
18623 "Release all buffers in list, asking the user for confirmation when needed.
18624 When a buffer is unmodified, it is just killed. When modified, it is saved
18625 \(if the user agrees) and then killed."
18626 (let (file)
18627 (dolist (buf blist)
18628 (setq file (buffer-file-name buf))
18629 (when (and (buffer-modified-p buf)
18630 file
18631 (y-or-n-p (format "Save file %s? " file)))
18632 (with-current-buffer buf (save-buffer)))
18633 (kill-buffer buf))))
18635 (defun org-agenda-prepare-buffers (files)
18636 "Create buffers for all agenda files, protect archived trees and comments."
18637 (interactive)
18638 (let ((pa '(:org-archived t))
18639 (pc '(:org-comment t))
18640 (pall '(:org-archived t :org-comment t))
18641 (inhibit-read-only t)
18642 (org-inhibit-startup org-agenda-inhibit-startup)
18643 (rea (concat ":" org-archive-tag ":"))
18644 re pos)
18645 (setq org-tag-alist-for-agenda nil
18646 org-tag-groups-alist-for-agenda nil)
18647 (save-excursion
18648 (save-restriction
18649 (dolist (file files)
18650 (catch 'nextfile
18651 (if (bufferp file)
18652 (set-buffer file)
18653 (org-check-agenda-file file)
18654 (set-buffer (org-get-agenda-file-buffer file)))
18655 (widen)
18656 (org-set-regexps-and-options 'tags-only)
18657 (setq pos (point))
18658 (or (memq 'category org-agenda-ignore-properties)
18659 (org-refresh-category-properties))
18660 (or (memq 'stats org-agenda-ignore-properties)
18661 (org-refresh-stats-properties))
18662 (or (memq 'effort org-agenda-ignore-properties)
18663 (org-refresh-effort-properties))
18664 (or (memq 'appt org-agenda-ignore-properties)
18665 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18666 (setq org-todo-keywords-for-agenda
18667 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18668 (setq org-done-keywords-for-agenda
18669 (append org-done-keywords-for-agenda org-done-keywords))
18670 (setq org-todo-keyword-alist-for-agenda
18671 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18672 (setq org-tag-alist-for-agenda
18673 (org-uniquify
18674 (append org-tag-alist-for-agenda
18675 org-tag-alist
18676 org-tag-persistent-alist)))
18677 ;; Merge current file's tag groups into global
18678 ;; `org-tag-groups-alist-for-agenda'.
18679 (when org-group-tags
18680 (dolist (alist org-tag-groups-alist)
18681 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18682 (if old
18683 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18684 (push alist org-tag-groups-alist-for-agenda)))))
18685 (org-with-silent-modifications
18686 (save-excursion
18687 (remove-text-properties (point-min) (point-max) pall)
18688 (when org-agenda-skip-archived-trees
18689 (goto-char (point-min))
18690 (while (re-search-forward rea nil t)
18691 (when (org-at-heading-p t)
18692 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18693 (goto-char (point-min))
18694 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18695 (while (re-search-forward re nil t)
18696 (when (save-match-data (org-in-commented-heading-p t))
18697 (add-text-properties
18698 (match-beginning 0) (org-end-of-subtree t) pc)))))
18699 (goto-char pos)))))
18700 (setq org-todo-keywords-for-agenda
18701 (org-uniquify org-todo-keywords-for-agenda))
18702 (setq org-todo-keyword-alist-for-agenda
18703 (org-uniquify org-todo-keyword-alist-for-agenda))))
18706 ;;;; CDLaTeX minor mode
18708 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18709 "Keymap for the minor `org-cdlatex-mode'.")
18711 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18712 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18713 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18714 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18715 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18717 (defvar org-cdlatex-texmathp-advice-is-done nil
18718 "Flag remembering if we have applied the advice to texmathp already.")
18720 (define-minor-mode org-cdlatex-mode
18721 "Toggle the minor `org-cdlatex-mode'.
18722 This mode supports entering LaTeX environment and math in LaTeX fragments
18723 in Org-mode.
18724 \\{org-cdlatex-mode-map}"
18725 nil " OCDL" nil
18726 (when org-cdlatex-mode
18727 (require 'cdlatex)
18728 (run-hooks 'cdlatex-mode-hook)
18729 (cdlatex-compute-tables))
18730 (unless org-cdlatex-texmathp-advice-is-done
18731 (setq org-cdlatex-texmathp-advice-is-done t)
18732 (defadvice texmathp (around org-math-always-on activate)
18733 "Always return t in org-mode buffers.
18734 This is because we want to insert math symbols without dollars even outside
18735 the LaTeX math segments. If Orgmode thinks that point is actually inside
18736 an embedded LaTeX fragment, let texmathp do its job.
18737 \\[org-cdlatex-mode-map]"
18738 (interactive)
18739 (let (p)
18740 (cond
18741 ((not (derived-mode-p 'org-mode)) ad-do-it)
18742 ((eq this-command 'cdlatex-math-symbol)
18743 (setq ad-return-value t
18744 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18746 (let ((p (org-inside-LaTeX-fragment-p)))
18747 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18748 (setq ad-return-value t
18749 texmathp-why '("Org-mode embedded math" . 0))
18750 (when p ad-do-it)))))))))
18752 (defun turn-on-org-cdlatex ()
18753 "Unconditionally turn on `org-cdlatex-mode'."
18754 (org-cdlatex-mode 1))
18756 (defun org-try-cdlatex-tab ()
18757 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18758 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18759 - inside a LaTeX fragment, or
18760 - after the first word in a line, where an abbreviation expansion could
18761 insert a LaTeX environment."
18762 (when org-cdlatex-mode
18763 (cond
18764 ;; Before any word on the line: No expansion possible.
18765 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18766 ;; Just after first word on the line: Expand it. Make sure it
18767 ;; cannot happen on headlines, though.
18768 ((save-excursion
18769 (skip-chars-backward "a-zA-Z0-9*")
18770 (skip-chars-backward " \t")
18771 (and (bolp) (not (org-at-heading-p))))
18772 (cdlatex-tab) t)
18773 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18775 (defun org-cdlatex-underscore-caret (&optional _arg)
18776 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18777 Revert to the normal definition outside of these fragments."
18778 (interactive "P")
18779 (if (org-inside-LaTeX-fragment-p)
18780 (call-interactively 'cdlatex-sub-superscript)
18781 (let (org-cdlatex-mode)
18782 (call-interactively (key-binding (vector last-input-event))))))
18784 (defun org-cdlatex-math-modify (&optional _arg)
18785 "Execute `cdlatex-math-modify' in LaTeX fragments.
18786 Revert to the normal definition outside of these fragments."
18787 (interactive "P")
18788 (if (org-inside-LaTeX-fragment-p)
18789 (call-interactively 'cdlatex-math-modify)
18790 (let (org-cdlatex-mode)
18791 (call-interactively (key-binding (vector last-input-event))))))
18793 (defun org-cdlatex-environment-indent (&optional environment item)
18794 "Execute `cdlatex-environment' and indent the inserted environment.
18796 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18798 The inserted environment is indented to current indentation
18799 unless point is at the beginning of the line, in which the
18800 environment remains unintended."
18801 (interactive)
18802 ;; cdlatex-environment always return nil. Therefore, capture output
18803 ;; first and determine if an environment was selected.
18804 (let* ((beg (point-marker))
18805 (end (copy-marker (point) t))
18806 (inserted (progn
18807 (ignore-errors (cdlatex-environment environment item))
18808 (< beg end)))
18809 ;; Figure out how many lines to move forward after the
18810 ;; environment has been inserted.
18811 (lines (when inserted
18812 (save-excursion
18813 (- (cl-loop while (< beg (point))
18814 with x = 0
18815 do (forward-line -1)
18816 (cl-incf x)
18817 finally return x)
18818 (if (progn (goto-char beg)
18819 (and (progn (skip-chars-forward " \t") (eolp))
18820 (progn (skip-chars-backward " \t") (bolp))))
18821 1 0)))))
18822 (env (org-trim (delete-and-extract-region beg end))))
18823 (when inserted
18824 ;; Get indentation of next line unless at column 0.
18825 (let ((ind (if (bolp) 0
18826 (save-excursion
18827 (org-return-indent)
18828 (prog1 (org-get-indentation)
18829 (when (progn (skip-chars-forward " \t") (eolp))
18830 (delete-region beg (point)))))))
18831 (bol (progn (skip-chars-backward " \t") (bolp))))
18832 ;; Insert a newline before environment unless at column zero
18833 ;; to "escape" the current line. Insert a newline if
18834 ;; something is one the same line as \end{ENVIRONMENT}.
18835 (insert
18836 (concat (unless bol "\n") env
18837 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18838 (unless (zerop ind)
18839 (save-excursion
18840 (goto-char beg)
18841 (while (< (point) end)
18842 (unless (eolp) (org-indent-line-to ind))
18843 (forward-line))))
18844 (goto-char beg)
18845 (forward-line lines)
18846 (org-indent-line-to ind)))
18847 (set-marker beg nil)
18848 (set-marker end nil)))
18851 ;;;; LaTeX fragments
18853 (defun org-inside-LaTeX-fragment-p ()
18854 "Test if point is inside a LaTeX fragment.
18855 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18856 sequence appearing also before point.
18857 Even though the matchers for math are configurable, this function assumes
18858 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18859 delimiters are skipped when they have been removed by customization.
18860 The return value is nil, or a cons cell with the delimiter and the
18861 position of this delimiter.
18863 This function does a reasonably good job, but can locally be fooled by
18864 for example currency specifications. For example it will assume being in
18865 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18866 fragments that are properly closed, but during editing, we have to live
18867 with the uncertainty caused by missing closing delimiters. This function
18868 looks only before point, not after."
18869 (catch 'exit
18870 (let ((pos (point))
18871 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18872 (lim (progn
18873 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18874 (point)))
18875 dd-on str (start 0) m re)
18876 (goto-char pos)
18877 (when dodollar
18878 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18879 re (nth 1 (assoc "$" org-latex-regexps)))
18880 (while (string-match re str start)
18881 (cond
18882 ((= (match-end 0) (length str))
18883 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18884 ((= (match-end 0) (- (length str) 5))
18885 (throw 'exit nil))
18886 (t (setq start (match-end 0))))))
18887 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18888 (goto-char pos)
18889 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18890 (and (match-beginning 2) (throw 'exit nil))
18891 ;; count $$
18892 (while (re-search-backward "\\$\\$" lim t)
18893 (setq dd-on (not dd-on)))
18894 (goto-char pos)
18895 (when dd-on (cons "$$" m))))))
18897 (defun org-inside-latex-macro-p ()
18898 "Is point inside a LaTeX macro or its arguments?"
18899 (save-match-data
18900 (org-in-regexp
18901 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18903 (defun org--format-latex-make-overlay (beg end image)
18904 "Build an overlay between BEG and END using IMAGE file."
18905 (let ((ov (make-overlay beg end)))
18906 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18907 (overlay-put ov 'evaporate t)
18908 (overlay-put ov
18909 'modification-hooks
18910 (list (lambda (o _flag _beg _end &optional _l)
18911 (delete-overlay o))))
18912 (if (featurep 'xemacs)
18913 (progn
18914 (overlay-put ov 'invisible t)
18915 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18916 (overlay-put ov
18917 'display
18918 (list 'image :type 'png :file image :ascent 'center)))))
18920 (defun org--list-latex-overlays (&optional beg end)
18921 "List all Org LaTeX overlays in current buffer.
18922 Limit to overlays between BEG and END when those are provided."
18923 (cl-remove-if-not
18924 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18925 (overlays-in (or beg (point-min)) (or end (point-max)))))
18927 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18928 "Remove all overlays with LaTeX fragment images in current buffer.
18929 When optional arguments BEG and END are non-nil, remove all
18930 overlays between them instead. Return a non-nil value when some
18931 overlays were removed, nil otherwise."
18932 (let ((overlays (org--list-latex-overlays beg end)))
18933 (mapc #'delete-overlay overlays)
18934 overlays))
18936 (define-obsolete-function-alias
18937 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18938 (defun org-toggle-latex-fragment (&optional arg)
18939 "Preview the LaTeX fragment at point, or all locally or globally.
18941 If the cursor is on a LaTeX fragment, create the image and overlay
18942 it over the source code, if there is none. Remove it otherwise.
18943 If there is no fragment at point, display all fragments in the
18944 current section.
18946 With prefix ARG, preview or clear image for all fragments in the
18947 current subtree or in the whole buffer when used before the first
18948 headline. With a double prefix ARG \\[universal-argument] \
18949 \\[universal-argument] preview or clear images
18950 for all fragments in the buffer."
18951 (interactive "P")
18952 (unless (buffer-file-name (buffer-base-buffer))
18953 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18954 (when (display-graphic-p)
18955 (catch 'exit
18956 (save-excursion
18957 (let ((window-start (window-start)) msg)
18958 (save-restriction
18959 (cond
18960 ((or (equal arg '(16))
18961 (and (equal arg '(4))
18962 (org-with-limited-levels (org-before-first-heading-p))))
18963 (if (org-remove-latex-fragment-image-overlays)
18964 (progn (message "LaTeX fragments images removed from buffer")
18965 (throw 'exit nil))
18966 (setq msg "Creating images for buffer...")))
18967 ((equal arg '(4))
18968 (org-with-limited-levels (org-back-to-heading t))
18969 (let ((beg (point))
18970 (end (progn (org-end-of-subtree t) (point))))
18971 (if (org-remove-latex-fragment-image-overlays beg end)
18972 (progn
18973 (message "LaTeX fragment images removed from subtree")
18974 (throw 'exit nil))
18975 (setq msg "Creating images for subtree...")
18976 (narrow-to-region beg end))))
18977 ((let ((datum (org-element-context)))
18978 (when (memq (org-element-type datum)
18979 '(latex-environment latex-fragment))
18980 (let* ((beg (org-element-property :begin datum))
18981 (end (org-element-property :end datum)))
18982 (if (org-remove-latex-fragment-image-overlays beg end)
18983 (progn (message "LaTeX fragment image removed")
18984 (throw 'exit nil))
18985 (narrow-to-region beg end)
18986 (setq msg "Creating image..."))))))
18988 (org-with-limited-levels
18989 (let ((beg (if (org-at-heading-p) (line-beginning-position)
18990 (outline-previous-heading)
18991 (point)))
18992 (end (progn (outline-next-heading) (point))))
18993 (if (org-remove-latex-fragment-image-overlays beg end)
18994 (progn
18995 (message "LaTeX fragment images removed from section")
18996 (throw 'exit nil))
18997 (setq msg "Creating images for section...")
18998 (narrow-to-region beg end))))))
18999 (let ((file (buffer-file-name (buffer-base-buffer))))
19000 (org-format-latex
19001 (concat org-latex-preview-ltxpng-directory
19002 (file-name-sans-extension (file-name-nondirectory file)))
19003 ;; Emacs cannot overlay images from remote hosts.
19004 ;; Create it in `temporary-file-directory' instead.
19005 (if (file-remote-p file) temporary-file-directory
19006 default-directory)
19007 'overlays msg 'forbuffer
19008 org-latex-create-formula-image-program)))
19009 ;; Work around a bug that doesn't restore window's start
19010 ;; when widening back the buffer.
19011 (set-window-start nil window-start)
19012 (message (concat msg "done")))))))
19014 (defun org-format-latex
19015 (prefix &optional dir overlays msg forbuffer processing-type)
19016 "Replace LaTeX fragments with links to an image, and produce images.
19018 When optional argument OVERLAYS is non-nil, display the image on
19019 top of the fragment instead of replacing it.
19021 PROCESSING-TYPE is the conversion method to use, as a symbol.
19023 Some of the options can be changed using the variable
19024 `org-format-latex-options', which see."
19025 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19026 (unless (eq processing-type 'verbatim)
19027 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19028 (cnt 0)
19029 checkdir-flag)
19030 (goto-char (point-min))
19031 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19032 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19033 (overlay-recenter (point-max)))
19034 (while (re-search-forward math-regexp nil t)
19035 (unless (and overlays
19036 (eq (get-char-property (point) 'org-overlay-type)
19037 'org-latex-overlay))
19038 (let* ((context (org-element-context))
19039 (type (org-element-type context)))
19040 (when (memq type '(latex-environment latex-fragment))
19041 (let ((block-type (eq type 'latex-environment))
19042 (value (org-element-property :value context))
19043 (beg (org-element-property :begin context))
19044 (end (save-excursion
19045 (goto-char (org-element-property :end context))
19046 (skip-chars-backward " \r\t\n")
19047 (point))))
19048 (cl-case processing-type
19049 (mathjax
19050 ;; Prepare for MathJax processing.
19051 (if (not (string-match "\\`\\$\\$?" value))
19052 (goto-char end)
19053 (delete-region beg end)
19054 (if (string= (match-string 0 value) "$$")
19055 (insert "\\[" (substring value 2 -2) "\\]")
19056 (insert "\\(" (substring value 1 -1) "\\)"))))
19057 ((dvipng imagemagick)
19058 ;; Process to an image.
19059 (cl-incf cnt)
19060 (goto-char beg)
19061 (let* ((face (face-at-point))
19062 ;; Get the colors from the face at point.
19064 (let ((color (plist-get org-format-latex-options
19065 :foreground)))
19066 (if (and forbuffer (eq color 'auto))
19067 (face-attribute face :foreground nil 'default)
19068 color)))
19070 (let ((color (plist-get org-format-latex-options
19071 :background)))
19072 (if (and forbuffer (eq color 'auto))
19073 (face-attribute face :background nil 'default)
19074 color)))
19075 (hash (sha1 (prin1-to-string
19076 (list org-format-latex-header
19077 org-latex-default-packages-alist
19078 org-latex-packages-alist
19079 org-format-latex-options
19080 forbuffer value fg bg))))
19081 (absprefix (expand-file-name prefix dir))
19082 (linkfile (format "%s_%s.png" prefix hash))
19083 (movefile (format "%s_%s.png" absprefix hash))
19084 (sep (and block-type "\n\n"))
19085 (link (concat sep "[[file:" linkfile "]]" sep))
19086 (options
19087 (org-combine-plists
19088 org-format-latex-options
19089 `(:foreground ,fg :background ,bg))))
19090 (when msg (message msg cnt))
19091 (unless checkdir-flag ; Ensure the directory exists.
19092 (setq checkdir-flag t)
19093 (let ((todir (file-name-directory absprefix)))
19094 (unless (file-directory-p todir)
19095 (make-directory todir t))))
19096 (unless (file-exists-p movefile)
19097 (org-create-formula-image
19098 value movefile options forbuffer processing-type))
19099 (if overlays
19100 (progn
19101 (dolist (o (overlays-in beg end))
19102 (when (eq (overlay-get o 'org-overlay-type)
19103 'org-latex-overlay)
19104 (delete-overlay o)))
19105 (org--format-latex-make-overlay beg end movefile)
19106 (goto-char end))
19107 (delete-region beg end)
19108 (insert
19109 (org-add-props link
19110 (list 'org-latex-src
19111 (replace-regexp-in-string "\"" "" value)
19112 'org-latex-src-embed-type
19113 (if block-type 'paragraph 'character)))))))
19114 (mathml
19115 ;; Process to MathML.
19116 (unless (org-format-latex-mathml-available-p)
19117 (user-error "LaTeX to MathML converter not configured"))
19118 (cl-incf cnt)
19119 (when msg (message msg cnt))
19120 (goto-char beg)
19121 (delete-region beg end)
19122 (insert (org-format-latex-as-mathml
19123 value block-type prefix dir)))
19124 (otherwise
19125 (error "Unknown conversion type %s for LaTeX fragments"
19126 processing-type)))))))))))
19128 (defun org-create-math-formula (latex-frag &optional mathml-file)
19129 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19130 Use `org-latex-to-mathml-convert-command'. If the conversion is
19131 sucessful, return the portion between \"<math...> </math>\"
19132 elements otherwise return nil. When MATHML-FILE is specified,
19133 write the results in to that file. When invoked as an
19134 interactive command, prompt for LATEX-FRAG, with initial value
19135 set to the current active region and echo the results for user
19136 inspection."
19137 (interactive (list (let ((frag (when (org-region-active-p)
19138 (buffer-substring-no-properties
19139 (region-beginning) (region-end)))))
19140 (read-string "LaTeX Fragment: " frag nil frag))))
19141 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19142 (let* ((tmp-in-file
19143 (let ((file (file-relative-name
19144 (make-temp-name (expand-file-name "ltxmathml-in")))))
19145 (write-region latex-frag nil file)
19146 file))
19147 (tmp-out-file (file-relative-name
19148 (make-temp-name (expand-file-name "ltxmathml-out"))))
19149 (cmd (format-spec
19150 org-latex-to-mathml-convert-command
19151 `((?j . ,(and org-latex-to-mathml-jar-file
19152 (shell-quote-argument
19153 (expand-file-name
19154 org-latex-to-mathml-jar-file))))
19155 (?I . ,(shell-quote-argument tmp-in-file))
19156 (?i . ,latex-frag)
19157 (?o . ,(shell-quote-argument tmp-out-file)))))
19158 mathml shell-command-output)
19159 (when (org-called-interactively-p 'any)
19160 (unless (org-format-latex-mathml-available-p)
19161 (user-error "LaTeX to MathML converter not configured")))
19162 (message "Running %s" cmd)
19163 (setq shell-command-output (shell-command-to-string cmd))
19164 (setq mathml
19165 (when (file-readable-p tmp-out-file)
19166 (with-current-buffer (find-file-noselect tmp-out-file t)
19167 (goto-char (point-min))
19168 (when (re-search-forward
19169 (concat
19170 (regexp-quote
19171 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19172 "[^>]*?>"
19173 "\\(.\\|\n\\)*"
19174 "</math>")
19175 nil t)
19176 (prog1 (match-string 0) (kill-buffer))))))
19177 (cond
19178 (mathml
19179 (setq mathml
19180 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19181 (when mathml-file
19182 (write-region mathml nil mathml-file))
19183 (when (org-called-interactively-p 'any)
19184 (message mathml)))
19185 ((message "LaTeX to MathML conversion failed")
19186 (message shell-command-output)))
19187 (delete-file tmp-in-file)
19188 (when (file-exists-p tmp-out-file)
19189 (delete-file tmp-out-file))
19190 mathml))
19192 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19193 prefix &optional dir)
19194 "Use `org-create-math-formula' but check local cache first."
19195 (let* ((absprefix (expand-file-name prefix dir))
19196 (print-length nil) (print-level nil)
19197 (formula-id (concat
19198 "formula-"
19199 (sha1
19200 (prin1-to-string
19201 (list latex-frag
19202 org-latex-to-mathml-convert-command)))))
19203 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19204 (formula-cache-dir (file-name-directory formula-cache)))
19206 (unless (file-directory-p formula-cache-dir)
19207 (make-directory formula-cache-dir t))
19209 (unless (file-exists-p formula-cache)
19210 (org-create-math-formula latex-frag formula-cache))
19212 (if (file-exists-p formula-cache)
19213 ;; Successful conversion. Return the link to MathML file.
19214 (org-add-props
19215 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19216 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19217 'org-latex-src-embed-type (if latex-frag-type
19218 'paragraph 'character)))
19219 ;; Failed conversion. Return the LaTeX fragment verbatim
19220 latex-frag)))
19222 (defun org-create-formula-image (string tofile options buffer &optional type)
19223 "Create an image from LaTeX source using dvipng or convert.
19224 This function calls either `org-create-formula-image-with-dvipng'
19225 or `org-create-formula-image-with-imagemagick' depending on the
19226 value of `org-latex-create-formula-image-program' or on the value
19227 of the optional TYPE variable.
19229 Note: ultimately these two function should be combined as they
19230 share a good deal of logic."
19231 (org-check-external-command
19232 "latex" "needed to convert LaTeX fragments to images")
19233 (funcall
19234 (cl-case (or type org-latex-create-formula-image-program)
19235 (dvipng
19236 (org-check-external-command
19237 "dvipng" "needed to convert LaTeX fragments to images")
19238 #'org-create-formula-image-with-dvipng)
19239 (imagemagick
19240 (org-check-external-command
19241 "convert" "you need to install imagemagick")
19242 #'org-create-formula-image-with-imagemagick)
19243 (t (error
19244 "Invalid value of `org-latex-create-formula-image-program'")))
19245 string tofile options buffer))
19247 (declare-function org-export-get-backend "ox" (name))
19248 (declare-function org-export--get-global-options "ox" (&optional backend))
19249 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19250 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19251 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19252 (defun org-create-formula--latex-header ()
19253 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19254 (let ((info (org-combine-plists (org-export--get-global-options
19255 (org-export-get-backend 'latex))
19256 (org-export--get-inbuffer-options
19257 (org-export-get-backend 'latex)))))
19258 (org-latex-guess-babel-language
19259 (org-latex-guess-inputenc
19260 (org-splice-latex-header
19261 org-format-latex-header
19262 org-latex-default-packages-alist
19263 org-latex-packages-alist t
19264 (plist-get info :latex-header)))
19265 info)))
19267 (defun org--get-display-dpi ()
19268 "Get the DPI of the display.
19270 Assumes that the display has the same pixel width in the
19271 horizontal and vertical directions."
19272 (if (display-graphic-p)
19273 (round (/ (display-pixel-height)
19274 (/ (display-mm-height) 25.4)))
19275 (error "Attempt to calculate the dpi of a non-graphic display")))
19277 ;; This function borrows from Ganesh Swami's latex2png.el
19278 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19279 "This calls dvipng."
19280 (require 'ox-latex)
19281 (let* ((tmpdir (if (featurep 'xemacs)
19282 (temp-directory)
19283 temporary-file-directory))
19284 (texfilebase (make-temp-name
19285 (expand-file-name "orgtex" tmpdir)))
19286 (texfile (concat texfilebase ".tex"))
19287 (dvifile (concat texfilebase ".dvi"))
19288 (pngfile (concat texfilebase ".png"))
19289 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19290 ;; This assumes that the display has the same pixel width in
19291 ;; the horizontal and vertical directions
19292 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19293 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19294 "Black"))
19295 (bg (or (plist-get options (if buffer :background :html-background))
19296 "Transparent")))
19297 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19298 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19299 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19300 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19301 (let ((latex-header (org-create-formula--latex-header)))
19302 (with-temp-file texfile
19303 (insert latex-header)
19304 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19305 (let ((dir default-directory))
19306 (ignore-errors
19307 (cd tmpdir)
19308 (call-process "latex" nil nil nil texfile))
19309 (cd dir))
19310 (if (not (file-exists-p dvifile))
19311 (progn (message "Failed to create dvi file from %s" texfile) nil)
19312 (ignore-errors
19313 (if (featurep 'xemacs)
19314 (call-process "dvipng" nil nil nil
19315 "-fg" fg "-bg" bg
19316 "-T" "tight"
19317 "-o" pngfile
19318 dvifile)
19319 (call-process "dvipng" nil nil nil
19320 "-fg" fg "-bg" bg
19321 "-D" dpi
19322 ;;"-x" scale "-y" scale
19323 "-T" "tight"
19324 "-o" pngfile
19325 dvifile)))
19326 (if (not (file-exists-p pngfile))
19327 (if org-format-latex-signal-error
19328 (error "Failed to create png file from %s" texfile)
19329 (message "Failed to create png file from %s" texfile)
19330 nil)
19331 ;; Use the requested file name and clean up
19332 (copy-file pngfile tofile 'replace)
19333 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19334 (when (file-exists-p (concat texfilebase e))
19335 (delete-file (concat texfilebase e))))
19336 pngfile))))
19338 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19339 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19340 "This calls convert, which is included into imagemagick."
19341 (require 'ox-latex)
19342 (let* ((tmpdir (if (featurep 'xemacs)
19343 (temp-directory)
19344 temporary-file-directory))
19345 (texfilebase (make-temp-name
19346 (expand-file-name "orgtex" tmpdir)))
19347 (texfile (concat texfilebase ".tex"))
19348 (pdffile (concat texfilebase ".pdf"))
19349 (pngfile (concat texfilebase ".png"))
19350 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19351 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19352 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19353 "black"))
19354 (bg (or (plist-get options (if buffer :background :html-background))
19355 "white")))
19356 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19357 (setq fg (org-latex-color-format fg)))
19358 (if (eq bg 'default) (setq bg (org-latex-color :background))
19359 (setq bg (org-latex-color-format
19360 (if (string= bg "Transparent") "white" bg))))
19361 (let ((latex-header (org-create-formula--latex-header)))
19362 (with-temp-file texfile
19363 (insert latex-header)
19364 (insert "\n\\begin{document}\n"
19365 "\\definecolor{fg}{rgb}{" fg "}\n"
19366 "\\definecolor{bg}{rgb}{" bg "}\n"
19367 "\n\\pagecolor{bg}\n"
19368 "\n{\\color{fg}\n"
19369 string
19370 "\n}\n"
19371 "\n\\end{document}\n")))
19372 (org-latex-compile texfile t)
19373 (if (not (file-exists-p pdffile))
19374 (progn (message "Failed to create pdf file from %s" texfile) nil)
19375 (ignore-errors
19376 (if (featurep 'xemacs)
19377 (call-process "convert" nil nil nil
19378 "-density" "96"
19379 "-trim"
19380 "-antialias"
19381 pdffile
19382 "-quality" "100"
19383 ;; "-sharpen" "0x1.0"
19384 pngfile)
19385 (call-process "convert" nil nil nil
19386 "-density" dpi
19387 "-trim"
19388 "-antialias"
19389 pdffile
19390 "-quality" "100"
19391 ;; "-sharpen" "0x1.0"
19392 pngfile)))
19393 (if (not (file-exists-p pngfile))
19394 (if org-format-latex-signal-error
19395 (error "Failed to create png file from %s" texfile)
19396 (message "Failed to create png file from %s" texfile)
19397 nil)
19398 ;; Use the requested file name and clean up
19399 (copy-file pngfile tofile 'replace)
19400 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19401 (when (file-exists-p (concat texfilebase e))
19402 (delete-file (concat texfilebase e))))
19403 pngfile))))
19405 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19406 "Fill a LaTeX header template TPL.
19407 In the template, the following place holders will be recognized:
19409 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19410 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19411 [PACKAGES] \\usepackage statements for PKG
19412 [NO-PACKAGES] do not include PKG
19413 [EXTRA] the string EXTRA
19414 [NO-EXTRA] do not include EXTRA
19416 For backward compatibility, if both the positive and the negative place
19417 holder is missing, the positive one (without the \"NO-\") will be
19418 assumed to be present at the end of the template.
19419 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19420 EXTRA is a string.
19421 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19422 (let (rpl (end ""))
19423 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19424 (setq rpl (if (or (match-end 1) (not def-pkg))
19425 "" (org-latex-packages-to-string def-pkg snippets-p t))
19426 tpl (replace-match rpl t t tpl))
19427 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19429 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19430 (setq rpl (if (or (match-end 1) (not pkg))
19431 "" (org-latex-packages-to-string pkg snippets-p t))
19432 tpl (replace-match rpl t t tpl))
19433 (when pkg (setq end
19434 (concat end "\n"
19435 (org-latex-packages-to-string pkg snippets-p)))))
19437 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19438 (setq rpl (if (or (match-end 1) (not extra))
19439 "" (concat extra "\n"))
19440 tpl (replace-match rpl t t tpl))
19441 (when (and extra (string-match "\\S-" extra))
19442 (setq end (concat end "\n" extra))))
19444 (if (string-match "\\S-" end)
19445 (concat tpl "\n" end)
19446 tpl)))
19448 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19449 "Turn an alist of packages into a string with the \\usepackage macros."
19450 (setq pkg (mapconcat (lambda(p)
19451 (cond
19452 ((stringp p) p)
19453 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19454 (format "%% Package %s omitted" (cadr p)))
19455 ((equal "" (car p))
19456 (format "\\usepackage{%s}" (cadr p)))
19458 (format "\\usepackage[%s]{%s}"
19459 (car p) (cadr p)))))
19461 "\n"))
19462 (if newline (concat pkg "\n") pkg))
19464 (defun org-dvipng-color (attr)
19465 "Return a RGB color specification for dvipng."
19466 (apply 'format "rgb %s %s %s"
19467 (mapcar 'org-normalize-color
19468 (if (featurep 'xemacs)
19469 (color-rgb-components
19470 (face-property 'default
19471 (cond ((eq attr :foreground) 'foreground)
19472 ((eq attr :background) 'background))))
19473 (color-values (face-attribute 'default attr nil))))))
19475 (defun org-dvipng-color-format (color-name)
19476 "Convert COLOR-NAME to a RGB color value for dvipng."
19477 (apply 'format "rgb %s %s %s"
19478 (mapcar 'org-normalize-color
19479 (color-values color-name))))
19481 (defun org-latex-color (attr)
19482 "Return a RGB color for the LaTeX color package."
19483 (apply 'format "%s,%s,%s"
19484 (mapcar 'org-normalize-color
19485 (if (featurep 'xemacs)
19486 (color-rgb-components
19487 (face-property 'default
19488 (cond ((eq attr :foreground) 'foreground)
19489 ((eq attr :background) 'background))))
19490 (color-values (face-attribute 'default attr nil))))))
19492 (defun org-latex-color-format (color-name)
19493 "Convert COLOR-NAME to a RGB color value."
19494 (apply 'format "%s,%s,%s"
19495 (mapcar 'org-normalize-color
19496 (color-values color-name))))
19498 (defun org-normalize-color (value)
19499 "Return string to be used as color value for an RGB component."
19500 (format "%g" (/ value 65535.0)))
19504 ;; Image display
19506 (defvar-local org-inline-image-overlays nil)
19508 (defun org-toggle-inline-images (&optional include-linked)
19509 "Toggle the display of inline images.
19510 INCLUDE-LINKED is passed to `org-display-inline-images'."
19511 (interactive "P")
19512 (if org-inline-image-overlays
19513 (progn
19514 (org-remove-inline-images)
19515 (when (org-called-interactively-p 'interactive)
19516 (message "Inline image display turned off")))
19517 (org-display-inline-images include-linked)
19518 (when (org-called-interactively-p 'interactive)
19519 (message (if org-inline-image-overlays
19520 (format "%d images displayed inline"
19521 (length org-inline-image-overlays))
19522 "No images to display inline")))))
19524 (defun org-redisplay-inline-images ()
19525 "Refresh the display of inline images."
19526 (interactive)
19527 (if (not org-inline-image-overlays)
19528 (org-toggle-inline-images)
19529 (org-toggle-inline-images)
19530 (org-toggle-inline-images)))
19532 (defun org-display-inline-images (&optional include-linked refresh beg end)
19533 "Display inline images.
19535 An inline image is a link which follows either of these
19536 conventions:
19538 1. Its path is a file with an extension matching return value
19539 from `image-file-name-regexp' and it has no contents.
19541 2. Its description consists in a single link of the previous
19542 type.
19544 When optional argument INCLUDE-LINKED is non-nil, also links with
19545 a text description part will be inlined. This can be nice for
19546 a quick look at those images, but it does not reflect what
19547 exported files will look like.
19549 When optional argument REFRESH is non-nil, refresh existing
19550 images between BEG and END. This will create new image displays
19551 only if necessary. BEG and END default to the buffer
19552 boundaries."
19553 (interactive "P")
19554 (when (display-graphic-p)
19555 (unless refresh
19556 (org-remove-inline-images)
19557 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19558 (org-with-wide-buffer
19559 (goto-char (or beg (point-min)))
19560 (let ((case-fold-search t)
19561 (file-extension-re (image-file-name-regexp)))
19562 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19563 (let ((link (save-match-data (org-element-context))))
19564 ;; Check if we're at an inline image.
19565 (when (and (equal (org-element-property :type link) "file")
19566 (or include-linked
19567 (not (org-element-property :contents-begin link)))
19568 (let ((parent (org-element-property :parent link)))
19569 (or (not (eq (org-element-type parent) 'link))
19570 (not (cdr (org-element-contents parent)))))
19571 (org-string-match-p file-extension-re
19572 (org-element-property :path link)))
19573 (let ((file (expand-file-name
19574 (org-link-unescape
19575 (org-element-property :path link)))))
19576 (when (file-exists-p file)
19577 (let ((width
19578 ;; Apply `org-image-actual-width' specifications.
19579 (cond
19580 ((not (image-type-available-p 'imagemagick)) nil)
19581 ((eq org-image-actual-width t) nil)
19582 ((listp org-image-actual-width)
19584 ;; First try to find a width among
19585 ;; attributes associated to the paragraph
19586 ;; containing link.
19587 (let ((paragraph
19588 (let ((e link))
19589 (while (and (setq e (org-element-property
19590 :parent e))
19591 (not (eq (org-element-type e)
19592 'paragraph))))
19593 e)))
19594 (when paragraph
19595 (save-excursion
19596 (goto-char (org-element-property :begin paragraph))
19597 (when
19598 (re-search-forward
19599 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19600 (org-element-property
19601 :post-affiliated paragraph)
19603 (string-to-number (match-string 1))))))
19604 ;; Otherwise, fall-back to provided number.
19605 (car org-image-actual-width)))
19606 ((numberp org-image-actual-width)
19607 org-image-actual-width)))
19608 (old (get-char-property-and-overlay
19609 (org-element-property :begin link)
19610 'org-image-overlay)))
19611 (if (and (car-safe old) refresh)
19612 (image-refresh (overlay-get (cdr old) 'display))
19613 (let ((image (create-image file
19614 (and width 'imagemagick)
19616 :width width)))
19617 (when image
19618 (let* ((link
19619 ;; If inline image is the description
19620 ;; of another link, be sure to
19621 ;; consider the latter as the one to
19622 ;; apply the overlay on.
19623 (let ((parent
19624 (org-element-property :parent link)))
19625 (if (eq (org-element-type parent) 'link)
19626 parent
19627 link)))
19628 (ov (make-overlay
19629 (org-element-property :begin link)
19630 (progn
19631 (goto-char
19632 (org-element-property :end link))
19633 (skip-chars-backward " \t")
19634 (point)))))
19635 (overlay-put ov 'display image)
19636 (overlay-put ov 'face 'default)
19637 (overlay-put ov 'org-image-overlay t)
19638 (overlay-put
19639 ov 'modification-hooks
19640 (list 'org-display-inline-remove-overlay))
19641 (push ov org-inline-image-overlays)))))))))))))))
19643 (define-obsolete-function-alias
19644 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19646 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19647 "Remove inline-display overlay if a corresponding region is modified."
19648 (let ((inhibit-modification-hooks t))
19649 (when (and ov after)
19650 (delete ov org-inline-image-overlays)
19651 (delete-overlay ov))))
19653 (defun org-remove-inline-images ()
19654 "Remove inline display of images."
19655 (interactive)
19656 (mapc #'delete-overlay org-inline-image-overlays)
19657 (setq org-inline-image-overlays nil))
19659 ;;;; Key bindings
19661 ;; Outline functions from `outline-mode-prefix-map'
19662 ;; that can be remapped in Org:
19663 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19664 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19665 (define-key org-mode-map [remap outline-forward-same-level]
19666 'org-forward-heading-same-level)
19667 (define-key org-mode-map [remap outline-backward-same-level]
19668 'org-backward-heading-same-level)
19669 (define-key org-mode-map [remap outline-show-branches]
19670 'org-kill-note-or-show-branches)
19671 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19672 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19673 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19674 (define-key org-mode-map [remap outline-next-visible-heading]
19675 'org-next-visible-heading)
19676 (define-key org-mode-map [remap outline-previous-visible-heading]
19677 'org-previous-visible-heading)
19678 (define-key org-mode-map [remap show-children] 'org-show-children)
19680 ;; Outline functions from `outline-mode-prefix-map' that can not
19681 ;; be remapped in Org:
19683 ;; - the column "key binding" shows whether the Outline function is still
19684 ;; available in Org mode on the same key that it has been bound to in
19685 ;; Outline mode:
19686 ;; - "overridden": key used for a different functionality in Org mode
19687 ;; - else: key still bound to the same Outline function in Org mode
19689 ;; | Outline function | key binding | Org replacement |
19690 ;; |------------------------------------+-------------+--------------------------|
19691 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19692 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19693 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19694 ;; | `show-entry' | overridden | no replacement |
19695 ;; | `show-branches' | `C-c C-k' | still same function |
19696 ;; | `show-subtree' | overridden | visibility cycling |
19697 ;; | `show-all' | overridden | no replacement |
19698 ;; | `hide-subtree' | overridden | visibility cycling |
19699 ;; | `hide-body' | overridden | no replacement |
19700 ;; | `hide-entry' | overridden | visibility cycling |
19701 ;; | `hide-leaves' | overridden | no replacement |
19702 ;; | `hide-sublevels' | overridden | no replacement |
19703 ;; | `hide-other' | overridden | no replacement |
19705 ;; Make `C-c C-x' a prefix key
19706 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19708 ;; TAB key with modifiers
19709 (org-defkey org-mode-map "\C-i" 'org-cycle)
19710 (org-defkey org-mode-map [(tab)] 'org-cycle)
19711 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19712 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19713 ;; The following line is necessary under Suse GNU/Linux
19714 (unless (featurep 'xemacs)
19715 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19716 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19717 (define-key org-mode-map [backtab] 'org-shifttab)
19719 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19720 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19721 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19723 ;; Cursor keys with modifiers
19724 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19725 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19726 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19727 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19729 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19730 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19731 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19732 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19733 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19734 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19736 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19737 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19738 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19739 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19741 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19742 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19743 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19744 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19746 ;; Babel keys
19747 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19748 (dolist (pair org-babel-key-bindings)
19749 (define-key org-babel-map (car pair) (cdr pair)))
19751 ;;; Extra keys for tty access.
19752 ;; We only set them when really needed because otherwise the
19753 ;; menus don't show the simple keys
19755 (when (or org-use-extra-keys
19756 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19757 (not window-system))
19758 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19759 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19760 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19761 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19762 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19763 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19764 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19765 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19766 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19767 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19768 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19769 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19770 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19771 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19772 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19773 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19774 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19775 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19776 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19777 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19778 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19779 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19780 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19781 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19782 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19783 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19784 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19785 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19787 ;; All the other keys
19789 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19790 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19791 (if (boundp 'narrow-map)
19792 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19793 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19794 (if (boundp 'narrow-map)
19795 (org-defkey narrow-map "b" 'org-narrow-to-block)
19796 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19797 (if (boundp 'narrow-map)
19798 (org-defkey narrow-map "e" 'org-narrow-to-element)
19799 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19800 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19801 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19802 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19803 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19804 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19805 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19806 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19807 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19808 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19809 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19810 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19811 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19812 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19813 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19814 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19815 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19816 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19817 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19818 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19819 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19820 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19821 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19822 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19823 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19824 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19825 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19826 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19827 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19828 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19829 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19830 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19831 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19832 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19833 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19834 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19835 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19836 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19837 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19838 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19839 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19840 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19841 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19842 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19843 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19844 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19845 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19846 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19847 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19848 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19849 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19850 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19851 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19852 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19853 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19854 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19855 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19856 (org-defkey org-mode-map "\C-c^" 'org-sort)
19857 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19858 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19859 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19860 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19861 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19862 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19863 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19864 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19865 (org-defkey org-mode-map "\C-m" 'org-return)
19866 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19867 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19868 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19869 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19870 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19871 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19872 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19873 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19874 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19875 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19876 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19877 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19878 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19879 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19880 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19881 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19882 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19883 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19884 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19885 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19886 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19887 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19888 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19889 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19890 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19892 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19893 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19894 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19896 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19897 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19898 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19899 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19900 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19901 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19902 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19903 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19904 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19905 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19906 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19907 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19908 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19909 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19910 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19911 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19912 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19913 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19914 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19915 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19916 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19917 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19919 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19920 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19921 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19922 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19923 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19925 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19927 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19929 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19930 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19932 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19935 (when (featurep 'xemacs)
19936 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19939 (defconst org-speed-commands-default
19941 ("Outline Navigation")
19942 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19943 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19944 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19945 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19946 ("F" . org-next-block)
19947 ("B" . org-previous-block)
19948 ("u" . (org-speed-move-safe 'outline-up-heading))
19949 ("j" . org-goto)
19950 ("g" . (org-refile t))
19951 ("Outline Visibility")
19952 ("c" . org-cycle)
19953 ("C" . org-shifttab)
19954 (" " . org-display-outline-path)
19955 ("s" . org-narrow-to-subtree)
19956 ("=" . org-columns)
19957 ("Outline Structure Editing")
19958 ("U" . org-metaup)
19959 ("D" . org-metadown)
19960 ("r" . org-metaright)
19961 ("l" . org-metaleft)
19962 ("R" . org-shiftmetaright)
19963 ("L" . org-shiftmetaleft)
19964 ("i" . (progn (forward-char 1) (call-interactively
19965 'org-insert-heading-respect-content)))
19966 ("^" . org-sort)
19967 ("w" . org-refile)
19968 ("a" . org-archive-subtree-default-with-confirmation)
19969 ("@" . org-mark-subtree)
19970 ("#" . org-toggle-comment)
19971 ("Clock Commands")
19972 ("I" . org-clock-in)
19973 ("O" . org-clock-out)
19974 ("Meta Data Editing")
19975 ("t" . org-todo)
19976 ("," . (org-priority))
19977 ("0" . (org-priority ?\ ))
19978 ("1" . (org-priority ?A))
19979 ("2" . (org-priority ?B))
19980 ("3" . (org-priority ?C))
19981 (":" . org-set-tags-command)
19982 ("e" . org-set-effort)
19983 ("E" . org-inc-effort)
19984 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19985 (org-entry-put (point) "APPT_WARNTIME" m)))
19986 ("Agenda Views etc")
19987 ("v" . org-agenda)
19988 ("/" . org-sparse-tree)
19989 ("Misc")
19990 ("o" . org-open-at-point)
19991 ("?" . org-speed-command-help)
19992 ("<" . (org-agenda-set-restriction-lock 'subtree))
19993 (">" . (org-agenda-remove-restriction-lock))
19995 "The default speed commands.")
19997 (defun org-print-speed-command (e)
19998 (if (> (length (car e)) 1)
19999 (progn
20000 (princ "\n")
20001 (princ (car e))
20002 (princ "\n")
20003 (princ (make-string (length (car e)) ?-))
20004 (princ "\n"))
20005 (princ (car e))
20006 (princ " ")
20007 (if (symbolp (cdr e))
20008 (princ (symbol-name (cdr e)))
20009 (prin1 (cdr e)))
20010 (princ "\n")))
20012 (defun org-speed-command-help ()
20013 "Show the available speed commands."
20014 (interactive)
20015 (if (not org-use-speed-commands)
20016 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20017 (with-output-to-temp-buffer "*Help*"
20018 (princ "User-defined Speed commands\n===========================\n")
20019 (mapc #'org-print-speed-command org-speed-commands-user)
20020 (princ "\n")
20021 (princ "Built-in Speed commands\n=======================\n")
20022 (mapc #'org-print-speed-command org-speed-commands-default))
20023 (with-current-buffer "*Help*"
20024 (setq truncate-lines t))))
20026 (defun org-speed-move-safe (cmd)
20027 "Execute CMD, but make sure that the cursor always ends up in a headline.
20028 If not, return to the original position and throw an error."
20029 (interactive)
20030 (let ((pos (point)))
20031 (call-interactively cmd)
20032 (unless (and (bolp) (org-at-heading-p))
20033 (goto-char pos)
20034 (error "Boundary reached while executing %s" cmd))))
20036 (defvar org-self-insert-command-undo-counter 0)
20038 (defvar org-table-auto-blank-field) ; defined in org-table.el
20039 (defvar org-speed-command nil)
20041 (define-obsolete-function-alias
20042 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20044 (defun org-speed-command-activate (keys)
20045 "Hook for activating single-letter speed commands.
20046 `org-speed-commands-default' specifies a minimal command set.
20047 Use `org-speed-commands-user' for further customization."
20048 (when (or (and (bolp) (looking-at org-outline-regexp))
20049 (and (functionp org-use-speed-commands)
20050 (funcall org-use-speed-commands)))
20051 (cdr (assoc keys (append org-speed-commands-user
20052 org-speed-commands-default)))))
20054 (define-obsolete-function-alias
20055 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20057 (defun org-babel-speed-command-activate (keys)
20058 "Hook for activating single-letter code block commands."
20059 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20060 (cdr (assoc keys org-babel-key-bindings))))
20062 (defcustom org-speed-command-hook
20063 '(org-speed-command-default-hook org-babel-speed-command-hook)
20064 "Hook for activating speed commands at strategic locations.
20065 Hook functions are called in sequence until a valid handler is
20066 found.
20068 Each hook takes a single argument, a user-pressed command key
20069 which is also a `self-insert-command' from the global map.
20071 Within the hook, examine the cursor position and the command key
20072 and return nil or a valid handler as appropriate. Handler could
20073 be one of an interactive command, a function, or a form.
20075 Set `org-use-speed-commands' to non-nil value to enable this
20076 hook. The default setting is `org-speed-command-activate'."
20077 :group 'org-structure
20078 :version "24.1"
20079 :type 'hook)
20081 (defun org-self-insert-command (N)
20082 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20083 If the cursor is in a table looking at whitespace, the whitespace is
20084 overwritten, and the table is not marked as requiring realignment."
20085 (interactive "p")
20086 (org-check-before-invisible-edit 'insert)
20087 (cond
20088 ((and org-use-speed-commands
20089 (let ((kv (this-command-keys-vector)))
20090 (setq org-speed-command
20091 (run-hook-with-args-until-success
20092 'org-speed-command-hook
20093 (make-string 1 (aref kv (1- (length kv))))))))
20094 (cond
20095 ((commandp org-speed-command)
20096 (setq this-command org-speed-command)
20097 (call-interactively org-speed-command))
20098 ((functionp org-speed-command)
20099 (funcall org-speed-command))
20100 ((and org-speed-command (listp org-speed-command))
20101 (eval org-speed-command))
20102 (t (let (org-use-speed-commands)
20103 (call-interactively 'org-self-insert-command)))))
20104 ((and
20105 (org-at-table-p)
20106 (progn
20107 ;; Check if we blank the field, and if that triggers align.
20108 (and (featurep 'org-table) org-table-auto-blank-field
20109 (memq last-command
20110 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20111 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20112 ;; Got extra space, this field does not determine
20113 ;; column width.
20114 (let (org-table-may-need-update) (org-table-blank-field))
20115 ;; No extra space, this field may determine column
20116 ;; width.
20117 (org-table-blank-field)))
20119 (eq N 1)
20120 (looking-at "[^|\n]* \\( \\)|"))
20121 ;; There is room for insertion without re-aligning the table.
20122 (delete-region (match-beginning 1) (match-end 1))
20123 (self-insert-command N))
20125 (setq org-table-may-need-update t)
20126 (self-insert-command N)
20127 (org-fix-tags-on-the-fly)
20128 (when org-self-insert-cluster-for-undo
20129 (if (not (eq last-command 'org-self-insert-command))
20130 (setq org-self-insert-command-undo-counter 1)
20131 (if (>= org-self-insert-command-undo-counter 20)
20132 (setq org-self-insert-command-undo-counter 1)
20133 (and (> org-self-insert-command-undo-counter 0)
20134 buffer-undo-list (listp buffer-undo-list)
20135 (not (cadr buffer-undo-list)) ; remove nil entry
20136 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20137 (setq org-self-insert-command-undo-counter
20138 (1+ org-self-insert-command-undo-counter))))))))
20140 (defun org-check-before-invisible-edit (kind)
20141 "Check is editing if kind KIND would be dangerous with invisible text around.
20142 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20143 ;; First, try to get out of here as quickly as possible, to reduce overhead
20144 (when (and org-catch-invisible-edits
20145 (or (not (boundp 'visible-mode)) (not visible-mode))
20146 (or (get-char-property (point) 'invisible)
20147 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20148 ;; OK, we need to take a closer look
20149 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20150 (invisible-before-point (unless (bobp) (get-char-property
20151 (1- (point)) 'invisible)))
20152 (border-and-ok-direction
20154 ;; Check if we are acting predictably before invisible text
20155 (and invisible-at-point (not invisible-before-point)
20156 (memq kind '(insert delete-backward)))
20157 ;; Check if we are acting predictably after invisible text
20158 ;; This works not well, and I have turned it off. It seems
20159 ;; better to always show and stop after invisible text.
20160 ;; (and (not invisible-at-point) invisible-before-point
20161 ;; (memq kind '(insert delete)))
20163 (when (or (memq invisible-at-point '(outline org-hide-block t))
20164 (memq invisible-before-point '(outline org-hide-block t)))
20165 (when (eq org-catch-invisible-edits 'error)
20166 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20167 (if (and org-custom-properties-overlays
20168 (y-or-n-p "Display invisible properties in this buffer? "))
20169 (org-toggle-custom-properties-visibility)
20170 ;; Make the area visible
20171 (save-excursion
20172 (when invisible-before-point
20173 (goto-char (previous-single-char-property-change
20174 (point) 'invisible)))
20175 (outline-show-subtree))
20176 (cond
20177 ((eq org-catch-invisible-edits 'show)
20178 ;; That's it, we do the edit after showing
20179 (message
20180 "Unfolding invisible region around point before editing")
20181 (sit-for 1))
20182 ((and (eq org-catch-invisible-edits 'smart)
20183 border-and-ok-direction)
20184 (message "Unfolding invisible region around point before editing"))
20186 ;; Don't do the edit, make the user repeat it in full visibility
20187 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20189 (defun org-fix-tags-on-the-fly ()
20190 (when (and (equal (char-after (point-at-bol)) ?*)
20191 (org-at-heading-p))
20192 (org-align-tags-here org-tags-column)))
20194 (defun org-delete-backward-char (N)
20195 "Like `delete-backward-char', insert whitespace at field end in tables.
20196 When deleting backwards, in tables this function will insert whitespace in
20197 front of the next \"|\" separator, to keep the table aligned. The table will
20198 still be marked for re-alignment if the field did fill the entire column,
20199 because, in this case the deletion might narrow the column."
20200 (interactive "p")
20201 (save-match-data
20202 (org-check-before-invisible-edit 'delete-backward)
20203 (if (and (org-at-table-p)
20204 (eq N 1)
20205 (string-match "|" (buffer-substring (point-at-bol) (point)))
20206 (looking-at ".*?|"))
20207 (let ((pos (point))
20208 (noalign (looking-at "[^|\n\r]* |"))
20209 (c org-table-may-need-update))
20210 (backward-delete-char N)
20211 (unless overwrite-mode
20212 (skip-chars-forward "^|")
20213 (insert " ")
20214 (goto-char (1- pos)))
20215 ;; noalign: if there were two spaces at the end, this field
20216 ;; does not determine the width of the column.
20217 (when noalign (setq org-table-may-need-update c)))
20218 (backward-delete-char N)
20219 (org-fix-tags-on-the-fly))))
20221 (defun org-delete-char (N)
20222 "Like `delete-char', but insert whitespace at field end in tables.
20223 When deleting characters, in tables this function will insert whitespace in
20224 front of the next \"|\" separator, to keep the table aligned. The table will
20225 still be marked for re-alignment if the field did fill the entire column,
20226 because, in this case the deletion might narrow the column."
20227 (interactive "p")
20228 (save-match-data
20229 (org-check-before-invisible-edit 'delete)
20230 (if (and (org-at-table-p)
20231 (not (bolp))
20232 (not (= (char-after) ?|))
20233 (eq N 1))
20234 (if (looking-at ".*?|")
20235 (let ((pos (point))
20236 (noalign (looking-at "[^|\n\r]* |"))
20237 (c org-table-may-need-update))
20238 (replace-match
20239 (concat (substring (match-string 0) 1 -1) " |") nil t)
20240 (goto-char pos)
20241 ;; noalign: if there were two spaces at the end, this field
20242 ;; does not determine the width of the column.
20243 (when noalign (setq org-table-may-need-update c)))
20244 (delete-char N))
20245 (delete-char N)
20246 (org-fix-tags-on-the-fly))))
20248 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20249 (put 'org-self-insert-command 'delete-selection
20250 (lambda ()
20251 (not (run-hook-with-args-until-success
20252 'self-insert-uses-region-functions))))
20253 (put 'orgtbl-self-insert-command 'delete-selection
20254 (lambda ()
20255 (not (run-hook-with-args-until-success
20256 'self-insert-uses-region-functions))))
20257 (put 'org-delete-char 'delete-selection 'supersede)
20258 (put 'org-delete-backward-char 'delete-selection 'supersede)
20259 (put 'org-yank 'delete-selection 'yank)
20261 ;; Make `flyspell-mode' delay after some commands
20262 (put 'org-self-insert-command 'flyspell-delayed t)
20263 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20264 (put 'org-delete-char 'flyspell-delayed t)
20265 (put 'org-delete-backward-char 'flyspell-delayed t)
20267 ;; Make pabbrev-mode expand after org-mode commands
20268 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20269 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20271 (defun org-remap (map &rest commands)
20272 "In MAP, remap the functions given in COMMANDS.
20273 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20274 (let (new old)
20275 (while commands
20276 (setq old (pop commands) new (pop commands))
20277 (if (fboundp 'command-remapping)
20278 (org-defkey map (vector 'remap old) new)
20279 (substitute-key-definition old new map global-map)))))
20281 (defun org-transpose-words ()
20282 "Transpose words for Org.
20283 This uses the `org-mode-transpose-word-syntax-table' syntax
20284 table, which interprets characters in `org-emphasis-alist' as
20285 word constituents."
20286 (interactive)
20287 (with-syntax-table org-mode-transpose-word-syntax-table
20288 (call-interactively 'transpose-words)))
20289 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20291 (when (eq org-enable-table-editor 'optimized)
20292 ;; If the user wants maximum table support, we need to hijack
20293 ;; some standard editing functions
20294 (org-remap org-mode-map
20295 'self-insert-command 'org-self-insert-command
20296 'delete-char 'org-delete-char
20297 'delete-backward-char 'org-delete-backward-char)
20298 (org-defkey org-mode-map "|" 'org-force-self-insert))
20300 (defvar org-ctrl-c-ctrl-c-hook nil
20301 "Hook for functions attaching themselves to `C-c C-c'.
20303 This can be used to add additional functionality to the C-c C-c
20304 key which executes context-dependent commands. This hook is run
20305 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20306 run after the last test.
20308 Each function will be called with no arguments. The function
20309 must check if the context is appropriate for it to act. If yes,
20310 it should do its thing and then return a non-nil value. If the
20311 context is wrong, just do nothing and return nil.")
20313 (defvar org-ctrl-c-ctrl-c-final-hook nil
20314 "Hook for functions attaching themselves to `C-c C-c'.
20316 This can be used to add additional functionality to the C-c C-c
20317 key which executes context-dependent commands. This hook is run
20318 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20319 before the first test.
20321 Each function will be called with no arguments. The function
20322 must check if the context is appropriate for it to act. If yes,
20323 it should do its thing and then return a non-nil value. If the
20324 context is wrong, just do nothing and return nil.")
20326 (defvar org-tab-first-hook nil
20327 "Hook for functions to attach themselves to TAB.
20328 See `org-ctrl-c-ctrl-c-hook' for more information.
20329 This hook runs as the first action when TAB is pressed, even before
20330 `org-cycle' messes around with the `outline-regexp' to cater for
20331 inline tasks and plain list item folding.
20332 If any function in this hook returns t, any other actions that
20333 would have been caused by TAB (such as table field motion or visibility
20334 cycling) will not occur.")
20336 (defvar org-tab-after-check-for-table-hook nil
20337 "Hook for functions to attach themselves to TAB.
20338 See `org-ctrl-c-ctrl-c-hook' for more information.
20339 This hook runs after it has been established that the cursor is not in a
20340 table, but before checking if the cursor is in a headline or if global cycling
20341 should be done.
20342 If any function in this hook returns t, not other actions like visibility
20343 cycling will be done.")
20345 (defvar org-tab-after-check-for-cycling-hook nil
20346 "Hook for functions to attach themselves to TAB.
20347 See `org-ctrl-c-ctrl-c-hook' for more information.
20348 This hook runs after it has been established that not table field motion and
20349 not visibility should be done because of current context. This is probably
20350 the place where a package like yasnippets can hook in.")
20352 (defvar org-tab-before-tab-emulation-hook nil
20353 "Hook for functions to attach themselves to TAB.
20354 See `org-ctrl-c-ctrl-c-hook' for more information.
20355 This hook runs after every other options for TAB have been exhausted, but
20356 before indentation and \t insertion takes place.")
20358 (defvar org-metaleft-hook nil
20359 "Hook for functions attaching themselves to `M-left'.
20360 See `org-ctrl-c-ctrl-c-hook' for more information.")
20361 (defvar org-metaright-hook nil
20362 "Hook for functions attaching themselves to `M-right'.
20363 See `org-ctrl-c-ctrl-c-hook' for more information.")
20364 (defvar org-metaup-hook nil
20365 "Hook for functions attaching themselves to `M-up'.
20366 See `org-ctrl-c-ctrl-c-hook' for more information.")
20367 (defvar org-metadown-hook nil
20368 "Hook for functions attaching themselves to `M-down'.
20369 See `org-ctrl-c-ctrl-c-hook' for more information.")
20370 (defvar org-shiftmetaleft-hook nil
20371 "Hook for functions attaching themselves to `M-S-left'.
20372 See `org-ctrl-c-ctrl-c-hook' for more information.")
20373 (defvar org-shiftmetaright-hook nil
20374 "Hook for functions attaching themselves to `M-S-right'.
20375 See `org-ctrl-c-ctrl-c-hook' for more information.")
20376 (defvar org-shiftmetaup-hook nil
20377 "Hook for functions attaching themselves to `M-S-up'.
20378 See `org-ctrl-c-ctrl-c-hook' for more information.")
20379 (defvar org-shiftmetadown-hook nil
20380 "Hook for functions attaching themselves to `M-S-down'.
20381 See `org-ctrl-c-ctrl-c-hook' for more information.")
20382 (defvar org-metareturn-hook nil
20383 "Hook for functions attaching themselves to `M-RET'.
20384 See `org-ctrl-c-ctrl-c-hook' for more information.")
20385 (defvar org-shiftup-hook nil
20386 "Hook for functions attaching themselves to `S-up'.
20387 See `org-ctrl-c-ctrl-c-hook' for more information.")
20388 (defvar org-shiftup-final-hook nil
20389 "Hook for functions attaching themselves to `S-up'.
20390 This one runs after all other options except shift-select have been excluded.
20391 See `org-ctrl-c-ctrl-c-hook' for more information.")
20392 (defvar org-shiftdown-hook nil
20393 "Hook for functions attaching themselves to `S-down'.
20394 See `org-ctrl-c-ctrl-c-hook' for more information.")
20395 (defvar org-shiftdown-final-hook nil
20396 "Hook for functions attaching themselves to `S-down'.
20397 This one runs after all other options except shift-select have been excluded.
20398 See `org-ctrl-c-ctrl-c-hook' for more information.")
20399 (defvar org-shiftleft-hook nil
20400 "Hook for functions attaching themselves to `S-left'.
20401 See `org-ctrl-c-ctrl-c-hook' for more information.")
20402 (defvar org-shiftleft-final-hook nil
20403 "Hook for functions attaching themselves to `S-left'.
20404 This one runs after all other options except shift-select have been excluded.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.")
20406 (defvar org-shiftright-hook nil
20407 "Hook for functions attaching themselves to `S-right'.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.")
20409 (defvar org-shiftright-final-hook nil
20410 "Hook for functions attaching themselves to `S-right'.
20411 This one runs after all other options except shift-select have been excluded.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.")
20414 (defun org-modifier-cursor-error ()
20415 "Throw an error, a modified cursor command was applied in wrong context."
20416 (user-error "This command is active in special context like tables, headlines or items"))
20418 (defun org-shiftselect-error ()
20419 "Throw an error because Shift-Cursor command was applied in wrong context."
20420 (if (and (boundp 'shift-select-mode) shift-select-mode)
20421 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20422 (user-error "This command works only in special context like headlines or timestamps")))
20424 (defun org-call-for-shift-select (cmd)
20425 (let ((this-command-keys-shift-translated t))
20426 (call-interactively cmd)))
20428 (defun org-shifttab (&optional arg)
20429 "Global visibility cycling or move to previous table field.
20430 Call `org-table-previous-field' within a table.
20431 When ARG is nil, cycle globally through visibility states.
20432 When ARG is a numeric prefix, show contents of this level."
20433 (interactive "P")
20434 (cond
20435 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20436 ((integerp arg)
20437 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20438 (message "Content view to level: %d" arg)
20439 (org-content (prefix-numeric-value arg2))
20440 (org-cycle-show-empty-lines t)
20441 (setq org-cycle-global-status 'overview)))
20442 (t (call-interactively 'org-global-cycle))))
20444 (defun org-shiftmetaleft ()
20445 "Promote subtree or delete table column.
20446 Calls `org-promote-subtree', `org-outdent-item-tree', or
20447 `org-table-delete-column', depending on context. See the
20448 individual commands for more information."
20449 (interactive)
20450 (cond
20451 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20452 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20453 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20454 ((if (not (org-region-active-p)) (org-at-item-p)
20455 (save-excursion (goto-char (region-beginning))
20456 (org-at-item-p)))
20457 (call-interactively 'org-outdent-item-tree))
20458 (t (org-modifier-cursor-error))))
20460 (defun org-shiftmetaright ()
20461 "Demote subtree or insert table column.
20462 Calls `org-demote-subtree', `org-indent-item-tree', or
20463 `org-table-insert-column', depending on context. See the
20464 individual commands for more information."
20465 (interactive)
20466 (cond
20467 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20468 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20469 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20470 ((if (not (org-region-active-p)) (org-at-item-p)
20471 (save-excursion (goto-char (region-beginning))
20472 (org-at-item-p)))
20473 (call-interactively 'org-indent-item-tree))
20474 (t (org-modifier-cursor-error))))
20476 (defun org-shiftmetaup (&optional _arg)
20477 "Drag the line at point up.
20478 In a table, kill the current row.
20479 On a clock timestamp, update the value of the timestamp like `S-<up>'
20480 but also adjust the previous clocked item in the clock history.
20481 Everywhere else, drag the line at point up."
20482 (interactive "P")
20483 (cond
20484 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20485 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20486 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20487 (call-interactively 'org-timestamp-up)))
20488 (t (call-interactively 'org-drag-line-backward))))
20490 (defun org-shiftmetadown (&optional _arg)
20491 "Drag the line at point down.
20492 In a table, insert an empty row at the current line.
20493 On a clock timestamp, update the value of the timestamp like `S-<down>'
20494 but also adjust the previous clocked item in the clock history.
20495 Everywhere else, drag the line at point down."
20496 (interactive "P")
20497 (cond
20498 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20499 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20500 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20501 (call-interactively 'org-timestamp-down)))
20502 (t (call-interactively 'org-drag-line-forward))))
20504 (defsubst org-hidden-tree-error ()
20505 (user-error
20506 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20508 (defun org-metaleft (&optional _arg)
20509 "Promote heading, list item at point or move table column left.
20511 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20512 depending on context. With no specific context, calls the Emacs
20513 default `backward-word'. See the individual commands for more
20514 information.
20516 This function runs the hook `org-metaleft-hook' as a first step,
20517 and returns at first non-nil value."
20518 (interactive "P")
20519 (cond
20520 ((run-hook-with-args-until-success 'org-metaleft-hook))
20521 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20522 ((org-with-limited-levels
20523 (or (org-at-heading-p)
20524 (and (org-region-active-p)
20525 (save-excursion
20526 (goto-char (region-beginning))
20527 (org-at-heading-p)))))
20528 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20529 (call-interactively 'org-do-promote))
20530 ;; At an inline task.
20531 ((org-at-heading-p)
20532 (call-interactively 'org-inlinetask-promote))
20533 ((or (org-at-item-p)
20534 (and (org-region-active-p)
20535 (save-excursion
20536 (goto-char (region-beginning))
20537 (org-at-item-p))))
20538 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20539 (call-interactively 'org-outdent-item))
20540 (t (call-interactively 'backward-word))))
20542 (defun org-metaright (&optional _arg)
20543 "Demote heading, list item at point or move table column right.
20545 In front of a drawer or a block keyword, indent it correctly.
20547 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20548 `org-indnet-drawer' or `org-indent-block' depending on context.
20549 With no specific context, calls the Emacs default `forward-word'.
20550 See the individual commands for more information.
20552 This function runs the hook `org-metaright-hook' as a first step,
20553 and returns at first non-nil value."
20554 (interactive "P")
20555 (cond
20556 ((run-hook-with-args-until-success 'org-metaright-hook))
20557 ((org-at-table-p) (call-interactively 'org-table-move-column))
20558 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20559 ((org-at-block-p) (call-interactively 'org-indent-block))
20560 ((org-with-limited-levels
20561 (or (org-at-heading-p)
20562 (and (org-region-active-p)
20563 (save-excursion
20564 (goto-char (region-beginning))
20565 (org-at-heading-p)))))
20566 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20567 (call-interactively 'org-do-demote))
20568 ;; At an inline task.
20569 ((org-at-heading-p)
20570 (call-interactively 'org-inlinetask-demote))
20571 ((or (org-at-item-p)
20572 (and (org-region-active-p)
20573 (save-excursion
20574 (goto-char (region-beginning))
20575 (org-at-item-p))))
20576 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20577 (call-interactively 'org-indent-item))
20578 (t (call-interactively 'forward-word))))
20580 (defun org-check-for-hidden (what)
20581 "Check if there are hidden headlines/items in the current visual line.
20582 WHAT can be either `headlines' or `items'. If the current line is
20583 an outline or item heading and it has a folded subtree below it,
20584 this function returns t, nil otherwise."
20585 (let ((re (cond
20586 ((eq what 'headlines) org-outline-regexp-bol)
20587 ((eq what 'items) (org-item-beginning-re))
20588 (t (error "This should not happen"))))
20589 beg end)
20590 (save-excursion
20591 (catch 'exit
20592 (unless (org-region-active-p)
20593 (setq beg (point-at-bol))
20594 (beginning-of-line 2)
20595 (while (and (not (eobp)) ;; this is like `next-line'
20596 (get-char-property (1- (point)) 'invisible))
20597 (beginning-of-line 2))
20598 (setq end (point))
20599 (goto-char beg)
20600 (goto-char (point-at-eol))
20601 (setq end (max end (point)))
20602 (while (re-search-forward re end t)
20603 (when (get-char-property (match-beginning 0) 'invisible)
20604 (throw 'exit t))))
20605 nil))))
20607 (defun org-metaup (&optional _arg)
20608 "Move subtree up or move table row up.
20609 Calls `org-move-subtree-up' or `org-table-move-row' or
20610 `org-move-item-up', depending on context. See the individual commands
20611 for more information."
20612 (interactive "P")
20613 (cond
20614 ((run-hook-with-args-until-success 'org-metaup-hook))
20615 ((org-region-active-p)
20616 (let* ((a (min (region-beginning) (region-end)))
20617 (b (1- (max (region-beginning) (region-end))))
20618 (c (save-excursion (goto-char a)
20619 (move-beginning-of-line 0)))
20620 (d (save-excursion (goto-char a)
20621 (move-end-of-line 0) (point))))
20622 (transpose-regions a b c d)
20623 (goto-char c)))
20624 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20625 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20626 ((org-at-item-p) (call-interactively 'org-move-item-up))
20627 (t (org-drag-element-backward))))
20629 (defun org-metadown (&optional _arg)
20630 "Move subtree down or move table row down.
20631 Calls `org-move-subtree-down' or `org-table-move-row' or
20632 `org-move-item-down', depending on context. See the individual
20633 commands for more information."
20634 (interactive "P")
20635 (cond
20636 ((run-hook-with-args-until-success 'org-metadown-hook))
20637 ((org-region-active-p)
20638 (let* ((a (min (region-beginning) (region-end)))
20639 (b (max (region-beginning) (region-end)))
20640 (c (save-excursion (goto-char b)
20641 (move-beginning-of-line 1)))
20642 (d (save-excursion (goto-char b)
20643 (move-end-of-line 1) (1+ (point)))))
20644 (transpose-regions a b c d)
20645 (goto-char d)))
20646 ((org-at-table-p) (call-interactively 'org-table-move-row))
20647 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20648 ((org-at-item-p) (call-interactively 'org-move-item-down))
20649 (t (org-drag-element-forward))))
20651 (defun org-shiftup (&optional arg)
20652 "Increase item in timestamp or increase priority of current headline.
20653 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20654 depending on context. See the individual commands for more information."
20655 (interactive "P")
20656 (cond
20657 ((run-hook-with-args-until-success 'org-shiftup-hook))
20658 ((and org-support-shift-select (org-region-active-p))
20659 (org-call-for-shift-select 'previous-line))
20660 ((org-at-timestamp-p t)
20661 (call-interactively (if org-edit-timestamp-down-means-later
20662 'org-timestamp-down 'org-timestamp-up)))
20663 ((and (not (eq org-support-shift-select 'always))
20664 org-enable-priority-commands
20665 (org-at-heading-p))
20666 (call-interactively 'org-priority-up))
20667 ((and (not org-support-shift-select) (org-at-item-p))
20668 (call-interactively 'org-previous-item))
20669 ((org-clocktable-try-shift 'up arg))
20670 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20671 (org-support-shift-select
20672 (org-call-for-shift-select 'previous-line))
20673 (t (org-shiftselect-error))))
20675 (defun org-shiftdown (&optional arg)
20676 "Decrease item in timestamp or decrease priority of current headline.
20677 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20678 depending on context. See the individual commands for more information."
20679 (interactive "P")
20680 (cond
20681 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20682 ((and org-support-shift-select (org-region-active-p))
20683 (org-call-for-shift-select 'next-line))
20684 ((org-at-timestamp-p t)
20685 (call-interactively (if org-edit-timestamp-down-means-later
20686 'org-timestamp-up 'org-timestamp-down)))
20687 ((and (not (eq org-support-shift-select 'always))
20688 org-enable-priority-commands
20689 (org-at-heading-p))
20690 (call-interactively 'org-priority-down))
20691 ((and (not org-support-shift-select) (org-at-item-p))
20692 (call-interactively 'org-next-item))
20693 ((org-clocktable-try-shift 'down arg))
20694 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20695 (org-support-shift-select
20696 (org-call-for-shift-select 'next-line))
20697 (t (org-shiftselect-error))))
20699 (defun org-shiftright (&optional arg)
20700 "Cycle the thing at point or in the current line, depending on context.
20701 Depending on context, this does one of the following:
20703 - switch a timestamp at point one day into the future
20704 - on a headline, switch to the next TODO keyword.
20705 - on an item, switch entire list to the next bullet type
20706 - on a property line, switch to the next allowed value
20707 - on a clocktable definition line, move time block into the future"
20708 (interactive "P")
20709 (cond
20710 ((run-hook-with-args-until-success 'org-shiftright-hook))
20711 ((and org-support-shift-select (org-region-active-p))
20712 (org-call-for-shift-select 'forward-char))
20713 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20714 ((and (not (eq org-support-shift-select 'always))
20715 (org-at-heading-p))
20716 (let ((org-inhibit-logging
20717 (not org-treat-S-cursor-todo-selection-as-state-change))
20718 (org-inhibit-blocking
20719 (not org-treat-S-cursor-todo-selection-as-state-change)))
20720 (org-call-with-arg 'org-todo 'right)))
20721 ((or (and org-support-shift-select
20722 (not (eq org-support-shift-select 'always))
20723 (org-at-item-bullet-p))
20724 (and (not org-support-shift-select) (org-at-item-p)))
20725 (org-call-with-arg 'org-cycle-list-bullet nil))
20726 ((and (not (eq org-support-shift-select 'always))
20727 (org-at-property-p))
20728 (call-interactively 'org-property-next-allowed-value))
20729 ((org-clocktable-try-shift 'right arg))
20730 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20731 (org-support-shift-select
20732 (org-call-for-shift-select 'forward-char))
20733 (t (org-shiftselect-error))))
20735 (defun org-shiftleft (&optional arg)
20736 "Cycle the thing at point or in the current line, depending on context.
20737 Depending on context, this does one of the following:
20739 - switch a timestamp at point one day into the past
20740 - on a headline, switch to the previous TODO keyword.
20741 - on an item, switch entire list to the previous bullet type
20742 - on a property line, switch to the previous allowed value
20743 - on a clocktable definition line, move time block into the past"
20744 (interactive "P")
20745 (cond
20746 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20747 ((and org-support-shift-select (org-region-active-p))
20748 (org-call-for-shift-select 'backward-char))
20749 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20750 ((and (not (eq org-support-shift-select 'always))
20751 (org-at-heading-p))
20752 (let ((org-inhibit-logging
20753 (not org-treat-S-cursor-todo-selection-as-state-change))
20754 (org-inhibit-blocking
20755 (not org-treat-S-cursor-todo-selection-as-state-change)))
20756 (org-call-with-arg 'org-todo 'left)))
20757 ((or (and org-support-shift-select
20758 (not (eq org-support-shift-select 'always))
20759 (org-at-item-bullet-p))
20760 (and (not org-support-shift-select) (org-at-item-p)))
20761 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20762 ((and (not (eq org-support-shift-select 'always))
20763 (org-at-property-p))
20764 (call-interactively 'org-property-previous-allowed-value))
20765 ((org-clocktable-try-shift 'left arg))
20766 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20767 (org-support-shift-select
20768 (org-call-for-shift-select 'backward-char))
20769 (t (org-shiftselect-error))))
20771 (defun org-shiftcontrolright ()
20772 "Switch to next TODO set."
20773 (interactive)
20774 (cond
20775 ((and org-support-shift-select (org-region-active-p))
20776 (org-call-for-shift-select 'forward-word))
20777 ((and (not (eq org-support-shift-select 'always))
20778 (org-at-heading-p))
20779 (org-call-with-arg 'org-todo 'nextset))
20780 (org-support-shift-select
20781 (org-call-for-shift-select 'forward-word))
20782 (t (org-shiftselect-error))))
20784 (defun org-shiftcontrolleft ()
20785 "Switch to previous TODO set."
20786 (interactive)
20787 (cond
20788 ((and org-support-shift-select (org-region-active-p))
20789 (org-call-for-shift-select 'backward-word))
20790 ((and (not (eq org-support-shift-select 'always))
20791 (org-at-heading-p))
20792 (org-call-with-arg 'org-todo 'previousset))
20793 (org-support-shift-select
20794 (org-call-for-shift-select 'backward-word))
20795 (t (org-shiftselect-error))))
20797 (defun org-shiftcontrolup (&optional n)
20798 "Change timestamps synchronously up in CLOCK log lines.
20799 Optional argument N tells to change by that many units."
20800 (interactive "P")
20801 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20802 (let (org-support-shift-select)
20803 (org-clock-timestamps-up n))
20804 (user-error "Not at a clock log")))
20806 (defun org-shiftcontroldown (&optional n)
20807 "Change timestamps synchronously down in CLOCK log lines.
20808 Optional argument N tells to change by that many units."
20809 (interactive "P")
20810 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20811 (let (org-support-shift-select)
20812 (org-clock-timestamps-down n))
20813 (user-error "Not at a clock log")))
20815 (defun org-increase-number-at-point (&optional inc)
20816 "Increment the number at point.
20817 With an optional prefix numeric argument INC, increment using
20818 this numeric value."
20819 (interactive "p")
20820 (if (not (number-at-point))
20821 (user-error "Not on a number")
20822 (unless inc (setq inc 1))
20823 (let ((pos (point))
20824 (beg (skip-chars-backward "-+^/*0-9eE."))
20825 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20826 (setq nap (buffer-substring-no-properties
20827 (+ pos beg) (+ pos beg end)))
20828 (delete-region (+ pos beg) (+ pos beg end))
20829 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20830 (when (org-at-table-p)
20831 (org-table-align)
20832 (org-table-end-of-field 1))))
20834 (defun org-decrease-number-at-point (&optional inc)
20835 "Decrement the number at point.
20836 With an optional prefix numeric argument INC, decrement using
20837 this numeric value."
20838 (interactive "p")
20839 (org-increase-number-at-point (- (or inc 1))))
20841 (defun org-ctrl-c-ret ()
20842 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20843 (interactive)
20844 (cond
20845 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20846 (t (call-interactively 'org-insert-heading))))
20848 (defun org-find-visible ()
20849 (let ((s (point)))
20850 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20851 (get-char-property s 'invisible)))
20853 (defun org-find-invisible ()
20854 (let ((s (point)))
20855 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20856 (not (get-char-property s 'invisible))))
20859 (defun org-copy-visible (beg end)
20860 "Copy the visible parts of the region."
20861 (interactive "r")
20862 (let (snippets s)
20863 (save-excursion
20864 (save-restriction
20865 (narrow-to-region beg end)
20866 (setq s (goto-char (point-min)))
20867 (while (not (= (point) (point-max)))
20868 (goto-char (org-find-invisible))
20869 (push (buffer-substring s (point)) snippets)
20870 (setq s (goto-char (org-find-visible))))))
20871 (kill-new (apply 'concat (nreverse snippets)))))
20873 (defun org-copy-special ()
20874 "Copy region in table or copy current subtree.
20875 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20876 See the individual commands for more information."
20877 (interactive)
20878 (call-interactively
20879 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20881 (defun org-cut-special ()
20882 "Cut region in table or cut current subtree.
20883 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20884 See the individual commands for more information."
20885 (interactive)
20886 (call-interactively
20887 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20889 (defun org-paste-special (arg)
20890 "Paste rectangular region into table, or past subtree relative to level.
20891 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20892 See the individual commands for more information."
20893 (interactive "P")
20894 (if (org-at-table-p)
20895 (org-table-paste-rectangle)
20896 (org-paste-subtree arg)))
20898 (defsubst org-in-fixed-width-region-p ()
20899 "Is point in a fixed-width region?"
20900 (save-match-data
20901 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20903 (defun org-edit-special (&optional arg)
20904 "Call a special editor for the element at point.
20905 When at a table, call the formula editor with `org-table-edit-formulas'.
20906 When in a source code block, call `org-edit-src-code'.
20907 When in a fixed-width region, call `org-edit-fixed-width-region'.
20908 When in an export block, call `org-edit-export-block'.
20909 When at an #+INCLUDE keyword, visit the included file.
20910 When at a footnote reference, call `org-edit-footnote-reference'
20911 On a link, call `ffap' to visit the link at point.
20912 Otherwise, return a user error."
20913 (interactive "P")
20914 (let ((element (org-element-at-point)))
20915 (cl-assert (not buffer-read-only) nil
20916 "Buffer is read-only: %s" (buffer-name))
20917 (pcase (org-element-type element)
20918 (`src-block
20919 (if (not arg) (org-edit-src-code)
20920 (let* ((info (org-babel-get-src-block-info))
20921 (lang (nth 0 info))
20922 (params (nth 2 info))
20923 (session (cdr (assq :session params))))
20924 (if (not session) (org-edit-src-code)
20925 ;; At a src-block with a session and function called with
20926 ;; an ARG: switch to the buffer related to the inferior
20927 ;; process.
20928 (switch-to-buffer
20929 (funcall (intern (concat "org-babel-prep-session:" lang))
20930 session params))))))
20931 (`keyword
20932 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20933 (org-open-link-from-string
20934 (format "[[%s]]"
20935 (expand-file-name
20936 (let ((value (org-element-property :value element)))
20937 (cond ((not (org-string-nw-p value))
20938 (user-error "No file to edit"))
20939 ((string-match "\\`\"\\(.*?\\)\"" value)
20940 (match-string 1 value))
20941 ((string-match "\\`[^ \t\"]\\S-*" value)
20942 (match-string 0 value))
20943 (t (user-error "No valid file specified")))))))
20944 (user-error "No special environment to edit here")))
20945 (`table
20946 (if (eq (org-element-property :type element) 'table.el)
20947 (org-edit-table.el)
20948 (call-interactively 'org-table-edit-formulas)))
20949 ;; Only Org tables contain `table-row' type elements.
20950 (`table-row (call-interactively 'org-table-edit-formulas))
20951 (`example-block (org-edit-src-code))
20952 (`export-block (org-edit-export-block))
20953 (`fixed-width (org-edit-fixed-width-region))
20955 ;; No notable element at point. Though, we may be at a link or
20956 ;; a footnote reference, which are objects. Thus, scan deeper.
20957 (let ((context (org-element-context element)))
20958 (pcase (org-element-type context)
20959 (`footnote-reference (org-edit-footnote-reference))
20960 (`inline-src-block (org-edit-inline-src-code))
20961 (`link (call-interactively #'ffap))
20962 (_ (user-error "No special environment to edit here"))))))))
20964 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20965 (defun org-ctrl-c-ctrl-c (&optional arg)
20966 "Set tags in headline, or update according to changed information at point.
20968 This command does many different things, depending on context:
20970 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20971 this is what we do.
20973 - If the cursor is on a statistics cookie, update it.
20975 - If the cursor is in a headline, prompt for tags and insert them
20976 into the current line, aligned to `org-tags-column'. When called
20977 with prefix arg, realign all tags in the current buffer.
20979 - If the cursor is in one of the special #+KEYWORD lines, this
20980 triggers scanning the buffer for these lines and updating the
20981 information.
20983 - If the cursor is inside a table, realign the table. This command
20984 works even if the automatic table editor has been turned off.
20986 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20987 the entire table.
20989 - If the cursor is at a footnote reference or definition, jump to
20990 the corresponding definition or references, respectively.
20992 - If the cursor is a the beginning of a dynamic block, update it.
20994 - If the current buffer is a capture buffer, close note and file it.
20996 - If the cursor is on a <<<target>>>, update radio targets and
20997 corresponding links in this buffer.
20999 - If the cursor is on a numbered item in a plain list, renumber the
21000 ordered list.
21002 - If the cursor is on a checkbox, toggle it.
21004 - If the cursor is on a code block, evaluate it. The variable
21005 `org-confirm-babel-evaluate' can be used to control prompting
21006 before code block evaluation, by default every code block
21007 evaluation requires confirmation. Code block evaluation can be
21008 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21009 (interactive "P")
21010 (cond
21011 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21012 org-occur-highlights)
21013 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21014 (org-remove-occur-highlights)
21015 (message "Temporary highlights/overlays removed from current buffer"))
21016 ((and (local-variable-p 'org-finish-function (current-buffer))
21017 (fboundp org-finish-function))
21018 (funcall org-finish-function))
21019 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21021 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21022 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21023 (user-error "C-c C-c can do nothing useful at this location"))
21024 (let* ((context (org-element-context))
21025 (type (org-element-type context)))
21026 (cl-case type
21027 ;; When at a link, act according to the parent instead.
21028 (link (setq context (org-element-property :parent context))
21029 (setq type (org-element-type context)))
21030 ;; Unsupported object types: refer to the first supported
21031 ;; element or object containing it.
21032 ((bold code entity export-snippet inline-babel-call inline-src-block
21033 italic latex-fragment line-break macro strike-through subscript
21034 superscript underline verbatim)
21035 (setq context
21036 (org-element-lineage
21037 context '(radio-target paragraph verse-block table-cell)))))
21038 ;; For convenience: at the first line of a paragraph on the
21039 ;; same line as an item, apply function on that item instead.
21040 (when (eq type 'paragraph)
21041 (let ((parent (org-element-property :parent context)))
21042 (when (and (eq (org-element-type parent) 'item)
21043 (= (line-beginning-position)
21044 (org-element-property :begin parent)))
21045 (setq context parent type 'item))))
21046 ;; Act according to type of element or object at point.
21047 (cl-case type
21048 (clock (org-clock-update-time-maybe))
21049 (dynamic-block
21050 (save-excursion
21051 (goto-char (org-element-property :post-affiliated context))
21052 (org-update-dblock)))
21053 (footnote-definition
21054 (goto-char (org-element-property :post-affiliated context))
21055 (call-interactively 'org-footnote-action))
21056 (footnote-reference (call-interactively 'org-footnote-action))
21057 ((headline inlinetask)
21058 (save-excursion (goto-char (org-element-property :begin context))
21059 (call-interactively 'org-set-tags)))
21060 (item
21061 ;; At an item: a double C-u set checkbox to "[-]"
21062 ;; unconditionally, whereas a single one will toggle its
21063 ;; presence. Without a universal argument, if the item
21064 ;; has a checkbox, toggle it. Otherwise repair the list.
21065 (let* ((box (org-element-property :checkbox context))
21066 (struct (org-element-property :structure context))
21067 (old-struct (copy-tree struct))
21068 (parents (org-list-parents-alist struct))
21069 (prevs (org-list-prevs-alist struct))
21070 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21071 (org-list-set-checkbox
21072 (org-element-property :begin context) struct
21073 (cond ((equal arg '(16)) "[-]")
21074 ((and (not box) (equal arg '(4))) "[ ]")
21075 ((or (not box) (equal arg '(4))) nil)
21076 ((eq box 'on) "[ ]")
21077 (t "[X]")))
21078 ;; Mimic `org-list-write-struct' but with grabbing
21079 ;; a return value from `org-list-struct-fix-box'.
21080 (org-list-struct-fix-ind struct parents 2)
21081 (org-list-struct-fix-item-end struct)
21082 (org-list-struct-fix-bul struct prevs)
21083 (org-list-struct-fix-ind struct parents)
21084 (let ((block-item
21085 (org-list-struct-fix-box struct parents prevs orderedp)))
21086 (if (and box (equal struct old-struct))
21087 (if (equal arg '(16))
21088 (message "Checkboxes already reset")
21089 (user-error "Cannot toggle this checkbox: %s"
21090 (if (eq box 'on)
21091 "all subitems checked"
21092 "unchecked subitems")))
21093 (org-list-struct-apply-struct struct old-struct)
21094 (org-update-checkbox-count-maybe))
21095 (when block-item
21096 (message "Checkboxes were removed due to empty box at line %d"
21097 (org-current-line block-item))))))
21098 (keyword
21099 (let ((org-inhibit-startup-visibility-stuff t)
21100 (org-startup-align-all-tables nil))
21101 (when (boundp 'org-table-coordinate-overlays)
21102 (mapc #'delete-overlay org-table-coordinate-overlays)
21103 (setq org-table-coordinate-overlays nil))
21104 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21105 (message "Local setup has been refreshed"))
21106 (plain-list
21107 ;; At a plain list, with a double C-u argument, set
21108 ;; checkboxes of each item to "[-]", whereas a single one
21109 ;; will toggle their presence according to the state of the
21110 ;; first item in the list. Without an argument, repair the
21111 ;; list.
21112 (let* ((begin (org-element-property :contents-begin context))
21113 (beginm (move-marker (make-marker) begin))
21114 (struct (org-element-property :structure context))
21115 (old-struct (copy-tree struct))
21116 (first-box (save-excursion
21117 (goto-char begin)
21118 (looking-at org-list-full-item-re)
21119 (match-string-no-properties 3)))
21120 (new-box (cond ((equal arg '(16)) "[-]")
21121 ((equal arg '(4)) (unless first-box "[ ]"))
21122 ((equal first-box "[X]") "[ ]")
21123 (t "[X]"))))
21124 (cond
21125 (arg
21126 (dolist (pos
21127 (org-list-get-all-items
21128 begin struct (org-list-prevs-alist struct)))
21129 (org-list-set-checkbox pos struct new-box)))
21130 ((and first-box (eq (point) begin))
21131 ;; For convenience, when point is at bol on the first
21132 ;; item of the list and no argument is provided, simply
21133 ;; toggle checkbox of that item, if any.
21134 (org-list-set-checkbox begin struct new-box)))
21135 (org-list-write-struct
21136 struct (org-list-parents-alist struct) old-struct)
21137 (org-update-checkbox-count-maybe)
21138 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21139 ((property-drawer node-property)
21140 (call-interactively 'org-property-action))
21141 ((radio-target target)
21142 (call-interactively 'org-update-radio-target-regexp))
21143 (statistics-cookie
21144 (call-interactively 'org-update-statistics-cookies))
21145 ((table table-cell table-row)
21146 ;; At a table, recalculate every field and align it. Also
21147 ;; send the table if necessary. If the table has
21148 ;; a `table.el' type, just give up. At a table row or
21149 ;; cell, maybe recalculate line but always align table.
21150 (if (eq (org-element-property :type context) 'table.el)
21151 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21152 Use \\[org-edit-special] to edit table.el tables"))
21153 (let ((org-enable-table-editor t))
21154 (if (or (eq type 'table)
21155 ;; Check if point is at a TBLFM line.
21156 (and (eq type 'table-row)
21157 (= (point) (org-element-property :end context))))
21158 (save-excursion
21159 (if (org-at-TBLFM-p)
21160 (progn (require 'org-table)
21161 (org-table-calc-current-TBLFM))
21162 (goto-char (org-element-property :contents-begin context))
21163 (org-call-with-arg 'org-table-recalculate (or arg t))
21164 (orgtbl-send-table 'maybe)))
21165 (org-table-maybe-eval-formula)
21166 (cond (arg (call-interactively 'org-table-recalculate))
21167 ((org-table-maybe-recalculate-line))
21168 (t (org-table-align)))))))
21169 (timestamp (org-timestamp-change 0 'day))
21170 (otherwise
21171 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21172 (user-error
21173 "C-c C-c can do nothing useful at this location")))))))))
21175 (defun org-mode-restart ()
21176 (interactive)
21177 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21178 (funcall major-mode)
21179 (hack-local-variables)
21180 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21181 (org-indent-mode -1)))
21182 (message "%s restarted" major-mode))
21184 (defun org-kill-note-or-show-branches ()
21185 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21186 (interactive)
21187 (if (not org-finish-function)
21188 (progn
21189 (outline-hide-subtree)
21190 (call-interactively 'outline-show-branches))
21191 (let ((org-note-abort t))
21192 (funcall org-finish-function))))
21194 (defun org-delete-indentation (&optional ARG)
21195 "Join current line to previous and fix whitespace at join.
21197 If previous line is a headline add to headline title. Otherwise
21198 the function calls `delete-indentation'.
21200 With argument, join this line to following line."
21201 (interactive "*P")
21202 (if (save-excursion
21203 (if ARG (beginning-of-line)
21204 (forward-line -1))
21205 (looking-at org-complex-heading-regexp))
21206 ;; At headline.
21207 (let ((tags-column (when (match-beginning 5)
21208 (save-excursion (goto-char (match-beginning 5))
21209 (current-column))))
21210 (string (concat " " (progn (when ARG (forward-line 1))
21211 (org-trim (delete-and-extract-region
21212 (line-beginning-position)
21213 (line-end-position)))))))
21214 (unless (bobp) (delete-region (point) (1- (point))))
21215 (goto-char (or (match-end 4)
21216 (match-beginning 5)
21217 (match-end 0)))
21218 (skip-chars-backward " \t")
21219 (save-excursion (insert string))
21220 ;; Adjust alignment of tags.
21221 (when tags-column
21222 (org-align-tags-here (if org-auto-align-tags
21223 org-tags-column
21224 tags-column))))
21225 (delete-indentation ARG)))
21227 (defun org-open-line (n)
21228 "Insert a new row in tables, call `open-line' elsewhere.
21229 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21230 (interactive "*p")
21231 (cond
21232 ((not org-special-ctrl-o)
21233 (open-line n))
21234 ((org-at-table-p)
21235 (org-table-insert-row))
21237 (open-line n))))
21239 (defun org-return (&optional indent)
21240 "Goto next table row or insert a newline.
21242 Calls `org-table-next-row' or `newline', depending on context.
21244 When optional INDENT argument is non-nil, call
21245 `newline-and-indent' instead of `newline'.
21247 When `org-return-follows-link' is non-nil and point is on
21248 a timestamp or a link, call `org-open-at-point'. However, it
21249 will not happen if point is in a table or on a \"dead\"
21250 object (e.g., within a comment). In these case, you need to use
21251 `org-open-at-point' directly."
21252 (interactive)
21253 (let ((context (if org-return-follows-link (org-element-context)
21254 (org-element-at-point))))
21255 (cond
21256 ;; In a table, call `org-table-next-row'.
21257 ((or (and (eq (org-element-type context) 'table)
21258 (>= (point) (org-element-property :contents-begin context))
21259 (< (point) (org-element-property :contents-end context)))
21260 (org-element-lineage context '(table-row table-cell) t))
21261 (org-table-justify-field-maybe)
21262 (call-interactively #'org-table-next-row))
21263 ;; On a link or a timestamp, call `org-open-at-point' if
21264 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21265 ;; locations, e.g., in a comment, as `org-open-at-point'.
21266 ((and org-return-follows-link
21267 (or (org-in-regexp org-ts-regexp-both nil t)
21268 (org-in-regexp org-tsr-regexp-both nil t)
21269 (org-in-regexp org-any-link-re nil t)))
21270 (call-interactively #'org-open-at-point))
21271 ;; Insert newline in heading, but preserve tags.
21272 ((and (not (bolp))
21273 (save-excursion (beginning-of-line)
21274 (looking-at org-complex-heading-regexp)))
21275 ;; At headline. Split line. However, if point is on keyword,
21276 ;; priority cookie or tags, do not break any of them: add
21277 ;; a newline after the headline instead.
21278 (let ((tags-column (and (match-beginning 5)
21279 (save-excursion (goto-char (match-beginning 5))
21280 (current-column))))
21281 (string
21282 (when (and (match-end 4)
21283 (>= (point)
21284 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21285 (<= (point) (match-end 4)))
21286 (delete-and-extract-region (point) (match-end 4)))))
21287 (when (and tags-column string) ; Adjust tag alignment.
21288 (org-align-tags-here
21289 (if org-auto-align-tags org-tags-column tags-column)))
21290 (end-of-line)
21291 (org-show-entry)
21292 (if indent (newline-and-indent) (newline))
21293 (when string (save-excursion (insert (org-trim string))))))
21294 ;; In a list, make sure indenting keeps trailing text within.
21295 ((and indent
21296 (not (eolp))
21297 (org-element-lineage context '(item)))
21298 (let ((trailing-data
21299 (delete-and-extract-region (point) (line-end-position))))
21300 (newline-and-indent)
21301 (save-excursion (insert trailing-data))))
21302 (t (if indent (newline-and-indent) (newline))))))
21304 (defun org-return-indent ()
21305 "Goto next table row or insert a newline and indent.
21306 Calls `org-table-next-row' or `newline-and-indent', depending on
21307 context. See the individual commands for more information."
21308 (interactive)
21309 (org-return t))
21311 (defun org-ctrl-c-star ()
21312 "Compute table, or change heading status of lines.
21313 Calls `org-table-recalculate' or `org-toggle-heading',
21314 depending on context."
21315 (interactive)
21316 (cond
21317 ((org-at-table-p)
21318 (call-interactively 'org-table-recalculate))
21320 ;; Convert all lines in region to list items
21321 (call-interactively 'org-toggle-heading))))
21323 (defun org-ctrl-c-minus ()
21324 "Insert separator line in table or modify bullet status of line.
21325 Also turns a plain line or a region of lines into list items.
21326 Calls `org-table-insert-hline', `org-toggle-item', or
21327 `org-cycle-list-bullet', depending on context."
21328 (interactive)
21329 (cond
21330 ((org-at-table-p)
21331 (call-interactively 'org-table-insert-hline))
21332 ((org-region-active-p)
21333 (call-interactively 'org-toggle-item))
21334 ((org-in-item-p)
21335 (call-interactively 'org-cycle-list-bullet))
21337 (call-interactively 'org-toggle-item))))
21339 (defun org-toggle-item (arg)
21340 "Convert headings or normal lines to items, items to normal lines.
21341 If there is no active region, only the current line is considered.
21343 If the first non blank line in the region is a headline, convert
21344 all headlines to items, shifting text accordingly.
21346 If it is an item, convert all items to normal lines.
21348 If it is normal text, change region into a list of items.
21349 With a prefix argument ARG, change the region in a single item."
21350 (interactive "P")
21351 (let ((shift-text
21352 (function
21353 ;; Shift text in current section to IND, from point to END.
21354 ;; The function leaves point to END line.
21355 (lambda (ind end)
21356 (let ((min-i 1000) (end (copy-marker end)))
21357 ;; First determine the minimum indentation (MIN-I) of
21358 ;; the text.
21359 (save-excursion
21360 (catch 'exit
21361 (while (< (point) end)
21362 (let ((i (org-get-indentation)))
21363 (cond
21364 ;; Skip blank lines and inline tasks.
21365 ((looking-at "^[ \t]*$"))
21366 ((looking-at org-outline-regexp-bol))
21367 ;; We can't find less than 0 indentation.
21368 ((zerop i) (throw 'exit (setq min-i 0)))
21369 ((< i min-i) (setq min-i i))))
21370 (forward-line))))
21371 ;; Then indent each line so that a line indented to
21372 ;; MIN-I becomes indented to IND. Ignore blank lines
21373 ;; and inline tasks in the process.
21374 (let ((delta (- ind min-i)))
21375 (while (< (point) end)
21376 (unless (or (looking-at "^[ \t]*$")
21377 (looking-at org-outline-regexp-bol))
21378 (org-indent-line-to (+ (org-get-indentation) delta)))
21379 (forward-line)))))))
21380 (skip-blanks
21381 (function
21382 ;; Return beginning of first non-blank line, starting from
21383 ;; line at POS.
21384 (lambda (pos)
21385 (save-excursion
21386 (goto-char pos)
21387 (skip-chars-forward " \r\t\n")
21388 (point-at-bol)))))
21389 beg end)
21390 ;; Determine boundaries of changes.
21391 (if (org-region-active-p)
21392 (setq beg (funcall skip-blanks (region-beginning))
21393 end (copy-marker (region-end)))
21394 (setq beg (funcall skip-blanks (point-at-bol))
21395 end (copy-marker (point-at-eol))))
21396 ;; Depending on the starting line, choose an action on the text
21397 ;; between BEG and END.
21398 (org-with-limited-levels
21399 (save-excursion
21400 (goto-char beg)
21401 (cond
21402 ;; Case 1. Start at an item: de-itemize. Note that it only
21403 ;; happens when a region is active: `org-ctrl-c-minus'
21404 ;; would call `org-cycle-list-bullet' otherwise.
21405 ((org-at-item-p)
21406 (while (< (point) end)
21407 (when (org-at-item-p)
21408 (skip-chars-forward " \t")
21409 (delete-region (point) (match-end 0)))
21410 (forward-line)))
21411 ;; Case 2. Start at an heading: convert to items.
21412 ((org-at-heading-p)
21413 (let* ((bul (org-list-bullet-string "-"))
21414 (bul-len (length bul))
21415 (done (org-entry-is-done-p))
21416 (todo (org-entry-is-todo-p))
21417 ;; Indentation of the first heading. It should be
21418 ;; relative to the indentation of its parent, if any.
21419 (start-ind (save-excursion
21420 (cond
21421 ((not org-adapt-indentation) 0)
21422 ((not (outline-previous-heading)) 0)
21423 (t (length (match-string 0))))))
21424 ;; Level of first heading. Further headings will be
21425 ;; compared to it to determine hierarchy in the list.
21426 (ref-level (org-reduced-level (org-outline-level))))
21427 (when (or done todo) (org-todo ""))
21428 (while (< (point) end)
21429 (let* ((level (org-reduced-level (org-outline-level)))
21430 (delta (max 0 (- level ref-level))))
21431 ;; If current headline is less indented than the first
21432 ;; one, set it as reference, in order to preserve
21433 ;; subtrees.
21434 (when (< level ref-level) (setq ref-level level))
21435 (replace-match bul t t)
21436 (org-indent-line-to (+ start-ind (* delta bul-len)))
21437 (when (or done todo)
21438 (let* ((struct (org-list-struct))
21439 (old (copy-tree struct)))
21440 (org-list-set-checkbox (line-beginning-position)
21441 struct
21442 (if done "[X]" "[ ]"))
21443 (org-list-write-struct struct
21444 (org-list-parents-alist struct)
21445 old)))
21446 ;; Ensure all text down to END (or SECTION-END) belongs
21447 ;; to the newly created item.
21448 (let ((section-end (save-excursion
21449 (or (outline-next-heading) (point)))))
21450 (forward-line)
21451 (funcall shift-text
21452 (+ start-ind (* (1+ delta) bul-len))
21453 (min end section-end)))))))
21454 ;; Case 3. Normal line with ARG: make the first line of region
21455 ;; an item, and shift indentation of others lines to
21456 ;; set them as item's body.
21457 (arg (let* ((bul (org-list-bullet-string "-"))
21458 (bul-len (length bul))
21459 (ref-ind (org-get-indentation)))
21460 (skip-chars-forward " \t")
21461 (insert bul)
21462 (forward-line)
21463 (while (< (point) end)
21464 ;; Ensure that lines less indented than first one
21465 ;; still get included in item body.
21466 (funcall shift-text
21467 (+ ref-ind bul-len)
21468 (min end (save-excursion (or (outline-next-heading)
21469 (point)))))
21470 (forward-line))))
21471 ;; Case 4. Normal line without ARG: turn each non-item line
21472 ;; into an item.
21474 (while (< (point) end)
21475 (unless (or (org-at-heading-p) (org-at-item-p))
21476 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21477 (replace-match
21478 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21479 (forward-line))))))))
21481 (defun org-toggle-heading (&optional nstars)
21482 "Convert headings to normal text, or items or text to headings.
21483 If there is no active region, only convert the current line.
21485 With a \\[universal-argument] prefix, convert the whole list at
21486 point into heading.
21488 In a region:
21490 - If the first non blank line is a headline, remove the stars
21491 from all headlines in the region.
21493 - If it is a normal line, turn each and every normal line (i.e.,
21494 not an heading or an item) in the region into headings. If you
21495 want to convert only the first line of this region, use one
21496 universal prefix argument.
21498 - If it is a plain list item, turn all plain list items into headings.
21500 When converting a line into a heading, the number of stars is chosen
21501 such that the lines become children of the current entry. However,
21502 when a numeric prefix argument is given, its value determines the
21503 number of stars to add."
21504 (interactive "P")
21505 (let ((skip-blanks
21506 (function
21507 ;; Return beginning of first non-blank line, starting from
21508 ;; line at POS.
21509 (lambda (pos)
21510 (save-excursion
21511 (goto-char pos)
21512 (while (org-at-comment-p) (forward-line))
21513 (skip-chars-forward " \r\t\n")
21514 (point-at-bol)))))
21515 beg end toggled)
21516 ;; Determine boundaries of changes. If a universal prefix has
21517 ;; been given, put the list in a region. If region ends at a bol,
21518 ;; do not consider the last line to be in the region.
21520 (when (and current-prefix-arg (org-at-item-p))
21521 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21522 (org-mark-element))
21524 (if (org-region-active-p)
21525 (setq beg (funcall skip-blanks (region-beginning))
21526 end (copy-marker (save-excursion
21527 (goto-char (region-end))
21528 (if (bolp) (point) (point-at-eol)))))
21529 (setq beg (funcall skip-blanks (point-at-bol))
21530 end (copy-marker (point-at-eol))))
21531 ;; Ensure inline tasks don't count as headings.
21532 (org-with-limited-levels
21533 (save-excursion
21534 (goto-char beg)
21535 (cond
21536 ;; Case 1. Started at an heading: de-star headings.
21537 ((org-at-heading-p)
21538 (while (< (point) end)
21539 (when (org-at-heading-p t)
21540 (looking-at org-outline-regexp) (replace-match "")
21541 (setq toggled t))
21542 (forward-line)))
21543 ;; Case 2. Started at an item: change items into headlines.
21544 ;; One star will be added by `org-list-to-subtree'.
21545 ((org-at-item-p)
21546 (while (< (point) end)
21547 (when (org-at-item-p)
21548 ;; Pay attention to cases when region ends before list.
21549 (let* ((struct (org-list-struct))
21550 (list-end
21551 (min (org-list-get-bottom-point struct) (1+ end))))
21552 (save-restriction
21553 (narrow-to-region (point) list-end)
21554 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21555 (setq toggled t))
21556 (forward-line)))
21557 ;; Case 3. Started at normal text: make every line an heading,
21558 ;; skipping headlines and items.
21559 (t (let* ((stars
21560 (make-string
21561 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21562 (add-stars
21563 (cond (nstars "") ; stars from prefix only
21564 ((equal stars "") "*") ; before first heading
21565 (org-odd-levels-only "**") ; inside heading, odd
21566 (t "*"))) ; inside heading, oddeven
21567 (rpl (concat stars add-stars " "))
21568 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21569 (while (< (point) (if (equal nstars '(4)) lend end))
21570 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21571 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21572 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21573 (forward-line)))))))
21574 (unless toggled (message "Cannot toggle heading from here"))))
21576 (defun org-meta-return (&optional _arg)
21577 "Insert a new heading or wrap a region in a table.
21578 Calls `org-insert-heading' or `org-table-wrap-region', depending
21579 on context. See the individual commands for more information."
21580 (interactive)
21581 (org-check-before-invisible-edit 'insert)
21582 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21583 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21584 #'org-insert-heading))))
21586 ;;; Menu entries
21588 (defsubst org-in-subtree-not-table-p ()
21589 "Are we in a subtree and not in a table?"
21590 (and (not (org-before-first-heading-p))
21591 (not (org-at-table-p))))
21593 ;; Define the Org-mode menus
21594 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21595 '("Tbl"
21596 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21597 ["Next Field" org-cycle (org-at-table-p)]
21598 ["Previous Field" org-shifttab (org-at-table-p)]
21599 ["Next Row" org-return (org-at-table-p)]
21600 "--"
21601 ["Blank Field" org-table-blank-field (org-at-table-p)]
21602 ["Edit Field" org-table-edit-field (org-at-table-p)]
21603 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21604 "--"
21605 ("Column"
21606 ["Move Column Left" org-metaleft (org-at-table-p)]
21607 ["Move Column Right" org-metaright (org-at-table-p)]
21608 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21609 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21610 ("Row"
21611 ["Move Row Up" org-metaup (org-at-table-p)]
21612 ["Move Row Down" org-metadown (org-at-table-p)]
21613 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21614 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21615 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21616 "--"
21617 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21618 ("Rectangle"
21619 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21620 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21621 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21622 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21623 "--"
21624 ("Calculate"
21625 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21626 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21627 ["Edit Formulas" org-edit-special (org-at-table-p)]
21628 "--"
21629 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21630 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21631 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21632 "--"
21633 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21634 "--"
21635 ["Sum Column/Rectangle" org-table-sum
21636 (or (org-at-table-p) (org-region-active-p))]
21637 ["Which Column?" org-table-current-column (org-at-table-p)])
21638 ["Debug Formulas"
21639 org-table-toggle-formula-debugger
21640 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21641 ["Show Col/Row Numbers"
21642 org-table-toggle-coordinate-overlays
21643 :style toggle
21644 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21645 "--"
21646 ["Create" org-table-create (and (not (org-at-table-p))
21647 org-enable-table-editor)]
21648 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21649 ["Import from File" org-table-import (not (org-at-table-p))]
21650 ["Export to File" org-table-export (org-at-table-p)]
21651 "--"
21652 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21653 "--"
21654 ("Plot"
21655 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21656 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21658 (easy-menu-define org-org-menu org-mode-map "Org menu"
21659 '("Org"
21660 ("Show/Hide"
21661 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21662 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21663 ["Sparse Tree..." org-sparse-tree t]
21664 ["Reveal Context" org-reveal t]
21665 ["Show All" outline-show-all t]
21666 "--"
21667 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21668 "--"
21669 ["New Heading" org-insert-heading t]
21670 ("Navigate Headings"
21671 ["Up" outline-up-heading t]
21672 ["Next" outline-next-visible-heading t]
21673 ["Previous" outline-previous-visible-heading t]
21674 ["Next Same Level" outline-forward-same-level t]
21675 ["Previous Same Level" outline-backward-same-level t]
21676 "--"
21677 ["Jump" org-goto t])
21678 ("Edit Structure"
21679 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21680 "--"
21681 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21682 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21683 "--"
21684 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21685 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21686 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21687 "--"
21688 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21689 "--"
21690 ["Copy visible text" org-copy-visible t]
21691 "--"
21692 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21693 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21694 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21695 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21696 "--"
21697 ["Sort Region/Children" org-sort t]
21698 "--"
21699 ["Convert to odd levels" org-convert-to-odd-levels t]
21700 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21701 ("Editing"
21702 ["Emphasis..." org-emphasize t]
21703 ["Edit Source Example" org-edit-special t]
21704 "--"
21705 ["Footnote new/jump" org-footnote-action t]
21706 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21707 ("Archive"
21708 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21709 "--"
21710 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21711 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21712 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21714 "--"
21715 ("Hyperlinks"
21716 ["Store Link (Global)" org-store-link t]
21717 ["Find existing link to here" org-occur-link-in-agenda-files t]
21718 ["Insert Link" org-insert-link t]
21719 ["Follow Link" org-open-at-point t]
21720 "--"
21721 ["Next link" org-next-link t]
21722 ["Previous link" org-previous-link t]
21723 "--"
21724 ["Descriptive Links"
21725 org-toggle-link-display
21726 :style radio
21727 :selected org-descriptive-links
21729 ["Literal Links"
21730 org-toggle-link-display
21731 :style radio
21732 :selected (not org-descriptive-links)])
21733 "--"
21734 ("TODO Lists"
21735 ["TODO/DONE/-" org-todo t]
21736 ("Select keyword"
21737 ["Next keyword" org-shiftright (org-at-heading-p)]
21738 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21739 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21740 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21741 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21742 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21743 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21744 "--"
21745 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21746 :selected org-enforce-todo-dependencies :style toggle :active t]
21747 "Settings for tree at point"
21748 ["Do Children sequentially" org-toggle-ordered-property :style radio
21749 :selected (org-entry-get nil "ORDERED")
21750 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21751 ["Do Children parallel" org-toggle-ordered-property :style radio
21752 :selected (not (org-entry-get nil "ORDERED"))
21753 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21754 "--"
21755 ["Set Priority" org-priority t]
21756 ["Priority Up" org-shiftup t]
21757 ["Priority Down" org-shiftdown t]
21758 "--"
21759 ["Get news from all feeds" org-feed-update-all t]
21760 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21761 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21762 ("TAGS and Properties"
21763 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21764 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21765 "--"
21766 ["Set property" org-set-property (not (org-before-first-heading-p))]
21767 ["Column view of properties" org-columns t]
21768 ["Insert Column View DBlock" org-insert-columns-dblock t])
21769 ("Dates and Scheduling"
21770 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21771 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21772 ("Change Date"
21773 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21774 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21775 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21776 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21777 ["Compute Time Range" org-evaluate-time-range t]
21778 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21779 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21780 "--"
21781 ["Custom time format" org-toggle-time-stamp-overlays
21782 :style radio :selected org-display-custom-times]
21783 "--"
21784 ["Goto Calendar" org-goto-calendar t]
21785 ["Date from Calendar" org-date-from-calendar t]
21786 "--"
21787 ["Start/Restart Timer" org-timer-start t]
21788 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21789 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21790 ["Insert Timer String" org-timer t]
21791 ["Insert Timer Item" org-timer-item t])
21792 ("Logging work"
21793 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21794 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21795 ["Clock out" org-clock-out t]
21796 ["Clock cancel" org-clock-cancel t]
21797 "--"
21798 ["Mark as default task" org-clock-mark-default-task t]
21799 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21800 ["Goto running clock" org-clock-goto t]
21801 "--"
21802 ["Display times" org-clock-display t]
21803 ["Create clock table" org-clock-report t]
21804 "--"
21805 ["Record DONE time"
21806 (progn (setq org-log-done (not org-log-done))
21807 (message "Switching to %s will %s record a timestamp"
21808 (car org-done-keywords)
21809 (if org-log-done "automatically" "not")))
21810 :style toggle :selected org-log-done])
21811 "--"
21812 ["Agenda Command..." org-agenda t]
21813 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21814 ("File List for Agenda")
21815 ("Special views current file"
21816 ["TODO Tree" org-show-todo-tree t]
21817 ["Check Deadlines" org-check-deadlines t]
21818 ["Timeline" org-timeline t]
21819 ["Tags/Property tree" org-match-sparse-tree t])
21820 "--"
21821 ["Export/Publish..." org-export-dispatch t]
21822 ("LaTeX"
21823 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21824 :selected org-cdlatex-mode]
21825 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21826 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21827 ["Modify math symbol" org-cdlatex-math-modify
21828 (org-inside-LaTeX-fragment-p)]
21829 ["Insert citation" org-reftex-citation t]
21830 "--"
21831 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21832 "--"
21833 ("MobileOrg"
21834 ["Push Files and Views" org-mobile-push t]
21835 ["Get Captured and Flagged" org-mobile-pull t]
21836 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21837 "--"
21838 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21839 "--"
21840 ("Documentation"
21841 ["Show Version" org-version t]
21842 ["Info Documentation" org-info t])
21843 ("Customize"
21844 ["Browse Org Group" org-customize t]
21845 "--"
21846 ["Expand This Menu" org-create-customize-menu
21847 (fboundp 'customize-menu-create)])
21848 ["Send bug report" org-submit-bug-report t]
21849 "--"
21850 ("Refresh/Reload"
21851 ["Refresh setup current buffer" org-mode-restart t]
21852 ["Reload Org (after update)" org-reload t]
21853 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21856 (defun org-info (&optional node)
21857 "Read documentation for Org-mode in the info system.
21858 With optional NODE, go directly to that node."
21859 (interactive)
21860 (info (format "(org)%s" (or node ""))))
21862 ;;;###autoload
21863 (defun org-submit-bug-report ()
21864 "Submit a bug report on Org-mode via mail.
21866 Don't hesitate to report any problems or inaccurate documentation.
21868 If you don't have setup sending mail from (X)Emacs, please copy the
21869 output buffer into your mail program, as it gives us important
21870 information about your Org-mode version and configuration."
21871 (interactive)
21872 (require 'reporter)
21873 (defvar reporter-prompt-for-summary-p)
21874 (org-load-modules-maybe)
21875 (org-require-autoloaded-modules)
21876 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21877 (reporter-submit-bug-report
21878 "emacs-orgmode@gnu.org"
21879 (org-version nil 'full)
21880 (let (list)
21881 (save-window-excursion
21882 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21883 (delete-other-windows)
21884 (erase-buffer)
21885 (insert "You are about to submit a bug report to the Org-mode mailing list.
21887 We would like to add your full Org-mode and Outline configuration to the
21888 bug report. This greatly simplifies the work of the maintainer and
21889 other experts on the mailing list.
21891 HOWEVER, some variables you have customized may contain private
21892 information. The names of customers, colleagues, or friends, might
21893 appear in the form of file names, tags, todo states, or search strings.
21894 If you answer yes to the prompt, you might want to check and remove
21895 such private information before sending the email.")
21896 (add-text-properties (point-min) (point-max) '(face org-warning))
21897 (when (yes-or-no-p "Include your Org-mode configuration ")
21898 (mapatoms
21899 (lambda (v)
21900 (and (boundp v)
21901 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21902 (or (and (symbol-value v)
21903 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21904 (and
21905 (get v 'custom-type) (get v 'standard-value)
21906 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21907 (push v list)))))
21908 (kill-buffer (get-buffer "*Warn about privacy*"))
21909 list))
21910 nil nil
21911 "Remember to cover the basics, that is, what you expected to happen and
21912 what in fact did happen. You don't know how to make a good report? See
21914 http://orgmode.org/manual/Feedback.html#Feedback
21916 Your bug report will be posted to the Org-mode mailing list.
21917 ------------------------------------------------------------------------")
21918 (save-excursion
21919 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21920 (replace-match "\\1Bug: \\3 [\\2]")))))
21923 (defun org-install-agenda-files-menu ()
21924 (let ((bl (buffer-list)))
21925 (save-excursion
21926 (while bl
21927 (set-buffer (pop bl))
21928 (when (derived-mode-p 'org-mode) (setq bl nil)))
21929 (when (derived-mode-p 'org-mode)
21930 (easy-menu-change
21931 '("Org") "File List for Agenda"
21932 (append
21933 (list
21934 ["Edit File List" (org-edit-agenda-file-list) t]
21935 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21936 ["Remove Current File from List" org-remove-file t]
21937 ["Cycle through agenda files" org-cycle-agenda-files t]
21938 ["Occur in all agenda files" org-occur-in-agenda-files t]
21939 "--")
21940 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21942 ;;;; Documentation
21944 (defun org-require-autoloaded-modules ()
21945 (interactive)
21946 (mapc #'require
21947 '(org-agenda org-archive org-attach org-clock org-colview org-id
21948 org-table org-timer)))
21950 ;;;###autoload
21951 (defun org-reload (&optional uncompiled)
21952 "Reload all org lisp files.
21953 With prefix arg UNCOMPILED, load the uncompiled versions."
21954 (interactive "P")
21955 (require 'loadhist)
21956 (let* ((org-dir (org-find-library-dir "org"))
21957 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21958 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21959 (remove-re (mapconcat 'identity
21960 (mapcar (lambda (f) (concat "^" f "$"))
21961 (list (if (featurep 'xemacs)
21962 "org-colview"
21963 "org-colview-xemacs")
21964 "org" "org-loaddefs" "org-version"))
21965 "\\|"))
21966 (feats (delete-dups
21967 (mapcar 'file-name-sans-extension
21968 (mapcar 'file-name-nondirectory
21969 (delq nil
21970 (mapcar 'feature-file
21971 features))))))
21972 (lfeat (append
21973 (sort
21974 (setq feats
21975 (delq nil (mapcar
21976 (lambda (f)
21977 (if (and (string-match feature-re f)
21978 (not (string-match remove-re f)))
21979 f nil))
21980 feats)))
21981 'string-lessp)
21982 (list "org-version" "org")))
21983 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21984 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21985 load-uncore load-misses)
21986 (setq load-misses
21987 (delq 't
21988 (mapcar (lambda (f)
21989 (or (org-load-noerror-mustsuffix (concat org-dir f))
21990 (and (string= org-dir contrib-dir)
21991 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21992 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21993 (add-to-list 'load-uncore f 'append)
21996 lfeat)))
21997 (when load-uncore
21998 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21999 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22000 (if load-misses
22001 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22002 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22003 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22005 ;;;###autoload
22006 (defun org-customize ()
22007 "Call the customize function with org as argument."
22008 (interactive)
22009 (org-load-modules-maybe)
22010 (org-require-autoloaded-modules)
22011 (customize-browse 'org))
22013 (defun org-create-customize-menu ()
22014 "Create a full customization menu for Org-mode, insert it into the menu."
22015 (interactive)
22016 (org-load-modules-maybe)
22017 (org-require-autoloaded-modules)
22018 (if (fboundp 'customize-menu-create)
22019 (progn
22020 (easy-menu-change
22021 '("Org") "Customize"
22022 `(["Browse Org group" org-customize t]
22023 "--"
22024 ,(customize-menu-create 'org)
22025 ["Set" Custom-set t]
22026 ["Save" Custom-save t]
22027 ["Reset to Current" Custom-reset-current t]
22028 ["Reset to Saved" Custom-reset-saved t]
22029 ["Reset to Standard Settings" Custom-reset-standard t]))
22030 (message "\"Org\"-menu now contains full customization menu"))
22031 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22033 ;;;; Miscellaneous stuff
22035 ;;; Generally useful functions
22037 (defun org-get-at-eol (property n)
22038 "Get text property PROPERTY at the end of line less N characters."
22039 (get-text-property (- (point-at-eol) n) property))
22041 (defun org-find-text-property-in-string (prop s)
22042 "Return the first non-nil value of property PROP in string S."
22043 (or (get-text-property 0 prop s)
22044 (get-text-property (or (next-single-property-change 0 prop s) 0)
22045 prop s)))
22047 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22048 "Display the given MESSAGE as a warning."
22049 (if (fboundp 'display-warning)
22050 (display-warning 'org message
22051 (if (featurep 'xemacs) 'warning :warning))
22052 (let ((buf (get-buffer-create "*Org warnings*")))
22053 (with-current-buffer buf
22054 (goto-char (point-max))
22055 (insert "Warning (Org): " message)
22056 (unless (bolp)
22057 (newline)))
22058 (display-buffer buf)
22059 (sit-for 0))))
22061 (defun org-eval (form)
22062 "Eval FORM and return result."
22063 (condition-case error
22064 (eval form)
22065 (error (format "%%![Error: %s]" error))))
22067 (defun org-in-clocktable-p ()
22068 "Check if the cursor is in a clocktable."
22069 (let ((pos (point)) start)
22070 (save-excursion
22071 (end-of-line 1)
22072 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22073 (setq start (match-beginning 0))
22074 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22075 (>= (match-end 0) pos)
22076 start))))
22078 (defun org-in-verbatim-emphasis ()
22079 (save-match-data
22080 (and (org-in-regexp org-emph-re 2)
22081 (>= (point) (match-beginning 3))
22082 (<= (point) (match-end 4))
22083 (member (match-string 3) '("=" "~")))))
22085 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22086 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22087 (if (and marker (marker-buffer marker)
22088 (buffer-live-p (marker-buffer marker)))
22089 (progn
22090 (org-pop-to-buffer-same-window (marker-buffer marker))
22091 (when (or (> marker (point-max)) (< marker (point-min)))
22092 (widen))
22093 (goto-char marker)
22094 (org-show-context 'org-goto))
22095 (if bookmark
22096 (bookmark-jump bookmark)
22097 (error "Cannot find location"))))
22099 (defun org-quote-csv-field (s)
22100 "Quote field for inclusion in CSV material."
22101 (if (string-match "[\",]" s)
22102 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22105 (defun org-force-self-insert (N)
22106 "Needed to enforce self-insert under remapping."
22107 (interactive "p")
22108 (self-insert-command N))
22110 (defun org-string-width (s)
22111 "Compute width of string, ignoring invisible characters.
22112 This ignores character with invisibility property `org-link', and also
22113 characters with property `org-cwidth', because these will become invisible
22114 upon the next fontification round."
22115 (let (b l)
22116 (when (or (eq t buffer-invisibility-spec)
22117 (assq 'org-link buffer-invisibility-spec))
22118 (while (setq b (text-property-any 0 (length s)
22119 'invisible 'org-link s))
22120 (setq s (concat (substring s 0 b)
22121 (substring s (or (next-single-property-change
22122 b 'invisible s)
22123 (length s)))))))
22124 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22125 (setq s (concat (substring s 0 b)
22126 (substring s (or (next-single-property-change
22127 b 'org-cwidth s)
22128 (length s))))))
22129 (setq l (string-width s) b -1)
22130 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22131 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22134 (defun org-shorten-string (s maxlength)
22135 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22136 If the string is shorter or has length MAXLENGTH, just return the
22137 original string. If it is longer, the functions finds a space in the
22138 string, breaks this string off at that locations and adds three dots
22139 as ellipsis. Including the ellipsis, the string will not be longer
22140 than MAXLENGTH. If finding a good breaking point in the string does
22141 not work, the string is just chopped off in the middle of a word
22142 if necessary."
22143 (if (<= (length s) maxlength)
22145 (let* ((n (max (- maxlength 4) 1))
22146 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22147 (if (string-match re s)
22148 (concat (match-string 1 s) "...")
22149 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22151 (defun org-get-indentation (&optional line)
22152 "Get the indentation of the current line, interpreting tabs.
22153 When LINE is given, assume it represents a line and compute its indentation."
22154 (if line
22155 (when (string-match "^ *" (org-remove-tabs line))
22156 (match-end 0))
22157 (save-excursion
22158 (beginning-of-line 1)
22159 (skip-chars-forward " \t")
22160 (current-column))))
22162 (defun org-get-string-indentation (s)
22163 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22164 (let ((n -1) (i 0) (w tab-width) c)
22165 (catch 'exit
22166 (while (< (setq n (1+ n)) (length s))
22167 (setq c (aref s n))
22168 (cond ((= c ?\ ) (setq i (1+ i)))
22169 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22170 (t (throw 'exit t)))))
22173 (defun org-remove-tabs (s &optional width)
22174 "Replace tabulators in S with spaces.
22175 Assumes that s is a single line, starting in column 0."
22176 (setq width (or width tab-width))
22177 (while (string-match "\t" s)
22178 (setq s (replace-match
22179 (make-string
22180 (- (* width (/ (+ (match-beginning 0) width) width))
22181 (match-beginning 0)) ?\ )
22182 t t s)))
22185 (defun org-fix-indentation (line ind)
22186 "Fix indentation in LINE.
22187 IND is a cons cell with target and minimum indentation.
22188 If the current indentation in LINE is smaller than the minimum,
22189 leave it alone. If it is larger than ind, set it to the target."
22190 (let* ((l (org-remove-tabs line))
22191 (i (org-get-indentation l))
22192 (i1 (car ind)) (i2 (cdr ind)))
22193 (when (>= i i2) (setq l (substring line i2)))
22194 (if (> i1 0)
22195 (concat (make-string i1 ?\ ) l)
22196 l)))
22198 (defun org-remove-indentation (code &optional n)
22199 "Remove maximum common indentation in string CODE and return it.
22200 N may optionally be the number of columns to remove. Return CODE
22201 as-is if removal failed."
22202 (with-temp-buffer
22203 (insert code)
22204 (if (org-do-remove-indentation n) (buffer-string) code)))
22206 (defun org-do-remove-indentation (&optional n)
22207 "Remove the maximum common indentation from the buffer.
22208 When optional argument N is a positive integer, remove exactly
22209 that much characters from indentation, if possible. Return nil
22210 if it fails."
22211 (catch :exit
22212 (goto-char (point-min))
22213 ;; Find maximum common indentation, if not specified.
22214 (let ((n (or n
22215 (let ((min-ind (point-max)))
22216 (save-excursion
22217 (while (re-search-forward "^[ \t]*\\S-" nil t)
22218 (let ((ind (1- (current-column))))
22219 (if (zerop ind) (throw :exit nil)
22220 (setq min-ind (min min-ind ind))))))
22221 min-ind))))
22222 (if (zerop n) (throw :exit nil)
22223 ;; Remove exactly N indentation, but give up if not possible.
22224 (while (not (eobp))
22225 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22226 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22227 ((< ind n) (throw :exit nil))
22228 (t (org-indent-line-to (- ind n))))
22229 (forward-line)))
22230 ;; Signal success.
22231 t))))
22233 (defun org-fill-template (template alist)
22234 "Find each %key of ALIST in TEMPLATE and replace it."
22235 (let ((case-fold-search nil))
22236 (dolist (entry (sort (copy-sequence alist)
22237 (lambda (a b) (< (length (car a)) (length (car b))))))
22238 (setq template
22239 (replace-regexp-in-string
22240 (concat "%" (regexp-quote (car entry)))
22241 (or (cdr entry) "") template t t)))
22242 template))
22244 (defun org-base-buffer (buffer)
22245 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22246 (if (not buffer)
22247 buffer
22248 (or (buffer-base-buffer buffer)
22249 buffer)))
22251 (defun org-wrap (string &optional width lines)
22252 "Wrap string to either a number of lines, or a width in characters.
22253 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22254 that costs. If there is a word longer than WIDTH, the text is actually
22255 wrapped to the length of that word.
22256 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22257 many lines, whatever width that takes.
22258 The return value is a list of lines, without newlines at the end."
22259 (let* ((words (org-split-string string "[ \t\n]+"))
22260 (maxword (apply 'max (mapcar 'org-string-width words)))
22261 w ll)
22262 (cond (width
22263 (org-do-wrap words (max maxword width)))
22264 (lines
22265 (setq w maxword)
22266 (setq ll (org-do-wrap words maxword))
22267 (if (<= (length ll) lines)
22269 (setq ll words)
22270 (while (> (length ll) lines)
22271 (setq w (1+ w))
22272 (setq ll (org-do-wrap words w)))
22273 ll))
22274 (t (error "Cannot wrap this")))))
22276 (defun org-do-wrap (words width)
22277 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22278 (let (lines line)
22279 (while words
22280 (setq line (pop words))
22281 (while (and words (< (+ (length line) (length (car words))) width))
22282 (setq line (concat line " " (pop words))))
22283 (setq lines (push line lines)))
22284 (nreverse lines)))
22286 (defun org-split-string (string &optional separators)
22287 "Splits STRING into substrings at SEPARATORS.
22288 SEPARATORS is a regular expression.
22289 No empty strings are returned if there are matches at the beginning
22290 and end of string."
22291 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22292 (let ((start 0) notfirst list)
22293 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22294 (if (and notfirst
22295 (= start (match-beginning 0))
22296 (< start (length string)))
22297 (1+ start) start))
22298 (< (match-beginning 0) (length string)))
22299 (setq notfirst t)
22300 (or (eq (match-beginning 0) 0)
22301 (and (eq (match-beginning 0) (match-end 0))
22302 (eq (match-beginning 0) start))
22303 (push (substring string start (match-beginning 0)) list))
22304 (setq start (match-end 0)))
22305 (or (eq start (length string))
22306 (push (substring string start) list))
22307 (nreverse list)))
22309 (defun org-quote-vert (s)
22310 "Replace \"|\" with \"\\vert\"."
22311 (while (string-match "|" s)
22312 (setq s (replace-match "\\vert" t t s)))
22315 (defun org-uuidgen-p (s)
22316 "Is S an ID created by UUIDGEN?"
22317 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22319 (defun org-in-src-block-p (&optional inside)
22320 "Whether point is in a code source block.
22321 When INSIDE is non-nil, don't consider we are within a src block
22322 when point is at #+BEGIN_SRC or #+END_SRC."
22323 (let ((case-fold-search t))
22324 (or (and (eq (get-char-property (point) 'src-block) t))
22325 (and (not inside)
22326 (save-match-data
22327 (save-excursion
22328 (beginning-of-line)
22329 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22331 (defun org-context ()
22332 "Return a list of contexts of the current cursor position.
22333 If several contexts apply, all are returned.
22334 Each context entry is a list with a symbol naming the context, and
22335 two positions indicating start and end of the context. Possible
22336 contexts are:
22338 :headline anywhere in a headline
22339 :headline-stars on the leading stars in a headline
22340 :todo-keyword on a TODO keyword (including DONE) in a headline
22341 :tags on the TAGS in a headline
22342 :priority on the priority cookie in a headline
22343 :item on the first line of a plain list item
22344 :item-bullet on the bullet/number of a plain list item
22345 :checkbox on the checkbox in a plain list item
22346 :table in an org-mode table
22347 :table-special on a special filed in a table
22348 :table-table in a table.el table
22349 :clocktable in a clocktable
22350 :src-block in a source block
22351 :link on a hyperlink
22352 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22353 :target on a <<target>>
22354 :radio-target on a <<<radio-target>>>
22355 :latex-fragment on a LaTeX fragment
22356 :latex-preview on a LaTeX fragment with overlaid preview image
22358 This function expects the position to be visible because it uses font-lock
22359 faces as a help to recognize the following contexts: :table-special, :link,
22360 and :keyword."
22361 (let* ((f (get-text-property (point) 'face))
22362 (faces (if (listp f) f (list f)))
22363 (case-fold-search t)
22364 (p (point)) clist o)
22365 ;; First the large context
22366 (cond
22367 ((org-at-heading-p t)
22368 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22369 (when (progn
22370 (beginning-of-line 1)
22371 (looking-at org-todo-line-tags-regexp))
22372 (push (org-point-in-group p 1 :headline-stars) clist)
22373 (push (org-point-in-group p 2 :todo-keyword) clist)
22374 (push (org-point-in-group p 4 :tags) clist))
22375 (goto-char p)
22376 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22377 (when (looking-at "\\[#[A-Z0-9]\\]")
22378 (push (org-point-in-group p 0 :priority) clist)))
22380 ((org-at-item-p)
22381 (push (org-point-in-group p 2 :item-bullet) clist)
22382 (push (list :item (point-at-bol)
22383 (save-excursion (org-end-of-item) (point)))
22384 clist)
22385 (and (org-at-item-checkbox-p)
22386 (push (org-point-in-group p 0 :checkbox) clist)))
22388 ((org-at-table-p)
22389 (push (list :table (org-table-begin) (org-table-end)) clist)
22390 (when (memq 'org-formula faces)
22391 (push (list :table-special
22392 (previous-single-property-change p 'face)
22393 (next-single-property-change p 'face)) clist)))
22394 ((org-at-table-p 'any)
22395 (push (list :table-table) clist)))
22396 (goto-char p)
22398 (let ((case-fold-search t))
22399 ;; New the "medium" contexts: clocktables, source blocks
22400 (cond ((org-in-clocktable-p)
22401 (push (list :clocktable
22402 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22403 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22404 (match-beginning 1))
22405 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22406 (match-end 0))) clist))
22407 ((org-in-src-block-p)
22408 (push (list :src-block
22409 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22410 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22411 (match-beginning 1))
22412 (and (search-forward "#+END_SRC" nil t)
22413 (match-beginning 0))) clist))))
22414 (goto-char p)
22416 ;; Now the small context
22417 (cond
22418 ((org-at-timestamp-p)
22419 (push (org-point-in-group p 0 :timestamp) clist))
22420 ((memq 'org-link faces)
22421 (push (list :link
22422 (previous-single-property-change p 'face)
22423 (next-single-property-change p 'face)) clist))
22424 ((memq 'org-special-keyword faces)
22425 (push (list :keyword
22426 (previous-single-property-change p 'face)
22427 (next-single-property-change p 'face)) clist))
22428 ((org-at-target-p)
22429 (push (org-point-in-group p 0 :target) clist)
22430 (goto-char (1- (match-beginning 0)))
22431 (when (looking-at org-radio-target-regexp)
22432 (push (org-point-in-group p 0 :radio-target) clist))
22433 (goto-char p))
22434 ((setq o (cl-some
22435 (lambda (o)
22436 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22438 (overlays-at (point))))
22439 (push (list :latex-fragment
22440 (overlay-start o) (overlay-end o)) clist)
22441 (push (list :latex-preview
22442 (overlay-start o) (overlay-end o)) clist))
22443 ((org-inside-LaTeX-fragment-p)
22444 ;; FIXME: positions wrong.
22445 (push (list :latex-fragment (point) (point)) clist)))
22447 (setq clist (nreverse (delq nil clist)))
22448 clist))
22450 (defun org-in-regexp (regexp &optional nlines visually)
22451 "Check if point is inside a match of REGEXP.
22453 Normally only the current line is checked, but you can include
22454 NLINES extra lines around point into the search. If VISUALLY is
22455 set, require that the cursor is not after the match but really
22456 on, so that the block visually is on the match.
22458 Return nil or a cons cell (BEG . END) where BEG and END are,
22459 respectively, the positions at the beginning and the end of the
22460 match."
22461 (catch :exit
22462 (let ((pos (point))
22463 (eol (line-end-position (if nlines (1+ nlines) 1))))
22464 (save-excursion
22465 (beginning-of-line (- 1 (or nlines 0)))
22466 (while (and (re-search-forward regexp eol t)
22467 (<= (match-beginning 0) pos))
22468 (let ((end (match-end 0)))
22469 (when (or (> end pos) (and (= end pos) (not visually)))
22470 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22471 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22472 "Org mode 8.3")
22474 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22475 "Non-nil when point is between matches of START-RE and END-RE.
22477 Also return a non-nil value when point is on one of the matches.
22479 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22480 buffer positions. Default values are the positions of headlines
22481 surrounding the point.
22483 The functions returns a cons cell whose car (resp. cdr) is the
22484 position before START-RE (resp. after END-RE)."
22485 (save-match-data
22486 (let ((pos (point))
22487 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22488 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22489 beg end)
22490 (save-excursion
22491 ;; Point is on a block when on START-RE or if START-RE can be
22492 ;; found before it...
22493 (and (or (org-in-regexp start-re)
22494 (re-search-backward start-re limit-up t))
22495 (setq beg (match-beginning 0))
22496 ;; ... and END-RE after it...
22497 (goto-char (match-end 0))
22498 (re-search-forward end-re limit-down t)
22499 (> (setq end (match-end 0)) pos)
22500 ;; ... without another START-RE in-between.
22501 (goto-char (match-beginning 0))
22502 (not (re-search-backward start-re (1+ beg) t))
22503 ;; Return value.
22504 (cons beg end))))))
22506 (defun org-in-block-p (names)
22507 "Non-nil when point belongs to a block whose name belongs to NAMES.
22509 NAMES is a list of strings containing names of blocks.
22511 Return first block name matched, or nil. Beware that in case of
22512 nested blocks, the returned name may not belong to the closest
22513 block from point."
22514 (save-match-data
22515 (catch 'exit
22516 (let ((case-fold-search t)
22517 (lim-up (save-excursion (outline-previous-heading)))
22518 (lim-down (save-excursion (outline-next-heading))))
22519 (dolist (name names)
22520 (let ((n (regexp-quote name)))
22521 (when (org-between-regexps-p
22522 (concat "^[ \t]*#\\+begin_" n)
22523 (concat "^[ \t]*#\\+end_" n)
22524 lim-up lim-down)
22525 (throw 'exit n)))))
22526 nil)))
22528 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22529 "Call `multi-occur' with buffers for all agenda files."
22530 (interactive "sOrg-files matching: ")
22531 (let* ((files (org-agenda-files))
22532 (tnames (mapcar #'file-truename files))
22533 (extra org-agenda-text-search-extra-files))
22534 (when (eq (car extra) 'agenda-archives)
22535 (setq extra (cdr extra))
22536 (setq files (org-add-archive-files files)))
22537 (dolist (f extra)
22538 (unless (member (file-truename f) tnames)
22539 (unless (member f files) (setq files (append files (list f))))
22540 (setq tnames (append tnames (list (file-truename f))))))
22541 (multi-occur
22542 (mapcar (lambda (x)
22543 (with-current-buffer
22544 ;; FIXME: Why not just (find-file-noselect x)?
22545 ;; Is it to avoid the "revert buffer" prompt?
22546 (or (get-file-buffer x) (find-file-noselect x))
22547 (widen)
22548 (current-buffer)))
22549 files)
22550 regexp)))
22552 (if (boundp 'occur-mode-find-occurrence-hook)
22553 ;; Emacs 23
22554 (add-hook 'occur-mode-find-occurrence-hook
22555 (lambda ()
22556 (when (derived-mode-p 'org-mode)
22557 (org-reveal))))
22558 ;; Emacs 22
22559 (defadvice occur-mode-goto-occurrence
22560 (after org-occur-reveal activate)
22561 (and (derived-mode-p 'org-mode) (org-reveal)))
22562 (defadvice occur-mode-goto-occurrence-other-window
22563 (after org-occur-reveal activate)
22564 (and (derived-mode-p 'org-mode) (org-reveal)))
22565 (defadvice occur-mode-display-occurrence
22566 (after org-occur-reveal activate)
22567 (when (derived-mode-p 'org-mode)
22568 (let ((pos (occur-mode-find-occurrence)))
22569 (with-current-buffer (marker-buffer pos)
22570 (save-excursion
22571 (goto-char pos)
22572 (org-reveal)))))))
22574 (defun org-occur-link-in-agenda-files ()
22575 "Create a link and search for it in the agendas.
22576 The link is not stored in `org-stored-links', it is just created
22577 for the search purpose."
22578 (interactive)
22579 (let ((link (condition-case nil
22580 (org-store-link nil)
22581 (error "Unable to create a link to here"))))
22582 (org-occur-in-agenda-files (regexp-quote link))))
22584 (defun org-reverse-string (string)
22585 "Return the reverse of STRING."
22586 (apply 'string (reverse (string-to-list string))))
22588 ;; defsubst org-uniquify must be defined before first use
22590 (defun org-uniquify-alist (alist)
22591 "Merge elements of ALIST with the same key.
22593 For example, in this alist:
22595 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22596 => \\='((a 1 3) (b 2))
22598 merge (a 1) and (a 3) into (a 1 3).
22600 The function returns the new ALIST."
22601 (let (rtn)
22602 (dolist (e alist rtn)
22603 (let (n)
22604 (if (not (assoc (car e) rtn))
22605 (push e rtn)
22606 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22607 (setq rtn (assq-delete-all (car e) rtn))
22608 (push n rtn))))))
22610 (defun org-delete-all (elts list)
22611 "Remove all elements in ELTS from LIST."
22612 (while elts
22613 (setq list (delete (pop elts) list)))
22614 list)
22616 (defun org-back-over-empty-lines ()
22617 "Move backwards over whitespace, to the beginning of the first empty line.
22618 Returns the number of empty lines passed."
22619 (let ((pos (point)))
22620 (if (cdr (assoc 'heading org-blank-before-new-entry))
22621 (skip-chars-backward " \t\n\r")
22622 (unless (eobp)
22623 (forward-line -1)))
22624 (beginning-of-line 2)
22625 (goto-char (min (point) pos))
22626 (count-lines (point) pos)))
22628 (defun org-skip-whitespace ()
22629 (skip-chars-forward " \t\n\r"))
22631 (defun org-point-in-group (point group &optional context)
22632 "Check if POINT is in match-group GROUP.
22633 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22634 match. If the match group does not exist or point is not inside it,
22635 return nil."
22636 (and (match-beginning group)
22637 (>= point (match-beginning group))
22638 (<= point (match-end group))
22639 (if context
22640 (list context (match-beginning group) (match-end group))
22641 t)))
22643 (defun org-switch-to-buffer-other-window (&rest args)
22644 "Switch to buffer in a second window on the current frame.
22645 In particular, do not allow pop-up frames.
22646 Returns the newly created buffer."
22647 (org-no-popups
22648 (apply 'switch-to-buffer-other-window args)))
22650 (defun org-combine-plists (&rest plists)
22651 "Create a single property list from all plists in PLISTS.
22652 The process starts by copying the first list, and then setting properties
22653 from the other lists. Settings in the last list are the most significant
22654 ones and overrule settings in the other lists."
22655 (let ((rtn (copy-sequence (pop plists)))
22656 p v ls)
22657 (while plists
22658 (setq ls (pop plists))
22659 (while ls
22660 (setq p (pop ls) v (pop ls))
22661 (setq rtn (plist-put rtn p v))))
22662 rtn))
22664 (defun org-replace-escapes (string table)
22665 "Replace %-escapes in STRING with values in TABLE.
22666 TABLE is an association list with keys like \"%a\" and string values.
22667 The sequences in STRING may contain normal field width and padding information,
22668 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22669 so values can contain further %-escapes if they are define later in TABLE."
22670 (let ((tbl (copy-alist table))
22671 (case-fold-search nil)
22672 (pchg 0)
22673 re rpl)
22674 (dolist (e tbl)
22675 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22676 (when (and (cdr e) (string-match re (cdr e)))
22677 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22678 (safe "SREF"))
22679 (add-text-properties 0 3 (list 'sref sref) safe)
22680 (setcdr e (replace-match safe t t (cdr e)))))
22681 (while (string-match re string)
22682 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22683 (cdr e)))
22684 (setq string (replace-match rpl t t string))))
22685 (while (setq pchg (next-property-change pchg string))
22686 (let ((sref (get-text-property pchg 'sref string)))
22687 (when (and sref (string-match "SREF" string pchg))
22688 (setq string (replace-match sref t t string)))))
22689 string))
22691 (defun org-sublist (list start end)
22692 "Return a section of LIST, from START to END.
22694 Counting starts at 1."
22695 (cl-subseq list (1- start) end))
22696 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22698 (defun org-find-base-buffer-visiting (file)
22699 "Like `find-buffer-visiting' but always return the base buffer and
22700 not an indirect buffer."
22701 (let ((buf (or (get-file-buffer file)
22702 (find-buffer-visiting file))))
22703 (if buf
22704 (or (buffer-base-buffer buf) buf)
22705 nil)))
22707 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22708 "Org 9.0")
22710 ;;; TODO: Only called once, from ox-odt which should probably use
22711 ;;; org-export-inline-image-p or something.
22712 (defun org-file-image-p (file)
22713 "Return non-nil if FILE is an image."
22714 (save-match-data
22715 (string-match (image-file-name-regexp) file)))
22717 (defun org-get-cursor-date (&optional with-time)
22718 "Return the date at cursor in as a time.
22719 This works in the calendar and in the agenda, anywhere else it just
22720 returns the current time.
22721 If WITH-TIME is non-nil, returns the time of the event at point (in
22722 the agenda) or the current time of the day."
22723 (let (date day defd tp hod mod)
22724 (when with-time
22725 (setq tp (get-text-property (point) 'time))
22726 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22727 (setq hod (string-to-number (match-string 1 tp))
22728 mod (string-to-number (match-string 2 tp))))
22729 (or tp (let ((now (decode-time)))
22730 (setq hod (nth 2 now)
22731 mod (nth 1 now)))))
22732 (cond
22733 ((eq major-mode 'calendar-mode)
22734 (setq date (calendar-cursor-to-date)
22735 defd (encode-time 0 (or mod 0) (or hod 0)
22736 (nth 1 date) (nth 0 date) (nth 2 date))))
22737 ((eq major-mode 'org-agenda-mode)
22738 (setq day (get-text-property (point) 'day))
22739 (when day
22740 (setq date (calendar-gregorian-from-absolute day)
22741 defd (encode-time 0 (or mod 0) (or hod 0)
22742 (nth 1 date) (nth 0 date) (nth 2 date))))))
22743 (or defd (current-time))))
22745 (defun org-mark-subtree (&optional up)
22746 "Mark the current subtree.
22747 This puts point at the start of the current subtree, and mark at
22748 the end. If a numeric prefix UP is given, move up into the
22749 hierarchy of headlines by UP levels before marking the subtree."
22750 (interactive "P")
22751 (org-with-limited-levels
22752 (cond ((org-at-heading-p) (beginning-of-line))
22753 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22754 (t (outline-previous-visible-heading 1))))
22755 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22756 (if (org-called-interactively-p 'any)
22757 (call-interactively 'org-mark-element)
22758 (org-mark-element)))
22761 ;;; Indentation
22763 (defun org--get-expected-indentation (element contentsp)
22764 "Expected indentation column for current line, according to ELEMENT.
22765 ELEMENT is an element containing point. CONTENTSP is non-nil
22766 when indentation is to be computed according to contents of
22767 ELEMENT."
22768 (let ((type (org-element-type element))
22769 (start (org-element-property :begin element))
22770 (post-affiliated (org-element-property :post-affiliated element)))
22771 (org-with-wide-buffer
22772 (cond
22773 (contentsp
22774 (cl-case type
22775 ((diary-sexp footnote-definition) 0)
22776 ((headline inlinetask nil)
22777 (if (not org-adapt-indentation) 0
22778 (let ((level (org-current-level)))
22779 (if level (1+ level) 0))))
22780 ((item plain-list) (org-list-item-body-column post-affiliated))
22782 (goto-char start)
22783 (org-get-indentation))))
22784 ((memq type '(headline inlinetask nil))
22785 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22786 (org--get-expected-indentation element t)
22788 ((memq type '(diary-sexp footnote-definition)) 0)
22789 ;; First paragraph of a footnote definition or an item.
22790 ;; Indent like parent.
22791 ((< (line-beginning-position) start)
22792 (org--get-expected-indentation
22793 (org-element-property :parent element) t))
22794 ;; At first line: indent according to previous sibling, if any,
22795 ;; ignoring footnote definitions and inline tasks, or parent's
22796 ;; contents.
22797 ((= (line-beginning-position) start)
22798 (catch 'exit
22799 (while t
22800 (if (= (point-min) start) (throw 'exit 0)
22801 (goto-char (1- start))
22802 (let* ((previous (org-element-at-point))
22803 (parent previous))
22804 (while (and parent (<= (org-element-property :end parent) start))
22805 (setq previous parent
22806 parent (org-element-property :parent parent)))
22807 (cond
22808 ((not previous) (throw 'exit 0))
22809 ((> (org-element-property :end previous) start)
22810 (throw 'exit (org--get-expected-indentation previous t)))
22811 ((memq (org-element-type previous)
22812 '(footnote-definition inlinetask))
22813 (setq start (org-element-property :begin previous)))
22814 (t (goto-char (org-element-property :begin previous))
22815 (throw 'exit
22816 (if (bolp) (org-get-indentation)
22817 ;; At first paragraph in an item or
22818 ;; a footnote definition.
22819 (org--get-expected-indentation
22820 (org-element-property :parent previous) t))))))))))
22821 ;; Otherwise, move to the first non-blank line above.
22823 (beginning-of-line)
22824 (let ((pos (point)))
22825 (skip-chars-backward " \r\t\n")
22826 (cond
22827 ;; Two blank lines end a footnote definition or a plain
22828 ;; list. When we indent an empty line after them, the
22829 ;; containing list or footnote definition is over, so it
22830 ;; qualifies as a previous sibling. Therefore, we indent
22831 ;; like its first line.
22832 ((and (memq type '(footnote-definition plain-list))
22833 (> (count-lines (point) pos) 2))
22834 (goto-char start)
22835 (org-get-indentation))
22836 ;; Line above is the first one of a paragraph at the
22837 ;; beginning of an item or a footnote definition. Indent
22838 ;; like parent.
22839 ((< (line-beginning-position) start)
22840 (org--get-expected-indentation
22841 (org-element-property :parent element) t))
22842 ;; Line above is the beginning of an element, i.e., point
22843 ;; was originally on the blank lines between element's start
22844 ;; and contents.
22845 ((= (line-beginning-position) post-affiliated)
22846 (org--get-expected-indentation element t))
22847 ;; POS is after contents in a greater element. Indent like
22848 ;; the beginning of the element.
22850 ;; As a special case, if point is at the end of a footnote
22851 ;; definition or an item, indent like the very last element
22852 ;; within.
22853 ((and (not (eq type 'paragraph))
22854 (let ((cend (org-element-property :contents-end element)))
22855 (and cend (<= cend pos))))
22856 (if (memq type '(footnote-definition item plain-list))
22857 (let ((last (org-element-at-point)))
22858 (org--get-expected-indentation
22859 last
22860 (memq (org-element-type last)
22861 '(footnote-definition item plain-list))))
22862 (goto-char start)
22863 (org-get-indentation)))
22864 ;; In any other case, indent like the current line.
22865 (t (org-get-indentation)))))))))
22867 (defun org--align-node-property ()
22868 "Align node property at point.
22869 Alignment is done according to `org-property-format', which see."
22870 (when (save-excursion
22871 (beginning-of-line)
22872 (looking-at org-property-re))
22873 (replace-match
22874 (concat (match-string 4)
22875 (org-trim
22876 (format org-property-format (match-string 1) (match-string 3))))
22877 t t)))
22879 (defun org-indent-line ()
22880 "Indent line depending on context.
22882 Indentation is done according to the following rules:
22884 - Footnote definitions, diary sexps, headlines and inline tasks
22885 have to start at column 0.
22887 - On the very first line of an element, consider, in order, the
22888 next rules until one matches:
22890 1. If there's a sibling element before, ignoring footnote
22891 definitions and inline tasks, indent like its first line.
22893 2. If element has a parent, indent like its contents. More
22894 precisely, if parent is an item, indent after the
22895 description part, if any, or the bullet (see
22896 `org-list-description-max-indent'). Else, indent like
22897 parent's first line.
22899 3. Otherwise, indent relatively to current level, if
22900 `org-adapt-indentation' is non-nil, or to left margin.
22902 - On a blank line at the end of an element, indent according to
22903 the type of the element. More precisely
22905 1. If element is a plain list, an item, or a footnote
22906 definition, indent like the very last element within.
22908 2. If element is a paragraph, indent like its last non blank
22909 line.
22911 3. Otherwise, indent like its very first line.
22913 - In the code part of a source block, use language major mode
22914 to indent current line if `org-src-tab-acts-natively' is
22915 non-nil. If it is nil, do nothing.
22917 - Otherwise, indent like the first non-blank line above.
22919 The function doesn't indent an item as it could break the whole
22920 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22921 \\[org-shiftmetaright].
22923 Also align node properties according to `org-property-format'."
22924 (interactive)
22925 (cond
22926 (orgstruct-is-++
22927 (let ((indent-line-function
22928 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22929 (indent-according-to-mode)))
22930 ((org-at-heading-p) 'noindent)
22932 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22933 (type (org-element-type element)))
22934 (cond ((and (memq type '(plain-list item))
22935 (= (line-beginning-position)
22936 (org-element-property :post-affiliated element)))
22937 'noindent)
22938 ((and (eq type 'src-block)
22939 org-src-tab-acts-natively
22940 (> (line-beginning-position)
22941 (org-element-property :post-affiliated element))
22942 (< (line-beginning-position)
22943 (org-with-wide-buffer
22944 (goto-char (org-element-property :end element))
22945 (skip-chars-backward " \r\t\n")
22946 (line-beginning-position))))
22947 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22949 (let ((column (org--get-expected-indentation element nil)))
22950 ;; Preserve current column.
22951 (if (<= (current-column) (current-indentation))
22952 (org-indent-line-to column)
22953 (save-excursion (org-indent-line-to column))))
22954 ;; Align node property. Also preserve current column.
22955 (when (eq type 'node-property)
22956 (let ((column (current-column)))
22957 (org--align-node-property)
22958 (org-move-to-column column)))))))))
22960 (defun org-indent-region (start end)
22961 "Indent each non-blank line in the region.
22962 Called from a program, START and END specify the region to
22963 indent. The function will not indent contents of example blocks,
22964 verse blocks and export blocks as leading white spaces are
22965 assumed to be significant there."
22966 (interactive "r")
22967 (save-excursion
22968 (goto-char start)
22969 (skip-chars-forward " \r\t\n")
22970 (unless (eobp) (beginning-of-line))
22971 (let ((indent-to
22972 (lambda (ind pos)
22973 ;; Set IND as indentation for all lines between point and
22974 ;; POS. Blank lines are ignored. Leave point after POS
22975 ;; once done.
22976 (let ((limit (copy-marker pos)))
22977 (while (< (point) limit)
22978 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22979 (forward-line))
22980 (set-marker limit nil))))
22981 (end (copy-marker end)))
22982 (while (< (point) end)
22983 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22984 (let* ((element (org-element-at-point))
22985 (type (org-element-type element))
22986 (element-end (copy-marker (org-element-property :end element)))
22987 (ind (org--get-expected-indentation element nil)))
22988 (cond
22989 ((or (memq type '(paragraph table table-row))
22990 (not (or (org-element-property :contents-begin element)
22991 (memq type
22992 '(example-block export-block src-block)))))
22993 ;; Elements here are indented as a single block. Also
22994 ;; align node properties.
22995 (when (eq type 'node-property)
22996 (org--align-node-property)
22997 (beginning-of-line))
22998 (funcall indent-to ind (min element-end end)))
23000 ;; Elements in this category consist of three parts:
23001 ;; before the contents, the contents, and after the
23002 ;; contents. The contents are treated specially,
23003 ;; according to the element type, or not indented at
23004 ;; all. Other parts are indented as a single block.
23005 (let* ((post (copy-marker
23006 (org-element-property :post-affiliated element)))
23007 (cbeg
23008 (copy-marker
23009 (cond
23010 ((not (org-element-property :contents-begin element))
23011 ;; Fake contents for source blocks.
23012 (org-with-wide-buffer
23013 (goto-char post)
23014 (forward-line)
23015 (point)))
23016 ((memq type '(footnote-definition item plain-list))
23017 ;; Contents in these elements could start on
23018 ;; the same line as the beginning of the
23019 ;; element. Make sure we start indenting
23020 ;; from the second line.
23021 (org-with-wide-buffer
23022 (goto-char post)
23023 (end-of-line)
23024 (skip-chars-forward " \r\t\n")
23025 (if (eobp) (point) (line-beginning-position))))
23026 (t (org-element-property :contents-begin element)))))
23027 (cend (copy-marker
23028 (or (org-element-property :contents-end element)
23029 ;; Fake contents for source blocks.
23030 (org-with-wide-buffer
23031 (goto-char element-end)
23032 (skip-chars-backward " \r\t\n")
23033 (line-beginning-position)))
23034 t)))
23035 ;; Do not change items indentation individually as it
23036 ;; might break the list as a whole. On the other
23037 ;; hand, when at a plain list, indent it as a whole.
23038 (cond ((eq type 'plain-list)
23039 (let ((offset (- ind (org-get-indentation))))
23040 (unless (zerop offset)
23041 (indent-rigidly (org-element-property :begin element)
23042 (org-element-property :end element)
23043 offset))
23044 (goto-char cbeg)))
23045 ((eq type 'item) (goto-char cbeg))
23046 (t (funcall indent-to ind (min cbeg end))))
23047 (when (< (point) end)
23048 (cl-case type
23049 ((example-block export-block verse-block))
23050 (src-block
23051 ;; In a source block, indent source code
23052 ;; according to language major mode, but only if
23053 ;; `org-src-tab-acts-natively' is non-nil.
23054 (when (and (< (point) end) org-src-tab-acts-natively)
23055 (ignore-errors
23056 (org-babel-do-in-edit-buffer
23057 (indent-region (point-min) (point-max))))))
23058 (t (org-indent-region (point) (min cend end))))
23059 (goto-char (min cend end))
23060 (when (< (point) end)
23061 (funcall indent-to ind (min element-end end))))
23062 (set-marker post nil)
23063 (set-marker cbeg nil)
23064 (set-marker cend nil))))
23065 (set-marker element-end nil))))
23066 (set-marker end nil))))
23068 (defun org-indent-drawer ()
23069 "Indent the drawer at point."
23070 (interactive)
23071 (unless (save-excursion
23072 (beginning-of-line)
23073 (org-looking-at-p org-drawer-regexp))
23074 (user-error "Not at a drawer"))
23075 (let ((element (org-element-at-point)))
23076 (unless (memq (org-element-type element) '(drawer property-drawer))
23077 (user-error "Not at a drawer"))
23078 (org-with-wide-buffer
23079 (org-indent-region (org-element-property :begin element)
23080 (org-element-property :end element))))
23081 (message "Drawer at point indented"))
23083 (defun org-indent-block ()
23084 "Indent the block at point."
23085 (interactive)
23086 (unless (save-excursion
23087 (beginning-of-line)
23088 (let ((case-fold-search t))
23089 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23090 (user-error "Not at a block"))
23091 (let ((element (org-element-at-point)))
23092 (unless (memq (org-element-type element)
23093 '(comment-block center-block dynamic-block example-block
23094 export-block quote-block special-block
23095 src-block verse-block))
23096 (user-error "Not at a block"))
23097 (org-with-wide-buffer
23098 (org-indent-region (org-element-property :begin element)
23099 (org-element-property :end element))))
23100 (message "Block at point indented"))
23103 ;;; Filling
23105 ;; We use our own fill-paragraph and auto-fill functions.
23107 ;; `org-fill-paragraph' relies on adaptive filling and context
23108 ;; checking. Appropriate `fill-prefix' is computed with
23109 ;; `org-adaptive-fill-function'.
23111 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23112 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23113 ;; `org-adaptive-fill-function' value. Internally,
23114 ;; `org-comment-line-break-function' breaks the line.
23116 ;; `org-setup-filling' installs filling and auto-filling related
23117 ;; variables during `org-mode' initialization.
23119 (defvar org-element-paragraph-separate) ; org-element.el
23120 (defun org-setup-filling ()
23121 (require 'org-element)
23122 ;; Prevent auto-fill from inserting unwanted new items.
23123 (when (boundp 'fill-nobreak-predicate)
23124 (setq-local
23125 fill-nobreak-predicate
23126 (org-uniquify
23127 (append fill-nobreak-predicate
23128 '(org-fill-line-break-nobreak-p
23129 org-fill-paragraph-with-timestamp-nobreak-p)))))
23130 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23131 (setq-local paragraph-start paragraph-ending)
23132 (setq-local paragraph-separate paragraph-ending))
23133 (setq-local fill-paragraph-function 'org-fill-paragraph)
23134 (setq-local auto-fill-inhibit-regexp nil)
23135 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23136 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23137 (setq-local comment-line-break-function 'org-comment-line-break-function))
23139 (defun org-fill-line-break-nobreak-p ()
23140 "Non-nil when a new line at point would create an Org line break."
23141 (save-excursion
23142 (skip-chars-backward "[ \t]")
23143 (skip-chars-backward "\\\\")
23144 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23146 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23147 "Non-nil when a new line at point would split a timestamp."
23148 (and (org-at-timestamp-p t)
23149 (not (looking-at org-ts-regexp-both))))
23151 (declare-function message-in-body-p "message" ())
23152 (defvar orgtbl-line-start-regexp) ; From org-table.el
23153 (defun org-adaptive-fill-function ()
23154 "Compute a fill prefix for the current line.
23155 Return fill prefix, as a string, or nil if current line isn't
23156 meant to be filled. For convenience, if `adaptive-fill-regexp'
23157 matches in paragraphs or comments, use it."
23158 (catch 'exit
23159 (when (derived-mode-p 'message-mode)
23160 (save-excursion
23161 (beginning-of-line)
23162 (cond ((not (message-in-body-p)) (throw 'exit nil))
23163 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23164 ((looking-at message-cite-prefix-regexp)
23165 (throw 'exit (match-string-no-properties 0)))
23166 ((looking-at org-outline-regexp)
23167 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23168 (org-with-wide-buffer
23169 (unless (org-at-heading-p)
23170 (let* ((p (line-beginning-position))
23171 (element (save-excursion
23172 (beginning-of-line)
23173 (org-element-at-point)))
23174 (type (org-element-type element))
23175 (post-affiliated (org-element-property :post-affiliated element)))
23176 (unless (< p post-affiliated)
23177 (cl-case type
23178 (comment
23179 (save-excursion
23180 (beginning-of-line)
23181 (looking-at "[ \t]*")
23182 (concat (match-string 0) "# ")))
23183 (footnote-definition "")
23184 ((item plain-list)
23185 (make-string (org-list-item-body-column post-affiliated) ?\s))
23186 (paragraph
23187 ;; Fill prefix is usually the same as the current line,
23188 ;; unless the paragraph is at the beginning of an item.
23189 (let ((parent (org-element-property :parent element)))
23190 (save-excursion
23191 (beginning-of-line)
23192 (cond ((eq (org-element-type parent) 'item)
23193 (make-string (org-list-item-body-column
23194 (org-element-property :begin parent))
23195 ?\s))
23196 ((and adaptive-fill-regexp
23197 ;; Locally disable
23198 ;; `adaptive-fill-function' to let
23199 ;; `fill-context-prefix' handle
23200 ;; `adaptive-fill-regexp' variable.
23201 (let (adaptive-fill-function)
23202 (fill-context-prefix
23203 post-affiliated
23204 (org-element-property :end element)))))
23205 ((looking-at "[ \t]+") (match-string 0))
23206 (t "")))))
23207 (comment-block
23208 ;; Only fill contents if P is within block boundaries.
23209 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23210 (forward-line)
23211 (point)))
23212 (cend (save-excursion
23213 (goto-char (org-element-property :end element))
23214 (skip-chars-backward " \r\t\n")
23215 (line-beginning-position))))
23216 (when (and (>= p cbeg) (< p cend))
23217 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23218 (match-string 0)
23219 "")))))))))))
23221 (declare-function message-goto-body "message" ())
23222 (defvar message-cite-prefix-regexp) ; From message.el
23223 (defun org-fill-paragraph (&optional justify)
23224 "Fill element at point, when applicable.
23226 This function only applies to comment blocks, comments, example
23227 blocks and paragraphs. Also, as a special case, re-align table
23228 when point is at one.
23230 If JUSTIFY is non-nil (interactively, with prefix argument),
23231 justify as well. If `sentence-end-double-space' is non-nil, then
23232 period followed by one space does not end a sentence, so don't
23233 break a line there. The variable `fill-column' controls the
23234 width for filling.
23236 For convenience, when point is at a plain list, an item or
23237 a footnote definition, try to fill the first paragraph within."
23238 (interactive)
23239 (if (and (derived-mode-p 'message-mode)
23240 (or (not (message-in-body-p))
23241 (save-excursion (move-beginning-of-line 1)
23242 (looking-at message-cite-prefix-regexp))))
23243 ;; First ensure filling is correct in message-mode.
23244 (let ((fill-paragraph-function
23245 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23246 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23247 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23248 (paragraph-separate
23249 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23250 (fill-paragraph nil))
23251 (with-syntax-table org-mode-transpose-word-syntax-table
23252 ;; Move to end of line in order to get the first paragraph
23253 ;; within a plain list or a footnote definition.
23254 (let ((element (save-excursion
23255 (end-of-line)
23256 (or (ignore-errors (org-element-at-point))
23257 (user-error "An element cannot be parsed line %d"
23258 (line-number-at-pos (point)))))))
23259 ;; First check if point is in a blank line at the beginning of
23260 ;; the buffer. In that case, ignore filling.
23261 (cl-case (org-element-type element)
23262 ;; Use major mode filling function is src blocks.
23263 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23264 ;; Align Org tables, leave table.el tables as-is.
23265 (table-row (org-table-align) t)
23266 (table
23267 (when (eq (org-element-property :type element) 'org)
23268 (save-excursion
23269 (goto-char (org-element-property :post-affiliated element))
23270 (org-table-align)))
23272 (paragraph
23273 ;; Paragraphs may contain `line-break' type objects.
23274 (let ((beg (max (point-min)
23275 (org-element-property :contents-begin element)))
23276 (end (min (point-max)
23277 (org-element-property :contents-end element))))
23278 ;; Do nothing if point is at an affiliated keyword.
23279 (if (< (line-end-position) beg) t
23280 (when (derived-mode-p 'message-mode)
23281 ;; In `message-mode', do not fill following citation
23282 ;; in current paragraph nor text before message body.
23283 (let ((body-start (save-excursion (message-goto-body))))
23284 (when body-start (setq beg (max body-start beg))))
23285 (when (save-excursion
23286 (re-search-forward
23287 (concat "^" message-cite-prefix-regexp) end t))
23288 (setq end (match-beginning 0))))
23289 ;; Fill paragraph, taking line breaks into account.
23290 (save-excursion
23291 (goto-char beg)
23292 (let ((cuts (list beg)))
23293 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23294 (when (eq 'line-break
23295 (org-element-type
23296 (save-excursion (backward-char)
23297 (org-element-context))))
23298 (push (point) cuts)))
23299 (dolist (c (delq end cuts))
23300 (fill-region-as-paragraph c end justify)
23301 (setq end c))))
23302 t)))
23303 ;; Contents of `comment-block' type elements should be
23304 ;; filled as plain text, but only if point is within block
23305 ;; markers.
23306 (comment-block
23307 (let* ((case-fold-search t)
23308 (beg (save-excursion
23309 (goto-char (org-element-property :begin element))
23310 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23311 (forward-line)
23312 (point)))
23313 (end (save-excursion
23314 (goto-char (org-element-property :end element))
23315 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23316 (line-beginning-position))))
23317 (if (or (< (point) beg) (> (point) end)) t
23318 (fill-region-as-paragraph
23319 (save-excursion (end-of-line)
23320 (re-search-backward "^[ \t]*$" beg 'move)
23321 (line-beginning-position))
23322 (save-excursion (beginning-of-line)
23323 (re-search-forward "^[ \t]*$" end 'move)
23324 (line-beginning-position))
23325 justify))))
23326 ;; Fill comments.
23327 (comment
23328 (let ((begin (org-element-property :post-affiliated element))
23329 (end (org-element-property :end element)))
23330 (when (and (>= (point) begin) (<= (point) end))
23331 (let ((begin (save-excursion
23332 (end-of-line)
23333 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23334 (progn (forward-line) (point))
23335 begin)))
23336 (end (save-excursion
23337 (end-of-line)
23338 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23339 (1- (line-beginning-position))
23340 (skip-chars-backward " \r\t\n")
23341 (line-end-position)))))
23342 ;; Do not fill comments when at a blank line.
23343 (when (> end begin)
23344 (let ((fill-prefix
23345 (save-excursion
23346 (beginning-of-line)
23347 (looking-at "[ \t]*#")
23348 (let ((comment-prefix (match-string 0)))
23349 (goto-char (match-end 0))
23350 (if (looking-at adaptive-fill-regexp)
23351 (concat comment-prefix (match-string 0))
23352 (concat comment-prefix " "))))))
23353 (save-excursion
23354 (fill-region-as-paragraph begin end justify))))))
23356 ;; Ignore every other element.
23357 (otherwise t))))))
23359 (defun org-auto-fill-function ()
23360 "Auto-fill function."
23361 ;; Check if auto-filling is meaningful.
23362 (let ((fc (current-fill-column)))
23363 (when (and fc (> (current-column) fc))
23364 (let* ((fill-prefix (org-adaptive-fill-function))
23365 ;; Enforce empty fill prefix, if required. Otherwise, it
23366 ;; will be computed again.
23367 (adaptive-fill-mode (not (equal fill-prefix ""))))
23368 (when fill-prefix (do-auto-fill))))))
23370 (defun org-comment-line-break-function (&optional soft)
23371 "Break line at point and indent, continuing comment if within one.
23372 The inserted newline is marked hard if variable
23373 `use-hard-newlines' is true, unless optional argument SOFT is
23374 non-nil."
23375 (if soft (insert-and-inherit ?\n) (newline 1))
23376 (save-excursion (forward-char -1) (delete-horizontal-space))
23377 (delete-horizontal-space)
23378 (indent-to-left-margin)
23379 (insert-before-markers-and-inherit fill-prefix))
23382 ;;; Fixed Width Areas
23384 (defun org-toggle-fixed-width ()
23385 "Toggle fixed-width markup.
23387 Add or remove fixed-width markup on current line, whenever it
23388 makes sense. Return an error otherwise.
23390 If a region is active and if it contains only fixed-width areas
23391 or blank lines, remove all fixed-width markup in it. If the
23392 region contains anything else, convert all non-fixed-width lines
23393 to fixed-width ones.
23395 Blank lines at the end of the region are ignored unless the
23396 region only contains such lines."
23397 (interactive)
23398 (if (not (org-region-active-p))
23399 ;; No region:
23401 ;; Remove fixed width marker only in a fixed-with element.
23403 ;; Add fixed width maker in paragraphs, in blank lines after
23404 ;; elements or at the beginning of a headline or an inlinetask,
23405 ;; and before any one-line elements (e.g., a clock).
23406 (progn
23407 (beginning-of-line)
23408 (let* ((element (org-element-at-point))
23409 (type (org-element-type element)))
23410 (cond
23411 ((and (eq type 'fixed-width)
23412 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23413 (replace-match
23414 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23415 ((and (memq type '(babel-call clock comment diary-sexp headline
23416 horizontal-rule keyword paragraph
23417 planning))
23418 (<= (org-element-property :post-affiliated element) (point)))
23419 (skip-chars-forward " \t")
23420 (insert ": "))
23421 ((and (org-looking-at-p "[ \t]*$")
23422 (or (eq type 'inlinetask)
23423 (save-excursion
23424 (skip-chars-forward " \r\t\n")
23425 (<= (org-element-property :end element) (point)))))
23426 (delete-region (point) (line-end-position))
23427 (org-indent-line)
23428 (insert ": "))
23429 (t (user-error "Cannot insert a fixed-width line here")))))
23430 ;; Region active.
23431 (let* ((begin (save-excursion
23432 (goto-char (region-beginning))
23433 (line-beginning-position)))
23434 (end (copy-marker
23435 (save-excursion
23436 (goto-char (region-end))
23437 (unless (eolp) (beginning-of-line))
23438 (if (save-excursion (re-search-backward "\\S-" begin t))
23439 (progn (skip-chars-backward " \r\t\n") (point))
23440 (point)))))
23441 (all-fixed-width-p
23442 (catch 'not-all-p
23443 (save-excursion
23444 (goto-char begin)
23445 (skip-chars-forward " \r\t\n")
23446 (when (eobp) (throw 'not-all-p nil))
23447 (while (< (point) end)
23448 (let ((element (org-element-at-point)))
23449 (if (eq (org-element-type element) 'fixed-width)
23450 (goto-char (org-element-property :end element))
23451 (throw 'not-all-p nil))))
23452 t))))
23453 (if all-fixed-width-p
23454 (save-excursion
23455 (goto-char begin)
23456 (while (< (point) end)
23457 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23458 (replace-match
23459 "" nil nil nil
23460 (if (= (line-end-position) (match-end 0)) 0 1)))
23461 (forward-line)))
23462 (let ((min-ind (point-max)))
23463 ;; Find minimum indentation across all lines.
23464 (save-excursion
23465 (goto-char begin)
23466 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23467 (setq min-ind 0)
23468 (catch 'zerop
23469 (while (< (point) end)
23470 (unless (org-looking-at-p "[ \t]*$")
23471 (let ((ind (org-get-indentation)))
23472 (setq min-ind (min min-ind ind))
23473 (when (zerop ind) (throw 'zerop t))))
23474 (forward-line)))))
23475 ;; Loop over all lines and add fixed-width markup everywhere
23476 ;; but in fixed-width lines.
23477 (save-excursion
23478 (goto-char begin)
23479 (while (< (point) end)
23480 (cond
23481 ((org-at-heading-p)
23482 (insert ": ")
23483 (forward-line)
23484 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23485 (insert ":")
23486 (forward-line)))
23487 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23488 (let* ((element (org-element-at-point))
23489 (element-end (org-element-property :end element)))
23490 (if (eq (org-element-type element) 'fixed-width)
23491 (progn (goto-char element-end)
23492 (skip-chars-backward " \r\t\n")
23493 (forward-line))
23494 (let ((limit (min end element-end)))
23495 (while (< (point) limit)
23496 (org-move-to-column min-ind t)
23497 (insert ": ")
23498 (forward-line))))))
23500 (org-move-to-column min-ind t)
23501 (insert ": ")
23502 (forward-line)))))))
23503 (set-marker end nil))))
23506 ;;; Comments
23508 ;; Org comments syntax is quite complex. It requires the entire line
23509 ;; to be just a comment. Also, even with the right syntax at the
23510 ;; beginning of line, some some elements (i.e. verse-block or
23511 ;; example-block) don't accept comments. Usual Emacs comment commands
23512 ;; cannot cope with those requirements. Therefore, Org replaces them.
23514 ;; Org still relies on `comment-dwim', but cannot trust
23515 ;; `comment-only-p'. So, `comment-region-function' and
23516 ;; `uncomment-region-function' both point
23517 ;; to`org-comment-or-uncomment-region'. Eventually,
23518 ;; `org-insert-comment' takes care of insertion of comments at the
23519 ;; beginning of line.
23521 ;; `org-setup-comments-handling' install comments related variables
23522 ;; during `org-mode' initialization.
23524 (defun org-setup-comments-handling ()
23525 (interactive)
23526 (setq-local comment-use-syntax nil)
23527 (setq-local comment-start "# ")
23528 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23529 (setq-local comment-insert-comment-function 'org-insert-comment)
23530 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23531 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23533 (defun org-insert-comment ()
23534 "Insert an empty comment above current line.
23535 If the line is empty, insert comment at its beginning. When
23536 point is within a source block, comment according to the related
23537 major mode."
23538 (if (let ((element (org-element-at-point)))
23539 (and (eq (org-element-type element) 'src-block)
23540 (< (save-excursion
23541 (goto-char (org-element-property :post-affiliated element))
23542 (line-end-position))
23543 (point))
23544 (> (save-excursion
23545 (goto-char (org-element-property :end element))
23546 (skip-chars-backward " \r\t\n")
23547 (line-beginning-position))
23548 (point))))
23549 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23550 (beginning-of-line)
23551 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23552 (open-line 1))
23553 (org-indent-line)
23554 (insert "# ")))
23556 (defvar comment-empty-lines) ; From newcomment.el.
23557 (defun org-comment-or-uncomment-region (beg end &rest _)
23558 "Comment or uncomment each non-blank line in the region.
23559 Uncomment each non-blank line between BEG and END if it only
23560 contains commented lines. Otherwise, comment them. If region is
23561 strictly within a source block, use appropriate comment syntax."
23562 (if (let ((element (org-element-at-point)))
23563 (and (eq (org-element-type element) 'src-block)
23564 (< (save-excursion
23565 (goto-char (org-element-property :post-affiliated element))
23566 (line-end-position))
23567 beg)
23568 (>= (save-excursion
23569 (goto-char (org-element-property :end element))
23570 (skip-chars-backward " \r\t\n")
23571 (line-beginning-position))
23572 end)))
23573 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23574 (save-restriction
23575 ;; Restrict region
23576 (narrow-to-region (save-excursion (goto-char beg)
23577 (skip-chars-forward " \r\t\n" end)
23578 (line-beginning-position))
23579 (save-excursion (goto-char end)
23580 (skip-chars-backward " \r\t\n" beg)
23581 (line-end-position)))
23582 (let ((uncommentp
23583 ;; UNCOMMENTP is non-nil when every non blank line between
23584 ;; BEG and END is a comment.
23585 (save-excursion
23586 (goto-char (point-min))
23587 (while (and (not (eobp))
23588 (let ((element (org-element-at-point)))
23589 (and (eq (org-element-type element) 'comment)
23590 (goto-char (min (point-max)
23591 (org-element-property
23592 :end element)))))))
23593 (eobp))))
23594 (if uncommentp
23595 ;; Only blank lines and comments in region: uncomment it.
23596 (save-excursion
23597 (goto-char (point-min))
23598 (while (not (eobp))
23599 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23600 (replace-match "" nil nil nil 1))
23601 (forward-line)))
23602 ;; Comment each line in region.
23603 (let ((min-indent (point-max)))
23604 ;; First find the minimum indentation across all lines.
23605 (save-excursion
23606 (goto-char (point-min))
23607 (while (and (not (eobp)) (not (zerop min-indent)))
23608 (unless (looking-at "[ \t]*$")
23609 (setq min-indent (min min-indent (current-indentation))))
23610 (forward-line)))
23611 ;; Then loop over all lines.
23612 (save-excursion
23613 (goto-char (point-min))
23614 (while (not (eobp))
23615 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23616 ;; Don't get fooled by invisible text (e.g. link path)
23617 ;; when moving to column MIN-INDENT.
23618 (let ((buffer-invisibility-spec nil))
23619 (org-move-to-column min-indent t))
23620 (insert comment-start))
23621 (forward-line)))))))))
23623 (defun org-comment-dwim (_arg)
23624 "Call `comment-dwim' within a source edit buffer if needed."
23625 (interactive "*P")
23626 (if (org-in-src-block-p)
23627 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23628 (call-interactively 'comment-dwim)))
23631 ;;; Timestamps API
23633 ;; This section contains tools to operate on timestamp objects, as
23634 ;; returned by, e.g. `org-element-context'.
23636 (defun org-timestamp--to-internal-time (timestamp &optional end)
23637 "Encode TIMESTAMP object into Emacs internal time.
23638 Use end of date range or time range when END is non-nil."
23639 (apply #'encode-time
23640 (cons 0
23641 (mapcar
23642 (lambda (prop) (or (org-element-property prop timestamp) 0))
23643 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23644 '(:minute-start :hour-start :day-start :month-start
23645 :year-start))))))
23647 (defun org-timestamp-has-time-p (timestamp)
23648 "Non-nil when TIMESTAMP has a time specified."
23649 (org-element-property :hour-start timestamp))
23651 (defun org-timestamp-format (timestamp format &optional end utc)
23652 "Format a TIMESTAMP object into a string.
23654 FORMAT is a format specifier to be passed to
23655 `format-time-string'.
23657 When optional argument END is non-nil, use end of date-range or
23658 time-range, if possible.
23660 When optional argument UTC is non-nil, time will be expressed as
23661 Universal Time."
23662 (format-time-string
23663 format (org-timestamp--to-internal-time timestamp end) utc))
23665 (defun org-timestamp-split-range (timestamp &optional end)
23666 "Extract a TIMESTAMP object from a date or time range.
23668 END, when non-nil, means extract the end of the range.
23669 Otherwise, extract its start.
23671 Return a new timestamp object."
23672 (let ((type (org-element-property :type timestamp)))
23673 (if (memq type '(active inactive diary)) timestamp
23674 (let ((split-ts (org-element-copy timestamp)))
23675 ;; Set new type.
23676 (org-element-put-property
23677 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23678 ;; Copy start properties over end properties if END is
23679 ;; non-nil. Otherwise, copy end properties over `start' ones.
23680 (let ((p-alist '((:minute-start . :minute-end)
23681 (:hour-start . :hour-end)
23682 (:day-start . :day-end)
23683 (:month-start . :month-end)
23684 (:year-start . :year-end))))
23685 (dolist (p-cell p-alist)
23686 (org-element-put-property
23687 split-ts
23688 (funcall (if end #'car #'cdr) p-cell)
23689 (org-element-property
23690 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23691 ;; Eventually refresh `:raw-value'.
23692 (org-element-put-property split-ts :raw-value nil)
23693 (org-element-put-property
23694 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23696 (defun org-timestamp-translate (timestamp &optional boundary)
23697 "Translate TIMESTAMP object to custom format.
23699 Format string is defined in `org-time-stamp-custom-formats',
23700 which see.
23702 When optional argument BOUNDARY is non-nil, it is either the
23703 symbol `start' or `end'. In this case, only translate the
23704 starting or ending part of TIMESTAMP if it is a date or time
23705 range. Otherwise, translate both parts.
23707 Return timestamp as-is if `org-display-custom-times' is nil or if
23708 it has a `diary' type."
23709 (let ((type (org-element-property :type timestamp)))
23710 (if (or (not org-display-custom-times) (eq type 'diary))
23711 (org-element-interpret-data timestamp)
23712 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23713 org-time-stamp-custom-formats)))
23714 (if (and (not boundary) (memq type '(active-range inactive-range)))
23715 (concat (org-timestamp-format timestamp fmt)
23716 "--"
23717 (org-timestamp-format timestamp fmt t))
23718 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23722 ;;; Other stuff.
23724 (defvar reftex-docstruct-symbol)
23725 (defvar reftex-cite-format)
23726 (defvar org--rds)
23728 (defun org-reftex-citation ()
23729 "Use reftex-citation to insert a citation into the buffer.
23730 This looks for a line like
23732 #+BIBLIOGRAPHY: foo plain option:-d
23734 and derives from it that foo.bib is the bibliography file relevant
23735 for this document. It then installs the necessary environment for RefTeX
23736 to work in this buffer and calls `reftex-citation' to insert a citation
23737 into the buffer.
23739 Export of such citations to both LaTeX and HTML is handled by the contributed
23740 package ox-bibtex by Taru Karttunen."
23741 (interactive)
23742 (let ((reftex-docstruct-symbol 'org--rds)
23743 (reftex-cite-format "\\cite{%l}")
23744 org--rds bib)
23745 (save-excursion
23746 (save-restriction
23747 (widen)
23748 (let ((case-fold-search t)
23749 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23750 (if (not (save-excursion
23751 (or (re-search-forward re nil t)
23752 (re-search-backward re nil t))))
23753 (user-error "No bibliography defined in file")
23754 (setq bib (concat (match-string 1) ".bib")
23755 org--rds (list (list 'bib bib)))))))
23756 (call-interactively 'reftex-citation)))
23758 ;;;; Functions extending outline functionality
23760 (defun org-beginning-of-line (&optional arg)
23761 "Go to the beginning of the current line. If that is invisible, continue
23762 to a visible line beginning. This makes the function of C-a more intuitive.
23763 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23764 first attempt, and only move to after the tags when the cursor is already
23765 beyond the end of the headline."
23766 (interactive "P")
23767 (let ((pos (point))
23768 (special (if (consp org-special-ctrl-a/e)
23769 (car org-special-ctrl-a/e)
23770 org-special-ctrl-a/e))
23771 deactivate-mark refpos)
23772 (if (org-bound-and-true-p visual-line-mode)
23773 (beginning-of-visual-line 1)
23774 (beginning-of-line 1))
23775 (if (and arg (fboundp 'move-beginning-of-line))
23776 (call-interactively 'move-beginning-of-line)
23777 (unless (bobp)
23778 (backward-char 1)
23779 (if (org-truely-invisible-p)
23780 (while (and (not (bobp)) (org-truely-invisible-p))
23781 (backward-char 1)
23782 (beginning-of-line 1))
23783 (forward-char 1))))
23784 (when special
23785 (cond
23786 ((and (looking-at org-complex-heading-regexp)
23787 (eq (char-after (match-end 1)) ?\s))
23788 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23789 (point-at-eol)))
23790 (goto-char
23791 (if (eq special t)
23792 (cond ((> pos refpos) refpos)
23793 ((= pos (point)) refpos)
23794 (t (point)))
23795 (cond ((> pos (point)) (point))
23796 ((not (eq last-command this-command)) (point))
23797 (t refpos)))))
23798 ((org-at-item-p)
23799 ;; Being at an item and not looking at an the item means point
23800 ;; was previously moved to beginning of a visual line, which
23801 ;; doesn't contain the item. Therefore, do nothing special,
23802 ;; just stay here.
23803 (when (looking-at org-list-full-item-re)
23804 ;; Set special position at first white space character after
23805 ;; bullet, and check-box, if any.
23806 (let ((after-bullet
23807 (let ((box (match-end 3)))
23808 (if (not box) (match-end 1)
23809 (let ((after (char-after box)))
23810 (if (and after (= after ? )) (1+ box) box))))))
23811 ;; Special case: Move point to special position when
23812 ;; currently after it or at beginning of line.
23813 (if (eq special t)
23814 (when (or (> pos after-bullet) (= (point) pos))
23815 (goto-char after-bullet))
23816 ;; Reversed case: Move point to special position when
23817 ;; point was already at beginning of line and command is
23818 ;; repeated.
23819 (when (and (= (point) pos) (eq last-command this-command))
23820 (goto-char after-bullet))))))))
23821 (org-no-warnings
23822 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23823 (setq disable-point-adjustment
23824 (or (not (invisible-p (point)))
23825 (not (invisible-p (max (point-min) (1- (point))))))))
23827 (defun org-end-of-line (&optional arg)
23828 "Go to the end of the line.
23829 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23830 tags on the first attempt, and only move to after the tags when
23831 the cursor is already beyond the end of the headline."
23832 (interactive "P")
23833 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23834 org-special-ctrl-a/e))
23835 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23836 'end-of-visual-line)
23837 ((fboundp 'move-end-of-line) 'move-end-of-line)
23838 (t 'end-of-line)))
23839 deactivate-mark)
23840 (if (or (not special) arg) (call-interactively move-fun)
23841 (let* ((element (save-excursion (beginning-of-line)
23842 (org-element-at-point)))
23843 (type (org-element-type element)))
23844 (cond
23845 ((memq type '(headline inlinetask))
23846 (let ((pos (point)))
23847 (beginning-of-line 1)
23848 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23849 (if (eq special t)
23850 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23851 (goto-char (match-beginning 1))
23852 (goto-char (match-end 0)))
23853 (if (or (< pos (match-end 0))
23854 (not (eq this-command last-command)))
23855 (goto-char (match-end 0))
23856 (goto-char (match-beginning 1))))
23857 (call-interactively move-fun))))
23858 ((outline-invisible-p (line-end-position))
23859 ;; If element is hidden, `move-end-of-line' would put point
23860 ;; after it. Use `end-of-line' to stay on current line.
23861 (call-interactively 'end-of-line))
23862 (t (call-interactively move-fun)))))
23863 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23864 (setq disable-point-adjustment
23865 (or (not (invisible-p (point)))
23866 (not (invisible-p (max (point-min) (1- (point))))))))
23868 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23869 (define-key org-mode-map "\C-e" 'org-end-of-line)
23871 (defun org-backward-sentence (&optional _arg)
23872 "Go to beginning of sentence, or beginning of table field.
23873 This will call `backward-sentence' or `org-table-beginning-of-field',
23874 depending on context."
23875 (interactive)
23876 (let* ((element (org-element-at-point))
23877 (contents-begin (org-element-property :contents-begin element))
23878 (table (org-element-lineage element '(table) t)))
23879 (if (and table
23880 (> (point) contents-begin)
23881 (<= (point) (org-element-property :contents-end table)))
23882 (call-interactively #'org-table-beginning-of-field)
23883 (save-restriction
23884 (when (and contents-begin
23885 (< (point-min) contents-begin)
23886 (> (point) contents-begin))
23887 (narrow-to-region contents-begin
23888 (org-element-property :contents-end element)))
23889 (call-interactively #'backward-sentence)))))
23891 (defun org-forward-sentence (&optional _arg)
23892 "Go to end of sentence, or end of table field.
23893 This will call `forward-sentence' or `org-table-end-of-field',
23894 depending on context."
23895 (interactive)
23896 (let* ((element (org-element-at-point))
23897 (contents-end (org-element-property :contents-end element))
23898 (table (org-element-lineage element '(table) t)))
23899 (if (and table
23900 (>= (point) (org-element-property :contents-begin table))
23901 (< (point) contents-end))
23902 (call-interactively #'org-table-end-of-field)
23903 (save-restriction
23904 (when (and contents-end
23905 (> (point-max) contents-end)
23906 ;; Skip blank lines between elements.
23907 (< (org-element-property :end element)
23908 (save-excursion (goto-char contents-end)
23909 (skip-chars-forward " \r\t\n"))))
23910 (narrow-to-region (org-element-property :contents-begin element)
23911 contents-end))
23912 (call-interactively #'forward-sentence)))))
23914 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23915 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23917 (defun org-kill-line (&optional _arg)
23918 "Kill line, to tags or end of line."
23919 (interactive)
23920 (cond
23921 ((or (not org-special-ctrl-k)
23922 (bolp)
23923 (not (org-at-heading-p)))
23924 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23925 org-ctrl-k-protect-subtree
23926 (or (eq org-ctrl-k-protect-subtree 'error)
23927 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23928 (user-error "C-k aborted as it would kill a hidden subtree"))
23929 (call-interactively
23930 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23931 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23932 (kill-region (point) (match-beginning 1))
23933 (org-set-tags nil t))
23934 (t (kill-region (point) (point-at-eol)))))
23936 (define-key org-mode-map "\C-k" 'org-kill-line)
23938 (defun org-yank (&optional arg)
23939 "Yank. If the kill is a subtree, treat it specially.
23940 This command will look at the current kill and check if is a single
23941 subtree, or a series of subtrees[1]. If it passes the test, and if the
23942 cursor is at the beginning of a line or after the stars of a currently
23943 empty headline, then the yank is handled specially. How exactly depends
23944 on the value of the following variables, both set by default.
23946 `org-yank-folded-subtrees'
23947 When set, the subtree(s) will be folded after insertion, but only
23948 if doing so would now swallow text after the yanked text.
23950 `org-yank-adjusted-subtrees'
23951 When set, the subtree will be promoted or demoted in order to
23952 fit into the local outline tree structure, which means that the
23953 level will be adjusted so that it becomes the smaller one of the
23954 two *visible* surrounding headings.
23956 Any prefix to this command will cause `yank' to be called directly with
23957 no special treatment. In particular, a simple \\[universal-argument] prefix \
23958 will just
23959 plainly yank the text as it is.
23961 \[1] The test checks if the first non-white line is a heading
23962 and if there are no other headings with fewer stars."
23963 (interactive "P")
23964 (org-yank-generic 'yank arg))
23966 (defun org-yank-generic (command arg)
23967 "Perform some yank-like command.
23969 This function implements the behavior described in the `org-yank'
23970 documentation. However, it has been generalized to work for any
23971 interactive command with similar behavior."
23973 ;; pretend to be command COMMAND
23974 (setq this-command command)
23976 (if arg
23977 (call-interactively command)
23979 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23980 (and (org-kill-is-subtree-p)
23981 (or (bolp)
23982 (and (looking-at "[ \t]*$")
23983 (string-match
23984 "\\`\\*+\\'"
23985 (buffer-substring (point-at-bol) (point)))))))
23986 swallowp)
23987 (cond
23988 ((and subtreep org-yank-folded-subtrees)
23989 (let ((beg (point))
23990 end)
23991 (if (and subtreep org-yank-adjusted-subtrees)
23992 (org-paste-subtree nil nil 'for-yank)
23993 (call-interactively command))
23995 (setq end (point))
23996 (goto-char beg)
23997 (when (and (bolp) subtreep
23998 (not (setq swallowp
23999 (org-yank-folding-would-swallow-text beg end))))
24000 (org-with-limited-levels
24001 (or (looking-at org-outline-regexp)
24002 (re-search-forward org-outline-regexp-bol end t))
24003 (while (and (< (point) end) (looking-at org-outline-regexp))
24004 (outline-hide-subtree)
24005 (org-cycle-show-empty-lines 'folded)
24006 (condition-case nil
24007 (outline-forward-same-level 1)
24008 (error (goto-char end))))))
24009 (when swallowp
24010 (message
24011 "Inserted text not folded because that would swallow text"))
24013 (goto-char end)
24014 (skip-chars-forward " \t\n\r")
24015 (beginning-of-line 1)
24016 (push-mark beg 'nomsg)))
24017 ((and subtreep org-yank-adjusted-subtrees)
24018 (let ((beg (point-at-bol)))
24019 (org-paste-subtree nil nil 'for-yank)
24020 (push-mark beg 'nomsg)))
24022 (call-interactively command))))))
24024 (defun org-yank-folding-would-swallow-text (beg end)
24025 "Would hide-subtree at BEG swallow any text after END?"
24026 (let (level)
24027 (org-with-limited-levels
24028 (save-excursion
24029 (goto-char beg)
24030 (when (or (looking-at org-outline-regexp)
24031 (re-search-forward org-outline-regexp-bol end t))
24032 (setq level (org-outline-level)))
24033 (goto-char end)
24034 (skip-chars-forward " \t\r\n\v\f")
24035 (not (or (eobp)
24036 (and (bolp) (looking-at-p org-outline-regexp)
24037 (<= (org-outline-level) level))))))))
24039 (define-key org-mode-map "\C-y" 'org-yank)
24041 (defun org-truely-invisible-p ()
24042 "Check if point is at a character currently not visible.
24043 This version does not only check the character property, but also
24044 `visible-mode'."
24045 ;; Early versions of noutline don't have `outline-invisible-p'.
24046 (unless (org-bound-and-true-p visible-mode)
24047 (outline-invisible-p)))
24049 (defun org-invisible-p2 ()
24050 "Check if point is at a character currently not visible."
24051 (save-excursion
24052 (when (and (eolp) (not (bobp))) (backward-char 1))
24053 ;; Early versions of noutline don't have `outline-invisible-p'.
24054 (outline-invisible-p)))
24056 (defun org-back-to-heading (&optional invisible-ok)
24057 "Call `outline-back-to-heading', but provide a better error message."
24058 (condition-case nil
24059 (outline-back-to-heading invisible-ok)
24060 (error (error "Before first headline at position %d in buffer %s"
24061 (point) (current-buffer)))))
24063 (defun org-before-first-heading-p ()
24064 "Before first heading?"
24065 (save-excursion
24066 (end-of-line)
24067 (null (re-search-backward org-outline-regexp-bol nil t))))
24069 (defun org-at-heading-p (&optional ignored)
24070 (outline-on-heading-p t))
24071 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24072 ;;; warning was only added in Org 9.0, which should be taken into
24073 ;;; account when deciding when to remove the alias.
24074 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24076 (defun org-in-commented-heading-p (&optional no-inheritance)
24077 "Non-nil if point is under a commented heading.
24078 This function also checks ancestors of the current headline,
24079 unless optional argument NO-INHERITANCE is non-nil."
24080 (cond
24081 ((org-before-first-heading-p) nil)
24082 ((let ((headline (nth 4 (org-heading-components))))
24083 (and headline
24084 (let ((case-fold-search nil))
24085 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24086 headline)))))
24087 (no-inheritance nil)
24089 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24091 (defun org-at-comment-p nil
24092 "Is cursor in a commented line?"
24093 (save-excursion
24094 (save-match-data
24095 (beginning-of-line)
24096 (looking-at "^[ \t]*# "))))
24098 (defun org-at-drawer-p nil
24099 "Is cursor at a drawer keyword?"
24100 (save-excursion
24101 (move-beginning-of-line 1)
24102 (looking-at org-drawer-regexp)))
24104 (defun org-at-block-p nil
24105 "Is cursor at a block keyword?"
24106 (save-excursion
24107 (move-beginning-of-line 1)
24108 (looking-at org-block-regexp)))
24110 (defun org-point-at-end-of-empty-headline ()
24111 "If point is at the end of an empty headline, return t, else nil.
24112 If the heading only contains a TODO keyword, it is still still considered
24113 empty."
24114 (and (looking-at "[ \t]*$")
24115 (when org-todo-line-regexp
24116 (save-excursion
24117 (beginning-of-line 1)
24118 (let ((case-fold-search nil))
24119 (looking-at org-todo-line-regexp)
24120 (string= (match-string 3) ""))))))
24122 (defun org-at-heading-or-item-p ()
24123 (or (org-at-heading-p) (org-at-item-p)))
24125 (defun org-at-target-p ()
24126 (or (org-in-regexp org-radio-target-regexp)
24127 (org-in-regexp org-target-regexp)))
24128 ;; Compatibility alias with Org versions < 7.8.03
24129 (defalias 'org-on-target-p 'org-at-target-p)
24131 (defun org-up-heading-all (arg)
24132 "Move to the heading line of which the present line is a subheading.
24133 This function considers both visible and invisible heading lines.
24134 With argument, move up ARG levels."
24135 (if (fboundp 'outline-up-heading-all)
24136 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24137 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24139 (defun org-up-heading-safe ()
24140 "Move to the heading line of which the present line is a subheading.
24141 This version will not throw an error. It will return the level of the
24142 headline found, or nil if no higher level is found.
24144 Also, this function will be a lot faster than `outline-up-heading',
24145 because it relies on stars being the outline starters. This can really
24146 make a significant difference in outlines with very many siblings."
24147 (when (ignore-errors (org-back-to-heading t))
24148 (let ((level-up (1- (funcall outline-level))))
24149 (and (> level-up 0)
24150 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24151 (funcall outline-level)))))
24153 (defun org-first-sibling-p ()
24154 "Is this heading the first child of its parents?"
24155 (interactive)
24156 (let ((re org-outline-regexp-bol)
24157 level l)
24158 (unless (org-at-heading-p t)
24159 (user-error "Not at a heading"))
24160 (setq level (funcall outline-level))
24161 (save-excursion
24162 (if (not (re-search-backward re nil t))
24164 (setq l (funcall outline-level))
24165 (< l level)))))
24167 (defun org-goto-sibling (&optional previous)
24168 "Goto the next sibling, even if it is invisible.
24169 When PREVIOUS is set, go to the previous sibling instead. Returns t
24170 when a sibling was found. When none is found, return nil and don't
24171 move point."
24172 (let ((fun (if previous 're-search-backward 're-search-forward))
24173 (pos (point))
24174 (re org-outline-regexp-bol)
24175 level l)
24176 (when (ignore-errors (org-back-to-heading t))
24177 (setq level (funcall outline-level))
24178 (catch 'exit
24179 (or previous (forward-char 1))
24180 (while (funcall fun re nil t)
24181 (setq l (funcall outline-level))
24182 (when (< l level) (goto-char pos) (throw 'exit nil))
24183 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24184 (goto-char pos)
24185 nil))))
24187 (defun org-show-siblings ()
24188 "Show all siblings of the current headline."
24189 (save-excursion
24190 (while (org-goto-sibling) (org-flag-heading nil)))
24191 (save-excursion
24192 (while (org-goto-sibling 'previous)
24193 (org-flag-heading nil))))
24195 (defun org-goto-first-child ()
24196 "Goto the first child, even if it is invisible.
24197 Return t when a child was found. Otherwise don't move point and
24198 return nil."
24199 (let (level (pos (point)) (re org-outline-regexp-bol))
24200 (when (ignore-errors (org-back-to-heading t))
24201 (setq level (outline-level))
24202 (forward-char 1)
24203 (if (and (re-search-forward re nil t) (> (outline-level) level))
24204 (progn (goto-char (match-beginning 0)) t)
24205 (goto-char pos) nil))))
24207 (defun org-show-hidden-entry ()
24208 "Show an entry where even the heading is hidden."
24209 (save-excursion
24210 (org-show-entry)))
24212 (defun org-flag-heading (flag &optional entry)
24213 "Flag the current heading. FLAG non-nil means make invisible.
24214 When ENTRY is non-nil, show the entire entry."
24215 (save-excursion
24216 (org-back-to-heading t)
24217 ;; Check if we should show the entire entry
24218 (if entry
24219 (progn
24220 (org-show-entry)
24221 (save-excursion
24222 (and (outline-next-heading)
24223 (org-flag-heading nil))))
24224 (outline-flag-region (max (point-min) (1- (point)))
24225 (save-excursion (outline-end-of-heading) (point))
24226 flag))))
24228 (defun org-get-next-sibling ()
24229 "Move to next heading of the same level, and return point.
24230 If there is no such heading, return nil.
24231 This is like outline-next-sibling, but invisible headings are ok."
24232 (let ((level (funcall outline-level)))
24233 (outline-next-heading)
24234 (while (and (not (eobp)) (> (funcall outline-level) level))
24235 (outline-next-heading))
24236 (unless (or (eobp) (< (funcall outline-level) level))
24237 (point))))
24239 (defun org-get-last-sibling ()
24240 "Move to previous heading of the same level, and return point.
24241 If there is no such heading, return nil."
24242 (let ((opoint (point))
24243 (level (funcall outline-level)))
24244 (outline-previous-heading)
24245 (when (and (/= (point) opoint) (outline-on-heading-p t))
24246 (while (and (> (funcall outline-level) level)
24247 (not (bobp)))
24248 (outline-previous-heading))
24249 (unless (< (funcall outline-level) level)
24250 (point)))))
24252 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24253 "Goto to the end of a subtree."
24254 ;; This contains an exact copy of the original function, but it uses
24255 ;; `org-back-to-heading', to make it work also in invisible
24256 ;; trees. And is uses an invisible-ok argument.
24257 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24258 ;; Furthermore, when used inside Org, finding the end of a large subtree
24259 ;; with many children and grandchildren etc, this can be much faster
24260 ;; than the outline version.
24261 (org-back-to-heading invisible-ok)
24262 (let ((first t)
24263 (level (funcall outline-level)))
24264 (if (and (derived-mode-p 'org-mode) (< level 1000))
24265 ;; A true heading (not a plain list item), in Org-mode
24266 ;; This means we can easily find the end by looking
24267 ;; only for the right number of stars. Using a regexp to do
24268 ;; this is so much faster than using a Lisp loop.
24269 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24270 (forward-char 1)
24271 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24272 ;; something else, do it the slow way
24273 (while (and (not (eobp))
24274 (or first (> (funcall outline-level) level)))
24275 (setq first nil)
24276 (outline-next-heading)))
24277 (unless to-heading
24278 (when (memq (preceding-char) '(?\n ?\^M))
24279 ;; Go to end of line before heading
24280 (forward-char -1)
24281 (when (memq (preceding-char) '(?\n ?\^M))
24282 ;; leave blank line before heading
24283 (forward-char -1)))))
24284 (point))
24286 (defun org-end-of-meta-data (&optional full)
24287 "Skip planning line and properties drawer in current entry.
24288 When optional argument FULL is non-nil, also skip empty lines,
24289 clocking lines and regular drawers at the beginning of the
24290 entry."
24291 (org-back-to-heading t)
24292 (forward-line)
24293 (when (org-looking-at-p org-planning-line-re) (forward-line))
24294 (when (looking-at org-property-drawer-re)
24295 (goto-char (match-end 0))
24296 (forward-line))
24297 (when (and full (not (org-at-heading-p)))
24298 (catch 'exit
24299 (let ((end (save-excursion (outline-next-heading) (point)))
24300 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24301 (while (not (eobp))
24302 (cond ((org-looking-at-p org-drawer-regexp)
24303 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24304 (forward-line)
24305 (throw 'exit t)))
24306 ((org-looking-at-p re) (forward-line))
24307 (t (throw 'exit t))))))))
24309 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24310 "Move forward to the ARG'th subheading at same level as this one.
24311 Stop at the first and last subheadings of a superior heading.
24312 Normally this only looks at visible headings, but when INVISIBLE-OK is
24313 non-nil it will also look at invisible ones."
24314 (interactive "p")
24315 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24316 (if (and arg (< arg 0))
24317 (goto-char (point-min))
24318 (outline-next-heading))
24319 (org-at-heading-p)
24320 (let ((level (- (match-end 0) (match-beginning 0) 1))
24321 (f (if (and arg (< arg 0))
24322 're-search-backward
24323 're-search-forward))
24324 (count (if arg (abs arg) 1))
24325 (result (point)))
24326 (while (and (prog1 (> count 0)
24327 (forward-char (if (and arg (< arg 0)) -1 1)))
24328 (funcall f org-outline-regexp-bol nil 'move))
24329 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24330 (cond ((< l level) (setq count 0))
24331 ((and (= l level)
24332 (or invisible-ok
24333 (progn
24334 (goto-char (line-beginning-position))
24335 (not (outline-invisible-p)))))
24336 (setq count (1- count))
24337 (when (eq l level)
24338 (setq result (point)))))))
24339 (goto-char result))
24340 (beginning-of-line 1)))
24342 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24343 "Move backward to the ARG'th subheading at same level as this one.
24344 Stop at the first and last subheadings of a superior heading."
24345 (interactive "p")
24346 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24348 (defun org-next-visible-heading (arg)
24349 "Move to the next visible heading.
24351 This function wraps `outline-next-visible-heading' with
24352 `org-with-limited-levels' in order to skip over inline tasks and
24353 respect customization of `org-odd-levels-only'."
24354 (interactive "p")
24355 (org-with-limited-levels
24356 (outline-next-visible-heading arg)))
24358 (defun org-previous-visible-heading (arg)
24359 "Move to the next visible heading.
24361 This function wraps `outline-previous-visible-heading' with
24362 `org-with-limited-levels' in order to skip over inline tasks and
24363 respect customization of `org-odd-levels-only'."
24364 (interactive "p")
24365 (org-with-limited-levels
24366 (outline-previous-visible-heading arg)))
24368 (defun org-next-block (arg &optional backward block-regexp)
24369 "Jump to the next block.
24371 With a prefix argument ARG, jump forward ARG many blocks.
24373 When BACKWARD is non-nil, jump to the previous block.
24375 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24376 Match data is set according to this regexp when the function
24377 returns.
24379 Return point at beginning of the opening line of found block.
24380 Throw an error if no block is found."
24381 (interactive "p")
24382 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24383 (case-fold-search t)
24384 (search-fn (if backward #'re-search-backward #'re-search-forward))
24385 (count (or arg 1))
24386 (origin (point))
24387 last-element)
24388 (if backward (beginning-of-line) (end-of-line))
24389 (while (and (> count 0) (funcall search-fn re nil t))
24390 (let ((element (save-excursion
24391 (goto-char (match-beginning 0))
24392 (save-match-data (org-element-at-point)))))
24393 (when (and (memq (org-element-type element)
24394 '(center-block comment-block dynamic-block
24395 example-block export-block quote-block
24396 special-block src-block verse-block))
24397 (<= (match-beginning 0)
24398 (org-element-property :post-affiliated element)))
24399 (setq last-element element)
24400 (cl-decf count))))
24401 (if (= count 0)
24402 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24403 (save-match-data (org-show-context)))
24404 (goto-char origin)
24405 (user-error "No %s code blocks" (if backward "previous" "further")))))
24407 (defun org-previous-block (arg &optional block-regexp)
24408 "Jump to the previous block.
24409 With a prefix argument ARG, jump backward ARG many source blocks.
24410 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24411 (interactive "p")
24412 (org-next-block arg t block-regexp))
24414 (defun org-forward-paragraph ()
24415 "Move forward to beginning of next paragraph or equivalent.
24417 The function moves point to the beginning of the next visible
24418 structural element, which can be a paragraph, a table, a list
24419 item, etc. It also provides some special moves for convenience:
24421 - On an affiliated keyword, jump to the beginning of the
24422 relative element.
24423 - On an item or a footnote definition, move to the second
24424 element inside, if any.
24425 - On a table or a property drawer, jump after it.
24426 - On a verse or source block, stop after blank lines."
24427 (interactive)
24428 (when (eobp) (user-error "Cannot move further down"))
24429 (let* ((deactivate-mark nil)
24430 (element (org-element-at-point))
24431 (type (org-element-type element))
24432 (post-affiliated (org-element-property :post-affiliated element))
24433 (contents-begin (org-element-property :contents-begin element))
24434 (contents-end (org-element-property :contents-end element))
24435 (end (let ((end (org-element-property :end element)) (parent element))
24436 (while (and (setq parent (org-element-property :parent parent))
24437 (= (org-element-property :contents-end parent) end))
24438 (setq end (org-element-property :end parent)))
24439 end)))
24440 (cond ((not element)
24441 (skip-chars-forward " \r\t\n")
24442 (or (eobp) (beginning-of-line)))
24443 ;; On affiliated keywords, move to element's beginning.
24444 ((< (point) post-affiliated)
24445 (goto-char post-affiliated))
24446 ;; At a table row, move to the end of the table. Similarly,
24447 ;; at a node property, move to the end of the property
24448 ;; drawer.
24449 ((memq type '(node-property table-row))
24450 (goto-char (org-element-property
24451 :end (org-element-property :parent element))))
24452 ((memq type '(property-drawer table)) (goto-char end))
24453 ;; Consider blank lines as separators in verse and source
24454 ;; blocks to ease editing.
24455 ((memq type '(src-block verse-block))
24456 (when (eq type 'src-block)
24457 (setq contents-end
24458 (save-excursion (goto-char end)
24459 (skip-chars-backward " \r\t\n")
24460 (line-beginning-position))))
24461 (beginning-of-line)
24462 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24463 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24464 (goto-char end)
24465 (skip-chars-forward " \r\t\n")
24466 (if (= (point) contents-end) (goto-char end)
24467 (beginning-of-line))))
24468 ;; With no contents, just skip element.
24469 ((not contents-begin) (goto-char end))
24470 ;; If contents are invisible, skip the element altogether.
24471 ((outline-invisible-p (line-end-position))
24472 (cl-case type
24473 (headline
24474 (org-with-limited-levels (outline-next-visible-heading 1)))
24475 ;; At a plain list, make sure we move to the next item
24476 ;; instead of skipping the whole list.
24477 (plain-list (forward-char)
24478 (org-forward-paragraph))
24479 (otherwise (goto-char end))))
24480 ((>= (point) contents-end) (goto-char end))
24481 ((>= (point) contents-begin)
24482 ;; This can only happen on paragraphs and plain lists.
24483 (cl-case type
24484 (paragraph (goto-char end))
24485 ;; At a plain list, try to move to second element in
24486 ;; first item, if possible.
24487 (plain-list (end-of-line)
24488 (org-forward-paragraph))))
24489 ;; When contents start on the middle of a line (e.g. in
24490 ;; items and footnote definitions), try to reach first
24491 ;; element starting after current line.
24492 ((> (line-end-position) contents-begin)
24493 (end-of-line)
24494 (org-forward-paragraph))
24495 (t (goto-char contents-begin)))))
24497 (defun org-backward-paragraph ()
24498 "Move backward to start of previous paragraph or equivalent.
24500 The function moves point to the beginning of the current
24501 structural element, which can be a paragraph, a table, a list
24502 item, etc., or to the beginning of the previous visible one if
24503 point is already there. It also provides some special moves for
24504 convenience:
24506 - On an affiliated keyword, jump to the first one.
24507 - On a table or a property drawer, move to its beginning.
24508 - On a verse or source block, stop before blank lines."
24509 (interactive)
24510 (when (bobp) (user-error "Cannot move further up"))
24511 (let* ((deactivate-mark nil)
24512 (element (org-element-at-point))
24513 (type (org-element-type element))
24514 (contents-begin (org-element-property :contents-begin element))
24515 (contents-end (org-element-property :contents-end element))
24516 (post-affiliated (org-element-property :post-affiliated element))
24517 (begin (org-element-property :begin element)))
24518 (cond
24519 ((not element) (goto-char (point-min)))
24520 ((= (point) begin)
24521 (backward-char)
24522 (org-backward-paragraph))
24523 ((<= (point) post-affiliated) (goto-char begin))
24524 ((memq type '(node-property table-row))
24525 (goto-char (org-element-property
24526 :post-affiliated (org-element-property :parent element))))
24527 ((memq type '(property-drawer table)) (goto-char begin))
24528 ((memq type '(src-block verse-block))
24529 (when (eq type 'src-block)
24530 (setq contents-begin
24531 (save-excursion (goto-char begin) (forward-line) (point))))
24532 (if (= (point) contents-begin) (goto-char post-affiliated)
24533 ;; Inside a verse block, see blank lines as paragraph
24534 ;; separators.
24535 (let ((origin (point)))
24536 (skip-chars-backward " \r\t\n" contents-begin)
24537 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24538 (skip-chars-forward " \r\t\n" origin)
24539 (if (= (point) origin) (goto-char contents-begin)
24540 (beginning-of-line))))))
24541 ((not contents-begin) (goto-char (or post-affiliated begin)))
24542 ((eq type 'paragraph)
24543 (goto-char contents-begin)
24544 ;; When at first paragraph in an item or a footnote definition,
24545 ;; move directly to beginning of line.
24546 (let ((parent-contents
24547 (org-element-property
24548 :contents-begin (org-element-property :parent element))))
24549 (when (and parent-contents (= parent-contents contents-begin))
24550 (beginning-of-line))))
24551 ;; At the end of a greater element, move to the beginning of the
24552 ;; last element within.
24553 ((>= (point) contents-end)
24554 (goto-char (1- contents-end))
24555 (org-backward-paragraph))
24556 (t (goto-char (or post-affiliated begin))))
24557 ;; Ensure we never leave point invisible.
24558 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24560 (defun org-forward-element ()
24561 "Move forward by one element.
24562 Move to the next element at the same level, when possible."
24563 (interactive)
24564 (cond ((eobp) (user-error "Cannot move further down"))
24565 ((org-with-limited-levels (org-at-heading-p))
24566 (let ((origin (point)))
24567 (goto-char (org-end-of-subtree nil t))
24568 (unless (org-with-limited-levels (org-at-heading-p))
24569 (goto-char origin)
24570 (user-error "Cannot move further down"))))
24572 (let* ((elem (org-element-at-point))
24573 (end (org-element-property :end elem))
24574 (parent (org-element-property :parent elem)))
24575 (cond ((and parent (= (org-element-property :contents-end parent) end))
24576 (goto-char (org-element-property :end parent)))
24577 ((integer-or-marker-p end) (goto-char end))
24578 (t (message "No element at point")))))))
24580 (defun org-backward-element ()
24581 "Move backward by one element.
24582 Move to the previous element at the same level, when possible."
24583 (interactive)
24584 (cond ((bobp) (user-error "Cannot move further up"))
24585 ((org-with-limited-levels (org-at-heading-p))
24586 ;; At a headline, move to the previous one, if any, or stay
24587 ;; here.
24588 (let ((origin (point)))
24589 (org-with-limited-levels (org-backward-heading-same-level 1))
24590 ;; When current headline has no sibling above, move to its
24591 ;; parent.
24592 (when (= (point) origin)
24593 (or (org-with-limited-levels (org-up-heading-safe))
24594 (progn (goto-char origin)
24595 (user-error "Cannot move further up"))))))
24597 (let* ((elem (org-element-at-point))
24598 (beg (org-element-property :begin elem)))
24599 (cond
24600 ;; Move to beginning of current element if point isn't
24601 ;; there already.
24602 ((null beg) (message "No element at point"))
24603 ((/= (point) beg) (goto-char beg))
24604 (t (goto-char beg)
24605 (skip-chars-backward " \r\t\n")
24606 (unless (bobp)
24607 (let ((prev (org-element-at-point)))
24608 (goto-char (org-element-property :begin prev))
24609 (while (and (setq prev (org-element-property :parent prev))
24610 (<= (org-element-property :end prev) beg))
24611 (goto-char (org-element-property :begin prev)))))))))))
24613 (defun org-up-element ()
24614 "Move to upper element."
24615 (interactive)
24616 (if (org-with-limited-levels (org-at-heading-p))
24617 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24618 (let* ((elem (org-element-at-point))
24619 (parent (org-element-property :parent elem)))
24620 (if parent (goto-char (org-element-property :begin parent))
24621 (if (org-with-limited-levels (org-before-first-heading-p))
24622 (user-error "No surrounding element")
24623 (org-with-limited-levels (org-back-to-heading)))))))
24625 (defvar org-element-greater-elements)
24626 (defun org-down-element ()
24627 "Move to inner element."
24628 (interactive)
24629 (let ((element (org-element-at-point)))
24630 (cond
24631 ((memq (org-element-type element) '(plain-list table))
24632 (goto-char (org-element-property :contents-begin element))
24633 (forward-char))
24634 ((memq (org-element-type element) org-element-greater-elements)
24635 ;; If contents are hidden, first disclose them.
24636 (when (outline-invisible-p (line-end-position)) (org-cycle))
24637 (goto-char (or (org-element-property :contents-begin element)
24638 (user-error "No content for this element"))))
24639 (t (user-error "No inner element")))))
24641 (defun org-drag-element-backward ()
24642 "Move backward element at point."
24643 (interactive)
24644 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24645 (let* ((elem (org-element-at-point))
24646 (prev-elem
24647 (save-excursion
24648 (goto-char (org-element-property :begin elem))
24649 (skip-chars-backward " \r\t\n")
24650 (unless (bobp)
24651 (let* ((beg (org-element-property :begin elem))
24652 (prev (org-element-at-point))
24653 (up prev))
24654 (while (and (setq up (org-element-property :parent up))
24655 (<= (org-element-property :end up) beg))
24656 (setq prev up))
24657 prev)))))
24658 ;; Error out if no previous element or previous element is
24659 ;; a parent of the current one.
24660 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24661 (user-error "Cannot drag element backward")
24662 (let ((pos (point)))
24663 (org-element-swap-A-B prev-elem elem)
24664 (goto-char (+ (org-element-property :begin prev-elem)
24665 (- pos (org-element-property :begin elem)))))))))
24667 (defun org-drag-element-forward ()
24668 "Move forward element at point."
24669 (interactive)
24670 (let* ((pos (point))
24671 (elem (org-element-at-point)))
24672 (when (= (point-max) (org-element-property :end elem))
24673 (user-error "Cannot drag element forward"))
24674 (goto-char (org-element-property :end elem))
24675 (let ((next-elem (org-element-at-point)))
24676 (when (or (org-element-nested-p elem next-elem)
24677 (and (eq (org-element-type next-elem) 'headline)
24678 (not (eq (org-element-type elem) 'headline))))
24679 (goto-char pos)
24680 (user-error "Cannot drag element forward"))
24681 ;; Compute new position of point: it's shifted by NEXT-ELEM
24682 ;; body's length (without final blanks) and by the length of
24683 ;; blanks between ELEM and NEXT-ELEM.
24684 (let ((size-next (- (save-excursion
24685 (goto-char (org-element-property :end next-elem))
24686 (skip-chars-backward " \r\t\n")
24687 (forward-line)
24688 ;; Small correction if buffer doesn't end
24689 ;; with a newline character.
24690 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24691 (org-element-property :begin next-elem)))
24692 (size-blank (- (org-element-property :end elem)
24693 (save-excursion
24694 (goto-char (org-element-property :end elem))
24695 (skip-chars-backward " \r\t\n")
24696 (forward-line)
24697 (point)))))
24698 (org-element-swap-A-B elem next-elem)
24699 (goto-char (+ pos size-next size-blank))))))
24701 (defun org-drag-line-forward (arg)
24702 "Drag the line at point ARG lines forward."
24703 (interactive "p")
24704 (dotimes (_ (abs arg))
24705 (let ((c (current-column)))
24706 (if (< 0 arg)
24707 (progn
24708 (beginning-of-line 2)
24709 (transpose-lines 1)
24710 (beginning-of-line 0))
24711 (transpose-lines 1)
24712 (beginning-of-line -1))
24713 (org-move-to-column c))))
24715 (defun org-drag-line-backward (arg)
24716 "Drag the line at point ARG lines backward."
24717 (interactive "p")
24718 (org-drag-line-forward (- arg)))
24720 (defun org-mark-element ()
24721 "Put point at beginning of this element, mark at end.
24723 Interactively, if this command is repeated or (in Transient Mark
24724 mode) if the mark is active, it marks the next element after the
24725 ones already marked."
24726 (interactive)
24727 (let (deactivate-mark)
24728 (if (and (org-called-interactively-p 'any)
24729 (or (and (eq last-command this-command) (mark t))
24730 (and transient-mark-mode mark-active)))
24731 (set-mark
24732 (save-excursion
24733 (goto-char (mark))
24734 (goto-char (org-element-property :end (org-element-at-point)))))
24735 (let ((element (org-element-at-point)))
24736 (end-of-line)
24737 (push-mark (org-element-property :end element) t t)
24738 (goto-char (org-element-property :begin element))))))
24740 (defun org-narrow-to-element ()
24741 "Narrow buffer to current element."
24742 (interactive)
24743 (let ((elem (org-element-at-point)))
24744 (cond
24745 ((eq (car elem) 'headline)
24746 (narrow-to-region
24747 (org-element-property :begin elem)
24748 (org-element-property :end elem)))
24749 ((memq (car elem) org-element-greater-elements)
24750 (narrow-to-region
24751 (org-element-property :contents-begin elem)
24752 (org-element-property :contents-end elem)))
24754 (narrow-to-region
24755 (org-element-property :begin elem)
24756 (org-element-property :end elem))))))
24758 (defun org-transpose-element ()
24759 "Transpose current and previous elements, keeping blank lines between.
24760 Point is moved after both elements."
24761 (interactive)
24762 (org-skip-whitespace)
24763 (let ((end (org-element-property :end (org-element-at-point))))
24764 (org-drag-element-backward)
24765 (goto-char end)))
24767 (defun org-unindent-buffer ()
24768 "Un-indent the visible part of the buffer.
24769 Relative indentation (between items, inside blocks, etc.) isn't
24770 modified."
24771 (interactive)
24772 (unless (eq major-mode 'org-mode)
24773 (user-error "Cannot un-indent a buffer not in Org mode"))
24774 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24775 (unindent-tree
24776 (lambda (contents)
24777 (dolist (element (reverse contents))
24778 (if (memq (org-element-type element) '(headline section))
24779 (funcall unindent-tree (org-element-contents element))
24780 (save-excursion
24781 (save-restriction
24782 (narrow-to-region
24783 (org-element-property :begin element)
24784 (org-element-property :end element))
24785 (org-do-remove-indentation))))))))
24786 (funcall unindent-tree (org-element-contents parse-tree))))
24788 (defun org-show-children (&optional level)
24789 "Show all direct subheadings of this heading.
24790 Prefix arg LEVEL is how many levels below the current level
24791 should be shown. Default is enough to cause the following
24792 heading to appear."
24793 (interactive "p")
24794 ;; If `orgstruct-mode' is active, use the slower version.
24795 (if orgstruct-mode (call-interactively #'outline-show-children)
24796 (save-excursion
24797 (org-back-to-heading t)
24798 (let* ((current-level (funcall outline-level))
24799 (max-level (org-get-valid-level
24800 current-level
24801 (if level (prefix-numeric-value level) 1)))
24802 (end (save-excursion (org-end-of-subtree t t)))
24803 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24804 (past-first-child nil)
24805 ;; Make sure to skip inlinetasks.
24806 (re (format regexp-fmt
24807 current-level
24808 (cond
24809 ((not (featurep 'org-inlinetask)) "")
24810 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24812 (t (1- org-inlinetask-min-level))))))
24813 ;; Display parent heading.
24814 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24815 (forward-line)
24816 ;; Display children. First child may be deeper than expected
24817 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24818 ;; MAX-LEVEL accordingly.
24819 (while (re-search-forward re end t)
24820 (unless past-first-child
24821 (setq re (format regexp-fmt
24822 current-level
24823 (max (funcall outline-level) max-level)))
24824 (setq past-first-child t))
24825 (outline-flag-region
24826 (line-end-position 0) (line-end-position) nil))))))
24828 (defun org-show-subtree ()
24829 "Show everything after this heading at deeper levels."
24830 (interactive)
24831 (outline-flag-region
24832 (point)
24833 (save-excursion
24834 (org-end-of-subtree t t))
24835 nil))
24837 (defun org-show-entry ()
24838 "Show the body directly following this heading.
24839 Show the heading too, if it is currently invisible."
24840 (interactive)
24841 (save-excursion
24842 (ignore-errors
24843 (org-back-to-heading t)
24844 (outline-flag-region
24845 (max (point-min) (1- (point)))
24846 (save-excursion
24847 (if (re-search-forward
24848 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24849 (match-beginning 1)
24850 (point-max)))
24851 nil)
24852 (org-cycle-hide-drawers 'children))))
24854 (defun org-make-options-regexp (kwds &optional extra)
24855 "Make a regular expression for keyword lines.
24856 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24857 when non-nil, is a regexp matching keywords names."
24858 (concat "^[ \t]*#\\+\\("
24859 (regexp-opt kwds)
24860 (and extra (concat (and kwds "\\|") extra))
24861 "\\):[ \t]*\\(.*\\)"))
24863 ;;;; Integration with and fixes for other packages
24865 ;;; Imenu support
24867 (defvar-local org-imenu-markers nil
24868 "All markers currently used by Imenu.")
24870 (defun org-imenu-new-marker (&optional pos)
24871 "Return a new marker for use by Imenu, and remember the marker."
24872 (let ((m (make-marker)))
24873 (move-marker m (or pos (point)))
24874 (push m org-imenu-markers)
24877 (defun org-imenu-get-tree ()
24878 "Produce the index for Imenu."
24879 (dolist (x org-imenu-markers) (move-marker x nil))
24880 (setq org-imenu-markers nil)
24881 (let* ((n org-imenu-depth)
24882 (re (concat "^" (org-get-limited-outline-regexp)))
24883 (subs (make-vector (1+ n) nil))
24884 (last-level 0)
24885 m level head0 head)
24886 (save-excursion
24887 (save-restriction
24888 (widen)
24889 (goto-char (point-max))
24890 (while (re-search-backward re nil t)
24891 (setq level (org-reduced-level (funcall outline-level)))
24892 (when (and (<= level n)
24893 (looking-at org-complex-heading-regexp)
24894 (setq head0 (org-match-string-no-properties 4)))
24895 (setq head (org-link-display-format head0)
24896 m (org-imenu-new-marker))
24897 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24898 (if (>= level last-level)
24899 (push (cons head m) (aref subs level))
24900 (push (cons head (aref subs (1+ level))) (aref subs level))
24901 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24902 (setq last-level level)))))
24903 (aref subs 1)))
24905 (eval-after-load "imenu"
24906 '(progn
24907 (add-hook 'imenu-after-jump-hook
24908 (lambda ()
24909 (when (derived-mode-p 'org-mode)
24910 (org-show-context 'org-goto))))))
24912 (defun org-link-display-format (link)
24913 "Replace a link with its the description.
24914 If there is no description, use the link target."
24915 (save-match-data
24916 (if (string-match org-bracket-link-analytic-regexp link)
24917 (replace-match (if (match-end 5)
24918 (match-string 5 link)
24919 (concat (match-string 1 link)
24920 (match-string 3 link)))
24921 nil t link)
24922 link)))
24924 (defun org-toggle-link-display ()
24925 "Toggle the literal or descriptive display of links."
24926 (interactive)
24927 (if org-descriptive-links
24928 (progn (org-remove-from-invisibility-spec '(org-link))
24929 (org-restart-font-lock)
24930 (setq org-descriptive-links nil))
24931 (progn (add-to-invisibility-spec '(org-link))
24932 (org-restart-font-lock)
24933 (setq org-descriptive-links t))))
24935 ;; Speedbar support
24937 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24938 "Overlay marking the agenda restriction line in speedbar.")
24939 (overlay-put org-speedbar-restriction-lock-overlay
24940 'face 'org-agenda-restriction-lock)
24941 (overlay-put org-speedbar-restriction-lock-overlay
24942 'help-echo "Agendas are currently limited to this item.")
24943 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24945 (defun org-speedbar-set-agenda-restriction ()
24946 "Restrict future agenda commands to the location at point in speedbar.
24947 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24948 (interactive)
24949 (require 'org-agenda)
24950 (let (p m tp np dir txt)
24951 (cond
24952 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24953 'org-imenu t))
24954 (setq m (get-text-property p 'org-imenu-marker))
24955 (with-current-buffer (marker-buffer m)
24956 (goto-char m)
24957 (org-agenda-set-restriction-lock 'subtree)))
24958 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24959 'speedbar-function 'speedbar-find-file))
24960 (setq tp (previous-single-property-change
24961 (1+ p) 'speedbar-function)
24962 np (next-single-property-change
24963 tp 'speedbar-function)
24964 dir (speedbar-line-directory)
24965 txt (buffer-substring-no-properties (or tp (point-min))
24966 (or np (point-max))))
24967 (with-current-buffer (find-file-noselect
24968 (let ((default-directory dir))
24969 (expand-file-name txt)))
24970 (unless (derived-mode-p 'org-mode)
24971 (user-error "Cannot restrict to non-Org-mode file"))
24972 (org-agenda-set-restriction-lock 'file)))
24973 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24974 (move-overlay org-speedbar-restriction-lock-overlay
24975 (point-at-bol) (point-at-eol))
24976 (setq current-prefix-arg nil)
24977 (org-agenda-maybe-redo)))
24979 (defvar speedbar-file-key-map)
24980 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24981 (eval-after-load "speedbar"
24982 '(progn
24983 (speedbar-add-supported-extension ".org")
24984 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24985 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24986 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24987 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24988 (add-hook 'speedbar-visiting-tag-hook
24989 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24991 ;;; Fixes and Hacks for problems with other packages
24993 (defun org--flyspell-object-check-p (element)
24994 "Non-nil when Flyspell can check object at point.
24995 ELEMENT is the element at point."
24996 (let ((object (save-excursion
24997 (when (org-looking-at-p "\\>") (backward-char))
24998 (org-element-context element))))
24999 (cl-case (org-element-type object)
25000 ;; Prevent checks in links due to keybinding conflict with
25001 ;; Flyspell.
25002 ((code entity export-snippet inline-babel-call
25003 inline-src-block line-break latex-fragment link macro
25004 statistics-cookie target timestamp verbatim)
25005 nil)
25006 (footnote-reference
25007 ;; Only in inline footnotes, within the definition.
25008 (and (eq (org-element-property :type object) 'inline)
25009 (< (save-excursion
25010 (goto-char (org-element-property :begin object))
25011 (search-forward ":" nil t 2))
25012 (point))))
25013 (otherwise t))))
25015 (defun org-mode-flyspell-verify ()
25016 "Function used for `flyspell-generic-check-word-predicate'."
25017 (if (org-at-heading-p)
25018 ;; At a headline or an inlinetask, check title only. This is
25019 ;; faster than relying on `org-element-at-point'.
25020 (and (save-excursion (beginning-of-line)
25021 (and (let ((case-fold-search t))
25022 (not (looking-at "\\*+ END[ \t]*$")))
25023 (looking-at org-complex-heading-regexp)))
25024 (match-beginning 4)
25025 (>= (point) (match-beginning 4))
25026 (or (not (match-beginning 5))
25027 (< (point) (match-beginning 5))))
25028 (let* ((element (org-element-at-point))
25029 (post-affiliated (org-element-property :post-affiliated element)))
25030 (cond
25031 ;; Ignore checks in all affiliated keywords but captions.
25032 ((< (point) post-affiliated)
25033 (and (save-excursion
25034 (beginning-of-line)
25035 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25036 (> (point) (match-end 0))
25037 (org--flyspell-object-check-p element)))
25038 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25039 ((let ((log (org-log-into-drawer)))
25040 (and log
25041 (let ((drawer (org-element-lineage element '(drawer))))
25042 (and drawer
25043 (eq (compare-strings
25044 log nil nil
25045 (org-element-property :drawer-name drawer) nil nil t)
25046 t)))))
25047 nil)
25049 (cl-case (org-element-type element)
25050 ((comment quote-section) t)
25051 (comment-block
25052 ;; Allow checks between block markers, not on them.
25053 (and (> (line-beginning-position) post-affiliated)
25054 (save-excursion
25055 (end-of-line)
25056 (skip-chars-forward " \r\t\n")
25057 (< (point) (org-element-property :end element)))))
25058 ;; Arbitrary list of keywords where checks are meaningful.
25059 ;; Make sure point is on the value part of the element.
25060 (keyword
25061 (and (member (org-element-property :key element)
25062 '("DESCRIPTION" "TITLE"))
25063 (save-excursion
25064 (search-backward ":" (line-beginning-position) t))))
25065 ;; Check is globally allowed in paragraphs verse blocks and
25066 ;; table rows (after affiliated keywords) but some objects
25067 ;; must not be affected.
25068 ((paragraph table-row verse-block)
25069 (let ((cbeg (org-element-property :contents-begin element))
25070 (cend (org-element-property :contents-end element)))
25071 (and cbeg (>= (point) cbeg) (< (point) cend)
25072 (org--flyspell-object-check-p element))))))))))
25073 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25075 (defun org-remove-flyspell-overlays-in (beg end)
25076 "Remove flyspell overlays in region."
25077 (and (org-bound-and-true-p flyspell-mode)
25078 (fboundp 'flyspell-delete-region-overlays)
25079 (flyspell-delete-region-overlays beg end)))
25081 (defvar flyspell-delayed-commands)
25082 (eval-after-load "flyspell"
25083 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25085 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25086 (eval-after-load "bookmark"
25087 '(if (boundp 'bookmark-after-jump-hook)
25088 ;; We can use the hook
25089 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25090 ;; Hook not available, use advice
25091 (defadvice bookmark-jump (after org-make-visible activate)
25092 "Make the position visible."
25093 (org-bookmark-jump-unhide))))
25095 ;; Make sure saveplace shows the location if it was hidden
25096 (eval-after-load "saveplace"
25097 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25098 "Make the position visible."
25099 (org-bookmark-jump-unhide)))
25101 ;; Make sure ecb shows the location if it was hidden
25102 (eval-after-load "ecb"
25103 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25104 "Make hierarchy visible when jumping into location from ECB tree buffer."
25105 (when (derived-mode-p 'org-mode)
25106 (org-show-context))))
25108 (defun org-bookmark-jump-unhide ()
25109 "Unhide the current position, to show the bookmark location."
25110 (and (derived-mode-p 'org-mode)
25111 (or (outline-invisible-p)
25112 (save-excursion (goto-char (max (point-min) (1- (point))))
25113 (outline-invisible-p)))
25114 (org-show-context 'bookmark-jump)))
25116 (defun org-mark-jump-unhide ()
25117 "Make the point visible with `org-show-context' after jumping to the mark."
25118 (when (and (derived-mode-p 'org-mode)
25119 (outline-invisible-p))
25120 (org-show-context 'mark-goto)))
25122 (eval-after-load "simple"
25123 '(defadvice pop-to-mark-command (after org-make-visible activate)
25124 "Make the point visible with `org-show-context'."
25125 (org-mark-jump-unhide)))
25127 (eval-after-load "simple"
25128 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25129 "Make the point visible with `org-show-context'."
25130 (org-mark-jump-unhide)))
25132 (eval-after-load "simple"
25133 '(defadvice pop-global-mark (after org-make-visible activate)
25134 "Make the point visible with `org-show-context'."
25135 (org-mark-jump-unhide)))
25137 ;; Make session.el ignore our circular variable
25138 (defvar session-globals-exclude)
25139 (eval-after-load "session"
25140 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25142 ;;;; Finish up
25144 (provide 'org)
25146 (run-hooks 'org-load-hook)
25148 ;;; org.el ends here