Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob90d51996b669c5de1ea8536c36a91158e3d2b36c
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2015 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
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (or (equal this-command 'eval-buffer)
82 (condition-case nil
83 (load (concat (file-name-directory load-file-name)
84 "org-loaddefs.el")
85 nil t t t)
86 (error
87 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (sit-for 3)
89 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
90 (sit-for 3))))
92 (require 'org-macs)
93 (require 'org-compat)
95 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
96 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 ;; In Org buffers, the value of `outline-regexp' is that of
99 ;; `org-outline-regexp'. The only function still directly relying on
100 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
101 ;; job when `orgstruct-mode' is active.
102 (defvar org-outline-regexp "\\*+ "
103 "Regexp to match Org headlines.")
105 (defvar org-outline-regexp-bol "^\\*+ "
106 "Regexp to match Org headlines.
107 This is similar to `org-outline-regexp' but additionally makes
108 sure that we are at the beginning of the line.")
110 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
111 "Matches a headline, putting stars and text into groups.
112 Stars are put in group 1 and the trimmed body in group 2.")
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
118 (declare-function org-agenda-redo "org-agenda" (&optional all))
119 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
120 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
121 (declare-function org-beamer-mode "ox-beamer" ())
122 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
125 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
126 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
127 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
128 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
129 (declare-function org-clock-update-time-maybe "org-clock" ())
130 (declare-function org-clocktable-shift "org-clock" (dir n))
131 (declare-function org-element-at-point "org-element" ())
132 (declare-function org-element-cache-refresh "org-element" (pos))
133 (declare-function org-element-cache-reset "org-element" (&optional all))
134 (declare-function org-element-contents "org-element" (element))
135 (declare-function org-element-context "org-element" (&optional element))
136 (declare-function org-element-copy "org-element" (datum))
137 (declare-function org-element-interpret-data "org-element" (data &optional parent))
138 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
139 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
140 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
141 (declare-function org-element-property "org-element" (property element))
142 (declare-function org-element-put-property "org-element" (element property value))
143 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
144 (declare-function org-element-type "org-element" (element))
145 (declare-function org-element-update-syntax "org-element" ())
146 (declare-function org-id-find-id-file "org-id" (id))
147 (declare-function org-id-get-create "org-id" (&optional force))
148 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
149 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
150 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
151 (declare-function org-plot/gnuplot "org-plot" (&optional params))
152 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-edit-field "org-table" (arg))
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function org-table-next-row "org-table" ())
166 (declare-function org-table-paste-rectangle "org-table" ())
167 (declare-function org-table-wrap-region "org-table" (arg))
168 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
169 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
170 (declare-function orgtbl-mode "org-table" (&optional arg))
172 (defsubst org-uniquify (list)
173 "Non-destructively remove duplicate elements from LIST."
174 (let ((res (copy-sequence list))) (delete-dups res)))
176 (defsubst org-get-at-bol (property)
177 "Get text property PROPERTY at the beginning of line."
178 (get-text-property (point-at-bol) property))
180 (defsubst org-trim (s)
181 "Remove whitespace at the beginning and the end of string S."
182 (replace-regexp-in-string
183 "\\`[ \t\n\r]+" ""
184 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
186 ;; load languages based on value of `org-babel-load-languages'
187 (defvar org-babel-load-languages)
189 ;;;###autoload
190 (defun org-babel-do-load-languages (sym value)
191 "Load the languages defined in `org-babel-load-languages'."
192 (set-default sym value)
193 (mapc (lambda (pair)
194 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
195 (if active
196 (progn
197 (require (intern (concat "ob-" lang))))
198 (progn
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
203 org-babel-load-languages))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org-mode FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the org-mode file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org-mode buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "IO" io)
267 (const :tag "J" J)
268 (const :tag "Java" java)
269 (const :tag "Javascript" js)
270 (const :tag "LaTeX" latex)
271 (const :tag "Ledger" ledger)
272 (const :tag "Lilypond" lilypond)
273 (const :tag "Lisp" lisp)
274 (const :tag "Makefile" makefile)
275 (const :tag "Maxima" maxima)
276 (const :tag "Matlab" matlab)
277 (const :tag "Mscgen" mscgen)
278 (const :tag "Ocaml" ocaml)
279 (const :tag "Octave" octave)
280 (const :tag "Org" org)
281 (const :tag "Perl" perl)
282 (const :tag "Pico Lisp" picolisp)
283 (const :tag "PlantUML" plantuml)
284 (const :tag "Python" python)
285 (const :tag "Ruby" ruby)
286 (const :tag "Sass" sass)
287 (const :tag "Scala" scala)
288 (const :tag "Scheme" scheme)
289 (const :tag "Screen" screen)
290 (const :tag "Shell Script" shell)
291 (const :tag "Shen" shen)
292 (const :tag "Sql" sql)
293 (const :tag "Sqlite" sqlite)
294 (const :tag "Stan" stan)
295 (const :tag "ebnf2ps" ebnf2ps))
296 :value-type (boolean :tag "Activate" :value t)))
298 ;;;; Customization variables
299 (defcustom org-clone-delete-id nil
300 "Remove ID property of clones of a subtree.
301 When non-nil, clones of a subtree don't inherit the ID property.
302 Otherwise they inherit the ID property with a new unique
303 identifier."
304 :type 'boolean
305 :version "24.1"
306 :group 'org-id)
308 ;;; Version
309 (org-check-version)
311 ;;;###autoload
312 (defun org-version (&optional here full message)
313 "Show the org-mode version.
314 Interactively, or when MESSAGE is non-nil, show it in echo area.
315 With prefix argument, or when HERE is non-nil, insert it at point.
316 In non-interactive uses, a reduced version string is output unless
317 FULL is given."
318 (interactive (list current-prefix-arg t (not current-prefix-arg)))
319 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
320 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
321 (load-suffixes (list ".el"))
322 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
323 (org-trash (or
324 (and (fboundp 'org-release) (fboundp 'org-git-version))
325 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
326 (load-suffixes save-load-suffixes)
327 (org-version (org-release))
328 (git-version (org-git-version))
329 (version (format "Org-mode version %s (%s @ %s)"
330 org-version
331 git-version
332 (if org-install-dir
333 (if (string= org-dir org-install-dir)
334 org-install-dir
335 (concat "mixed installation! " org-install-dir " and " org-dir))
336 "org-loaddefs.el can not be found!")))
337 (version1 (if full version org-version)))
338 (when here (insert version1))
339 (when message (message "%s" version1))
340 version1))
342 (defconst org-version (org-version))
345 ;;; Syntax Constants
347 ;;;; Block
349 (defconst org-block-regexp
350 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
351 "Regular expression for hiding blocks.")
353 (defconst org-dblock-start-re
354 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
355 "Matches the start line of a dynamic block, with parameters.")
357 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
358 "Matches the end of a dynamic block.")
360 ;;;; Clock and Planning
362 (defconst org-clock-string "CLOCK:"
363 "String used as prefix for timestamps clocking work hours on an item.")
365 (defvar org-closed-string "CLOSED:"
366 "String used as the prefix for timestamps logging closing a TODO entry.")
368 (defvar org-deadline-string "DEADLINE:"
369 "String to mark deadline entries.
370 A deadline is this string, followed by a time stamp. Should be a word,
371 terminated by a colon. You can insert a schedule keyword and
372 a timestamp with \\[org-deadline].")
374 (defvar org-scheduled-string "SCHEDULED:"
375 "String to mark scheduled TODO entries.
376 A schedule is this string, followed by a time stamp. Should be a word,
377 terminated by a colon. You can insert a schedule keyword and
378 a timestamp with \\[org-schedule].")
380 (defconst org-ds-keyword-length
381 (+ 2
382 (apply #'max
383 (mapcar #'length
384 (list org-deadline-string org-scheduled-string
385 org-clock-string org-closed-string))))
386 "Maximum length of the DEADLINE and SCHEDULED keywords.")
388 (defconst org-planning-line-re
389 (concat "^[ \t]*"
390 (regexp-opt
391 (list org-closed-string org-deadline-string org-scheduled-string)
393 "Matches a line with planning info.
394 Matched keyword is in group 1.")
396 (defconst org-clock-line-re
397 (concat "^[ \t]*" org-clock-string)
398 "Matches a line with clock info.")
400 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
401 "Matches the DEADLINE keyword.")
403 (defconst org-deadline-time-regexp
404 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
405 "Matches the DEADLINE keyword together with a time stamp.")
407 (defconst org-deadline-time-hour-regexp
408 (concat "\\<" org-deadline-string
409 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
410 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
412 (defconst org-deadline-line-regexp
413 (concat "\\<\\(" org-deadline-string "\\).*")
414 "Matches the DEADLINE keyword and the rest of the line.")
416 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
417 "Matches the SCHEDULED keyword.")
419 (defconst org-scheduled-time-regexp
420 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
421 "Matches the SCHEDULED keyword together with a time stamp.")
423 (defconst org-scheduled-time-hour-regexp
424 (concat "\\<" org-scheduled-string
425 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
426 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
428 (defconst org-closed-time-regexp
429 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
430 "Matches the CLOSED keyword together with a time stamp.")
432 (defconst org-keyword-time-regexp
433 (concat "\\<"
434 (regexp-opt
435 (list org-scheduled-string org-deadline-string org-closed-string
436 org-clock-string)
438 " *[[<]\\([^]>]+\\)[]>]")
439 "Matches any of the 4 keywords, together with the time stamp.")
441 (defconst org-keyword-time-not-clock-regexp
442 (concat
443 "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string) t)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 3 keywords, together with the time stamp.")
449 (defconst org-maybe-keyword-time-regexp
450 (concat "\\(\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string
453 org-clock-string)
455 "\\)?"
456 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
457 "\\|"
458 "<%%([^\r\n>]*>\\)")
459 "Matches a timestamp, possibly preceded by a keyword.")
461 (defconst org-all-time-keywords
462 (mapcar (lambda (w) (substring w 0 -1))
463 (list org-scheduled-string org-deadline-string
464 org-clock-string org-closed-string))
465 "List of time keywords.")
467 ;;;; Drawer
469 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
470 "Matches first or last line of a hidden block.
471 Group 1 contains drawer's name or \"END\".")
473 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
474 "Regular expression matching the first line of a property drawer.")
476 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
477 "Regular expression matching the last line of a property drawer.")
479 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
480 "Regular expression matching the first line of a clock drawer.")
482 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
483 "Regular expression matching the last line of a clock drawer.")
485 (defconst org-property-drawer-re
486 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
487 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
488 "[ \t]*:END:[ \t]*$")
489 "Matches an entire property drawer.")
491 (defconst org-clock-drawer-re
492 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
493 org-clock-drawer-end-re "\\)\n?")
494 "Matches an entire clock drawer.")
496 ;;;; Headline
498 (defconst org-heading-keyword-regexp-format
499 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
500 "Printf format for a regexp matching a headline with some keyword.
501 This regexp will match the headline of any node which has the
502 exact keyword that is put into the format. The keyword isn't in
503 any group by default, but the stars and the body are.")
505 (defconst org-heading-keyword-maybe-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline, possibly with some keyword.
508 This regexp can match any headline with the specified keyword, or
509 without a keyword. The keyword isn't in any group by default,
510 but the stars and the body are.")
512 (defconst org-archive-tag "ARCHIVE"
513 "The tag that marks a subtree as archived.
514 An archived subtree does not open during visibility cycling, and does
515 not contribute to the agenda listings.")
517 (defconst org-comment-string "COMMENT"
518 "Entries starting with this keyword will never be exported.
519 An entry can be toggled between COMMENT and normal with
520 \\[org-toggle-comment].")
523 ;;;; LaTeX Environments and Fragments
525 (defconst org-latex-regexps
526 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
527 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
528 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
529 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
531 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
532 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
533 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
534 "Regular expressions for matching embedded LaTeX.")
536 ;;;; Node Property
538 (defconst org-effort-property "Effort"
539 "The property that is being used to keep track of effort estimates.
540 Effort estimates given in this property need to have the format H:MM.")
542 ;;;; Table
544 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
545 "Detect an org-type or table-type table.")
547 (defconst org-table-line-regexp "^[ \t]*|"
548 "Detect an org-type table line.")
550 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
551 "Detect an org-type table line.")
553 (defconst org-table-hline-regexp "^[ \t]*|-"
554 "Detect an org-type table hline.")
556 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
557 "Detect a table-type table hline.")
559 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
560 "Detect the first line outside a table when searching from within it.
561 This works for both table types.")
563 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
564 "Detect a #+TBLFM line.")
566 ;;;; Timestamp
568 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
569 "Regular expression for fast time stamp matching.")
571 (defconst org-ts-regexp-inactive
572 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
573 "Regular expression for fast inactive time stamp matching.")
575 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
576 "Regular expression for fast time stamp matching.")
578 (defconst org-ts-regexp0
579 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
580 "Regular expression matching time strings for analysis.
581 This one does not require the space after the date, so it can be used
582 on a string that terminates immediately after the date.")
584 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
585 "Regular expression matching time strings for analysis.")
587 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
588 "Regular expression matching time stamps, with groups.")
590 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
591 "Regular expression matching time stamps (also [..]), with groups.")
593 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
594 "Regular expression matching a time stamp range.")
596 (defconst org-tr-regexp-both
597 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
598 "Regular expression matching a time stamp range.")
600 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
601 org-ts-regexp "\\)?")
602 "Regular expression matching a time stamp or time stamp range.")
604 (defconst org-tsr-regexp-both
605 (concat org-ts-regexp-both "\\(--?-?"
606 org-ts-regexp-both "\\)?")
607 "Regular expression matching a time stamp or time stamp range.
608 The time stamps may be either active or inactive.")
610 (defconst org-repeat-re
611 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
612 "Regular expression for specifying repeated events.
613 After a match, group 1 contains the repeat expression.")
615 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
616 "Formats for `format-time-string' which are used for time stamps.")
619 ;;; The custom variables
621 (defgroup org nil
622 "Outline-based notes management and organizer."
623 :tag "Org"
624 :group 'outlines
625 :group 'calendar)
627 (defcustom org-mode-hook nil
628 "Mode hook for Org-mode, run after the mode was turned on."
629 :group 'org
630 :type 'hook)
632 (defcustom org-load-hook nil
633 "Hook that is run after org.el has been loaded."
634 :group 'org
635 :type 'hook)
637 (defcustom org-log-buffer-setup-hook nil
638 "Hook that is run after an Org log buffer is created."
639 :group 'org
640 :version "24.1"
641 :type 'hook)
643 (defvar org-modules) ; defined below
644 (defvar org-modules-loaded nil
645 "Have the modules been loaded already?")
647 (defun org-load-modules-maybe (&optional force)
648 "Load all extensions listed in `org-modules'."
649 (when (or force (not org-modules-loaded))
650 (mapc (lambda (ext)
651 (condition-case nil (require ext)
652 (error (message "Problems while trying to load feature `%s'" ext))))
653 org-modules)
654 (setq org-modules-loaded t)))
656 (defun org-set-modules (var value)
657 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
658 (set var value)
659 (when (featurep 'org)
660 (org-load-modules-maybe 'force)
661 (org-element-cache-reset 'all)))
663 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
664 "Modules that should always be loaded together with org.el.
666 If a description starts with <C>, the file is not part of Emacs
667 and loading it will require that you have downloaded and properly
668 installed the Org mode distribution.
670 You can also use this system to load external packages (i.e. neither Org
671 core modules, nor modules from the CONTRIB directory). Just add symbols
672 to the end of the list. If the package is called org-xyz.el, then you need
673 to add the symbol `xyz', and the package must have a call to:
675 (provide \\='org-xyz)
677 For export specific modules, see also `org-export-backends'."
678 :group 'org
679 :set 'org-set-modules
680 :version "24.4"
681 :package-version '(Org . "8.0")
682 :type
683 '(set :greedy t
684 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
685 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
686 (const :tag " crypt: Encryption of subtrees" org-crypt)
687 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
688 (const :tag " docview: Links to doc-view buffers" org-docview)
689 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
690 (const :tag " habit: Track your consistency with habits" org-habit)
691 (const :tag " id: Global IDs for identifying entries" org-id)
692 (const :tag " info: Links to Info nodes" org-info)
693 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
694 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
695 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
696 (const :tag " mouse: Additional mouse support" org-mouse)
697 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
698 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
699 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
701 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
702 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
703 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
704 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
705 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
706 (const :tag "C collector: Collect properties into tables" org-collector)
707 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
708 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
709 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
710 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
711 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
712 (const :tag "C eval: Include command output as text" org-eval)
713 (const :tag "C eww: Store link to url of eww" org-eww)
714 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
715 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
716 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
717 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
718 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
719 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
720 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
721 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
722 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
723 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
724 (const :tag "C mew: Links to Mew folders/messages" org-mew)
725 (const :tag "C mtags: Support for muse-like tags" org-mtags)
726 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
727 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
728 (const :tag "C registry: A registry for Org-mode links" org-registry)
729 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
730 (const :tag "C secretary: Team management with org-mode" org-secretary)
731 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
732 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
733 (const :tag "C track: Keep up with Org-mode development" org-track)
734 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
735 (const :tag "C vm: Links to VM folders/messages" org-vm)
736 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
737 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
738 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
740 (defvar org-export-registered-backends) ; From ox.el.
741 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
742 (declare-function org-export-backend-name "ox" (backend))
743 (defcustom org-export-backends '(ascii html icalendar latex)
744 "List of export back-ends that should be always available.
746 If a description starts with <C>, the file is not part of Emacs
747 and loading it will require that you have downloaded and properly
748 installed the Org mode distribution.
750 Unlike to `org-modules', libraries in this list will not be
751 loaded along with Org, but only once the export framework is
752 needed.
754 This variable needs to be set before org.el is loaded. If you
755 need to make a change while Emacs is running, use the customize
756 interface or run the following code, where VAL stands for the new
757 value of the variable, after updating it:
759 (progn
760 (setq org-export-registered-backends
761 (cl-remove-if-not
762 (lambda (backend)
763 (let ((name (org-export-backend-name backend)))
764 (or (memq name val)
765 (catch \\='parentp
766 (dolist (b val)
767 (and (org-export-derived-backend-p b name)
768 (throw \\='parentp t)))))))
769 org-export-registered-backends))
770 (let ((new-list (mapcar #\\='org-export-backend-name
771 org-export-registered-backends)))
772 (dolist (backend val)
773 (cond
774 ((not (load (format \"ox-%s\" backend) t t))
775 (message \"Problems while trying to load export back-end \\=`%s\\='\"
776 backend))
777 ((not (memq backend new-list)) (push backend new-list))))
778 (set-default \\='org-export-backends new-list)))
780 Adding a back-end to this list will also pull the back-end it
781 depends on, if any."
782 :group 'org
783 :group 'org-export
784 :version "24.4"
785 :package-version '(Org . "8.0")
786 :initialize 'custom-initialize-set
787 :set (lambda (var val)
788 (if (not (featurep 'ox)) (set-default var val)
789 ;; Any back-end not required anymore (not present in VAL and not
790 ;; a parent of any back-end in the new value) is removed from the
791 ;; list of registered back-ends.
792 (setq org-export-registered-backends
793 (cl-remove-if-not
794 (lambda (backend)
795 (let ((name (org-export-backend-name backend)))
796 (or (memq name val)
797 (catch 'parentp
798 (dolist (b val)
799 (and (org-export-derived-backend-p b name)
800 (throw 'parentp t)))))))
801 org-export-registered-backends))
802 ;; Now build NEW-LIST of both new back-ends and required
803 ;; parents.
804 (let ((new-list (mapcar #'org-export-backend-name
805 org-export-registered-backends)))
806 (dolist (backend val)
807 (cond
808 ((not (load (format "ox-%s" backend) t t))
809 (message "Problems while trying to load export back-end `%s'"
810 backend))
811 ((not (memq backend new-list)) (push backend new-list))))
812 ;; Set VAR to that list with fixed dependencies.
813 (set-default var new-list))))
814 :type '(set :greedy t
815 (const :tag " ascii Export buffer to ASCII format" ascii)
816 (const :tag " beamer Export buffer to Beamer presentation" beamer)
817 (const :tag " html Export buffer to HTML format" html)
818 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
819 (const :tag " latex Export buffer to LaTeX format" latex)
820 (const :tag " man Export buffer to MAN format" man)
821 (const :tag " md Export buffer to Markdown format" md)
822 (const :tag " odt Export buffer to ODT format" odt)
823 (const :tag " org Export buffer to Org format" org)
824 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
825 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
826 (const :tag "C deck Export buffer to deck.js presentations" deck)
827 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
828 (const :tag "C groff Export buffer to Groff format" groff)
829 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
830 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
831 (const :tag "C s5 Export buffer to s5 presentations" s5)
832 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
834 (eval-after-load 'ox
835 '(mapc
836 (lambda (backend)
837 (condition-case nil (require (intern (format "ox-%s" backend)))
838 (error (message "Problems while trying to load export back-end `%s'"
839 backend))))
840 org-export-backends))
842 (defcustom org-support-shift-select nil
843 "Non-nil means make shift-cursor commands select text when possible.
844 \\<org-mode-map>\
846 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
847 start selecting a region, or enlarge regions started in this way.
848 In Org-mode, in special contexts, these same keys are used for
849 other purposes, important enough to compete with shift selection.
850 Org tries to balance these needs by supporting `shift-select-mode'
851 outside these special contexts, under control of this variable.
853 The default of this variable is nil, to avoid confusing behavior. Shifted
854 cursor keys will then execute Org commands in the following contexts:
855 - on a headline, changing TODO state (left/right) and priority (up/down)
856 - on a time stamp, changing the time
857 - in a plain list item, changing the bullet type
858 - in a property definition line, switching between allowed values
859 - in the BEGIN line of a clock table (changing the time block).
860 Outside these contexts, the commands will throw an error.
862 When this variable is t and the cursor is not in a special
863 context, Org-mode will support shift-selection for making and
864 enlarging regions. To make this more effective, the bullet
865 cycling will no longer happen anywhere in an item line, but only
866 if the cursor is exactly on the bullet.
868 If you set this variable to the symbol `always', then the keys
869 will not be special in headlines, property lines, and item lines,
870 to make shift selection work there as well. If this is what you
871 want, you can use the following alternative commands:
872 `\\[org-todo]' and `\\[org-priority]' \
873 to change TODO state and priority,
874 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
875 can be used to switch TODO sets,
876 `\\[org-ctrl-c-minus]' to cycle item bullet types,
877 and properties can be edited by hand or in column view.
879 However, when the cursor is on a timestamp, shift-cursor commands
880 will still edit the time stamp - this is just too good to give up.
882 XEmacs user should have this variable set to nil, because
883 `shift-select-mode' is in Emacs 23 or later only."
884 :group 'org
885 :type '(choice
886 (const :tag "Never" nil)
887 (const :tag "When outside special context" t)
888 (const :tag "Everywhere except timestamps" always)))
890 (defcustom org-loop-over-headlines-in-active-region nil
891 "Shall some commands act upon headlines in the active region?
893 When set to t, some commands will be performed in all headlines
894 within the active region.
896 When set to `start-level', some commands will be performed in all
897 headlines within the active region, provided that these headlines
898 are of the same level than the first one.
900 When set to a string, those commands will be performed on the
901 matching headlines within the active region. Such string must be
902 a tags/property/todo match as it is used in the agenda tags view.
904 The list of commands is: `org-schedule', `org-deadline',
905 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
906 `org-archive-to-archive-sibling'. The archiving commands skip
907 already archived entries."
908 :type '(choice (const :tag "Don't loop" nil)
909 (const :tag "All headlines in active region" t)
910 (const :tag "In active region, headlines at the same level than the first one" start-level)
911 (string :tag "Tags/Property/Todo matcher"))
912 :version "24.1"
913 :group 'org-todo
914 :group 'org-archive)
916 (defgroup org-startup nil
917 "Options concerning startup of Org-mode."
918 :tag "Org Startup"
919 :group 'org)
921 (defcustom org-startup-folded t
922 "Non-nil means entering Org-mode will switch to OVERVIEW.
923 This can also be configured on a per-file basis by adding one of
924 the following lines anywhere in the buffer:
926 #+STARTUP: fold (or `overview', this is equivalent)
927 #+STARTUP: nofold (or `showall', this is equivalent)
928 #+STARTUP: content
929 #+STARTUP: showeverything
931 By default, this option is ignored when Org opens agenda files
932 for the first time. If you want the agenda to honor the startup
933 option, set `org-agenda-inhibit-startup' to nil."
934 :group 'org-startup
935 :type '(choice
936 (const :tag "nofold: show all" nil)
937 (const :tag "fold: overview" t)
938 (const :tag "content: all headlines" content)
939 (const :tag "show everything, even drawers" showeverything)))
941 (defcustom org-startup-truncated t
942 "Non-nil means entering Org-mode will set `truncate-lines'.
943 This is useful since some lines containing links can be very long and
944 uninteresting. Also tables look terrible when wrapped."
945 :group 'org-startup
946 :type 'boolean)
948 (defcustom org-startup-indented nil
949 "Non-nil means turn on `org-indent-mode' on startup.
950 This can also be configured on a per-file basis by adding one of
951 the following lines anywhere in the buffer:
953 #+STARTUP: indent
954 #+STARTUP: noindent"
955 :group 'org-structure
956 :type '(choice
957 (const :tag "Not" nil)
958 (const :tag "Globally (slow on startup in large files)" t)))
960 (defcustom org-use-sub-superscripts t
961 "Non-nil means interpret \"_\" and \"^\" for display.
963 If you want to control how Org exports those characters, see
964 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
965 used to be an alias for `org-export-with-sub-superscripts' in
966 Org <8.0, it is not anymore.
968 When this option is turned on, you can use TeX-like syntax for
969 sub- and superscripts within the buffer. Several characters after
970 \"_\" or \"^\" will be considered as a single item - so grouping
971 with {} is normally not needed. For example, the following things
972 will be parsed as single sub- or superscripts:
974 10^24 or 10^tau several digits will be considered 1 item.
975 10^-12 or 10^-tau a leading sign with digits or a word
976 x^2-y^3 will be read as x^2 - y^3, because items are
977 terminated by almost any nonword/nondigit char.
978 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
980 Still, ambiguity is possible. So when in doubt, use {} to enclose
981 the sub/superscript. If you set this variable to the symbol `{}',
982 the braces are *required* in order to trigger interpretations as
983 sub/superscript. This can be helpful in documents that need \"_\"
984 frequently in plain text."
985 :group 'org-startup
986 :version "24.4"
987 :package-version '(Org . "8.0")
988 :type '(choice
989 (const :tag "Always interpret" t)
990 (const :tag "Only with braces" {})
991 (const :tag "Never interpret" nil)))
993 (defcustom org-startup-with-beamer-mode nil
994 "Non-nil means turn on `org-beamer-mode' on startup.
995 This can also be configured on a per-file basis by adding one of
996 the following lines anywhere in the buffer:
998 #+STARTUP: beamer"
999 :group 'org-startup
1000 :version "24.1"
1001 :type 'boolean)
1003 (defcustom org-startup-align-all-tables nil
1004 "Non-nil means align all tables when visiting a file.
1005 This is useful when the column width in tables is forced with <N> cookies
1006 in table fields. Such tables will look correct only after the first re-align.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1009 #+STARTUP: align
1010 #+STARTUP: noalign"
1011 :group 'org-startup
1012 :type 'boolean)
1014 (defcustom org-startup-with-inline-images nil
1015 "Non-nil means show inline images when loading a new Org file.
1016 This can also be configured on a per-file basis by adding one of
1017 the following lines anywhere in the buffer:
1018 #+STARTUP: inlineimages
1019 #+STARTUP: noinlineimages"
1020 :group 'org-startup
1021 :version "24.1"
1022 :type 'boolean)
1024 (defcustom org-startup-with-latex-preview nil
1025 "Non-nil means preview LaTeX fragments when loading a new Org file.
1027 This can also be configured on a per-file basis by adding one of
1028 the following lines anywhere in the buffer:
1029 #+STARTUP: latexpreview
1030 #+STARTUP: nolatexpreview"
1031 :group 'org-startup
1032 :version "24.4"
1033 :package-version '(Org . "8.0")
1034 :type 'boolean)
1036 (defcustom org-insert-mode-line-in-empty-file nil
1037 "Non-nil means insert the first line setting Org-mode in empty files.
1038 When the function `org-mode' is called interactively in an empty file, this
1039 normally means that the file name does not automatically trigger Org-mode.
1040 To ensure that the file will always be in Org-mode in the future, a
1041 line enforcing Org-mode will be inserted into the buffer, if this option
1042 has been set."
1043 :group 'org-startup
1044 :type 'boolean)
1046 (defcustom org-replace-disputed-keys nil
1047 "Non-nil means use alternative key bindings for some keys.
1048 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1049 These keys are also used by other packages like shift-selection-mode'
1050 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1051 If you want to use Org-mode together with one of these other modes,
1052 or more generally if you would like to move some Org-mode commands to
1053 other keys, set this variable and configure the keys with the variable
1054 `org-disputed-keys'.
1056 This option is only relevant at load-time of Org-mode, and must be set
1057 *before* org.el is loaded. Changing it requires a restart of Emacs to
1058 become effective."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-use-extra-keys nil
1063 "Non-nil means use extra key sequence definitions for certain commands.
1064 This happens automatically if you run XEmacs or if `window-system'
1065 is nil. This variable lets you do the same manually. You must
1066 set it before loading org.
1068 Example: on Carbon Emacs 22 running graphically, with an external
1069 keyboard on a Powerbook, the default way of setting M-left might
1070 not work for either Alt or ESC. Setting this variable will make
1071 it work for ESC."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1077 (defcustom org-disputed-keys
1078 '(([(shift up)] . [(meta p)])
1079 ([(shift down)] . [(meta n)])
1080 ([(shift left)] . [(meta -)])
1081 ([(shift right)] . [(meta +)])
1082 ([(control shift right)] . [(meta shift +)])
1083 ([(control shift left)] . [(meta shift -)]))
1084 "Keys for which Org-mode and other modes compete.
1085 This is an alist, cars are the default keys, second element specifies
1086 the alternative to use when `org-replace-disputed-keys' is t.
1088 Keys can be specified in any syntax supported by `define-key'.
1089 The value of this option takes effect only at Org-mode's startup,
1090 therefore you'll have to restart Emacs to apply it after changing."
1091 :group 'org-startup
1092 :type 'alist)
1094 (defun org-key (key)
1095 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1096 Or return the original if not disputed.
1097 Also apply the translations defined in `org-xemacs-key-equivalents'."
1098 (when org-replace-disputed-keys
1099 (let* ((nkey (key-description key))
1100 (x (org-find-if (lambda (x)
1101 (equal (key-description (car x)) nkey))
1102 org-disputed-keys)))
1103 (setq key (if x (cdr x) key))))
1104 (when (featurep 'xemacs)
1105 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1106 key)
1108 (defun org-find-if (predicate seq)
1109 (catch 'exit
1110 (while seq
1111 (if (funcall predicate (car seq))
1112 (throw 'exit (car seq))
1113 (pop seq)))))
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org-mode outline.
1121 When nil, just use the standard three dots.
1122 When a string, use that string instead.
1123 When a face, use the standard 3 dots, but with the specified face.
1124 The change affects only Org-mode (which will then use its own display table).
1125 Changing this requires executing \\[org-mode] in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (face :tag "Face" :value org-warning)
1130 (string :tag "String" :value "...#")))
1132 (defvar org-display-table nil
1133 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org-mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org-mode files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((isearch . lineage)
1159 (bookmark-jump . lineage)
1160 (default . ancestors))
1161 "Alist between context and visibility span when revealing a location.
1163 \\<org-mode-map>Some actions may move point into invisible
1164 locations. As a consequence, Org always expose a neighborhood
1165 around point. How much is shown depends on the initial action,
1166 or context. Valid contexts are
1168 agenda when exposing an entry from the agenda
1169 org-goto when using the command `org-goto' (\\[org-goto])
1170 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1171 tags-tree when constructing a sparse tree based on tags matches
1172 link-search when exposing search matches associated with a link
1173 mark-goto when exposing the jump goal of a mark
1174 bookmark-jump when exposing a bookmark location
1175 isearch when exiting from an incremental search
1176 default default for all contexts not set explicitly
1178 Allowed visibility spans are
1180 minimal show current headline; if point is not on headline,
1181 also show entry
1183 local show current headline, entry and next headline
1185 ancestors show current headline and its direct ancestors; if
1186 point is not on headline, also show entry
1188 lineage show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and first child
1192 tree show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and all children
1196 canonical show current headline, its direct ancestors along with
1197 their entries and children; if point is not located on
1198 the headline, also show current entry and all children
1200 As special cases, a nil or t value means show all contexts in
1201 `minimal' or `canonical' view, respectively.
1203 Some views can make displayed information very compact, but also
1204 make it harder to edit the location of the match. In such
1205 a case, use the command `org-reveal' (\\[org-reveal]) to show
1206 more context."
1207 :group 'org-reveal-location
1208 :version "25.1"
1209 :package-version '(Org . "8.3")
1210 :type '(choice
1211 (const :tag "Canonical" t)
1212 (const :tag "Minimal" nil)
1213 (repeat :greedy t :tag "Individual contexts"
1214 (cons
1215 (choice :tag "Context"
1216 (const agenda)
1217 (const org-goto)
1218 (const occur-tree)
1219 (const tags-tree)
1220 (const link-search)
1221 (const mark-goto)
1222 (const bookmark-jump)
1223 (const isearch)
1224 (const default))
1225 (choice :tag "Detail level"
1226 (const minimal)
1227 (const local)
1228 (const ancestors)
1229 (const lineage)
1230 (const tree)
1231 (const canonical))))))
1233 (defcustom org-indirect-buffer-display 'other-window
1234 "How should indirect tree buffers be displayed?
1235 This applies to indirect buffers created with the commands
1236 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1237 Valid values are:
1238 current-window Display in the current window
1239 other-window Just display in another window.
1240 dedicated-frame Create one new frame, and re-use it each time.
1241 new-frame Make a new frame each time. Note that in this case
1242 previously-made indirect buffers are kept, and you need to
1243 kill these buffers yourself."
1244 :group 'org-structure
1245 :group 'org-agenda-windows
1246 :type '(choice
1247 (const :tag "In current window" current-window)
1248 (const :tag "In current frame, other window" other-window)
1249 (const :tag "Each time a new frame" new-frame)
1250 (const :tag "One dedicated frame" dedicated-frame)))
1252 (defcustom org-use-speed-commands nil
1253 "Non-nil means activate single letter commands at beginning of a headline.
1254 This may also be a function to test for appropriate locations where speed
1255 commands should be active.
1257 For example, to activate speed commands when the point is on any
1258 star at the beginning of the headline, you can do this:
1260 (setq org-use-speed-commands
1261 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1262 :group 'org-structure
1263 :type '(choice
1264 (const :tag "Never" nil)
1265 (const :tag "At beginning of headline stars" t)
1266 (function)))
1268 (defcustom org-speed-commands-user nil
1269 "Alist of additional speed commands.
1270 This list will be checked before `org-speed-commands-default'
1271 when the variable `org-use-speed-commands' is non-nil
1272 and when the cursor is at the beginning of a headline.
1273 The car if each entry is a string with a single letter, which must
1274 be assigned to `self-insert-command' in the global map.
1275 The cdr is either a command to be called interactively, a function
1276 to be called, or a form to be evaluated.
1277 An entry that is just a list with a single string will be interpreted
1278 as a descriptive headline that will be added when listing the speed
1279 commands in the Help buffer using the `?' speed command."
1280 :group 'org-structure
1281 :type '(repeat :value ("k" . ignore)
1282 (choice :value ("k" . ignore)
1283 (list :tag "Descriptive Headline" (string :tag "Headline"))
1284 (cons :tag "Letter and Command"
1285 (string :tag "Command letter")
1286 (choice
1287 (function)
1288 (sexp))))))
1290 (defcustom org-bookmark-names-plist
1291 '(:last-capture "org-capture-last-stored"
1292 :last-refile "org-refile-last-stored"
1293 :last-capture-marker "org-capture-last-stored-marker")
1294 "Names for bookmarks automatically set by some Org commands.
1295 This can provide strings as names for a number of bookmarks Org sets
1296 automatically. The following keys are currently implemented:
1297 :last-capture
1298 :last-capture-marker
1299 :last-refile
1300 When a key does not show up in the property list, the corresponding bookmark
1301 is not set."
1302 :group 'org-structure
1303 :type 'plist)
1305 (defgroup org-cycle nil
1306 "Options concerning visibility cycling in Org-mode."
1307 :tag "Org Cycle"
1308 :group 'org-structure)
1310 (defcustom org-cycle-skip-children-state-if-no-children t
1311 "Non-nil means skip CHILDREN state in entries that don't have any."
1312 :group 'org-cycle
1313 :type 'boolean)
1315 (defcustom org-cycle-max-level nil
1316 "Maximum level which should still be subject to visibility cycling.
1317 Levels higher than this will, for cycling, be treated as text, not a headline.
1318 When `org-odd-levels-only' is set, a value of N in this variable actually
1319 means 2N-1 stars as the limiting headline.
1320 When nil, cycle all levels.
1321 Note that the limiting level of cycling is also influenced by
1322 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1323 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1324 than its value."
1325 :group 'org-cycle
1326 :type '(choice
1327 (const :tag "No limit" nil)
1328 (integer :tag "Maximum level")))
1330 (defcustom org-hide-block-startup nil
1331 "Non-nil means entering Org-mode will fold all blocks.
1332 This can also be set in on a per-file basis with
1334 #+STARTUP: hideblocks
1335 #+STARTUP: showblocks"
1336 :group 'org-startup
1337 :group 'org-cycle
1338 :type 'boolean)
1340 (defcustom org-cycle-global-at-bob nil
1341 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1342 This makes it possible to do global cycling without having to use S-TAB or
1343 \\[universal-argument] TAB. For this special case to work, the first line
1344 of the buffer must not be a headline -- it may be empty or some other text.
1345 When used in this way, `org-cycle-hook' is disabled temporarily to make
1346 sure the cursor stays at the beginning of the buffer. When this option is
1347 nil, don't do anything special at the beginning of the buffer."
1348 :group 'org-cycle
1349 :type 'boolean)
1351 (defcustom org-cycle-level-after-item/entry-creation t
1352 "Non-nil means cycle entry level or item indentation in new empty entries.
1354 When the cursor is at the end of an empty headline, i.e., with only stars
1355 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1356 and then all possible ancestor states, before returning to the original state.
1357 This makes data entry extremely fast: M-RET to create a new headline,
1358 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1360 When the cursor is at the end of an empty plain list item, one TAB will
1361 make it a subitem, two or more tabs will back up to make this an item
1362 higher up in the item hierarchy."
1363 :group 'org-cycle
1364 :type 'boolean)
1366 (defcustom org-cycle-emulate-tab t
1367 "Where should `org-cycle' emulate TAB.
1368 nil Never
1369 white Only in completely white lines
1370 whitestart Only at the beginning of lines, before the first non-white char
1371 t Everywhere except in headlines
1372 exc-hl-bol Everywhere except at the start of a headline
1373 If TAB is used in a place where it does not emulate TAB, the current subtree
1374 visibility is cycled."
1375 :group 'org-cycle
1376 :type '(choice (const :tag "Never" nil)
1377 (const :tag "Only in completely white lines" white)
1378 (const :tag "Before first char in a line" whitestart)
1379 (const :tag "Everywhere except in headlines" t)
1380 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1382 (defcustom org-cycle-separator-lines 2
1383 "Number of empty lines needed to keep an empty line between collapsed trees.
1384 If you leave an empty line between the end of a subtree and the following
1385 headline, this empty line is hidden when the subtree is folded.
1386 Org-mode will leave (exactly) one empty line visible if the number of
1387 empty lines is equal or larger to the number given in this variable.
1388 So the default 2 means at least 2 empty lines after the end of a subtree
1389 are needed to produce free space between a collapsed subtree and the
1390 following headline.
1392 If the number is negative, and the number of empty lines is at least -N,
1393 all empty lines are shown.
1395 Special case: when 0, never leave empty lines in collapsed view."
1396 :group 'org-cycle
1397 :type 'integer)
1398 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1400 (defcustom org-pre-cycle-hook nil
1401 "Hook that is run before visibility cycling is happening.
1402 The function(s) in this hook must accept a single argument which indicates
1403 the new state that will be set right after running this hook. The
1404 argument is a symbol. Before a global state change, it can have the values
1405 `overview', `content', or `all'. Before a local state change, it can have
1406 the values `folded', `children', or `subtree'."
1407 :group 'org-cycle
1408 :type 'hook)
1410 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1411 org-cycle-hide-drawers
1412 org-cycle-show-empty-lines
1413 org-optimize-window-after-visibility-change)
1414 "Hook that is run after `org-cycle' has changed the buffer visibility.
1415 The function(s) in this hook must accept a single argument which indicates
1416 the new state that was set by the most recent `org-cycle' command. The
1417 argument is a symbol. After a global state change, it can have the values
1418 `overview', `contents', or `all'. After a local state change, it can have
1419 the values `folded', `children', or `subtree'."
1420 :group 'org-cycle
1421 :type 'hook
1422 :version "25.1"
1423 :package-version '(Org . "8.3"))
1425 (defgroup org-edit-structure nil
1426 "Options concerning structure editing in Org-mode."
1427 :tag "Org Edit Structure"
1428 :group 'org-structure)
1430 (defcustom org-odd-levels-only nil
1431 "Non-nil means skip even levels and only use odd levels for the outline.
1432 This has the effect that two stars are being added/taken away in
1433 promotion/demotion commands. It also influences how levels are
1434 handled by the exporters.
1435 Changing it requires restart of `font-lock-mode' to become effective
1436 for fontification also in regions already fontified.
1437 You may also set this on a per-file basis by adding one of the following
1438 lines to the buffer:
1440 #+STARTUP: odd
1441 #+STARTUP: oddeven"
1442 :group 'org-edit-structure
1443 :group 'org-appearance
1444 :type 'boolean)
1446 (defcustom org-adapt-indentation t
1447 "Non-nil means adapt indentation to outline node level.
1449 When this variable is set, Org assumes that you write outlines by
1450 indenting text in each node to align with the headline (after the
1451 stars). The following issues are influenced by this variable:
1453 - The indentation is increased by one space in a demotion
1454 command, and decreased by one in a promotion command. However,
1455 in the latter case, if shifting some line in the entry body
1456 would alter document structure (e.g., insert a new headline),
1457 indentation is not changed at all.
1459 - Property drawers and planning information is inserted indented
1460 when this variable is set. When nil, they will not be indented.
1462 - TAB indents a line relative to current level. The lines below
1463 a headline will be indented when this variable is set.
1465 Note that this is all about true indentation, by adding and
1466 removing space characters. See also `org-indent.el' which does
1467 level-dependent indentation in a virtual way, i.e. at display
1468 time in Emacs."
1469 :group 'org-edit-structure
1470 :type 'boolean)
1472 (defcustom org-special-ctrl-a/e nil
1473 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1475 When t, `C-a' will bring back the cursor to the beginning of the
1476 headline text, i.e. after the stars and after a possible TODO
1477 keyword. In an item, this will be the position after bullet and
1478 check-box, if any. When the cursor is already at that position,
1479 another `C-a' will bring it to the beginning of the line.
1481 `C-e' will jump to the end of the headline, ignoring the presence
1482 of tags in the headline. A second `C-e' will then jump to the
1483 true end of the line, after any tags. This also means that, when
1484 this variable is non-nil, `C-e' also will never jump beyond the
1485 end of the heading of a folded section, i.e. not after the
1486 ellipses.
1488 When set to the symbol `reversed', the first `C-a' or `C-e' works
1489 normally, going to the true line boundary first. Only a directly
1490 following, identical keypress will bring the cursor to the
1491 special positions.
1493 This may also be a cons cell where the behavior for `C-a' and
1494 `C-e' is set separately."
1495 :group 'org-edit-structure
1496 :type '(choice
1497 (const :tag "off" nil)
1498 (const :tag "on: after stars/bullet and before tags first" t)
1499 (const :tag "reversed: true line boundary first" reversed)
1500 (cons :tag "Set C-a and C-e separately"
1501 (choice :tag "Special C-a"
1502 (const :tag "off" nil)
1503 (const :tag "on: after stars/bullet first" t)
1504 (const :tag "reversed: before stars/bullet first" reversed))
1505 (choice :tag "Special C-e"
1506 (const :tag "off" nil)
1507 (const :tag "on: before tags first" t)
1508 (const :tag "reversed: after tags first" reversed)))))
1509 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1511 (defcustom org-special-ctrl-k nil
1512 "Non-nil means `C-k' will behave specially in headlines.
1513 When nil, `C-k' will call the default `kill-line' command.
1514 When t, the following will happen while the cursor is in the headline:
1516 - When the cursor is at the beginning of a headline, kill the entire
1517 line and possible the folded subtree below the line.
1518 - When in the middle of the headline text, kill the headline up to the tags.
1519 - When after the headline text, kill the tags."
1520 :group 'org-edit-structure
1521 :type 'boolean)
1523 (defcustom org-ctrl-k-protect-subtree nil
1524 "Non-nil means, do not delete a hidden subtree with C-k.
1525 When set to the symbol `error', simply throw an error when C-k is
1526 used to kill (part-of) a headline that has hidden text behind it.
1527 Any other non-nil value will result in a query to the user, if it is
1528 OK to kill that hidden subtree. When nil, kill without remorse."
1529 :group 'org-edit-structure
1530 :version "24.1"
1531 :type '(choice
1532 (const :tag "Do not protect hidden subtrees" nil)
1533 (const :tag "Protect hidden subtrees with a security query" t)
1534 (const :tag "Never kill a hidden subtree with C-k" error)))
1536 (defcustom org-special-ctrl-o t
1537 "Non-nil means, make `C-o' insert a row in tables."
1538 :group 'org-edit-structure
1539 :type 'boolean)
1541 (defcustom org-catch-invisible-edits nil
1542 "Check if in invisible region before inserting or deleting a character.
1543 Valid values are:
1545 nil Do not check, so just do invisible edits.
1546 error Throw an error and do nothing.
1547 show Make point visible, and do the requested edit.
1548 show-and-error Make point visible, then throw an error and abort the edit.
1549 smart Make point visible, and do insertion/deletion if it is
1550 adjacent to visible text and the change feels predictable.
1551 Never delete a previously invisible character or add in the
1552 middle or right after an invisible region. Basically, this
1553 allows insertion and backward-delete right before ellipses.
1554 FIXME: maybe in this case we should not even show?"
1555 :group 'org-edit-structure
1556 :version "24.1"
1557 :type '(choice
1558 (const :tag "Do not check" nil)
1559 (const :tag "Throw error when trying to edit" error)
1560 (const :tag "Unhide, but do not do the edit" show-and-error)
1561 (const :tag "Show invisible part and do the edit" show)
1562 (const :tag "Be smart and do the right thing" smart)))
1564 (defcustom org-yank-folded-subtrees t
1565 "Non-nil means when yanking subtrees, fold them.
1566 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1567 it starts with a heading and all other headings in it are either children
1568 or siblings, then fold all the subtrees. However, do this only if no
1569 text after the yank would be swallowed into a folded tree by this action."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-yank-adjusted-subtrees nil
1574 "Non-nil means when yanking subtrees, adjust the level.
1575 With this setting, `org-paste-subtree' is used to insert the subtree, see
1576 this function for details."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-M-RET-may-split-line '((default . t))
1581 "Non-nil means M-RET will split the line at the cursor position.
1582 When nil, it will go to the end of the line before making a
1583 new line.
1584 You may also set this option in a different way for different
1585 contexts. Valid contexts are:
1587 headline when creating a new headline
1588 item when creating a new item
1589 table in a table field
1590 default the value to be used for all contexts not explicitly
1591 customized"
1592 :group 'org-structure
1593 :group 'org-table
1594 :type '(choice
1595 (const :tag "Always" t)
1596 (const :tag "Never" nil)
1597 (repeat :greedy t :tag "Individual contexts"
1598 (cons
1599 (choice :tag "Context"
1600 (const headline)
1601 (const item)
1602 (const table)
1603 (const default))
1604 (boolean)))))
1607 (defcustom org-insert-heading-respect-content nil
1608 "Non-nil means insert new headings after the current subtree.
1609 When nil, the new heading is created directly after the current line.
1610 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1611 this variable on for the duration of the command."
1612 :group 'org-structure
1613 :type 'boolean)
1615 (defcustom org-blank-before-new-entry '((heading . auto)
1616 (plain-list-item . auto))
1617 "Should `org-insert-heading' leave a blank line before new heading/item?
1618 The value is an alist, with `heading' and `plain-list-item' as CAR,
1619 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1620 which case Org will look at the surrounding headings/items and try to
1621 make an intelligent decision whether to insert a blank line or not."
1622 :group 'org-edit-structure
1623 :type '(list
1624 (cons (const heading)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))
1628 (cons (const plain-list-item)
1629 (choice (const :tag "Never" nil)
1630 (const :tag "Always" t)
1631 (const :tag "Auto" auto)))))
1633 (defcustom org-insert-heading-hook nil
1634 "Hook being run after inserting a new heading."
1635 :group 'org-edit-structure
1636 :type 'hook)
1638 (defcustom org-enable-fixed-width-editor t
1639 "Non-nil means lines starting with \":\" are treated as fixed-width.
1640 This currently only means they are never auto-wrapped.
1641 When nil, such lines will be treated like ordinary lines."
1642 :group 'org-edit-structure
1643 :type 'boolean)
1645 (defcustom org-goto-auto-isearch t
1646 "Non-nil means typing characters in `org-goto' starts incremental search.
1647 When nil, you can use these keybindings to navigate the buffer:
1649 q Quit the org-goto interface
1650 n Go to the next visible heading
1651 p Go to the previous visible heading
1652 f Go one heading forward on same level
1653 b Go one heading backward on same level
1654 u Go one heading up"
1655 :group 'org-edit-structure
1656 :type 'boolean)
1658 (defgroup org-sparse-trees nil
1659 "Options concerning sparse trees in Org-mode."
1660 :tag "Org Sparse Trees"
1661 :group 'org-structure)
1663 (defcustom org-highlight-sparse-tree-matches t
1664 "Non-nil means highlight all matches that define a sparse tree.
1665 The highlights will automatically disappear the next time the buffer is
1666 changed by an edit command."
1667 :group 'org-sparse-trees
1668 :type 'boolean)
1670 (defcustom org-remove-highlights-with-change t
1671 "Non-nil means any change to the buffer will remove temporary highlights.
1672 \\<org-mode-map>\
1673 Such highlights are created by `org-occur' and `org-clock-display'.
1674 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1675 to get rid of the highlights.
1676 The highlights created by `org-toggle-latex-fragment' always need
1677 `\\[org-toggle-latex-fragment]' to be removed."
1678 :group 'org-sparse-trees
1679 :group 'org-time
1680 :type 'boolean)
1683 (defcustom org-occur-hook '(org-first-headline-recenter)
1684 "Hook that is run after `org-occur' has constructed a sparse tree.
1685 This can be used to recenter the window to show as much of the structure
1686 as possible."
1687 :group 'org-sparse-trees
1688 :type 'hook)
1690 (defgroup org-imenu-and-speedbar nil
1691 "Options concerning imenu and speedbar in Org-mode."
1692 :tag "Org Imenu and Speedbar"
1693 :group 'org-structure)
1695 (defcustom org-imenu-depth 2
1696 "The maximum level for Imenu access to Org-mode headlines.
1697 This also applied for speedbar access."
1698 :group 'org-imenu-and-speedbar
1699 :type 'integer)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org-mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-enable-table-editor 'optimized
1707 "Non-nil means lines starting with \"|\" are handled by the table editor.
1708 When nil, such lines will be treated like ordinary lines.
1710 When equal to the symbol `optimized', the table editor will be optimized to
1711 do the following:
1712 - Automatic overwrite mode in front of whitespace in table fields.
1713 This makes the structure of the table stay in tact as long as the edited
1714 field does not exceed the column width.
1715 - Minimize the number of realigns. Normally, the table is aligned each time
1716 TAB or RET are pressed to move to another field. With optimization this
1717 happens only if changes to a field might have changed the column width.
1718 Optimization requires replacing the functions `self-insert-command',
1719 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1720 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1721 very good at guessing when a re-align will be necessary, but you can always
1722 force one with \\[org-ctrl-c-ctrl-c].
1724 If you would like to use the optimized version in Org-mode, but the
1725 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1727 This variable can be used to turn on and off the table editor during a session,
1728 but in order to toggle optimization, a restart is required.
1730 See also the variable `org-table-auto-blank-field'."
1731 :group 'org-table
1732 :type '(choice
1733 (const :tag "off" nil)
1734 (const :tag "on" t)
1735 (const :tag "on, optimized" optimized)))
1737 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1738 (version<= emacs-version "24.1"))
1739 "Non-nil means cluster self-insert commands for undo when possible.
1740 If this is set, then, like in the Emacs command loop, 20 consecutive
1741 characters will be undone together.
1742 This is configurable, because there is some impact on typing performance."
1743 :group 'org-table
1744 :type 'boolean)
1746 (defcustom org-table-tab-recognizes-table.el t
1747 "Non-nil means TAB will automatically notice a table.el table.
1748 When it sees such a table, it moves point into it and - if necessary -
1749 calls `table-recognize-table'."
1750 :group 'org-table-editing
1751 :type 'boolean)
1753 (defgroup org-link nil
1754 "Options concerning links in Org-mode."
1755 :tag "Org Link"
1756 :group 'org)
1758 (defvar-local org-link-abbrev-alist-local nil
1759 "Buffer-local version of `org-link-abbrev-alist', which see.
1760 The value of this is taken from the #+LINK lines.")
1762 (defcustom org-link-abbrev-alist nil
1763 "Alist of link abbreviations.
1764 The car of each element is a string, to be replaced at the start of a link.
1765 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1766 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1768 [[linkkey:tag][description]]
1770 The `linkkey' must be a word word, starting with a letter, followed
1771 by letters, numbers, `-' or `_'.
1773 If REPLACE is a string, the tag will simply be appended to create the link.
1774 If the string contains \"%s\", the tag will be inserted there. If the string
1775 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1776 at that point (see the function `url-hexify-string'). If the string contains
1777 the specifier \"%(my-function)\", then the custom function `my-function' will
1778 be invoked: this function takes the tag as its only argument and must return
1779 a string.
1781 REPLACE may also be a function that will be called with the tag as the
1782 only argument to create the link, which should be returned as a string.
1784 See the manual for examples."
1785 :group 'org-link
1786 :type '(repeat
1787 (cons
1788 (string :tag "Protocol")
1789 (choice
1790 (string :tag "Format")
1791 (function)))))
1793 (defcustom org-descriptive-links t
1794 "Non-nil means Org will display descriptive links.
1795 E.g. [[http://orgmode.org][Org website]] will be displayed as
1796 \"Org Website\", hiding the link itself and just displaying its
1797 description. When set to nil, Org will display the full links
1798 literally.
1800 You can interactively set the value of this variable by calling
1801 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1802 :group 'org-link
1803 :type 'boolean)
1805 (defcustom org-link-file-path-type 'adaptive
1806 "How the path name in file links should be stored.
1807 Valid values are:
1809 relative Relative to the current directory, i.e. the directory of the file
1810 into which the link is being inserted.
1811 absolute Absolute path, if possible with ~ for home directory.
1812 noabbrev Absolute path, no abbreviation of home directory.
1813 adaptive Use relative path for files in the current directory and sub-
1814 directories of it. For other files, use an absolute path."
1815 :group 'org-link
1816 :type '(choice
1817 (const relative)
1818 (const absolute)
1819 (const noabbrev)
1820 (const adaptive)))
1822 (defvaralias 'org-activate-links 'org-highlight-links)
1823 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1824 "Types of links that should be highlighted in Org-mode files.
1826 This is a list of symbols, each one of them leading to the
1827 highlighting of a certain link type.
1829 You can still open links that are not highlighted.
1831 In principle, it does not hurt to turn on highlighting for all
1832 link types. There may be a small gain when turning off unused
1833 link types. The types are:
1835 bracket The recommended [[link][description]] or [[link]] links with hiding.
1836 angle Links in angular brackets that may contain whitespace like
1837 <bbdb:Carsten Dominik>.
1838 plain Plain links in normal text, no whitespace, like http://google.com.
1839 radio Text that is matched by a radio target, see manual for details.
1840 tag Tag settings in a headline (link to tag search).
1841 date Time stamps (link to calendar).
1842 footnote Footnote labels.
1844 If you set this variable during an Emacs session, use `org-mode-restart'
1845 in the Org buffer so that the change takes effect."
1846 :group 'org-link
1847 :group 'org-appearance
1848 :type '(set :greedy t
1849 (const :tag "Double bracket links" bracket)
1850 (const :tag "Angular bracket links" angle)
1851 (const :tag "Plain text links" plain)
1852 (const :tag "Radio target matches" radio)
1853 (const :tag "Tags" tag)
1854 (const :tag "Timestamps" date)
1855 (const :tag "Footnotes" footnote)))
1857 (defcustom org-make-link-description-function nil
1858 "Function to use for generating link descriptions from links.
1859 When nil, the link location will be used. This function must take
1860 two parameters: the first one is the link, the second one is the
1861 description generated by `org-insert-link'. The function should
1862 return the description to use."
1863 :group 'org-link
1864 :type '(choice (const nil) (function)))
1866 (defgroup org-link-store nil
1867 "Options concerning storing links in Org-mode."
1868 :tag "Org Store Link"
1869 :group 'org-link)
1871 (defcustom org-url-hexify-p t
1872 "When non-nil, hexify URL when creating a link."
1873 :type 'boolean
1874 :version "24.3"
1875 :group 'org-link-store)
1877 (defcustom org-email-link-description-format "Email %c: %.30s"
1878 "Format of the description part of a link to an email or usenet message.
1879 The following %-escapes will be replaced by corresponding information:
1881 %F full \"From\" field
1882 %f name, taken from \"From\" field, address if no name
1883 %T full \"To\" field
1884 %t first name in \"To\" field, address if no name
1885 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1886 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1887 %s subject
1888 %d date
1889 %m message-id.
1891 You may use normal field width specification between the % and the letter.
1892 This is for example useful to limit the length of the subject.
1894 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1895 :group 'org-link-store
1896 :type 'string)
1898 (defcustom org-from-is-user-regexp
1899 (let (r1 r2)
1900 (when (and user-mail-address (not (string= user-mail-address "")))
1901 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1902 (when (and user-full-name (not (string= user-full-name "")))
1903 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1904 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1905 "Regexp matched against the \"From:\" header of an email or usenet message.
1906 It should match if the message is from the user him/herself."
1907 :group 'org-link-store
1908 :type 'regexp)
1910 (defcustom org-context-in-file-links t
1911 "Non-nil means file links from `org-store-link' contain context.
1912 A search string will be added to the file name with :: as separator and
1913 used to find the context when the link is activated by the command
1914 `org-open-at-point'. When this option is t, the entire active region
1915 will be placed in the search string of the file link. If set to a
1916 positive integer, only the first n lines of context will be stored.
1918 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1919 negates this setting for the duration of the command."
1920 :group 'org-link-store
1921 :type '(choice boolean integer))
1923 (defcustom org-keep-stored-link-after-insertion nil
1924 "Non-nil means keep link in list for entire session.
1926 The command `org-store-link' adds a link pointing to the current
1927 location to an internal list. These links accumulate during a session.
1928 The command `org-insert-link' can be used to insert links into any
1929 Org-mode file (offering completion for all stored links). When this
1930 option is nil, every link which has been inserted once using \\[org-insert-link]
1931 will be removed from the list, to make completing the unused links
1932 more efficient."
1933 :group 'org-link-store
1934 :type 'boolean)
1936 (defgroup org-link-follow nil
1937 "Options concerning following links in Org-mode."
1938 :tag "Org Follow Link"
1939 :group 'org-link)
1941 (defcustom org-link-translation-function nil
1942 "Function to translate links with different syntax to Org syntax.
1943 This can be used to translate links created for example by the Planner
1944 or emacs-wiki packages to Org syntax.
1945 The function must accept two parameters, a TYPE containing the link
1946 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1947 which is everything after the link protocol. It should return a cons
1948 with possibly modified values of type and path.
1949 Org contains a function for this, so if you set this variable to
1950 `org-translate-link-from-planner', you should be able follow many
1951 links created by planner."
1952 :group 'org-link-follow
1953 :type '(choice (const nil) (function)))
1955 (defcustom org-follow-link-hook nil
1956 "Hook that is run after a link has been followed."
1957 :group 'org-link-follow
1958 :type 'hook)
1960 (defcustom org-tab-follows-link nil
1961 "Non-nil means on links TAB will follow the link.
1962 Needs to be set before org.el is loaded.
1963 This really should not be used, it does not make sense, and the
1964 implementation is bad."
1965 :group 'org-link-follow
1966 :type 'boolean)
1968 (defcustom org-return-follows-link nil
1969 "Non-nil means on links RET will follow the link.
1970 In tables, the special behavior of RET has precedence."
1971 :group 'org-link-follow
1972 :type 'boolean)
1974 (defcustom org-mouse-1-follows-link
1975 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1976 "Non-nil means mouse-1 on a link will follow the link.
1977 A longer mouse click will still set point. Does not work on XEmacs.
1978 Needs to be set before org.el is loaded."
1979 :group 'org-link-follow
1980 :version "24.4"
1981 :package-version '(Org . "8.3")
1982 :type '(choice
1983 (const :tag "A double click follows the link" double)
1984 (const :tag "Unconditionally follow the link with mouse-1" t)
1985 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1987 (defcustom org-mark-ring-length 4
1988 "Number of different positions to be recorded in the ring.
1989 Changing this requires a restart of Emacs to work correctly."
1990 :group 'org-link-follow
1991 :type 'integer)
1993 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1994 "Non-nil means internal links in Org files must exactly match a headline.
1995 When nil, the link search tries to match a phrase with all words
1996 in the search text."
1997 :group 'org-link-follow
1998 :version "24.1"
1999 :type '(choice
2000 (const :tag "Use fuzzy text search" nil)
2001 (const :tag "Match only exact headline" t)
2002 (const :tag "Match exact headline or query to create it"
2003 query-to-create)))
2005 (defcustom org-link-frame-setup
2006 '((vm . vm-visit-folder-other-frame)
2007 (vm-imap . vm-visit-imap-folder-other-frame)
2008 (gnus . org-gnus-no-new-news)
2009 (file . find-file-other-window)
2010 (wl . wl-other-frame))
2011 "Setup the frame configuration for following links.
2012 When following a link with Emacs, it may often be useful to display
2013 this link in another window or frame. This variable can be used to
2014 set this up for the different types of links.
2015 For VM, use any of
2016 `vm-visit-folder'
2017 `vm-visit-folder-other-window'
2018 `vm-visit-folder-other-frame'
2019 For Gnus, use any of
2020 `gnus'
2021 `gnus-other-frame'
2022 `org-gnus-no-new-news'
2023 For FILE, use any of
2024 `find-file'
2025 `find-file-other-window'
2026 `find-file-other-frame'
2027 For Wanderlust use any of
2028 `wl'
2029 `wl-other-frame'
2030 For the calendar, use the variable `calendar-setup'.
2031 For BBDB, it is currently only possible to display the matches in
2032 another window."
2033 :group 'org-link-follow
2034 :type '(list
2035 (cons (const vm)
2036 (choice
2037 (const vm-visit-folder)
2038 (const vm-visit-folder-other-window)
2039 (const vm-visit-folder-other-frame)))
2040 (cons (const vm-imap)
2041 (choice
2042 (const vm-visit-imap-folder)
2043 (const vm-visit-imap-folder-other-window)
2044 (const vm-visit-imap-folder-other-frame)))
2045 (cons (const gnus)
2046 (choice
2047 (const gnus)
2048 (const gnus-other-frame)
2049 (const org-gnus-no-new-news)))
2050 (cons (const file)
2051 (choice
2052 (const find-file)
2053 (const find-file-other-window)
2054 (const find-file-other-frame)))
2055 (cons (const wl)
2056 (choice
2057 (const wl)
2058 (const wl-other-frame)))))
2060 (defcustom org-display-internal-link-with-indirect-buffer nil
2061 "Non-nil means use indirect buffer to display infile links.
2062 Activating internal links (from one location in a file to another location
2063 in the same file) normally just jumps to the location. When the link is
2064 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2065 is displayed in
2066 another window. When this option is set, the other window actually displays
2067 an indirect buffer clone of the current buffer, to avoid any visibility
2068 changes to the current buffer."
2069 :group 'org-link-follow
2070 :type 'boolean)
2072 (defcustom org-open-non-existing-files nil
2073 "Non-nil means `org-open-file' will open non-existing files.
2074 When nil, an error will be generated.
2075 This variable applies only to external applications because they
2076 might choke on non-existing files. If the link is to a file that
2077 will be opened in Emacs, the variable is ignored."
2078 :group 'org-link-follow
2079 :type 'boolean)
2081 (defcustom org-open-directory-means-index-dot-org nil
2082 "Non-nil means a link to a directory really means to index.org.
2083 When nil, following a directory link will run dired or open a finder/explorer
2084 window on that directory."
2085 :group 'org-link-follow
2086 :type 'boolean)
2088 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2089 "Non-nil means ask for confirmation before executing shell links.
2090 Shell links can be dangerous: just think about a link
2092 [[shell:rm -rf ~/*][Google Search]]
2094 This link would show up in your Org-mode document as \"Google Search\",
2095 but really it would remove your entire home directory.
2096 Therefore we advise against setting this variable to nil.
2097 Just change it to `y-or-n-p' if you want to confirm with a
2098 single keystroke rather than having to type \"yes\"."
2099 :group 'org-link-follow
2100 :type '(choice
2101 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2102 (const :tag "with y-or-n (faster)" y-or-n-p)
2103 (const :tag "no confirmation (dangerous)" nil)))
2104 (put 'org-confirm-shell-link-function
2105 'safe-local-variable
2106 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2108 (defcustom org-confirm-shell-link-not-regexp ""
2109 "A regexp to skip confirmation for shell links."
2110 :group 'org-link-follow
2111 :version "24.1"
2112 :type 'regexp)
2114 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2115 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2116 Elisp links can be dangerous: just think about a link
2118 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2120 This link would show up in your Org-mode document as \"Google Search\",
2121 but really it would remove your entire home directory.
2122 Therefore we advise against setting this variable to nil.
2123 Just change it to `y-or-n-p' if you want to confirm with a
2124 single keystroke rather than having to type \"yes\"."
2125 :group 'org-link-follow
2126 :type '(choice
2127 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2128 (const :tag "with y-or-n (faster)" y-or-n-p)
2129 (const :tag "no confirmation (dangerous)" nil)))
2130 (put 'org-confirm-shell-link-function
2131 'safe-local-variable
2132 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2134 (defcustom org-confirm-elisp-link-not-regexp ""
2135 "A regexp to skip confirmation for Elisp links."
2136 :group 'org-link-follow
2137 :version "24.1"
2138 :type 'regexp)
2140 (defconst org-file-apps-defaults-gnu
2141 '((remote . emacs)
2142 (system . mailcap)
2143 (t . mailcap))
2144 "Default file applications on a UNIX or GNU/Linux system.
2145 See `org-file-apps'.")
2147 (defconst org-file-apps-defaults-macosx
2148 '((remote . emacs)
2149 (t . "open %s")
2150 (system . "open %s")
2151 ("ps.gz" . "gv %s")
2152 ("eps.gz" . "gv %s")
2153 ("dvi" . "xdvi %s")
2154 ("fig" . "xfig %s"))
2155 "Default file applications on a MacOS X system.
2156 The system \"open\" is known as a default, but we use X11 applications
2157 for some files for which the OS does not have a good default.
2158 See `org-file-apps'.")
2160 (defconst org-file-apps-defaults-windowsnt
2161 (list
2162 '(remote . emacs)
2163 (cons t
2164 (list (if (featurep 'xemacs)
2165 'mswindows-shell-execute
2166 'w32-shell-execute)
2167 "open" 'file))
2168 (cons 'system
2169 (list (if (featurep 'xemacs)
2170 'mswindows-shell-execute
2171 'w32-shell-execute)
2172 "open" 'file)))
2173 "Default file applications on a Windows NT system.
2174 The system \"open\" is used for most files.
2175 See `org-file-apps'.")
2177 (defcustom org-file-apps
2178 '((auto-mode . emacs)
2179 ("\\.mm\\'" . default)
2180 ("\\.x?html?\\'" . default)
2181 ("\\.pdf\\'" . default))
2182 "External applications for opening `file:path' items in a document.
2183 Org-mode uses system defaults for different file types, but
2184 you can use this variable to set the application for a given file
2185 extension. The entries in this list are cons cells where the car identifies
2186 files and the cdr the corresponding command. Possible values for the
2187 file identifier are
2188 \"string\" A string as a file identifier can be interpreted in different
2189 ways, depending on its contents:
2191 - Alphanumeric characters only:
2192 Match links with this file extension.
2193 Example: (\"pdf\" . \"evince %s\")
2194 to open PDFs with evince.
2196 - Regular expression: Match links where the
2197 filename matches the regexp. If you want to
2198 use groups here, use shy groups.
2200 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2201 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2202 to open *.html and *.xhtml with firefox.
2204 - Regular expression which contains (non-shy) groups:
2205 Match links where the whole link, including \"::\", and
2206 anything after that, matches the regexp.
2207 In a custom command string, %1, %2, etc. are replaced with
2208 the parts of the link that were matched by the groups.
2209 For backwards compatibility, if a command string is given
2210 that does not use any of the group matches, this case is
2211 handled identically to the second one (i.e. match against
2212 file name only).
2213 In a custom lisp form, you can access the group matches with
2214 (match-string n link).
2216 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2217 to open [[file:document.pdf::5]] with evince at page 5.
2219 `directory' Matches a directory
2220 `remote' Matches a remote file, accessible through tramp or efs.
2221 Remote files most likely should be visited through Emacs
2222 because external applications cannot handle such paths.
2223 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2224 so all files Emacs knows how to handle. Using this with
2225 command `emacs' will open most files in Emacs. Beware that this
2226 will also open html files inside Emacs, unless you add
2227 (\"html\" . default) to the list as well.
2228 t Default for files not matched by any of the other options.
2229 `system' The system command to open files, like `open' on Windows
2230 and Mac OS X, and mailcap under GNU/Linux. This is the command
2231 that will be selected if you call `C-c C-o' with a double
2232 \\[universal-argument] \\[universal-argument] prefix.
2234 Possible values for the command are:
2235 `emacs' The file will be visited by the current Emacs process.
2236 `default' Use the default application for this file type, which is the
2237 association for t in the list, most likely in the system-specific
2238 part.
2239 This can be used to overrule an unwanted setting in the
2240 system-specific variable.
2241 `system' Use the system command for opening files, like \"open\".
2242 This command is specified by the entry whose car is `system'.
2243 Most likely, the system-specific version of this variable
2244 does define this command, but you can overrule/replace it
2245 here.
2246 string A command to be executed by a shell; %s will be replaced
2247 by the path to the file.
2248 sexp A Lisp form which will be evaluated. The file path will
2249 be available in the Lisp variable `file'.
2250 For more examples, see the system specific constants
2251 `org-file-apps-defaults-macosx'
2252 `org-file-apps-defaults-windowsnt'
2253 `org-file-apps-defaults-gnu'."
2254 :group 'org-link-follow
2255 :type '(repeat
2256 (cons (choice :value ""
2257 (string :tag "Extension")
2258 (const :tag "System command to open files" system)
2259 (const :tag "Default for unrecognized files" t)
2260 (const :tag "Remote file" remote)
2261 (const :tag "Links to a directory" directory)
2262 (const :tag "Any files that have Emacs modes"
2263 auto-mode))
2264 (choice :value ""
2265 (const :tag "Visit with Emacs" emacs)
2266 (const :tag "Use default" default)
2267 (const :tag "Use the system command" system)
2268 (string :tag "Command")
2269 (sexp :tag "Lisp form")))))
2271 (defcustom org-doi-server-url "http://dx.doi.org/"
2272 "The URL of the DOI server."
2273 :type 'string
2274 :version "24.3"
2275 :group 'org-link-follow)
2277 (defgroup org-refile nil
2278 "Options concerning refiling entries in Org-mode."
2279 :tag "Org Refile"
2280 :group 'org)
2282 (defcustom org-directory "~/org"
2283 "Directory with org files.
2284 This is just a default location to look for Org files. There is no need
2285 at all to put your files into this directory. It is only used in the
2286 following situations:
2288 1. When a capture template specifies a target file that is not an
2289 absolute path. The path will then be interpreted relative to
2290 `org-directory'
2291 2. When a capture note is filed away in an interactive way (when exiting the
2292 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2293 with `org-directory' as the default path."
2294 :group 'org-refile
2295 :group 'org-capture
2296 :type 'directory)
2298 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2299 "Default target for storing notes.
2300 Used as a fall back file for org-capture.el, for templates that
2301 do not specify a target file."
2302 :group 'org-refile
2303 :group 'org-capture
2304 :type 'file)
2306 (defcustom org-goto-interface 'outline
2307 "The default interface to be used for `org-goto'.
2308 Allowed values are:
2309 outline The interface shows an outline of the relevant file
2310 and the correct heading is found by moving through
2311 the outline or by searching with incremental search.
2312 outline-path-completion Headlines in the current buffer are offered via
2313 completion. This is the interface also used by
2314 the refile command."
2315 :group 'org-refile
2316 :type '(choice
2317 (const :tag "Outline" outline)
2318 (const :tag "Outline-path-completion" outline-path-completion)))
2320 (defcustom org-goto-max-level 5
2321 "Maximum target level when running `org-goto' with refile interface."
2322 :group 'org-refile
2323 :type 'integer)
2325 (defcustom org-reverse-note-order nil
2326 "Non-nil means store new notes at the beginning of a file or entry.
2327 When nil, new notes will be filed to the end of a file or entry.
2328 This can also be a list with cons cells of regular expressions that
2329 are matched against file names, and values."
2330 :group 'org-capture
2331 :group 'org-refile
2332 :type '(choice
2333 (const :tag "Reverse always" t)
2334 (const :tag "Reverse never" nil)
2335 (repeat :tag "By file name regexp"
2336 (cons regexp boolean))))
2338 (defcustom org-log-refile nil
2339 "Information to record when a task is refiled.
2341 Possible values are:
2343 nil Don't add anything
2344 time Add a time stamp to the task
2345 note Prompt for a note and add it with template `org-log-note-headings'
2347 This option can also be set with on a per-file-basis with
2349 #+STARTUP: nologrefile
2350 #+STARTUP: logrefile
2351 #+STARTUP: lognoterefile
2353 You can have local logging settings for a subtree by setting the LOGGING
2354 property to one or more of these keywords.
2356 When bulk-refiling from the agenda, the value `note' is forbidden and
2357 will temporarily be changed to `time'."
2358 :group 'org-refile
2359 :group 'org-progress
2360 :version "24.1"
2361 :type '(choice
2362 (const :tag "No logging" nil)
2363 (const :tag "Record timestamp" time)
2364 (const :tag "Record timestamp with note." note)))
2366 (defcustom org-refile-targets nil
2367 "Targets for refiling entries with \\[org-refile].
2368 This is a list of cons cells. Each cell contains:
2369 - a specification of the files to be considered, either a list of files,
2370 or a symbol whose function or variable value will be used to retrieve
2371 a file name or a list of file names. If you use `org-agenda-files' for
2372 that, all agenda files will be scanned for targets. Nil means consider
2373 headings in the current buffer.
2374 - A specification of how to find candidate refile targets. This may be
2375 any of:
2376 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2377 This tag has to be present in all target headlines, inheritance will
2378 not be considered.
2379 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2380 todo keyword.
2381 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2382 headlines that are refiling targets.
2383 - a cons cell (:level . N). Any headline of level N is considered a target.
2384 Note that, when `org-odd-levels-only' is set, level corresponds to
2385 order in hierarchy, not to the number of stars.
2386 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2387 Note that, when `org-odd-levels-only' is set, level corresponds to
2388 order in hierarchy, not to the number of stars.
2390 Each element of this list generates a set of possible targets.
2391 The union of these sets is presented (with completion) to
2392 the user by `org-refile'.
2394 You can set the variable `org-refile-target-verify-function' to a function
2395 to verify each headline found by the simple criteria above.
2397 When this variable is nil, all top-level headlines in the current buffer
2398 are used, equivalent to the value `((nil . (:level . 1))'."
2399 :group 'org-refile
2400 :type '(repeat
2401 (cons
2402 (choice :value org-agenda-files
2403 (const :tag "All agenda files" org-agenda-files)
2404 (const :tag "Current buffer" nil)
2405 (function) (variable) (file))
2406 (choice :tag "Identify target headline by"
2407 (cons :tag "Specific tag" (const :value :tag) (string))
2408 (cons :tag "TODO keyword" (const :value :todo) (string))
2409 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2410 (cons :tag "Level number" (const :value :level) (integer))
2411 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2413 (defcustom org-refile-target-verify-function nil
2414 "Function to verify if the headline at point should be a refile target.
2415 The function will be called without arguments, with point at the
2416 beginning of the headline. It should return t and leave point
2417 where it is if the headline is a valid target for refiling.
2419 If the target should not be selected, the function must return nil.
2420 In addition to this, it may move point to a place from where the search
2421 should be continued. For example, the function may decide that the entire
2422 subtree of the current entry should be excluded and move point to the end
2423 of the subtree."
2424 :group 'org-refile
2425 :type '(choice
2426 (const nil)
2427 (function)))
2429 (defcustom org-refile-use-cache nil
2430 "Non-nil means cache refile targets to speed up the process.
2431 \\<org-mode-map>\
2432 The cache for a particular file will be updated automatically when
2433 the buffer has been killed, or when any of the marker used for flagging
2434 refile targets no longer points at a live buffer.
2435 If you have added new entries to a buffer that might themselves be targets,
2436 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2437 if you find that easier, \
2438 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2439 \\[org-refile]'."
2440 :group 'org-refile
2441 :version "24.1"
2442 :type 'boolean)
2444 (defcustom org-refile-use-outline-path nil
2445 "Non-nil means provide refile targets as paths.
2446 So a level 3 headline will be available as level1/level2/level3.
2448 When the value is `file', also include the file name (without directory)
2449 into the path. In this case, you can also stop the completion after
2450 the file name, to get entries inserted as top level in the file.
2452 When `full-file-path', include the full file path."
2453 :group 'org-refile
2454 :type '(choice
2455 (const :tag "Not" nil)
2456 (const :tag "Yes" t)
2457 (const :tag "Start with file name" file)
2458 (const :tag "Start with full file path" full-file-path)))
2460 (defcustom org-outline-path-complete-in-steps t
2461 "Non-nil means complete the outline path in hierarchical steps.
2462 When Org-mode uses the refile interface to select an outline path
2463 \(see variable `org-refile-use-outline-path'), the completion of
2464 the path can be done in a single go, or it can be done in steps down
2465 the headline hierarchy. Going in steps is probably the best if you
2466 do not use a special completion package like `ido' or `icicles'.
2467 However, when using these packages, going in one step can be very
2468 fast, while still showing the whole path to the entry."
2469 :group 'org-refile
2470 :type 'boolean)
2472 (defcustom org-refile-allow-creating-parent-nodes nil
2473 "Non-nil means allow to create new nodes as refile targets.
2474 New nodes are then created by adding \"/new node name\" to the completion
2475 of an existing node. When the value of this variable is `confirm',
2476 new node creation must be confirmed by the user (recommended).
2477 When nil, the completion must match an existing entry.
2479 Note that, if the new heading is not seen by the criteria
2480 listed in `org-refile-targets', multiple instances of the same
2481 heading would be created by trying again to file under the new
2482 heading."
2483 :group 'org-refile
2484 :type '(choice
2485 (const :tag "Never" nil)
2486 (const :tag "Always" t)
2487 (const :tag "Prompt for confirmation" confirm)))
2489 (defcustom org-refile-active-region-within-subtree nil
2490 "Non-nil means also refile active region within a subtree.
2492 By default `org-refile' doesn't allow refiling regions if they
2493 don't contain a set of subtrees, but it might be convenient to
2494 do so sometimes: in that case, the first line of the region is
2495 converted to a headline before refiling."
2496 :group 'org-refile
2497 :version "24.1"
2498 :type 'boolean)
2500 (defgroup org-todo nil
2501 "Options concerning TODO items in Org-mode."
2502 :tag "Org TODO"
2503 :group 'org)
2505 (defgroup org-progress nil
2506 "Options concerning Progress logging in Org-mode."
2507 :tag "Org Progress"
2508 :group 'org-time)
2510 (defvar org-todo-interpretation-widgets
2511 '((:tag "Sequence (cycling hits every state)" sequence)
2512 (:tag "Type (cycling directly to DONE)" type))
2513 "The available interpretation symbols for customizing `org-todo-keywords'.
2514 Interested libraries should add to this list.")
2516 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2517 "List of TODO entry keyword sequences and their interpretation.
2518 \\<org-mode-map>This is a list of sequences.
2520 Each sequence starts with a symbol, either `sequence' or `type',
2521 indicating if the keywords should be interpreted as a sequence of
2522 action steps, or as different types of TODO items. The first
2523 keywords are states requiring action - these states will select a headline
2524 for inclusion into the global TODO list Org-mode produces. If one of
2525 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2526 signify that no further action is necessary. If \"|\" is not found,
2527 the last keyword is treated as the only DONE state of the sequence.
2529 The command \\[org-todo] cycles an entry through these states, and one
2530 additional state where no keyword is present. For details about this
2531 cycling, see the manual.
2533 TODO keywords and interpretation can also be set on a per-file basis with
2534 the special #+SEQ_TODO and #+TYP_TODO lines.
2536 Each keyword can optionally specify a character for fast state selection
2537 \(in combination with the variable `org-use-fast-todo-selection')
2538 and specifiers for state change logging, using the same syntax that
2539 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2540 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2541 indicates to record a time stamp each time this state is selected.
2543 Each keyword may also specify if a timestamp or a note should be
2544 recorded when entering or leaving the state, by adding additional
2545 characters in the parenthesis after the keyword. This looks like this:
2546 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2547 record only the time of the state change. With X and Y being either
2548 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2549 Y when leaving the state if and only if the *target* state does not
2550 define X. You may omit any of the fast-selection key or X or /Y,
2551 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2553 For backward compatibility, this variable may also be just a list
2554 of keywords. In this case the interpretation (sequence or type) will be
2555 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2556 :group 'org-todo
2557 :group 'org-keywords
2558 :type '(choice
2559 (repeat :tag "Old syntax, just keywords"
2560 (string :tag "Keyword"))
2561 (repeat :tag "New syntax"
2562 (cons
2563 (choice
2564 :tag "Interpretation"
2565 ;;Quick and dirty way to see
2566 ;;`org-todo-interpretations'. This takes the
2567 ;;place of item arguments
2568 :convert-widget
2569 (lambda (widget)
2570 (widget-put widget
2571 :args (mapcar
2572 (lambda (x)
2573 (widget-convert
2574 (cons 'const x)))
2575 org-todo-interpretation-widgets))
2576 widget))
2577 (repeat
2578 (string :tag "Keyword"))))))
2580 (defvar-local org-todo-keywords-1 nil
2581 "All TODO and DONE keywords active in a buffer.")
2582 (defvar org-todo-keywords-for-agenda nil)
2583 (defvar org-done-keywords-for-agenda nil)
2584 (defvar org-todo-keyword-alist-for-agenda nil)
2585 (defvar org-tag-alist-for-agenda nil
2586 "Alist of all tags from all agenda files.")
2587 (defvar org-tag-groups-alist-for-agenda nil
2588 "Alist of all groups tags from all current agenda files.")
2589 (defvar-local org-tag-groups-alist nil)
2590 (defvar org-agenda-contributing-files nil)
2591 (defvar-local org-not-done-keywords nil)
2592 (defvar-local org-done-keywords nil)
2593 (defvar-local org-todo-heads nil)
2594 (defvar-local org-todo-sets nil)
2595 (defvar-local org-todo-log-states nil)
2596 (defvar-local org-todo-kwd-alist nil)
2597 (defvar-local org-todo-key-alist nil)
2598 (defvar-local org-todo-key-trigger nil)
2600 (defcustom org-todo-interpretation 'sequence
2601 "Controls how TODO keywords are interpreted.
2602 This variable is in principle obsolete and is only used for
2603 backward compatibility, if the interpretation of todo keywords is
2604 not given already in `org-todo-keywords'. See that variable for
2605 more information."
2606 :group 'org-todo
2607 :group 'org-keywords
2608 :type '(choice (const sequence)
2609 (const type)))
2611 (defcustom org-use-fast-todo-selection t
2612 "\\<org-mode-map>\
2613 Non-nil means use the fast todo selection scheme with \\[org-todo].
2614 This variable describes if and under what circumstances the cycling
2615 mechanism for TODO keywords will be replaced by a single-key, direct
2616 selection scheme.
2618 When nil, fast selection is never used.
2620 When the symbol `prefix', it will be used when `org-todo' is called
2621 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2622 in an Org-mode buffer, and
2623 `\\[universal-argument] t' in an agenda buffer.
2625 When t, fast selection is used by default. In this case, the prefix
2626 argument forces cycling instead.
2628 In all cases, the special interface is only used if access keys have
2629 actually been assigned by the user, i.e. if keywords in the configuration
2630 are followed by a letter in parenthesis, like TODO(t)."
2631 :group 'org-todo
2632 :type '(choice
2633 (const :tag "Never" nil)
2634 (const :tag "By default" t)
2635 (const :tag "Only with C-u C-c C-t" prefix)))
2637 (defcustom org-provide-todo-statistics t
2638 "Non-nil means update todo statistics after insert and toggle.
2639 ALL-HEADLINES means update todo statistics by including headlines
2640 with no TODO keyword as well, counting them as not done.
2641 A list of TODO keywords means the same, but skip keywords that are
2642 not in this list.
2643 When set to a list of two lists, the first list contains keywords
2644 to consider as TODO keywords, the second list contains keywords
2645 to consider as DONE keywords.
2647 When this is set, todo statistics is updated in the parent of the
2648 current entry each time a todo state is changed."
2649 :group 'org-todo
2650 :type '(choice
2651 (const :tag "Yes, only for TODO entries" t)
2652 (const :tag "Yes, including all entries" all-headlines)
2653 (repeat :tag "Yes, for TODOs in this list"
2654 (string :tag "TODO keyword"))
2655 (list :tag "Yes, for TODOs and DONEs in these lists"
2656 (repeat (string :tag "TODO keyword"))
2657 (repeat (string :tag "DONE keyword")))
2658 (other :tag "No TODO statistics" nil)))
2660 (defcustom org-hierarchical-todo-statistics t
2661 "Non-nil means TODO statistics covers just direct children.
2662 When nil, all entries in the subtree are considered.
2663 This has only an effect if `org-provide-todo-statistics' is set.
2664 To set this to nil for only a single subtree, use a COOKIE_DATA
2665 property and include the word \"recursive\" into the value."
2666 :group 'org-todo
2667 :type 'boolean)
2669 (defcustom org-after-todo-state-change-hook nil
2670 "Hook which is run after the state of a TODO item was changed.
2671 The new state (a string with a TODO keyword, or nil) is available in the
2672 Lisp variable `org-state'."
2673 :group 'org-todo
2674 :type 'hook)
2676 (defvar org-blocker-hook nil
2677 "Hook for functions that are allowed to block a state change.
2679 Functions in this hook should not modify the buffer.
2680 Each function gets as its single argument a property list,
2681 see `org-trigger-hook' for more information about this list.
2683 If any of the functions in this hook returns nil, the state change
2684 is blocked.")
2686 (defvar org-trigger-hook nil
2687 "Hook for functions that are triggered by a state change.
2689 Each function gets as its single argument a property list with at
2690 least the following elements:
2692 (:type type-of-change :position pos-at-entry-start
2693 :from old-state :to new-state)
2695 Depending on the type, more properties may be present.
2697 This mechanism is currently implemented for:
2699 TODO state changes
2700 ------------------
2701 :type todo-state-change
2702 :from previous state (keyword as a string), or nil, or a symbol
2703 `todo' or `done', to indicate the general type of state.
2704 :to new state, like in :from")
2706 (defcustom org-enforce-todo-dependencies nil
2707 "Non-nil means undone TODO entries will block switching the parent to DONE.
2708 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2709 be blocked if any prior sibling is not yet done.
2710 Finally, if the parent is blocked because of ordered siblings of its own,
2711 the child will also be blocked."
2712 :set (lambda (var val)
2713 (set var val)
2714 (if val
2715 (add-hook 'org-blocker-hook
2716 'org-block-todo-from-children-or-siblings-or-parent)
2717 (remove-hook 'org-blocker-hook
2718 'org-block-todo-from-children-or-siblings-or-parent)))
2719 :group 'org-todo
2720 :type 'boolean)
2722 (defcustom org-enforce-todo-checkbox-dependencies nil
2723 "Non-nil means unchecked boxes will block switching the parent to DONE.
2724 When this is nil, checkboxes have no influence on switching TODO states.
2725 When non-nil, you first need to check off all check boxes before the TODO
2726 entry can be switched to DONE.
2727 This variable needs to be set before org.el is loaded, and you need to
2728 restart Emacs after a change to make the change effective. The only way
2729 to change is while Emacs is running is through the customize interface."
2730 :set (lambda (var val)
2731 (set var val)
2732 (if val
2733 (add-hook 'org-blocker-hook
2734 'org-block-todo-from-checkboxes)
2735 (remove-hook 'org-blocker-hook
2736 'org-block-todo-from-checkboxes)))
2737 :group 'org-todo
2738 :type 'boolean)
2740 (defcustom org-treat-insert-todo-heading-as-state-change nil
2741 "Non-nil means inserting a TODO heading is treated as state change.
2742 So when the command \\[org-insert-todo-heading] is used, state change
2743 logging will apply if appropriate. When nil, the new TODO item will
2744 be inserted directly, and no logging will take place."
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2749 "Non-nil means switching TODO states with S-cursor counts as state change.
2750 This is the default behavior. However, setting this to nil allows a
2751 convenient way to select a TODO state and bypass any logging associated
2752 with that."
2753 :group 'org-todo
2754 :type 'boolean)
2756 (defcustom org-todo-state-tags-triggers nil
2757 "Tag changes that should be triggered by TODO state changes.
2758 This is a list. Each entry is
2760 (state-change (tag . flag) .......)
2762 State-change can be a string with a state, and empty string to indicate the
2763 state that has no TODO keyword, or it can be one of the symbols `todo'
2764 or `done', meaning any not-done or done state, respectively."
2765 :group 'org-todo
2766 :group 'org-tags
2767 :type '(repeat
2768 (cons (choice :tag "When changing to"
2769 (const :tag "Not-done state" todo)
2770 (const :tag "Done state" done)
2771 (string :tag "State"))
2772 (repeat
2773 (cons :tag "Tag action"
2774 (string :tag "Tag")
2775 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2777 (defcustom org-log-done nil
2778 "Information to record when a task moves to the DONE state.
2780 Possible values are:
2782 nil Don't add anything, just change the keyword
2783 time Add a time stamp to the task
2784 note Prompt for a note and add it with template `org-log-note-headings'
2786 This option can also be set with on a per-file-basis with
2788 #+STARTUP: nologdone
2789 #+STARTUP: logdone
2790 #+STARTUP: lognotedone
2792 You can have local logging settings for a subtree by setting the LOGGING
2793 property to one or more of these keywords."
2794 :group 'org-todo
2795 :group 'org-progress
2796 :type '(choice
2797 (const :tag "No logging" nil)
2798 (const :tag "Record CLOSED timestamp" time)
2799 (const :tag "Record CLOSED timestamp with note." note)))
2801 ;; Normalize old uses of org-log-done.
2802 (cond
2803 ((eq org-log-done t) (setq org-log-done 'time))
2804 ((and (listp org-log-done) (memq 'done org-log-done))
2805 (setq org-log-done 'note)))
2807 (defcustom org-log-reschedule nil
2808 "Information to record when the scheduling date of a tasks is modified.
2810 Possible values are:
2812 nil Don't add anything, just change the date
2813 time Add a time stamp to the task
2814 note Prompt for a note and add it with template `org-log-note-headings'
2816 This option can also be set with on a per-file-basis with
2818 #+STARTUP: nologreschedule
2819 #+STARTUP: logreschedule
2820 #+STARTUP: lognotereschedule"
2821 :group 'org-todo
2822 :group 'org-progress
2823 :type '(choice
2824 (const :tag "No logging" nil)
2825 (const :tag "Record timestamp" time)
2826 (const :tag "Record timestamp with note." note)))
2828 (defcustom org-log-redeadline nil
2829 "Information to record when the deadline date of a tasks is modified.
2831 Possible values are:
2833 nil Don't add anything, just change the date
2834 time Add a time stamp to the task
2835 note Prompt for a note and add it with template `org-log-note-headings'
2837 This option can also be set with on a per-file-basis with
2839 #+STARTUP: nologredeadline
2840 #+STARTUP: logredeadline
2841 #+STARTUP: lognoteredeadline
2843 You can have local logging settings for a subtree by setting the LOGGING
2844 property to one or more of these keywords."
2845 :group 'org-todo
2846 :group 'org-progress
2847 :type '(choice
2848 (const :tag "No logging" nil)
2849 (const :tag "Record timestamp" time)
2850 (const :tag "Record timestamp with note." note)))
2852 (defcustom org-log-note-clock-out nil
2853 "Non-nil means record a note when clocking out of an item.
2854 This can also be configured on a per-file basis by adding one of
2855 the following lines anywhere in the buffer:
2857 #+STARTUP: lognoteclock-out
2858 #+STARTUP: nolognoteclock-out"
2859 :group 'org-todo
2860 :group 'org-progress
2861 :type 'boolean)
2863 (defcustom org-log-done-with-time t
2864 "Non-nil means the CLOSED time stamp will contain date and time.
2865 When nil, only the date will be recorded."
2866 :group 'org-progress
2867 :type 'boolean)
2869 (defcustom org-log-note-headings
2870 '((done . "CLOSING NOTE %t")
2871 (state . "State %-12s from %-12S %t")
2872 (note . "Note taken on %t")
2873 (reschedule . "Rescheduled from %S on %t")
2874 (delschedule . "Not scheduled, was %S on %t")
2875 (redeadline . "New deadline from %S on %t")
2876 (deldeadline . "Removed deadline, was %S on %t")
2877 (refile . "Refiled on %t")
2878 (clock-out . ""))
2879 "Headings for notes added to entries.
2881 The value is an alist, with the car being a symbol indicating the
2882 note context, and the cdr is the heading to be used. The heading
2883 may also be the empty string. The following placeholders can be
2884 used:
2886 %t a time stamp.
2887 %T an active time stamp instead the default inactive one
2888 %d a short-format time stamp.
2889 %D an active short-format time stamp.
2890 %s the new TODO state or time stamp (inactive), in double quotes.
2891 %S the old TODO state or time stamp (inactive), in double quotes.
2892 %u the user name.
2893 %U full user name.
2895 In fact, it is not a good idea to change the `state' entry,
2896 because Agenda Log mode depends on the format of these entries."
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type '(list :greedy t
2900 (cons (const :tag "Heading when closing an item" done) string)
2901 (cons (const :tag
2902 "Heading when changing todo state (todo sequence only)"
2903 state) string)
2904 (cons (const :tag "Heading when just taking a note" note) string)
2905 (cons (const :tag "Heading when rescheduling" reschedule) string)
2906 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2907 (cons (const :tag "Heading when changing deadline" redeadline) string)
2908 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2909 (cons (const :tag "Heading when refiling" refile) string)
2910 (cons (const :tag "Heading when clocking out" clock-out) string)))
2912 (unless (assq 'note org-log-note-headings)
2913 (push '(note . "%t") org-log-note-headings))
2915 (defcustom org-log-into-drawer nil
2916 "Non-nil means insert state change notes and time stamps into a drawer.
2917 When nil, state changes notes will be inserted after the headline and
2918 any scheduling and clock lines, but not inside a drawer.
2920 The value of this variable should be the name of the drawer to use.
2921 LOGBOOK is proposed as the default drawer for this purpose, you can
2922 also set this to a string to define the drawer of your choice.
2924 A value of t is also allowed, representing \"LOGBOOK\".
2926 A value of t or nil can also be set with on a per-file-basis with
2928 #+STARTUP: logdrawer
2929 #+STARTUP: nologdrawer
2931 If this variable is set, `org-log-state-notes-insert-after-drawers'
2932 will be ignored.
2934 You can set the property LOG_INTO_DRAWER to overrule this setting for
2935 a subtree.
2937 Do not check directly this variable in a Lisp program. Call
2938 function `org-log-into-drawer' instead."
2939 :group 'org-todo
2940 :group 'org-progress
2941 :type '(choice
2942 (const :tag "Not into a drawer" nil)
2943 (const :tag "LOGBOOK" t)
2944 (string :tag "Other")))
2946 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2948 (defun org-log-into-drawer ()
2949 "Name of the log drawer, as a string, or nil.
2950 This is the value of `org-log-into-drawer'. However, if the
2951 current entry has or inherits a LOG_INTO_DRAWER property, it will
2952 be used instead of the default value."
2953 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2954 (cond ((equal p "nil") nil)
2955 ((equal p "t") "LOGBOOK")
2956 ((stringp p) p)
2957 (p "LOGBOOK")
2958 ((stringp org-log-into-drawer) org-log-into-drawer)
2959 (org-log-into-drawer "LOGBOOK"))))
2961 (defcustom org-log-state-notes-insert-after-drawers nil
2962 "Non-nil means insert state change notes after any drawers in entry.
2963 Only the drawers that *immediately* follow the headline and the
2964 deadline/scheduled line are skipped.
2965 When nil, insert notes right after the heading and perhaps the line
2966 with deadline/scheduling if present.
2968 This variable will have no effect if `org-log-into-drawer' is
2969 set."
2970 :group 'org-todo
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-states-order-reversed t
2975 "Non-nil means the latest state note will be directly after heading.
2976 When nil, the state change notes will be ordered according to time.
2978 This option can also be set with on a per-file-basis with
2980 #+STARTUP: logstatesreversed
2981 #+STARTUP: nologstatesreversed"
2982 :group 'org-todo
2983 :group 'org-progress
2984 :type 'boolean)
2986 (defcustom org-todo-repeat-to-state nil
2987 "The TODO state to which a repeater should return the repeating task.
2988 By default this is the first task in a TODO sequence, or the previous state
2989 in a TODO_TYP set. But you can specify another task here.
2990 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2991 :group 'org-todo
2992 :version "24.1"
2993 :type '(choice (const :tag "Head of sequence" nil)
2994 (string :tag "Specific state")))
2996 (defcustom org-log-repeat 'time
2997 "Non-nil means record moving through the DONE state when triggering repeat.
2998 An auto-repeating task is immediately switched back to TODO when
2999 marked DONE. If you are not logging state changes (by adding \"@\"
3000 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3001 record a closing note, there will be no record of the task moving
3002 through DONE. This variable forces taking a note anyway.
3004 nil Don't force a record
3005 time Record a time stamp
3006 note Prompt for a note and add it with template `org-log-note-headings'
3008 This option can also be set with on a per-file-basis with
3010 #+STARTUP: nologrepeat
3011 #+STARTUP: logrepeat
3012 #+STARTUP: lognoterepeat
3014 You can have local logging settings for a subtree by setting the LOGGING
3015 property to one or more of these keywords."
3016 :group 'org-todo
3017 :group 'org-progress
3018 :type '(choice
3019 (const :tag "Don't force a record" nil)
3020 (const :tag "Force recording the DONE state" time)
3021 (const :tag "Force recording a note with the DONE state" note)))
3024 (defgroup org-priorities nil
3025 "Priorities in Org-mode."
3026 :tag "Org Priorities"
3027 :group 'org-todo)
3029 (defcustom org-enable-priority-commands t
3030 "Non-nil means priority commands are active.
3031 When nil, these commands will be disabled, so that you never accidentally
3032 set a priority."
3033 :group 'org-priorities
3034 :type 'boolean)
3036 (defcustom org-highest-priority ?A
3037 "The highest priority of TODO items. A character like ?A, ?B etc.
3038 Must have a smaller ASCII number than `org-lowest-priority'."
3039 :group 'org-priorities
3040 :type 'character)
3042 (defcustom org-lowest-priority ?C
3043 "The lowest priority of TODO items. A character like ?A, ?B etc.
3044 Must have a larger ASCII number than `org-highest-priority'."
3045 :group 'org-priorities
3046 :type 'character)
3048 (defcustom org-default-priority ?B
3049 "The default priority of TODO items.
3050 This is the priority an item gets if no explicit priority is given.
3051 When starting to cycle on an empty priority the first step in the cycle
3052 depends on `org-priority-start-cycle-with-default'. The resulting first
3053 step priority must not exceed the range from `org-highest-priority' to
3054 `org-lowest-priority' which means that `org-default-priority' has to be
3055 in this range exclusive or inclusive the range boundaries. Else the
3056 first step refuses to set the default and the second will fall back
3057 to (depending on the command used) the highest or lowest priority."
3058 :group 'org-priorities
3059 :type 'character)
3061 (defcustom org-priority-start-cycle-with-default t
3062 "Non-nil means start with default priority when starting to cycle.
3063 When this is nil, the first step in the cycle will be (depending on the
3064 command used) one higher or lower than the default priority.
3065 See also `org-default-priority'."
3066 :group 'org-priorities
3067 :type 'boolean)
3069 (defcustom org-get-priority-function nil
3070 "Function to extract the priority from a string.
3071 The string is normally the headline. If this is nil Org computes the
3072 priority from the priority cookie like [#A] in the headline. It returns
3073 an integer, increasing by 1000 for each priority level.
3074 The user can set a different function here, which should take a string
3075 as an argument and return the numeric priority."
3076 :group 'org-priorities
3077 :version "24.1"
3078 :type '(choice
3079 (const nil)
3080 (function)))
3082 (defgroup org-time nil
3083 "Options concerning time stamps and deadlines in Org-mode."
3084 :tag "Org Time"
3085 :group 'org)
3087 (defcustom org-time-stamp-rounding-minutes '(0 5)
3088 "Number of minutes to round time stamps to.
3089 \\<org-mode-map>\
3090 These are two values, the first applies when first creating a time stamp.
3091 The second applies when changing it with the commands `S-up' and `S-down'.
3092 When changing the time stamp, this means that it will change in steps
3093 of N minutes, as given by the second value.
3095 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3096 numbers should be factors of 60, so for example 5, 10, 15.
3098 When this is larger than 1, you can still force an exact time stamp by using
3099 a double prefix argument to a time stamp command like \
3100 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3101 and by using a prefix arg to `S-up/down' to specify the exact number
3102 of minutes to shift."
3103 :group 'org-time
3104 :get (lambda (var) ; Make sure both elements are there
3105 (if (integerp (default-value var))
3106 (list (default-value var) 5)
3107 (default-value var)))
3108 :type '(list
3109 (integer :tag "when inserting times")
3110 (integer :tag "when modifying times")))
3112 ;; Normalize old customizations of this variable.
3113 (when (integerp org-time-stamp-rounding-minutes)
3114 (setq org-time-stamp-rounding-minutes
3115 (list org-time-stamp-rounding-minutes
3116 org-time-stamp-rounding-minutes)))
3118 (defcustom org-display-custom-times nil
3119 "Non-nil means overlay custom formats over all time stamps.
3120 The formats are defined through the variable `org-time-stamp-custom-formats'.
3121 To turn this on on a per-file basis, insert anywhere in the file:
3122 #+STARTUP: customtime"
3123 :group 'org-time
3124 :set 'set-default
3125 :type 'sexp)
3126 (make-variable-buffer-local 'org-display-custom-times)
3128 (defcustom org-time-stamp-custom-formats
3129 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3130 "Custom formats for time stamps. See `format-time-string' for the syntax.
3131 These are overlaid over the default ISO format if the variable
3132 `org-display-custom-times' is set. Time like %H:%M should be at the
3133 end of the second format. The custom formats are also honored by export
3134 commands, if custom time display is turned on at the time of export."
3135 :group 'org-time
3136 :type 'sexp)
3138 (defun org-time-stamp-format (&optional long inactive)
3139 "Get the right format for a time string."
3140 (let ((f (if long (cdr org-time-stamp-formats)
3141 (car org-time-stamp-formats))))
3142 (if inactive
3143 (concat "[" (substring f 1 -1) "]")
3144 f)))
3146 (defcustom org-time-clocksum-format
3147 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3148 "The format string used when creating CLOCKSUM lines.
3149 This is also used when Org mode generates a time duration.
3151 The value can be a single format string containing two
3152 %-sequences, which will be filled with the number of hours and
3153 minutes in that order.
3155 Alternatively, the value can be a plist associating any of the
3156 keys :years, :months, :weeks, :days, :hours or :minutes with
3157 format strings. The time duration is formatted using only the
3158 time components that are needed and concatenating the results.
3159 If a time unit in absent, it falls back to the next smallest
3160 unit.
3162 The keys :require-years, :require-months, :require-days,
3163 :require-weeks, :require-hours, :require-minutes are also
3164 meaningful. A non-nil value for these keys indicates that the
3165 corresponding time component should always be included, even if
3166 its value is 0.
3169 For example,
3171 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3172 :require-minutes t)
3174 means durations longer than a day will be expressed in days,
3175 hours and minutes, and durations less than a day will always be
3176 expressed in hours and minutes (even for durations less than an
3177 hour).
3179 The value
3181 (:days \"%dd\" :minutes \"%dm\")
3183 means durations longer than a day will be expressed in days and
3184 minutes, and durations less than a day will be expressed entirely
3185 in minutes (even for durations longer than an hour)."
3186 :group 'org-time
3187 :group 'org-clock
3188 :version "24.4"
3189 :package-version '(Org . "8.0")
3190 :type '(choice (string :tag "Format string")
3191 (set :tag "Plist"
3192 (group :inline t (const :tag "Years" :years)
3193 (string :tag "Format string"))
3194 (group :inline t
3195 (const :tag "Always show years" :require-years)
3196 (const t))
3197 (group :inline t (const :tag "Months" :months)
3198 (string :tag "Format string"))
3199 (group :inline t
3200 (const :tag "Always show months" :require-months)
3201 (const t))
3202 (group :inline t (const :tag "Weeks" :weeks)
3203 (string :tag "Format string"))
3204 (group :inline t
3205 (const :tag "Always show weeks" :require-weeks)
3206 (const t))
3207 (group :inline t (const :tag "Days" :days)
3208 (string :tag "Format string"))
3209 (group :inline t
3210 (const :tag "Always show days" :require-days)
3211 (const t))
3212 (group :inline t (const :tag "Hours" :hours)
3213 (string :tag "Format string"))
3214 (group :inline t
3215 (const :tag "Always show hours" :require-hours)
3216 (const t))
3217 (group :inline t (const :tag "Minutes" :minutes)
3218 (string :tag "Format string"))
3219 (group :inline t
3220 (const :tag "Always show minutes" :require-minutes)
3221 (const t)))))
3223 (defcustom org-time-clocksum-use-fractional nil
3224 "When non-nil, \\[org-clock-display] uses fractional times.
3225 See `org-time-clocksum-format' for more on time clock formats."
3226 :group 'org-time
3227 :group 'org-clock
3228 :version "24.3"
3229 :type 'boolean)
3231 (defcustom org-time-clocksum-use-effort-durations nil
3232 "When non-nil, \\[org-clock-display] uses effort durations.
3233 E.g. by default, one day is considered to be a 8 hours effort,
3234 so a task that has been clocked for 16 hours will be displayed
3235 as during 2 days in the clock display or in the clocktable.
3237 See `org-effort-durations' on how to set effort durations
3238 and `org-time-clocksum-format' for more on time clock formats."
3239 :group 'org-time
3240 :group 'org-clock
3241 :version "24.4"
3242 :package-version '(Org . "8.0")
3243 :type 'boolean)
3245 (defcustom org-time-clocksum-fractional-format "%.2f"
3246 "The format string used when creating CLOCKSUM lines,
3247 or when Org mode generates a time duration, if
3248 `org-time-clocksum-use-fractional' is enabled.
3250 The value can be a single format string containing one
3251 %-sequence, which will be filled with the number of hours as
3252 a float.
3254 Alternatively, the value can be a plist associating any of the
3255 keys :years, :months, :weeks, :days, :hours or :minutes with
3256 a format string. The time duration is formatted using the
3257 largest time unit which gives a non-zero integer part. If all
3258 specified formats have zero integer part, the smallest time unit
3259 is used."
3260 :group 'org-time
3261 :type '(choice (string :tag "Format string")
3262 (set (group :inline t (const :tag "Years" :years)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Months" :months)
3265 (string :tag "Format string"))
3266 (group :inline t (const :tag "Weeks" :weeks)
3267 (string :tag "Format string"))
3268 (group :inline t (const :tag "Days" :days)
3269 (string :tag "Format string"))
3270 (group :inline t (const :tag "Hours" :hours)
3271 (string :tag "Format string"))
3272 (group :inline t (const :tag "Minutes" :minutes)
3273 (string :tag "Format string")))))
3275 (defcustom org-deadline-warning-days 14
3276 "Number of days before expiration during which a deadline becomes active.
3277 This variable governs the display in sparse trees and in the agenda.
3278 When 0 or negative, it means use this number (the absolute value of it)
3279 even if a deadline has a different individual lead time specified.
3281 Custom commands can set this variable in the options section."
3282 :group 'org-time
3283 :group 'org-agenda-daily/weekly
3284 :type 'integer)
3286 (defcustom org-scheduled-delay-days 0
3287 "Number of days before a scheduled item becomes active.
3288 This variable governs the display in sparse trees and in the agenda.
3289 The default value (i.e. 0) means: don't delay scheduled item.
3290 When negative, it means use this number (the absolute value of it)
3291 even if a scheduled item has a different individual delay time
3292 specified.
3294 Custom commands can set this variable in the options section."
3295 :group 'org-time
3296 :group 'org-agenda-daily/weekly
3297 :version "24.4"
3298 :package-version '(Org . "8.0")
3299 :type 'integer)
3301 (defcustom org-read-date-prefer-future t
3302 "Non-nil means assume future for incomplete date input from user.
3303 This affects the following situations:
3304 1. The user gives a month but not a year.
3305 For example, if it is April and you enter \"feb 2\", this will be read
3306 as Feb 2, *next* year. \"May 5\", however, will be this year.
3307 2. The user gives a day, but no month.
3308 For example, if today is the 15th, and you enter \"3\", Org-mode will
3309 read this as the third of *next* month. However, if you enter \"17\",
3310 it will be considered as *this* month.
3312 If you set this variable to the symbol `time', then also the following
3313 will work:
3315 3. If the user gives a time.
3316 If the time is before now, it will be interpreted as tomorrow.
3318 Currently none of this works for ISO week specifications.
3320 When this option is nil, the current day, month and year will always be
3321 used as defaults.
3323 See also `org-agenda-jump-prefer-future'."
3324 :group 'org-time
3325 :type '(choice
3326 (const :tag "Never" nil)
3327 (const :tag "Check month and day" t)
3328 (const :tag "Check month, day, and time" time)))
3330 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3331 "Should the agenda jump command prefer the future for incomplete dates?
3332 The default is to do the same as configured in `org-read-date-prefer-future'.
3333 But you can also set a deviating value here.
3334 This may t or nil, or the symbol `org-read-date-prefer-future'."
3335 :group 'org-agenda
3336 :group 'org-time
3337 :version "24.1"
3338 :type '(choice
3339 (const :tag "Use org-read-date-prefer-future"
3340 org-read-date-prefer-future)
3341 (const :tag "Never" nil)
3342 (const :tag "Always" t)))
3344 (defcustom org-read-date-force-compatible-dates t
3345 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3347 Depending on the system Emacs is running on, certain dates cannot
3348 be represented with the type used internally to represent time.
3349 Dates between 1970-1-1 and 2038-1-1 can always be represented
3350 correctly. Some systems allow for earlier dates, some for later,
3351 some for both. One way to find out it to insert any date into an
3352 Org buffer, putting the cursor on the year and hitting S-up and
3353 S-down to test the range.
3355 When this variable is set to t, the date/time prompt will not let
3356 you specify dates outside the 1970-2037 range, so it is certain that
3357 these dates will work in whatever version of Emacs you are
3358 running, and also that you can move a file from one Emacs implementation
3359 to another. WHenever Org is forcing the year for you, it will display
3360 a message and beep.
3362 When this variable is nil, Org will check if the date is
3363 representable in the specific Emacs implementation you are using.
3364 If not, it will force a year, usually the current year, and beep
3365 to remind you. Currently this setting is not recommended because
3366 the likelihood that you will open your Org files in an Emacs that
3367 has limited date range is not negligible.
3369 A workaround for this problem is to use diary sexp dates for time
3370 stamps outside of this range."
3371 :group 'org-time
3372 :version "24.1"
3373 :type 'boolean)
3375 (defcustom org-read-date-display-live t
3376 "Non-nil means display current interpretation of date prompt live.
3377 This display will be in an overlay, in the minibuffer."
3378 :group 'org-time
3379 :type 'boolean)
3381 (defcustom org-read-date-popup-calendar t
3382 "Non-nil means pop up a calendar when prompting for a date.
3383 In the calendar, the date can be selected with mouse-1. However, the
3384 minibuffer will also be active, and you can simply enter the date as well.
3385 When nil, only the minibuffer will be available."
3386 :group 'org-time
3387 :type 'boolean)
3388 (org-defvaralias 'org-popup-calendar-for-date-prompt
3389 'org-read-date-popup-calendar)
3391 (make-obsolete-variable
3392 'org-read-date-minibuffer-setup-hook
3393 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3394 (defcustom org-read-date-minibuffer-setup-hook nil
3395 "Hook to be used to set up keys for the date/time interface.
3396 Add key definitions to `minibuffer-local-map', which will be a
3397 temporary copy.
3399 WARNING: This option is obsolete, you should use
3400 `org-read-date-minibuffer-local-map' to set up keys."
3401 :group 'org-time
3402 :type 'hook)
3404 (defcustom org-extend-today-until 0
3405 "The hour when your day really ends. Must be an integer.
3406 This has influence for the following applications:
3407 - When switching the agenda to \"today\". It it is still earlier than
3408 the time given here, the day recognized as TODAY is actually yesterday.
3409 - When a date is read from the user and it is still before the time given
3410 here, the current date and time will be assumed to be yesterday, 23:59.
3411 Also, timestamps inserted in capture templates follow this rule.
3413 IMPORTANT: This is a feature whose implementation is and likely will
3414 remain incomplete. Really, it is only here because past midnight seems to
3415 be the favorite working time of John Wiegley :-)"
3416 :group 'org-time
3417 :type 'integer)
3419 (defcustom org-use-effective-time nil
3420 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3421 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3422 \"effective time\" of any timestamps between midnight and 8am will be
3423 23:59 of the previous day."
3424 :group 'org-time
3425 :version "24.1"
3426 :type 'boolean)
3428 (defcustom org-use-last-clock-out-time-as-effective-time nil
3429 "When non-nil, use the last clock out time for `org-todo'.
3430 Note that this option has precedence over the combined use of
3431 `org-use-effective-time' and `org-extend-today-until'."
3432 :group 'org-time
3433 :version "24.4"
3434 :package-version '(Org . "8.0")
3435 :type 'boolean)
3437 (defcustom org-edit-timestamp-down-means-later nil
3438 "Non-nil means S-down will increase the time in a time stamp.
3439 When nil, S-up will increase."
3440 :group 'org-time
3441 :type 'boolean)
3443 (defcustom org-calendar-follow-timestamp-change t
3444 "Non-nil means make the calendar window follow timestamp changes.
3445 When a timestamp is modified and the calendar window is visible, it will be
3446 moved to the new date."
3447 :group 'org-time
3448 :type 'boolean)
3450 (defgroup org-tags nil
3451 "Options concerning tags in Org-mode."
3452 :tag "Org Tags"
3453 :group 'org)
3455 (defcustom org-tag-alist nil
3456 "List of tags allowed in Org-mode files.
3457 When this list is nil, Org-mode will base TAG input on what is already in the
3458 buffer.
3459 The value of this variable is an alist, the car of each entry must be a
3460 keyword as a string, the cdr may be a character that is used to select
3461 that tag through the fast-tag-selection interface.
3462 See the manual for details."
3463 :group 'org-tags
3464 :type '(repeat
3465 (choice
3466 (cons (string :tag "Tag name")
3467 (character :tag "Access char"))
3468 (list :tag "Start radio group"
3469 (const :startgroup)
3470 (option (string :tag "Group description")))
3471 (list :tag "Start tag group, non distinct"
3472 (const :startgrouptag)
3473 (option (string :tag "Group description")))
3474 (list :tag "Group tags delimiter"
3475 (const :grouptags))
3476 (list :tag "End radio group"
3477 (const :endgroup)
3478 (option (string :tag "Group description")))
3479 (list :tag "End tag group, non distinct"
3480 (const :endgrouptag)
3481 (option (string :tag "Group description")))
3482 (const :tag "New line" (:newline)))))
3484 (defcustom org-tag-persistent-alist nil
3485 "List of tags that will always appear in all Org-mode files.
3486 This is in addition to any in buffer settings or customizations
3487 of `org-tag-alist'.
3488 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3489 The value of this variable is an alist, the car of each entry must be a
3490 keyword as a string, the cdr may be a character that is used to select
3491 that tag through the fast-tag-selection interface.
3492 See the manual for details.
3493 To disable these tags on a per-file basis, insert anywhere in the file:
3494 #+STARTUP: noptag"
3495 :group 'org-tags
3496 :type '(repeat
3497 (choice
3498 (cons (string :tag "Tag name")
3499 (character :tag "Access char"))
3500 (const :tag "Start radio group" (:startgroup))
3501 (const :tag "Group tags delimiter" (:grouptags))
3502 (const :tag "End radio group" (:endgroup))
3503 (const :tag "New line" (:newline)))))
3505 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3506 "If non-nil, always offer completion for all tags of all agenda files.
3507 Instead of customizing this variable directly, you might want to
3508 set it locally for capture buffers, because there no list of
3509 tags in that file can be created dynamically (there are none).
3511 (add-hook \\='org-capture-mode-hook
3512 (lambda ()
3513 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3514 :group 'org-tags
3515 :version "24.1"
3516 :type 'boolean)
3518 (defvar org-file-tags nil
3519 "List of tags that can be inherited by all entries in the file.
3520 The tags will be inherited if the variable `org-use-tag-inheritance'
3521 says they should be.
3522 This variable is populated from #+FILETAGS lines.")
3524 (defcustom org-use-fast-tag-selection 'auto
3525 "Non-nil means use fast tag selection scheme.
3526 This is a special interface to select and deselect tags with single keys.
3527 When nil, fast selection is never used.
3528 When the symbol `auto', fast selection is used if and only if selection
3529 characters for tags have been configured, either through the variable
3530 `org-tag-alist' or through a #+TAGS line in the buffer.
3531 When t, fast selection is always used and selection keys are assigned
3532 automatically if necessary."
3533 :group 'org-tags
3534 :type '(choice
3535 (const :tag "Always" t)
3536 (const :tag "Never" nil)
3537 (const :tag "When selection characters are configured" auto)))
3539 (defcustom org-fast-tag-selection-single-key nil
3540 "Non-nil means fast tag selection exits after first change.
3541 When nil, you have to press RET to exit it.
3542 During fast tag selection, you can toggle this flag with `C-c'.
3543 This variable can also have the value `expert'. In this case, the window
3544 displaying the tags menu is not even shown, until you press C-c again."
3545 :group 'org-tags
3546 :type '(choice
3547 (const :tag "No" nil)
3548 (const :tag "Yes" t)
3549 (const :tag "Expert" expert)))
3551 (defvar org-fast-tag-selection-include-todo nil
3552 "Non-nil means fast tags selection interface will also offer TODO states.
3553 This is an undocumented feature, you should not rely on it.")
3555 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3556 "The column to which tags should be indented in a headline.
3557 If this number is positive, it specifies the column. If it is negative,
3558 it means that the tags should be flushright to that column. For example,
3559 -80 works well for a normal 80 character screen.
3560 When 0, place tags directly after headline text, with only one space in
3561 between."
3562 :group 'org-tags
3563 :type 'integer)
3565 (defcustom org-auto-align-tags t
3566 "Non-nil keeps tags aligned when modifying headlines.
3567 Some operations (i.e. demoting) change the length of a headline and
3568 therefore shift the tags around. With this option turned on, after
3569 each such operation the tags are again aligned to `org-tags-column'."
3570 :group 'org-tags
3571 :type 'boolean)
3573 (defcustom org-use-tag-inheritance t
3574 "Non-nil means tags in levels apply also for sublevels.
3575 When nil, only the tags directly given in a specific line apply there.
3576 This may also be a list of tags that should be inherited, or a regexp that
3577 matches tags that should be inherited. Additional control is possible
3578 with the variable `org-tags-exclude-from-inheritance' which gives an
3579 explicit list of tags to be excluded from inheritance, even if the value of
3580 `org-use-tag-inheritance' would select it for inheritance.
3582 If this option is t, a match early-on in a tree can lead to a large
3583 number of matches in the subtree when constructing the agenda or creating
3584 a sparse tree. If you only want to see the first match in a tree during
3585 a search, check out the variable `org-tags-match-list-sublevels'."
3586 :group 'org-tags
3587 :type '(choice
3588 (const :tag "Not" nil)
3589 (const :tag "Always" t)
3590 (repeat :tag "Specific tags" (string :tag "Tag"))
3591 (regexp :tag "Tags matched by regexp")))
3593 (defcustom org-tags-exclude-from-inheritance nil
3594 "List of tags that should never be inherited.
3595 This is a way to exclude a few tags from inheritance. For way to do
3596 the opposite, to actively allow inheritance for selected tags,
3597 see the variable `org-use-tag-inheritance'."
3598 :group 'org-tags
3599 :type '(repeat (string :tag "Tag")))
3601 (defun org-tag-inherit-p (tag)
3602 "Check if TAG is one that should be inherited."
3603 (cond
3604 ((member tag org-tags-exclude-from-inheritance) nil)
3605 ((eq org-use-tag-inheritance t) t)
3606 ((not org-use-tag-inheritance) nil)
3607 ((stringp org-use-tag-inheritance)
3608 (string-match org-use-tag-inheritance tag))
3609 ((listp org-use-tag-inheritance)
3610 (member tag org-use-tag-inheritance))
3611 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3613 (defcustom org-tags-match-list-sublevels t
3614 "Non-nil means list also sublevels of headlines matching a search.
3615 This variable applies to tags/property searches, and also to stuck
3616 projects because this search is based on a tags match as well.
3618 When set to the symbol `indented', sublevels are indented with
3619 leading dots.
3621 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3622 the sublevels of a headline matching a tag search often also match
3623 the same search. Listing all of them can create very long lists.
3624 Setting this variable to nil causes subtrees of a match to be skipped.
3626 This variable is semi-obsolete and probably should always be true. It
3627 is better to limit inheritance to certain tags using the variables
3628 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3629 :group 'org-tags
3630 :type '(choice
3631 (const :tag "No, don't list them" nil)
3632 (const :tag "Yes, do list them" t)
3633 (const :tag "List them, indented with leading dots" indented)))
3635 (defcustom org-tags-sort-function nil
3636 "When set, tags are sorted using this function as a comparator."
3637 :group 'org-tags
3638 :type '(choice
3639 (const :tag "No sorting" nil)
3640 (const :tag "Alphabetical" string<)
3641 (const :tag "Reverse alphabetical" string>)
3642 (function :tag "Custom function" nil)))
3644 (defvar org-tags-history nil
3645 "History of minibuffer reads for tags.")
3646 (defvar org-last-tags-completion-table nil
3647 "The last used completion table for tags.")
3648 (defvar org-after-tags-change-hook nil
3649 "Hook that is run after the tags in a line have changed.")
3651 (defgroup org-properties nil
3652 "Options concerning properties in Org-mode."
3653 :tag "Org Properties"
3654 :group 'org)
3656 (defcustom org-property-format "%-10s %s"
3657 "How property key/value pairs should be formatted by `indent-line'.
3658 When `indent-line' hits a property definition, it will format the line
3659 according to this format, mainly to make sure that the values are
3660 lined-up with respect to each other."
3661 :group 'org-properties
3662 :type 'string)
3664 (defcustom org-properties-postprocess-alist nil
3665 "Alist of properties and functions to adjust inserted values.
3666 Elements of this alist must be of the form
3668 ([string] [function])
3670 where [string] must be a property name and [function] must be a
3671 lambda expression: this lambda expression must take one argument,
3672 the value to adjust, and return the new value as a string.
3674 For example, this element will allow the property \"Remaining\"
3675 to be updated wrt the relation between the \"Effort\" property
3676 and the clock summary:
3678 ((\"Remaining\" (lambda(value)
3679 (let ((clocksum (org-clock-sum-current-item))
3680 (effort (org-duration-string-to-minutes
3681 (org-entry-get (point) \"Effort\"))))
3682 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3683 :group 'org-properties
3684 :version "24.1"
3685 :type '(alist :key-type (string :tag "Property")
3686 :value-type (function :tag "Function")))
3688 (defcustom org-use-property-inheritance nil
3689 "Non-nil means properties apply also for sublevels.
3691 This setting is chiefly used during property searches. Turning it on can
3692 cause significant overhead when doing a search, which is why it is not
3693 on by default.
3695 When nil, only the properties directly given in the current entry count.
3696 When t, every property is inherited. The value may also be a list of
3697 properties that should have inheritance, or a regular expression matching
3698 properties that should be inherited.
3700 However, note that some special properties use inheritance under special
3701 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3702 and the properties ending in \"_ALL\" when they are used as descriptor
3703 for valid values of a property.
3705 Note for programmers:
3706 When querying an entry with `org-entry-get', you can control if inheritance
3707 should be used. By default, `org-entry-get' looks only at the local
3708 properties. You can request inheritance by setting the inherit argument
3709 to t (to force inheritance) or to `selective' (to respect the setting
3710 in this variable)."
3711 :group 'org-properties
3712 :type '(choice
3713 (const :tag "Not" nil)
3714 (const :tag "Always" t)
3715 (repeat :tag "Specific properties" (string :tag "Property"))
3716 (regexp :tag "Properties matched by regexp")))
3718 (defun org-property-inherit-p (property)
3719 "Check if PROPERTY is one that should be inherited."
3720 (cond
3721 ((eq org-use-property-inheritance t) t)
3722 ((not org-use-property-inheritance) nil)
3723 ((stringp org-use-property-inheritance)
3724 (string-match org-use-property-inheritance property))
3725 ((listp org-use-property-inheritance)
3726 (member property org-use-property-inheritance))
3727 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3729 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3730 "The default column format, if no other format has been defined.
3731 This variable can be set on the per-file basis by inserting a line
3733 #+COLUMNS: %25ITEM ....."
3734 :group 'org-properties
3735 :type 'string)
3737 (defcustom org-columns-ellipses ".."
3738 "The ellipses to be used when a field in column view is truncated.
3739 When this is the empty string, as many characters as possible are shown,
3740 but then there will be no visual indication that the field has been truncated.
3741 When this is a string of length N, the last N characters of a truncated
3742 field are replaced by this string. If the column is narrower than the
3743 ellipses string, only part of the ellipses string will be shown."
3744 :group 'org-properties
3745 :type 'string)
3747 (defcustom org-columns-modify-value-for-display-function nil
3748 "Function that modifies values for display in column view.
3749 For example, it can be used to cut out a certain part from a time stamp.
3750 The function must take 2 arguments:
3752 column-title The title of the column (*not* the property name)
3753 value The value that should be modified.
3755 The function should return the value that should be displayed,
3756 or nil if the normal value should be used."
3757 :group 'org-properties
3758 :type '(choice (const nil) (function)))
3760 (defconst org-global-properties-fixed
3761 '(("VISIBILITY_ALL" . "folded children content all")
3762 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3763 "List of property/value pairs that can be inherited by any entry.
3765 These are fixed values, for the preset properties. The user variable
3766 that can be used to add to this list is `org-global-properties'.
3768 The entries in this list are cons cells where the car is a property
3769 name and cdr is a string with the value. If the value represents
3770 multiple items like an \"_ALL\" property, separate the items by
3771 spaces.")
3773 (defcustom org-global-properties nil
3774 "List of property/value pairs that can be inherited by any entry.
3776 This list will be combined with the constant `org-global-properties-fixed'.
3778 The entries in this list are cons cells where the car is a property
3779 name and cdr is a string with the value.
3781 You can set buffer-local values for the same purpose in the variable
3782 `org-file-properties' this by adding lines like
3784 #+PROPERTY: NAME VALUE"
3785 :group 'org-properties
3786 :type '(repeat
3787 (cons (string :tag "Property")
3788 (string :tag "Value"))))
3790 (defvar-local org-file-properties nil
3791 "List of property/value pairs that can be inherited by any entry.
3792 Valid for the current buffer.
3793 This variable is populated from #+PROPERTY lines.")
3795 (defgroup org-agenda nil
3796 "Options concerning agenda views in Org-mode."
3797 :tag "Org Agenda"
3798 :group 'org)
3800 (defvar-local org-category nil
3801 "Variable used by org files to set a category for agenda display.
3802 Such files should use a file variable to set it, for example
3804 # -*- mode: org; org-category: \"ELisp\"
3806 or contain a special line
3808 #+CATEGORY: ELisp
3810 If the file does not specify a category, then file's base name
3811 is used instead.")
3812 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3814 (defcustom org-agenda-files nil
3815 "The files to be used for agenda display.
3816 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3817 \\[org-remove-file]. You can also use customize to edit the list.
3819 If an entry is a directory, all files in that directory that are matched by
3820 `org-agenda-file-regexp' will be part of the file list.
3822 If the value of the variable is not a list but a single file name, then
3823 the list of agenda files is actually stored and maintained in that file, one
3824 agenda file per line. In this file paths can be given relative to
3825 `org-directory'. Tilde expansion and environment variable substitution
3826 are also made."
3827 :group 'org-agenda
3828 :type '(choice
3829 (repeat :tag "List of files and directories" file)
3830 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3832 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3833 "Regular expression to match files for `org-agenda-files'.
3834 If any element in the list in that variable contains a directory instead
3835 of a normal file, all files in that directory that are matched by this
3836 regular expression will be included."
3837 :group 'org-agenda
3838 :type 'regexp)
3840 (defcustom org-agenda-text-search-extra-files nil
3841 "List of extra files to be searched by text search commands.
3842 These files will be searched in addition to the agenda files by the
3843 commands `org-search-view' (`\\[org-agenda] s') \
3844 and `org-occur-in-agenda-files'.
3845 Note that these files will only be searched for text search commands,
3846 not for the other agenda views like todo lists, tag searches or the weekly
3847 agenda. This variable is intended to list notes and possibly archive files
3848 that should also be searched by these two commands.
3849 In fact, if the first element in the list is the symbol `agenda-archives',
3850 then all archive files of all agenda files will be added to the search
3851 scope."
3852 :group 'org-agenda
3853 :type '(set :greedy t
3854 (const :tag "Agenda Archives" agenda-archives)
3855 (repeat :inline t (file))))
3857 (org-defvaralias 'org-agenda-multi-occur-extra-files
3858 'org-agenda-text-search-extra-files)
3860 (defcustom org-agenda-skip-unavailable-files nil
3861 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3862 A nil value means to remove them, after a query, from the list."
3863 :group 'org-agenda
3864 :type 'boolean)
3866 (defcustom org-calendar-to-agenda-key [?c]
3867 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3868 The command `org-calendar-goto-agenda' will be bound to this key. The
3869 default is the character `c' because then `c' can be used to switch back and
3870 forth between agenda and calendar."
3871 :group 'org-agenda
3872 :type 'sexp)
3874 (defcustom org-calendar-insert-diary-entry-key [?i]
3875 "The key to be installed in `calendar-mode-map' for adding diary entries.
3876 This option is irrelevant until `org-agenda-diary-file' has been configured
3877 to point to an Org-mode file. When that is the case, the command
3878 `org-agenda-diary-entry' will be bound to the key given here, by default
3879 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3880 if you want to continue doing this, you need to change this to a different
3881 key."
3882 :group 'org-agenda
3883 :type 'sexp)
3885 (defcustom org-agenda-diary-file 'diary-file
3886 "File to which to add new entries with the `i' key in agenda and calendar.
3887 When this is the symbol `diary-file', the functionality in the Emacs
3888 calendar will be used to add entries to the `diary-file'. But when this
3889 points to a file, `org-agenda-diary-entry' will be used instead."
3890 :group 'org-agenda
3891 :type '(choice
3892 (const :tag "The standard Emacs diary file" diary-file)
3893 (file :tag "Special Org file diary entries")))
3895 (eval-after-load "calendar"
3896 '(progn
3897 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3898 'org-calendar-goto-agenda)
3899 (add-hook 'calendar-mode-hook
3900 (lambda ()
3901 (unless (eq org-agenda-diary-file 'diary-file)
3902 (define-key calendar-mode-map
3903 org-calendar-insert-diary-entry-key
3904 'org-agenda-diary-entry))))))
3906 (defgroup org-latex nil
3907 "Options for embedding LaTeX code into Org-mode."
3908 :tag "Org LaTeX"
3909 :group 'org)
3911 (defcustom org-format-latex-options
3912 '(:foreground default :background default :scale 1.0
3913 :html-foreground "Black" :html-background "Transparent"
3914 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3915 "Options for creating images from LaTeX fragments.
3916 This is a property list with the following properties:
3917 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3918 `default' means use the foreground of the default face.
3919 `auto' means use the foreground from the text face.
3920 :background the background color, or \"Transparent\".
3921 `default' means use the background of the default face.
3922 `auto' means use the background from the text face.
3923 :scale a scaling factor for the size of the images, to get more pixels
3924 :html-foreground, :html-background, :html-scale
3925 the same numbers for HTML export.
3926 :matchers a list indicating which matchers should be used to
3927 find LaTeX fragments. Valid members of this list are:
3928 \"begin\" find environments
3929 \"$1\" find single characters surrounded by $.$
3930 \"$\" find math expressions surrounded by $...$
3931 \"$$\" find math expressions surrounded by $$....$$
3932 \"\\(\" find math expressions surrounded by \\(...\\)
3933 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3934 :group 'org-latex
3935 :type 'plist)
3937 (defcustom org-format-latex-signal-error t
3938 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3939 When nil, just push out a message."
3940 :group 'org-latex
3941 :version "24.1"
3942 :type 'boolean)
3944 (defcustom org-latex-to-mathml-jar-file nil
3945 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3946 Use this to specify additional executable file say a jar file.
3948 When using MathToWeb as the converter, specify the full-path to
3949 your mathtoweb.jar file."
3950 :group 'org-latex
3951 :version "24.1"
3952 :type '(choice
3953 (const :tag "None" nil)
3954 (file :tag "JAR file" :must-match t)))
3956 (defcustom org-latex-to-mathml-convert-command nil
3957 "Command to convert LaTeX fragments to MathML.
3958 Replace format-specifiers in the command as noted below and use
3959 `shell-command' to convert LaTeX to MathML.
3960 %j: Executable file in fully expanded form as specified by
3961 `org-latex-to-mathml-jar-file'.
3962 %I: Input LaTeX file in fully expanded form.
3963 %i: The latex fragment to be converted.
3964 %o: Output MathML file.
3966 This command is used by `org-create-math-formula'.
3968 When using MathToWeb as the converter, set this option to
3969 \"java -jar %j -unicode -force -df %o %I\".
3971 When using LaTeXML set this option to
3972 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3973 :group 'org-latex
3974 :version "24.1"
3975 :type '(choice
3976 (const :tag "None" nil)
3977 (string :tag "\nShell command")))
3979 (defcustom org-latex-create-formula-image-program 'dvipng
3980 "Program to convert LaTeX fragments with.
3982 dvipng Process the LaTeX fragments to dvi file, then convert
3983 dvi files to png files using dvipng.
3984 This will also include processing of non-math environments.
3985 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3986 to convert pdf files to png files"
3987 :group 'org-latex
3988 :version "24.1"
3989 :type '(choice
3990 (const :tag "dvipng" dvipng)
3991 (const :tag "imagemagick" imagemagick)))
3993 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3994 "Path to store latex preview images.
3995 A relative path here creates many directories relative to the
3996 processed org files paths. An absolute path puts all preview
3997 images at the same place."
3998 :group 'org-latex
3999 :version "24.3"
4000 :type 'string)
4002 (defun org-format-latex-mathml-available-p ()
4003 "Return t if `org-latex-to-mathml-convert-command' is usable."
4004 (save-match-data
4005 (when (and (boundp 'org-latex-to-mathml-convert-command)
4006 org-latex-to-mathml-convert-command)
4007 (let ((executable (car (split-string
4008 org-latex-to-mathml-convert-command))))
4009 (when (executable-find executable)
4010 (if (string-match
4011 "%j" org-latex-to-mathml-convert-command)
4012 (file-readable-p org-latex-to-mathml-jar-file)
4013 t))))))
4015 (defcustom org-format-latex-header "\\documentclass{article}
4016 \\usepackage[usenames]{color}
4017 \[PACKAGES]
4018 \[DEFAULT-PACKAGES]
4019 \\pagestyle{empty} % do not remove
4020 % The settings below are copied from fullpage.sty
4021 \\setlength{\\textwidth}{\\paperwidth}
4022 \\addtolength{\\textwidth}{-3cm}
4023 \\setlength{\\oddsidemargin}{1.5cm}
4024 \\addtolength{\\oddsidemargin}{-2.54cm}
4025 \\setlength{\\evensidemargin}{\\oddsidemargin}
4026 \\setlength{\\textheight}{\\paperheight}
4027 \\addtolength{\\textheight}{-\\headheight}
4028 \\addtolength{\\textheight}{-\\headsep}
4029 \\addtolength{\\textheight}{-\\footskip}
4030 \\addtolength{\\textheight}{-3cm}
4031 \\setlength{\\topmargin}{1.5cm}
4032 \\addtolength{\\topmargin}{-2.54cm}"
4033 "The document header used for processing LaTeX fragments.
4034 It is imperative that this header make sure that no page number
4035 appears on the page. The package defined in the variables
4036 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4037 will either replace the placeholder \"[PACKAGES]\" in this
4038 header, or they will be appended."
4039 :group 'org-latex
4040 :type 'string)
4042 (defun org-set-packages-alist (var val)
4043 "Set the packages alist and make sure it has 3 elements per entry."
4044 (set var (mapcar (lambda (x)
4045 (if (and (consp x) (= (length x) 2))
4046 (list (car x) (nth 1 x) t)
4048 val)))
4050 (defun org-get-packages-alist (var)
4051 "Get the packages alist and make sure it has 3 elements per entry."
4052 (mapcar (lambda (x)
4053 (if (and (consp x) (= (length x) 2))
4054 (list (car x) (nth 1 x) t)
4056 (default-value var)))
4058 (defcustom org-latex-default-packages-alist
4059 '(("AUTO" "inputenc" t ("pdflatex"))
4060 ("T1" "fontenc" t ("pdflatex"))
4061 ("" "graphicx" t)
4062 ("" "grffile" t)
4063 ("" "longtable" nil)
4064 ("" "wrapfig" nil)
4065 ("" "rotating" nil)
4066 ("normalem" "ulem" t)
4067 ("" "amsmath" t)
4068 ("" "textcomp" t)
4069 ("" "amssymb" t)
4070 ("" "capt-of" nil)
4071 ("" "hyperref" nil))
4072 "Alist of default packages to be inserted in the header.
4074 Change this only if one of the packages here causes an
4075 incompatibility with another package you are using.
4077 The packages in this list are needed by one part or another of
4078 Org mode to function properly:
4080 - inputenc, fontenc: for basic font and character selection
4081 - graphicx: for including images
4082 - grffile: allow periods and spaces in graphics file names
4083 - longtable: For multipage tables
4084 - wrapfig: for figure placement
4085 - rotating: for sideways figures and tables
4086 - ulem: for underline and strike-through
4087 - amsmath: for subscript and superscript and math environments
4088 - textcomp, amssymb: for various symbols used
4089 for interpreting the entities in `org-entities'. You can skip
4090 some of these packages if you don't use any of their symbols.
4091 - capt-of: for captions outside of floats
4092 - hyperref: for cross references
4094 Therefore you should not modify this variable unless you know
4095 what you are doing. The one reason to change it anyway is that
4096 you might be loading some other package that conflicts with one
4097 of the default packages. Each element is either a cell or
4098 a string.
4100 A cell is of the format
4102 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4104 If SNIPPET-FLAG is non-nil, the package also needs to be included
4105 when compiling LaTeX snippets into images for inclusion into
4106 non-LaTeX output. COMPILERS is a list of compilers that should
4107 include the package, see `org-latex-compiler'. If the document
4108 compiler is not in the list, and the list is non-nil, the package
4109 will not be inserted in the final document.
4111 A string will be inserted as-is in the header of the document."
4112 :group 'org-latex
4113 :group 'org-export-latex
4114 :set 'org-set-packages-alist
4115 :get 'org-get-packages-alist
4116 :version "25.1"
4117 :package-version '(Org . "8.3")
4118 :type '(repeat
4119 (choice
4120 (list :tag "options/package pair"
4121 (string :tag "options")
4122 (string :tag "package")
4123 (boolean :tag "Snippet"))
4124 (string :tag "A line of LaTeX"))))
4126 (defcustom org-latex-packages-alist nil
4127 "Alist of packages to be inserted in every LaTeX header.
4129 These will be inserted after `org-latex-default-packages-alist'.
4130 Each element is either a cell or a string.
4132 A cell is of the format:
4134 (\"options\" \"package\" SNIPPET-FLAG)
4136 SNIPPET-FLAG, when non-nil, indicates that this package is also
4137 needed when turning LaTeX snippets into images for inclusion into
4138 non-LaTeX output.
4140 A string will be inserted as-is in the header of the document.
4142 Make sure that you only list packages here which:
4144 - you want in every file;
4145 - do not conflict with the setup in `org-format-latex-header';
4146 - do not conflict with the default packages in
4147 `org-latex-default-packages-alist'."
4148 :group 'org-latex
4149 :group 'org-export-latex
4150 :set 'org-set-packages-alist
4151 :get 'org-get-packages-alist
4152 :type '(repeat
4153 (choice
4154 (list :tag "options/package pair"
4155 (string :tag "options")
4156 (string :tag "package")
4157 (boolean :tag "Snippet"))
4158 (string :tag "A line of LaTeX"))))
4160 (defgroup org-appearance nil
4161 "Settings for Org-mode appearance."
4162 :tag "Org Appearance"
4163 :group 'org)
4165 (defcustom org-level-color-stars-only nil
4166 "Non-nil means fontify only the stars in each headline.
4167 When nil, the entire headline is fontified.
4168 Changing it requires restart of `font-lock-mode' to become effective
4169 also in regions already fontified."
4170 :group 'org-appearance
4171 :type 'boolean)
4173 (defcustom org-hide-leading-stars nil
4174 "Non-nil means hide the first N-1 stars in a headline.
4175 This works by using the face `org-hide' for these stars. This
4176 face is white for a light background, and black for a dark
4177 background. You may have to customize the face `org-hide' to
4178 make this work.
4179 Changing it requires restart of `font-lock-mode' to become effective
4180 also in regions already fontified.
4181 You may also set this on a per-file basis by adding one of the following
4182 lines to the buffer:
4184 #+STARTUP: hidestars
4185 #+STARTUP: showstars"
4186 :group 'org-appearance
4187 :type 'boolean)
4189 (defcustom org-hidden-keywords nil
4190 "List of symbols corresponding to keywords to be hidden the org buffer.
4191 For example, a value \\='(title) for this list will make the document's title
4192 appear in the buffer without the initial #+TITLE: keyword."
4193 :group 'org-appearance
4194 :version "24.1"
4195 :type '(set (const :tag "#+AUTHOR" author)
4196 (const :tag "#+DATE" date)
4197 (const :tag "#+EMAIL" email)
4198 (const :tag "#+TITLE" title)))
4200 (defcustom org-custom-properties nil
4201 "List of properties (as strings) with a special meaning.
4202 The default use of these custom properties is to let the user
4203 hide them with `org-toggle-custom-properties-visibility'."
4204 :group 'org-properties
4205 :group 'org-appearance
4206 :version "24.3"
4207 :type '(repeat (string :tag "Property Name")))
4209 (defcustom org-fontify-done-headline nil
4210 "Non-nil means change the face of a headline if it is marked DONE.
4211 Normally, only the TODO/DONE keyword indicates the state of a headline.
4212 When this is non-nil, the headline after the keyword is set to the
4213 `org-headline-done' as an additional indication."
4214 :group 'org-appearance
4215 :type 'boolean)
4217 (defcustom org-fontify-emphasized-text t
4218 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4219 Changing this variable requires a restart of Emacs to take effect."
4220 :group 'org-appearance
4221 :type 'boolean)
4223 (defcustom org-fontify-whole-heading-line nil
4224 "Non-nil means fontify the whole line for headings.
4225 This is useful when setting a background color for the
4226 org-level-* faces."
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-highlight-latex-and-related nil
4231 "Non-nil means highlight LaTeX related syntax in the buffer.
4232 When non nil, the value should be a list containing any of the
4233 following symbols:
4234 `latex' Highlight LaTeX snippets and environments.
4235 `script' Highlight subscript and superscript.
4236 `entities' Highlight entities."
4237 :group 'org-appearance
4238 :version "24.4"
4239 :package-version '(Org . "8.0")
4240 :type '(choice
4241 (const :tag "No highlighting" nil)
4242 (set :greedy t :tag "Highlight"
4243 (const :tag "LaTeX snippets and environments" latex)
4244 (const :tag "Subscript and superscript" script)
4245 (const :tag "Entities" entities))))
4247 (defcustom org-hide-emphasis-markers nil
4248 "Non-nil mean font-lock should hide the emphasis marker characters."
4249 :group 'org-appearance
4250 :type 'boolean)
4252 (defcustom org-hide-macro-markers nil
4253 "Non-nil mean font-lock should hide the brackets marking macro calls."
4254 :group 'org-appearance
4255 :type 'boolean)
4257 (defcustom org-pretty-entities nil
4258 "Non-nil means show entities as UTF8 characters.
4259 When nil, the \\name form remains in the buffer."
4260 :group 'org-appearance
4261 :version "24.1"
4262 :type 'boolean)
4264 (defcustom org-pretty-entities-include-sub-superscripts t
4265 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4266 :group 'org-appearance
4267 :version "24.1"
4268 :type 'boolean)
4270 (defvar org-emph-re nil
4271 "Regular expression for matching emphasis.
4272 After a match, the match groups contain these elements:
4273 0 The match of the full regular expression, including the characters
4274 before and after the proper match
4275 1 The character before the proper match, or empty at beginning of line
4276 2 The proper match, including the leading and trailing markers
4277 3 The leading marker like * or /, indicating the type of highlighting
4278 4 The text between the emphasis markers, not including the markers
4279 5 The character after the match, empty at the end of a line")
4280 (defvar org-verbatim-re nil
4281 "Regular expression for matching verbatim text.")
4282 (defvar org-emphasis-regexp-components) ; defined just below
4283 (defvar org-emphasis-alist) ; defined just below
4284 (defun org-set-emph-re (var val)
4285 "Set variable and compute the emphasis regular expression."
4286 (set var val)
4287 (when (and (boundp 'org-emphasis-alist)
4288 (boundp 'org-emphasis-regexp-components)
4289 org-emphasis-alist org-emphasis-regexp-components)
4290 (let* ((e org-emphasis-regexp-components)
4291 (pre (car e))
4292 (post (nth 1 e))
4293 (border (nth 2 e))
4294 (body (nth 3 e))
4295 (nl (nth 4 e))
4296 (body1 (concat body "*?"))
4297 (markers (mapconcat 'car org-emphasis-alist ""))
4298 (vmarkers (mapconcat
4299 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4300 org-emphasis-alist "")))
4301 ;; make sure special characters appear at the right position in the class
4302 (if (string-match "\\^" markers)
4303 (setq markers (concat (replace-match "" t t markers) "^")))
4304 (if (string-match "-" markers)
4305 (setq markers (concat (replace-match "" t t markers) "-")))
4306 (if (string-match "\\^" vmarkers)
4307 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4308 (if (string-match "-" vmarkers)
4309 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4310 (if (> nl 0)
4311 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4312 (int-to-string nl) "\\}")))
4313 ;; Make the regexp
4314 (setq org-emph-re
4315 (concat "\\([" pre "]\\|^\\)"
4316 "\\("
4317 "\\([" markers "]\\)"
4318 "\\("
4319 "[^" border "]\\|"
4320 "[^" border "]"
4321 body1
4322 "[^" border "]"
4323 "\\)"
4324 "\\3\\)"
4325 "\\([" post "]\\|$\\)"))
4326 (setq org-verbatim-re
4327 (concat "\\([" pre "]\\|^\\)"
4328 "\\("
4329 "\\([" vmarkers "]\\)"
4330 "\\("
4331 "[^" border "]\\|"
4332 "[^" border "]"
4333 body1
4334 "[^" border "]"
4335 "\\)"
4336 "\\3\\)"
4337 "\\([" post "]\\|$\\)")))))
4339 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4340 ;; set this option proved cumbersome. See this message/thread:
4341 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4342 (defvar org-emphasis-regexp-components
4343 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4344 "Components used to build the regular expression for emphasis.
4345 This is a list with five entries. Terminology: In an emphasis string
4346 like \" *strong word* \", we call the initial space PREMATCH, the final
4347 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4348 and \"trong wor\" is the body. The different components in this variable
4349 specify what is allowed/forbidden in each part:
4351 pre Chars allowed as prematch. Beginning of line will be allowed too.
4352 post Chars allowed as postmatch. End of line will be allowed too.
4353 border The chars *forbidden* as border characters.
4354 body-regexp A regexp like \".\" to match a body character. Don't use
4355 non-shy groups here, and don't allow newline here.
4356 newline The maximum number of newlines allowed in an emphasis exp.
4358 You need to reload Org or to restart Emacs after customizing this.")
4360 (defcustom org-emphasis-alist
4361 `(("*" bold)
4362 ("/" italic)
4363 ("_" underline)
4364 ("=" org-verbatim verbatim)
4365 ("~" org-code verbatim)
4366 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4367 "Alist of characters and faces to emphasize text.
4368 Text starting and ending with a special character will be emphasized,
4369 for example *bold*, _underlined_ and /italic/. This variable sets the
4370 marker characters and the face to be used by font-lock for highlighting
4371 in Org-mode Emacs buffers.
4373 You need to reload Org or to restart Emacs after customizing this."
4374 :group 'org-appearance
4375 :set 'org-set-emph-re
4376 :version "24.4"
4377 :package-version '(Org . "8.0")
4378 :type '(repeat
4379 (list
4380 (string :tag "Marker character")
4381 (choice
4382 (face :tag "Font-lock-face")
4383 (plist :tag "Face property list"))
4384 (option (const verbatim)))))
4386 (defvar org-protecting-blocks '("src" "example" "export")
4387 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4388 This is needed for font-lock setup.")
4390 ;;; Miscellaneous options
4392 (defgroup org-completion nil
4393 "Completion in Org-mode."
4394 :tag "Org Completion"
4395 :group 'org)
4397 (defcustom org-completion-use-ido nil
4398 "Non-nil means use ido completion wherever possible.
4399 Note that `ido-mode' must be active for this variable to be relevant.
4400 If you decide to turn this variable on, you might well want to turn off
4401 `org-outline-path-complete-in-steps'.
4402 See also `org-completion-use-iswitchb'."
4403 :group 'org-completion
4404 :type 'boolean)
4406 (defcustom org-completion-use-iswitchb nil
4407 "Non-nil means use iswitchb completion wherever possible.
4408 Note that `iswitchb-mode' must be active for this variable to be relevant.
4409 If you decide to turn this variable on, you might well want to turn off
4410 `org-outline-path-complete-in-steps'.
4411 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4412 :group 'org-completion
4413 :type 'boolean)
4415 (defcustom org-completion-fallback-command 'hippie-expand
4416 "The expansion command called by \\[pcomplete] in normal context.
4417 Normal means, no org-mode-specific context."
4418 :group 'org-completion
4419 :type 'function)
4421 ;;; Functions and variables from their packages
4422 ;; Declared here to avoid compiler warnings
4424 ;; XEmacs only
4425 (defvar outline-mode-menu-heading)
4426 (defvar outline-mode-menu-show)
4427 (defvar outline-mode-menu-hide)
4428 (defvar zmacs-regions) ; XEmacs regions
4430 ;; Emacs only
4431 (defvar mark-active)
4433 ;; Various packages
4434 (declare-function calc-eval "calc" (str &optional separator &rest args))
4435 (declare-function calendar-forward-day "cal-move" (arg))
4436 (declare-function calendar-goto-date "cal-move" (date))
4437 (declare-function calendar-goto-today "cal-move" ())
4438 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4439 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4440 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4441 (declare-function cdlatex-tab "ext:cdlatex" ())
4442 (declare-function dired-get-filename
4443 "dired"
4444 (&optional localp no-error-if-not-filep))
4445 (declare-function iswitchb-read-buffer
4446 "iswitchb"
4447 (prompt &optional default require-match start matches-set))
4448 (declare-function org-agenda-change-all-lines
4449 "org-agenda"
4450 (newhead hdmarker &optional fixface just-this))
4451 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4452 "org-agenda"
4453 (&optional end))
4454 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4455 (declare-function org-agenda-format-item
4456 "org-agenda"
4457 (extra txt &optional level category tags dotime noprefix
4458 remove-re habitp))
4459 (declare-function org-agenda-maybe-redo "org-agenda" ())
4460 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4461 (declare-function org-agenda-save-markers-for-cut-and-paste
4462 "org-agenda"
4463 (beg end))
4464 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4465 (declare-function org-agenda-skip "org-agenda" ())
4466 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4467 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4468 (declare-function org-indent-mode "org-indent" (&optional arg))
4469 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4470 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4471 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4472 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4473 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4474 (declare-function parse-time-string "parse-time" (string))
4475 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4476 (declare-function table--at-cell-p
4477 "table"
4478 (position &optional object at-column))
4480 (defvar align-mode-rules-list)
4481 (defvar calc-embedded-close-formula)
4482 (defvar calc-embedded-open-formula)
4483 (defvar calc-embedded-open-mode)
4484 (defvar font-lock-unfontify-region-function)
4485 (defvar iswitchb-temp-buflist)
4486 (defvar org-agenda-tags-todo-honor-ignore-options)
4487 (defvar remember-data-file)
4488 (defvar texmathp-why)
4490 ;;;###autoload
4491 (defun turn-on-orgtbl ()
4492 "Unconditionally turn on `orgtbl-mode'."
4493 (require 'org-table)
4494 (orgtbl-mode 1))
4496 (defun org-at-table-p (&optional table-type)
4497 "Non-nil if the cursor is inside an Org table.
4498 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4499 If `org-enable-table-editor' is nil, return nil unconditionally."
4500 (and
4501 org-enable-table-editor
4502 (save-excursion
4503 (beginning-of-line)
4504 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4505 (or (not (derived-mode-p 'org-mode))
4506 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4507 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4508 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4510 (defun org-at-table.el-p ()
4511 "Non-nil when point is at a table.el table."
4512 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4513 (let ((element (org-element-at-point)))
4514 (and (eq (org-element-type element) 'table)
4515 (eq (org-element-property :type element) 'table.el)))))
4517 (defun org-table-recognize-table.el ()
4518 "If there is a table.el table nearby, recognize it and move into it."
4519 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4520 (beginning-of-line)
4521 (unless (or (looking-at org-table-dataline-regexp)
4522 (not (looking-at org-table1-hline-regexp)))
4523 (forward-line)
4524 (when (looking-at org-table-any-border-regexp)
4525 (forward-line -2)))
4526 (if (re-search-forward "|" (org-table-end t) t)
4527 (progn
4528 (require 'table)
4529 (if (table--at-cell-p (point)) t
4530 (message "recognizing table.el table...")
4531 (table-recognize-table)
4532 (message "recognizing table.el table...done")))
4533 (error "This should not happen"))))
4534 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4535 (make-obsolete 'org-table-recognize-table.el
4536 "please notify the org mailing list if you use this function."
4537 "Org 9.0")
4539 (defun org-at-table-hline-p ()
4540 "Non-nil when point is inside a hline in a table.
4541 Assume point is already in a table. If `org-enable-table-editor'
4542 is nil, return nil unconditionally."
4543 (and org-enable-table-editor
4544 (save-excursion
4545 (beginning-of-line)
4546 (looking-at org-table-hline-regexp))))
4548 (defun org-table-map-tables (function &optional quietly)
4549 "Apply FUNCTION to the start of all tables in the buffer."
4550 (save-excursion
4551 (save-restriction
4552 (widen)
4553 (goto-char (point-min))
4554 (while (re-search-forward org-table-any-line-regexp nil t)
4555 (unless quietly
4556 (message "Mapping tables: %d%%"
4557 (floor (* 100.0 (point)) (buffer-size))))
4558 (beginning-of-line 1)
4559 (when (and (looking-at org-table-line-regexp)
4560 ;; Exclude tables in src/example/verbatim/clocktable blocks
4561 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4562 (save-excursion (funcall function))
4563 (or (looking-at org-table-line-regexp)
4564 (forward-char 1)))
4565 (re-search-forward org-table-any-border-regexp nil 1))))
4566 (unless quietly (message "Mapping tables: done")))
4568 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4569 (declare-function org-clock-update-mode-line "org-clock" ())
4570 (declare-function org-resolve-clocks "org-clock"
4571 (&optional also-non-dangling-p prompt last-valid))
4573 (defun org-at-TBLFM-p (&optional pos)
4574 "Non-nil when point (or POS) is in #+TBLFM line."
4575 (save-excursion
4576 (goto-char (or pos (point)))
4577 (beginning-of-line)
4578 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4579 (eq (org-element-type (org-element-at-point)) 'table))))
4581 (defvar org-clock-start-time)
4582 (defvar org-clock-marker (make-marker)
4583 "Marker recording the last clock-in.")
4584 (defvar org-clock-hd-marker (make-marker)
4585 "Marker recording the last clock-in, but the headline position.")
4586 (defvar org-clock-heading ""
4587 "The heading of the current clock entry.")
4588 (defun org-clock-is-active ()
4589 "Return the buffer where the clock is currently running.
4590 Return nil if no clock is running."
4591 (marker-buffer org-clock-marker))
4593 (defun org-check-running-clock ()
4594 "Check if the current buffer contains the running clock.
4595 If yes, offer to stop it and to save the buffer with the changes."
4596 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4597 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4598 (buffer-name))))
4599 (org-clock-out)
4600 (when (y-or-n-p "Save changed buffer?")
4601 (save-buffer))))
4603 (defun org-clocktable-try-shift (dir n)
4604 "Check if this line starts a clock table, if yes, shift the time block."
4605 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4606 (org-clocktable-shift dir n)))
4608 ;;;###autoload
4609 (defun org-clock-persistence-insinuate ()
4610 "Set up hooks for clock persistence."
4611 (require 'org-clock)
4612 (add-hook 'org-mode-hook 'org-clock-load)
4613 (add-hook 'kill-emacs-hook 'org-clock-save))
4615 (defgroup org-archive nil
4616 "Options concerning archiving in Org-mode."
4617 :tag "Org Archive"
4618 :group 'org-structure)
4620 (defcustom org-archive-location "%s_archive::"
4621 "The location where subtrees should be archived.
4623 The value of this variable is a string, consisting of two parts,
4624 separated by a double-colon. The first part is a filename and
4625 the second part is a headline.
4627 When the filename is omitted, archiving happens in the same file.
4628 %s in the filename will be replaced by the current file
4629 name (without the directory part). Archiving to a different file
4630 is useful to keep archived entries from contributing to the
4631 Org-mode Agenda.
4633 The archived entries will be filed as subtrees of the specified
4634 headline. When the headline is omitted, the subtrees are simply
4635 filed away at the end of the file, as top-level entries. Also in
4636 the heading you can use %s to represent the file name, this can be
4637 useful when using the same archive for a number of different files.
4639 Here are a few examples:
4640 \"%s_archive::\"
4641 If the current file is Projects.org, archive in file
4642 Projects.org_archive, as top-level trees. This is the default.
4644 \"::* Archived Tasks\"
4645 Archive in the current file, under the top-level headline
4646 \"* Archived Tasks\".
4648 \"~/org/archive.org::\"
4649 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4651 \"~/org/archive.org::* From %s\"
4652 Archive in file ~/org/archive.org (absolute path), under headlines
4653 \"From FILENAME\" where file name is the current file name.
4655 \"~/org/datetree.org::datetree/* Finished Tasks\"
4656 The \"datetree/\" string is special, signifying to archive
4657 items to the datetree. Items are placed in either the CLOSED
4658 date of the item, or the current date if there is no CLOSED date.
4659 The heading will be a subentry to the current date. There doesn't
4660 need to be a heading, but there always needs to be a slash after
4661 datetree. For example, to store archived items directly in the
4662 datetree, use \"~/org/datetree.org::datetree/\".
4664 \"basement::** Finished Tasks\"
4665 Archive in file ./basement (relative path), as level 3 trees
4666 below the level 2 heading \"** Finished Tasks\".
4668 You may set this option on a per-file basis by adding to the buffer a
4669 line like
4671 #+ARCHIVE: basement::** Finished Tasks
4673 You may also define it locally for a subtree by setting an ARCHIVE property
4674 in the entry. If such a property is found in an entry, or anywhere up
4675 the hierarchy, it will be used."
4676 :group 'org-archive
4677 :type 'string)
4679 (defcustom org-agenda-skip-archived-trees t
4680 "Non-nil means the agenda will skip any items located in archived trees.
4681 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4682 variable is no longer recommended, you should leave it at the value t.
4683 Instead, use the key `v' to cycle the archives-mode in the agenda."
4684 :group 'org-archive
4685 :group 'org-agenda-skip
4686 :type 'boolean)
4688 (defcustom org-columns-skip-archived-trees t
4689 "Non-nil means ignore archived trees when creating column view."
4690 :group 'org-archive
4691 :group 'org-properties
4692 :type 'boolean)
4694 (defcustom org-cycle-open-archived-trees nil
4695 "Non-nil means `org-cycle' will open archived trees.
4696 An archived tree is a tree marked with the tag ARCHIVE.
4697 When nil, archived trees will stay folded. You can still open them with
4698 normal outline commands like `show-all', but not with the cycling commands."
4699 :group 'org-archive
4700 :group 'org-cycle
4701 :type 'boolean)
4703 (defcustom org-sparse-tree-open-archived-trees nil
4704 "Non-nil means sparse tree construction shows matches in archived trees.
4705 When nil, matches in these trees are highlighted, but the trees are kept in
4706 collapsed state."
4707 :group 'org-archive
4708 :group 'org-sparse-trees
4709 :type 'boolean)
4711 (defcustom org-sparse-tree-default-date-type nil
4712 "The default date type when building a sparse tree.
4713 When this is nil, a date is a scheduled or a deadline timestamp.
4714 Otherwise, these types are allowed:
4716 all: all timestamps
4717 active: only active timestamps (<...>)
4718 inactive: only inactive timestamps ([...])
4719 scheduled: only scheduled timestamps
4720 deadline: only deadline timestamps"
4721 :type '(choice (const :tag "Scheduled or deadline" nil)
4722 (const :tag "All timestamps" all)
4723 (const :tag "Only active timestamps" active)
4724 (const :tag "Only inactive timestamps" inactive)
4725 (const :tag "Only scheduled timestamps" scheduled)
4726 (const :tag "Only deadline timestamps" deadline)
4727 (const :tag "Only closed timestamps" closed))
4728 :version "25.1"
4729 :package-version '(Org . "8.3")
4730 :group 'org-sparse-trees)
4732 (defun org-cycle-hide-archived-subtrees (state)
4733 "Re-hide all archived subtrees after a visibility state change."
4734 (when (and (not org-cycle-open-archived-trees)
4735 (not (memq state '(overview folded))))
4736 (save-excursion
4737 (let* ((globalp (memq state '(contents all)))
4738 (beg (if globalp (point-min) (point)))
4739 (end (if globalp (point-max) (org-end-of-subtree t))))
4740 (org-hide-archived-subtrees beg end)
4741 (goto-char beg)
4742 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4743 (message "%s" (substitute-command-keys
4744 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4746 (defun org-force-cycle-archived ()
4747 "Cycle subtree even if it is archived."
4748 (interactive)
4749 (setq this-command 'org-cycle)
4750 (let ((org-cycle-open-archived-trees t))
4751 (call-interactively 'org-cycle)))
4753 (defun org-hide-archived-subtrees (beg end)
4754 "Re-hide all archived subtrees after a visibility state change."
4755 (org-with-wide-buffer
4756 (let ((case-fold-search nil)
4757 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4758 (goto-char beg)
4759 ;; Include headline point is currently on.
4760 (beginning-of-line)
4761 (while (and (< (point) end) (re-search-forward re end t))
4762 (when (member org-archive-tag (org-get-tags))
4763 (org-flag-subtree t)
4764 (org-end-of-subtree t))))))
4766 (declare-function outline-end-of-heading "outline" ())
4767 (declare-function outline-flag-region "outline" (from to flag))
4768 (defun org-flag-subtree (flag)
4769 (save-excursion
4770 (org-back-to-heading t)
4771 (outline-end-of-heading)
4772 (outline-flag-region (point)
4773 (progn (org-end-of-subtree t) (point))
4774 flag)))
4776 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4778 ;; Declare Column View Code
4780 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4781 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4782 (declare-function org-columns-compute "org-colview" (property))
4784 ;; Declare ID code
4786 (declare-function org-id-store-link "org-id")
4787 (declare-function org-id-locations-load "org-id")
4788 (declare-function org-id-locations-save "org-id")
4789 (defvar org-id-track-globally)
4791 ;;; Variables for pre-computed regular expressions, all buffer local
4793 (defvar-local org-todo-regexp nil
4794 "Matches any of the TODO state keywords.")
4795 (defvar-local org-not-done-regexp nil
4796 "Matches any of the TODO state keywords except the last one.")
4797 (defvar-local org-not-done-heading-regexp nil
4798 "Matches a TODO headline that is not done.")
4799 (defvar-local org-todo-line-regexp nil
4800 "Matches a headline and puts TODO state into group 2 if present.")
4801 (defvar-local org-complex-heading-regexp nil
4802 "Matches a headline and puts everything into groups:
4803 group 1: the stars
4804 group 2: The todo keyword, maybe
4805 group 3: Priority cookie
4806 group 4: True headline
4807 group 5: Tags")
4808 (defvar-local org-complex-heading-regexp-format nil
4809 "Printf format to make regexp to match an exact headline.
4810 This regexp will match the headline of any node which has the
4811 exact headline text that is put into the format, but may have any
4812 TODO state, priority and tags.")
4813 (defvar-local org-todo-line-tags-regexp nil
4814 "Matches a headline and puts TODO state into group 2 if present.
4815 Also put tags into group 4 if tags are present.")
4817 (defconst org-plain-time-of-day-regexp
4818 (concat
4819 "\\(\\<[012]?[0-9]"
4820 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4821 "\\(--?"
4822 "\\(\\<[012]?[0-9]"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4824 "\\)?")
4825 "Regular expression to match a plain time or time range.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4828 0 the full match
4829 1 the first time, range or not
4830 8 the second time, if it is a range.")
4832 (defconst org-plain-time-extension-regexp
4833 (concat
4834 "\\(\\<[012]?[0-9]"
4835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4836 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4837 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4838 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4839 groups carry important information:
4840 0 the full match
4841 7 hours of duration
4842 9 minutes of duration")
4844 (defconst org-stamp-time-of-day-regexp
4845 (concat
4846 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4847 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4848 "\\(--?"
4849 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4850 "Regular expression to match a timestamp time or time range.
4851 After a match, the following groups carry important information:
4852 0 the full match
4853 1 date plus weekday, for back referencing to make sure both times are on the same day
4854 2 the first time, range or not
4855 4 the second time, if it is a range.")
4857 (defconst org-startup-options
4858 '(("fold" org-startup-folded t)
4859 ("overview" org-startup-folded t)
4860 ("nofold" org-startup-folded nil)
4861 ("showall" org-startup-folded nil)
4862 ("showeverything" org-startup-folded showeverything)
4863 ("content" org-startup-folded content)
4864 ("indent" org-startup-indented t)
4865 ("noindent" org-startup-indented nil)
4866 ("hidestars" org-hide-leading-stars t)
4867 ("showstars" org-hide-leading-stars nil)
4868 ("odd" org-odd-levels-only t)
4869 ("oddeven" org-odd-levels-only nil)
4870 ("align" org-startup-align-all-tables t)
4871 ("noalign" org-startup-align-all-tables nil)
4872 ("inlineimages" org-startup-with-inline-images t)
4873 ("noinlineimages" org-startup-with-inline-images nil)
4874 ("latexpreview" org-startup-with-latex-preview t)
4875 ("nolatexpreview" org-startup-with-latex-preview nil)
4876 ("customtime" org-display-custom-times t)
4877 ("logdone" org-log-done time)
4878 ("lognotedone" org-log-done note)
4879 ("nologdone" org-log-done nil)
4880 ("lognoteclock-out" org-log-note-clock-out t)
4881 ("nolognoteclock-out" org-log-note-clock-out nil)
4882 ("logrepeat" org-log-repeat state)
4883 ("lognoterepeat" org-log-repeat note)
4884 ("logdrawer" org-log-into-drawer t)
4885 ("nologdrawer" org-log-into-drawer nil)
4886 ("logstatesreversed" org-log-states-order-reversed t)
4887 ("nologstatesreversed" org-log-states-order-reversed nil)
4888 ("nologrepeat" org-log-repeat nil)
4889 ("logreschedule" org-log-reschedule time)
4890 ("lognotereschedule" org-log-reschedule note)
4891 ("nologreschedule" org-log-reschedule nil)
4892 ("logredeadline" org-log-redeadline time)
4893 ("lognoteredeadline" org-log-redeadline note)
4894 ("nologredeadline" org-log-redeadline nil)
4895 ("logrefile" org-log-refile time)
4896 ("lognoterefile" org-log-refile note)
4897 ("nologrefile" org-log-refile nil)
4898 ("fninline" org-footnote-define-inline t)
4899 ("nofninline" org-footnote-define-inline nil)
4900 ("fnlocal" org-footnote-section nil)
4901 ("fnauto" org-footnote-auto-label t)
4902 ("fnprompt" org-footnote-auto-label nil)
4903 ("fnconfirm" org-footnote-auto-label confirm)
4904 ("fnplain" org-footnote-auto-label plain)
4905 ("fnadjust" org-footnote-auto-adjust t)
4906 ("nofnadjust" org-footnote-auto-adjust nil)
4907 ("constcgs" constants-unit-system cgs)
4908 ("constSI" constants-unit-system SI)
4909 ("noptag" org-tag-persistent-alist nil)
4910 ("hideblocks" org-hide-block-startup t)
4911 ("nohideblocks" org-hide-block-startup nil)
4912 ("beamer" org-startup-with-beamer-mode t)
4913 ("entitiespretty" org-pretty-entities t)
4914 ("entitiesplain" org-pretty-entities nil))
4915 "Variable associated with STARTUP options for org-mode.
4916 Each element is a list of three items: the startup options (as written
4917 in the #+STARTUP line), the corresponding variable, and the value to set
4918 this variable to if the option is found. An optional forth element PUSH
4919 means to push this value onto the list in the variable.")
4921 (defcustom org-group-tags t
4922 "When non-nil (the default), use group tags.
4923 This can be turned on/off through `org-toggle-tags-groups'."
4924 :group 'org-tags
4925 :group 'org-startup
4926 :type 'boolean)
4928 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4930 (defun org-toggle-tags-groups ()
4931 "Toggle support for group tags.
4932 Support for group tags is controlled by the option
4933 `org-group-tags', which is non-nil by default."
4934 (interactive)
4935 (setq org-group-tags (not org-group-tags))
4936 (cond ((and (derived-mode-p 'org-agenda-mode)
4937 org-group-tags)
4938 (org-agenda-redo))
4939 ((derived-mode-p 'org-mode)
4940 (let ((org-inhibit-startup t)) (org-mode))))
4941 (message "Groups tags support has been turned %s"
4942 (if org-group-tags "on" "off")))
4944 (defun org-set-regexps-and-options (&optional tags-only)
4945 "Precompute regular expressions used in the current buffer.
4946 When optional argument TAGS-ONLY is non-nil, only compute tags
4947 related expressions."
4948 (when (derived-mode-p 'org-mode)
4949 (let ((alist (org--setup-collect-keywords
4950 (org-make-options-regexp
4951 (append '("FILETAGS" "TAGS" "SETUPFILE")
4952 (and (not tags-only)
4953 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4954 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4955 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4956 (org--setup-process-tags
4957 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4958 (unless tags-only
4959 ;; File properties.
4960 (setq-local org-file-properties (cdr (assq 'property alist)))
4961 ;; Archive location.
4962 (let ((archive (cdr (assq 'archive alist))))
4963 (when archive (setq-local org-archive-location archive)))
4964 ;; Category.
4965 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4966 (when cat
4967 (setq-local org-category (intern cat))
4968 (setq-local org-file-properties
4969 (org--update-property-plist
4970 "CATEGORY" cat org-file-properties))))
4971 ;; Columns.
4972 (let ((column (cdr (assq 'columns alist))))
4973 (when column (setq-local org-columns-default-format column)))
4974 ;; Constants.
4975 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4976 ;; Link abbreviations.
4977 (let ((links (cdr (assq 'link alist))))
4978 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4979 ;; Priorities.
4980 (let ((priorities (cdr (assq 'priorities alist))))
4981 (when priorities
4982 (setq-local org-highest-priority (nth 0 priorities))
4983 (setq-local org-lowest-priority (nth 1 priorities))
4984 (setq-local org-default-priority (nth 2 priorities))))
4985 ;; Scripts.
4986 (let ((scripts (assq 'scripts alist)))
4987 (when scripts
4988 (setq-local org-use-sub-superscripts (cdr scripts))))
4989 ;; Startup options.
4990 (let ((startup (cdr (assq 'startup alist))))
4991 (dolist (option startup)
4992 (let ((entry (assoc-string option org-startup-options t)))
4993 (when entry
4994 (let ((var (nth 1 entry))
4995 (val (nth 2 entry)))
4996 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4997 (unless (listp (symbol-value var))
4998 (set (make-local-variable var) nil))
4999 (add-to-list var val)))))))
5000 ;; TODO keywords.
5001 (setq-local org-todo-kwd-alist nil)
5002 (setq-local org-todo-key-alist nil)
5003 (setq-local org-todo-key-trigger nil)
5004 (setq-local org-todo-keywords-1 nil)
5005 (setq-local org-done-keywords nil)
5006 (setq-local org-todo-heads nil)
5007 (setq-local org-todo-sets nil)
5008 (setq-local org-todo-log-states nil)
5009 (let ((todo-sequences
5010 (or (nreverse (cdr (assq 'todo alist)))
5011 (let ((d (default-value 'org-todo-keywords)))
5012 (if (not (stringp (car d))) d
5013 ;; XXX: Backward compatibility code.
5014 (list (cons org-todo-interpretation d)))))))
5015 (dolist (sequence todo-sequences)
5016 (let* ((sequence (or (run-hook-with-args-until-success
5017 'org-todo-setup-filter-hook sequence)
5018 sequence))
5019 (sequence-type (car sequence))
5020 (keywords (cdr sequence))
5021 (sep (member "|" keywords))
5022 names alist)
5023 (dolist (k (remove "|" keywords))
5024 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5026 (error "Invalid TODO keyword %s" k))
5027 (let ((name (match-string 1 k))
5028 (key (match-string 2 k))
5029 (log (org-extract-log-state-settings k)))
5030 (push name names)
5031 (push (cons name (and key (string-to-char key))) alist)
5032 (when log (push log org-todo-log-states))))
5033 (let* ((names (nreverse names))
5034 (done (if sep (org-remove-keyword-keys (cdr sep))
5035 (last names)))
5036 (head (car names))
5037 (tail (list sequence-type head (car done) (org-last done))))
5038 (add-to-list 'org-todo-heads head 'append)
5039 (push names org-todo-sets)
5040 (setq org-done-keywords (append org-done-keywords done nil))
5041 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5042 (setq org-todo-key-alist
5043 (append org-todo-key-alist
5044 (and alist
5045 (append '((:startgroup))
5046 (nreverse alist)
5047 '((:endgroup))))))
5048 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5049 (setq org-todo-sets (nreverse org-todo-sets)
5050 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5051 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5052 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5053 ;; Compute the regular expressions and other local variables.
5054 ;; Using `org-outline-regexp-bol' would complicate them much,
5055 ;; because of the fixed white space at the end of that string.
5056 (unless org-done-keywords
5057 (setq org-done-keywords
5058 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5059 (setq org-not-done-keywords
5060 (org-delete-all org-done-keywords
5061 (copy-sequence org-todo-keywords-1))
5062 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5063 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5064 org-not-done-heading-regexp
5065 (format org-heading-keyword-regexp-format org-not-done-regexp)
5066 org-todo-line-regexp
5067 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5068 org-complex-heading-regexp
5069 (concat "^\\(\\*+\\)"
5070 "\\(?: +" org-todo-regexp "\\)?"
5071 "\\(?: +\\(\\[#.\\]\\)\\)?"
5072 "\\(?: +\\(.*?\\)\\)??"
5073 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5074 "[ \t]*$")
5075 org-complex-heading-regexp-format
5076 (concat "^\\(\\*+\\)"
5077 "\\(?: +" org-todo-regexp "\\)?"
5078 "\\(?: +\\(\\[#.\\]\\)\\)?"
5079 "\\(?: +"
5080 ;; Stats cookies can be stuck to body.
5081 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5082 "\\(%s\\)"
5083 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5084 "\\)"
5085 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5086 "[ \t]*$")
5087 org-todo-line-tags-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(.*?\\)\\)??"
5091 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5092 "[ \t]*$"))
5093 (org-compute-latex-and-related-regexp)))))
5095 (defun org--setup-collect-keywords (regexp &optional files alist)
5096 "Return setup keywords values as an alist.
5098 REGEXP matches a subset of setup keywords. FILES is a list of
5099 file names already visited. It is used to avoid circular setup
5100 files. ALIST, when non-nil, is the alist computed so far.
5102 Return value contains the following keys: `archive', `category',
5103 `columns', `constants', `filetags', `link', `priorities',
5104 `property', `scripts', `startup', `tags' and `todo'."
5105 (org-with-wide-buffer
5106 (goto-char (point-min))
5107 (let ((case-fold-search t))
5108 (while (re-search-forward regexp nil t)
5109 (let ((element (org-element-at-point)))
5110 (when (eq (org-element-type element) 'keyword)
5111 (let ((key (org-element-property :key element))
5112 (value (org-element-property :value element)))
5113 (cond
5114 ((equal key "ARCHIVE")
5115 (when (org-string-nw-p value)
5116 (push (cons 'archive value) alist)))
5117 ((equal key "CATEGORY") (push (cons 'category value) alist))
5118 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5119 ((equal key "CONSTANTS")
5120 (let* ((constants (assq 'constants alist))
5121 (store (cdr constants)))
5122 (dolist (pair (org-split-string value))
5123 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5124 pair)
5125 (let* ((name (match-string 1 pair))
5126 (value (match-string 2 pair))
5127 (old (assoc name store)))
5128 (if old (setcdr old value)
5129 (push (cons name value) store)))))
5130 (if constants (setcdr constants store)
5131 (push (cons 'constants store) alist))))
5132 ((equal key "FILETAGS")
5133 (when (org-string-nw-p value)
5134 (let ((old (assq 'filetags alist))
5135 (new (apply #'nconc
5136 (mapcar (lambda (x) (org-split-string x ":"))
5137 (org-split-string value)))))
5138 (if old (setcdr old (append new (cdr old)))
5139 (push (cons 'filetags new) alist)))))
5140 ((equal key "LINK")
5141 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5142 (let ((links (assq 'link alist))
5143 (pair (cons (org-match-string-no-properties 1 value)
5144 (org-match-string-no-properties 2 value))))
5145 (if links (push pair (cdr links))
5146 (push (list 'link pair) alist)))))
5147 ((equal key "OPTIONS")
5148 (when (and (org-string-nw-p value)
5149 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5150 (push (cons 'scripts (read (match-string 1 value))) alist)))
5151 ((equal key "PRIORITIES")
5152 (push (cons 'priorities
5153 (let ((prio (org-split-string value)))
5154 (if (< (length prio) 3) '(?A ?C ?B)
5155 (mapcar #'string-to-char prio))))
5156 alist))
5157 ((equal key "PROPERTY")
5158 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5159 (let* ((property (assq 'property alist))
5160 (value (org--update-property-plist
5161 (org-match-string-no-properties 1 value)
5162 (org-match-string-no-properties 2 value)
5163 (cdr property))))
5164 (if property (setcdr property value)
5165 (push (cons 'property value) alist)))))
5166 ((equal key "STARTUP")
5167 (let ((startup (assq 'startup alist)))
5168 (if startup
5169 (setcdr startup
5170 (append (cdr startup) (org-split-string value)))
5171 (push (cons 'startup (org-split-string value)) alist))))
5172 ((equal key "TAGS")
5173 (let ((tag-cell (assq 'tags alist)))
5174 (if tag-cell
5175 (setcdr tag-cell
5176 (append (cdr tag-cell)
5177 '("\\n")
5178 (org-split-string value)))
5179 (push (cons 'tags (org-split-string value)) alist))))
5180 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5181 (let ((todo (assq 'todo alist))
5182 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5183 (org-split-string value))))
5184 (if todo (push value (cdr todo))
5185 (push (list 'todo value) alist))))
5186 ((equal key "SETUPFILE")
5187 (unless buffer-read-only ; Do not check in Gnus messages.
5188 (let ((f (and (org-string-nw-p value)
5189 (expand-file-name
5190 (org-remove-double-quotes value)))))
5191 (when (and f (file-readable-p f) (not (member f files)))
5192 (with-temp-buffer
5193 (setq default-directory (file-name-directory f))
5194 (insert-file-contents f)
5195 (setq alist
5196 ;; Fake Org mode to benefit from cache
5197 ;; without recurring needlessly.
5198 (let ((major-mode 'org-mode))
5199 (org--setup-collect-keywords
5200 regexp (cons f files) alist)))))))))))))))
5201 alist)
5203 (defun org--setup-process-tags (tags filetags)
5204 "Precompute variables used for tags.
5205 TAGS is a list of tags and tag group symbols, as strings.
5206 FILETAGS is a list of tags, as strings."
5207 ;; Process the file tags.
5208 (setq-local org-file-tags
5209 (mapcar #'org-add-prop-inherited filetags))
5210 ;; Provide default tags if no local tags are found.
5211 (when (and (not tags) org-tag-alist)
5212 (setq tags
5213 (mapcar (lambda (tag)
5214 (case (car tag)
5215 (:startgroup "{")
5216 (:endgroup "}")
5217 (:startgrouptag "[")
5218 (:endgrouptag "]")
5219 (:grouptags ":")
5220 (:newline "\\n")
5221 (otherwise (concat (car tag)
5222 (and (characterp (cdr tag))
5223 (format "(%c)" (cdr tag)))))))
5224 org-tag-alist)))
5225 ;; Process the tags.
5226 (setq-local org-tag-groups-alist nil)
5227 (setq-local org-tag-alist nil)
5228 (let (group-flag)
5229 (while tags
5230 (let ((e (car tags)))
5231 (setq tags (cdr tags))
5232 (cond
5233 ((equal e "{")
5234 (push '(:startgroup) org-tag-alist)
5235 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5236 ((equal e "}")
5237 (push '(:endgroup) org-tag-alist)
5238 (setq group-flag nil))
5239 ((equal e "[")
5240 (push '(:startgrouptag) org-tag-alist)
5241 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5242 ((equal e "]")
5243 (push '(:endgrouptag) org-tag-alist)
5244 (setq group-flag nil))
5245 ((equal e ":")
5246 (push '(:grouptags) org-tag-alist)
5247 (setq group-flag 'append))
5248 ((equal e "\\n") (push '(:newline) org-tag-alist))
5249 ((string-match
5250 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5251 "\\|{.+?}\\)" ; regular expression
5252 "\\(?:(\\(.\\))\\)?\\'")) e)
5253 (let ((tag (match-string 1 e))
5254 (key (and (match-beginning 2)
5255 (string-to-char (match-string 2 e)))))
5256 (cond ((eq group-flag 'append)
5257 (setcar org-tag-groups-alist
5258 (append (car org-tag-groups-alist) (list tag))))
5259 (group-flag (push (list tag) org-tag-groups-alist)))
5260 ;; Push all tags in groups, no matter if they already exist.
5261 (unless (and (not group-flag) (assoc tag org-tag-alist))
5262 (push (cons tag key) org-tag-alist))))))))
5263 (setq org-tag-alist (nreverse org-tag-alist)))
5265 (defun org-file-contents (file &optional noerror)
5266 "Return the contents of FILE, as a string."
5267 (if (and file (file-readable-p file))
5268 (with-temp-buffer
5269 (insert-file-contents file)
5270 (buffer-string))
5271 (funcall (if noerror 'message 'error)
5272 "Cannot read file \"%s\"%s"
5273 file
5274 (let ((from (buffer-file-name (buffer-base-buffer))))
5275 (if from (concat " (referenced in file \"" from "\")") "")))))
5277 (defun org-extract-log-state-settings (x)
5278 "Extract the log state setting from a TODO keyword string.
5279 This will extract info from a string like \"WAIT(w@/!)\"."
5280 (let (kw key log1 log2)
5281 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5282 (setq kw (match-string 1 x)
5283 key (and (match-end 2) (match-string 2 x))
5284 log1 (and (match-end 3) (match-string 3 x))
5285 log2 (and (match-end 4) (match-string 4 x)))
5286 (and (or log1 log2)
5287 (list kw
5288 (and log1 (if (equal log1 "!") 'time 'note))
5289 (and log2 (if (equal log2 "!") 'time 'note)))))))
5291 (defun org-remove-keyword-keys (list)
5292 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (mapcar (lambda (x)
5294 (if (string-match "(.*)$" x)
5295 (substring x 0 (match-beginning 0))
5297 list))
5299 (defun org-assign-fast-keys (alist)
5300 "Assign fast keys to a keyword-key alist.
5301 Respect keys that are already there."
5302 (let (new e (alt ?0))
5303 (while (setq e (pop alist))
5304 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5305 (cdr e)) ;; Key already assigned.
5306 (push e new)
5307 (let ((clist (string-to-list (downcase (car e))))
5308 (used (append new alist)))
5309 (when (= (car clist) ?@)
5310 (pop clist))
5311 (while (and clist (rassoc (car clist) used))
5312 (pop clist))
5313 (unless clist
5314 (while (rassoc alt used)
5315 (incf alt)))
5316 (push (cons (car e) (or (car clist) alt)) new))))
5317 (nreverse new)))
5319 ;;; Some variables used in various places
5321 (defvar org-window-configuration nil
5322 "Used in various places to store a window configuration.")
5323 (defvar org-selected-window nil
5324 "Used in various places to store a window configuration.")
5325 (defvar org-finish-function nil
5326 "Function to be called when `C-c C-c' is used.
5327 This is for getting out of special buffers like capture.")
5330 ;; FIXME: Occasionally check by commenting these, to make sure
5331 ;; no other functions uses these, forgetting to let-bind them.
5332 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5333 (defvar org-last-state)
5334 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5336 ;; Defined somewhere in this file, but used before definition.
5337 (defvar org-entities) ;; defined in org-entities.el
5338 (defvar org-struct-menu)
5339 (defvar org-org-menu)
5340 (defvar org-tbl-menu)
5342 ;;;; Define the Org-mode
5344 ;; We use a before-change function to check if a table might need
5345 ;; an update.
5346 (defvar org-table-may-need-update t
5347 "Indicates that a table might need an update.
5348 This variable is set by `org-before-change-function'.
5349 `org-table-align' sets it back to nil.")
5350 (defun org-before-change-function (beg end)
5351 "Every change indicates that a table might need an update."
5352 (setq org-table-may-need-update t))
5353 (defvar org-mode-map)
5354 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5355 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5357 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5358 (defvar org-table-buffer-is-an nil)
5360 (defvar bidi-paragraph-direction)
5361 (defvar buffer-face-mode-face)
5363 (require 'outline)
5364 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5365 (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"))
5366 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5368 ;; Other stuff we need.
5369 (require 'time-date)
5370 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5371 (require 'easymenu)
5372 (autoload 'easy-menu-add "easymenu")
5373 (require 'overlay)
5375 ;; (require 'org-macs) moved higher up in the file before it is first used
5376 (require 'org-entities)
5377 ;; (require 'org-compat) moved higher up in the file before it is first used
5378 (require 'org-faces)
5379 (require 'org-list)
5380 (require 'org-pcomplete)
5381 (require 'org-src)
5382 (require 'org-footnote)
5383 (require 'org-macro)
5385 ;; babel
5386 (require 'ob)
5388 ;;;###autoload
5389 (define-derived-mode org-mode outline-mode "Org"
5390 "Outline-based notes management and organizer, alias
5391 \"Carsten's outline-mode for keeping track of everything.\"
5393 Org-mode develops organizational tasks around a NOTES file which
5394 contains information about projects as plain text. Org-mode is
5395 implemented on top of outline-mode, which is ideal to keep the content
5396 of large files well structured. It supports ToDo items, deadlines and
5397 time stamps, which magically appear in the diary listing of the Emacs
5398 calendar. Tables are easily created with a built-in table editor.
5399 Plain text URL-like links connect to websites, emails (VM), Usenet
5400 messages (Gnus), BBDB entries, and any files related to the project.
5401 For printing and sharing of notes, an Org-mode file (or a part of it)
5402 can be exported as a structured ASCII or HTML file.
5404 The following commands are available:
5406 \\{org-mode-map}"
5408 ;; Get rid of Outline menus, they are not needed
5409 ;; Need to do this here because define-derived-mode sets up
5410 ;; the keymap so late. Still, it is a waste to call this each time
5411 ;; we switch another buffer into org-mode.
5412 (if (featurep 'xemacs)
5413 (when (boundp 'outline-mode-menu-heading)
5414 ;; Assume this is Greg's port, it uses easymenu
5415 (easy-menu-remove outline-mode-menu-heading)
5416 (easy-menu-remove outline-mode-menu-show)
5417 (easy-menu-remove outline-mode-menu-hide))
5418 (define-key org-mode-map [menu-bar headings] 'undefined)
5419 (define-key org-mode-map [menu-bar hide] 'undefined)
5420 (define-key org-mode-map [menu-bar show] 'undefined))
5422 (org-load-modules-maybe)
5423 (when (featurep 'xemacs)
5424 (easy-menu-add org-org-menu)
5425 (easy-menu-add org-tbl-menu))
5426 (org-install-agenda-files-menu)
5427 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5428 (add-to-invisibility-spec '(org-cwidth))
5429 (add-to-invisibility-spec '(org-hide-block . t))
5430 (when (featurep 'xemacs)
5431 (setq-local line-move-ignore-invisible t))
5432 (setq-local outline-regexp org-outline-regexp)
5433 (setq-local outline-level 'org-outline-level)
5434 (setq bidi-paragraph-direction 'left-to-right)
5435 (when (and org-ellipsis
5436 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5437 (fboundp 'make-glyph-code))
5438 (unless org-display-table
5439 (setq org-display-table (make-display-table)))
5440 (set-display-table-slot
5441 org-display-table 4
5442 (vconcat (mapcar
5443 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5444 org-ellipsis)))
5445 (if (stringp org-ellipsis) org-ellipsis "..."))))
5446 (setq buffer-display-table org-display-table))
5447 (org-set-regexps-and-options)
5448 (org-set-font-lock-defaults)
5449 (when (and org-tag-faces (not org-tags-special-faces-re))
5450 ;; tag faces set outside customize.... force initialization.
5451 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5452 ;; Calc embedded
5453 (setq-local calc-embedded-open-mode "# ")
5454 ;; Modify a few syntax entries
5455 (modify-syntax-entry ?@ "w")
5456 (modify-syntax-entry ?\" "\"")
5457 (modify-syntax-entry ?\\ "_")
5458 (modify-syntax-entry ?~ "_")
5459 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5460 ;; Activate before-change-function
5461 (setq-local org-table-may-need-update t)
5462 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5463 ;; Check for running clock before killing a buffer
5464 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5465 ;; Initialize macros templates.
5466 (org-macro-initialize-templates)
5467 ;; Initialize radio targets.
5468 (org-update-radio-target-regexp)
5469 ;; Indentation.
5470 (setq-local indent-line-function 'org-indent-line)
5471 (setq-local indent-region-function 'org-indent-region)
5472 ;; Filling and auto-filling.
5473 (org-setup-filling)
5474 ;; Comments.
5475 (org-setup-comments-handling)
5476 ;; Initialize cache.
5477 (org-element-cache-reset)
5478 ;; Beginning/end of defun
5479 (setq-local beginning-of-defun-function 'org-backward-element)
5480 (setq-local end-of-defun-function
5481 (lambda ()
5482 (if (not (org-at-heading-p))
5483 (org-forward-element)
5484 (org-forward-element)
5485 (forward-char -1))))
5486 ;; Next error for sparse trees
5487 (setq-local next-error-function 'org-occur-next-match)
5488 ;; Make sure dependence stuff works reliably, even for users who set it
5489 ;; too late :-(
5490 (if org-enforce-todo-dependencies
5491 (add-hook 'org-blocker-hook
5492 'org-block-todo-from-children-or-siblings-or-parent)
5493 (remove-hook 'org-blocker-hook
5494 'org-block-todo-from-children-or-siblings-or-parent))
5495 (if org-enforce-todo-checkbox-dependencies
5496 (add-hook 'org-blocker-hook
5497 'org-block-todo-from-checkboxes)
5498 (remove-hook 'org-blocker-hook
5499 'org-block-todo-from-checkboxes))
5501 ;; Align options lines
5502 (setq-local
5503 align-mode-rules-list
5504 '((org-in-buffer-settings
5505 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5506 (modes . '(org-mode)))))
5508 ;; Imenu
5509 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5511 ;; Make isearch reveal context
5512 (if (or (featurep 'xemacs)
5513 (not (boundp 'outline-isearch-open-invisible-function)))
5514 ;; Emacs 21 and XEmacs make use of the hook
5515 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5516 ;; Emacs 22 deals with this through a special variable
5517 (setq-local outline-isearch-open-invisible-function
5518 (lambda (&rest ignore) (org-show-context 'isearch))))
5520 ;; Setup the pcomplete hooks
5521 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5522 (setq-local pcomplete-command-name-function 'org-command-at-point)
5523 (setq-local pcomplete-default-completion-function 'ignore)
5524 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5525 (setq-local pcomplete-termination-string "")
5526 (setq-local buffer-face-mode-face 'org-default)
5528 ;; If empty file that did not turn on Org mode automatically, make
5529 ;; it to.
5530 (when (and org-insert-mode-line-in-empty-file
5531 (org-called-interactively-p 'any)
5532 (= (point-min) (point-max)))
5533 (insert "# -*- mode: org -*-\n\n"))
5534 (unless org-inhibit-startup
5535 (org-unmodified
5536 (when org-startup-with-beamer-mode (org-beamer-mode))
5537 (when org-startup-align-all-tables
5538 (org-table-map-tables #'org-table-align t))
5539 (when org-startup-with-inline-images (org-display-inline-images))
5540 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5541 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5542 (when org-startup-truncated (setq truncate-lines t))
5543 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5544 (org-refresh-effort-properties)))
5545 ;; Try to set `org-hide' face correctly.
5546 (let ((foreground (org-find-invisible-foreground)))
5547 (when foreground
5548 (set-face-foreground 'org-hide foreground))))
5550 ;; Update `customize-package-emacs-version-alist'
5551 (add-to-list 'customize-package-emacs-version-alist
5552 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5553 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5554 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5556 (defvar org-mode-transpose-word-syntax-table
5557 (let ((st (make-syntax-table text-mode-syntax-table)))
5558 (mapc (lambda(c) (modify-syntax-entry
5559 (string-to-char (car c)) "w p" st))
5560 org-emphasis-alist)
5561 st))
5563 (when (fboundp 'abbrev-table-put)
5564 (abbrev-table-put org-mode-abbrev-table
5565 :parents (list text-mode-abbrev-table)))
5567 (defun org-find-invisible-foreground ()
5568 (let ((candidates (remove
5569 "unspecified-bg"
5570 (nconc
5571 (list (face-background 'default)
5572 (face-background 'org-default))
5573 (mapcar
5574 (lambda (alist)
5575 (when (boundp alist)
5576 (cdr (assoc 'background-color (symbol-value alist)))))
5577 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5578 (list (face-foreground 'org-hide))))))
5579 (car (remove nil candidates))))
5581 (defun org-current-time (&optional rounding-minutes past)
5582 "Current time, possibly rounded to ROUNDING-MINUTES.
5583 When ROUNDING-MINUTES is not an integer, fall back on the car of
5584 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5585 the rounding returns a past time."
5586 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5587 (car org-time-stamp-rounding-minutes)))
5588 (time (decode-time)) res)
5589 (if (< r 1)
5590 (current-time)
5591 (setq res
5592 (apply 'encode-time
5593 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5594 (nthcdr 2 time))))
5595 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5596 (seconds-to-time (- (org-float-time res) (* r 60)))
5597 res))))
5599 (defun org-today ()
5600 "Return today date, considering `org-extend-today-until'."
5601 (time-to-days
5602 (time-subtract (current-time)
5603 (list 0 (* 3600 org-extend-today-until) 0))))
5605 ;;;; Font-Lock stuff, including the activators
5607 (defvar org-mouse-map (make-sparse-keymap))
5608 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5609 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5610 (when org-mouse-1-follows-link
5611 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5612 (when org-tab-follows-link
5613 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5614 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5616 (require 'font-lock)
5618 (defconst org-non-link-chars "]\t\n\r<>")
5619 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5620 "file+sys" "news" "shell" "elisp" "doi" "message"
5621 "help"))
5622 (defvar org-link-types-re nil
5623 "Matches a link that has a url-like prefix like \"http:\"")
5624 (defvar org-link-re-with-space nil
5625 "Matches a link with spaces, optional angular brackets around it.")
5626 (defvar org-link-re-with-space2 nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space3 nil
5629 "Matches a link with spaces, only for internal part in bracket links.")
5630 (defvar org-angle-link-re nil
5631 "Matches link with angular brackets, spaces are allowed.")
5632 (defvar org-plain-link-re nil
5633 "Matches plain link, without spaces.")
5634 (defvar org-bracket-link-regexp nil
5635 "Matches a link in double brackets.")
5636 (defvar org-bracket-link-analytic-regexp nil
5637 "Regular expression used to analyze links.
5638 Here is what the match groups contain after a match:
5639 1: http:
5640 2: http
5641 3: path
5642 4: [desc]
5643 5: desc")
5644 (defvar org-bracket-link-analytic-regexp++ nil
5645 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5646 (defvar org-any-link-re nil
5647 "Regular expression matching any link.")
5649 (defconst org-match-sexp-depth 3
5650 "Number of stacked braces for sub/superscript matching.")
5652 (defun org-create-multibrace-regexp (left right n)
5653 "Create a regular expression which will match a balanced sexp.
5654 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5655 as single character strings.
5656 The regexp returned will match the entire expression including the
5657 delimiters. It will also define a single group which contains the
5658 match except for the outermost delimiters. The maximum depth of
5659 stacked delimiters is N. Escaping delimiters is not possible."
5660 (let* ((nothing (concat "[^" left right "]*?"))
5661 (or "\\|")
5662 (re nothing)
5663 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5664 (while (> n 1)
5665 (setq n (1- n)
5666 re (concat re or next)
5667 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5668 (concat left "\\(" re "\\)" right)))
5670 (defconst org-match-substring-regexp
5671 (concat
5672 "\\(\\S-\\)\\([_^]\\)\\("
5673 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5674 "\\|"
5675 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5678 "The regular expression matching a sub- or superscript.")
5680 (defconst org-match-substring-with-braces-regexp
5681 (concat
5682 "\\(\\S-\\)\\([_^]\\)"
5683 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5684 "The regular expression matching a sub- or superscript, forcing braces.")
5686 (defun org-make-link-regexps ()
5687 "Update the link regular expressions.
5688 This should be called after the variable `org-link-types' has changed."
5689 (let ((types-re (regexp-opt org-link-types t)))
5690 (setq org-link-types-re
5691 (concat "\\`" types-re ":")
5692 org-link-re-with-space
5693 (concat "<?" types-re ":"
5694 "\\([^" org-non-link-chars " ]"
5695 "[^" org-non-link-chars "]*"
5696 "[^" org-non-link-chars " ]\\)>?")
5697 org-link-re-with-space2
5698 (concat "<?" types-re ":"
5699 "\\([^" org-non-link-chars " ]"
5700 "[^\t\n\r]*"
5701 "[^" org-non-link-chars " ]\\)>?")
5702 org-link-re-with-space3
5703 (concat "<?" types-re ":"
5704 "\\([^" org-non-link-chars " ]"
5705 "[^\t\n\r]*\\)")
5706 org-angle-link-re
5707 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5708 types-re)
5709 org-plain-link-re
5710 (concat
5711 "\\<" types-re ":"
5712 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5713 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5714 org-bracket-link-regexp
5715 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5716 org-bracket-link-analytic-regexp
5717 (concat
5718 "\\[\\["
5719 "\\(" types-re ":\\)?"
5720 "\\([^]]+\\)"
5721 "\\]"
5722 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5723 "\\]")
5724 org-bracket-link-analytic-regexp++
5725 (concat
5726 "\\[\\["
5727 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5728 "\\([^]]+\\)"
5729 "\\]"
5730 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5731 "\\]")
5732 org-any-link-re
5733 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5734 org-angle-link-re "\\)\\|\\("
5735 org-plain-link-re "\\)"))))
5737 (org-make-link-regexps)
5739 (defvar org-emph-face nil)
5741 (defun org-do-emphasis-faces (limit)
5742 "Run through the buffer and emphasize strings."
5743 (let (rtn a)
5744 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5745 (let* ((border (char-after (match-beginning 3)))
5746 (bre (regexp-quote (char-to-string border))))
5747 (when (and (not (= border (char-after (match-beginning 4))))
5748 (not (string-match-p (concat bre ".*" bre)
5749 (replace-regexp-in-string
5750 "\n" " "
5751 (substring (match-string 2) 1 -1)))))
5752 (setq rtn t)
5753 (setq a (assoc (match-string 3) org-emphasis-alist))
5754 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5755 'face
5756 (nth 1 a))
5757 (and (nth 2 a)
5758 (org-remove-flyspell-overlays-in
5759 (match-beginning 0) (match-end 0)))
5760 (add-text-properties (match-beginning 2) (match-end 2)
5761 '(font-lock-multiline t org-emphasis t))
5762 (when org-hide-emphasis-markers
5763 (add-text-properties (match-end 4) (match-beginning 5)
5764 '(invisible org-link))
5765 (add-text-properties (match-beginning 3) (match-end 3)
5766 '(invisible org-link)))))
5767 (goto-char (1+ (match-beginning 0))))
5768 rtn))
5770 (defun org-emphasize (&optional char)
5771 "Insert or change an emphasis, i.e. a font like bold or italic.
5772 If there is an active region, change that region to a new emphasis.
5773 If there is no region, just insert the marker characters and position
5774 the cursor between them.
5775 CHAR should be the marker character. If it is a space, it means to
5776 remove the emphasis of the selected region.
5777 If CHAR is not given (for example in an interactive call) it will be
5778 prompted for."
5779 (interactive)
5780 (let ((erc org-emphasis-regexp-components)
5781 (prompt "")
5782 (string "") beg end move c s)
5783 (if (org-region-active-p)
5784 (setq beg (region-beginning) end (region-end)
5785 string (buffer-substring beg end))
5786 (setq move t))
5788 (unless char
5789 (message "Emphasis marker or tag: [%s]"
5790 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5791 (setq char (read-char-exclusive)))
5792 (if (equal char ?\ )
5793 (setq s "" move nil)
5794 (unless (assoc (char-to-string char) org-emphasis-alist)
5795 (user-error "No such emphasis marker: \"%c\"" char))
5796 (setq s (char-to-string char)))
5797 (while (and (> (length string) 1)
5798 (equal (substring string 0 1) (substring string -1))
5799 (assoc (substring string 0 1) org-emphasis-alist))
5800 (setq string (substring string 1 -1)))
5801 (setq string (concat s string s))
5802 (when beg (delete-region beg end))
5803 (unless (or (bolp)
5804 (string-match (concat "[" (nth 0 erc) "\n]")
5805 (char-to-string (char-before (point)))))
5806 (insert " "))
5807 (unless (or (eobp)
5808 (string-match (concat "[" (nth 1 erc) "\n]")
5809 (char-to-string (char-after (point)))))
5810 (insert " ") (backward-char 1))
5811 (insert string)
5812 (and move (backward-char 1))))
5814 (defconst org-nonsticky-props
5815 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5817 (defsubst org-rear-nonsticky-at (pos)
5818 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5820 (defun org-activate-plain-links (limit)
5821 "Add link properties for plain links."
5822 (let (f hl)
5823 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5824 (not (member 'org-tag
5825 (get-text-property (1- (match-beginning 0)) 'face)))
5826 (not (org-in-src-block-p)))
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (setq f (get-text-property (match-beginning 0) 'face))
5829 (setq hl (org-match-string-no-properties 0))
5830 (unless (or (eq f 'org-tag)
5831 (and (listp f) (memq 'org-tag f)))
5832 (add-text-properties (match-beginning 0) (match-end 0)
5833 (list 'mouse-face 'highlight
5834 'face 'org-link
5835 'htmlize-link `(:uri ,hl)
5836 'keymap org-mouse-map))
5837 (org-rear-nonsticky-at (match-end 0)))
5838 t)))
5840 (defun org-activate-code (limit)
5841 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5842 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5843 (remove-text-properties (match-beginning 0) (match-end 0)
5844 '(display t invisible t intangible t))
5847 (defcustom org-src-fontify-natively t
5848 "When non-nil, fontify code in code blocks."
5849 :type 'boolean
5850 :version "24.4"
5851 :package-version '(Org . "8.3")
5852 :group 'org-appearance
5853 :group 'org-babel)
5855 (defcustom org-allow-promoting-top-level-subtree nil
5856 "When non-nil, allow promoting a top level subtree.
5857 The leading star of the top level headline will be replaced
5858 by a #."
5859 :type 'boolean
5860 :version "24.1"
5861 :group 'org-appearance)
5863 (defun org-fontify-meta-lines-and-blocks (limit)
5864 (condition-case nil
5865 (org-fontify-meta-lines-and-blocks-1 limit)
5866 (error (message "org-mode fontification error"))))
5868 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5869 "Fontify #+ lines and blocks."
5870 (let ((case-fold-search t))
5871 (when (re-search-forward
5872 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5873 limit t)
5874 (let ((beg (match-beginning 0))
5875 (block-start (match-end 0))
5876 (block-end nil)
5877 (lang (match-string 7))
5878 (beg1 (line-beginning-position 2))
5879 (dc1 (downcase (match-string 2)))
5880 (dc3 (downcase (match-string 3)))
5881 end end1 quoting block-type ovl)
5882 (cond
5883 ((and (match-end 4) (equal dc3 "+begin"))
5884 ;; Truly a block
5885 (setq block-type (downcase (match-string 5))
5886 quoting (member block-type org-protecting-blocks))
5887 (when (re-search-forward
5888 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5889 nil t) ;; on purpose, we look further than LIMIT
5890 (setq end (min (point-max) (match-end 0))
5891 end1 (min (point-max) (1- (match-beginning 0))))
5892 (setq block-end (match-beginning 0))
5893 (when quoting
5894 (org-remove-flyspell-overlays-in beg1 end1)
5895 (remove-text-properties beg end
5896 '(display t invisible t intangible t)))
5897 (add-text-properties
5898 beg end '(font-lock-fontified t font-lock-multiline t))
5899 (add-text-properties beg beg1 '(face org-meta-line))
5900 (org-remove-flyspell-overlays-in beg beg1)
5901 (add-text-properties ; For end_src
5902 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5903 (org-remove-flyspell-overlays-in end1 end)
5904 (cond
5905 ((and lang (not (string= lang "")) org-src-fontify-natively)
5906 (org-src-font-lock-fontify-block lang block-start block-end)
5907 (add-text-properties beg1 block-end '(src-block t)))
5908 (quoting
5909 (add-text-properties beg1 (min (point-max) (1+ end1))
5910 '(face org-block))) ; end of source block
5911 ((not org-fontify-quote-and-verse-blocks))
5912 ((string= block-type "quote")
5913 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5914 ((string= block-type "verse")
5915 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5916 (add-text-properties beg beg1 '(face org-block-begin-line))
5917 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5918 '(face org-block-end-line))
5920 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5921 (org-remove-flyspell-overlays-in
5922 (match-beginning 0)
5923 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5924 (add-text-properties
5925 beg (match-end 3)
5926 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5927 '(font-lock-fontified t invisible t)
5928 '(font-lock-fontified t face org-document-info-keyword)))
5929 (add-text-properties
5930 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5931 (if (string-equal dc1 "+title:")
5932 '(font-lock-fontified t face org-document-title)
5933 '(font-lock-fontified t face org-document-info))))
5934 ((equal dc1 "+caption:")
5935 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5936 (remove-text-properties (match-beginning 0) (match-end 0)
5937 '(display t invisible t intangible t))
5938 (add-text-properties (match-beginning 1) (match-end 3)
5939 '(font-lock-fontified t face org-meta-line))
5940 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5941 '(font-lock-fontified t face org-block))
5943 ((member dc3 '(" " ""))
5944 (org-remove-flyspell-overlays-in beg (match-end 0))
5945 (add-text-properties
5946 beg (match-end 0)
5947 '(font-lock-fontified t face font-lock-comment-face)))
5948 (t ;; just any other in-buffer setting, but not indented
5949 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5950 (remove-text-properties (match-beginning 0) (match-end 0)
5951 '(display t invisible t intangible t))
5952 (add-text-properties beg (match-end 0)
5953 '(font-lock-fontified t face org-meta-line))
5954 t))))))
5956 (defun org-fontify-drawers (limit)
5957 "Fontify drawers."
5958 (when (re-search-forward org-drawer-regexp limit t)
5959 (add-text-properties
5960 (match-beginning 0) (match-end 0)
5961 '(font-lock-fontified t face org-special-keyword))
5962 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (defun org-fontify-macros (limit)
5966 "Fontify macros."
5967 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5968 (add-text-properties
5969 (match-beginning 0) (match-end 0)
5970 '(font-lock-fontified t face org-macro))
5971 (when org-hide-macro-markers
5972 (add-text-properties (match-end 2) (match-beginning 2)
5973 '(invisible t))
5974 (add-text-properties (match-beginning 1) (match-end 1)
5975 '(invisible t)))
5976 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5979 (defun org-activate-angle-links (limit)
5980 "Add text properties for angle links."
5981 (when (and (re-search-forward org-angle-link-re limit t)
5982 (not (org-in-src-block-p)))
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (add-text-properties (match-beginning 0) (match-end 0)
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map
5987 'font-lock-multiline t))
5988 (org-rear-nonsticky-at (match-end 0))
5991 (defun org-activate-footnote-links (limit)
5992 "Add text properties for footnotes."
5993 (let ((fn (org-footnote-next-reference-or-definition limit)))
5994 (when fn
5995 (let* ((beg (nth 1 fn))
5996 (end (nth 2 fn))
5997 (label (car fn))
5998 (referencep (/= (line-beginning-position) beg)))
5999 (when (and referencep (nth 3 fn))
6000 (save-excursion
6001 (goto-char beg)
6002 (search-forward (or label "fn:"))
6003 (org-remove-flyspell-overlays-in beg (match-end 0))))
6004 (add-text-properties beg end
6005 (list 'mouse-face 'highlight
6006 'keymap org-mouse-map
6007 'help-echo
6008 (if referencep "Footnote reference"
6009 "Footnote definition")
6010 'font-lock-fontified t
6011 'font-lock-multiline t
6012 'face 'org-footnote))))))
6014 (defun org-activate-bracket-links (limit)
6015 "Add text properties for bracketed links."
6016 (when (and (re-search-forward org-bracket-link-regexp limit t)
6017 (not (org-in-src-block-p)))
6018 (let* ((hl (org-match-string-no-properties 1))
6019 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6020 (ip (org-maybe-intangible
6021 (list 'invisible 'org-link
6022 'keymap org-mouse-map 'mouse-face 'highlight
6023 'font-lock-multiline t 'help-echo help
6024 'htmlize-link `(:uri ,hl))))
6025 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6026 'font-lock-multiline t 'help-echo help
6027 'htmlize-link `(:uri ,hl))))
6028 ;; We need to remove the invisible property here. Table narrowing
6029 ;; may have made some of this invisible.
6030 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6031 (remove-text-properties (match-beginning 0) (match-end 0)
6032 '(invisible nil))
6033 (if (match-end 3)
6034 (progn
6035 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6036 (org-rear-nonsticky-at (match-beginning 3))
6037 (add-text-properties (match-beginning 3) (match-end 3) vp)
6038 (org-rear-nonsticky-at (match-end 3))
6039 (add-text-properties (match-end 3) (match-end 0) ip)
6040 (org-rear-nonsticky-at (match-end 0)))
6041 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6042 (org-rear-nonsticky-at (match-beginning 1))
6043 (add-text-properties (match-beginning 1) (match-end 1) vp)
6044 (org-rear-nonsticky-at (match-end 1))
6045 (add-text-properties (match-end 1) (match-end 0) ip)
6046 (org-rear-nonsticky-at (match-end 0)))
6047 t)))
6049 (defun org-activate-dates (limit)
6050 "Add text properties for dates."
6051 (when (and (re-search-forward org-tsr-regexp-both limit t)
6052 (not (equal (char-before (match-beginning 0)) 91)))
6053 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (add-text-properties (match-beginning 0) (match-end 0)
6055 (list 'mouse-face 'highlight
6056 'keymap org-mouse-map))
6057 (org-rear-nonsticky-at (match-end 0))
6058 (when org-display-custom-times
6059 (if (match-end 3)
6060 (org-display-custom-time (match-beginning 3) (match-end 3))
6061 (org-display-custom-time (match-beginning 1) (match-end 1))))
6064 (defvar-local org-target-link-regexp nil
6065 "Regular expression matching radio targets in plain text.")
6067 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6068 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6069 border border border))
6070 "Regular expression matching a link target.")
6072 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6073 "Regular expression matching a radio target.")
6075 (defconst org-any-target-regexp
6076 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6077 "Regular expression matching any target.")
6079 (defun org-activate-target-links (limit)
6080 "Add text properties for target matches."
6081 (when org-target-link-regexp
6082 (let ((case-fold-search t))
6083 (when (re-search-forward org-target-link-regexp limit t)
6084 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6085 (add-text-properties (match-beginning 1) (match-end 1)
6086 (list 'mouse-face 'highlight
6087 'keymap org-mouse-map
6088 'help-echo "Radio target link"
6089 'org-linked-text t))
6090 (org-rear-nonsticky-at (match-end 1))
6091 t))))
6093 (defun org-update-radio-target-regexp ()
6094 "Find all radio targets in this file and update the regular expression.
6095 Also refresh fontification if needed."
6096 (interactive)
6097 (let ((old-regexp org-target-link-regexp)
6098 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6099 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6100 (targets
6101 (org-with-wide-buffer
6102 (goto-char (point-min))
6103 (let (rtn)
6104 (while (re-search-forward org-radio-target-regexp nil t)
6105 ;; Make sure point is really within the object.
6106 (backward-char)
6107 (let ((obj (org-element-context)))
6108 (when (eq (org-element-type obj) 'radio-target)
6109 (add-to-list 'rtn (org-element-property :value obj)))))
6110 rtn))))
6111 (setq org-target-link-regexp
6112 (and targets
6113 (concat before-re
6114 (mapconcat
6115 (lambda (x)
6116 (replace-regexp-in-string
6117 " +" "\\s-+" (regexp-quote x) t t))
6118 targets
6119 "\\|")
6120 after-re)))
6121 (unless (equal old-regexp org-target-link-regexp)
6122 ;; Clean-up cache.
6123 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6124 ((not org-target-link-regexp) old-regexp)
6126 (concat before-re
6127 (mapconcat
6128 (lambda (re)
6129 (substring re (length before-re)
6130 (- (length after-re))))
6131 (list old-regexp org-target-link-regexp)
6132 "\\|")
6133 after-re)))))
6134 (org-with-wide-buffer
6135 (goto-char (point-min))
6136 (while (re-search-forward regexp nil t)
6137 (org-element-cache-refresh (match-beginning 1)))))
6138 ;; Re fontify buffer.
6139 (when (memq 'radio org-highlight-links)
6140 (org-restart-font-lock)))))
6142 (defun org-hide-wide-columns (limit)
6143 (let (s e)
6144 (setq s (text-property-any (point) (or limit (point-max))
6145 'org-cwidth t))
6146 (when s
6147 (setq e (next-single-property-change s 'org-cwidth))
6148 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6149 (goto-char e)
6150 t)))
6152 (defvar org-latex-and-related-regexp nil
6153 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6155 (defun org-compute-latex-and-related-regexp ()
6156 "Compute regular expression for LaTeX, entities and sub/superscript.
6157 Result depends on variable `org-highlight-latex-and-related'."
6158 (setq-local
6159 org-latex-and-related-regexp
6160 (let* ((re-sub
6161 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6162 ((eq org-use-sub-superscripts '{})
6163 (list org-match-substring-with-braces-regexp))
6164 (org-use-sub-superscripts (list org-match-substring-regexp))))
6165 (re-latex
6166 (when (memq 'latex org-highlight-latex-and-related)
6167 (let ((matchers (plist-get org-format-latex-options :matchers)))
6168 (delq nil
6169 (mapcar (lambda (x)
6170 (and (member (car x) matchers) (nth 1 x)))
6171 org-latex-regexps)))))
6172 (re-entities
6173 (when (memq 'entities org-highlight-latex-and-related)
6174 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6175 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6177 (defun org-do-latex-and-related (limit)
6178 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6179 LIMIT bounds the search for syntax to highlight. Stop at first
6180 highlighted object, if any. Return t if some highlighting was
6181 done, nil otherwise."
6182 (when (org-string-nw-p org-latex-and-related-regexp)
6183 (catch 'found
6184 (while (re-search-forward org-latex-and-related-regexp limit t)
6185 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6186 'face))
6187 '(org-code org-verbatim underline))
6188 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6189 '(?_ ?^))
6191 0)))
6192 (font-lock-prepend-text-property
6193 (+ offset (match-beginning 0)) (match-end 0)
6194 'face 'org-latex-and-related)
6195 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6196 '(font-lock-multiline t)))
6197 (throw 'found t)))
6198 nil)))
6200 (defun org-restart-font-lock ()
6201 "Restart `font-lock-mode', to force refontification."
6202 (when (and (boundp 'font-lock-mode) font-lock-mode)
6203 (font-lock-mode -1)
6204 (font-lock-mode 1)))
6206 (defun org-activate-tags (limit)
6207 (when (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6208 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6209 (add-text-properties (match-beginning 1) (match-end 1)
6210 (list 'mouse-face 'highlight
6211 'keymap org-mouse-map))
6212 (org-rear-nonsticky-at (match-end 1))
6215 (defun org-outline-level ()
6216 "Compute the outline level of the heading at point.
6218 If this is called at a normal headline, the level is the number
6219 of stars. Use `org-reduced-level' to remove the effect of
6220 `org-odd-levels'. Unlike to `org-current-level', this function
6221 takes into consideration inlinetasks."
6222 (org-with-wide-buffer
6223 (end-of-line)
6224 (if (re-search-backward org-outline-regexp-bol nil t)
6225 (1- (- (match-end 0) (match-beginning 0)))
6226 0)))
6228 (defvar org-font-lock-keywords nil)
6230 (defsubst org-re-property (property &optional literal allow-null value)
6231 "Return a regexp matching a PROPERTY line.
6233 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6234 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6235 non-nil, match properties even without a value.
6237 Match group 3 is set to the value when it exists. If there is no
6238 value and ALLOW-NULL is non-nil, it is set to the empty string.
6240 With optional argument VALUE, match only property lines with
6241 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6242 unless LITERAL is non-nil."
6243 (concat
6244 "^\\(?4:[ \t]*\\)"
6245 (format "\\(?1::\\(?2:%s\\):\\)"
6246 (if literal property (regexp-quote property)))
6247 (cond (value
6248 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6249 (if literal value (regexp-quote value))))
6250 (allow-null
6251 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6253 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6255 (defconst org-property-re
6256 (org-re-property "\\S-+" 'literal t)
6257 "Regular expression matching a property line.
6258 There are four matching groups:
6259 1: :PROPKEY: including the leading and trailing colon,
6260 2: PROPKEY without the leading and trailing colon,
6261 3: PROPVAL without leading or trailing spaces,
6262 4: the indentation of the current line,
6263 5: trailing whitespace.")
6265 (defvar org-font-lock-hook nil
6266 "Functions to be called for special font lock stuff.")
6268 (defvar org-font-lock-set-keywords-hook nil
6269 "Functions that can manipulate `org-font-lock-extra-keywords'.
6270 This is called after `org-font-lock-extra-keywords' is defined, but before
6271 it is installed to be used by font lock. This can be useful if something
6272 needs to be inserted at a specific position in the font-lock sequence.")
6274 (defun org-font-lock-hook (limit)
6275 "Run `org-font-lock-hook' within LIMIT."
6276 (run-hook-with-args 'org-font-lock-hook limit))
6278 (defun org-set-font-lock-defaults ()
6279 "Set font lock defaults for the current buffer."
6280 (let* ((em org-fontify-emphasized-text)
6281 (lk org-highlight-links)
6282 (org-font-lock-extra-keywords
6283 (list
6284 ;; Call the hook
6285 '(org-font-lock-hook)
6286 ;; Headlines
6287 `(,(if org-fontify-whole-heading-line
6288 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6289 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6290 (1 (org-get-level-face 1))
6291 (2 (org-get-level-face 2))
6292 (3 (org-get-level-face 3)))
6293 ;; Table lines
6294 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6295 (1 'org-table t))
6296 ;; Table internals
6297 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6298 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6299 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6300 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6301 ;; Drawers
6302 '(org-fontify-drawers)
6303 ;; Properties
6304 (list org-property-re
6305 '(1 'org-special-keyword t)
6306 '(3 'org-property-value t))
6307 ;; Links
6308 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6309 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6310 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6311 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6312 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6313 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6314 (when (memq 'footnote lk) '(org-activate-footnote-links))
6315 ;; Targets.
6316 (list org-any-target-regexp '(0 'org-target t))
6317 ;; Diary sexps.
6318 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6319 ;; Macro
6320 '(org-fontify-macros)
6321 '(org-hide-wide-columns (0 nil append))
6322 ;; TODO keyword
6323 (list (format org-heading-keyword-regexp-format
6324 org-todo-regexp)
6325 '(2 (org-get-todo-face 2) t))
6326 ;; DONE
6327 (if org-fontify-done-headline
6328 (list (format org-heading-keyword-regexp-format
6329 (concat
6330 "\\(?:"
6331 (mapconcat 'regexp-quote org-done-keywords "\\|")
6332 "\\)"))
6333 '(2 'org-headline-done t))
6334 nil)
6335 ;; Priorities
6336 '(org-font-lock-add-priority-faces)
6337 ;; Tags
6338 '(org-font-lock-add-tag-faces)
6339 ;; Tags groups
6340 (when (and org-group-tags org-tag-groups-alist)
6341 (list (concat org-outline-regexp-bol ".+\\(:"
6342 (regexp-opt (mapcar 'car org-tag-groups-alist))
6343 ":\\).*$")
6344 '(1 'org-tag-group prepend)))
6345 ;; Special keywords
6346 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6347 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6348 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6349 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6350 ;; Emphasis
6351 (when em
6352 (if (featurep 'xemacs)
6353 '(org-do-emphasis-faces (0 nil append))
6354 '(org-do-emphasis-faces)))
6355 ;; Checkboxes
6356 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6357 1 'org-checkbox prepend)
6358 (when (cdr (assq 'checkbox org-list-automatic-rules))
6359 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6360 (0 (org-get-checkbox-statistics-face) t)))
6361 ;; Description list items
6362 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6363 1 'org-list-dt prepend)
6364 ;; ARCHIVEd headings
6365 (list (concat
6366 org-outline-regexp-bol
6367 "\\(.*:" org-archive-tag ":.*\\)")
6368 '(1 'org-archived prepend))
6369 ;; Specials
6370 '(org-do-latex-and-related)
6371 '(org-fontify-entities)
6372 '(org-raise-scripts)
6373 ;; Code
6374 '(org-activate-code (1 'org-code t))
6375 ;; COMMENT
6376 (list (format
6377 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6378 org-todo-regexp
6379 org-comment-string)
6380 '(9 'org-special-keyword t))
6381 ;; Blocks and meta lines
6382 '(org-fontify-meta-lines-and-blocks))))
6383 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6384 (run-hooks 'org-font-lock-set-keywords-hook)
6385 ;; Now set the full font-lock-keywords
6386 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6387 (setq-local font-lock-defaults
6388 '(org-font-lock-keywords t nil nil backward-paragraph))
6389 (kill-local-variable 'font-lock-keywords) nil))
6391 (defun org-toggle-pretty-entities ()
6392 "Toggle the composition display of entities as UTF8 characters."
6393 (interactive)
6394 (setq-local org-pretty-entities (not org-pretty-entities))
6395 (org-restart-font-lock)
6396 (if org-pretty-entities
6397 (message "Entities are now displayed as UTF8 characters")
6398 (save-restriction
6399 (widen)
6400 (org-decompose-region (point-min) (point-max))
6401 (message "Entities are now displayed as plain text"))))
6403 (defvar-local org-custom-properties-overlays nil
6404 "List of overlays used for custom properties.")
6406 (defun org-toggle-custom-properties-visibility ()
6407 "Display or hide properties in `org-custom-properties'."
6408 (interactive)
6409 (if org-custom-properties-overlays
6410 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6411 (setq org-custom-properties-overlays nil))
6412 (when org-custom-properties
6413 (org-with-wide-buffer
6414 (goto-char (point-min))
6415 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6416 (while (re-search-forward regexp nil t)
6417 (let ((end (cdr (save-match-data (org-get-property-block)))))
6418 (when (and end (< (point) end))
6419 ;; Hide first custom property in current drawer.
6420 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6421 (overlay-put o 'invisible t)
6422 (overlay-put o 'org-custom-property t)
6423 (push o org-custom-properties-overlays))
6424 ;; Hide additional custom properties in the same drawer.
6425 (while (re-search-forward regexp end t)
6426 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6427 (overlay-put o 'invisible t)
6428 (overlay-put o 'org-custom-property t)
6429 (push o org-custom-properties-overlays)))))
6430 ;; Each entry is limited to a single property drawer.
6431 (outline-next-heading)))))))
6433 (defun org-fontify-entities (limit)
6434 "Find an entity to fontify."
6435 (let (ee)
6436 (when org-pretty-entities
6437 (catch 'match
6438 ;; "\_ "-family is left out on purpose. Only the first one,
6439 ;; i.e., "\_ ", could be fontified anyway, and it would be
6440 ;; confusing when adding a second white space character.
6441 (while (re-search-forward
6442 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6443 limit t)
6444 (when (and (not (org-at-comment-p))
6445 (setq ee (org-entity-get (match-string 1)))
6446 (= (length (nth 6 ee)) 1))
6447 (let* ((end (if (equal (match-string 2) "{}")
6448 (match-end 2)
6449 (match-end 1))))
6450 (add-text-properties
6451 (match-beginning 0) end
6452 (list 'font-lock-fontified t))
6453 (compose-region (match-beginning 0) end
6454 (nth 6 ee) nil)
6455 (backward-char 1)
6456 (throw 'match t))))
6457 nil))))
6459 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6460 "Fontify string S like in Org-mode."
6461 (with-temp-buffer
6462 (insert s)
6463 (let ((org-odd-levels-only odd-levels))
6464 (org-mode)
6465 (font-lock-ensure)
6466 (buffer-string))))
6468 (defvar org-m nil)
6469 (defvar org-l nil)
6470 (defvar org-f nil)
6471 (defun org-get-level-face (n)
6472 "Get the right face for match N in font-lock matching of headlines."
6473 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6474 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6475 (if org-cycle-level-faces
6476 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6477 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6478 (cond
6479 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6480 ((eq n 2) org-f)
6481 (t (unless org-level-color-stars-only org-f))))
6483 (defun org-face-from-face-or-color (context inherit face-or-color)
6484 "Create a face list that inherits INHERIT, but sets the foreground color.
6485 When FACE-OR-COLOR is not a string, just return it."
6486 (if (stringp face-or-color)
6487 (list :inherit inherit
6488 (cdr (assoc context org-faces-easy-properties))
6489 face-or-color)
6490 face-or-color))
6492 (defun org-get-todo-face (kwd)
6493 "Get the right face for a TODO keyword KWD.
6494 If KWD is a number, get the corresponding match group."
6495 (when (numberp kwd) (setq kwd (match-string kwd)))
6496 (or (org-face-from-face-or-color
6497 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6498 (and (member kwd org-done-keywords) 'org-done)
6499 'org-todo))
6501 (defun org-get-priority-face (priority)
6502 "Get the right face for PRIORITY.
6503 PRIORITY is a character."
6504 (or (org-face-from-face-or-color
6505 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6506 'org-priority))
6508 (defun org-get-tag-face (tag)
6509 "Get the right face for TAG.
6510 If TAG is a number, get the corresponding match group."
6511 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6512 (or (org-face-from-face-or-color
6513 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6514 'org-tag)))
6516 (defun org-font-lock-add-priority-faces (limit)
6517 "Add the special priority faces."
6518 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6519 (add-text-properties
6520 (match-beginning 1) (match-end 1)
6521 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6522 'font-lock-fontified t))))
6524 (defun org-font-lock-add-tag-faces (limit)
6525 "Add the special tag faces."
6526 (when (and org-tag-faces org-tags-special-faces-re)
6527 (while (re-search-forward org-tags-special-faces-re limit t)
6528 (add-text-properties (match-beginning 1) (match-end 1)
6529 (list 'face (org-get-tag-face 1)
6530 'font-lock-fontified t))
6531 (backward-char 1))))
6533 (defun org-unfontify-region (beg end &optional maybe_loudly)
6534 "Remove fontification and activation overlays from links."
6535 (font-lock-default-unfontify-region beg end)
6536 (let* ((buffer-undo-list t)
6537 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6538 (inhibit-modification-hooks t)
6539 deactivate-mark buffer-file-name buffer-file-truename)
6540 (org-decompose-region beg end)
6541 (remove-text-properties beg end
6542 '(mouse-face t keymap t org-linked-text t
6543 invisible t intangible t
6544 org-emphasis t))
6545 (org-remove-font-lock-display-properties beg end)))
6547 (defconst org-script-display '(((raise -0.3) (height 0.7))
6548 ((raise 0.3) (height 0.7))
6549 ((raise -0.5))
6550 ((raise 0.5)))
6551 "Display properties for showing superscripts and subscripts.")
6553 (defun org-remove-font-lock-display-properties (beg end)
6554 "Remove specific display properties that have been added by font lock.
6555 The will remove the raise properties that are used to show superscripts
6556 and subscripts."
6557 (let (next prop)
6558 (while (< beg end)
6559 (setq next (next-single-property-change beg 'display nil end)
6560 prop (get-text-property beg 'display))
6561 (when (member prop org-script-display)
6562 (put-text-property beg next 'display nil))
6563 (setq beg next))))
6565 (defun org-raise-scripts (limit)
6566 "Add raise properties to sub/superscripts."
6567 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6568 (re-search-forward
6569 (if (eq org-use-sub-superscripts t)
6570 org-match-substring-regexp
6571 org-match-substring-with-braces-regexp)
6572 limit t))
6573 (let* ((pos (point)) table-p comment-p
6574 (mpos (match-beginning 3))
6575 (emph-p (get-text-property mpos 'org-emphasis))
6576 (link-p (get-text-property mpos 'mouse-face))
6577 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6578 (goto-char (point-at-bol))
6579 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6580 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6581 (goto-char pos)
6582 ;; Handle a_b^c
6583 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6584 (unless (or comment-p emph-p link-p keyw-p)
6585 (put-text-property (match-beginning 3) (match-end 0)
6586 'display
6587 (if (equal (char-after (match-beginning 2)) ?^)
6588 (nth (if table-p 3 1) org-script-display)
6589 (nth (if table-p 2 0) org-script-display)))
6590 (add-text-properties (match-beginning 2) (match-end 2)
6591 (list 'invisible t
6592 'org-dwidth t 'org-dwidth-n 1))
6593 (if (and (eq (char-after (match-beginning 3)) ?{)
6594 (eq (char-before (match-end 3)) ?}))
6595 (progn
6596 (add-text-properties
6597 (match-beginning 3) (1+ (match-beginning 3))
6598 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6599 (add-text-properties
6600 (1- (match-end 3)) (match-end 3)
6601 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6602 t)))
6604 ;;;; Visibility cycling, including org-goto and indirect buffer
6606 ;;; Cycling
6608 (defvar-local org-cycle-global-status nil)
6609 (put 'org-cycle-global-status 'org-state t)
6610 (defvar-local org-cycle-subtree-status nil)
6611 (put 'org-cycle-subtree-status 'org-state t)
6613 (defvar org-inlinetask-min-level)
6615 (defun org-unlogged-message (&rest args)
6616 "Display a message, but avoid logging it in the *Messages* buffer."
6617 (let ((message-log-max nil))
6618 (apply 'message args)))
6620 ;;;###autoload
6621 (defun org-cycle (&optional arg)
6622 "TAB-action and visibility cycling for Org-mode.
6624 This is the command invoked in Org-mode by the TAB key. Its main purpose
6625 is outline visibility cycling, but it also invokes other actions
6626 in special contexts.
6628 - When this function is called with a prefix argument, rotate the entire
6629 buffer through 3 states (global cycling)
6630 1. OVERVIEW: Show only top-level headlines.
6631 2. CONTENTS: Show all headlines of all levels, but no body text.
6632 3. SHOW ALL: Show everything.
6633 With a double \\[universal-argument] prefix argument, \
6634 switch to the startup visibility,
6635 determined by the variable `org-startup-folded', and by any VISIBILITY
6636 properties in the buffer.
6637 With a triple \\[universal-argument] prefix argument, \
6638 show the entire buffer, including any drawers.
6640 - When inside a table, re-align the table and move to the next field.
6642 - When point is at the beginning of a headline, rotate the subtree started
6643 by this line through 3 different states (local cycling)
6644 1. FOLDED: Only the main headline is shown.
6645 2. CHILDREN: The main headline and the direct children are shown.
6646 From this state, you can move to one of the children
6647 and zoom in further.
6648 3. SUBTREE: Show the entire subtree, including body text.
6649 If there is no subtree, switch directly from CHILDREN to FOLDED.
6651 - When point is at the beginning of an empty headline and the variable
6652 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6653 of the headline by demoting and promoting it to likely levels. This
6654 speeds up creation document structure by pressing TAB once or several
6655 times right after creating a new headline.
6657 - When there is a numeric prefix, go up to a heading with level ARG, do
6658 a `show-subtree' and return to the previous cursor position. If ARG
6659 is negative, go up that many levels.
6661 - When point is not at the beginning of a headline, execute the global
6662 binding for TAB, which is re-indenting the line. See the option
6663 `org-cycle-emulate-tab' for details.
6665 - Special case: if point is at the beginning of the buffer and there is
6666 no headline in line 1, this function will act as if called with prefix arg
6667 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6668 But only if also the variable `org-cycle-global-at-bob' is t."
6669 (interactive "P")
6670 (org-load-modules-maybe)
6671 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6672 (and org-cycle-level-after-item/entry-creation
6673 (or (org-cycle-level)
6674 (org-cycle-item-indentation))))
6675 (let* ((limit-level
6676 (or org-cycle-max-level
6677 (and (boundp 'org-inlinetask-min-level)
6678 org-inlinetask-min-level
6679 (1- org-inlinetask-min-level))))
6680 (nstars (and limit-level
6681 (if org-odd-levels-only
6682 (and limit-level (1- (* limit-level 2)))
6683 limit-level)))
6684 (org-outline-regexp
6685 (if (not (derived-mode-p 'org-mode))
6686 outline-regexp
6687 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6688 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6689 (not (looking-at org-outline-regexp))))
6690 (org-cycle-hook
6691 (if bob-special
6692 (delq 'org-optimize-window-after-visibility-change
6693 (copy-sequence org-cycle-hook))
6694 org-cycle-hook))
6695 (pos (point)))
6697 (when (or bob-special (equal arg '(4)))
6698 ;; special case: use global cycling
6699 (setq arg t))
6701 (cond
6703 ((equal arg '(16))
6704 (setq last-command 'dummy)
6705 (org-set-startup-visibility)
6706 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6708 ((equal arg '(64))
6709 (outline-show-all)
6710 (org-unlogged-message "Entire buffer visible, including drawers"))
6712 ;; Try cdlatex TAB completion
6713 ((org-try-cdlatex-tab))
6715 ;; Table: enter it or move to the next field.
6716 ((org-at-table-p 'any)
6717 (if (org-at-table.el-p)
6718 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6719 Use \\[org-edit-special] to edit table.el tables"))
6720 (if arg (org-table-edit-field t)
6721 (org-table-justify-field-maybe)
6722 (call-interactively 'org-table-next-field))))
6724 ((run-hook-with-args-until-success
6725 'org-tab-after-check-for-table-hook))
6727 ;; Global cycling: delegate to `org-cycle-internal-global'.
6728 ((eq arg t) (org-cycle-internal-global))
6730 ;; Drawers: delegate to `org-flag-drawer'.
6731 ((save-excursion
6732 (beginning-of-line 1)
6733 (looking-at org-drawer-regexp))
6734 (org-flag-drawer ; toggle block visibility
6735 (not (get-char-property (match-end 0) 'invisible))))
6737 ;; Show-subtree, ARG levels up from here.
6738 ((integerp arg)
6739 (save-excursion
6740 (org-back-to-heading)
6741 (outline-up-heading (if (< arg 0) (- arg)
6742 (- (funcall outline-level) arg)))
6743 (org-show-subtree)))
6745 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6746 ((and (featurep 'org-inlinetask)
6747 (org-inlinetask-at-task-p)
6748 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6749 (org-inlinetask-toggle-visibility))
6751 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6752 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6753 (save-excursion (move-beginning-of-line 1)
6754 (looking-at org-outline-regexp)))
6755 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6756 (org-cycle-internal-local))
6758 ;; From there: TAB emulation and template completion.
6759 (buffer-read-only (org-back-to-heading))
6761 ((run-hook-with-args-until-success
6762 'org-tab-after-check-for-cycling-hook))
6764 ((org-try-structure-completion))
6766 ((run-hook-with-args-until-success
6767 'org-tab-before-tab-emulation-hook))
6769 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6770 (or (not (bolp))
6771 (not (looking-at org-outline-regexp))))
6772 (call-interactively (global-key-binding "\t")))
6774 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6775 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6776 (or (and (eq org-cycle-emulate-tab 'white)
6777 (= (match-end 0) (point-at-eol)))
6778 (and (eq org-cycle-emulate-tab 'whitestart)
6779 (>= (match-end 0) pos))))
6781 (eq org-cycle-emulate-tab t))
6782 (call-interactively (global-key-binding "\t")))
6784 (t (save-excursion
6785 (org-back-to-heading)
6786 (org-cycle)))))))
6788 (defun org-cycle-internal-global ()
6789 "Do the global cycling action."
6790 ;; Hack to avoid display of messages for .org attachments in Gnus
6791 (let ((ga (string-match "\\*fontification" (buffer-name))))
6792 (cond
6793 ((and (eq last-command this-command)
6794 (eq org-cycle-global-status 'overview))
6795 ;; We just created the overview - now do table of contents
6796 ;; This can be slow in very large buffers, so indicate action
6797 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6798 (unless ga (org-unlogged-message "CONTENTS..."))
6799 (org-content)
6800 (unless ga (org-unlogged-message "CONTENTS...done"))
6801 (setq org-cycle-global-status 'contents)
6802 (run-hook-with-args 'org-cycle-hook 'contents))
6804 ((and (eq last-command this-command)
6805 (eq org-cycle-global-status 'contents))
6806 ;; We just showed the table of contents - now show everything
6807 (run-hook-with-args 'org-pre-cycle-hook 'all)
6808 (outline-show-all)
6809 (unless ga (org-unlogged-message "SHOW ALL"))
6810 (setq org-cycle-global-status 'all)
6811 (run-hook-with-args 'org-cycle-hook 'all))
6814 ;; Default action: go to overview
6815 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6816 (org-overview)
6817 (unless ga (org-unlogged-message "OVERVIEW"))
6818 (setq org-cycle-global-status 'overview)
6819 (run-hook-with-args 'org-cycle-hook 'overview)))))
6821 (defvar org-called-with-limited-levels nil
6822 "Non-nil when `org-with-limited-levels' is currently active.")
6824 (defun org-cycle-internal-local ()
6825 "Do the local cycling action."
6826 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6827 ;; First, determine end of headline (EOH), end of subtree or item
6828 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6829 (save-excursion
6830 (if (org-at-item-p)
6831 (progn
6832 (beginning-of-line)
6833 (setq struct (org-list-struct))
6834 (setq eoh (point-at-eol))
6835 (setq eos (org-list-get-item-end-before-blank (point) struct))
6836 (setq has-children (org-list-has-child-p (point) struct)))
6837 (org-back-to-heading)
6838 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6839 (setq eos (save-excursion (org-end-of-subtree t t)
6840 (when (bolp) (backward-char)) (point)))
6841 (setq has-children
6842 (or (save-excursion
6843 (let ((level (funcall outline-level)))
6844 (outline-next-heading)
6845 (and (org-at-heading-p t)
6846 (> (funcall outline-level) level))))
6847 (save-excursion
6848 (org-list-search-forward (org-item-beginning-re) eos t)))))
6849 ;; Determine end invisible part of buffer (EOL)
6850 (beginning-of-line 2)
6851 ;; XEmacs doesn't have `next-single-char-property-change'
6852 (if (featurep 'xemacs)
6853 (while (and (not (eobp)) ;; this is like `next-line'
6854 (get-char-property (1- (point)) 'invisible))
6855 (beginning-of-line 2))
6856 (while (and (not (eobp)) ;; this is like `next-line'
6857 (get-char-property (1- (point)) 'invisible))
6858 (goto-char (next-single-char-property-change (point) 'invisible))
6859 (and (eolp) (beginning-of-line 2))))
6860 (setq eol (point)))
6861 ;; Find out what to do next and set `this-command'
6862 (cond
6863 ((= eos eoh)
6864 ;; Nothing is hidden behind this heading
6865 (unless (org-before-first-heading-p)
6866 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6867 (org-unlogged-message "EMPTY ENTRY")
6868 (setq org-cycle-subtree-status nil)
6869 (save-excursion
6870 (goto-char eos)
6871 (outline-next-heading)
6872 (when (outline-invisible-p) (org-flag-heading nil))))
6873 ((and (or (>= eol eos)
6874 (not (string-match "\\S-" (buffer-substring eol eos))))
6875 (or has-children
6876 (not (setq children-skipped
6877 org-cycle-skip-children-state-if-no-children))))
6878 ;; Entire subtree is hidden in one line: children view
6879 (unless (org-before-first-heading-p)
6880 (run-hook-with-args 'org-pre-cycle-hook 'children))
6881 (if (org-at-item-p)
6882 (org-list-set-item-visibility (point-at-bol) struct 'children)
6883 (org-show-entry)
6884 (org-with-limited-levels (org-show-children))
6885 ;; FIXME: This slows down the func way too much.
6886 ;; How keep drawers hidden in subtree anyway?
6887 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6888 ;; (org-cycle-hide-drawers 'subtree))
6890 ;; Fold every list in subtree to top-level items.
6891 (when (eq org-cycle-include-plain-lists 'integrate)
6892 (save-excursion
6893 (org-back-to-heading)
6894 (while (org-list-search-forward (org-item-beginning-re) eos t)
6895 (beginning-of-line 1)
6896 (let* ((struct (org-list-struct))
6897 (prevs (org-list-prevs-alist struct))
6898 (end (org-list-get-bottom-point struct)))
6899 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6900 (org-list-get-all-items (point) struct prevs))
6901 (goto-char (if (< end eos) end eos)))))))
6902 (org-unlogged-message "CHILDREN")
6903 (save-excursion
6904 (goto-char eos)
6905 (outline-next-heading)
6906 (when (outline-invisible-p) (org-flag-heading nil)))
6907 (setq org-cycle-subtree-status 'children)
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-cycle-hook 'children)))
6910 ((or children-skipped
6911 (and (eq last-command this-command)
6912 (eq org-cycle-subtree-status 'children)))
6913 ;; We just showed the children, or no children are there,
6914 ;; now show everything.
6915 (unless (org-before-first-heading-p)
6916 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6917 (outline-flag-region eoh eos nil)
6918 (org-unlogged-message
6919 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6920 (setq org-cycle-subtree-status 'subtree)
6921 (unless (org-before-first-heading-p)
6922 (run-hook-with-args 'org-cycle-hook 'subtree)))
6924 ;; Default action: hide the subtree.
6925 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6926 (outline-flag-region eoh eos t)
6927 (org-unlogged-message "FOLDED")
6928 (setq org-cycle-subtree-status 'folded)
6929 (unless (org-before-first-heading-p)
6930 (run-hook-with-args 'org-cycle-hook 'folded))))))
6932 ;;;###autoload
6933 (defun org-global-cycle (&optional arg)
6934 "Cycle the global visibility. For details see `org-cycle'.
6935 With \\[universal-argument] prefix arg, switch to startup visibility.
6936 With a numeric prefix, show all headlines up to that level."
6937 (interactive "P")
6938 (let ((org-cycle-include-plain-lists
6939 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6940 (cond
6941 ((integerp arg)
6942 (outline-show-all)
6943 (outline-hide-sublevels arg)
6944 (setq org-cycle-global-status 'contents))
6945 ((equal arg '(4))
6946 (org-set-startup-visibility)
6947 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6949 (org-cycle '(4))))))
6951 (defun org-set-startup-visibility ()
6952 "Set the visibility required by startup options and properties."
6953 (cond
6954 ((eq org-startup-folded t)
6955 (org-overview))
6956 ((eq org-startup-folded 'content)
6957 (org-content))
6958 ((or (eq org-startup-folded 'showeverything)
6959 (eq org-startup-folded nil))
6960 (outline-show-all)))
6961 (unless (eq org-startup-folded 'showeverything)
6962 (when org-hide-block-startup (org-hide-block-all))
6963 (org-set-visibility-according-to-property 'no-cleanup)
6964 (org-cycle-hide-archived-subtrees 'all)
6965 (org-cycle-hide-drawers 'all)
6966 (org-cycle-show-empty-lines t)))
6968 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6969 "Switch subtree visibilities according to :VISIBILITY: property."
6970 (interactive)
6971 (let (org-show-entry-below)
6972 (org-with-wide-buffer
6973 (goto-char (point-min))
6974 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6975 (if (not (org-at-property-p)) (outline-next-heading)
6976 (let ((state (match-string 3)))
6977 (save-excursion
6978 (org-back-to-heading t)
6979 (outline-hide-subtree)
6980 (org-reveal)
6981 (cond
6982 ((equal state "folded")
6983 (outline-hide-subtree))
6984 ((equal state "children")
6985 (org-show-hidden-entry)
6986 (org-show-children))
6987 ((equal state "content")
6988 (save-excursion
6989 (save-restriction
6990 (org-narrow-to-subtree)
6991 (org-content))))
6992 ((member state '("all" "showall"))
6993 (outline-show-subtree)))))))
6994 (unless no-cleanup
6995 (org-cycle-hide-archived-subtrees 'all)
6996 (org-cycle-hide-drawers 'all)
6997 (org-cycle-show-empty-lines 'all)))))
6999 ;; This function uses outline-regexp instead of the more fundamental
7000 ;; org-outline-regexp so that org-cycle-global works outside of Org
7001 ;; buffers, where outline-regexp is needed.
7002 (defun org-overview ()
7003 "Switch to overview mode, showing only top-level headlines.
7004 This shows all headlines with a level equal or greater than the level
7005 of the first headline in the buffer. This is important, because if the
7006 first headline is not level one, then (hide-sublevels 1) gives confusing
7007 results."
7008 (interactive)
7009 (save-excursion
7010 (let ((level
7011 (save-excursion
7012 (goto-char (point-min))
7013 (when (re-search-forward (concat "^" outline-regexp) nil t)
7014 (goto-char (match-beginning 0))
7015 (funcall outline-level)))))
7016 (and level (outline-hide-sublevels level)))))
7018 (defun org-content (&optional arg)
7019 "Show all headlines in the buffer, like a table of contents.
7020 With numerical argument N, show content up to level N."
7021 (interactive "P")
7022 (org-overview)
7023 (save-excursion
7024 ;; Visit all headings and show their offspring
7025 (and (integerp arg) (org-overview))
7026 (goto-char (point-max))
7027 (catch 'exit
7028 (while (and (progn (condition-case nil
7029 (outline-previous-visible-heading 1)
7030 (error (goto-char (point-min))))
7032 (looking-at org-outline-regexp))
7033 (if (integerp arg)
7034 (org-show-children (1- arg))
7035 (outline-show-branches))
7036 (when (bobp) (throw 'exit nil))))))
7038 (defun org-optimize-window-after-visibility-change (state)
7039 "Adjust the window after a change in outline visibility.
7040 This function is the default value of the hook `org-cycle-hook'."
7041 (when (get-buffer-window (current-buffer))
7042 (cond
7043 ((eq state 'content) nil)
7044 ((eq state 'all) nil)
7045 ((eq state 'folded) nil)
7046 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7047 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7049 (defun org-remove-empty-overlays-at (pos)
7050 "Remove outline overlays that do not contain non-white stuff."
7051 (mapc
7052 (lambda (o)
7053 (and (eq 'outline (overlay-get o 'invisible))
7054 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7055 (overlay-end o))))
7056 (delete-overlay o)))
7057 (overlays-at pos)))
7059 (defun org-clean-visibility-after-subtree-move ()
7060 "Fix visibility issues after moving a subtree."
7061 ;; First, find a reasonable region to look at:
7062 ;; Start two siblings above, end three below
7063 (let* ((beg (save-excursion
7064 (and (org-get-last-sibling)
7065 (org-get-last-sibling))
7066 (point)))
7067 (end (save-excursion
7068 (and (org-get-next-sibling)
7069 (org-get-next-sibling)
7070 (org-get-next-sibling))
7071 (if (org-at-heading-p)
7072 (point-at-eol)
7073 (point))))
7074 (level (looking-at "\\*+"))
7075 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7076 (save-excursion
7077 (save-restriction
7078 (narrow-to-region beg end)
7079 (when re
7080 ;; Properly fold already folded siblings
7081 (goto-char (point-min))
7082 (while (re-search-forward re nil t)
7083 (when (and (not (outline-invisible-p))
7084 (save-excursion
7085 (goto-char (point-at-eol)) (outline-invisible-p)))
7086 (outline-hide-entry))))
7087 (org-cycle-show-empty-lines 'overview)
7088 (org-cycle-hide-drawers 'overview)))))
7090 (defun org-cycle-show-empty-lines (state)
7091 "Show empty lines above all visible headlines.
7092 The region to be covered depends on STATE when called through
7093 `org-cycle-hook'. Lisp program can use t for STATE to get the
7094 entire buffer covered. Note that an empty line is only shown if there
7095 are at least `org-cycle-separator-lines' empty lines before the headline."
7096 (when (/= org-cycle-separator-lines 0)
7097 (save-excursion
7098 (let* ((n (abs org-cycle-separator-lines))
7099 (re (cond
7100 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7101 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7102 (t (let ((ns (number-to-string (- n 2))))
7103 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7104 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7105 beg end)
7106 (cond
7107 ((memq state '(overview contents t))
7108 (setq beg (point-min) end (point-max)))
7109 ((memq state '(children folded))
7110 (setq beg (point)
7111 end (progn (org-end-of-subtree t t)
7112 (line-beginning-position 2)))))
7113 (when beg
7114 (goto-char beg)
7115 (while (re-search-forward re end t)
7116 (unless (get-char-property (match-end 1) 'invisible)
7117 (let ((e (match-end 1))
7118 (b (if (>= org-cycle-separator-lines 0)
7119 (match-beginning 1)
7120 (save-excursion
7121 (goto-char (match-beginning 0))
7122 (skip-chars-backward " \t\n")
7123 (line-end-position)))))
7124 (outline-flag-region b e nil))))))))
7125 ;; Never hide empty lines at the end of the file.
7126 (save-excursion
7127 (goto-char (point-max))
7128 (outline-previous-heading)
7129 (outline-end-of-heading)
7130 (when (and (looking-at "[ \t\n]+")
7131 (= (match-end 0) (point-max)))
7132 (outline-flag-region (point) (match-end 0) nil))))
7134 (defun org-show-empty-lines-in-parent ()
7135 "Move to the parent and re-show empty lines before visible headlines."
7136 (save-excursion
7137 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7138 (org-cycle-show-empty-lines context))))
7140 (defun org-files-list ()
7141 "Return `org-agenda-files' list, plus all open org-mode files.
7142 This is useful for operations that need to scan all of a user's
7143 open and agenda-wise Org files."
7144 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7145 (dolist (buf (buffer-list))
7146 (with-current-buffer buf
7147 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7148 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7149 files))
7151 (defsubst org-entry-beginning-position ()
7152 "Return the beginning position of the current entry."
7153 (save-excursion (outline-back-to-heading t) (point)))
7155 (defsubst org-entry-end-position ()
7156 "Return the end position of the current entry."
7157 (save-excursion (outline-next-heading) (point)))
7159 (defun org-cycle-hide-drawers (state &optional exceptions)
7160 "Re-hide all drawers after a visibility state change.
7161 When non-nil, optional argument EXCEPTIONS is a list of strings
7162 specifying which drawers should not be hidden."
7163 (when (and (derived-mode-p 'org-mode)
7164 (not (memq state '(overview folded contents))))
7165 (save-excursion
7166 (let* ((globalp (memq state '(contents all)))
7167 (beg (if globalp (point-min) (point)))
7168 (end (if globalp (point-max)
7169 (if (eq state 'children)
7170 (save-excursion (outline-next-heading) (point))
7171 (org-end-of-subtree t)))))
7172 (goto-char beg)
7173 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7174 (unless (member-ignore-case (match-string 1) exceptions)
7175 (let ((drawer (org-element-at-point)))
7176 (when (memq (org-element-type drawer) '(drawer property-drawer))
7177 (org-flag-drawer t drawer)
7178 ;; Make sure to skip drawer entirely or we might flag
7179 ;; it another time when matching its ending line with
7180 ;; `org-drawer-regexp'.
7181 (goto-char (org-element-property :end drawer))))))))))
7183 (defun org-flag-drawer (flag &optional element)
7184 "When FLAG is non-nil, hide the drawer we are at.
7185 Otherwise make it visible. When optional argument ELEMENT is
7186 a parsed drawer, as returned by `org-element-at-point', hide or
7187 show that drawer instead."
7188 (when (save-excursion
7189 (beginning-of-line)
7190 (org-looking-at-p org-drawer-regexp))
7191 (let ((drawer (or element (org-element-at-point))))
7192 (when (memq (org-element-type drawer) '(drawer property-drawer))
7193 (let ((post (org-element-property :post-affiliated drawer)))
7194 (save-excursion
7195 (outline-flag-region
7196 (progn (goto-char post) (line-end-position))
7197 (progn (goto-char (org-element-property :end drawer))
7198 (skip-chars-backward " \r\t\n")
7199 (line-end-position))
7200 flag))
7201 ;; When the drawer is hidden away, make sure point lies in
7202 ;; a visible part of the buffer.
7203 (when (and flag (> (line-beginning-position) post))
7204 (goto-char post)))))))
7206 (defun org-subtree-end-visible-p ()
7207 "Is the end of the current subtree visible?"
7208 (pos-visible-in-window-p
7209 (save-excursion (org-end-of-subtree t) (point))))
7211 (defun org-first-headline-recenter ()
7212 "Move cursor to the first headline and recenter the headline."
7213 (goto-char (point-min))
7214 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7215 (set-window-start (selected-window) (point-at-bol))))
7217 ;;; Saving and restoring visibility
7219 (defun org-outline-overlay-data (&optional use-markers)
7220 "Return a list of the locations of all outline overlays.
7221 These are overlays with the `invisible' property value `outline'.
7222 The return value is a list of cons cells, with start and stop
7223 positions for each overlay.
7224 If USE-MARKERS is set, return the positions as markers."
7225 (let (beg end)
7226 (save-excursion
7227 (save-restriction
7228 (widen)
7229 (delq nil
7230 (mapcar (lambda (o)
7231 (when (eq (overlay-get o 'invisible) 'outline)
7232 (setq beg (overlay-start o)
7233 end (overlay-end o))
7234 (and beg end (> end beg)
7235 (if use-markers
7236 (cons (copy-marker beg)
7237 (copy-marker end t))
7238 (cons beg end)))))
7239 (overlays-in (point-min) (point-max))))))))
7241 (defun org-set-outline-overlay-data (data)
7242 "Create visibility overlays for all positions in DATA.
7243 DATA should have been made by `org-outline-overlay-data'."
7244 (let (o)
7245 (save-excursion
7246 (save-restriction
7247 (widen)
7248 (outline-show-all)
7249 (mapc (lambda (c)
7250 (outline-flag-region (car c) (cdr c) t))
7251 data)))))
7253 ;;; Folding of blocks
7255 (defvar-local org-hide-block-overlays nil
7256 "Overlays hiding blocks.")
7258 (defun org-block-map (function &optional start end)
7259 "Call FUNCTION at the head of all source blocks in the current buffer.
7260 Optional arguments START and END can be used to limit the range."
7261 (let ((start (or start (point-min)))
7262 (end (or end (point-max))))
7263 (save-excursion
7264 (goto-char start)
7265 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7266 (save-excursion
7267 (save-match-data
7268 (goto-char (match-beginning 0))
7269 (funcall function)))))))
7271 (defun org-hide-block-toggle-all ()
7272 "Toggle the visibility of all blocks in the current buffer."
7273 (org-block-map 'org-hide-block-toggle))
7275 (defun org-hide-block-all ()
7276 "Fold all blocks in the current buffer."
7277 (interactive)
7278 (org-show-block-all)
7279 (org-block-map 'org-hide-block-toggle-maybe))
7281 (defun org-show-block-all ()
7282 "Unfold all blocks in the current buffer."
7283 (interactive)
7284 (mapc 'delete-overlay org-hide-block-overlays)
7285 (setq org-hide-block-overlays nil))
7287 (defun org-hide-block-toggle-maybe ()
7288 "Toggle visibility of block at point.
7289 Unlike to `org-hide-block-toggle', this function does not throw
7290 an error. Return a non-nil value when toggling is successful."
7291 (interactive)
7292 (ignore-errors (org-hide-block-toggle)))
7294 (defun org-hide-block-toggle (&optional force)
7295 "Toggle the visibility of the current block.
7296 When optional argument FORCE is `off', make block visible. If it
7297 is non-nil, hide it unconditionally. Throw an error when not at
7298 a block. Return a non-nil value when toggling is successful."
7299 (interactive)
7300 (let ((element (org-element-at-point)))
7301 (unless (memq (org-element-type element)
7302 '(center-block comment-block dynamic-block example-block
7303 export-block quote-block special-block
7304 src-block verse-block))
7305 (user-error "Not at a block"))
7306 (let* ((start (save-excursion
7307 (goto-char (org-element-property :post-affiliated element))
7308 (line-end-position)))
7309 (end (save-excursion
7310 (goto-char (org-element-property :end element))
7311 (skip-chars-backward " \r\t\n")
7312 (line-end-position)))
7313 (overlays (overlays-at start)))
7314 (cond
7315 ;; Do nothing when not before or at the block opening line or
7316 ;; at the block closing line.
7317 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7318 ((and (not (eq force 'off))
7319 (not (memq t (mapcar
7320 (lambda (o)
7321 (eq (overlay-get o 'invisible) 'org-hide-block))
7322 overlays))))
7323 (let ((ov (make-overlay start end)))
7324 (overlay-put ov 'invisible 'org-hide-block)
7325 ;; Make the block accessible to `isearch'.
7326 (overlay-put
7327 ov 'isearch-open-invisible
7328 (lambda (ov)
7329 (when (memq ov org-hide-block-overlays)
7330 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7331 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7332 (delete-overlay ov))))
7333 (push ov org-hide-block-overlays)
7334 ;; When the block is hidden away, make sure point is left in
7335 ;; a visible part of the buffer.
7336 (when (> (line-beginning-position) start)
7337 (goto-char start)
7338 (beginning-of-line))
7339 ;; Signal successful toggling.
7341 ((or (not force) (eq force 'off))
7342 (dolist (ov overlays t)
7343 (when (memq ov org-hide-block-overlays)
7344 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7345 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7346 (delete-overlay ov))))))))
7348 ;; org-tab-after-check-for-cycling-hook
7349 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7350 ;; Remove overlays when changing major mode
7351 (add-hook 'org-mode-hook
7352 (lambda () (org-add-hook 'change-major-mode-hook
7353 'org-show-block-all 'append 'local)))
7355 ;;; Org-goto
7357 (defvar org-goto-window-configuration nil)
7358 (defvar org-goto-marker nil)
7359 (defvar org-goto-map)
7360 (defun org-goto-map ()
7361 "Set the keymap `org-goto'."
7362 (setq org-goto-map
7363 (let ((map (make-sparse-keymap)))
7364 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7365 mouse-drag-region universal-argument org-occur)))
7366 (dolist (cmd cmds)
7367 (substitute-key-definition cmd cmd map global-map)))
7368 (suppress-keymap map)
7369 (org-defkey map "\C-m" 'org-goto-ret)
7370 (org-defkey map [(return)] 'org-goto-ret)
7371 (org-defkey map [(left)] 'org-goto-left)
7372 (org-defkey map [(right)] 'org-goto-right)
7373 (org-defkey map [(control ?g)] 'org-goto-quit)
7374 (org-defkey map "\C-i" 'org-cycle)
7375 (org-defkey map [(tab)] 'org-cycle)
7376 (org-defkey map [(down)] 'outline-next-visible-heading)
7377 (org-defkey map [(up)] 'outline-previous-visible-heading)
7378 (if org-goto-auto-isearch
7379 (if (fboundp 'define-key-after)
7380 (define-key-after map [t] 'org-goto-local-auto-isearch)
7381 nil)
7382 (org-defkey map "q" 'org-goto-quit)
7383 (org-defkey map "n" 'outline-next-visible-heading)
7384 (org-defkey map "p" 'outline-previous-visible-heading)
7385 (org-defkey map "f" 'outline-forward-same-level)
7386 (org-defkey map "b" 'outline-backward-same-level)
7387 (org-defkey map "u" 'outline-up-heading))
7388 (org-defkey map "/" 'org-occur)
7389 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7390 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7391 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7392 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7393 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7394 map)))
7396 (defconst org-goto-help
7397 "Browse buffer copy, to find location or copy text.%s
7398 RET=jump to location C-g=quit and return to previous location
7399 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7401 (defvar org-goto-start-pos) ; dynamically scoped parameter
7403 (defun org-goto (&optional alternative-interface)
7404 "Look up a different location in the current file, keeping current visibility.
7406 When you want look-up or go to a different location in a
7407 document, the fastest way is often to fold the entire buffer and
7408 then dive into the tree. This method has the disadvantage, that
7409 the previous location will be folded, which may not be what you
7410 want.
7412 This command works around this by showing a copy of the current
7413 buffer in an indirect buffer, in overview mode. You can dive
7414 into the tree in that copy, use org-occur and incremental search
7415 to find a location. When pressing RET or `Q', the command
7416 returns to the original buffer in which the visibility is still
7417 unchanged. After RET it will also jump to the location selected
7418 in the indirect buffer and expose the headline hierarchy above.
7420 With a prefix argument, use the alternative interface: e.g., if
7421 `org-goto-interface' is `outline' use `outline-path-completion'."
7422 (interactive "P")
7423 (org-goto-map)
7424 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7425 (org-refile-use-outline-path t)
7426 (org-refile-target-verify-function nil)
7427 (interface
7428 (if (not alternative-interface)
7429 org-goto-interface
7430 (if (eq org-goto-interface 'outline)
7431 'outline-path-completion
7432 'outline)))
7433 (org-goto-start-pos (point))
7434 (selected-point
7435 (if (eq interface 'outline)
7436 (car (org-get-location (current-buffer) org-goto-help))
7437 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7438 (org-refile-check-position pa)
7439 (nth 3 pa)))))
7440 (if selected-point
7441 (progn
7442 (org-mark-ring-push org-goto-start-pos)
7443 (goto-char selected-point)
7444 (when (or (outline-invisible-p) (org-invisible-p2))
7445 (org-show-context 'org-goto)))
7446 (message "Quit"))))
7448 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7449 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7450 (defvar org-goto-local-auto-isearch-map) ; defined below
7452 (defun org-get-location (buf help)
7453 "Let the user select a location in the Org-mode buffer BUF.
7454 This function uses a recursive edit. It returns the selected position
7455 or nil."
7456 (org-no-popups
7457 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7458 (isearch-hide-immediately nil)
7459 (isearch-search-fun-function
7460 (lambda () 'org-goto-local-search-headings))
7461 (org-goto-selected-point org-goto-exit-command))
7462 (save-excursion
7463 (save-window-excursion
7464 (delete-other-windows)
7465 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7466 (org-pop-to-buffer-same-window
7467 (condition-case nil
7468 (make-indirect-buffer (current-buffer) "*org-goto*")
7469 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7470 (with-output-to-temp-buffer "*Org Help*"
7471 (princ (format help (if org-goto-auto-isearch
7472 " Just type for auto-isearch."
7473 " n/p/f/b/u to navigate, q to quit."))))
7474 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7475 (setq buffer-read-only nil)
7476 (let ((org-startup-truncated t)
7477 (org-startup-folded nil)
7478 (org-startup-align-all-tables nil))
7479 (org-mode)
7480 (org-overview))
7481 (setq buffer-read-only t)
7482 (if (and (boundp 'org-goto-start-pos)
7483 (integer-or-marker-p org-goto-start-pos))
7484 (progn (goto-char org-goto-start-pos)
7485 (when (outline-invisible-p)
7486 (org-show-set-visibility 'lineage)))
7487 (goto-char (point-min)))
7488 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7489 (message "Select location and press RET")
7490 (use-local-map org-goto-map)
7491 (recursive-edit)))
7492 (kill-buffer "*org-goto*")
7493 (cons org-goto-selected-point org-goto-exit-command))))
7495 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7496 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7497 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7498 (if (fboundp 'isearch-other-control-char)
7499 (progn
7500 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7501 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7502 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7503 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7504 (define-key org-goto-local-auto-isearch-map [return] nil))
7506 (defun org-goto-local-search-headings (string bound noerror)
7507 "Search and make sure that any matches are in headlines."
7508 (catch 'return
7509 (while (if isearch-forward
7510 (search-forward string bound noerror)
7511 (search-backward string bound noerror))
7512 (when (save-match-data
7513 (and (save-excursion
7514 (beginning-of-line)
7515 (looking-at org-complex-heading-regexp))
7516 (or (not (match-beginning 5))
7517 (< (point) (match-beginning 5)))))
7518 (throw 'return (point))))))
7520 (defun org-goto-local-auto-isearch ()
7521 "Start isearch."
7522 (interactive)
7523 (goto-char (point-min))
7524 (let ((keys (this-command-keys)))
7525 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7526 (isearch-mode t)
7527 (isearch-process-search-char (string-to-char keys)))))
7529 (defun org-goto-ret (&optional arg)
7530 "Finish `org-goto' by going to the new location."
7531 (interactive "P")
7532 (setq org-goto-selected-point (point)
7533 org-goto-exit-command 'return)
7534 (throw 'exit nil))
7536 (defun org-goto-left ()
7537 "Finish `org-goto' by going to the new location."
7538 (interactive)
7539 (if (org-at-heading-p)
7540 (progn
7541 (beginning-of-line 1)
7542 (setq org-goto-selected-point (point)
7543 org-goto-exit-command 'left)
7544 (throw 'exit nil))
7545 (user-error "Not on a heading")))
7547 (defun org-goto-right ()
7548 "Finish `org-goto' by going to the new location."
7549 (interactive)
7550 (if (org-at-heading-p)
7551 (progn
7552 (setq org-goto-selected-point (point)
7553 org-goto-exit-command 'right)
7554 (throw 'exit nil))
7555 (user-error "Not on a heading")))
7557 (defun org-goto-quit ()
7558 "Finish `org-goto' without cursor motion."
7559 (interactive)
7560 (setq org-goto-selected-point nil)
7561 (setq org-goto-exit-command 'quit)
7562 (throw 'exit nil))
7564 ;;; Indirect buffer display of subtrees
7566 (defvar org-indirect-dedicated-frame nil
7567 "This is the frame being used for indirect tree display.")
7568 (defvar org-last-indirect-buffer nil)
7570 (defun org-tree-to-indirect-buffer (&optional arg)
7571 "Create indirect buffer and narrow it to current subtree.
7572 With a numerical prefix ARG, go up to this level and then take that tree.
7573 If ARG is negative, go up that many levels.
7575 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7576 indirect buffer previously made with this command, to avoid proliferation of
7577 indirect buffers. However, when you call the command with a \
7578 \\[universal-argument] prefix, or
7579 when `org-indirect-buffer-display' is `new-frame', the last buffer
7580 is kept so that you can work with several indirect buffers at the same time.
7581 If `org-indirect-buffer-display' is `dedicated-frame', the \
7582 \\[universal-argument] prefix also
7583 requests that a new frame be made for the new buffer, so that the dedicated
7584 frame is not changed."
7585 (interactive "P")
7586 (let ((cbuf (current-buffer))
7587 (cwin (selected-window))
7588 (pos (point))
7589 beg end level heading ibuf)
7590 (save-excursion
7591 (org-back-to-heading t)
7592 (when (numberp arg)
7593 (setq level (org-outline-level))
7594 (when (< arg 0) (setq arg (+ level arg)))
7595 (while (> (setq level (org-outline-level)) arg)
7596 (org-up-heading-safe)))
7597 (setq beg (point)
7598 heading (org-get-heading))
7599 (org-end-of-subtree t t)
7600 (when (org-at-heading-p) (backward-char 1))
7601 (setq end (point)))
7602 (when (and (buffer-live-p org-last-indirect-buffer)
7603 (not (eq org-indirect-buffer-display 'new-frame))
7604 (not arg))
7605 (kill-buffer org-last-indirect-buffer))
7606 (setq ibuf (org-get-indirect-buffer cbuf heading)
7607 org-last-indirect-buffer ibuf)
7608 (cond
7609 ((or (eq org-indirect-buffer-display 'new-frame)
7610 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7611 (select-frame (make-frame))
7612 (delete-other-windows)
7613 (org-pop-to-buffer-same-window ibuf)
7614 (org-set-frame-title heading))
7615 ((eq org-indirect-buffer-display 'dedicated-frame)
7616 (raise-frame
7617 (select-frame (or (and org-indirect-dedicated-frame
7618 (frame-live-p org-indirect-dedicated-frame)
7619 org-indirect-dedicated-frame)
7620 (setq org-indirect-dedicated-frame (make-frame)))))
7621 (delete-other-windows)
7622 (org-pop-to-buffer-same-window ibuf)
7623 (org-set-frame-title (concat "Indirect: " heading)))
7624 ((eq org-indirect-buffer-display 'current-window)
7625 (org-pop-to-buffer-same-window ibuf))
7626 ((eq org-indirect-buffer-display 'other-window)
7627 (pop-to-buffer ibuf))
7628 (t (error "Invalid value")))
7629 (when (featurep 'xemacs)
7630 (save-excursion (org-mode) (turn-on-font-lock)))
7631 (narrow-to-region beg end)
7632 (outline-show-all)
7633 (goto-char pos)
7634 (run-hook-with-args 'org-cycle-hook 'all)
7635 (and (window-live-p cwin) (select-window cwin))))
7637 (defun org-get-indirect-buffer (&optional buffer heading)
7638 (setq buffer (or buffer (current-buffer)))
7639 (let ((n 1) (base (buffer-name buffer)) bname)
7640 (while (buffer-live-p
7641 (get-buffer
7642 (setq bname
7643 (concat base "-"
7644 (if heading (concat heading "-" (number-to-string n))
7645 (number-to-string n))))))
7646 (setq n (1+ n)))
7647 (condition-case nil
7648 (make-indirect-buffer buffer bname 'clone)
7649 (error (make-indirect-buffer buffer bname)))))
7651 (defun org-set-frame-title (title)
7652 "Set the title of the current frame to the string TITLE."
7653 ;; FIXME: how to name a single frame in XEmacs???
7654 (unless (featurep 'xemacs)
7655 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7657 ;;;; Structure editing
7659 ;;; Inserting headlines
7661 (defun org--line-empty-p (n)
7662 "Is the Nth next line empty?
7664 Counts the current line as N = 1 and the previous line as N = 0;
7665 see `beginning-of-line'."
7666 (save-excursion
7667 (and (not (bobp))
7668 (or (beginning-of-line n) t)
7669 (save-match-data
7670 (looking-at "[ \t]*$")))))
7672 (defun org-previous-line-empty-p ()
7673 "Is the previous line a blank line?
7674 When NEXT is non-nil, check the next line instead."
7675 (org--line-empty-p 0))
7677 (defun org-next-line-empty-p ()
7678 "Is the previous line a blank line?
7679 When NEXT is non-nil, check the next line instead."
7680 (org--line-empty-p 2))
7682 (defun org-insert-heading (&optional arg invisible-ok top-level)
7683 "Insert a new heading or an item with the same depth at point.
7685 If point is at the beginning of a heading or a list item, insert
7686 a new heading or a new item above the current one. If point is
7687 at the beginning of a normal line, turn the line into a heading.
7689 If point is in the middle of a headline or a list item, split the
7690 headline or the item and create a new headline/item with the text
7691 in the current line after point \(see `org-M-RET-may-split-line'
7692 on how to modify this behavior).
7694 With one universal prefix argument, set the user option
7695 `org-insert-heading-respect-content' to t for the duration of
7696 the command. This modifies the behavior described above in this
7697 ways: on list items and at the beginning of normal lines, force
7698 the insertion of a heading after the current subtree.
7700 With two universal prefix arguments, insert the heading at the
7701 end of the grandparent subtree. For example, if point is within
7702 a 2nd-level heading, then it will insert a 2nd-level heading at
7703 the end of the 1st-level parent heading.
7705 If point is at the beginning of a headline, insert a sibling
7706 before the current headline. If point is not at the beginning,
7707 split the line and create a new headline with the text in the
7708 current line after point \(see `org-M-RET-may-split-line' on how
7709 to modify this behavior).
7711 If point is at the beginning of a normal line, turn this line
7712 into a heading.
7714 When INVISIBLE-OK is set, stop at invisible headlines when going
7715 back. This is important for non-interactive uses of the
7716 command.
7718 When optional argument TOP-LEVEL is non-nil, insert a level 1
7719 heading, unconditionally."
7720 (interactive "P")
7721 (when (org-called-interactively-p 'any) (org-reveal))
7722 (let ((itemp (and (not top-level) (org-in-item-p)))
7723 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7724 (respect-content (or org-insert-heading-respect-content
7725 (equal arg '(4))))
7726 (initial-content ""))
7728 (cond
7730 ((or (= (buffer-size) 0)
7731 (and (not (save-excursion
7732 (and (ignore-errors (org-back-to-heading invisible-ok))
7733 (org-at-heading-p))))
7734 (or arg (not itemp))))
7735 ;; At beginning of buffer or so high up that only a heading
7736 ;; makes sense.
7737 (cond ((and (bolp) (not respect-content)) (insert "* "))
7738 ((not respect-content)
7739 (unless may-split (end-of-line))
7740 (insert "\n* "))
7741 ((re-search-forward org-outline-regexp-bol nil t)
7742 (beginning-of-line)
7743 (insert "* \n")
7744 (backward-char))
7745 (t (goto-char (point-max))
7746 (insert "\n* ")))
7747 (run-hooks 'org-insert-heading-hook))
7749 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7752 ;; Maybe move at the end of the subtree
7753 (when (equal arg '(16))
7754 (org-up-heading-safe)
7755 (org-end-of-subtree t))
7756 ;; Insert a heading
7757 (save-restriction
7758 (widen)
7759 (let* ((level nil)
7760 (on-heading (org-at-heading-p))
7761 (empty-line-p (if on-heading
7762 (org-previous-line-empty-p)
7763 ;; We will decide later
7764 nil))
7765 ;; Get a level string to fall back on.
7766 (fix-level
7767 (if (org-before-first-heading-p) "*"
7768 (save-excursion
7769 (org-back-to-heading t)
7770 (when (org-previous-line-empty-p) (setq empty-line-p t))
7771 (looking-at org-outline-regexp)
7772 (make-string (1- (length (match-string 0))) ?*))))
7773 (stars
7774 (save-excursion
7775 (condition-case nil
7776 (if top-level "* "
7777 (org-back-to-heading invisible-ok)
7778 (when (and (not on-heading)
7779 (featurep 'org-inlinetask)
7780 (integerp org-inlinetask-min-level)
7781 (>= (length (match-string 0))
7782 org-inlinetask-min-level))
7783 ;; Find a heading level before the inline
7784 ;; task.
7785 (while (and (setq level (org-up-heading-safe))
7786 (>= level org-inlinetask-min-level)))
7787 (if (org-at-heading-p)
7788 (org-back-to-heading invisible-ok)
7789 (error "This should not happen")))
7790 (unless (and (save-excursion
7791 (save-match-data
7792 (org-backward-heading-same-level
7793 1 invisible-ok))
7794 (= (point) (match-beginning 0)))
7795 (not (org-next-line-empty-p)))
7796 (setq empty-line-p (or empty-line-p
7797 (org-previous-line-empty-p))))
7798 (match-string 0))
7799 (error (or fix-level "* ")))))
7800 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7801 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7802 pos hide-previous previous-pos)
7804 ;; If we insert after content, move there and clean up
7805 ;; whitespace.
7806 (when (and respect-content
7807 (not (org-looking-at-p org-outline-regexp-bol)))
7808 (if (not (org-before-first-heading-p))
7809 (org-end-of-subtree nil t)
7810 (re-search-forward org-outline-regexp-bol)
7811 (beginning-of-line 0))
7812 (skip-chars-backward " \r\t\n")
7813 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7814 (looking-at "[ \t]+") (replace-match ""))
7815 (unless (eobp) (forward-char 1))
7816 (when (looking-at "^\\*")
7817 (unless (bobp) (backward-char 1))
7818 (insert "\n")))
7820 ;; If we are splitting, grab the text that should be moved
7821 ;; to the new headline.
7822 (when may-split
7823 (if (org-at-heading-p)
7824 ;; This is a heading: split intelligently (keeping
7825 ;; tags).
7826 (let ((pos (point)))
7827 (beginning-of-line)
7828 (unless (looking-at org-complex-heading-regexp)
7829 (error "This should not happen"))
7830 (when (and (match-beginning 4)
7831 (> pos (match-beginning 4))
7832 (< pos (match-end 4)))
7833 (setq initial-content (buffer-substring pos (match-end 4)))
7834 (goto-char pos)
7835 (delete-region (point) (match-end 4))
7836 (if (looking-at "[ \t]*$")
7837 (replace-match "")
7838 (insert (make-string (length initial-content) ?\s)))
7839 (setq initial-content (org-trim initial-content)))
7840 (goto-char pos))
7841 ;; A normal line.
7842 (setq initial-content
7843 (org-trim
7844 (delete-and-extract-region (point) (line-end-position))))))
7846 ;; If we are at the beginning of the line, insert before it.
7847 ;; Otherwise, after it.
7848 (cond
7849 ((and (bolp) (looking-at "[ \t]*$")))
7850 ((bolp) (save-excursion (insert "\n")))
7851 (t (end-of-line)
7852 (insert "\n")))
7854 ;; Insert the new heading
7855 (insert stars)
7856 (just-one-space)
7857 (insert initial-content)
7858 (unless (and blank (org-previous-line-empty-p))
7859 (org-N-empty-lines-before-current (if blank 1 0)))
7860 ;; Adjust visibility, which may be messed up if we removed
7861 ;; blank lines while previous entry was hidden.
7862 (let ((bol (line-beginning-position)))
7863 (dolist (o (overlays-at (1- bol)))
7864 (when (and (eq (overlay-get o 'invisible) 'outline)
7865 (eq (overlay-end o) bol))
7866 (move-overlay o (overlay-start o) (1- bol)))))
7867 (run-hooks 'org-insert-heading-hook)))))))
7869 (defun org-N-empty-lines-before-current (N)
7870 "Make the number of empty lines before current exactly N.
7871 So this will delete or add empty lines."
7872 (save-excursion
7873 (beginning-of-line)
7874 (let ((p (point)))
7875 (skip-chars-backward " \r\t\n")
7876 (unless (bolp) (forward-line))
7877 (delete-region (point) p))
7878 (when (> N 0) (insert (make-string N ?\n)))))
7880 (defun org-get-heading (&optional no-tags no-todo)
7881 "Return the heading of the current entry, without the stars.
7882 When NO-TAGS is non-nil, don't include tags.
7883 When NO-TODO is non-nil, don't include TODO keywords."
7884 (save-excursion
7885 (org-back-to-heading t)
7886 (cond
7887 ((and no-tags no-todo)
7888 (looking-at org-complex-heading-regexp)
7889 (match-string 4))
7890 (no-tags
7891 (looking-at (concat org-outline-regexp
7892 "\\(.*?\\)"
7893 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7894 (match-string 1))
7895 (no-todo
7896 (looking-at org-todo-line-regexp)
7897 (match-string 3))
7898 (t (looking-at org-heading-regexp)
7899 (match-string 2)))))
7901 (defvar orgstruct-mode) ; defined below
7903 (defun org-heading-components ()
7904 "Return the components of the current heading.
7905 This is a list with the following elements:
7906 - the level as an integer
7907 - the reduced level, different if `org-odd-levels-only' is set.
7908 - the TODO keyword, or nil
7909 - the priority character, like ?A, or nil if no priority is given
7910 - the headline text itself, or the tags string if no headline text
7911 - the tags string, or nil."
7912 (save-excursion
7913 (org-back-to-heading t)
7914 (when (let (case-fold-search)
7915 (looking-at
7916 (if orgstruct-mode
7917 org-heading-regexp
7918 org-complex-heading-regexp)))
7919 (if orgstruct-mode
7920 (list (length (match-string 1))
7921 (org-reduced-level (length (match-string 1)))
7924 (match-string 2)
7925 nil)
7926 (list (length (match-string 1))
7927 (org-reduced-level (length (match-string 1)))
7928 (org-match-string-no-properties 2)
7929 (and (match-end 3) (aref (match-string 3) 2))
7930 (org-match-string-no-properties 4)
7931 (org-match-string-no-properties 5))))))
7933 (defun org-get-entry ()
7934 "Get the entry text, after heading, entire subtree."
7935 (save-excursion
7936 (org-back-to-heading t)
7937 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7939 (defun org-insert-heading-after-current ()
7940 "Insert a new heading with same level as current, after current subtree."
7941 (interactive)
7942 (org-back-to-heading)
7943 (org-insert-heading)
7944 (org-move-subtree-down)
7945 (end-of-line 1))
7947 (defun org-insert-heading-respect-content (&optional invisible-ok)
7948 "Insert heading with `org-insert-heading-respect-content' set to t."
7949 (interactive)
7950 (org-insert-heading '(4) invisible-ok))
7952 (defun org-insert-todo-heading-respect-content (&optional force-state)
7953 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7954 (interactive)
7955 (org-insert-todo-heading force-state '(4)))
7957 (defun org-insert-todo-heading (arg &optional force-heading)
7958 "Insert a new heading with the same level and TODO state as current heading.
7959 If the heading has no TODO state, or if the state is DONE, use the first
7960 state (TODO by default). Also with one prefix arg, force first state. With
7961 two prefix args, force inserting at the end of the parent subtree."
7962 (interactive "P")
7963 (when (or force-heading (not (org-insert-item 'checkbox)))
7964 (org-insert-heading (or (and (equal arg '(16)) '(16))
7965 force-heading))
7966 (save-excursion
7967 (org-back-to-heading)
7968 (outline-previous-heading)
7969 (looking-at org-todo-line-regexp))
7970 (let*
7971 ((new-mark-x
7972 (if (or (equal arg '(4))
7973 (not (match-beginning 2))
7974 (member (match-string 2) org-done-keywords))
7975 (car org-todo-keywords-1)
7976 (match-string 2)))
7977 (new-mark
7979 (run-hook-with-args-until-success
7980 'org-todo-get-default-hook new-mark-x nil)
7981 new-mark-x)))
7982 (beginning-of-line 1)
7983 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7984 (if org-treat-insert-todo-heading-as-state-change
7985 (org-todo new-mark)
7986 (insert new-mark " "))))
7987 (when org-provide-todo-statistics
7988 (org-update-parent-todo-statistics))))
7990 (defun org-insert-subheading (arg)
7991 "Insert a new subheading and demote it.
7992 Works for outline headings and for plain lists alike."
7993 (interactive "P")
7994 (org-insert-heading arg)
7995 (cond
7996 ((org-at-heading-p) (org-do-demote))
7997 ((org-at-item-p) (org-indent-item))))
7999 (defun org-insert-todo-subheading (arg)
8000 "Insert a new subheading with TODO keyword or checkbox and demote it.
8001 Works for outline headings and for plain lists alike."
8002 (interactive "P")
8003 (org-insert-todo-heading arg)
8004 (cond
8005 ((org-at-heading-p) (org-do-demote))
8006 ((org-at-item-p) (org-indent-item))))
8008 ;;; Promotion and Demotion
8010 (defvar org-after-demote-entry-hook nil
8011 "Hook run after an entry has been demoted.
8012 The cursor will be at the beginning of the entry.
8013 When a subtree is being demoted, the hook will be called for each node.")
8015 (defvar org-after-promote-entry-hook nil
8016 "Hook run after an entry has been promoted.
8017 The cursor will be at the beginning of the entry.
8018 When a subtree is being promoted, the hook will be called for each node.")
8020 (defun org-promote-subtree ()
8021 "Promote the entire subtree.
8022 See also `org-promote'."
8023 (interactive)
8024 (save-excursion
8025 (org-with-limited-levels (org-map-tree 'org-promote)))
8026 (org-fix-position-after-promote))
8028 (defun org-demote-subtree ()
8029 "Demote the entire subtree.
8030 See `org-demote' and `org-promote'."
8031 (interactive)
8032 (save-excursion
8033 (org-with-limited-levels (org-map-tree 'org-demote)))
8034 (org-fix-position-after-promote))
8036 (defun org-do-promote ()
8037 "Promote the current heading higher up the tree.
8038 If the region is active in `transient-mark-mode', promote all
8039 headings in the region."
8040 (interactive)
8041 (save-excursion
8042 (if (org-region-active-p)
8043 (org-map-region 'org-promote (region-beginning) (region-end))
8044 (org-promote)))
8045 (org-fix-position-after-promote))
8047 (defun org-do-demote ()
8048 "Demote the current heading lower down the tree.
8049 If the region is active in `transient-mark-mode', demote all
8050 headings in the region."
8051 (interactive)
8052 (save-excursion
8053 (if (org-region-active-p)
8054 (org-map-region 'org-demote (region-beginning) (region-end))
8055 (org-demote)))
8056 (org-fix-position-after-promote))
8058 (defun org-fix-position-after-promote ()
8059 "Fix cursor position and indentation after demoting/promoting."
8060 (let ((pos (point)))
8061 (when (save-excursion
8062 (beginning-of-line 1)
8063 (looking-at org-todo-line-regexp)
8064 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8065 (cond ((eobp) (insert " "))
8066 ((eolp) (insert " "))
8067 ((equal (char-after) ?\ ) (forward-char 1))))))
8069 (defun org-current-level ()
8070 "Return the level of the current entry, or nil if before the first headline.
8071 The level is the number of stars at the beginning of the
8072 headline. Use `org-reduced-level' to remove the effect of
8073 `org-odd-levels'. Unlike to `org-outline-level', this function
8074 ignores inlinetasks."
8075 (let ((level (org-with-limited-levels (org-outline-level))))
8076 (and (> level 0) level)))
8078 (defun org-get-previous-line-level ()
8079 "Return the outline depth of the last headline before the current line.
8080 Returns 0 for the first headline in the buffer, and nil if before the
8081 first headline."
8082 (and (org-current-level)
8083 (or (and (/= (line-beginning-position) (point-min))
8084 (save-excursion (beginning-of-line 0) (org-current-level)))
8085 0)))
8087 (defun org-reduced-level (l)
8088 "Compute the effective level of a heading.
8089 This takes into account the setting of `org-odd-levels-only'."
8090 (cond
8091 ((zerop l) 0)
8092 (org-odd-levels-only (1+ (floor (/ l 2))))
8093 (t l)))
8095 (defun org-level-increment ()
8096 "Return the number of stars that will be added or removed at a
8097 time to headlines when structure editing, based on the value of
8098 `org-odd-levels-only'."
8099 (if org-odd-levels-only 2 1))
8101 (defun org-get-valid-level (level &optional change)
8102 "Rectify a level change under the influence of `org-odd-levels-only'
8103 LEVEL is a current level, CHANGE is by how much the level should be
8104 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8105 even level numbers will become the next higher odd number."
8106 (if org-odd-levels-only
8107 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8108 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8109 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8110 (max 1 (+ level (or change 0)))))
8111 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8113 (defun org-promote ()
8114 "Promote the current heading higher up the tree."
8115 (org-with-wide-buffer
8116 (org-back-to-heading t)
8117 (let* ((after-change-functions (remq 'flyspell-after-change-function
8118 after-change-functions))
8119 (level (save-match-data (funcall outline-level)))
8120 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8121 (diff (abs (- level (length up-head) -1))))
8122 (cond
8123 ((and (= level 1) org-allow-promoting-top-level-subtree)
8124 (replace-match "# " nil t))
8125 ((= level 1)
8126 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8127 (t (replace-match up-head nil t)))
8128 (unless (= level 1)
8129 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8130 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8131 (run-hooks 'org-after-promote-entry-hook))))
8133 (defun org-demote ()
8134 "Demote the current heading lower down the tree."
8135 (org-with-wide-buffer
8136 (org-back-to-heading t)
8137 (let* ((after-change-functions (remq 'flyspell-after-change-function
8138 after-change-functions))
8139 (level (save-match-data (funcall outline-level)))
8140 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8141 (diff (abs (- level (length down-head) -1))))
8142 (replace-match down-head nil t)
8143 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8144 (when org-adapt-indentation (org-fixup-indentation diff))
8145 (run-hooks 'org-after-demote-entry-hook))))
8147 (defun org-cycle-level ()
8148 "Cycle the level of an empty headline through possible states.
8149 This goes first to child, then to parent, level, then up the hierarchy.
8150 After top level, it switches back to sibling level."
8151 (interactive)
8152 (let ((org-adapt-indentation nil))
8153 (when (org-point-at-end-of-empty-headline)
8154 (setq this-command 'org-cycle-level) ; Only needed for caching
8155 (let ((cur-level (org-current-level))
8156 (prev-level (org-get-previous-line-level)))
8157 (cond
8158 ;; If first headline in file, promote to top-level.
8159 ((= prev-level 0)
8160 (loop repeat (/ (- cur-level 1) (org-level-increment))
8161 do (org-do-promote)))
8162 ;; If same level as prev, demote one.
8163 ((= prev-level cur-level)
8164 (org-do-demote))
8165 ;; If parent is top-level, promote to top level if not already.
8166 ((= prev-level 1)
8167 (loop repeat (/ (- cur-level 1) (org-level-increment))
8168 do (org-do-promote)))
8169 ;; If top-level, return to prev-level.
8170 ((= cur-level 1)
8171 (loop repeat (/ (- prev-level 1) (org-level-increment))
8172 do (org-do-demote)))
8173 ;; If less than prev-level, promote one.
8174 ((< cur-level prev-level)
8175 (org-do-promote))
8176 ;; If deeper than prev-level, promote until higher than
8177 ;; prev-level.
8178 ((> cur-level prev-level)
8179 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8180 do (org-do-promote))))
8181 t))))
8183 (defun org-map-tree (fun)
8184 "Call FUN for every heading underneath the current one."
8185 (org-back-to-heading)
8186 (let ((level (funcall outline-level)))
8187 (save-excursion
8188 (funcall fun)
8189 (while (and (progn
8190 (outline-next-heading)
8191 (> (funcall outline-level) level))
8192 (not (eobp)))
8193 (funcall fun)))))
8195 (defun org-map-region (fun beg end)
8196 "Call FUN for every heading between BEG and END."
8197 (let ((org-ignore-region t))
8198 (save-excursion
8199 (setq end (copy-marker end))
8200 (goto-char beg)
8201 (when (and (re-search-forward org-outline-regexp-bol nil t)
8202 (< (point) end))
8203 (funcall fun))
8204 (while (and (progn
8205 (outline-next-heading)
8206 (< (point) end))
8207 (not (eobp)))
8208 (funcall fun)))))
8210 (defun org-fixup-indentation (diff)
8211 "Change the indentation in the current entry by DIFF.
8213 DIFF is an integer. Indentation is done according to the
8214 following rules:
8216 - Planning information and property drawers are always indented
8217 according to the new level of the headline;
8219 - Footnote definitions and their contents are ignored;
8221 - Inlinetasks' boundaries are not shifted;
8223 - Empty lines are ignored;
8225 - Other lines' indentation are shifted by DIFF columns, unless
8226 it would introduce a structural change in the document, in
8227 which case no shifting is done at all.
8229 Assume point is at a heading or an inlinetask beginning."
8230 (org-with-wide-buffer
8231 (narrow-to-region (line-beginning-position)
8232 (save-excursion
8233 (if (org-with-limited-levels (org-at-heading-p))
8234 (org-with-limited-levels (outline-next-heading))
8235 (org-inlinetask-goto-end))
8236 (point)))
8237 (forward-line)
8238 ;; Indent properly planning info and property drawer.
8239 (when (org-looking-at-p org-planning-line-re)
8240 (org-indent-line)
8241 (forward-line))
8242 (when (looking-at org-property-drawer-re)
8243 (goto-char (match-end 0))
8244 (forward-line)
8245 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8246 (catch 'no-shift
8247 (when (zerop diff) (throw 'no-shift nil))
8248 ;; If DIFF is negative, first check if a shift is possible at all
8249 ;; (e.g., it doesn't break structure). This can only happen if
8250 ;; some contents are not properly indented.
8251 (let ((case-fold-search t))
8252 (when (< diff 0)
8253 (let ((diff (- diff))
8254 (forbidden-re (concat org-outline-regexp
8255 "\\|"
8256 (substring org-footnote-definition-re 1))))
8257 (save-excursion
8258 (while (not (eobp))
8259 (cond
8260 ((org-looking-at-p "[ \t]*$") (forward-line))
8261 ((and (org-looking-at-p org-footnote-definition-re)
8262 (let ((e (org-element-at-point)))
8263 (and (eq (org-element-type e) 'footnote-definition)
8264 (goto-char (org-element-property :end e))))))
8265 ((org-looking-at-p org-outline-regexp) (forward-line))
8266 ;; Give up if shifting would move before column 0 or
8267 ;; if it would introduce a headline or a footnote
8268 ;; definition.
8270 (skip-chars-forward " \t")
8271 (let ((ind (current-column)))
8272 (when (or (< ind diff)
8273 (and (= ind diff) (org-looking-at-p forbidden-re)))
8274 (throw 'no-shift nil)))
8275 ;; Ignore contents of example blocks and source
8276 ;; blocks if their indentation is meant to be
8277 ;; preserved. Jump to block's closing line.
8278 (beginning-of-line)
8279 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8280 (let ((e (org-element-at-point)))
8281 (and (memq (org-element-type e)
8282 '(example-block src-block))
8283 (or org-src-preserve-indentation
8284 (org-element-property :preserve-indent e))
8285 (goto-char (org-element-property :end e))
8286 (progn (skip-chars-backward " \r\t\n")
8287 (beginning-of-line)
8288 t))))
8289 (forward-line))))))))
8290 ;; Shift lines but footnote definitions, inlinetasks boundaries
8291 ;; by DIFF. Also skip contents of source or example blocks
8292 ;; when indentation is meant to be preserved.
8293 (while (not (eobp))
8294 (cond
8295 ((and (org-looking-at-p org-footnote-definition-re)
8296 (let ((e (org-element-at-point)))
8297 (and (eq (org-element-type e) 'footnote-definition)
8298 (goto-char (org-element-property :end e))))))
8299 ((org-looking-at-p org-outline-regexp) (forward-line))
8300 ((org-looking-at-p "[ \t]*$") (forward-line))
8302 (org-indent-line-to (+ (org-get-indentation) diff))
8303 (beginning-of-line)
8304 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8305 (let ((e (org-element-at-point)))
8306 (and (memq (org-element-type e)
8307 '(example-block src-block))
8308 (or org-src-preserve-indentation
8309 (org-element-property :preserve-indent e))
8310 (goto-char (org-element-property :end e))
8311 (progn (skip-chars-backward " \r\t\n")
8312 (beginning-of-line)
8313 t))))
8314 (forward-line)))))))))
8316 (defun org-convert-to-odd-levels ()
8317 "Convert an org-mode file with all levels allowed to one with odd levels.
8318 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8319 level 5 etc."
8320 (interactive)
8321 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8322 (let ((outline-level 'org-outline-level)
8323 (org-odd-levels-only nil) n)
8324 (save-excursion
8325 (goto-char (point-min))
8326 (while (re-search-forward "^\\*\\*+ " nil t)
8327 (setq n (- (length (match-string 0)) 2))
8328 (while (>= (setq n (1- n)) 0)
8329 (org-demote))
8330 (end-of-line 1))))))
8332 (defun org-convert-to-oddeven-levels ()
8333 "Convert an org-mode file with only odd levels to one with odd/even levels.
8334 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8335 file contains a section with an even level, conversion would
8336 destroy the structure of the file. An error is signaled in this
8337 case."
8338 (interactive)
8339 (goto-char (point-min))
8340 ;; First check if there are no even levels
8341 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8342 (org-show-set-visibility 'canonical)
8343 (error "Not all levels are odd in this file. Conversion not possible"))
8344 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8345 (let ((outline-regexp org-outline-regexp)
8346 (outline-level 'org-outline-level)
8347 (org-odd-levels-only nil) n)
8348 (save-excursion
8349 (goto-char (point-min))
8350 (while (re-search-forward "^\\*\\*+ " nil t)
8351 (setq n (/ (1- (length (match-string 0))) 2))
8352 (while (>= (setq n (1- n)) 0)
8353 (org-promote))
8354 (end-of-line 1))))))
8356 (defun org-tr-level (n)
8357 "Make N odd if required."
8358 (if org-odd-levels-only (1+ (/ n 2)) n))
8360 ;;; Vertical tree motion, cutting and pasting of subtrees
8362 (defun org-move-subtree-up (&optional arg)
8363 "Move the current subtree up past ARG headlines of the same level."
8364 (interactive "p")
8365 (org-move-subtree-down (- (prefix-numeric-value arg))))
8367 (defun org-move-subtree-down (&optional arg)
8368 "Move the current subtree down past ARG headlines of the same level."
8369 (interactive "p")
8370 (setq arg (prefix-numeric-value arg))
8371 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8372 'org-get-last-sibling))
8373 (ins-point (make-marker))
8374 (cnt (abs arg))
8375 (col (current-column))
8376 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8377 ;; Select the tree
8378 (org-back-to-heading)
8379 (setq beg0 (point))
8380 (save-excursion
8381 (setq ne-beg (org-back-over-empty-lines))
8382 (setq beg (point)))
8383 (save-match-data
8384 (save-excursion (outline-end-of-heading)
8385 (setq folded (outline-invisible-p)))
8386 (progn (org-end-of-subtree nil t)
8387 (unless (eobp) (backward-char))))
8388 (outline-next-heading)
8389 (setq ne-end (org-back-over-empty-lines))
8390 (setq end (point))
8391 (goto-char beg0)
8392 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8393 ;; include less whitespace
8394 (save-excursion
8395 (goto-char beg)
8396 (forward-line (- ne-beg ne-end))
8397 (setq beg (point))))
8398 ;; Find insertion point, with error handling
8399 (while (> cnt 0)
8400 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8401 (progn (goto-char beg0)
8402 (user-error "Cannot move past superior level or buffer limit")))
8403 (setq cnt (1- cnt)))
8404 (when (> arg 0)
8405 ;; Moving forward - still need to move over subtree
8406 (org-end-of-subtree t t)
8407 (save-excursion
8408 (org-back-over-empty-lines)
8409 (or (bolp) (newline))))
8410 (setq ne-ins (org-back-over-empty-lines))
8411 (move-marker ins-point (point))
8412 (setq txt (buffer-substring beg end))
8413 (org-save-markers-in-region beg end)
8414 (delete-region beg end)
8415 (org-remove-empty-overlays-at beg)
8416 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8417 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8418 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8419 (let ((bbb (point)))
8420 (insert-before-markers txt)
8421 (org-reinstall-markers-in-region bbb)
8422 (move-marker ins-point bbb))
8423 (or (bolp) (insert "\n"))
8424 (setq ins-end (point))
8425 (goto-char ins-point)
8426 (org-skip-whitespace)
8427 (when (and (< arg 0)
8428 (org-first-sibling-p)
8429 (> ne-ins ne-beg))
8430 ;; Move whitespace back to beginning
8431 (save-excursion
8432 (goto-char ins-end)
8433 (let ((kill-whole-line t))
8434 (kill-line (- ne-ins ne-beg)) (point)))
8435 (insert (make-string (- ne-ins ne-beg) ?\n)))
8436 (move-marker ins-point nil)
8437 (if folded
8438 (outline-hide-subtree)
8439 (org-show-entry)
8440 (org-show-children)
8441 (org-cycle-hide-drawers 'children))
8442 (org-clean-visibility-after-subtree-move)
8443 ;; move back to the initial column we were at
8444 (move-to-column col)))
8446 (defvar org-subtree-clip ""
8447 "Clipboard for cut and paste of subtrees.
8448 This is actually only a copy of the kill, because we use the normal kill
8449 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8451 (defvar org-subtree-clip-folded nil
8452 "Was the last copied subtree folded?
8453 This is used to fold the tree back after pasting.")
8455 (defun org-cut-subtree (&optional n)
8456 "Cut the current subtree into the clipboard.
8457 With prefix arg N, cut this many sequential subtrees.
8458 This is a short-hand for marking the subtree and then cutting it."
8459 (interactive "p")
8460 (org-copy-subtree n 'cut))
8462 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8463 "Copy the current subtree it in the clipboard.
8464 With prefix arg N, copy this many sequential subtrees.
8465 This is a short-hand for marking the subtree and then copying it.
8466 If CUT is non-nil, actually cut the subtree.
8467 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8468 of some markers in the region, even if CUT is non-nil. This is
8469 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8470 (interactive "p")
8471 (let (beg end folded (beg0 (point)))
8472 (if (org-called-interactively-p 'any)
8473 (org-back-to-heading nil) ; take what looks like a subtree
8474 (org-back-to-heading t)) ; take what is really there
8475 (setq beg (point))
8476 (skip-chars-forward " \t\r\n")
8477 (save-match-data
8478 (if nosubtrees
8479 (outline-next-heading)
8480 (save-excursion (outline-end-of-heading)
8481 (setq folded (outline-invisible-p)))
8482 (ignore-errors (org-forward-heading-same-level (1- n) t))
8483 (org-end-of-subtree t t)))
8484 ;; Include the end of an inlinetask
8485 (when (and (featurep 'org-inlinetask)
8486 (looking-at-p (concat (org-inlinetask-outline-regexp)
8487 "END[ \t]*$")))
8488 (end-of-line))
8489 (setq end (point))
8490 (goto-char beg0)
8491 (when (> end beg)
8492 (setq org-subtree-clip-folded folded)
8493 (when (or cut force-store-markers)
8494 (org-save-markers-in-region beg end))
8495 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8496 (setq org-subtree-clip (current-kill 0))
8497 (message "%s: Subtree(s) with %d characters"
8498 (if cut "Cut" "Copied")
8499 (length org-subtree-clip)))))
8501 (defun org-paste-subtree (&optional level tree for-yank remove)
8502 "Paste the clipboard as a subtree, with modification of headline level.
8503 The entire subtree is promoted or demoted in order to match a new headline
8504 level.
8506 If the cursor is at the beginning of a headline, the same level as
8507 that headline is used to paste the tree.
8509 If not, the new level is derived from the *visible* headings
8510 before and after the insertion point, and taken to be the inferior headline
8511 level of the two. So if the previous visible heading is level 3 and the
8512 next is level 4 (or vice versa), level 4 will be used for insertion.
8513 This makes sure that the subtree remains an independent subtree and does
8514 not swallow low level entries.
8516 You can also force a different level, either by using a numeric prefix
8517 argument, or by inserting the heading marker by hand. For example, if the
8518 cursor is after \"*****\", then the tree will be shifted to level 5.
8520 If optional TREE is given, use this text instead of the kill ring.
8522 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8523 move back over whitespace before inserting, and move point to the end of
8524 the inserted text when done.
8526 When REMOVE is non-nil, remove the subtree from the clipboard."
8527 (interactive "P")
8528 (setq tree (or tree (and kill-ring (current-kill 0))))
8529 (unless (org-kill-is-subtree-p tree)
8530 (user-error "%s"
8531 (substitute-command-keys
8532 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8533 (org-with-limited-levels
8534 (let* ((visp (not (outline-invisible-p)))
8535 (txt tree)
8536 (^re_ "\\(\\*+\\)[ \t]*")
8537 (old-level (if (string-match org-outline-regexp-bol txt)
8538 (- (match-end 0) (match-beginning 0) 1)
8539 -1))
8540 (force-level (cond (level (prefix-numeric-value level))
8541 ((and (looking-at "[ \t]*$")
8542 (string-match
8543 "^\\*+$" (buffer-substring
8544 (point-at-bol) (point))))
8545 (- (match-end 0) (match-beginning 0)))
8546 ((and (bolp)
8547 (looking-at org-outline-regexp))
8548 (- (match-end 0) (point) 1))))
8549 (previous-level (save-excursion
8550 (condition-case nil
8551 (progn
8552 (outline-previous-visible-heading 1)
8553 (if (looking-at ^re_)
8554 (- (match-end 0) (match-beginning 0) 1)
8556 (error 1))))
8557 (next-level (save-excursion
8558 (condition-case nil
8559 (progn
8560 (or (looking-at org-outline-regexp)
8561 (outline-next-visible-heading 1))
8562 (if (looking-at ^re_)
8563 (- (match-end 0) (match-beginning 0) 1)
8565 (error 1))))
8566 (new-level (or force-level (max previous-level next-level)))
8567 (shift (if (or (= old-level -1)
8568 (= new-level -1)
8569 (= old-level new-level))
8571 (- new-level old-level)))
8572 (delta (if (> shift 0) -1 1))
8573 (func (if (> shift 0) 'org-demote 'org-promote))
8574 (org-odd-levels-only nil)
8575 beg end newend)
8576 ;; Remove the forced level indicator
8577 (when force-level
8578 (delete-region (point-at-bol) (point)))
8579 ;; Paste
8580 (beginning-of-line (if (bolp) 1 2))
8581 (setq beg (point))
8582 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8583 (insert-before-markers txt)
8584 (unless (string-match "\n\\'" txt) (insert "\n"))
8585 (setq newend (point))
8586 (org-reinstall-markers-in-region beg)
8587 (setq end (point))
8588 (goto-char beg)
8589 (skip-chars-forward " \t\n\r")
8590 (setq beg (point))
8591 (when (and (outline-invisible-p) visp)
8592 (save-excursion (outline-show-heading)))
8593 ;; Shift if necessary
8594 (unless (= shift 0)
8595 (save-restriction
8596 (narrow-to-region beg end)
8597 (while (not (= shift 0))
8598 (org-map-region func (point-min) (point-max))
8599 (setq shift (+ delta shift)))
8600 (goto-char (point-min))
8601 (setq newend (point-max))))
8602 (when (or (org-called-interactively-p 'interactive) for-yank)
8603 (message "Clipboard pasted as level %d subtree" new-level))
8604 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8605 kill-ring
8606 (eq org-subtree-clip (current-kill 0))
8607 org-subtree-clip-folded)
8608 ;; The tree was folded before it was killed/copied
8609 (outline-hide-subtree))
8610 (and for-yank (goto-char newend))
8611 (and remove (setq kill-ring (cdr kill-ring))))))
8613 (defun org-kill-is-subtree-p (&optional txt)
8614 "Check if the current kill is an outline subtree, or a set of trees.
8615 Returns nil if kill does not start with a headline, or if the first
8616 headline level is not the largest headline level in the tree.
8617 So this will actually accept several entries of equal levels as well,
8618 which is OK for `org-paste-subtree'.
8619 If optional TXT is given, check this string instead of the current kill."
8620 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8621 (re (org-get-limited-outline-regexp))
8622 (^re (concat "^" re))
8623 (start-level (and kill
8624 (string-match
8625 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8626 kill)
8627 (- (match-end 2) (match-beginning 2) 1)))
8628 (start (1+ (or (match-beginning 2) -1))))
8629 (if (not start-level)
8630 (progn
8631 nil) ;; does not even start with a heading
8632 (catch 'exit
8633 (while (setq start (string-match ^re kill (1+ start)))
8634 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8635 (throw 'exit nil)))
8636 t))))
8638 (defvar org-markers-to-move nil
8639 "Markers that should be moved with a cut-and-paste operation.
8640 Those markers are stored together with their positions relative to
8641 the start of the region.")
8643 (defun org-save-markers-in-region (beg end)
8644 "Check markers in region.
8645 If these markers are between BEG and END, record their position relative
8646 to BEG, so that after moving the block of text, we can put the markers back
8647 into place.
8648 This function gets called just before an entry or tree gets cut from the
8649 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8650 called immediately, to move the markers with the entries."
8651 (setq org-markers-to-move nil)
8652 (when (featurep 'org-clock)
8653 (org-clock-save-markers-for-cut-and-paste beg end))
8654 (when (featurep 'org-agenda)
8655 (org-agenda-save-markers-for-cut-and-paste beg end)))
8657 (defun org-check-and-save-marker (marker beg end)
8658 "Check if MARKER is between BEG and END.
8659 If yes, remember the marker and the distance to BEG."
8660 (when (and (marker-buffer marker)
8661 (equal (marker-buffer marker) (current-buffer))
8662 (>= marker beg) (< marker end))
8663 (push (cons marker (- marker beg)) org-markers-to-move)))
8665 (defun org-reinstall-markers-in-region (beg)
8666 "Move all remembered markers to their position relative to BEG."
8667 (mapc (lambda (x)
8668 (move-marker (car x) (+ beg (cdr x))))
8669 org-markers-to-move)
8670 (setq org-markers-to-move nil))
8672 (defun org-narrow-to-subtree ()
8673 "Narrow buffer to the current subtree."
8674 (interactive)
8675 (save-excursion
8676 (save-match-data
8677 (org-with-limited-levels
8678 (narrow-to-region
8679 (progn (org-back-to-heading t) (point))
8680 (progn (org-end-of-subtree t t)
8681 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8682 (point)))))))
8684 (defun org-narrow-to-block ()
8685 "Narrow buffer to the current block."
8686 (interactive)
8687 (let* ((case-fold-search t)
8688 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8689 "^[ \t]*#\\+end_.*")))
8690 (if blockp
8691 (narrow-to-region (car blockp) (cdr blockp))
8692 (user-error "Not in a block"))))
8694 (defun org-clone-subtree-with-time-shift (n &optional shift)
8695 "Clone the task (subtree) at point N times.
8696 The clones will be inserted as siblings.
8698 In interactive use, the user will be prompted for the number of
8699 clones to be produced. If the entry has a timestamp, the user
8700 will also be prompted for a time shift, which may be a repeater
8701 as used in time stamps, for example `+3d'. To disable this,
8702 you can call the function with a universal prefix argument.
8704 When a valid repeater is given and the entry contains any time
8705 stamps, the clones will become a sequence in time, with time
8706 stamps in the subtree shifted for each clone produced. If SHIFT
8707 is nil or the empty string, time stamps will be left alone. The
8708 ID property of the original subtree is removed.
8710 If the original subtree did contain time stamps with a repeater,
8711 the following will happen:
8712 - the repeater will be removed in each clone
8713 - an additional clone will be produced, with the current, unshifted
8714 date(s) in the entry.
8715 - the original entry will be placed *after* all the clones, with
8716 repeater intact.
8717 - the start days in the repeater in the original entry will be shifted
8718 to past the last clone.
8719 In this way you can spell out a number of instances of a repeating task,
8720 and still retain the repeater to cover future instances of the task.
8722 As described above, N+1 clones are produced when the original
8723 subtree has a repeater. Setting N to 0, then, can be used to
8724 remove the repeater from a subtree and create a shifted clone
8725 with the original repeater."
8726 (interactive "nNumber of clones to produce: ")
8727 (let ((shift
8728 (or shift
8729 (if (and (not (equal current-prefix-arg '(4)))
8730 (save-excursion
8731 (re-search-forward org-ts-regexp-both
8732 (save-excursion
8733 (org-end-of-subtree t)
8734 (point)) t)))
8735 (read-from-minibuffer
8736 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8737 ""))) ;; No time shift
8738 (n-no-remove -1)
8739 (drawer-re org-drawer-regexp)
8740 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8741 beg end template task idprop
8742 shift-n shift-what doshift nmin nmax)
8743 (unless (wholenump n)
8744 (user-error "Invalid number of replications %s" n))
8745 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8746 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8747 shift)))
8748 (user-error "Invalid shift specification %s" shift))
8749 (when doshift
8750 (setq shift-n (string-to-number (match-string 1 shift))
8751 shift-what (cdr (assoc (match-string 2 shift)
8752 '(("d" . day) ("w" . week)
8753 ("m" . month) ("y" . year))))))
8754 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8755 (setq nmin 1 nmax n)
8756 (org-back-to-heading t)
8757 (setq beg (point))
8758 (setq idprop (org-entry-get nil "ID"))
8759 (org-end-of-subtree t t)
8760 (or (bolp) (insert "\n"))
8761 (setq end (point))
8762 (setq template (buffer-substring beg end))
8763 (when (and doshift
8764 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8765 (delete-region beg end)
8766 (setq end beg)
8767 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8768 (goto-char end)
8769 (loop for n from nmin to nmax do
8770 ;; prepare clone
8771 (with-temp-buffer
8772 (insert template)
8773 (org-mode)
8774 (goto-char (point-min))
8775 (org-show-subtree)
8776 (and idprop (if org-clone-delete-id
8777 (org-entry-delete nil "ID")
8778 (org-id-get-create t)))
8779 (unless (= n 0)
8780 (while (re-search-forward org-clock-re nil t)
8781 (kill-whole-line))
8782 (goto-char (point-min))
8783 (while (re-search-forward drawer-re nil t)
8784 (org-remove-empty-drawer-at (point))))
8785 (goto-char (point-min))
8786 (when doshift
8787 (while (re-search-forward org-ts-regexp-both nil t)
8788 (org-timestamp-change (* n shift-n) shift-what))
8789 (unless (= n n-no-remove)
8790 (goto-char (point-min))
8791 (while (re-search-forward org-ts-regexp nil t)
8792 (save-excursion
8793 (goto-char (match-beginning 0))
8794 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8795 (delete-region (match-beginning 1) (match-end 1)))))))
8796 (setq task (buffer-string)))
8797 (insert task))
8798 (goto-char beg)))
8800 ;;; Outline Sorting
8802 (defun org-sort (with-case)
8803 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8804 Optional argument WITH-CASE means sort case-sensitively."
8805 (interactive "P")
8806 (cond
8807 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8808 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8810 (org-call-with-arg 'org-sort-entries with-case))))
8812 (defun org-sort-remove-invisible (s)
8813 "Remove invisible links from string S."
8814 (remove-text-properties 0 (length s) org-rm-props s)
8815 (while (string-match org-bracket-link-regexp s)
8816 (setq s (replace-match (if (match-end 2)
8817 (match-string 3 s)
8818 (match-string 1 s))
8819 t t s)))
8820 (let ((st (format " %s " s)))
8821 (while (string-match org-emph-re st)
8822 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8823 (setq s (substring st 1 -1)))
8826 (defvar org-priority-regexp) ; defined later in the file
8828 (defvar org-after-sorting-entries-or-items-hook nil
8829 "Hook that is run after a bunch of entries or items have been sorted.
8830 When children are sorted, the cursor is in the parent line when this
8831 hook gets called. When a region or a plain list is sorted, the cursor
8832 will be in the first entry of the sorted region/list.")
8834 (defun org-sort-entries
8835 (&optional with-case sorting-type getkey-func compare-func property)
8836 "Sort entries on a certain level of an outline tree.
8837 If there is an active region, the entries in the region are sorted.
8838 Else, if the cursor is before the first entry, sort the top-level items.
8839 Else, the children of the entry at point are sorted.
8841 Sorting can be alphabetically, numerically, by date/time as given by
8842 a time stamp, by a property, by priority order, or by a custom function.
8844 The command prompts for the sorting type unless it has been given to the
8845 function through the SORTING-TYPE argument, which needs to be a character,
8846 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8847 the precise meaning of each character:
8849 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8850 c By creation time, which is assumed to be the first inactive time stamp
8851 at the beginning of a line.
8852 d By deadline date/time.
8853 k By clocking time.
8854 n Numerically, by converting the beginning of the entry/item to a number.
8855 o By order of TODO keywords.
8856 p By priority according to the cookie.
8857 r By the value of a property.
8858 s By scheduled date/time.
8859 t By date/time, either the first active time stamp in the entry, or, if
8860 none exist, by the first inactive one.
8862 Capital letters will reverse the sort order.
8864 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8865 called with point at the beginning of the record. It must return either
8866 a string or a number that should serve as the sorting key for that record.
8868 Comparing entries ignores case by default. However, with an optional argument
8869 WITH-CASE, the sorting considers case as well.
8871 Sorting is done against the visible part of the headlines, it ignores hidden
8872 links.
8874 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8875 (interactive "P")
8876 (let ((case-func (if with-case 'identity 'downcase))
8877 (cmstr
8878 ;; The clock marker is lost when using `sort-subr', let's
8879 ;; store the clocking string.
8880 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8881 (save-excursion
8882 (goto-char org-clock-marker)
8883 (buffer-substring-no-properties (line-beginning-position)
8884 (point)))))
8885 start beg end stars re re2
8886 txt what tmp)
8887 ;; Find beginning and end of region to sort
8888 (cond
8889 ((org-region-active-p)
8890 ;; we will sort the region
8891 (setq end (region-end)
8892 what "region")
8893 (goto-char (region-beginning))
8894 (unless (org-at-heading-p) (outline-next-heading))
8895 (setq start (point)))
8896 ((or (org-at-heading-p)
8897 (ignore-errors (progn (org-back-to-heading) t)))
8898 ;; we will sort the children of the current headline
8899 (org-back-to-heading)
8900 (setq start (point)
8901 end (progn (org-end-of-subtree t t)
8902 (or (bolp) (insert "\n"))
8903 (when (>= (org-back-over-empty-lines) 1)
8904 (forward-line 1))
8905 (point))
8906 what "children")
8907 (goto-char start)
8908 (outline-show-subtree)
8909 (outline-next-heading))
8911 ;; we will sort the top-level entries in this file
8912 (goto-char (point-min))
8913 (or (org-at-heading-p) (outline-next-heading))
8914 (setq start (point))
8915 (goto-char (point-max))
8916 (beginning-of-line 1)
8917 (when (looking-at ".*?\\S-")
8918 ;; File ends in a non-white line
8919 (end-of-line 1)
8920 (insert "\n"))
8921 (setq end (point-max))
8922 (setq what "top-level")
8923 (goto-char start)
8924 (outline-show-all)))
8926 (setq beg (point))
8927 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8929 (looking-at "\\(\\*+\\)")
8930 (setq stars (match-string 1)
8931 re (concat "^" (regexp-quote stars) " +")
8932 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8933 txt (buffer-substring beg end))
8934 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8935 (when (and (not (equal stars "*")) (string-match re2 txt))
8936 (user-error "Region to sort contains a level above the first entry"))
8938 (unless sorting-type
8939 (message
8940 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8941 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8942 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8943 what)
8944 (setq sorting-type (read-char-exclusive))
8946 (unless getkey-func
8947 (and (= (downcase sorting-type) ?f)
8948 (setq getkey-func
8949 (org-icompleting-read "Sort using function: "
8950 obarray 'fboundp t nil nil))
8951 (setq getkey-func (intern getkey-func))))
8953 (and (= (downcase sorting-type) ?r)
8954 (not property)
8955 (setq property
8956 (org-icompleting-read "Property: "
8957 (mapcar 'list (org-buffer-property-keys t))
8958 nil t))))
8960 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8961 (message "Sorting entries...")
8963 (save-restriction
8964 (narrow-to-region start end)
8965 (let ((dcst (downcase sorting-type))
8966 (case-fold-search nil)
8967 (now (current-time)))
8968 (sort-subr
8969 (/= dcst sorting-type)
8970 ;; This function moves to the beginning character of the "record" to
8971 ;; be sorted.
8972 (lambda nil
8973 (if (re-search-forward re nil t)
8974 (goto-char (match-beginning 0))
8975 (goto-char (point-max))))
8976 ;; This function moves to the last character of the "record" being
8977 ;; sorted.
8978 (lambda nil
8979 (save-match-data
8980 (condition-case nil
8981 (outline-forward-same-level 1)
8982 (error
8983 (goto-char (point-max))))))
8984 ;; This function returns the value that gets sorted against.
8985 (lambda nil
8986 (cond
8987 ((= dcst ?n)
8988 (if (looking-at org-complex-heading-regexp)
8989 (string-to-number (org-sort-remove-invisible (match-string 4)))
8990 nil))
8991 ((= dcst ?a)
8992 (if (looking-at org-complex-heading-regexp)
8993 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8994 nil))
8995 ((= dcst ?k)
8996 (or (get-text-property (point) :org-clock-minutes) 0))
8997 ((= dcst ?t)
8998 (let ((end (save-excursion (outline-next-heading) (point))))
8999 (if (or (re-search-forward org-ts-regexp end t)
9000 (re-search-forward org-ts-regexp-both end t))
9001 (org-time-string-to-seconds (match-string 0))
9002 (org-float-time now))))
9003 ((= dcst ?c)
9004 (let ((end (save-excursion (outline-next-heading) (point))))
9005 (if (re-search-forward
9006 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9007 end t)
9008 (org-time-string-to-seconds (match-string 0))
9009 (org-float-time now))))
9010 ((= dcst ?s)
9011 (let ((end (save-excursion (outline-next-heading) (point))))
9012 (if (re-search-forward org-scheduled-time-regexp end t)
9013 (org-time-string-to-seconds (match-string 1))
9014 (org-float-time now))))
9015 ((= dcst ?d)
9016 (let ((end (save-excursion (outline-next-heading) (point))))
9017 (if (re-search-forward org-deadline-time-regexp end t)
9018 (org-time-string-to-seconds (match-string 1))
9019 (org-float-time now))))
9020 ((= dcst ?p)
9021 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9022 (string-to-char (match-string 2))
9023 org-default-priority))
9024 ((= dcst ?r)
9025 (or (org-entry-get nil property) ""))
9026 ((= dcst ?o)
9027 (when (looking-at org-complex-heading-regexp)
9028 (let* ((m (match-string 2))
9029 (s (if (member m org-done-keywords) '- '+)))
9030 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9031 ((= dcst ?f)
9032 (if getkey-func
9033 (progn
9034 (setq tmp (funcall getkey-func))
9035 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9036 tmp)
9037 (error "Invalid key function `%s'" getkey-func)))
9038 (t (error "Invalid sorting type `%c'" sorting-type))))
9040 (cond
9041 ((= dcst ?a) 'string<)
9042 ((= dcst ?f) compare-func)
9043 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9044 (run-hooks 'org-after-sorting-entries-or-items-hook)
9045 ;; Reset the clock marker if needed
9046 (when cmstr
9047 (save-excursion
9048 (goto-char start)
9049 (search-forward cmstr nil t)
9050 (move-marker org-clock-marker (point))))
9051 (message "Sorting entries...done")))
9053 ;;; The orgstruct minor mode
9055 ;; Define a minor mode which can be used in other modes in order to
9056 ;; integrate the org-mode structure editing commands.
9058 ;; This is really a hack, because the org-mode structure commands use
9059 ;; keys which normally belong to the major mode. Here is how it
9060 ;; works: The minor mode defines all the keys necessary to operate the
9061 ;; structure commands, but wraps the commands into a function which
9062 ;; tests if the cursor is currently at a headline or a plain list
9063 ;; item. If that is the case, the structure command is used,
9064 ;; temporarily setting many Org-mode variables like regular
9065 ;; expressions for filling etc. However, when any of those keys is
9066 ;; used at a different location, function uses `key-binding' to look
9067 ;; up if the key has an associated command in another currently active
9068 ;; keymap (minor modes, major mode, global), and executes that
9069 ;; command. There might be problems if any of the keys is otherwise
9070 ;; used as a prefix key.
9072 (defcustom orgstruct-heading-prefix-regexp ""
9073 "Regexp that matches the custom prefix of Org headlines in
9074 orgstruct(++)-mode."
9075 :group 'org
9076 :version "24.4"
9077 :package-version '(Org . "8.3")
9078 :type 'regexp)
9079 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9081 (defcustom orgstruct-setup-hook nil
9082 "Hook run after orgstruct-mode-map is filled."
9083 :group 'org
9084 :version "24.4"
9085 :package-version '(Org . "8.0")
9086 :type 'hook)
9088 (defvar orgstruct-initialized nil)
9090 (defvar org-local-vars nil
9091 "List of local variables, for use by `orgstruct-mode'.")
9093 ;;;###autoload
9094 (define-minor-mode orgstruct-mode
9095 "Toggle the minor mode `orgstruct-mode'.
9096 This mode is for using Org-mode structure commands in other
9097 modes. The following keys behave as if Org-mode were active, if
9098 the cursor is on a headline, or on a plain list item (both as
9099 defined by Org-mode)."
9100 nil " OrgStruct" (make-sparse-keymap)
9101 (funcall (if orgstruct-mode
9102 'add-to-invisibility-spec
9103 'remove-from-invisibility-spec)
9104 '(outline . t))
9105 (when orgstruct-mode
9106 (org-load-modules-maybe)
9107 (unless orgstruct-initialized
9108 (orgstruct-setup)
9109 (setq orgstruct-initialized t))))
9111 ;;;###autoload
9112 (defun turn-on-orgstruct ()
9113 "Unconditionally turn on `orgstruct-mode'."
9114 (orgstruct-mode 1))
9116 (defvar-local orgstruct-is-++ nil
9117 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9118 (defvar-local org-fb-vars nil)
9119 (defun orgstruct++-mode (&optional arg)
9120 "Toggle `orgstruct-mode', the enhanced version of it.
9121 In addition to setting orgstruct-mode, this also exports all
9122 indentation and autofilling variables from org-mode into the
9123 buffer. It will also recognize item context in multiline items."
9124 (interactive "P")
9125 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9126 (if (< arg 1)
9127 (progn (orgstruct-mode -1)
9128 (mapc (lambda(v)
9129 (set (make-local-variable (car v))
9130 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9131 org-fb-vars))
9132 (orgstruct-mode 1)
9133 (setq org-fb-vars nil)
9134 (unless org-local-vars
9135 (setq org-local-vars (org-get-local-variables)))
9136 (let (var val)
9137 (mapc
9138 (lambda (x)
9139 (when (string-match
9140 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9141 (symbol-name (car x)))
9142 (setq var (car x) val (nth 1 x))
9143 (push (list var `(quote ,(eval var))) org-fb-vars)
9144 (set (make-local-variable var)
9145 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9146 org-local-vars)
9147 (setq-local orgstruct-is-++ t))))
9149 ;;;###autoload
9150 (defun turn-on-orgstruct++ ()
9151 "Unconditionally turn on `orgstruct++-mode'."
9152 (orgstruct++-mode 1))
9154 (defun orgstruct-error ()
9155 "Error when there is no default binding for a structure key."
9156 (interactive)
9157 (funcall (if (fboundp 'user-error)
9158 'user-error
9159 'error)
9160 "This key has no function outside structure elements"))
9162 (defun orgstruct-setup ()
9163 "Setup orgstruct keymap."
9164 (dolist (cell '((org-demote . t)
9165 (org-metaleft . t)
9166 (org-metaright . t)
9167 (org-promote . t)
9168 (org-shiftmetaleft . t)
9169 (org-shiftmetaright . t)
9170 org-backward-element
9171 org-backward-heading-same-level
9172 org-ctrl-c-ret
9173 org-ctrl-c-minus
9174 org-ctrl-c-star
9175 org-cycle
9176 org-forward-heading-same-level
9177 org-insert-heading
9178 org-insert-heading-respect-content
9179 org-kill-note-or-show-branches
9180 org-mark-subtree
9181 org-meta-return
9182 org-metadown
9183 org-metaup
9184 org-narrow-to-subtree
9185 org-promote-subtree
9186 org-reveal
9187 org-shiftdown
9188 org-shiftleft
9189 org-shiftmetadown
9190 org-shiftmetaup
9191 org-shiftright
9192 org-shifttab
9193 org-shifttab
9194 org-shiftup
9195 org-show-children
9196 org-show-subtree
9197 org-sort
9198 org-up-element
9199 outline-demote
9200 outline-next-visible-heading
9201 outline-previous-visible-heading
9202 outline-promote
9203 outline-up-heading))
9204 (let ((f (or (car-safe cell) cell))
9205 (disable-when-heading-prefix (cdr-safe cell)))
9206 (when (fboundp f)
9207 (let ((new-bindings))
9208 (dolist (binding (nconc (where-is-internal f org-mode-map)
9209 (where-is-internal f outline-mode-map)))
9210 (push binding new-bindings)
9211 ;; TODO use local-function-key-map
9212 (dolist (rep '(("<tab>" . "TAB")
9213 ("<return>" . "RET")
9214 ("<escape>" . "ESC")
9215 ("<delete>" . "DEL")))
9216 (setq binding (read-kbd-macro
9217 (let ((case-fold-search))
9218 (replace-regexp-in-string
9219 (regexp-quote (cdr rep))
9220 (car rep)
9221 (key-description binding)))))
9222 (pushnew binding new-bindings :test 'equal)))
9223 (dolist (binding new-bindings)
9224 (let ((key (lookup-key orgstruct-mode-map binding)))
9225 (when (or (not key) (numberp key))
9226 (ignore-errors
9227 (org-defkey orgstruct-mode-map
9228 binding
9229 (orgstruct-make-binding
9230 f binding disable-when-heading-prefix))))))))))
9231 (run-hooks 'orgstruct-setup-hook))
9233 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9234 "Create a function for binding in the structure minor mode.
9235 FUN is the command to call inside a table. KEY is the key that
9236 should be checked in for a command to execute outside of tables.
9237 Non-nil `disable-when-heading-prefix' means to disable the command
9238 if `orgstruct-heading-prefix-regexp' is not empty."
9239 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9240 (let ((nname name)
9241 (i 0))
9242 (while (fboundp (intern nname))
9243 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9244 (setq name (intern nname)))
9245 (eval
9246 (let ((bindings '((org-heading-regexp
9247 (concat "^"
9248 orgstruct-heading-prefix-regexp
9249 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9250 (org-outline-regexp
9251 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9252 (org-outline-regexp-bol
9253 (concat "^" org-outline-regexp))
9254 (outline-regexp org-outline-regexp)
9255 (outline-heading-end-regexp "\n")
9256 (outline-level 'org-outline-level)
9257 (outline-heading-alist))))
9258 `(defun ,name (arg)
9259 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9260 "Outside of structure, run the binding of `"
9261 (key-description key) "'."
9262 (when disable-when-heading-prefix
9263 (concat
9264 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9265 "back to the default binding due to limitations of Org's implementation of\n"
9266 "`" (symbol-name fun) "'.")))
9267 (interactive "p")
9268 (let* ((disable
9269 ,(and disable-when-heading-prefix
9270 '(not (string= orgstruct-heading-prefix-regexp ""))))
9271 (fallback
9272 (or disable
9273 (not
9274 (let* ,bindings
9275 (org-context-p 'headline 'item
9276 ,(when (memq fun
9277 '(org-insert-heading
9278 org-insert-heading-respect-content
9279 org-meta-return))
9280 '(when orgstruct-is-++
9281 'item-body))))))))
9282 (if fallback
9283 (let* ((orgstruct-mode)
9284 (binding
9285 (let ((key ,key))
9286 (catch 'exit
9287 (dolist
9288 (rep
9289 '(nil
9290 ("<\\([^>]*\\)tab>" . "\\1TAB")
9291 ("<\\([^>]*\\)return>" . "\\1RET")
9292 ("<\\([^>]*\\)escape>" . "\\1ESC")
9293 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9294 nil)
9295 (when rep
9296 (setq key (read-kbd-macro
9297 (let ((case-fold-search))
9298 (replace-regexp-in-string
9299 (car rep)
9300 (cdr rep)
9301 (key-description key))))))
9302 (when (key-binding key)
9303 (throw 'exit (key-binding key))))))))
9304 (if (keymapp binding)
9305 (org-set-transient-map binding)
9306 (let ((func (or binding
9307 (unless disable
9308 'orgstruct-error))))
9309 (when func
9310 (call-interactively func)))))
9311 (org-run-like-in-org-mode
9312 (lambda ()
9313 (interactive)
9314 (let* ,bindings
9315 (call-interactively ',fun)))))))))
9316 name))
9318 (defun org-contextualize-keys (alist contexts)
9319 "Return valid elements in ALIST depending on CONTEXTS.
9321 `org-agenda-custom-commands' or `org-capture-templates' are the
9322 values used for ALIST, and `org-agenda-custom-commands-contexts'
9323 or `org-capture-templates-contexts' are the associated contexts
9324 definitions."
9325 (let ((contexts
9326 ;; normalize contexts
9327 (mapcar
9328 (lambda(c) (cond ((listp (cadr c))
9329 (list (car c) (car c) (cadr c)))
9330 ((string= "" (cadr c))
9331 (list (car c) (car c) (caddr c)))
9332 (t c)))
9333 contexts))
9334 (a alist) r s)
9335 ;; loop over all commands or templates
9336 (dolist (c a)
9337 (let (vrules repl)
9338 (cond
9339 ((not (assoc (car c) contexts))
9340 (push c r))
9341 ((and (assoc (car c) contexts)
9342 (setq vrules (org-contextualize-validate-key
9343 (car c) contexts)))
9344 (mapc (lambda (vr)
9345 (unless (equal (car vr) (cadr vr))
9346 (setq repl vr)))
9347 vrules)
9348 (if (not repl) (push c r)
9349 (push (cadr repl) s)
9350 (push
9351 (cons (car c)
9352 (cdr (or (assoc (cadr repl) alist)
9353 (error "Undefined key `%s' as contextual replacement for `%s'"
9354 (cadr repl) (car c)))))
9355 r))))))
9356 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9357 (delq
9359 (delete-dups
9360 (mapcar (lambda (x)
9361 (let ((tpl (car x)))
9362 (unless (delq
9364 (mapcar (lambda (y)
9365 (equal y tpl))
9367 x)))
9368 (reverse r))))))
9370 (defun org-contextualize-validate-key (key contexts)
9371 "Check CONTEXTS for agenda or capture KEY."
9372 (let (rr res)
9373 (dolist (r contexts)
9374 (mapc
9375 (lambda (rr)
9376 (when
9377 (and (equal key (car r))
9378 (if (functionp rr) (funcall rr)
9379 (or (and (eq (car rr) 'in-file)
9380 (buffer-file-name)
9381 (string-match (cdr rr) (buffer-file-name)))
9382 (and (eq (car rr) 'in-mode)
9383 (string-match (cdr rr) (symbol-name major-mode)))
9384 (and (eq (car rr) 'in-buffer)
9385 (string-match (cdr rr) (buffer-name)))
9386 (when (and (eq (car rr) 'not-in-file)
9387 (buffer-file-name))
9388 (not (string-match (cdr rr) (buffer-file-name))))
9389 (when (eq (car rr) 'not-in-mode)
9390 (not (string-match (cdr rr) (symbol-name major-mode))))
9391 (when (eq (car rr) 'not-in-buffer)
9392 (not (string-match (cdr rr) (buffer-name)))))))
9393 (push r res)))
9394 (car (last r))))
9395 (delete-dups (delq nil res))))
9397 (defun org-context-p (&rest contexts)
9398 "Check if local context is any of CONTEXTS.
9399 Possible values in the list of contexts are `table', `headline', and `item'."
9400 (let ((pos (point)))
9401 (goto-char (point-at-bol))
9402 (prog1 (or (and (memq 'table contexts)
9403 (looking-at "[ \t]*|"))
9404 (and (memq 'headline contexts)
9405 (looking-at org-outline-regexp))
9406 (and (memq 'item contexts)
9407 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9408 (and (memq 'item-body contexts)
9409 (org-in-item-p)))
9410 (goto-char pos))))
9412 (defconst org-unique-local-variables
9413 '(org-element--cache
9414 org-element--cache-objects
9415 org-element--cache-sync-keys
9416 org-element--cache-sync-requests
9417 org-element--cache-sync-timer)
9418 "List of local variables that cannot be transferred to another buffer.")
9420 (defun org-get-local-variables ()
9421 "Return a list of all local variables in an Org mode buffer."
9422 (delq nil
9423 (mapcar
9424 (lambda (x)
9425 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9426 (name (car binding)))
9427 (and (not (get name 'org-state))
9428 (not (memq name org-unique-local-variables))
9429 (string-match-p
9430 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9431 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9432 (symbol-name name))
9433 binding)))
9434 (with-temp-buffer
9435 (org-mode)
9436 (buffer-local-variables)))))
9438 (defun org-clone-local-variables (from-buffer &optional regexp)
9439 "Clone local variables from FROM-BUFFER.
9440 Optional argument REGEXP selects variables to clone."
9441 (dolist (pair (buffer-local-variables from-buffer))
9442 (let ((name (car pair)))
9443 (when (and (symbolp name)
9444 (not (memq name org-unique-local-variables))
9445 (or (null regexp) (string-match regexp (symbol-name name))))
9446 (set (make-local-variable name) (cdr pair))))))
9448 ;;;###autoload
9449 (defun org-run-like-in-org-mode (cmd)
9450 "Run a command, pretending that the current buffer is in Org-mode.
9451 This will temporarily bind local variables that are typically bound in
9452 Org-mode to the values they have in Org-mode, and then interactively
9453 call CMD."
9454 (org-load-modules-maybe)
9455 (unless org-local-vars
9456 (setq org-local-vars (org-get-local-variables)))
9457 (let (binds)
9458 (dolist (var org-local-vars)
9459 (when (or (not (boundp (car var)))
9460 (eq (symbol-value (car var))
9461 (default-value (car var))))
9462 (push (list (car var) `(quote ,(cadr var))) binds)))
9463 (eval `(let ,binds
9464 (call-interactively (quote ,cmd))))))
9466 (defun org-get-category (&optional pos force-refresh)
9467 "Get the category applying to position POS."
9468 (save-match-data
9469 (when force-refresh (org-refresh-category-properties))
9470 (let ((pos (or pos (point))))
9471 (or (get-text-property pos 'org-category)
9472 (progn (org-refresh-category-properties)
9473 (get-text-property pos 'org-category))))))
9475 ;;; Refresh properties
9477 (defun org-refresh-properties (dprop tprop)
9478 "Refresh buffer text properties.
9479 DPROP is the drawer property and TPROP is either the
9480 corresponding text property to set, or an alist with each element
9481 being a text property (as a symbol) and a function to apply to
9482 the value of the drawer property."
9483 (let ((case-fold-search t)
9484 (inhibit-read-only t))
9485 (org-with-silent-modifications
9486 (save-excursion
9487 (save-restriction
9488 (widen)
9489 (goto-char (point-min))
9490 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9491 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9493 (defun org-refresh-property (tprop p)
9494 "Refresh the buffer text property TPROP from the drawer property P.
9495 The refresh happens only for the current tree (not subtree)."
9496 (unless (org-before-first-heading-p)
9497 (save-excursion
9498 (org-back-to-heading t)
9499 (if (symbolp tprop)
9500 ;; TPROP is a text property symbol
9501 (put-text-property
9502 (point) (or (outline-next-heading) (point-max)) tprop p)
9503 ;; TPROP is an alist with (properties . function) elements
9504 (dolist (al tprop)
9505 (save-excursion
9506 (put-text-property
9507 (line-beginning-position) (or (outline-next-heading) (point-max))
9508 (car al)
9509 (funcall (cdr al) p))))))))
9511 (defun org-refresh-category-properties ()
9512 "Refresh category text properties in the buffer."
9513 (let ((case-fold-search t)
9514 (inhibit-read-only t)
9515 (default-category
9516 (cond ((null org-category)
9517 (if buffer-file-name
9518 (file-name-sans-extension
9519 (file-name-nondirectory buffer-file-name))
9520 "???"))
9521 ((symbolp org-category) (symbol-name org-category))
9522 (t org-category))))
9523 (org-with-silent-modifications
9524 (org-with-wide-buffer
9525 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9526 ;; This is the default category for the buffer. If none is
9527 ;; found, fall-back to `org-category' or buffer file name.
9528 (put-text-property
9529 (point-min) (point-max)
9530 'org-category
9531 (catch 'buffer-category
9532 (goto-char (point-max))
9533 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9534 (let ((element (org-element-at-point)))
9535 (when (eq (org-element-type element) 'keyword)
9536 (throw 'buffer-category
9537 (org-element-property :value element)))))
9538 default-category))
9539 ;; Set sub-tree specific categories.
9540 (goto-char (point-min))
9541 (let ((regexp (org-re-property "CATEGORY")))
9542 (while (re-search-forward regexp nil t)
9543 (let ((value (org-match-string-no-properties 3)))
9544 (when (org-at-property-p)
9545 (put-text-property
9546 (save-excursion (org-back-to-heading t) (point))
9547 (save-excursion (org-end-of-subtree t t) (point))
9548 'org-category
9549 value)))))))))
9551 (defun org-refresh-stats-properties ()
9552 "Refresh stats text properties in the buffer."
9553 (let (stats)
9554 (org-with-silent-modifications
9555 (save-excursion
9556 (save-restriction
9557 (widen)
9558 (goto-char (point-min))
9559 (while (re-search-forward
9560 (concat org-outline-regexp-bol ".*"
9561 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9562 nil t)
9563 (setq stats (cond ((equal (match-string 3) "0") 0)
9564 ((match-string 2)
9565 (/ (* (string-to-number (match-string 2)) 100)
9566 (string-to-number (match-string 3))))
9567 (t (string-to-number (match-string 1)))))
9568 (org-back-to-heading t)
9569 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9570 'org-stats stats)))))))
9572 (defun org-refresh-effort-properties ()
9573 "Refresh effort properties"
9574 (org-refresh-properties
9575 org-effort-property
9576 '((effort . identity)
9577 (effort-minutes . org-duration-string-to-minutes))))
9579 ;;;; Link Stuff
9581 ;;; Link abbreviations
9583 (defun org-link-expand-abbrev (link)
9584 "Apply replacements as defined in `org-link-abbrev-alist'."
9585 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9586 (let* ((key (match-string 1 link))
9587 (as (or (assoc key org-link-abbrev-alist-local)
9588 (assoc key org-link-abbrev-alist)))
9589 (tag (and (match-end 2) (match-string 3 link)))
9590 rpl)
9591 (if (not as)
9592 link
9593 (setq rpl (cdr as))
9594 (cond
9595 ((symbolp rpl) (funcall rpl tag))
9596 ((string-match "%(\\([^)]+\\))" rpl)
9597 (replace-match
9598 (save-match-data
9599 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9600 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9601 ((string-match "%h" rpl)
9602 (replace-match (url-hexify-string (or tag "")) t t rpl))
9603 (t (concat rpl tag)))))
9604 link))
9606 ;;; Storing and inserting links
9608 (defvar org-insert-link-history nil
9609 "Minibuffer history for links inserted with `org-insert-link'.")
9611 (defvar org-stored-links nil
9612 "Contains the links stored with `org-store-link'.")
9614 (defvar org-store-link-plist nil
9615 "Plist with info about the most recently link created with `org-store-link'.")
9617 (defvar org-link-protocols nil
9618 "Link protocols added to Org-mode using `org-add-link-type'.")
9620 (defvar org-store-link-functions nil
9621 "List of functions that are called to create and store a link.
9622 Each function will be called in turn until one returns a non-nil
9623 value. Each function should check if it is responsible for creating
9624 this link (for example by looking at the major mode).
9625 If not, it must exit and return nil.
9626 If yes, it should return a non-nil value after a calling
9627 `org-store-link-props' with a list of properties and values.
9628 Special properties are:
9630 :type The link prefix, like \"http\". This must be given.
9631 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9632 This is obligatory as well.
9633 :description Optional default description for the second pair
9634 of brackets in an Org-mode link. The user can still change
9635 this when inserting this link into an Org-mode buffer.
9637 In addition to these, any additional properties can be specified
9638 and then used in capture templates.")
9640 (defun org-add-link-type (type &optional follow export)
9641 "Add TYPE to the list of `org-link-types'.
9642 Re-compute all regular expressions depending on `org-link-types'
9644 FOLLOW and EXPORT are two functions.
9646 FOLLOW should take the link path as the single argument and do whatever
9647 is necessary to follow the link, for example find a file or display
9648 a mail message.
9650 EXPORT should format the link path for export to one of the export formats.
9651 It should be a function accepting three arguments:
9653 path the path of the link, the text after the prefix (like \"http:\")
9654 desc the description of the link, if any
9655 format the export format, a symbol like `html' or `latex' or `ascii'.
9657 The function may use the FORMAT information to return different values
9658 depending on the format. The return value will be put literally into
9659 the exported file. If the return value is nil, this means Org should
9660 do what it normally does with links which do not have EXPORT defined.
9662 Org mode has a built-in default for exporting links. If you are happy with
9663 this default, there is no need to define an export function for the link
9664 type. For a simple example of an export function, see `org-bbdb.el'."
9665 (add-to-list 'org-link-types type t)
9666 (org-make-link-regexps)
9667 (org-element-update-syntax)
9668 (if (assoc type org-link-protocols)
9669 (setcdr (assoc type org-link-protocols) (list follow export))
9670 (push (list type follow export) org-link-protocols)))
9672 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9673 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9675 ;;;###autoload
9676 (defun org-store-link (arg)
9677 "\\<org-mode-map>Store an org-link to the current location.
9678 This link is added to `org-stored-links' and can later be inserted
9679 into an Org buffer with \\[org-insert-link].
9681 For some link types, a prefix ARG is interpreted.
9682 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9683 For file links, ARG negates `org-context-in-file-links'.
9685 A double prefix ARG force skipping storing functions that are not
9686 part of Org's core.
9688 A triple prefix ARG force storing a link for each line in the
9689 active region."
9690 (interactive "P")
9691 (org-load-modules-maybe)
9692 (if (and (equal arg '(64)) (org-region-active-p))
9693 (save-excursion
9694 (let ((end (region-end)))
9695 (goto-char (region-beginning))
9696 (set-mark (point))
9697 (while (< (point-at-eol) end)
9698 (move-end-of-line 1) (activate-mark)
9699 (let (current-prefix-arg)
9700 (call-interactively 'org-store-link))
9701 (move-beginning-of-line 2)
9702 (set-mark (point)))))
9703 (org-with-limited-levels
9704 (setq org-store-link-plist nil)
9705 (let (link cpltxt desc description search
9706 txt custom-id agenda-link sfuns sfunsn)
9707 (cond
9709 ;; Store a link using an external link type
9710 ((and (not (equal arg '(16)))
9711 (setq sfuns
9712 (delq
9713 nil (mapcar (lambda (f)
9714 (let (fs) (if (funcall f) (push f fs))))
9715 org-store-link-functions))
9716 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9717 (or (and (cdr sfuns)
9718 (funcall (intern
9719 (completing-read
9720 "Which function for creating the link? "
9721 sfunsn nil t (car sfunsn)))))
9722 (funcall (caar sfuns)))
9723 (setq link (plist-get org-store-link-plist :link)
9724 desc (or (plist-get org-store-link-plist
9725 :description)
9726 link))))
9728 ;; Store a link from a source code buffer.
9729 ((org-src-edit-buffer-p)
9730 (cond
9731 ((save-excursion
9732 (beginning-of-line)
9733 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9734 "[ \t]*$")))
9735 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9736 ((org-called-interactively-p 'any)
9737 (let (label)
9738 (while (or (not label)
9739 (org-with-wide-buffer
9740 (goto-char (point-min))
9741 (re-search-forward
9742 (regexp-quote (format org-coderef-label-format label))
9743 nil t)))
9744 (when label (message "Label exists already") (sit-for 2))
9745 (setq label (read-string "Code line label: " label)))
9746 (end-of-line)
9747 (setq link (format org-coderef-label-format label))
9748 (let ((gc (- 79 (length link))))
9749 (if (< (current-column) gc) (org-move-to-column gc t)
9750 (insert " ")))
9751 (insert link)
9752 (setq link (concat "(" label ")") desc nil)))
9753 (t (setq link nil))))
9755 ;; We are in the agenda, link to referenced location
9756 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9757 (let ((m (or (get-text-property (point) 'org-hd-marker)
9758 (get-text-property (point) 'org-marker))))
9759 (when m
9760 (org-with-point-at m
9761 (setq agenda-link
9762 (if (org-called-interactively-p 'any)
9763 (call-interactively 'org-store-link)
9764 (org-store-link nil)))))))
9766 ((eq major-mode 'calendar-mode)
9767 (let ((cd (calendar-cursor-to-date)))
9768 (setq link
9769 (format-time-string
9770 (car org-time-stamp-formats)
9771 (apply 'encode-time
9772 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9773 nil nil nil))))
9774 (org-store-link-props :type "calendar" :date cd)))
9776 ((eq major-mode 'help-mode)
9777 (setq link (concat "help:" (save-excursion
9778 (goto-char (point-min))
9779 (looking-at "^[^ ]+")
9780 (match-string 0))))
9781 (org-store-link-props :type "help"))
9783 ((eq major-mode 'w3-mode)
9784 (setq cpltxt (if (and (buffer-name)
9785 (not (string-match "Untitled" (buffer-name))))
9786 (buffer-name)
9787 (url-view-url t))
9788 link (url-view-url t))
9789 (org-store-link-props :type "w3" :url (url-view-url t)))
9791 ((eq major-mode 'image-mode)
9792 (setq cpltxt (concat "file:"
9793 (abbreviate-file-name buffer-file-name))
9794 link cpltxt)
9795 (org-store-link-props :type "image" :file buffer-file-name))
9797 ;; In dired, store a link to the file of the current line
9798 ((derived-mode-p 'dired-mode)
9799 (let ((file (dired-get-filename nil t)))
9800 (setq file (if file
9801 (abbreviate-file-name
9802 (expand-file-name (dired-get-filename nil t)))
9803 ;; otherwise, no file so use current directory.
9804 default-directory))
9805 (setq cpltxt (concat "file:" file)
9806 link cpltxt)))
9808 ((setq search (run-hook-with-args-until-success
9809 'org-create-file-search-functions))
9810 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9811 "::" search))
9812 (setq cpltxt (or description link)))
9814 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9815 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9816 (cond
9817 ;; Store a link using the target at point
9818 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9819 (setq cpltxt
9820 (concat "file:"
9821 (abbreviate-file-name
9822 (buffer-file-name (buffer-base-buffer)))
9823 "::" (match-string 1))
9824 link cpltxt))
9825 ((and (featurep 'org-id)
9826 (or (eq org-id-link-to-org-use-id t)
9827 (and (org-called-interactively-p 'any)
9828 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9829 (and (eq org-id-link-to-org-use-id
9830 'create-if-interactive-and-no-custom-id)
9831 (not custom-id))))
9832 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9833 ;; Store a link using the ID at point
9834 (setq link (condition-case nil
9835 (prog1 (org-id-store-link)
9836 (setq desc (or (plist-get org-store-link-plist
9837 :description)
9838 "")))
9839 (error
9840 ;; Probably before first headline, link only to file
9841 (concat "file:"
9842 (abbreviate-file-name
9843 (buffer-file-name (buffer-base-buffer))))))))
9845 ;; Just link to current headline
9846 (setq cpltxt (concat "file:"
9847 (abbreviate-file-name
9848 (buffer-file-name (buffer-base-buffer)))))
9849 ;; Add a context search string
9850 (when (org-xor org-context-in-file-links arg)
9851 (let* ((ee (org-element-at-point))
9852 (et (org-element-type ee))
9853 (ev (plist-get (cadr ee) :value))
9854 (ek (plist-get (cadr ee) :key))
9855 (eok (and (stringp ek) (string-match "name" ek))))
9856 (setq txt (cond
9857 ((org-at-heading-p) nil)
9858 ((and (eq et 'keyword) eok) ev)
9859 ((org-region-active-p)
9860 (buffer-substring (region-beginning) (region-end)))))
9861 (when (or (null txt) (string-match "\\S-" txt))
9862 (setq cpltxt
9863 (concat cpltxt "::"
9864 (condition-case nil
9865 (org-make-org-heading-search-string txt)
9866 (error "")))
9867 desc (or (and (eq et 'keyword) eok ev)
9868 (nth 4 (ignore-errors (org-heading-components)))
9869 "NONE")))))
9870 (when (string-match "::\\'" cpltxt)
9871 (setq cpltxt (substring cpltxt 0 -2)))
9872 (setq link cpltxt))))
9874 ((buffer-file-name (buffer-base-buffer))
9875 ;; Just link to this file here.
9876 (setq cpltxt (concat "file:"
9877 (abbreviate-file-name
9878 (buffer-file-name (buffer-base-buffer)))))
9879 ;; Add a context string.
9880 (when (org-xor org-context-in-file-links arg)
9881 (setq txt (if (org-region-active-p)
9882 (buffer-substring (region-beginning) (region-end))
9883 (buffer-substring (point-at-bol) (point-at-eol))))
9884 ;; Only use search option if there is some text.
9885 (when (string-match "\\S-" txt)
9886 (setq cpltxt
9887 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9888 desc "NONE")))
9889 (setq link cpltxt))
9891 ((org-called-interactively-p 'interactive)
9892 (user-error "No method for storing a link from this buffer"))
9894 (t (setq link nil)))
9896 ;; We're done setting link and desc, clean up
9897 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9898 (setq link (or link cpltxt)
9899 desc (or desc cpltxt))
9900 (cond ((equal desc "NONE") (setq desc nil))
9901 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9902 (let ((d0 (match-string 3 desc))
9903 (p0 (match-string 5 desc)))
9904 (setq desc
9905 (replace-regexp-in-string
9906 org-bracket-link-regexp
9907 (concat (or p0 d0)
9908 (if (equal (length (match-string 0 desc))
9909 (length desc)) "*" "")) desc)))))
9911 ;; Return the link
9912 (if (not (and (or (org-called-interactively-p 'any)
9913 executing-kbd-macro)
9914 link))
9915 (or agenda-link (and link (org-make-link-string link desc)))
9916 (push (list link desc) org-stored-links)
9917 (message "Stored: %s" (or desc link))
9918 (when custom-id
9919 (setq link (concat "file:" (abbreviate-file-name
9920 (buffer-file-name)) "::#" custom-id))
9921 (push (list link desc) org-stored-links))
9922 (car org-stored-links))))))
9924 (defun org-store-link-props (&rest plist)
9925 "Store link properties, extract names, addresses and dates."
9926 (let ((x (plist-get plist :from)))
9927 (when x
9928 (let ((adr (mail-extract-address-components x)))
9929 (setq plist (plist-put plist :fromname (car adr)))
9930 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9931 (let ((x (plist-get plist :to)))
9932 (when x
9933 (let ((adr (mail-extract-address-components x)))
9934 (setq plist (plist-put plist :toname (car adr)))
9935 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9936 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9937 (when x
9938 (setq plist (plist-put plist :date-timestamp
9939 (format-time-string
9940 (org-time-stamp-format t) x)))
9941 (setq plist (plist-put plist :date-timestamp-inactive
9942 (format-time-string
9943 (org-time-stamp-format t t) x)))))
9944 (let ((from (plist-get plist :from))
9945 (to (plist-get plist :to)))
9946 (when (and from to org-from-is-user-regexp)
9947 (setq plist
9948 (plist-put plist :fromto
9949 (if (string-match org-from-is-user-regexp from)
9950 (concat "to %t")
9951 (concat "from %f"))))))
9952 (setq org-store-link-plist plist))
9954 (defun org-add-link-props (&rest plist)
9955 "Add these properties to the link property list."
9956 (let (key value)
9957 (while plist
9958 (setq key (pop plist) value (pop plist))
9959 (setq org-store-link-plist
9960 (plist-put org-store-link-plist key value)))))
9962 (defun org-email-link-description (&optional fmt)
9963 "Return the description part of an email link.
9964 This takes information from `org-store-link-plist' and formats it
9965 according to FMT (default from `org-email-link-description-format')."
9966 (setq fmt (or fmt org-email-link-description-format))
9967 (let* ((p org-store-link-plist)
9968 (to (plist-get p :toaddress))
9969 (from (plist-get p :fromaddress))
9970 (table
9971 (list
9972 (cons "%c" (plist-get p :fromto))
9973 (cons "%F" (plist-get p :from))
9974 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9975 (cons "%T" (plist-get p :to))
9976 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9977 (cons "%s" (plist-get p :subject))
9978 (cons "%d" (plist-get p :date))
9979 (cons "%m" (plist-get p :message-id)))))
9980 (when (string-match "%c" fmt)
9981 ;; Check if the user wrote this message
9982 (if (and org-from-is-user-regexp from to
9983 (save-match-data (string-match org-from-is-user-regexp from)))
9984 (setq fmt (replace-match "to %t" t t fmt))
9985 (setq fmt (replace-match "from %f" t t fmt))))
9986 (org-replace-escapes fmt table)))
9988 (defun org-make-org-heading-search-string (&optional string)
9989 "Make search string for the current headline or STRING."
9990 (let ((s (or string
9991 (and (derived-mode-p 'org-mode)
9992 (save-excursion
9993 (org-back-to-heading t)
9994 (org-element-property :raw-value (org-element-at-point))))))
9995 (lines org-context-in-file-links))
9996 (or string (setq s (concat "*" s))) ; Add * for headlines
9997 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9998 (when (and string (integerp lines) (> lines 0))
9999 (let ((slines (org-split-string s "\n")))
10000 (when (< lines (length slines))
10001 (setq s (mapconcat
10002 'identity
10003 (reverse (nthcdr (- (length slines) lines)
10004 (reverse slines))) "\n")))))
10005 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10007 (defun org-make-link-string (link &optional description)
10008 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10009 (unless (org-string-nw-p link) (error "Empty link"))
10010 (let ((uri (cond ((string-match org-link-types-re link)
10011 (concat (match-string 1 link)
10012 (org-link-escape (substring link (match-end 1)))))
10013 ;; For readability, url-encode internal links only
10014 ;; when absolutely needed (i.e, when they contain
10015 ;; square brackets). File links however, are
10016 ;; encoded since, e.g., spaces are significant.
10017 ((or (file-name-absolute-p link)
10018 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10019 (org-link-escape link))
10020 (t link)))
10021 (description
10022 (and (org-string-nw-p description)
10023 ;; Remove brackets from description, as they are fatal.
10024 (replace-regexp-in-string
10025 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10026 (org-trim description)))))
10027 (format "[[%s]%s]"
10029 (if description (format "[%s]" description) ""))))
10031 (defconst org-link-escape-chars
10032 ;;%20 %5B %5D %25
10033 '(?\s ?\[ ?\] ?%)
10034 "List of characters that should be escaped in a link when stored to Org.
10035 This is the list that is used for internal purposes.")
10037 (defconst org-link-escape-chars-browser
10038 ;;%20 %22
10039 '(?\s ?\")
10040 "List of characters to be escaped before handing over to the browser.
10041 If you consider using this constant then you probably want to use
10042 the function `org-link-escape-browser' instead. See there why
10043 this constant is a candidate to be removed once Org drops support
10044 for Emacs 24.1 and 24.2.")
10046 (defun org-link-escape (text &optional table merge)
10047 "Return percent escaped representation of TEXT.
10048 TEXT is a string with the text to escape.
10049 Optional argument TABLE is a list with characters that should be
10050 escaped. When nil, `org-link-escape-chars' is used.
10051 If optional argument MERGE is set, merge TABLE into
10052 `org-link-escape-chars'."
10053 (let ((characters-to-encode
10054 (cond ((null table) org-link-escape-chars)
10055 (merge (append org-link-escape-chars table))
10056 (t table))))
10057 (mapconcat
10058 (lambda (c)
10059 (if (or (memq c characters-to-encode)
10060 (and org-url-hexify-p (or (< c 32) (> c 126))))
10061 (mapconcat (lambda (e) (format "%%%.2X" e))
10062 (or (encode-coding-char c 'utf-8)
10063 (error "Unable to percent escape character: %c" c))
10065 (char-to-string c)))
10066 text "")))
10068 (defun org-link-escape-browser (text)
10069 "Escape some characters before handing over to the browser.
10070 This function is a candidate to be removed together with the
10071 constant `org-link-escape-chars-browser' once Org drops support
10072 for Emacs 24.1 and 24.2. All calls to this function will have to
10073 be replaced with `url-encode-url' which is available since Emacs
10074 24.3.1."
10075 ;; Example with the Org link
10076 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10077 ;; to open the browser with +subject:"Release 8.2" filled into the
10078 ;; query field: In this case the variable TEXT contains the
10079 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10080 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10081 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10082 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10083 (if (fboundp 'url-encode-url)
10084 (url-encode-url text)
10085 (if (org-string-match-p
10086 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10087 text)
10088 (org-link-escape text org-link-escape-chars-browser)
10089 text)))
10091 (defun org-link-unescape (str)
10092 "Unhex hexified Unicode parts in string STR.
10093 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10094 reciprocal of `org-link-escape', which see."
10095 (if (org-string-nw-p str)
10096 (replace-regexp-in-string
10097 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10098 str))
10100 (defun org-link-unescape-compound (hex)
10101 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10102 Note: this function also decodes single byte encodings like
10103 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10104 (save-match-data
10105 (let* ((bytes (cdr (split-string hex "%")))
10106 (ret "")
10107 (eat 0)
10108 (sum 0))
10109 (while bytes
10110 (let* ((val (string-to-number (pop bytes) 16))
10111 (shift-xor
10112 (if (= 0 eat)
10113 (cond
10114 ((>= val 252) (cons 6 252))
10115 ((>= val 248) (cons 5 248))
10116 ((>= val 240) (cons 4 240))
10117 ((>= val 224) (cons 3 224))
10118 ((>= val 192) (cons 2 192))
10119 (t (cons 0 0)))
10120 (cons 6 128))))
10121 (when (>= val 192) (setq eat (car shift-xor)))
10122 (setq val (logxor val (cdr shift-xor)))
10123 (setq sum (+ (lsh sum (car shift-xor)) val))
10124 (when (> eat 0) (setq eat (- eat 1)))
10125 (cond
10126 ((= 0 eat) ;multi byte
10127 (setq ret (concat ret (org-char-to-string sum)))
10128 (setq sum 0))
10129 ((not bytes) ; single byte(s)
10130 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10131 ret)))
10133 (defun org-link-unescape-single-byte-sequence (hex)
10134 "Unhexify hex-encoded single byte character sequences."
10135 (mapconcat (lambda (byte)
10136 (char-to-string (string-to-number byte 16)))
10137 (cdr (split-string hex "%")) ""))
10139 (defun org-xor (a b)
10140 "Exclusive or."
10141 (if a (not b) b))
10143 (defun org-fixup-message-id-for-http (s)
10144 "Replace special characters in a message id, so it can be used in an http query."
10145 (when (string-match "%" s)
10146 (setq s (mapconcat (lambda (c)
10147 (if (eq c ?%)
10148 "%25"
10149 (char-to-string c)))
10150 s "")))
10151 (while (string-match "<" s)
10152 (setq s (replace-match "%3C" t t s)))
10153 (while (string-match ">" s)
10154 (setq s (replace-match "%3E" t t s)))
10155 (while (string-match "@" s)
10156 (setq s (replace-match "%40" t t s)))
10159 (defun org-link-prettify (link)
10160 "Return a human-readable representation of LINK.
10161 The car of LINK must be a raw link.
10162 The cdr of LINK must be either a link description or nil."
10163 (let ((desc (or (cadr link) "<no description>")))
10164 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10165 "<" (car link) ">")))
10167 ;;;###autoload
10168 (defun org-insert-link-global ()
10169 "Insert a link like Org-mode does.
10170 This command can be called in any mode to insert a link in Org-mode syntax."
10171 (interactive)
10172 (org-load-modules-maybe)
10173 (org-run-like-in-org-mode 'org-insert-link))
10175 (defun org-insert-all-links (arg &optional pre post)
10176 "Insert all links in `org-stored-links'.
10177 When a universal prefix, do not delete the links from `org-stored-links'.
10178 When `ARG' is a number, insert the last N link(s).
10179 `PRE' and `POST' are optional arguments to define a string to
10180 prepend or to append."
10181 (interactive "P")
10182 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10183 (links (copy-seq org-stored-links))
10184 (pr (or pre "- "))
10185 (po (or post "\n"))
10186 (cnt 1) l)
10187 (if (null org-stored-links)
10188 (message "No link to insert")
10189 (while (and (or (listp arg) (>= arg cnt))
10190 (setq l (if (listp arg)
10191 (pop links)
10192 (pop org-stored-links))))
10193 (setq cnt (1+ cnt))
10194 (insert pr)
10195 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10196 (insert po)))))
10198 (defun org-insert-last-stored-link (arg)
10199 "Insert the last link stored in `org-stored-links'."
10200 (interactive "p")
10201 (org-insert-all-links arg "" "\n"))
10203 (defun org-link-fontify-links-to-this-file ()
10204 "Fontify links to the current file in `org-stored-links'."
10205 (let ((f (buffer-file-name)) a b)
10206 (setq a (mapcar (lambda(l)
10207 (let ((ll (car l)))
10208 (when (and (string-match "^file:\\(.+\\)::" ll)
10209 (equal f (expand-file-name (match-string 1 ll))))
10210 ll)))
10211 org-stored-links))
10212 (when (featurep 'org-id)
10213 (setq b (mapcar (lambda(l)
10214 (let ((ll (car l)))
10215 (when (and (string-match "^id:\\(.+\\)$" ll)
10216 (equal f (expand-file-name
10217 (or (org-id-find-id-file
10218 (match-string 1 ll)) ""))))
10219 ll)))
10220 org-stored-links)))
10221 (mapcar (lambda(l)
10222 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10223 (delq nil (append a b)))))
10225 (defvar org-link-links-in-this-file nil)
10226 (defun org-insert-link (&optional complete-file link-location default-description)
10227 "Insert a link. At the prompt, enter the link.
10229 Completion can be used to insert any of the link protocol prefixes like
10230 http or ftp in use.
10232 The history can be used to select a link previously stored with
10233 `org-store-link'. When the empty string is entered (i.e. if you just
10234 press RET at the prompt), the link defaults to the most recently
10235 stored link. As SPC triggers completion in the minibuffer, you need to
10236 use M-SPC or C-q SPC to force the insertion of a space character.
10238 You will also be prompted for a description, and if one is given, it will
10239 be displayed in the buffer instead of the link.
10241 If there is already a link at point, this command will allow you to edit link
10242 and description parts.
10244 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10245 be selected using completion. The path to the file will be relative to the
10246 current directory if the file is in the current directory or a subdirectory.
10247 Otherwise, the link will be the absolute path as completed in the minibuffer
10248 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10249 option `org-link-file-path-type'.
10251 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10252 the current directory or below.
10254 With three \\[universal-argument] prefixes, negate the meaning of
10255 `org-keep-stored-link-after-insertion'.
10257 If `org-make-link-description-function' is non-nil, this function will be
10258 called with the link target, and the result will be the default
10259 link description.
10261 If the LINK-LOCATION parameter is non-nil, this value will be
10262 used as the link location instead of reading one interactively.
10264 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10265 be used as the default description."
10266 (interactive "P")
10267 (let* ((wcf (current-window-configuration))
10268 (origbuf (current-buffer))
10269 (region (when (org-region-active-p)
10270 (buffer-substring (region-beginning) (region-end))))
10271 (remove (and region (list (region-beginning) (region-end))))
10272 (desc region)
10273 tmphist ; byte-compile incorrectly complains about this
10274 (link link-location)
10275 (abbrevs org-link-abbrev-alist-local)
10276 entry file all-prefixes auto-desc)
10277 (cond
10278 (link-location) ; specified by arg, just use it.
10279 ((org-in-regexp org-bracket-link-regexp 1)
10280 ;; We do have a link at point, and we are going to edit it.
10281 (setq remove (list (match-beginning 0) (match-end 0)))
10282 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10283 (setq link (read-string "Link: "
10284 (org-link-unescape
10285 (org-match-string-no-properties 1)))))
10286 ((or (org-in-regexp org-angle-link-re)
10287 (org-in-regexp org-plain-link-re))
10288 ;; Convert to bracket link
10289 (setq remove (list (match-beginning 0) (match-end 0))
10290 link (read-string "Link: "
10291 (org-remove-angle-brackets (match-string 0)))))
10292 ((member complete-file '((4) (16)))
10293 ;; Completing read for file names.
10294 (setq link (org-file-complete-link complete-file)))
10296 ;; Read link, with completion for stored links.
10297 (org-link-fontify-links-to-this-file)
10298 (org-switch-to-buffer-other-window "*Org Links*")
10299 (with-current-buffer "*Org Links*"
10300 (erase-buffer)
10301 (insert "Insert a link.
10302 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10303 (when org-stored-links
10304 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10305 (insert (mapconcat 'org-link-prettify
10306 (reverse org-stored-links) "\n")))
10307 (goto-char (point-min)))
10308 (let ((cw (selected-window)))
10309 (select-window (get-buffer-window "*Org Links*" 'visible))
10310 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10311 (unless (pos-visible-in-window-p (point-max))
10312 (org-fit-window-to-buffer))
10313 (and (window-live-p cw) (select-window cw)))
10314 ;; Fake a link history, containing the stored links.
10315 (setq tmphist (append (mapcar 'car org-stored-links)
10316 org-insert-link-history))
10317 (setq all-prefixes (append (mapcar 'car abbrevs)
10318 (mapcar 'car org-link-abbrev-alist)
10319 org-link-types))
10320 (unwind-protect
10321 (progn
10322 (setq link
10323 (org-completing-read
10324 "Link: "
10325 (append
10326 (mapcar (lambda (x) (concat x ":"))
10327 all-prefixes)
10328 (mapcar 'car org-stored-links))
10329 nil nil nil
10330 'tmphist
10331 (caar org-stored-links)))
10332 (unless (string-match "\\S-" link)
10333 (user-error "No link selected"))
10334 (mapc (lambda(l)
10335 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10336 org-stored-links)
10337 (when (or (member link all-prefixes)
10338 (and (equal ":" (substring link -1))
10339 (member (substring link 0 -1) all-prefixes)
10340 (setq link (substring link 0 -1))))
10341 (setq link (with-current-buffer origbuf
10342 (org-link-try-special-completion link)))))
10343 (set-window-configuration wcf)
10344 (kill-buffer "*Org Links*"))
10345 (setq entry (assoc link org-stored-links))
10346 (or entry (push link org-insert-link-history))
10347 (setq desc (or desc (nth 1 entry)))))
10349 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10350 (not org-keep-stored-link-after-insertion))
10351 (setq org-stored-links (delq (assoc link org-stored-links)
10352 org-stored-links)))
10354 (when (and (string-match org-plain-link-re link)
10355 (not (string-match org-ts-regexp link)))
10356 ;; URL-like link, normalize the use of angular brackets.
10357 (setq link (org-remove-angle-brackets link)))
10359 ;; Check if we are linking to the current file with a search
10360 ;; option If yes, simplify the link by using only the search
10361 ;; option.
10362 (when (and buffer-file-name
10363 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10364 (let* ((path (match-string 1 link))
10365 (case-fold-search nil)
10366 (search (match-string 2 link)))
10367 (save-match-data
10368 (when (equal (file-truename buffer-file-name) (file-truename path))
10369 ;; We are linking to this same file, with a search option
10370 (setq link search)))))
10372 ;; Check if we can/should use a relative path. If yes, simplify the link
10373 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10374 (let* ((type (match-string 1 link))
10375 (path (match-string 2 link))
10376 (origpath path)
10377 (case-fold-search nil))
10378 (cond
10379 ((or (eq org-link-file-path-type 'absolute)
10380 (equal complete-file '(16)))
10381 (setq path (abbreviate-file-name (expand-file-name path))))
10382 ((eq org-link-file-path-type 'noabbrev)
10383 (setq path (expand-file-name path)))
10384 ((eq org-link-file-path-type 'relative)
10385 (setq path (file-relative-name path)))
10387 (save-match-data
10388 (if (string-match (concat "^" (regexp-quote
10389 (expand-file-name
10390 (file-name-as-directory
10391 default-directory))))
10392 (expand-file-name path))
10393 ;; We are linking a file with relative path name.
10394 (setq path (substring (expand-file-name path)
10395 (match-end 0)))
10396 (setq path (abbreviate-file-name (expand-file-name path)))))))
10397 (setq link (concat type path))
10398 (when (equal desc origpath)
10399 (setq desc path))))
10401 (if org-make-link-description-function
10402 (setq desc
10403 (or (condition-case nil
10404 (funcall org-make-link-description-function link desc)
10405 (error (progn (message "Can't get link description from `%s'"
10406 (symbol-name org-make-link-description-function))
10407 (sit-for 2) nil)))
10408 (read-string "Description: " default-description)))
10409 (if default-description (setq desc default-description)
10410 (setq desc (or (and auto-desc desc)
10411 (read-string "Description: " desc)))))
10413 (unless (string-match "\\S-" desc) (setq desc nil))
10414 (when remove (apply 'delete-region remove))
10415 (insert (org-make-link-string link desc))
10416 ;; Redisplay so as the new link has proper invisible characters.
10417 (sit-for 0)))
10419 (defun org-link-try-special-completion (type)
10420 "If there is completion support for link type TYPE, offer it."
10421 (let ((fun (intern (concat "org-" type "-complete-link"))))
10422 (if (functionp fun)
10423 (funcall fun)
10424 (read-string "Link (no completion support): " (concat type ":")))))
10426 (defun org-file-complete-link (&optional arg)
10427 "Create a file link using completion."
10428 (let ((file (org-iread-file-name "File: "))
10429 (pwd (file-name-as-directory (expand-file-name ".")))
10430 (pwd1 (file-name-as-directory (abbreviate-file-name
10431 (expand-file-name ".")))))
10432 (cond ((equal arg '(16))
10433 (concat "file:"
10434 (abbreviate-file-name (expand-file-name file))))
10435 ((string-match
10436 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10437 (concat "file:" (match-string 1 file)))
10438 ((string-match
10439 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10440 (expand-file-name file))
10441 (concat "file:"
10442 (match-string 1 (expand-file-name file))))
10443 (t (concat "file:" file)))))
10445 (defun org-iread-file-name (&rest args)
10446 "Read-file-name using `ido-mode' speedup if available.
10447 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10448 See `read-file-name' for a description of parameters."
10449 (org-without-partial-completion
10450 (if (and org-completion-use-ido
10451 (fboundp 'ido-read-file-name)
10452 (org-bound-and-true-p ido-mode)
10453 (listp (nth 1 args)))
10454 (let ((ido-enter-matching-directory nil))
10455 (apply #'ido-read-file-name args))
10456 (apply #'read-file-name args))))
10458 (defun org-completing-read (&rest args)
10459 "Completing-read with SPACE being a normal character."
10460 (let ((enable-recursive-minibuffers t)
10461 (minibuffer-local-completion-map
10462 (copy-keymap minibuffer-local-completion-map)))
10463 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10464 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10465 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10466 (apply 'org-icompleting-read args)))
10468 (defun org-completing-read-no-i (&rest args)
10469 (let (org-completion-use-ido org-completion-use-iswitchb)
10470 (apply 'org-completing-read args)))
10472 (defun org-iswitchb-completing-read (prompt choices &rest args)
10473 "Use iswitch as a completing-read replacement to choose from choices.
10474 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10475 from."
10476 (let* ((iswitchb-use-virtual-buffers nil)
10477 (iswitchb-make-buflist-hook
10478 (lambda ()
10479 (setq iswitchb-temp-buflist choices))))
10480 (iswitchb-read-buffer prompt)))
10482 (defun org-icompleting-read (&rest args)
10483 "Completing-read using `ido-mode' or `iswitchb' speedups if available.
10484 Should be called like `completing-read'."
10485 (org-without-partial-completion
10486 (if (not (listp (nth 1 args)))
10487 ;; Ido only supports lists as the COLLECTION argument. Use
10488 ;; default completion function when second argument is not
10489 ;; a list.
10490 (apply #'completing-read args)
10491 (let ((ido-enter-matching-directory nil))
10492 (apply (cond ((and org-completion-use-ido
10493 (fboundp 'ido-completing-read)
10494 (org-bound-and-true-p ido-mode))
10495 #'ido-completing-read)
10496 ((and org-completion-use-iswitchb
10497 (org-bound-and-true-p iswitchb-mode))
10498 #'org-iswitchb-completing-read)
10499 (t #'completing-read))
10500 args)))))
10502 ;;; Opening/following a link
10504 (defvar org-link-search-failed nil)
10506 (defvar org-open-link-functions nil
10507 "Hook for functions finding a plain text link.
10508 These functions must take a single argument, the link content.
10509 They will be called for links that look like [[link text][description]]
10510 when LINK TEXT does not have a protocol like \"http:\" and does not look
10511 like a filename (e.g. \"./blue.png\").
10513 These functions will be called *before* Org attempts to resolve the
10514 link by doing text searches in the current buffer - so if you want a
10515 link \"[[target]]\" to still find \"<<target>>\", your function should
10516 handle this as a special case.
10518 When the function does handle the link, it must return a non-nil value.
10519 If it decides that it is not responsible for this link, it must return
10520 nil to indicate that that Org-mode can continue with other options
10521 like exact and fuzzy text search.")
10523 (defun org-next-link (&optional search-backward)
10524 "Move forward to the next link.
10525 If the link is in hidden text, expose it."
10526 (interactive "P")
10527 (when (and org-link-search-failed (eq this-command last-command))
10528 (goto-char (point-min))
10529 (message "Link search wrapped back to beginning of buffer"))
10530 (setq org-link-search-failed nil)
10531 (let* ((pos (point))
10532 (ct (org-context))
10533 (a (assoc :link ct))
10534 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10535 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10536 ((looking-at org-any-link-re)
10537 ;; Don't stay stuck at link without an org-link face
10538 (forward-char (if search-backward -1 1))))
10539 (if (funcall srch-fun org-any-link-re nil t)
10540 (progn
10541 (goto-char (match-beginning 0))
10542 (when (outline-invisible-p) (org-show-context)))
10543 (goto-char pos)
10544 (setq org-link-search-failed t)
10545 (message "No further link found"))))
10547 (defun org-previous-link ()
10548 "Move backward to the previous link.
10549 If the link is in hidden text, expose it."
10550 (interactive)
10551 (funcall 'org-next-link t))
10553 (defun org-translate-link (s)
10554 "Translate a link string if a translation function has been defined."
10555 (with-temp-buffer
10556 (insert (org-trim s))
10557 (org-trim (org-element-interpret-data (org-element-context)))))
10559 (defun org-translate-link-from-planner (type path)
10560 "Translate a link from Emacs Planner syntax so that Org can follow it.
10561 This is still an experimental function, your mileage may vary."
10562 (cond
10563 ((member type '("http" "https" "news" "ftp"))
10564 ;; standard Internet links are the same.
10565 nil)
10566 ((and (equal type "irc") (string-match "^//" path))
10567 ;; Planner has two / at the beginning of an irc link, we have 1.
10568 ;; We should have zero, actually....
10569 (setq path (substring path 1)))
10570 ((and (equal type "lisp") (string-match "^/" path))
10571 ;; Planner has a slash, we do not.
10572 (setq type "elisp" path (substring path 1)))
10573 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10574 ;; A typical message link. Planner has the id after the final slash,
10575 ;; we separate it with a hash mark
10576 (setq path (concat (match-string 1 path) "#"
10577 (org-remove-angle-brackets (match-string 2 path))))))
10578 (cons type path))
10580 (defun org-find-file-at-mouse (ev)
10581 "Open file link or URL at mouse."
10582 (interactive "e")
10583 (mouse-set-point ev)
10584 (org-open-at-point 'in-emacs))
10586 (defun org-open-at-mouse (ev)
10587 "Open file link or URL at mouse.
10588 See the docstring of `org-open-file' for details."
10589 (interactive "e")
10590 (mouse-set-point ev)
10591 (when (eq major-mode 'org-agenda-mode)
10592 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10593 (org-open-at-point))
10595 (defvar org-window-config-before-follow-link nil
10596 "The window configuration before following a link.
10597 This is saved in case the need arises to restore it.")
10599 ;;;###autoload
10600 (defun org-open-at-point-global ()
10601 "Follow a link like Org-mode does.
10602 This command can be called in any mode to follow a link that has
10603 Org-mode syntax."
10604 (interactive)
10605 (org-run-like-in-org-mode 'org-open-at-point))
10607 ;;;###autoload
10608 (defun org-open-link-from-string (s &optional arg reference-buffer)
10609 "Open a link in the string S, as if it was in Org-mode."
10610 (interactive "sLink: \nP")
10611 (let ((reference-buffer (or reference-buffer (current-buffer))))
10612 (with-temp-buffer
10613 (let ((org-inhibit-startup (not reference-buffer)))
10614 (org-mode)
10615 (insert s)
10616 (goto-char (point-min))
10617 (when reference-buffer
10618 (setq org-link-abbrev-alist-local
10619 (with-current-buffer reference-buffer
10620 org-link-abbrev-alist-local)))
10621 (org-open-at-point arg reference-buffer)))))
10623 (defvar org-open-at-point-functions nil
10624 "Hook that is run when following a link at point.
10626 Functions in this hook must return t if they identify and follow
10627 a link at point. If they don't find anything interesting at point,
10628 they must return nil.")
10630 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10631 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10632 (defun org-open-at-point (&optional arg reference-buffer)
10633 "Open link, timestamp, footnote or tags at point.
10635 When point is on a link, follow it. Normally, files will be
10636 opened by an appropriate application. If the optional prefix
10637 argument ARG is non-nil, Emacs will visit the file. With
10638 a double prefix argument, try to open outside of Emacs, in the
10639 application the system uses for this file type.
10641 When point is on a timestamp, open the agenda at the day
10642 specified.
10644 When point is a footnote definition, move to the first reference
10645 found. If it is on a reference, move to the associated
10646 definition.
10648 When point is on a headline, display a list of every link in the
10649 entry, so it is possible to pick one, or all, of them. If point
10650 is on a tag, call `org-tags-view' instead.
10652 When optional argument REFERENCE-BUFFER is non-nil, it should
10653 specify a buffer from where the link search should happen. This
10654 is used internally by `org-open-link-from-string'.
10656 On top of syntactically correct links, this function will open
10657 the link at point in comments or comment blocks and the first
10658 link in a property drawer line."
10659 (interactive "P")
10660 ;; On a code block, open block's results.
10661 (unless (call-interactively 'org-babel-open-src-block-result)
10662 (org-load-modules-maybe)
10663 (setq org-window-config-before-follow-link (current-window-configuration))
10664 (org-remove-occur-highlights nil nil t)
10665 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10666 (let* ((context
10667 ;; Only consider supported types, even if they are not
10668 ;; the closest one.
10669 (org-element-lineage
10670 (org-element-context)
10671 '(clock comment comment-block footnote-definition
10672 footnote-reference headline inlinetask keyword link
10673 node-property timestamp)
10675 (type (org-element-type context))
10676 (value (org-element-property :value context)))
10677 (cond
10678 ((not context) (user-error "No link found"))
10679 ;; Exception: open timestamps and links in properties
10680 ;; drawers, keywords and comments.
10681 ((memq type '(comment comment-block keyword node-property))
10682 (cond ((org-in-regexp org-any-link-re)
10683 (org-open-link-from-string (match-string-no-properties 0)))
10684 ((or (org-in-regexp org-ts-regexp-both nil t)
10685 (org-in-regexp org-tsr-regexp-both nil t))
10686 (org-follow-timestamp-link))
10687 (t (user-error "No link found"))))
10688 ;; On a headline or an inlinetask, but not on a timestamp,
10689 ;; a link, a footnote reference or on tags.
10690 ((and (memq type '(headline inlinetask))
10691 ;; Not on tags.
10692 (progn (save-excursion (beginning-of-line)
10693 (looking-at org-complex-heading-regexp))
10694 (or (not (match-beginning 5))
10695 (< (point) (match-beginning 5)))))
10696 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10697 (links (car data))
10698 (links-end (cdr data)))
10699 (if links
10700 (dolist (link (if (stringp links) (list links) links))
10701 (search-forward link nil links-end)
10702 (goto-char (match-beginning 0))
10703 (org-open-at-point))
10704 (require 'org-attach)
10705 (org-attach-reveal 'if-exists))))
10706 ;; On a clock line, make sure point is on the timestamp
10707 ;; before opening it.
10708 ((and (eq type 'clock)
10709 value
10710 (>= (point) (org-element-property :begin value))
10711 (<= (point) (org-element-property :end value)))
10712 (org-follow-timestamp-link))
10713 ;; Do nothing on white spaces after an object.
10714 ((>= (point)
10715 (save-excursion
10716 (goto-char (org-element-property :end context))
10717 (skip-chars-backward " \t")
10718 (point)))
10719 (user-error "No link found"))
10720 ((eq type 'timestamp) (org-follow-timestamp-link))
10721 ;; On tags within a headline or an inlinetask.
10722 ((and (memq type '(headline inlinetask))
10723 (progn (save-excursion (beginning-of-line)
10724 (looking-at org-complex-heading-regexp))
10725 (and (match-beginning 5)
10726 (>= (point) (match-beginning 5)))))
10727 (org-tags-view arg (substring (match-string 5) 0 -1)))
10728 ((eq type 'link)
10729 ;; When link is located within the description of another
10730 ;; link (e.g., an inline image), always open the parent
10731 ;; link.
10732 (let*((link (let ((up (org-element-property :parent context)))
10733 (if (eq (org-element-type up) 'link) up context)))
10734 (type (org-element-property :type link))
10735 (path (org-link-unescape (org-element-property :path link))))
10736 ;; Switch back to REFERENCE-BUFFER needed when called in
10737 ;; a temporary buffer through `org-open-link-from-string'.
10738 (with-current-buffer (or reference-buffer (current-buffer))
10739 (cond
10740 ((equal type "file")
10741 (if (string-match "[*?{]" (file-name-nondirectory path))
10742 (dired path)
10743 ;; Look into `org-link-protocols' in order to find
10744 ;; a DEDICATED-FUNCTION to open file. The function
10745 ;; will be applied on raw link instead of parsed
10746 ;; link due to the limitation in `org-add-link-type'
10747 ;; ("open" function called with a single argument).
10748 ;; If no such function is found, fallback to
10749 ;; `org-open-file'.
10751 ;; Note : "file+emacs" and "file+sys" types are
10752 ;; hard-coded in order to escape the previous
10753 ;; limitation.
10754 (let* ((option (org-element-property :search-option link))
10755 (app (org-element-property :application link))
10756 (dedicated-function
10757 (nth 1 (assoc app org-link-protocols))))
10758 (if dedicated-function
10759 (funcall dedicated-function
10760 (concat path
10761 (and option (concat "::" option))))
10762 (apply #'org-open-file
10763 path
10764 (cond (arg)
10765 ((equal app "emacs") 'emacs)
10766 ((equal app "sys") 'system))
10767 (cond ((not option) nil)
10768 ((org-string-match-p "\\`[0-9]+\\'" option)
10769 (list (string-to-number option)))
10770 (t (list nil
10771 (org-link-unescape option)))))))))
10772 ((assoc type org-link-protocols)
10773 (funcall (nth 1 (assoc type org-link-protocols)) path))
10774 ((equal type "help")
10775 (let ((f-or-v (intern path)))
10776 (cond ((fboundp f-or-v) (describe-function f-or-v))
10777 ((boundp f-or-v) (describe-variable f-or-v))
10778 (t (error "Not a known function or variable")))))
10779 ((member type '("http" "https" "ftp" "mailto" "news"))
10780 (browse-url (org-link-escape-browser (concat type ":" path))))
10781 ((equal type "doi")
10782 (browse-url
10783 (org-link-escape-browser (concat org-doi-server-url path))))
10784 ((equal type "message") (browse-url (concat type ":" path)))
10785 ((equal type "shell")
10786 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10787 (cmd path))
10788 (if (or (and (org-string-nw-p
10789 org-confirm-shell-link-not-regexp)
10790 (string-match
10791 org-confirm-shell-link-not-regexp cmd))
10792 (not org-confirm-shell-link-function)
10793 (funcall org-confirm-shell-link-function
10794 (format "Execute \"%s\" in shell? "
10795 (org-add-props cmd nil
10796 'face 'org-warning))))
10797 (progn
10798 (message "Executing %s" cmd)
10799 (shell-command cmd buf)
10800 (when (featurep 'midnight)
10801 (setq clean-buffer-list-kill-buffer-names
10802 (cons (buffer-name buf)
10803 clean-buffer-list-kill-buffer-names))))
10804 (user-error "Abort"))))
10805 ((equal type "elisp")
10806 (let ((cmd path))
10807 (if (or (and (org-string-nw-p
10808 org-confirm-elisp-link-not-regexp)
10809 (org-string-match-p
10810 org-confirm-elisp-link-not-regexp cmd))
10811 (not org-confirm-elisp-link-function)
10812 (funcall org-confirm-elisp-link-function
10813 (format "Execute \"%s\" as elisp? "
10814 (org-add-props cmd nil
10815 'face 'org-warning))))
10816 (message "%s => %s" cmd
10817 (if (eq (string-to-char cmd) ?\()
10818 (eval (read cmd))
10819 (call-interactively (read cmd))))
10820 (user-error "Abort"))))
10821 ((equal type "id")
10822 (require 'org-id)
10823 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10824 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10825 (unless (run-hook-with-args-until-success
10826 'org-open-link-functions path)
10827 (if (not arg) (org-mark-ring-push)
10828 (switch-to-buffer-other-window
10829 (org-get-buffer-for-internal-link (current-buffer))))
10830 (let ((destination
10831 (org-with-wide-buffer
10832 (if (equal type "radio")
10833 (org-search-radio-target
10834 (org-element-property :path link))
10835 (org-link-search
10836 (if (member type '("custom-id" "coderef"))
10837 (org-element-property :raw-link link)
10838 path)
10839 ;; Prevent fuzzy links from matching
10840 ;; themselves.
10841 (and (equal type "fuzzy")
10842 (+ 2 (org-element-property :begin link)))))
10843 (point))))
10844 (unless (and (<= (point-min) destination)
10845 (>= (point-max) destination))
10846 (widen))
10847 (goto-char destination))))
10848 (t (browse-url-at-point))))))
10849 ;; On a footnote reference or at a footnote definition's label.
10850 ((or (eq type 'footnote-reference)
10851 (and (eq type 'footnote-definition)
10852 (save-excursion
10853 ;; Do not validate action when point is on the
10854 ;; spaces right after the footnote label, in
10855 ;; order to be on par with behaviour on links.
10856 (skip-chars-forward " \t")
10857 (let ((begin
10858 (org-element-property :contents-begin context)))
10859 (if begin (< (point) begin)
10860 (= (org-element-property :post-affiliated context)
10861 (line-beginning-position)))))))
10862 (org-footnote-action))
10863 (t (user-error "No link found")))))
10864 (run-hook-with-args 'org-follow-link-hook)))
10866 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10867 "Offer links in the current entry and return the selected link.
10868 If there is only one link, return it.
10869 If NTH is an integer, return the NTH link found.
10870 If ZERO is a string, check also this string for a link, and if
10871 there is one, return it."
10872 (with-current-buffer buffer
10873 (save-excursion
10874 (save-restriction
10875 (widen)
10876 (goto-char marker)
10877 (let ((cnt ?0)
10878 (in-emacs (unless (integerp nth) nth))
10879 have-zero end links link c)
10880 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10881 (push (match-string 0 zero) links)
10882 (setq cnt (1- cnt) have-zero t))
10883 (save-excursion
10884 (org-back-to-heading t)
10885 (setq end (save-excursion (outline-next-heading) (point)))
10886 (while (re-search-forward org-any-link-re end t)
10887 (push (match-string 0) links))
10888 (setq links (org-uniquify (reverse links))))
10889 (cond
10890 ((null links)
10891 (message "No links"))
10892 ((equal (length links) 1)
10893 (setq link (car links)))
10894 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10895 (setq link (nth (if have-zero nth (1- nth)) links)))
10896 (t ; we have to select a link
10897 (save-excursion
10898 (save-window-excursion
10899 (delete-other-windows)
10900 (with-output-to-temp-buffer "*Select Link*"
10901 (mapc (lambda (l)
10902 (if (not (string-match org-bracket-link-regexp l))
10903 (princ (format "[%c] %s\n" (incf cnt)
10904 (org-remove-angle-brackets l)))
10905 (if (match-end 3)
10906 (princ (format "[%c] %s (%s)\n" (incf cnt)
10907 (match-string 3 l) (match-string 1 l)))
10908 (princ (format "[%c] %s\n" (incf cnt)
10909 (match-string 1 l))))))
10910 links))
10911 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10912 (message "Select link to open, RET to open all:")
10913 (setq c (read-char-exclusive))
10914 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10915 (when (equal c ?q) (user-error "Abort"))
10916 (if (equal c ?\C-m)
10917 (setq link links)
10918 (setq nth (- c ?0))
10919 (when have-zero (setq nth (1+ nth)))
10920 (unless (and (integerp nth) (>= (length links) nth))
10921 (user-error "Invalid link selection"))
10922 (setq link (nth (1- nth) links)))))
10923 (cons link end))))))
10925 ;; TODO: These functions are deprecated since `org-open-at-point'
10926 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10927 (defun org-open-file-with-system (path)
10928 "Open file at PATH using the system way of opening it."
10929 (org-open-file path 'system))
10930 (defun org-open-file-with-emacs (path)
10931 "Open file at PATH in Emacs."
10932 (org-open-file path 'emacs))
10935 ;;; File search
10937 (defvar org-create-file-search-functions nil
10938 "List of functions to construct the right search string for a file link.
10939 These functions are called in turn with point at the location to
10940 which the link should point.
10942 A function in the hook should first test if it would like to
10943 handle this file type, for example by checking the `major-mode'
10944 or the file extension. If it decides not to handle this file, it
10945 should just return nil to give other functions a chance. If it
10946 does handle the file, it must return the search string to be used
10947 when following the link. The search string will be part of the
10948 file link, given after a double colon, and `org-open-at-point'
10949 will automatically search for it. If special measures must be
10950 taken to make the search successful, another function should be
10951 added to the companion hook `org-execute-file-search-functions',
10952 which see.
10954 A function in this hook may also use `setq' to set the variable
10955 `description' to provide a suggestion for the descriptive text to
10956 be used for this link when it gets inserted into an Org-mode
10957 buffer with \\[org-insert-link].")
10959 (defvar org-execute-file-search-functions nil
10960 "List of functions to execute a file search triggered by a link.
10962 Functions added to this hook must accept a single argument, the
10963 search string that was part of the file link, the part after the
10964 double colon. The function must first check if it would like to
10965 handle this search, for example by checking the `major-mode' or
10966 the file extension. If it decides not to handle this search, it
10967 should just return nil to give other functions a chance. If it
10968 does handle the search, it must return a non-nil value to keep
10969 other functions from trying.
10971 Each function can access the current prefix argument through the
10972 variable `current-prefix-arg'. Note that a single prefix is used
10973 to force opening a link in Emacs, so it may be good to only use a
10974 numeric or double prefix to guide the search function.
10976 In case this is needed, a function in this hook can also restore
10977 the window configuration before `org-open-at-point' was called using:
10979 (set-window-configuration org-window-config-before-follow-link)")
10981 (defun org-search-radio-target (target)
10982 "Search a radio target matching TARGET in current buffer.
10983 White spaces are not significant."
10984 (let ((re (format "<<<%s>>>"
10985 (mapconcat #'regexp-quote
10986 (org-split-string target "[ \t\n]+")
10987 "[ \t]+\\(?:\n[ \t]*\\)?")))
10988 (origin (point)))
10989 (goto-char (point-min))
10990 (catch :radio-match
10991 (while (re-search-forward re nil t)
10992 (backward-char)
10993 (let ((object (org-element-context)))
10994 (when (eq (org-element-type object) 'radio-target)
10995 (goto-char (org-element-property :begin object))
10996 (org-show-context 'link-search)
10997 (throw :radio-match nil))))
10998 (goto-char origin)
10999 (user-error "No match for radio target: %s" target))))
11001 (defun org-link-search (s &optional avoid-pos stealth)
11002 "Search for a search string S.
11004 If S starts with \"#\", it triggers a custom ID search.
11006 If S is enclosed within parenthesis, it initiates a coderef
11007 search.
11009 If S is surrounded by forward slashes, it is interpreted as
11010 a regular expression. In Org mode files, this will create an
11011 `org-occur' sparse tree. In ordinary files, `occur' will be used
11012 to list matches. If the current buffer is in `dired-mode', grep
11013 will be used to search in all files.
11015 When AVOID-POS is given, ignore matches near that position.
11017 When optional argument STEALTH is non-nil, do not modify
11018 visibility around point, thus ignoring `org-show-context-detail'
11019 variable.
11021 Search is case-insensitive and ignores white spaces. Return type
11022 of matched result, with is either `dedicated' or `fuzzy'."
11023 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11024 (let* ((case-fold-search t)
11025 (origin (point))
11026 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11027 (words (org-split-string s "[ \t\n]+"))
11028 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11029 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11030 type)
11031 (cond
11032 ;; Check if there are any special search functions.
11033 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11034 ((eq (string-to-char s) ?#)
11035 ;; Look for a custom ID S if S starts with "#".
11036 (let* ((id (substring normalized 1))
11037 (match (org-find-property "CUSTOM_ID" id)))
11038 (if match (progn (goto-char match) (setf type 'dedicated))
11039 (error "No match for custom ID: %s" id))))
11040 ((string-match "\\`(\\(.*\\))\\'" normalized)
11041 ;; Look for coderef targets if S is enclosed within parenthesis.
11042 (let ((coderef (match-string-no-properties 1 normalized))
11043 (re (substring s-single-re 1 -1)))
11044 (goto-char (point-min))
11045 (catch :coderef-match
11046 (while (re-search-forward re nil t)
11047 (let ((element (org-element-at-point)))
11048 (when (and (memq (org-element-type element)
11049 '(example-block src-block))
11050 ;; Build proper regexp according to current
11051 ;; block's label format.
11052 (let ((label-fmt
11053 (regexp-quote
11054 (or (org-element-property :label-fmt element)
11055 org-coderef-label-format))))
11056 (save-excursion
11057 (beginning-of-line)
11058 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11059 (format label-fmt coderef))))))
11060 (setq type 'dedicated)
11061 (goto-char (match-beginning 1))
11062 (throw :coderef-match nil))))
11063 (goto-char origin)
11064 (error "No match for coderef: %s" coderef))))
11065 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11066 ;; Look for a regular expression.
11067 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11068 (match-string 1 s)))
11069 ;; Fuzzy links.
11071 (let* ((starred (eq (string-to-char normalized) ?*))
11072 (headline-search (and (derived-mode-p 'org-mode)
11073 (or org-link-search-must-match-exact-headline
11074 starred))))
11075 (cond
11076 ;; Look for targets, only if not in a headline search.
11077 ((and (not starred)
11078 (let ((target (format "<<%s>>" s-multi-re)))
11079 (catch :target-match
11080 (goto-char (point-min))
11081 (while (re-search-forward target nil t)
11082 (backward-char)
11083 (let ((context (org-element-context)))
11084 (when (eq (org-element-type context) 'target)
11085 (setq type 'dedicated)
11086 (goto-char (org-element-property :begin context))
11087 (throw :target-match t))))
11088 nil))))
11089 ;; Look for elements named after S, only if not in a headline
11090 ;; search.
11091 ((and (not starred)
11092 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11093 (catch :name-match
11094 (goto-char (point-min))
11095 (while (re-search-forward name nil t)
11096 (let ((element (org-element-at-point)))
11097 (when (equal (org-split-string
11098 (org-element-property :name element)
11099 "[ \t]+")
11100 words)
11101 (setq type 'dedicated)
11102 (beginning-of-line)
11103 (throw :name-match t))))
11104 nil))))
11105 ;; Regular text search. Prefer headlines in Org mode
11106 ;; buffers.
11107 ((and (derived-mode-p 'org-mode)
11108 (let* ((wspace "[ \t]")
11109 (wspaceopt (concat wspace "*"))
11110 (cookie (concat "\\(?:"
11111 wspaceopt
11112 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11113 wspaceopt
11114 "\\)"))
11115 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11116 (re (concat
11117 org-outline-regexp-bol
11118 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11119 "\\(?:\\[#.\\][ \t]+\\)?"
11120 "\\(?:" org-comment-string "[ \t]+\\)?"
11121 sep "?"
11122 (let ((title (mapconcat #'regexp-quote
11123 words
11124 sep)))
11125 (if starred (substring title 1) title))
11126 sep "?"
11127 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11128 "[ \t]*$")))
11129 (goto-char (point-min))
11130 (re-search-forward re nil t)))
11131 (goto-char (match-beginning 0))
11132 (setq type 'dedicated))
11133 ;; Offer to create non-existent headline depending on
11134 ;; `org-link-search-must-match-exact-headline'.
11135 ((and (derived-mode-p 'org-mode)
11136 (not org-link-search-inhibit-query)
11137 (eq org-link-search-must-match-exact-headline 'query-to-create)
11138 (yes-or-no-p "No match - create this as a new heading? "))
11139 (goto-char (point-max))
11140 (unless (bolp) (newline))
11141 (org-insert-heading nil t t)
11142 (insert s "\n")
11143 (beginning-of-line 0))
11144 ;; Only headlines are looked after. No need to process
11145 ;; further: throw an error.
11146 ((and (derived-mode-p 'org-mode)
11147 (or starred org-link-search-must-match-exact-headline))
11148 (goto-char origin)
11149 (error "No match for fuzzy expression: %s" normalized))
11150 ;; Regular text search.
11151 ((catch :fuzzy-match
11152 (goto-char (point-min))
11153 (while (re-search-forward s-multi-re nil t)
11154 ;; Skip match if it contains AVOID-POS or it is included
11155 ;; in a link with a description but outside the
11156 ;; description.
11157 (unless (or (and avoid-pos
11158 (<= (match-beginning 0) avoid-pos)
11159 (> (match-end 0) avoid-pos))
11160 (and (save-match-data
11161 (org-in-regexp org-bracket-link-regexp))
11162 (match-beginning 3)
11163 (or (> (match-beginning 3) (point))
11164 (<= (match-end 3) (point)))
11165 (org-element-lineage
11166 (save-match-data (org-element-context))
11167 '(link) t)))
11168 (goto-char (match-beginning 0))
11169 (setq type 'fuzzy)
11170 (throw :fuzzy-match t)))
11171 nil))
11172 ;; All failed. Throw an error.
11173 (t (goto-char origin)
11174 (error "No match for fuzzy expression: %s" normalized))))))
11175 ;; Disclose surroundings of match, if appropriate.
11176 (when (and (derived-mode-p 'org-mode) (not stealth))
11177 (org-show-context 'link-search))
11178 type))
11180 (defun org-get-buffer-for-internal-link (buffer)
11181 "Return a buffer to be used for displaying the link target of internal links."
11182 (cond
11183 ((not org-display-internal-link-with-indirect-buffer)
11184 buffer)
11185 ((string-match "(Clone)$" (buffer-name buffer))
11186 (message "Buffer is already a clone, not making another one")
11187 ;; we also do not modify visibility in this case
11188 buffer)
11189 (t ; make a new indirect buffer for displaying the link
11190 (let* ((bn (buffer-name buffer))
11191 (ibn (concat bn "(Clone)"))
11192 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11193 (with-current-buffer ib (org-overview))
11194 ib))))
11196 (defun org-do-occur (regexp &optional cleanup)
11197 "Call the Emacs command `occur'.
11198 If CLEANUP is non-nil, remove the printout of the regular expression
11199 in the *Occur* buffer. This is useful if the regex is long and not useful
11200 to read."
11201 (occur regexp)
11202 (when cleanup
11203 (let ((cwin (selected-window)) win beg end)
11204 (when (setq win (get-buffer-window "*Occur*"))
11205 (select-window win))
11206 (goto-char (point-min))
11207 (when (re-search-forward "match[a-z]+" nil t)
11208 (setq beg (match-end 0))
11209 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11210 (setq end (1- (match-beginning 0)))))
11211 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11212 (goto-char (point-min))
11213 (select-window cwin))))
11215 ;;; The mark ring for links jumps
11217 (defvar org-mark-ring nil
11218 "Mark ring for positions before jumps in Org-mode.")
11219 (defvar org-mark-ring-last-goto nil
11220 "Last position in the mark ring used to go back.")
11221 ;; Fill and close the ring
11222 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11223 (loop for i from 1 to org-mark-ring-length do
11224 (push (make-marker) org-mark-ring))
11225 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11226 org-mark-ring)
11228 (defun org-mark-ring-push (&optional pos buffer)
11229 "Put the current position or POS into the mark ring and rotate it."
11230 (interactive)
11231 (setq pos (or pos (point)))
11232 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11233 (move-marker (car org-mark-ring)
11234 (or pos (point))
11235 (or buffer (current-buffer)))
11236 (message "%s"
11237 (substitute-command-keys
11238 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11240 (defun org-mark-ring-goto (&optional n)
11241 "Jump to the previous position in the mark ring.
11242 With prefix arg N, jump back that many stored positions. When
11243 called several times in succession, walk through the entire ring.
11244 Org-mode commands jumping to a different position in the current file,
11245 or to another Org-mode file, automatically push the old position
11246 onto the ring."
11247 (interactive "p")
11248 (let (p m)
11249 (if (eq last-command this-command)
11250 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11251 (setq p org-mark-ring))
11252 (setq org-mark-ring-last-goto p)
11253 (setq m (car p))
11254 (org-pop-to-buffer-same-window (marker-buffer m))
11255 (goto-char m)
11256 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11258 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11259 ;;; Emacs 24.4+
11260 (defun org-remove-angle-brackets (s)
11261 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11262 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11264 (defun org-add-angle-brackets (s)
11265 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11266 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11268 (defun org-remove-double-quotes (s)
11269 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11270 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11273 ;;; Following specific links
11275 (defun org-follow-timestamp-link ()
11276 "Open an agenda view for the time-stamp date/range at point."
11277 (cond
11278 ((org-at-date-range-p t)
11279 (let ((org-agenda-start-on-weekday)
11280 (t1 (match-string 1))
11281 (t2 (match-string 2)) tt1 tt2)
11282 (setq tt1 (time-to-days (org-time-string-to-time t1))
11283 tt2 (time-to-days (org-time-string-to-time t2)))
11284 (let ((org-agenda-buffer-tmp-name
11285 (format "*Org Agenda(a:%s)"
11286 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11287 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11288 ((org-at-timestamp-p t)
11289 (let ((org-agenda-buffer-tmp-name
11290 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11291 (org-agenda-list nil (time-to-days (org-time-string-to-time
11292 (substring (match-string 1) 0 10)))
11293 1)))
11294 (t (error "This should not happen"))))
11297 ;;; Following file links
11298 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11299 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11300 (declare-function mailcap-mime-info
11301 "mailcap" (string &optional request no-decode))
11302 (defvar org-wait nil)
11303 (defun org-open-file (path &optional in-emacs line search)
11304 "Open the file at PATH.
11305 First, this expands any special file name abbreviations. Then the
11306 configuration variable `org-file-apps' is checked if it contains an
11307 entry for this file type, and if yes, the corresponding command is launched.
11309 If no application is found, Emacs simply visits the file.
11311 With optional prefix argument IN-EMACS, Emacs will visit the file.
11312 With a double \\[universal-argument] \\[universal-argument] \
11313 prefix arg, Org tries to avoid opening in Emacs
11314 and to use an external application to visit the file.
11316 Optional LINE specifies a line to go to, optional SEARCH a string
11317 to search for. If LINE or SEARCH is given, the file will be
11318 opened in Emacs, unless an entry from org-file-apps that makes
11319 use of groups in a regexp matches.
11321 If you want to change the way frames are used when following a
11322 link, please customize `org-link-frame-setup'.
11324 If the file does not exist, an error is thrown."
11325 (let* ((file (if (equal path "")
11326 buffer-file-name
11327 (substitute-in-file-name (expand-file-name path))))
11328 (file-apps (append org-file-apps (org-default-apps)))
11329 (apps (cl-remove-if
11330 'org-file-apps-entry-match-against-dlink-p file-apps))
11331 (apps-dlink (cl-remove-if-not
11332 'org-file-apps-entry-match-against-dlink-p file-apps))
11333 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11334 (dirp (unless remp (file-directory-p file)))
11335 (file (if (and dirp org-open-directory-means-index-dot-org)
11336 (concat (file-name-as-directory file) "index.org")
11337 file))
11338 (a-m-a-p (assq 'auto-mode apps))
11339 (dfile (downcase file))
11340 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11341 (link (cond ((and (eq line nil)
11342 (eq search nil))
11343 file)
11344 (line
11345 (concat file "::" (number-to-string line)))
11346 (search
11347 (concat file "::" search))))
11348 (dlink (downcase link))
11349 (old-buffer (current-buffer))
11350 (old-pos (point))
11351 (old-mode major-mode)
11352 ext cmd link-match-data)
11353 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11354 (setq ext (match-string 1 dfile))
11355 (when (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11356 (setq ext (match-string 1 dfile))))
11357 (cond
11358 ((member in-emacs '((16) system))
11359 (setq cmd (cdr (assoc 'system apps))))
11360 (in-emacs (setq cmd 'emacs))
11362 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11363 (and dirp (cdr (assoc 'directory apps)))
11364 ; first, try matching against apps-dlink
11365 ; if we get a match here, store the match data for later
11366 (let ((match (assoc-default dlink apps-dlink
11367 'string-match)))
11368 (if match
11369 (progn (setq link-match-data (match-data))
11370 match)
11371 (progn (setq in-emacs (or in-emacs line search))
11372 nil))) ; if we have no match in apps-dlink,
11373 ; always open the file in emacs if line or search
11374 ; is given (for backwards compatibility)
11375 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11376 'string-match)
11377 (cdr (assoc ext apps))
11378 (cdr (assoc t apps))))))
11379 (when (eq cmd 'system)
11380 (setq cmd (cdr (assoc 'system apps))))
11381 (when (eq cmd 'default)
11382 (setq cmd (cdr (assoc t apps))))
11383 (when (eq cmd 'mailcap)
11384 (require 'mailcap)
11385 (mailcap-parse-mailcaps)
11386 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11387 (command (mailcap-mime-info mime-type)))
11388 (if (stringp command)
11389 (setq cmd command)
11390 (setq cmd 'emacs))))
11391 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11392 (not (file-exists-p file))
11393 (not org-open-non-existing-files))
11394 (user-error "No such file: %s" file))
11395 (cond
11396 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11397 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11398 (while (string-match "['\"]%s['\"]" cmd)
11399 (setq cmd (replace-match "%s" t t cmd)))
11400 (while (string-match "%s" cmd)
11401 (setq cmd (replace-match
11402 (save-match-data
11403 (shell-quote-argument
11404 (convert-standard-filename file)))
11405 t t cmd)))
11407 ;; Replace "%1", "%2" etc. in command with group matches from regex
11408 (save-match-data
11409 (let ((match-index 1)
11410 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11411 (set-match-data link-match-data)
11412 (while (<= match-index number-of-groups)
11413 (let ((regex (concat "%" (number-to-string match-index)))
11414 (replace-with (match-string match-index dlink)))
11415 (while (string-match regex cmd)
11416 (setq cmd (replace-match replace-with t t cmd))))
11417 (setq match-index (+ match-index 1)))))
11419 (save-window-excursion
11420 (message "Running %s...done" cmd)
11421 (start-process-shell-command cmd nil cmd)
11422 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11423 ((or (stringp cmd)
11424 (eq cmd 'emacs))
11425 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11426 (widen)
11427 (if line (progn (org-goto-line line)
11428 (when (derived-mode-p 'org-mode)
11429 (org-reveal)))
11430 (when search (org-link-search search))))
11431 ((consp cmd)
11432 (let ((file (convert-standard-filename file)))
11433 (save-match-data
11434 (set-match-data link-match-data)
11435 (eval cmd))))
11436 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11437 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11438 (or (not (equal old-buffer (current-buffer)))
11439 (not (equal old-pos (point))))
11440 (org-mark-ring-push old-pos old-buffer))))
11442 (defun org-file-apps-entry-match-against-dlink-p (entry)
11443 "This function returns non-nil if `entry' uses a regular
11444 expression which should be matched against the whole link by
11445 org-open-file.
11447 It assumes that is the case when the entry uses a regular
11448 expression which has at least one grouping construct and the
11449 action is either a lisp form or a command string containing
11450 `%1', i.e. using at least one subexpression match as a
11451 parameter."
11452 (let ((selector (car entry))
11453 (action (cdr entry)))
11454 (if (stringp selector)
11455 (and (> (regexp-opt-depth selector) 0)
11456 (or (and (stringp action)
11457 (string-match "%[0-9]" action))
11458 (consp action)))
11459 nil)))
11461 (defun org-default-apps ()
11462 "Return the default applications for this operating system."
11463 (cond
11464 ((eq system-type 'darwin)
11465 org-file-apps-defaults-macosx)
11466 ((eq system-type 'windows-nt)
11467 org-file-apps-defaults-windowsnt)
11468 (t org-file-apps-defaults-gnu)))
11470 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11471 "Convert extensions to regular expressions in the cars of LIST.
11472 Also, weed out any non-string entries, because the return value is used
11473 only for regexp matching.
11474 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11475 point to the symbol `emacs', indicating that the file should
11476 be opened in Emacs."
11477 (append
11478 (delq nil
11479 (mapcar (lambda (x)
11480 (unless (not (stringp (car x)))
11481 (if (string-match "\\W" (car x))
11483 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11484 list))
11485 (when add-auto-mode
11486 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11488 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11489 (defun org-file-remote-p (file)
11490 "Test whether FILE specifies a location on a remote system.
11491 Return non-nil if the location is indeed remote.
11493 For example, the filename \"/user@host:/foo\" specifies a location
11494 on the system \"/user@host:\"."
11495 (cond ((fboundp 'file-remote-p)
11496 (file-remote-p file))
11497 ((fboundp 'tramp-handle-file-remote-p)
11498 (tramp-handle-file-remote-p file))
11499 ((and (boundp 'ange-ftp-name-format)
11500 (string-match (car ange-ftp-name-format) file))
11501 t)))
11504 ;;;; Refiling
11506 (defun org-get-org-file ()
11507 "Read a filename, with default directory `org-directory'."
11508 (let ((default (or org-default-notes-file remember-data-file)))
11509 (read-file-name (format "File name [%s]: " default)
11510 (file-name-as-directory org-directory)
11511 default)))
11513 (defun org-notes-order-reversed-p ()
11514 "Check if the current file should receive notes in reversed order."
11515 (cond
11516 ((not org-reverse-note-order) nil)
11517 ((eq t org-reverse-note-order) t)
11518 ((not (listp org-reverse-note-order)) nil)
11519 (t (catch 'exit
11520 (dolist (entry org-reverse-note-order)
11521 (when (string-match (car entry) buffer-file-name)
11522 (throw 'exit (cdr entry))))))))
11524 (defvar org-refile-target-table nil
11525 "The list of refile targets, created by `org-refile'.")
11527 (defvar org-agenda-new-buffers nil
11528 "Buffers created to visit agenda files.")
11530 (defvar org-refile-cache nil
11531 "Cache for refile targets.")
11533 (defvar org-refile-markers nil
11534 "All the markers used for caching refile locations.")
11536 (defun org-refile-marker (pos)
11537 "Get a new refile marker, but only if caching is in use."
11538 (if (not org-refile-use-cache)
11540 (let ((m (make-marker)))
11541 (move-marker m pos)
11542 (push m org-refile-markers)
11543 m)))
11545 (defun org-refile-cache-clear ()
11546 "Clear the refile cache and disable all the markers."
11547 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11548 (setq org-refile-markers nil)
11549 (setq org-refile-cache nil)
11550 (message "Refile cache has been cleared"))
11552 (defun org-refile-cache-check-set (set)
11553 "Check if all the markers in the cache still have live buffers."
11554 (let (marker)
11555 (catch 'exit
11556 (while (and set (setq marker (nth 3 (pop set))))
11557 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11558 (when (and marker (null (marker-buffer marker)))
11559 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11560 (sit-for 3)
11561 (throw 'exit nil)))
11562 t)))
11564 (defun org-refile-cache-put (set &rest identifiers)
11565 "Push the refile targets SET into the cache, under IDENTIFIERS."
11566 (let* ((key (sha1 (prin1-to-string identifiers)))
11567 (entry (assoc key org-refile-cache)))
11568 (if entry
11569 (setcdr entry set)
11570 (push (cons key set) org-refile-cache))))
11572 (defun org-refile-cache-get (&rest identifiers)
11573 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11574 (cond
11575 ((not org-refile-cache) nil)
11576 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11578 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11579 org-refile-cache))))
11580 (and set (org-refile-cache-check-set set) set)))))
11582 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11583 "Produce a table with refile targets."
11584 (let ((case-fold-search nil)
11585 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11586 (entries (or org-refile-targets '((nil . (:level . 1)))))
11587 targets tgs txt re files desc descre fast-path-p level pos0)
11588 (message "Getting targets...")
11589 (with-current-buffer (or default-buffer (current-buffer))
11590 (dolist (entry entries)
11591 (setq files (car entry) desc (cdr entry))
11592 (setq fast-path-p nil)
11593 (cond
11594 ((null files) (setq files (list (current-buffer))))
11595 ((eq files 'org-agenda-files)
11596 (setq files (org-agenda-files 'unrestricted)))
11597 ((and (symbolp files) (fboundp files))
11598 (setq files (funcall files)))
11599 ((and (symbolp files) (boundp files))
11600 (setq files (symbol-value files))))
11601 (when (stringp files) (setq files (list files)))
11602 (cond
11603 ((eq (car desc) :tag)
11604 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11605 ((eq (car desc) :todo)
11606 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11607 ((eq (car desc) :regexp)
11608 (setq descre (cdr desc)))
11609 ((eq (car desc) :level)
11610 (setq descre (concat "^\\*\\{" (number-to-string
11611 (if org-odd-levels-only
11612 (1- (* 2 (cdr desc)))
11613 (cdr desc)))
11614 "\\}[ \t]")))
11615 ((eq (car desc) :maxlevel)
11616 (setq fast-path-p t)
11617 (setq descre (concat "^\\*\\{1," (number-to-string
11618 (if org-odd-levels-only
11619 (1- (* 2 (cdr desc)))
11620 (cdr desc)))
11621 "\\}[ \t]")))
11622 (t (error "Bad refiling target description %s" desc)))
11623 (dolist (f files)
11624 (with-current-buffer
11625 (if (bufferp f) f (org-get-agenda-file-buffer f))
11627 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11628 (progn
11629 (when (bufferp f) (setq f (buffer-file-name
11630 (buffer-base-buffer f))))
11631 (setq f (and f (expand-file-name f)))
11632 (when (eq org-refile-use-outline-path 'file)
11633 (push (list (file-name-nondirectory f) f nil nil) tgs))
11634 (save-excursion
11635 (save-restriction
11636 (widen)
11637 (goto-char (point-min))
11638 (while (re-search-forward descre nil t)
11639 (goto-char (setq pos0 (point-at-bol)))
11640 (catch 'next
11641 (when org-refile-target-verify-function
11642 (save-match-data
11643 (or (funcall org-refile-target-verify-function)
11644 (throw 'next t))))
11645 (when (and (looking-at org-complex-heading-regexp)
11646 (not (member (match-string 4) excluded-entries))
11647 (match-string 4))
11648 (setq level (org-reduced-level
11649 (- (match-end 1) (match-beginning 1)))
11650 txt (org-link-display-format (match-string 4))
11651 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11652 re (format org-complex-heading-regexp-format
11653 (regexp-quote (match-string 4))))
11654 (when org-refile-use-outline-path
11655 (setq txt (mapconcat
11656 'org-protect-slash
11657 (append
11658 (if (eq org-refile-use-outline-path
11659 'file)
11660 (list (file-name-nondirectory
11661 (buffer-file-name
11662 (buffer-base-buffer))))
11663 (when (eq org-refile-use-outline-path
11664 'full-file-path)
11665 (list (buffer-file-name
11666 (buffer-base-buffer)))))
11667 (org-get-outline-path fast-path-p
11668 level txt)
11669 (list txt))
11670 "/")))
11671 (push (list txt f re (org-refile-marker (point)))
11672 tgs)))
11673 (when (= (point) pos0)
11674 ;; verification function has not moved point
11675 (goto-char (point-at-eol))))))))
11676 (when org-refile-use-cache
11677 (org-refile-cache-put tgs (buffer-file-name) descre))
11678 (setq targets (append tgs targets))))))
11679 (message "Getting targets...done")
11680 (nreverse targets)))
11682 (defun org-protect-slash (s)
11683 (while (string-match "/" s)
11684 (setq s (replace-match "\\" t t s)))
11687 (defvar org-olpa (make-vector 20 nil))
11689 (defun org-get-outline-path (&optional fastp level heading)
11690 "Return the outline path to the current entry, as a list.
11692 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11693 routine which makes outline path derivations for an entire file,
11694 avoiding backtracing. Refile target collection makes use of that."
11695 (if fastp
11696 (progn
11697 (when (> level 19)
11698 (error "Outline path failure, more than 19 levels"))
11699 (loop for i from level upto 19 do
11700 (aset org-olpa i nil))
11701 (prog1
11702 (delq nil (append org-olpa nil))
11703 (aset org-olpa level heading)))
11704 (let (rtn case-fold-search)
11705 (save-excursion
11706 (save-restriction
11707 (widen)
11708 (while (org-up-heading-safe)
11709 (when (looking-at org-complex-heading-regexp)
11710 (push (org-trim
11711 (replace-regexp-in-string
11712 ;; Remove statistical/checkboxes cookies
11713 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11714 (org-match-string-no-properties 4)))
11715 rtn)))
11716 rtn)))))
11718 (defun org-format-outline-path (path &optional width prefix separator)
11719 "Format the outline path PATH for display.
11720 WIDTH is the maximum number of characters that is available.
11721 PREFIX is a prefix to be included in the returned string,
11722 such as the file name.
11723 SEPARATOR is inserted between the different parts of the path,
11724 the default is \"/\"."
11725 (setq width (or width 79))
11726 (setq path (delq nil path))
11727 (unless (> width 0)
11728 (user-error "Argument `width' must be positive"))
11729 (setq separator (or separator "/"))
11730 (let* ((org-odd-levels-only nil)
11731 (fpath (concat
11732 prefix (and prefix path separator)
11733 (mapconcat
11734 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11735 (loop for head in path
11736 for n from 0
11737 collect (org-add-props
11738 head nil 'face
11739 (nth (% n org-n-level-faces) org-level-faces)))
11740 separator))))
11741 (when (> (length fpath) width)
11742 (if (< width 7)
11743 ;; It's unlikely that `width' will be this small, but don't
11744 ;; waste characters by adding ".." if it is.
11745 (setq fpath (substring fpath 0 width))
11746 (setf (substring fpath (- width 2)) "..")))
11747 fpath))
11749 (defun org-display-outline-path (&optional file current separator just-return-string)
11750 "Display the current outline path in the echo area.
11752 If FILE is non-nil, prepend the output with the file name.
11753 If CURRENT is non-nil, append the current heading to the output.
11754 SEPARATOR is passed through to `org-format-outline-path'. It separates
11755 the different parts of the path and defaults to \"/\".
11756 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11757 (interactive "P")
11758 (let* (case-fold-search
11759 (bfn (buffer-file-name (buffer-base-buffer)))
11760 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11761 res)
11762 (when current (setq path (append path
11763 (save-excursion
11764 (org-back-to-heading t)
11765 (when (looking-at org-complex-heading-regexp)
11766 (list (match-string 4)))))))
11767 (setq res
11768 (org-format-outline-path
11769 path
11770 (1- (frame-width))
11771 (and file bfn (concat (file-name-nondirectory bfn) separator))
11772 separator))
11773 (if just-return-string
11774 (org-no-properties res)
11775 (org-unlogged-message "%s" res))))
11777 (defvar org-refile-history nil
11778 "History for refiling operations.")
11780 (defvar org-after-refile-insert-hook nil
11781 "Hook run after `org-refile' has inserted its stuff at the new location.
11782 Note that this is still *before* the stuff will be removed from
11783 the *old* location.")
11785 (defvar org-capture-last-stored-marker)
11786 (defvar org-refile-keep nil
11787 "Non-nil means `org-refile' will copy instead of refile.")
11789 (defun org-copy ()
11790 "Like `org-refile', but copy."
11791 (interactive)
11792 (let ((org-refile-keep t))
11793 (funcall 'org-refile nil nil nil "Copy")))
11795 (defun org-refile (&optional arg default-buffer rfloc msg)
11796 "Move the entry or entries at point to another heading.
11797 The list of target headings is compiled using the information in
11798 `org-refile-targets', which see.
11800 At the target location, the entry is filed as a subitem of the
11801 target heading. Depending on `org-reverse-note-order', the new
11802 subitem will either be the first or the last subitem.
11804 If there is an active region, all entries in that region will be
11805 refiled. However, the region must fulfill the requirement that
11806 the first heading sets the top-level of the moved text.
11808 With prefix arg ARG, the command will only visit the target
11809 location and not actually move anything.
11811 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11812 refiling operation has put the subtree.
11814 With a numeric prefix argument of `2', refile to the running clock.
11816 With a numeric prefix argument of `3', emulate `org-refile-keep'
11817 being set to t and copy to the target location, don't move it.
11818 Beware that keeping refiled entries may result in duplicated ID
11819 properties.
11821 RFLOC can be a refile location obtained in a different way.
11823 MSG is a string to replace \"Refile\" in the default prompt with
11824 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11826 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11828 If you are using target caching (see `org-refile-use-cache'), you
11829 have to clear the target cache in order to find new targets.
11830 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11831 prefix argument (`C-u C-u C-u C-c C-w')."
11832 (interactive "P")
11833 (if (member arg '(0 (64)))
11834 (org-refile-cache-clear)
11835 (let* ((actionmsg (cond (msg msg)
11836 ((equal arg 3) "Refile (and keep)")
11837 (t "Refile")))
11838 (cbuf (current-buffer))
11839 (regionp (org-region-active-p))
11840 (region-start (and regionp (region-beginning)))
11841 (region-end (and regionp (region-end)))
11842 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11843 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11844 pos it nbuf file re level reversed)
11845 (setq last-command nil)
11846 (when regionp
11847 (goto-char region-start)
11848 (or (bolp) (goto-char (point-at-bol)))
11849 (setq region-start (point))
11850 (unless (or (org-kill-is-subtree-p
11851 (buffer-substring region-start region-end))
11852 (prog1 org-refile-active-region-within-subtree
11853 (let ((s (point-at-eol)))
11854 (org-toggle-heading)
11855 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11856 (user-error "The region is not a (sequence of) subtree(s)")))
11857 (if (equal arg '(16))
11858 (org-refile-goto-last-stored)
11859 (when (or
11860 (and (equal arg 2)
11861 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11862 (prog1
11863 (setq it (list (or org-clock-heading "running clock")
11864 (buffer-file-name
11865 (marker-buffer org-clock-hd-marker))
11867 (marker-position org-clock-hd-marker)))
11868 (setq arg nil)))
11869 (setq it (or rfloc
11870 (let (heading-text)
11871 (save-excursion
11872 (unless (and arg (listp arg))
11873 (org-back-to-heading t)
11874 (setq heading-text
11875 (replace-regexp-in-string
11876 org-bracket-link-regexp
11877 "\\3"
11878 (nth 4 (org-heading-components)))))
11879 (org-refile-get-location
11880 (cond ((and arg (listp arg)) "Goto")
11881 (regionp (concat actionmsg " region to"))
11882 (t (concat actionmsg " subtree \""
11883 heading-text "\" to")))
11884 default-buffer
11885 (and (not (equal '(4) arg))
11886 org-refile-allow-creating-parent-nodes)
11887 arg))))))
11888 (setq file (nth 1 it)
11889 re (nth 2 it)
11890 pos (nth 3 it))
11891 (when (and (not arg)
11893 (equal (buffer-file-name) file)
11894 (if regionp
11895 (and (>= pos region-start)
11896 (<= pos region-end))
11897 (and (>= pos (point))
11898 (< pos (save-excursion
11899 (org-end-of-subtree t t))))))
11900 (error "Cannot refile to position inside the tree or region"))
11901 (setq nbuf (or (find-buffer-visiting file)
11902 (find-file-noselect file)))
11903 (if (and arg (not (equal arg 3)))
11904 (progn
11905 (org-pop-to-buffer-same-window nbuf)
11906 (goto-char pos)
11907 (org-show-context 'org-goto))
11908 (if regionp
11909 (progn
11910 (org-kill-new (buffer-substring region-start region-end))
11911 (org-save-markers-in-region region-start region-end))
11912 (org-copy-subtree 1 nil t))
11913 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11914 (find-file-noselect file)))
11915 (setq reversed (org-notes-order-reversed-p))
11916 (save-excursion
11917 (save-restriction
11918 (widen)
11919 (if pos
11920 (progn
11921 (goto-char pos)
11922 (looking-at org-outline-regexp)
11923 (setq level (org-get-valid-level (funcall outline-level) 1))
11924 (goto-char
11925 (if reversed
11926 (or (outline-next-heading) (point-max))
11927 (or (save-excursion (org-get-next-sibling))
11928 (org-end-of-subtree t t)
11929 (point-max)))))
11930 (setq level 1)
11931 (if (not reversed)
11932 (goto-char (point-max))
11933 (goto-char (point-min))
11934 (or (outline-next-heading) (goto-char (point-max)))))
11935 (unless (bolp) (newline))
11936 (org-paste-subtree level nil nil t)
11937 (when org-log-refile
11938 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11939 (unless (eq org-log-refile 'note)
11940 (save-excursion (org-add-log-note))))
11941 (and org-auto-align-tags
11942 (let ((org-loop-over-headlines-in-active-region nil))
11943 (org-set-tags nil t)))
11944 (let ((bookmark-name (plist-get org-bookmark-names-plist
11945 :last-refile)))
11946 (when bookmark-name
11947 (with-demoted-errors
11948 (bookmark-set bookmark-name))))
11949 ;; If we are refiling for capture, make sure that the
11950 ;; last-capture pointers point here
11951 (when (org-bound-and-true-p org-capture-is-refiling)
11952 (let ((bookmark-name (plist-get org-bookmark-names-plist
11953 :last-capture-marker)))
11954 (when bookmark-name
11955 (with-demoted-errors
11956 (bookmark-set bookmark-name))))
11957 (move-marker org-capture-last-stored-marker (point)))
11958 (when (fboundp 'deactivate-mark) (deactivate-mark))
11959 (run-hooks 'org-after-refile-insert-hook))))
11960 (unless org-refile-keep
11961 (if regionp
11962 (delete-region (point) (+ (point) (- region-end region-start)))
11963 (delete-region
11964 (and (org-back-to-heading t) (point))
11965 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11966 (when (featurep 'org-inlinetask)
11967 (org-inlinetask-remove-END-maybe))
11968 (setq org-markers-to-move nil)
11969 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11971 (defun org-refile-goto-last-stored ()
11972 "Go to the location where the last refile was stored."
11973 (interactive)
11974 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11975 (message "This is the location of the last refile"))
11977 (defun org-refile--get-location (refloc tbl)
11978 "When user refile to REFLOC, find the associated target in TBL.
11979 Also check `org-refile-target-table'."
11980 (car (delq
11982 (mapcar
11983 (lambda (r) (or (assoc r tbl)
11984 (assoc r org-refile-target-table)))
11985 (list (replace-regexp-in-string "/$" "" refloc)
11986 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11988 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11989 no-exclude)
11990 "Prompt the user for a refile location, using PROMPT.
11991 PROMPT should not be suffixed with a colon and a space, because
11992 this function appends the default value from
11993 `org-refile-history' automatically, if that is not empty.
11994 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11995 this is used for the GOTO interface."
11996 (let ((org-refile-targets org-refile-targets)
11997 (org-refile-use-outline-path org-refile-use-outline-path)
11998 excluded-entries)
11999 (when (and (derived-mode-p 'org-mode)
12000 (not org-refile-use-cache)
12001 (not no-exclude))
12002 (org-map-tree
12003 (lambda()
12004 (setq excluded-entries
12005 (append excluded-entries (list (org-get-heading t t)))))))
12006 (setq org-refile-target-table
12007 (org-refile-get-targets default-buffer excluded-entries)))
12008 (unless org-refile-target-table
12009 (user-error "No refile targets"))
12010 (let* ((cbuf (current-buffer))
12011 (partial-completion-mode nil)
12012 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12013 (cfunc (if (and org-refile-use-outline-path
12014 org-outline-path-complete-in-steps)
12015 'org-olpath-completing-read
12016 'org-icompleting-read))
12017 (extra (if org-refile-use-outline-path "/" ""))
12018 (cbnex (concat (buffer-name) extra))
12019 (filename (and cfn (expand-file-name cfn)))
12020 (tbl (mapcar
12021 (lambda (x)
12022 (if (and (not (member org-refile-use-outline-path
12023 '(file full-file-path)))
12024 (not (equal filename (nth 1 x))))
12025 (cons (concat (car x) extra " ("
12026 (file-name-nondirectory (nth 1 x)) ")")
12027 (cdr x))
12028 (cons (concat (car x) extra) (cdr x))))
12029 org-refile-target-table))
12030 (completion-ignore-case t)
12031 cdef
12032 (prompt (concat prompt
12033 (or (and (car org-refile-history)
12034 (concat " (default " (car org-refile-history) ")"))
12035 (and (assoc cbnex tbl) (setq cdef cbnex)
12036 (concat " (default " cbnex ")"))) ": "))
12037 pa answ parent-target child parent old-hist)
12038 (setq old-hist org-refile-history)
12039 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12040 nil 'org-refile-history (or cdef (car org-refile-history))))
12041 (if (setq pa (org-refile--get-location answ tbl))
12042 (progn
12043 (org-refile-check-position pa)
12044 (when (or (not org-refile-history)
12045 (not (eq old-hist org-refile-history))
12046 (not (equal (car pa) (car org-refile-history))))
12047 (setq org-refile-history
12048 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12049 org-refile-history
12050 (cdr org-refile-history))))
12051 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12052 (pop org-refile-history)))
12054 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12055 (progn
12056 (setq parent (match-string 1 answ)
12057 child (match-string 2 answ))
12058 (setq parent-target (org-refile--get-location parent tbl))
12059 (when (and parent-target
12060 (or (eq new-nodes t)
12061 (and (eq new-nodes 'confirm)
12062 (y-or-n-p (format "Create new node \"%s\"? "
12063 child)))))
12064 (org-refile-new-child parent-target child)))
12065 (user-error "Invalid target location")))))
12067 (declare-function org-string-nw-p "org-macs" (s))
12068 (defun org-refile-check-position (refile-pointer)
12069 "Check if the refile pointer matches the headline to which it points."
12070 (let* ((file (nth 1 refile-pointer))
12071 (re (nth 2 refile-pointer))
12072 (pos (nth 3 refile-pointer))
12073 buffer)
12074 (if (and (not (markerp pos)) (not file))
12075 (user-error "Please indicate a target file in the refile path")
12076 (when (org-string-nw-p re)
12077 (setq buffer (if (markerp pos)
12078 (marker-buffer pos)
12079 (or (find-buffer-visiting file)
12080 (find-file-noselect file))))
12081 (with-current-buffer buffer
12082 (save-excursion
12083 (save-restriction
12084 (widen)
12085 (goto-char pos)
12086 (beginning-of-line 1)
12087 (unless (org-looking-at-p re)
12088 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12090 (defun org-refile-new-child (parent-target child)
12091 "Use refile target PARENT-TARGET to add new CHILD below it."
12092 (unless parent-target
12093 (error "Cannot find parent for new node"))
12094 (let ((file (nth 1 parent-target))
12095 (pos (nth 3 parent-target))
12096 level)
12097 (with-current-buffer (or (find-buffer-visiting file)
12098 (find-file-noselect file))
12099 (save-excursion
12100 (save-restriction
12101 (widen)
12102 (if pos
12103 (goto-char pos)
12104 (goto-char (point-max))
12105 (unless (bolp) (newline)))
12106 (when (looking-at org-outline-regexp)
12107 (setq level (funcall outline-level))
12108 (org-end-of-subtree t t))
12109 (org-back-over-empty-lines)
12110 (insert "\n" (make-string
12111 (if pos (org-get-valid-level level 1) 1) ?*)
12112 " " child "\n")
12113 (beginning-of-line 0)
12114 (list (concat (car parent-target) "/" child) file "" (point)))))))
12116 (defun org-olpath-completing-read (prompt collection &rest args)
12117 "Read an outline path like a file name."
12118 (let ((thetable collection)
12119 (org-completion-use-ido nil) ; does not work with ido.
12120 (org-completion-use-iswitchb nil)) ; or iswitchb
12121 (apply #'org-icompleting-read
12122 prompt
12123 (lambda (string predicate &optional flag)
12124 (cond
12125 ((eq flag nil) (try-completion string thetable))
12126 ((eq flag t)
12127 (let ((l (length string)))
12128 (mapcar (lambda (x)
12129 (let ((r (substring x l))
12130 (f (if (string-match " ([^)]*)$" x)
12131 (match-string 0 x)
12132 "")))
12133 (if (string-match "/" r)
12134 (concat string (substring r 0 (match-end 0)) f)
12135 x)))
12136 (all-completions string thetable predicate))))
12137 ;; Exact match?
12138 ((eq flag 'lambda) (assoc string thetable))))
12139 args)))
12141 ;;;; Dynamic blocks
12143 (defun org-find-dblock (name)
12144 "Find the first dynamic block with name NAME in the buffer.
12145 If not found, stay at current position and return nil."
12146 (let ((case-fold-search t) pos)
12147 (save-excursion
12148 (goto-char (point-min))
12149 (setq pos (and (re-search-forward
12150 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12151 (match-beginning 0))))
12152 (when pos (goto-char pos))
12153 pos))
12155 (defun org-create-dblock (plist)
12156 "Create a dynamic block section, with parameters taken from PLIST.
12157 PLIST must contain a :name entry which is used as the name of the block."
12158 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12159 (end-of-line 1)
12160 (newline))
12161 (let ((col (current-column))
12162 (name (plist-get plist :name)))
12163 (insert "#+BEGIN: " name)
12164 (while plist
12165 (if (eq (car plist) :name)
12166 (setq plist (cddr plist))
12167 (insert " " (prin1-to-string (pop plist)))))
12168 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12169 (beginning-of-line -2)))
12171 (defun org-prepare-dblock ()
12172 "Prepare dynamic block for refresh.
12173 This empties the block, puts the cursor at the insert position and returns
12174 the property list including an extra property :name with the block name."
12175 (unless (looking-at org-dblock-start-re)
12176 (user-error "Not at a dynamic block"))
12177 (let* ((begdel (1+ (match-end 0)))
12178 (name (org-no-properties (match-string 1)))
12179 (params (append (list :name name)
12180 (read (concat "(" (match-string 3) ")")))))
12181 (save-excursion
12182 (beginning-of-line 1)
12183 (skip-chars-forward " \t")
12184 (setq params (plist-put params :indentation-column (current-column))))
12185 (unless (re-search-forward org-dblock-end-re nil t)
12186 (error "Dynamic block not terminated"))
12187 (setq params
12188 (append params
12189 (list :content (buffer-substring
12190 begdel (match-beginning 0)))))
12191 (delete-region begdel (match-beginning 0))
12192 (goto-char begdel)
12193 (open-line 1)
12194 params))
12196 (defun org-map-dblocks (&optional command)
12197 "Apply COMMAND to all dynamic blocks in the current buffer.
12198 If COMMAND is not given, use `org-update-dblock'."
12199 (let ((cmd (or command 'org-update-dblock)))
12200 (save-excursion
12201 (goto-char (point-min))
12202 (while (re-search-forward org-dblock-start-re nil t)
12203 (goto-char (match-beginning 0))
12204 (save-excursion
12205 (condition-case nil
12206 (funcall cmd)
12207 (error (message "Error during update of dynamic block"))))
12208 (unless (re-search-forward org-dblock-end-re nil t)
12209 (error "Dynamic block not terminated"))))))
12211 (defun org-dblock-update (&optional arg)
12212 "User command for updating dynamic blocks.
12213 Update the dynamic block at point. With prefix ARG, update all dynamic
12214 blocks in the buffer."
12215 (interactive "P")
12216 (if arg
12217 (org-update-all-dblocks)
12218 (or (looking-at org-dblock-start-re)
12219 (org-beginning-of-dblock))
12220 (org-update-dblock)))
12222 (defun org-update-dblock ()
12223 "Update the dynamic block at point.
12224 This means to empty the block, parse for parameters and then call
12225 the correct writing function."
12226 (interactive)
12227 (save-excursion
12228 (let* ((win (selected-window))
12229 (pos (point))
12230 (line (org-current-line))
12231 (params (org-prepare-dblock))
12232 (name (plist-get params :name))
12233 (indent (plist-get params :indentation-column))
12234 (cmd (intern (concat "org-dblock-write:" name))))
12235 (message "Updating dynamic block `%s' at line %d..." name line)
12236 (funcall cmd params)
12237 (message "Updating dynamic block `%s' at line %d...done" name line)
12238 (goto-char pos)
12239 (when (and indent (> indent 0))
12240 (setq indent (make-string indent ?\ ))
12241 (save-excursion
12242 (select-window win)
12243 (org-beginning-of-dblock)
12244 (forward-line 1)
12245 (while (not (looking-at org-dblock-end-re))
12246 (insert indent)
12247 (beginning-of-line 2))
12248 (when (looking-at org-dblock-end-re)
12249 (and (looking-at "[ \t]+")
12250 (replace-match ""))
12251 (insert indent)))))))
12253 (defun org-beginning-of-dblock ()
12254 "Find the beginning of the dynamic block at point.
12255 Error if there is no such block at point."
12256 (let ((pos (point))
12257 beg)
12258 (end-of-line 1)
12259 (if (and (re-search-backward org-dblock-start-re nil t)
12260 (setq beg (match-beginning 0))
12261 (re-search-forward org-dblock-end-re nil t)
12262 (> (match-end 0) pos))
12263 (goto-char beg)
12264 (goto-char pos)
12265 (error "Not in a dynamic block"))))
12267 (defun org-update-all-dblocks ()
12268 "Update all dynamic blocks in the buffer.
12269 This function can be used in a hook."
12270 (interactive)
12271 (when (derived-mode-p 'org-mode)
12272 (org-map-dblocks 'org-update-dblock)))
12275 ;;;; Completion
12277 (declare-function org-export-backend-name "org-export" (cl-x))
12278 (declare-function org-export-backend-options "org-export" (cl-x))
12279 (defun org-get-export-keywords ()
12280 "Return a list of all currently understood export keywords.
12281 Export keywords include options, block names, attributes and
12282 keywords relative to each registered export back-end."
12283 (let (keywords)
12284 (dolist (backend
12285 (org-bound-and-true-p org-export-registered-backends)
12286 (delq nil keywords))
12287 ;; Back-end name (for keywords, like #+LATEX:)
12288 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12289 (dolist (option-entry (org-export-backend-options backend))
12290 ;; Back-end options.
12291 (push (nth 1 option-entry) keywords)))))
12293 (defconst org-options-keywords
12294 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12295 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12296 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12297 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12298 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12300 (defcustom org-structure-template-alist
12301 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12302 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12303 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12304 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12305 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12306 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12307 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12308 ("L" "#+LaTeX: ")
12309 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12310 ("H" "#+HTML: ")
12311 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12312 ("A" "#+ASCII: ")
12313 ("i" "#+INDEX: ?")
12314 ("I" "#+INCLUDE: %file ?"))
12315 "Structure completion elements.
12316 This is a list of abbreviation keys and values. The value gets inserted
12317 if you type `<' followed by the key and then press the completion key,
12318 usually `TAB'. %file will be replaced by a file name after prompting
12319 for the file using completion. The cursor will be placed at the position
12320 of the `?' in the template.
12321 There are two templates for each key, the first uses the original Org syntax,
12322 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12323 the default when the /org-mtags.el/ module has been loaded. See also the
12324 variable `org-mtags-prefer-muse-templates'."
12325 :group 'org-completion
12326 :type '(repeat
12327 (list
12328 (string :tag "Key")
12329 (string :tag "Template")))
12330 :version "25.1"
12331 :package-version '(Org . "8.3"))
12333 (defun org-try-structure-completion ()
12334 "Try to complete a structure template before point.
12335 This looks for strings like \"<e\" on an otherwise empty line and
12336 expands them."
12337 (let ((l (buffer-substring (point-at-bol) (point)))
12339 (when (and (looking-at "[ \t]*$")
12340 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12341 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12342 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12343 (match-beginning 1)) a)
12344 t)))
12346 (defun org-complete-expand-structure-template (start cell)
12347 "Expand a structure template."
12348 (let ((rpl (nth 1 cell))
12349 (ind ""))
12350 (delete-region start (point))
12351 (when (string-match "\\`[ \t]*#\\+" rpl)
12352 (cond
12353 ((bolp))
12354 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12355 (setq ind (buffer-substring (point-at-bol) (point))))
12356 (t (newline))))
12357 (setq start (point))
12358 (when (string-match "%file" rpl)
12359 (setq rpl (replace-match
12360 (concat
12361 "\""
12362 (save-match-data
12363 (abbreviate-file-name (read-file-name "Include file: ")))
12364 "\"")
12365 t t rpl)))
12366 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12367 (concat "\n" ind)))
12368 (insert rpl)
12369 (when (re-search-backward "\\?" start t) (delete-char 1))))
12371 ;;;; TODO, DEADLINE, Comments
12373 (defun org-toggle-comment ()
12374 "Change the COMMENT state of an entry."
12375 (interactive)
12376 (save-excursion
12377 (org-back-to-heading)
12378 (looking-at org-complex-heading-regexp)
12379 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12380 (skip-chars-forward " \t")
12381 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12382 (if (org-in-commented-heading-p t)
12383 (delete-region (point)
12384 (progn (search-forward " " (line-end-position) 'move)
12385 (skip-chars-forward " \t")
12386 (point)))
12387 (insert org-comment-string)
12388 (unless (eolp) (insert " ")))))
12390 (defvar org-last-todo-state-is-todo nil
12391 "This is non-nil when the last TODO state change led to a TODO state.
12392 If the last change removed the TODO tag or switched to DONE, then
12393 this is nil.")
12395 (defvar org-setting-tags nil) ; dynamically skipped
12397 (defvar org-todo-setup-filter-hook nil
12398 "Hook for functions that pre-filter todo specs.
12399 Each function takes a todo spec and returns either nil or the spec
12400 transformed into canonical form." )
12402 (defvar org-todo-get-default-hook nil
12403 "Hook for functions that get a default item for todo.
12404 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12405 nil or a string to be used for the todo mark." )
12407 (defvar org-agenda-headline-snapshot-before-repeat)
12409 (defun org-current-effective-time ()
12410 "Return current time adjusted for `org-extend-today-until' variable."
12411 (let* ((ct (org-current-time))
12412 (dct (decode-time ct))
12413 (ct1
12414 (cond
12415 (org-use-last-clock-out-time-as-effective-time
12416 (or (org-clock-get-last-clock-out-time) ct))
12417 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12418 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12419 (t ct))))
12420 ct1))
12422 (defun org-todo-yesterday (&optional arg)
12423 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12424 (interactive "P")
12425 (if (eq major-mode 'org-agenda-mode)
12426 (apply 'org-agenda-todo-yesterday arg)
12427 (let* ((org-use-effective-time t)
12428 (hour (third (decode-time
12429 (org-current-time))))
12430 (org-extend-today-until (1+ hour)))
12431 (org-todo arg))))
12433 (defvar org-block-entry-blocking ""
12434 "First entry preventing the TODO state change.")
12436 (defun org-cancel-repeater ()
12437 "Cancel a repeater by setting its numeric value to zero."
12438 (interactive)
12439 (save-excursion
12440 (org-back-to-heading t)
12441 (let ((bound1 (point))
12442 (bound0 (save-excursion (outline-next-heading) (point))))
12443 (when (and (re-search-forward
12444 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12445 org-deadline-time-regexp "\\)\\|\\("
12446 org-ts-regexp "\\)")
12447 bound0 t)
12448 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12449 bound1 t))
12450 (replace-match "0" t nil nil 1)))))
12452 (defun org-todo (&optional arg)
12453 "Change the TODO state of an item.
12454 The state of an item is given by a keyword at the start of the heading,
12455 like
12456 *** TODO Write paper
12457 *** DONE Call mom
12459 The different keywords are specified in the variable `org-todo-keywords'.
12460 By default the available states are \"TODO\" and \"DONE\".
12461 So for this example: when the item starts with TODO, it is changed to DONE.
12462 When it starts with DONE, the DONE is removed. And when neither TODO nor
12463 DONE are present, add TODO at the beginning of the heading.
12465 With \\[universal-argument] prefix arg, use completion to determine the new \
12466 state.
12467 With numeric prefix arg, switch to that state.
12468 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12469 keywords (nextset).
12470 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12471 With a numeric prefix arg of 0, inhibit note taking for the change.
12472 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12474 When called through ELisp, arg is also interpreted in the following way:
12475 `none' -> empty state
12476 \"\"(empty string) -> switch to empty state
12477 `done' -> switch to DONE
12478 `nextset' -> switch to the next set of keywords
12479 `previousset' -> switch to the previous set of keywords
12480 \"WAITING\" -> switch to the specified keyword, but only if it
12481 really is a member of `org-todo-keywords'."
12482 (interactive "P")
12483 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12484 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12485 'region-start-level 'region))
12486 org-loop-over-headlines-in-active-region)
12487 (org-map-entries
12488 `(org-todo ,arg)
12489 org-loop-over-headlines-in-active-region
12490 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12491 (when (equal arg '(16)) (setq arg 'nextset))
12492 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12493 (let ((org-blocker-hook org-blocker-hook)
12494 commentp
12495 case-fold-search)
12496 (when (equal arg '(64))
12497 (setq arg nil org-blocker-hook nil))
12498 (when (and org-blocker-hook
12499 (or org-inhibit-blocking
12500 (org-entry-get nil "NOBLOCKING")))
12501 (setq org-blocker-hook nil))
12502 (save-excursion
12503 (catch 'exit
12504 (org-back-to-heading t)
12505 (when (org-in-commented-heading-p t)
12506 (org-toggle-comment)
12507 (setq commentp t))
12508 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12509 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12510 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12511 (let* ((match-data (match-data))
12512 (startpos (point-at-bol))
12513 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12514 (org-log-done org-log-done)
12515 (org-log-repeat org-log-repeat)
12516 (org-todo-log-states org-todo-log-states)
12517 (org-inhibit-logging
12518 (if (equal arg 0)
12519 (progn (setq arg nil) 'note) org-inhibit-logging))
12520 (this (match-string 1))
12521 (hl-pos (match-beginning 0))
12522 (head (org-get-todo-sequence-head this))
12523 (ass (assoc head org-todo-kwd-alist))
12524 (interpret (nth 1 ass))
12525 (done-word (nth 3 ass))
12526 (final-done-word (nth 4 ass))
12527 (org-last-state (or this ""))
12528 (completion-ignore-case t)
12529 (member (member this org-todo-keywords-1))
12530 (tail (cdr member))
12531 (org-state (cond
12532 ((and org-todo-key-trigger
12533 (or (and (equal arg '(4))
12534 (eq org-use-fast-todo-selection 'prefix))
12535 (and (not arg) org-use-fast-todo-selection
12536 (not (eq org-use-fast-todo-selection
12537 'prefix)))))
12538 ;; Use fast selection
12539 (org-fast-todo-selection))
12540 ((and (equal arg '(4))
12541 (or (not org-use-fast-todo-selection)
12542 (not org-todo-key-trigger)))
12543 ;; Read a state with completion
12544 (org-icompleting-read
12545 "State: " (mapcar 'list org-todo-keywords-1)
12546 nil t))
12547 ((eq arg 'right)
12548 (if this
12549 (if tail (car tail) nil)
12550 (car org-todo-keywords-1)))
12551 ((eq arg 'left)
12552 (unless (equal member org-todo-keywords-1)
12553 (if this
12554 (nth (- (length org-todo-keywords-1)
12555 (length tail) 2)
12556 org-todo-keywords-1)
12557 (org-last org-todo-keywords-1))))
12558 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12559 (setq arg nil))) ; hack to fall back to cycling
12560 (arg
12561 ;; user or caller requests a specific state
12562 (cond
12563 ((equal arg "") nil)
12564 ((eq arg 'none) nil)
12565 ((eq arg 'done) (or done-word (car org-done-keywords)))
12566 ((eq arg 'nextset)
12567 (or (car (cdr (member head org-todo-heads)))
12568 (car org-todo-heads)))
12569 ((eq arg 'previousset)
12570 (let ((org-todo-heads (reverse org-todo-heads)))
12571 (or (car (cdr (member head org-todo-heads)))
12572 (car org-todo-heads))))
12573 ((car (member arg org-todo-keywords-1)))
12574 ((stringp arg)
12575 (user-error "State `%s' not valid in this file" arg))
12576 ((nth (1- (prefix-numeric-value arg))
12577 org-todo-keywords-1))))
12578 ((null member) (or head (car org-todo-keywords-1)))
12579 ((equal this final-done-word) nil) ;; -> make empty
12580 ((null tail) nil) ;; -> first entry
12581 ((memq interpret '(type priority))
12582 (if (eq this-command last-command)
12583 (car tail)
12584 (if (> (length tail) 0)
12585 (or done-word (car org-done-keywords))
12586 nil)))
12588 (car tail))))
12589 (org-state (or
12590 (run-hook-with-args-until-success
12591 'org-todo-get-default-hook org-state org-last-state)
12592 org-state))
12593 (next (if org-state (concat " " org-state " ") " "))
12594 (change-plist (list :type 'todo-state-change :from this :to org-state
12595 :position startpos))
12596 dolog now-done-p)
12597 (when org-blocker-hook
12598 (setq org-last-todo-state-is-todo
12599 (not (member this org-done-keywords)))
12600 (unless (save-excursion
12601 (save-match-data
12602 (org-with-wide-buffer
12603 (run-hook-with-args-until-failure
12604 'org-blocker-hook change-plist))))
12605 (if (org-called-interactively-p 'interactive)
12606 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12607 this org-state org-block-entry-blocking)
12608 ;; fail silently
12609 (message "TODO state change from %s to %s blocked (by \"%s\")"
12610 this org-state org-block-entry-blocking)
12611 (throw 'exit nil))))
12612 (store-match-data match-data)
12613 (replace-match next t t)
12614 (cond ((equal this org-state)
12615 (message "TODO state was already %s" (org-trim next)))
12616 ((pos-visible-in-window-p hl-pos)
12617 (message "TODO state changed to %s" (org-trim next))))
12618 (unless head
12619 (setq head (org-get-todo-sequence-head org-state)
12620 ass (assoc head org-todo-kwd-alist)
12621 interpret (nth 1 ass)
12622 done-word (nth 3 ass)
12623 final-done-word (nth 4 ass)))
12624 (when (memq arg '(nextset previousset))
12625 (message "Keyword-Set %d/%d: %s"
12626 (- (length org-todo-sets) -1
12627 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12628 (length org-todo-sets)
12629 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12630 (setq org-last-todo-state-is-todo
12631 (not (member org-state org-done-keywords)))
12632 (setq now-done-p (and (member org-state org-done-keywords)
12633 (not (member this org-done-keywords))))
12634 (and logging (org-local-logging logging))
12635 (when (and (or org-todo-log-states org-log-done)
12636 (not (eq org-inhibit-logging t))
12637 (not (memq arg '(nextset previousset))))
12638 ;; we need to look at recording a time and note
12639 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12640 (nth 2 (assoc this org-todo-log-states))))
12641 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12642 (setq dolog 'time))
12643 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12644 (and org-state
12645 (member org-state org-not-done-keywords)
12646 (not (member this org-not-done-keywords))))
12647 ;; This is now a todo state and was not one before
12648 ;; If there was a CLOSED time stamp, get rid of it.
12649 (org-add-planning-info nil nil 'closed))
12650 (when (and now-done-p org-log-done)
12651 ;; It is now done, and it was not done before
12652 (org-add-planning-info 'closed (org-current-effective-time))
12653 (when (and (not dolog) (eq 'note org-log-done))
12654 (org-add-log-setup 'done org-state this 'findpos 'note)))
12655 (when (and org-state dolog)
12656 ;; This is a non-nil state, and we need to log it
12657 (org-add-log-setup 'state org-state this 'findpos dolog)))
12658 ;; Fixup tag positioning
12659 (org-todo-trigger-tag-changes org-state)
12660 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12661 (when org-provide-todo-statistics
12662 (org-update-parent-todo-statistics))
12663 (run-hooks 'org-after-todo-state-change-hook)
12664 (when (and arg (not (member org-state org-done-keywords)))
12665 (setq head (org-get-todo-sequence-head org-state)))
12666 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12667 ;; Do we need to trigger a repeat?
12668 (when now-done-p
12669 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12670 ;; This is for the agenda, take a snapshot of the headline.
12671 (save-match-data
12672 (setq org-agenda-headline-snapshot-before-repeat
12673 (org-get-heading))))
12674 (org-auto-repeat-maybe org-state))
12675 ;; Fixup cursor location if close to the keyword
12676 (when (and (outline-on-heading-p)
12677 (not (bolp))
12678 (save-excursion (beginning-of-line 1)
12679 (looking-at org-todo-line-regexp))
12680 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12681 (goto-char (or (match-end 2) (match-end 1)))
12682 (and (looking-at " ") (just-one-space)))
12683 (when org-trigger-hook
12684 (save-excursion
12685 (run-hook-with-args 'org-trigger-hook change-plist)))
12686 (when commentp (org-toggle-comment))))))))
12688 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12689 "Block turning an entry into a TODO, using the hierarchy.
12690 This checks whether the current task should be blocked from state
12691 changes. Such blocking occurs when:
12693 1. The task has children which are not all in a completed state.
12695 2. A task has a parent with the property :ORDERED:, and there
12696 are siblings prior to the current task with incomplete
12697 status.
12699 3. The parent of the task is blocked because it has siblings that should
12700 be done first, or is child of a block grandparent TODO entry."
12702 (if (not org-enforce-todo-dependencies)
12703 t ; if locally turned off don't block
12704 (catch 'dont-block
12705 ;; If this is not a todo state change, or if this entry is already DONE,
12706 ;; do not block
12707 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12708 (member (plist-get change-plist :from)
12709 (cons 'done org-done-keywords))
12710 (member (plist-get change-plist :to)
12711 (cons 'todo org-not-done-keywords))
12712 (not (plist-get change-plist :to)))
12713 (throw 'dont-block t))
12714 ;; If this task has children, and any are undone, it's blocked
12715 (save-excursion
12716 (org-back-to-heading t)
12717 (let ((this-level (funcall outline-level)))
12718 (outline-next-heading)
12719 (let ((child-level (funcall outline-level)))
12720 (while (and (not (eobp))
12721 (> child-level this-level))
12722 ;; this todo has children, check whether they are all
12723 ;; completed
12724 (when (and (not (org-entry-is-done-p))
12725 (org-entry-is-todo-p))
12726 (setq org-block-entry-blocking (org-get-heading))
12727 (throw 'dont-block nil))
12728 (outline-next-heading)
12729 (setq child-level (funcall outline-level))))))
12730 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12731 ;; any previous siblings are undone, it's blocked
12732 (save-excursion
12733 (org-back-to-heading t)
12734 (let* ((pos (point))
12735 (parent-pos (and (org-up-heading-safe) (point))))
12736 (unless parent-pos (throw 'dont-block t)) ; no parent
12737 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12738 (forward-line 1)
12739 (re-search-forward org-not-done-heading-regexp pos t))
12740 (setq org-block-entry-blocking (match-string 0))
12741 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12742 ;; Search further up the hierarchy, to see if an ancestor is blocked
12743 (while t
12744 (goto-char parent-pos)
12745 (unless (looking-at org-not-done-heading-regexp)
12746 (throw 'dont-block t)) ; do not block, parent is not a TODO
12747 (setq pos (point))
12748 (setq parent-pos (and (org-up-heading-safe) (point)))
12749 (unless parent-pos (throw 'dont-block t)) ; no parent
12750 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12751 (forward-line 1)
12752 (re-search-forward org-not-done-heading-regexp pos t)
12753 (setq org-block-entry-blocking (org-get-heading)))
12754 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12756 (defcustom org-track-ordered-property-with-tag nil
12757 "Should the ORDERED property also be shown as a tag?
12758 The ORDERED property decides if an entry should require subtasks to be
12759 completed in sequence. Since a property is not very visible, setting
12760 this option means that toggling the ORDERED property with the command
12761 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12762 not relevant for the behavior, but it makes things more visible.
12764 Note that toggling the tag with tags commands will not change the property
12765 and therefore not influence behavior!
12767 This can be t, meaning the tag ORDERED should be used, It can also be a
12768 string to select a different tag for this task."
12769 :group 'org-todo
12770 :type '(choice
12771 (const :tag "No tracking" nil)
12772 (const :tag "Track with ORDERED tag" t)
12773 (string :tag "Use other tag")))
12775 (defun org-toggle-ordered-property ()
12776 "Toggle the ORDERED property of the current entry.
12777 For better visibility, you can track the value of this property with a tag.
12778 See variable `org-track-ordered-property-with-tag'."
12779 (interactive)
12780 (let* ((t1 org-track-ordered-property-with-tag)
12781 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12782 (save-excursion
12783 (org-back-to-heading)
12784 (if (org-entry-get nil "ORDERED")
12785 (progn
12786 (org-delete-property "ORDERED")
12787 (and tag (org-toggle-tag tag 'off))
12788 (message "Subtasks can be completed in arbitrary order"))
12789 (org-entry-put nil "ORDERED" "t")
12790 (and tag (org-toggle-tag tag 'on))
12791 (message "Subtasks must be completed in sequence")))))
12793 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12794 (defun org-block-todo-from-checkboxes (change-plist)
12795 "Block turning an entry into a TODO, using checkboxes.
12796 This checks whether the current task should be blocked from state
12797 changes because there are unchecked boxes in this entry."
12798 (if (not org-enforce-todo-checkbox-dependencies)
12799 t ; if locally turned off don't block
12800 (catch 'dont-block
12801 ;; If this is not a todo state change, or if this entry is already DONE,
12802 ;; do not block
12803 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12804 (member (plist-get change-plist :from)
12805 (cons 'done org-done-keywords))
12806 (member (plist-get change-plist :to)
12807 (cons 'todo org-not-done-keywords))
12808 (not (plist-get change-plist :to)))
12809 (throw 'dont-block t))
12810 ;; If this task has checkboxes that are not checked, it's blocked
12811 (save-excursion
12812 (org-back-to-heading t)
12813 (let ((beg (point)) end)
12814 (outline-next-heading)
12815 (setq end (point))
12816 (goto-char beg)
12817 (when (org-list-search-forward
12818 (concat (org-item-beginning-re)
12819 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12820 "\\[[- ]\\]")
12821 end t)
12822 (when (boundp 'org-blocked-by-checkboxes)
12823 (setq org-blocked-by-checkboxes t))
12824 (throw 'dont-block nil))))
12825 t))) ; do not block
12827 (defun org-entry-blocked-p ()
12828 "Non-nil if entry at point is blocked."
12829 (and (not (org-entry-get nil "NOBLOCKING"))
12830 (member (org-entry-get nil "TODO") org-not-done-keywords)
12831 (not (run-hook-with-args-until-failure
12832 'org-blocker-hook
12833 (list :type 'todo-state-change
12834 :position (point)
12835 :from 'todo
12836 :to 'done)))))
12838 (defun org-update-statistics-cookies (all)
12839 "Update the statistics cookie, either from TODO or from checkboxes.
12840 This should be called with the cursor in a line with a statistics cookie."
12841 (interactive "P")
12842 (if all
12843 (progn
12844 (org-update-checkbox-count 'all)
12845 (org-map-entries 'org-update-parent-todo-statistics))
12846 (if (not (org-at-heading-p))
12847 (org-update-checkbox-count)
12848 (let ((pos (point-marker))
12849 end l1 l2)
12850 (ignore-errors (org-back-to-heading t))
12851 (if (not (org-at-heading-p))
12852 (org-update-checkbox-count)
12853 (setq l1 (org-outline-level))
12854 (setq end (save-excursion
12855 (outline-next-heading)
12856 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12857 (point)))
12858 (if (and (save-excursion
12859 (re-search-forward
12860 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12861 (not (save-excursion (re-search-forward
12862 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12863 (org-update-checkbox-count)
12864 (if (and l2 (> l2 l1))
12865 (progn
12866 (goto-char end)
12867 (org-update-parent-todo-statistics))
12868 (goto-char pos)
12869 (beginning-of-line 1)
12870 (while (re-search-forward
12871 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12872 (point-at-eol) t)
12873 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12874 (goto-char pos)
12875 (move-marker pos nil)))))
12877 (defvar org-entry-property-inherited-from) ;; defined below
12878 (defun org-update-parent-todo-statistics ()
12879 "Update any statistics cookie in the parent of the current headline.
12880 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12881 the entire subtree and this will travel up the hierarchy and update
12882 statistics everywhere."
12883 (let* ((prop (save-excursion (org-up-heading-safe)
12884 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12885 (recursive (or (not org-hierarchical-todo-statistics)
12886 (and prop (string-match "\\<recursive\\>" prop))))
12887 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12889 (first t)
12890 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12891 level ltoggle l1 new ndel
12892 (cnt-all 0) (cnt-done 0) is-percent kwd
12893 checkbox-beg ov ovs ove cookie-present)
12894 (catch 'exit
12895 (save-excursion
12896 (beginning-of-line 1)
12897 (setq ltoggle (funcall outline-level))
12898 ;; Three situations are to consider:
12900 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12901 ;; to the top-level ancestor on the headline;
12903 ;; 2. If parent has "recursive" property, repeat up to the
12904 ;; headline setting that property, taking inheritance into
12905 ;; account;
12907 ;; 3. Else, move up to direct parent and proceed only once.
12908 (while (and (setq level (org-up-heading-safe))
12909 (or recursive first)
12910 (>= (point) lim))
12911 (setq first nil cookie-present nil)
12912 (unless (and level
12913 (not (string-match
12914 "\\<checkbox\\>"
12915 (downcase (or (org-entry-get nil "COOKIE_DATA")
12916 "")))))
12917 (throw 'exit nil))
12918 (while (re-search-forward box-re (point-at-eol) t)
12919 (setq cnt-all 0 cnt-done 0 cookie-present t)
12920 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12921 (save-match-data
12922 (unless (outline-next-heading) (throw 'exit nil))
12923 (while (and (looking-at org-complex-heading-regexp)
12924 (> (setq l1 (length (match-string 1))) level))
12925 (setq kwd (and (or recursive (= l1 ltoggle))
12926 (match-string 2)))
12927 (if (or (eq org-provide-todo-statistics 'all-headlines)
12928 (and (eq org-provide-todo-statistics t)
12929 (or (member kwd org-done-keywords)))
12930 (and (listp org-provide-todo-statistics)
12931 (stringp (car org-provide-todo-statistics))
12932 (or (member kwd org-provide-todo-statistics)
12933 (member kwd org-done-keywords)))
12934 (and (listp org-provide-todo-statistics)
12935 (listp (car org-provide-todo-statistics))
12936 (or (member kwd (car org-provide-todo-statistics))
12937 (and (member kwd org-done-keywords)
12938 (member kwd (cadr org-provide-todo-statistics))))))
12939 (setq cnt-all (1+ cnt-all))
12940 (and (eq org-provide-todo-statistics t)
12942 (setq cnt-all (1+ cnt-all))))
12943 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12944 (member kwd org-done-keywords))
12945 (and (listp org-provide-todo-statistics)
12946 (listp (car org-provide-todo-statistics))
12947 (member kwd org-done-keywords)
12948 (member kwd (cadr org-provide-todo-statistics)))
12949 (and (listp org-provide-todo-statistics)
12950 (stringp (car org-provide-todo-statistics))
12951 (member kwd org-done-keywords)))
12952 (setq cnt-done (1+ cnt-done)))
12953 (outline-next-heading)))
12954 (setq new
12955 (if is-percent
12956 (format "[%d%%]" (floor (* 100.0 cnt-done)
12957 (max 1 cnt-all)))
12958 (format "[%d/%d]" cnt-done cnt-all))
12959 ndel (- (match-end 0) checkbox-beg))
12960 ;; handle overlays when updating cookie from column view
12961 (when (setq ov (car (overlays-at checkbox-beg)))
12962 (setq ovs (overlay-start ov) ove (overlay-end ov))
12963 (delete-overlay ov))
12964 (goto-char checkbox-beg)
12965 (insert new)
12966 (delete-region (point) (+ (point) ndel))
12967 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12968 (when ov (move-overlay ov ovs ove)))
12969 (when cookie-present
12970 (run-hook-with-args 'org-after-todo-statistics-hook
12971 cnt-done (- cnt-all cnt-done))))))
12972 (run-hooks 'org-todo-statistics-hook)))
12974 (defvar org-after-todo-statistics-hook nil
12975 "Hook that is called after a TODO statistics cookie has been updated.
12976 Each function is called with two arguments: the number of not-done entries
12977 and the number of done entries.
12979 For example, the following function, when added to this hook, will switch
12980 an entry to DONE when all children are done, and back to TODO when new
12981 entries are set to a TODO status. Note that this hook is only called
12982 when there is a statistics cookie in the headline!
12984 (defun org-summary-todo (n-done n-not-done)
12985 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12986 (let (org-log-done org-log-states) ; turn off logging
12987 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12990 (defvar org-todo-statistics-hook nil
12991 "Hook that is run whenever Org thinks TODO statistics should be updated.
12992 This hook runs even if there is no statistics cookie present, in which case
12993 `org-after-todo-statistics-hook' would not run.")
12995 (defun org-todo-trigger-tag-changes (state)
12996 "Apply the changes defined in `org-todo-state-tags-triggers'."
12997 (let ((l org-todo-state-tags-triggers)
12998 changes)
12999 (when (or (not state) (equal state ""))
13000 (setq changes (append changes (cdr (assoc "" l)))))
13001 (when (and (stringp state) (> (length state) 0))
13002 (setq changes (append changes (cdr (assoc state l)))))
13003 (when (member state org-not-done-keywords)
13004 (setq changes (append changes (cdr (assoc 'todo l)))))
13005 (when (member state org-done-keywords)
13006 (setq changes (append changes (cdr (assoc 'done l)))))
13007 (dolist (c changes)
13008 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13010 (defun org-local-logging (value)
13011 "Get logging settings from a property VALUE."
13012 ;; Directly set the variables, they are already local.
13013 (setq org-log-done nil
13014 org-log-repeat nil
13015 org-todo-log-states nil)
13016 (dolist (w (org-split-string value))
13017 (let (a)
13018 (cond
13019 ((setq a (assoc w org-startup-options))
13020 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13021 (set (nth 1 a) (nth 2 a))))
13022 ((setq a (org-extract-log-state-settings w))
13023 (and (member (car a) org-todo-keywords-1)
13024 (push a org-todo-log-states)))))))
13026 (defun org-get-todo-sequence-head (kwd)
13027 "Return the head of the TODO sequence to which KWD belongs.
13028 If KWD is not set, check if there is a text property remembering the
13029 right sequence."
13030 (let (p)
13031 (cond
13032 ((not kwd)
13033 (or (get-text-property (point-at-bol) 'org-todo-head)
13034 (progn
13035 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13036 nil (point-at-eol)))
13037 (get-text-property p 'org-todo-head))))
13038 ((not (member kwd org-todo-keywords-1))
13039 (car org-todo-keywords-1))
13040 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13042 (defun org-fast-todo-selection ()
13043 "Fast TODO keyword selection with single keys.
13044 Returns the new TODO keyword, or nil if no state change should occur."
13045 (let* ((fulltable org-todo-key-alist)
13046 (done-keywords org-done-keywords) ;; needed for the faces.
13047 (maxlen (apply 'max (mapcar
13048 (lambda (x)
13049 (if (stringp (car x)) (string-width (car x)) 0))
13050 fulltable)))
13051 (expert nil)
13052 (fwidth (+ maxlen 3 1 3))
13053 (ncol (/ (- (window-width) 4) fwidth))
13054 tg cnt e c tbl
13055 groups ingroup)
13056 (save-excursion
13057 (save-window-excursion
13058 (if expert
13059 (set-buffer (get-buffer-create " *Org todo*"))
13060 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13061 (erase-buffer)
13062 (setq-local org-done-keywords done-keywords)
13063 (setq tbl fulltable cnt 0)
13064 (while (setq e (pop tbl))
13065 (cond
13066 ((equal e '(:startgroup))
13067 (push '() groups) (setq ingroup t)
13068 (unless (= cnt 0)
13069 (setq cnt 0)
13070 (insert "\n"))
13071 (insert "{ "))
13072 ((equal e '(:endgroup))
13073 (setq ingroup nil cnt 0)
13074 (insert "}\n"))
13075 ((equal e '(:newline))
13076 (unless (= cnt 0)
13077 (setq cnt 0)
13078 (insert "\n")
13079 (setq e (car tbl))
13080 (while (equal (car tbl) '(:newline))
13081 (insert "\n")
13082 (setq tbl (cdr tbl)))))
13084 (setq tg (car e) c (cdr e))
13085 (when ingroup (push tg (car groups)))
13086 (setq tg (org-add-props tg nil 'face
13087 (org-get-todo-face tg)))
13088 (when (and (= cnt 0) (not ingroup)) (insert " "))
13089 (insert "[" c "] " tg (make-string
13090 (- fwidth 4 (length tg)) ?\ ))
13091 (when (= (setq cnt (1+ cnt)) ncol)
13092 (insert "\n")
13093 (when ingroup (insert " "))
13094 (setq cnt 0)))))
13095 (insert "\n")
13096 (goto-char (point-min))
13097 (unless expert (org-fit-window-to-buffer))
13098 (message "[a-z..]:Set [SPC]:clear")
13099 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13100 (cond
13101 ((or (= c ?\C-g)
13102 (and (= c ?q) (not (rassoc c fulltable))))
13103 (setq quit-flag t))
13104 ((= c ?\ ) nil)
13105 ((setq e (rassoc c fulltable) tg (car e))
13107 (t (setq quit-flag t)))))))
13109 (defun org-entry-is-todo-p ()
13110 (member (org-get-todo-state) org-not-done-keywords))
13112 (defun org-entry-is-done-p ()
13113 (member (org-get-todo-state) org-done-keywords))
13115 (defun org-get-todo-state ()
13116 "Return the TODO keyword of the current subtree."
13117 (save-excursion
13118 (org-back-to-heading t)
13119 (and (looking-at org-todo-line-regexp)
13120 (match-end 2)
13121 (match-string 2))))
13123 (defun org-at-date-range-p (&optional inactive-ok)
13124 "Non-nil if point is inside a date range.
13126 When optional argument INACTIVE-OK is non-nil, also consider
13127 inactive time ranges.
13129 When this function returns a non-nil value, match data is set
13130 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13131 on INACTIVE-OK."
13132 (interactive)
13133 (save-excursion
13134 (catch 'exit
13135 (let ((pos (point)))
13136 (skip-chars-backward "^[<\r\n")
13137 (skip-chars-backward "<[")
13138 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13139 (>= (match-end 0) pos)
13140 (throw 'exit t))
13141 (skip-chars-backward "^<[\r\n")
13142 (skip-chars-backward "<[")
13143 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13144 (>= (match-end 0) pos)
13145 (throw 'exit t)))
13146 nil)))
13148 (defun org-get-repeat (&optional tagline)
13149 "Check if there is a deadline/schedule with repeater in this entry."
13150 (save-match-data
13151 (save-excursion
13152 (org-back-to-heading t)
13153 (and (re-search-forward (if tagline
13154 (concat tagline "\\s-*" org-repeat-re)
13155 org-repeat-re)
13156 (org-entry-end-position) t)
13157 (match-string-no-properties 1)))))
13159 (defvar org-last-changed-timestamp)
13160 (defvar org-last-inserted-timestamp)
13161 (defvar org-log-post-message)
13162 (defvar org-log-note-purpose)
13163 (defvar org-log-note-how nil)
13164 (defvar org-log-note-extra)
13165 (defun org-auto-repeat-maybe (done-word)
13166 "Check if the current headline contains a repeated deadline/schedule.
13167 If yes, set TODO state back to what it was and change the base date
13168 of repeating deadline/scheduled time stamps to new date.
13169 This function is run automatically after each state change to a DONE state."
13170 ;; last-state is dynamically scoped into this function
13171 (let* ((repeat (org-get-repeat))
13172 (aa (assoc org-last-state org-todo-kwd-alist))
13173 (interpret (nth 1 aa))
13174 (head (nth 2 aa))
13175 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13176 (msg "Entry repeats: ")
13177 (org-log-done nil)
13178 (org-todo-log-states nil)
13179 re type n what ts time to-state)
13180 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13181 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13182 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13183 org-todo-repeat-to-state))
13184 (unless (and to-state (member to-state org-todo-keywords-1))
13185 (setq to-state (if (eq interpret 'type) org-last-state head)))
13186 (org-todo to-state)
13187 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13188 (org-entry-put nil "LAST_REPEAT" (format-time-string
13189 (org-time-stamp-format t t))))
13190 (when org-log-repeat
13191 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13192 (memq 'org-add-log-note post-command-hook))
13193 ;; OK, we are already setup for some record
13194 (when (eq org-log-repeat 'note)
13195 ;; make sure we take a note, not only a time stamp
13196 (setq org-log-note-how 'note))
13197 ;; Set up for taking a record
13198 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13199 org-last-state
13200 'findpos org-log-repeat)))
13201 (org-back-to-heading t)
13202 (org-add-planning-info nil nil 'closed)
13203 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13204 org-deadline-time-regexp "\\)\\|\\("
13205 org-ts-regexp "\\)"))
13206 (while (re-search-forward
13207 re (save-excursion (outline-next-heading) (point)) t)
13208 (setq type (if (match-end 1) org-scheduled-string
13209 (if (match-end 3) org-deadline-string "Plain:"))
13210 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13211 (if (not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13212 (org-remove-timestamp-with-keyword org-scheduled-string)
13213 (setq n (string-to-number (match-string 2 ts))
13214 what (match-string 3 ts))
13215 (when (equal what "w") (setq n (* n 7) what "d"))
13216 (when (and (equal what "h")
13217 (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13218 (user-error
13219 "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13220 ;; Preparation, see if we need to modify the start date for the change
13221 (when (match-end 1)
13222 (setq time (save-match-data (org-time-string-to-time ts)))
13223 (cond
13224 ((equal (match-string 1 ts) ".")
13225 ;; Shift starting date to today
13226 (org-timestamp-change
13227 (- (org-today) (time-to-days time))
13228 'day))
13229 ((equal (match-string 1 ts) "+")
13230 (let ((nshiftmax 10) (nshift 0))
13231 (while (or (= nshift 0)
13232 (<= (time-to-days time)
13233 (time-to-days (current-time))))
13234 (when (= (incf nshift) nshiftmax)
13235 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13236 (user-error "Abort")))
13237 (org-timestamp-change n (cdr (assoc what whata)))
13238 (org-at-timestamp-p t)
13239 (setq ts (match-string 1))
13240 (setq time (save-match-data (org-time-string-to-time ts)))))
13241 (org-timestamp-change (- n) (cdr (assoc what whata)))
13242 ;; rematch, so that we have everything in place for the real shift
13243 (org-at-timestamp-p t)
13244 (setq ts (match-string 1))
13245 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13246 (save-excursion
13247 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13248 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13249 (setq org-log-post-message msg)
13250 (message "%s" msg))))
13252 (defun org-show-todo-tree (arg)
13253 "Make a compact tree which shows all headlines marked with TODO.
13254 The tree will show the lines where the regexp matches, and all higher
13255 headlines above the match.
13256 With a \\[universal-argument] prefix, prompt for a regexp to match.
13257 With a numeric prefix N, construct a sparse tree for the Nth element
13258 of `org-todo-keywords-1'."
13259 (interactive "P")
13260 (let ((case-fold-search nil)
13261 (kwd-re
13262 (cond ((null arg) org-not-done-regexp)
13263 ((equal arg '(4))
13264 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13265 (mapcar 'list org-todo-keywords-1))))
13266 (concat "\\("
13267 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13268 "\\)\\>")))
13269 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13270 (regexp-quote (nth (1- (prefix-numeric-value arg))
13271 org-todo-keywords-1)))
13272 (t (user-error "Invalid prefix argument: %s" arg)))))
13273 (message "%d TODO entries found"
13274 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13276 (defun org-deadline (arg &optional time)
13277 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13278 With one universal prefix argument, remove any deadline from the item.
13279 With two universal prefix arguments, prompt for a warning delay.
13280 With argument TIME, set the deadline at the corresponding date. TIME
13281 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13282 (interactive "P")
13283 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13284 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13285 'region-start-level 'region))
13286 org-loop-over-headlines-in-active-region)
13287 (org-map-entries
13288 `(org-deadline ',arg ,time)
13289 org-loop-over-headlines-in-active-region
13290 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13291 (let* ((old-date (org-entry-get nil "DEADLINE"))
13292 (old-date-time (when old-date (org-time-string-to-time old-date)))
13293 (repeater (and old-date
13294 (string-match
13295 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13296 old-date)
13297 (match-string 1 old-date))))
13298 (cond
13299 ((equal arg '(4))
13300 (when (and old-date org-log-redeadline)
13301 (org-add-log-setup 'deldeadline nil old-date 'findpos
13302 org-log-redeadline))
13303 (org-remove-timestamp-with-keyword org-deadline-string)
13304 (message "Item no longer has a deadline."))
13305 ((equal arg '(16))
13306 (save-excursion
13307 (org-back-to-heading t)
13308 (if (re-search-forward
13309 org-deadline-time-regexp
13310 (save-excursion (outline-next-heading) (point)) t)
13311 (let* ((rpl0 (match-string 1))
13312 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13313 (replace-match
13314 (concat org-deadline-string
13315 " <" rpl
13316 (format " -%dd"
13317 (abs
13318 (- (time-to-days
13319 (save-match-data
13320 (org-read-date nil t nil "Warn starting from" old-date-time)))
13321 (time-to-days old-date-time))))
13322 ">") t t))
13323 (user-error "No deadline information to update"))))
13325 (org-add-planning-info 'deadline time 'closed)
13326 (when (and old-date
13327 org-log-redeadline
13328 (not (equal old-date org-last-inserted-timestamp)))
13329 (org-add-log-setup
13330 'redeadline org-last-inserted-timestamp old-date 'findpos
13331 org-log-redeadline))
13332 (when repeater
13333 (save-excursion
13334 (org-back-to-heading t)
13335 (when (re-search-forward (concat org-deadline-string " "
13336 org-last-inserted-timestamp)
13337 (save-excursion
13338 (outline-next-heading) (point)) t)
13339 (goto-char (1- (match-end 0)))
13340 (insert " " repeater)
13341 (setq org-last-inserted-timestamp
13342 (concat (substring org-last-inserted-timestamp 0 -1)
13343 " " repeater
13344 (substring org-last-inserted-timestamp -1))))))
13345 (message "Deadline on %s" org-last-inserted-timestamp))))))
13347 (defun org-schedule (arg &optional time)
13348 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13349 With one universal prefix argument, remove any scheduling date from the item.
13350 With two universal prefix arguments, prompt for a delay cookie.
13351 With argument TIME, scheduled at the corresponding date. TIME can
13352 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13353 (interactive "P")
13354 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13355 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13356 'region-start-level 'region))
13357 org-loop-over-headlines-in-active-region)
13358 (org-map-entries
13359 `(org-schedule ',arg ,time)
13360 org-loop-over-headlines-in-active-region
13361 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13362 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13363 (old-date-time (when old-date (org-time-string-to-time old-date)))
13364 (repeater (and old-date
13365 (string-match
13366 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13367 old-date)
13368 (match-string 1 old-date))))
13369 (cond
13370 ((equal arg '(4))
13371 (progn
13372 (when (and old-date org-log-reschedule)
13373 (org-add-log-setup 'delschedule nil old-date 'findpos
13374 org-log-reschedule))
13375 (org-remove-timestamp-with-keyword org-scheduled-string)
13376 (message "Item is no longer scheduled.")))
13377 ((equal arg '(16))
13378 (save-excursion
13379 (org-back-to-heading t)
13380 (if (re-search-forward
13381 org-scheduled-time-regexp
13382 (save-excursion (outline-next-heading) (point)) t)
13383 (let* ((rpl0 (match-string 1))
13384 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13385 (replace-match
13386 (concat org-scheduled-string
13387 " <" rpl
13388 (format " -%dd"
13389 (abs
13390 (- (time-to-days
13391 (save-match-data
13392 (org-read-date nil t nil "Delay until" old-date-time)))
13393 (time-to-days old-date-time))))
13394 ">") t t))
13395 (user-error "No scheduled information to update"))))
13397 (org-add-planning-info 'scheduled time 'closed)
13398 (when (and old-date
13399 org-log-reschedule
13400 (not (equal old-date org-last-inserted-timestamp)))
13401 (org-add-log-setup
13402 'reschedule org-last-inserted-timestamp old-date 'findpos
13403 org-log-reschedule))
13404 (when repeater
13405 (save-excursion
13406 (org-back-to-heading t)
13407 (when (re-search-forward (concat org-scheduled-string " "
13408 org-last-inserted-timestamp)
13409 (save-excursion
13410 (outline-next-heading) (point)) t)
13411 (goto-char (1- (match-end 0)))
13412 (insert " " repeater)
13413 (setq org-last-inserted-timestamp
13414 (concat (substring org-last-inserted-timestamp 0 -1)
13415 " " repeater
13416 (substring org-last-inserted-timestamp -1))))))
13417 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13419 (defun org-get-scheduled-time (pom &optional inherit)
13420 "Get the scheduled time as a time tuple, of a format suitable
13421 for calling org-schedule with, or if there is no scheduling,
13422 returns nil."
13423 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13424 (when time
13425 (apply 'encode-time (org-parse-time-string time)))))
13427 (defun org-get-deadline-time (pom &optional inherit)
13428 "Get the deadline as a time tuple, of a format suitable for
13429 calling org-deadline with, or if there is no scheduling, returns
13430 nil."
13431 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13432 (when time
13433 (apply 'encode-time (org-parse-time-string time)))))
13435 (defun org-remove-timestamp-with-keyword (keyword)
13436 "Remove all time stamps with KEYWORD in the current entry."
13437 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13438 beg)
13439 (save-excursion
13440 (org-back-to-heading t)
13441 (setq beg (point))
13442 (outline-next-heading)
13443 (while (re-search-backward re beg t)
13444 (replace-match "")
13445 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13446 (equal (char-before) ?\ ))
13447 (backward-delete-char 1)
13448 (when (string-match "^[ \t]*$" (buffer-substring
13449 (point-at-bol) (point-at-eol)))
13450 (delete-region (point-at-bol)
13451 (min (point-max) (1+ (point-at-eol))))))))))
13453 (defvar org-time-was-given) ; dynamically scoped parameter
13454 (defvar org-end-time-was-given) ; dynamically scoped parameter
13456 (defun org-at-planning-p ()
13457 "Non-nil when point is on a planning info line."
13458 ;; This is as accurate and faster than `org-element-at-point' since
13459 ;; planning info location is fixed in the section.
13460 (org-with-wide-buffer
13461 (beginning-of-line)
13462 (and (org-looking-at-p org-planning-line-re)
13463 (eq (point)
13464 (ignore-errors
13465 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13466 (org-back-to-heading t)
13467 (org-with-limited-levels (org-back-to-heading t)))
13468 (line-beginning-position 2))))))
13470 (defun org-add-planning-info (what &optional time &rest remove)
13471 "Insert new timestamp with keyword in the planning line.
13472 WHAT indicates what kind of time stamp to add. It is a symbol
13473 among `closed', `deadline', `scheduled' and nil. TIME indicates
13474 the time to use. If none is given, the user is prompted for
13475 a date. REMOVE indicates what kind of entries to remove. An old
13476 WHAT entry will also be removed."
13477 (let (org-time-was-given org-end-time-was-given default-time default-input)
13478 (catch 'exit
13479 (when (and (memq what '(scheduled deadline))
13480 (or (not time)
13481 (and (stringp time)
13482 (string-match "^[-+]+[0-9]" time))))
13483 ;; Try to get a default date/time from existing timestamp
13484 (save-excursion
13485 (org-back-to-heading t)
13486 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13487 (when (re-search-forward (if (eq what 'scheduled)
13488 org-scheduled-time-regexp
13489 org-deadline-time-regexp)
13490 end t)
13491 (setq ts (match-string 1)
13492 default-time (apply 'encode-time (org-parse-time-string ts))
13493 default-input (and ts (org-get-compact-tod ts)))))))
13494 (when what
13495 (setq time
13496 (if (stringp time)
13497 ;; This is a string (relative or absolute), set
13498 ;; proper date.
13499 (apply #'encode-time
13500 (org-read-date-analyze
13501 time default-time (decode-time default-time)))
13502 ;; If necessary, get the time from the user
13503 (or time (org-read-date nil 'to-time nil nil
13504 default-time default-input)))))
13506 (org-with-wide-buffer
13507 (org-back-to-heading t)
13508 (forward-line)
13509 (unless (bolp) (insert "\n"))
13510 (cond ((org-looking-at-p org-planning-line-re)
13511 ;; Move to current indentation.
13512 (skip-chars-forward " \t")
13513 ;; Check if we have to remove something.
13514 (dolist (type (if what (cons what remove) remove))
13515 (save-excursion
13516 (when (re-search-forward
13517 (case type
13518 (closed org-closed-time-regexp)
13519 (deadline org-deadline-time-regexp)
13520 (scheduled org-scheduled-time-regexp)
13521 (otherwise
13522 (error "Invalid planning type: %s" type)))
13523 (line-end-position) t)
13524 ;; Delete until next keyword or end of line.
13525 (delete-region
13526 (match-beginning 0)
13527 (if (re-search-forward org-keyword-time-not-clock-regexp
13528 (line-end-position)
13530 (match-beginning 0)
13531 (line-end-position))))))
13532 ;; If there is nothing more to add and no more keyword
13533 ;; is left, remove the line completely.
13534 (if (and (org-looking-at-p "[ \t]*$") (not what))
13535 (delete-region (line-beginning-position)
13536 (line-beginning-position 2))
13537 ;; If we removed last keyword, do not leave trailing
13538 ;; white space at the end of line.
13539 (let ((p (point)))
13540 (save-excursion
13541 (end-of-line)
13542 (unless (= (skip-chars-backward " \t" p) 0)
13543 (delete-region (point) (line-end-position)))))))
13544 ((not what) (throw 'exit nil)) ; Nothing to do.
13545 (t (insert-before-markers "\n")
13546 (backward-char 1)
13547 (when org-adapt-indentation
13548 (org-indent-to-column (1+ (org-outline-level))))))
13549 (when what
13550 ;; Insert planning keyword.
13551 (insert (case what
13552 (closed org-closed-string)
13553 (deadline org-deadline-string)
13554 (scheduled org-scheduled-string)
13555 (otherwise (error "Invalid planning type: %s" what)))
13556 " ")
13557 ;; Insert associated timestamp.
13558 (let ((ts (org-insert-time-stamp
13559 time
13560 (or org-time-was-given
13561 (and (eq what 'closed) org-log-done-with-time))
13562 (eq what 'closed)
13563 nil nil (list org-end-time-was-given))))
13564 (unless (eolp) (insert " "))
13565 ts))))))
13567 (defvar org-log-note-marker (make-marker))
13568 (defvar org-log-note-purpose nil)
13569 (defvar org-log-note-state nil)
13570 (defvar org-log-note-previous-state nil)
13571 (defvar org-log-note-extra nil)
13572 (defvar org-log-note-window-configuration nil)
13573 (defvar org-log-note-return-to (make-marker))
13574 (defvar org-log-note-effective-time nil
13575 "Remembered current time so that dynamically scoped
13576 `org-extend-today-until' affects tha timestamps in state change
13577 log")
13579 (defvar org-log-post-message nil
13580 "Message to be displayed after a log note has been stored.
13581 The auto-repeater uses this.")
13583 (defun org-add-note ()
13584 "Add a note to the current entry.
13585 This is done in the same way as adding a state change note."
13586 (interactive)
13587 (org-add-log-setup 'note nil nil 'findpos nil))
13589 (defun org-log-beginning (&optional create)
13590 "Return expected start of log notes in current entry.
13591 When optional argument CREATE is non-nil, the function creates
13592 a drawer to store notes, if necessary. Returned position ignores
13593 narrowing."
13594 (org-with-wide-buffer
13595 (org-end-of-meta-data)
13596 (let ((end (if (org-at-heading-p) (point)
13597 (save-excursion (outline-next-heading) (point))))
13598 (drawer (org-log-into-drawer)))
13599 (cond
13600 (drawer
13601 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13602 (case-fold-search t))
13603 (catch 'exit
13604 ;; Try to find existing drawer.
13605 (while (re-search-forward regexp end t)
13606 (let ((element (org-element-at-point)))
13607 (when (eq (org-element-type element) 'drawer)
13608 (let ((cend (org-element-property :contents-end element)))
13609 (when (and (not org-log-states-order-reversed) cend)
13610 (goto-char cend)))
13611 (throw 'exit nil))))
13612 ;; No drawer found. Create one, if permitted.
13613 (when create
13614 (unless (bolp) (insert "\n"))
13615 (let ((beg (point)))
13616 (insert ":" drawer ":\n:END:\n")
13617 (org-indent-region beg (point)))
13618 (end-of-line -1)))))
13619 (org-log-state-notes-insert-after-drawers
13620 (while (and (looking-at org-drawer-regexp)
13621 (progn (goto-char (match-end 0))
13622 (re-search-forward org-property-end-re end t)))
13623 (forward-line)))))
13624 (if (bolp) (point) (line-beginning-position 2))))
13626 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13627 "Set up the post command hook to take a note.
13628 If this is about to TODO state change, the new state is expected in STATE.
13629 When FINDPOS is non-nil, find the correct position for the note in
13630 the current entry. If not, assume that it can be inserted at point.
13631 HOW is an indicator what kind of note should be created.
13632 EXTRA is additional text that will be inserted into the notes buffer."
13633 (org-with-wide-buffer
13634 (when findpos
13635 (goto-char (org-log-beginning t))
13636 (unless org-log-states-order-reversed
13637 (org-skip-over-state-notes)
13638 (skip-chars-backward " \t\n\r")
13639 (forward-line)))
13640 (move-marker org-log-note-marker (point))
13641 ;; Preserve position even if a property drawer is inserted in the
13642 ;; process.
13643 (set-marker-insertion-type org-log-note-marker t)
13644 (setq org-log-note-purpose purpose
13645 org-log-note-state state
13646 org-log-note-previous-state prev-state
13647 org-log-note-how how
13648 org-log-note-extra extra
13649 org-log-note-effective-time (org-current-effective-time))
13650 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13652 (defun org-skip-over-state-notes ()
13653 "Skip past the list of State notes in an entry."
13654 (when (ignore-errors (goto-char (org-in-item-p)))
13655 (let* ((struct (org-list-struct))
13656 (prevs (org-list-prevs-alist struct))
13657 (regexp
13658 (concat "[ \t]*- +"
13659 (replace-regexp-in-string
13660 " +" " +"
13661 (org-replace-escapes
13662 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13663 `(("%d" . ,org-ts-regexp-inactive)
13664 ("%D" . ,org-ts-regexp)
13665 ("%s" . "\"\\S-+\"")
13666 ("%S" . "\"\\S-+\"")
13667 ("%t" . ,org-ts-regexp-inactive)
13668 ("%T" . ,org-ts-regexp)
13669 ("%u" . ".*?")
13670 ("%U" . ".*?")))))))
13671 (while (org-looking-at-p regexp)
13672 (goto-char (or (org-list-get-next-item (point) struct prevs)
13673 (org-list-get-item-end (point) struct)))))))
13675 (defun org-add-log-note (&optional purpose)
13676 "Pop up a window for taking a note, and add this note later at point."
13677 (remove-hook 'post-command-hook 'org-add-log-note)
13678 (setq org-log-note-window-configuration (current-window-configuration))
13679 (delete-other-windows)
13680 (move-marker org-log-note-return-to (point))
13681 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13682 (goto-char org-log-note-marker)
13683 (org-switch-to-buffer-other-window "*Org Note*")
13684 (erase-buffer)
13685 (if (memq org-log-note-how '(time state))
13686 (let (current-prefix-arg) (org-store-log-note))
13687 (let ((org-inhibit-startup t)) (org-mode))
13688 (insert (format "# Insert note for %s.
13689 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13690 (cond
13691 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13692 ((eq org-log-note-purpose 'done) "closed todo item")
13693 ((eq org-log-note-purpose 'state)
13694 (format "state change from \"%s\" to \"%s\""
13695 (or org-log-note-previous-state "")
13696 (or org-log-note-state "")))
13697 ((eq org-log-note-purpose 'reschedule)
13698 "rescheduling")
13699 ((eq org-log-note-purpose 'delschedule)
13700 "no longer scheduled")
13701 ((eq org-log-note-purpose 'redeadline)
13702 "changing deadline")
13703 ((eq org-log-note-purpose 'deldeadline)
13704 "removing deadline")
13705 ((eq org-log-note-purpose 'refile)
13706 "refiling")
13707 ((eq org-log-note-purpose 'note)
13708 "this entry")
13709 (t (error "This should not happen")))))
13710 (when org-log-note-extra (insert org-log-note-extra))
13711 (setq-local org-finish-function 'org-store-log-note)
13712 (run-hooks 'org-log-buffer-setup-hook)))
13714 (defvar org-note-abort nil) ; dynamically scoped
13715 (defun org-store-log-note ()
13716 "Finish taking a log note, and insert it to where it belongs."
13717 (let ((txt (buffer-string)))
13718 (kill-buffer (current-buffer))
13719 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13720 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13721 (setq txt (replace-match "" t t txt)))
13722 (when (string-match "\\s-+\\'" txt)
13723 (setq txt (replace-match "" t t txt)))
13724 (setq lines (org-split-string txt "\n"))
13725 (when (and note (string-match "\\S-" note))
13726 (setq note
13727 (org-replace-escapes
13728 note
13729 (list (cons "%u" (user-login-name))
13730 (cons "%U" user-full-name)
13731 (cons "%t" (format-time-string
13732 (org-time-stamp-format 'long 'inactive)
13733 org-log-note-effective-time))
13734 (cons "%T" (format-time-string
13735 (org-time-stamp-format 'long nil)
13736 org-log-note-effective-time))
13737 (cons "%d" (format-time-string
13738 (org-time-stamp-format nil 'inactive)
13739 org-log-note-effective-time))
13740 (cons "%D" (format-time-string
13741 (org-time-stamp-format nil nil)
13742 org-log-note-effective-time))
13743 (cons "%s" (cond
13744 ((not org-log-note-state) "")
13745 ((org-string-match-p org-ts-regexp
13746 org-log-note-state)
13747 (format "\"[%s]\""
13748 (substring org-log-note-state 1 -1)))
13749 (t (format "\"%s\"" org-log-note-state))))
13750 (cons "%S"
13751 (cond
13752 ((not org-log-note-previous-state) "")
13753 ((org-string-match-p org-ts-regexp
13754 org-log-note-previous-state)
13755 (format "\"[%s]\""
13756 (substring
13757 org-log-note-previous-state 1 -1)))
13758 (t (format "\"%s\""
13759 org-log-note-previous-state)))))))
13760 (when lines (setq note (concat note " \\\\")))
13761 (push note lines))
13762 (when (or current-prefix-arg org-note-abort)
13763 (when (org-log-into-drawer)
13764 (org-remove-empty-drawer-at org-log-note-marker))
13765 (setq lines nil))
13766 (when lines
13767 (with-current-buffer (marker-buffer org-log-note-marker)
13768 (org-with-wide-buffer
13769 (goto-char org-log-note-marker)
13770 (move-marker org-log-note-marker nil)
13771 ;; Make sure point is at the beginning of an empty line.
13772 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13773 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13774 ;; In an existing list, add a new item at the top level.
13775 ;; Otherwise, indent line like a regular one.
13776 (let ((itemp (org-in-item-p)))
13777 (if itemp
13778 (org-indent-line-to
13779 (let ((struct (save-excursion
13780 (goto-char itemp) (org-list-struct))))
13781 (org-list-get-ind (org-list-get-top-point struct) struct)))
13782 (org-indent-line)))
13783 (insert (org-list-bullet-string "-") (pop lines))
13784 (let ((ind (org-list-item-body-column (line-beginning-position))))
13785 (dolist (line lines)
13786 (insert "\n")
13787 (org-indent-line-to ind)
13788 (insert line)))
13789 (message "Note stored")
13790 (org-back-to-heading t)
13791 (org-cycle-hide-drawers 'children))
13792 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13793 ;; from within `org-add-log-note' because `buffer-undo-list'
13794 ;; is then modified outside of `org-with-remote-undo'.
13795 (when (eq this-command 'org-agenda-todo)
13796 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13797 ;; Don't add undo information when called from `org-agenda-todo'
13798 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13799 (set-window-configuration org-log-note-window-configuration)
13800 (with-current-buffer (marker-buffer org-log-note-return-to)
13801 (goto-char org-log-note-return-to))
13802 (move-marker org-log-note-return-to nil)
13803 (and org-log-post-message (message "%s" org-log-post-message))))
13805 (defun org-remove-empty-drawer-at (pos)
13806 "Remove an empty drawer at position POS.
13807 POS may also be a marker."
13808 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13809 (org-with-wide-buffer
13810 (goto-char pos)
13811 (let ((drawer (org-element-at-point)))
13812 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13813 (not (org-element-property :contents-begin drawer)))
13814 (delete-region (org-element-property :begin drawer)
13815 (progn (goto-char (org-element-property :end drawer))
13816 (skip-chars-backward " \r\t\n")
13817 (forward-line)
13818 (point))))))))
13820 (defvar org-ts-type nil)
13821 (defun org-sparse-tree (&optional arg type)
13822 "Create a sparse tree, prompt for the details.
13823 This command can create sparse trees. You first need to select the type
13824 of match used to create the tree:
13826 t Show all TODO entries.
13827 T Show entries with a specific TODO keyword.
13828 m Show entries selected by a tags/property match.
13829 p Enter a property name and its value (both with completion on existing
13830 names/values) and show entries with that property.
13831 r Show entries matching a regular expression (`/' can be used as well).
13832 b Show deadlines and scheduled items before a date.
13833 a Show deadlines and scheduled items after a date.
13834 d Show deadlines due within `org-deadline-warning-days'.
13835 D Show deadlines and scheduled items between a date range."
13836 (interactive "P")
13837 (setq type (or type org-sparse-tree-default-date-type))
13838 (setq org-ts-type type)
13839 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13840 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13841 [c]ycle through date types: %s"
13842 (case type
13843 (all "all timestamps")
13844 (scheduled "only scheduled")
13845 (deadline "only deadline")
13846 (active "only active timestamps")
13847 (inactive "only inactive timestamps")
13848 (closed "with a closed time-stamp")
13849 (otherwise "scheduled/deadline")))
13850 (let ((answer (read-char-exclusive)))
13851 (case answer
13853 (org-sparse-tree
13855 (cadr
13856 (memq type '(nil all scheduled deadline active inactive closed)))))
13857 (?d (call-interactively 'org-check-deadlines))
13858 (?b (call-interactively 'org-check-before-date))
13859 (?a (call-interactively 'org-check-after-date))
13860 (?D (call-interactively 'org-check-dates-range))
13861 (?t (call-interactively 'org-show-todo-tree))
13862 (?T (org-show-todo-tree '(4)))
13863 (?m (call-interactively 'org-match-sparse-tree))
13864 ((?p ?P)
13865 (let* ((kwd (org-icompleting-read
13866 "Property: " (mapcar 'list (org-buffer-property-keys))))
13867 (value (org-icompleting-read
13868 "Value: " (mapcar 'list (org-property-values kwd)))))
13869 (unless (string-match "\\`{.*}\\'" value)
13870 (setq value (concat "\"" value "\"")))
13871 (org-match-sparse-tree arg (concat kwd "=" value))))
13872 ((?r ?R ?/) (call-interactively 'org-occur))
13873 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13875 (defvar-local org-occur-highlights nil
13876 "List of overlays used for occur matches.")
13877 (defvar-local org-occur-parameters nil
13878 "Parameters of the active org-occur calls.
13879 This is a list, each call to org-occur pushes as cons cell,
13880 containing the regular expression and the callback, onto the list.
13881 The list can contain several entries if `org-occur' has been called
13882 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13883 will only contain one set of parameters. When the highlights are
13884 removed (for example with `C-c C-c', or with the next edit (depending
13885 on `org-remove-highlights-with-change'), this variable is emptied
13886 as well.")
13888 (defun org-occur (regexp &optional keep-previous callback)
13889 "Make a compact tree which shows all matches of REGEXP.
13890 The tree will show the lines where the regexp matches, and all higher
13891 headlines above the match. It will also show the heading after the match,
13892 to make sure editing the matching entry is easy.
13893 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13894 call to `org-occur' will be kept, to allow stacking of calls to this
13895 command.
13896 If CALLBACK is non-nil, it is a function which is called to confirm
13897 that the match should indeed be shown."
13898 (interactive "sRegexp: \nP")
13899 (when (equal regexp "")
13900 (user-error "Regexp cannot be empty"))
13901 (unless keep-previous
13902 (org-remove-occur-highlights nil nil t))
13903 (push (cons regexp callback) org-occur-parameters)
13904 (let ((cnt 0))
13905 (save-excursion
13906 (goto-char (point-min))
13907 (when (or (not keep-previous) ; do not want to keep
13908 (not org-occur-highlights)) ; no previous matches
13909 ;; hide everything
13910 (org-overview))
13911 (while (re-search-forward regexp nil t)
13912 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13913 (when (or (not callback)
13914 (save-match-data (funcall callback)))
13915 (setq cnt (1+ cnt))
13916 (when org-highlight-sparse-tree-matches
13917 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13918 (org-show-context 'occur-tree))))
13919 (when org-remove-highlights-with-change
13920 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13921 nil 'local))
13922 (unless org-sparse-tree-open-archived-trees
13923 (org-hide-archived-subtrees (point-min) (point-max)))
13924 (run-hooks 'org-occur-hook)
13925 (when (org-called-interactively-p 'interactive)
13926 (message "%d match(es) for regexp %s" cnt regexp))
13927 cnt))
13929 (defun org-occur-next-match (&optional n reset)
13930 "Function for `next-error-function' to find sparse tree matches.
13931 N is the number of matches to move, when negative move backwards.
13932 RESET is entirely ignored - this function always goes back to the
13933 starting point when no match is found."
13934 (let* ((limit (if (< n 0) (point-min) (point-max)))
13935 (search-func (if (< n 0)
13936 'previous-single-char-property-change
13937 'next-single-char-property-change))
13938 (n (abs n))
13939 (pos (point))
13941 (catch 'exit
13942 (while (setq p1 (funcall search-func (point) 'org-type))
13943 (when (equal p1 limit)
13944 (goto-char pos)
13945 (user-error "No more matches"))
13946 (when (equal (get-char-property p1 'org-type) 'org-occur)
13947 (setq n (1- n))
13948 (when (= n 0)
13949 (goto-char p1)
13950 (throw 'exit (point))))
13951 (goto-char p1))
13952 (goto-char p1)
13953 (user-error "No more matches"))))
13955 (defun org-show-context (&optional key)
13956 "Make sure point and context are visible.
13957 Optional argument KEY, when non-nil, is a symbol. See
13958 `org-show-context-detail' for allowed values and how much is to
13959 be shown."
13960 (org-show-set-visibility
13961 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13962 ((cdr (assq key org-show-context-detail)))
13963 (t (cdr (assq 'default org-show-context-detail))))))
13965 (defun org-show-set-visibility (detail)
13966 "Set visibility around point according to DETAIL.
13967 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13968 `tree', `canonical' or t. See `org-show-context-detail' for more
13969 information."
13970 (unless (org-before-first-heading-p)
13971 ;; Show current heading and possibly its entry, following headline
13972 ;; or all children.
13973 (if (and (org-at-heading-p) (not (eq detail 'local)))
13974 (org-flag-heading nil)
13975 (org-show-entry)
13976 (org-with-limited-levels
13977 (case detail
13978 ((tree canonical t) (org-show-children))
13979 ((nil minimal ancestors))
13980 (t (save-excursion
13981 (outline-next-heading)
13982 (org-flag-heading nil))))))
13983 ;; Show all siblings.
13984 (when (eq detail 'lineage) (org-show-siblings))
13985 ;; Show ancestors, possibly with their children.
13986 (when (memq detail '(ancestors lineage tree canonical t))
13987 (save-excursion
13988 (while (org-up-heading-safe)
13989 (org-flag-heading nil)
13990 (when (memq detail '(canonical t)) (org-show-entry))
13991 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13993 (defvar org-reveal-start-hook nil
13994 "Hook run before revealing a location.")
13996 (defun org-reveal (&optional siblings)
13997 "Show current entry, hierarchy above it, and the following headline.
13999 This can be used to show a consistent set of context around
14000 locations exposed with `org-show-context'.
14002 With optional argument SIBLINGS, on each level of the hierarchy all
14003 siblings are shown. This repairs the tree structure to what it would
14004 look like when opened with hierarchical calls to `org-cycle'.
14006 With double optional argument \\[universal-argument] \\[universal-argument], \
14007 go to the parent and show the
14008 entire tree."
14009 (interactive "P")
14010 (run-hooks 'org-reveal-start-hook)
14011 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14012 ((equal siblings '(16))
14013 (save-excursion
14014 (when (org-up-heading-safe)
14015 (org-show-subtree)
14016 (run-hook-with-args 'org-cycle-hook 'subtree))))
14017 (t (org-show-set-visibility 'lineage))))
14019 (defun org-highlight-new-match (beg end)
14020 "Highlight from BEG to END and mark the highlight is an occur headline."
14021 (let ((ov (make-overlay beg end)))
14022 (overlay-put ov 'face 'secondary-selection)
14023 (overlay-put ov 'org-type 'org-occur)
14024 (push ov org-occur-highlights)))
14026 (defun org-remove-occur-highlights (&optional beg end noremove)
14027 "Remove the occur highlights from the buffer.
14028 BEG and END are ignored. If NOREMOVE is nil, remove this function
14029 from the `before-change-functions' in the current buffer."
14030 (interactive)
14031 (unless org-inhibit-highlight-removal
14032 (mapc 'delete-overlay org-occur-highlights)
14033 (setq org-occur-highlights nil)
14034 (setq org-occur-parameters nil)
14035 (unless noremove
14036 (remove-hook 'before-change-functions
14037 'org-remove-occur-highlights 'local))))
14039 ;;;; Priorities
14041 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14042 "Regular expression matching the priority indicator.")
14044 (defvar org-remove-priority-next-time nil)
14046 (defun org-priority-up ()
14047 "Increase the priority of the current item."
14048 (interactive)
14049 (org-priority 'up))
14051 (defun org-priority-down ()
14052 "Decrease the priority of the current item."
14053 (interactive)
14054 (org-priority 'down))
14056 (defun org-priority (&optional action show)
14057 "Change the priority of an item.
14058 ACTION can be `set', `up', `down', or a character."
14059 (interactive "P")
14060 (if (equal action '(4))
14061 (org-show-priority)
14062 (unless org-enable-priority-commands
14063 (user-error "Priority commands are disabled"))
14064 (setq action (or action 'set))
14065 (let (current new news have remove)
14066 (save-excursion
14067 (org-back-to-heading t)
14068 (when (looking-at org-priority-regexp)
14069 (setq current (string-to-char (match-string 2))
14070 have t))
14071 (cond
14072 ((eq action 'remove)
14073 (setq remove t new ?\ ))
14074 ((or (eq action 'set)
14075 (if (featurep 'xemacs) (characterp action) (integerp action)))
14076 (if (not (eq action 'set))
14077 (setq new action)
14078 (message "Priority %c-%c, SPC to remove: "
14079 org-highest-priority org-lowest-priority)
14080 (save-match-data
14081 (setq new (read-char-exclusive))))
14082 (when (and (= (upcase org-highest-priority) org-highest-priority)
14083 (= (upcase org-lowest-priority) org-lowest-priority))
14084 (setq new (upcase new)))
14085 (cond ((equal new ?\ ) (setq remove t))
14086 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14087 (user-error "Priority must be between `%c' and `%c'"
14088 org-highest-priority org-lowest-priority))))
14089 ((eq action 'up)
14090 (setq new (if have
14091 (1- current) ; normal cycling
14092 ;; last priority was empty
14093 (if (eq last-command this-command)
14094 org-lowest-priority ; wrap around empty to lowest
14095 ;; default
14096 (if org-priority-start-cycle-with-default
14097 org-default-priority
14098 (1- org-default-priority))))))
14099 ((eq action 'down)
14100 (setq new (if have
14101 (1+ current) ; normal cycling
14102 ;; last priority was empty
14103 (if (eq last-command this-command)
14104 org-highest-priority ; wrap around empty to highest
14105 ;; default
14106 (if org-priority-start-cycle-with-default
14107 org-default-priority
14108 (1+ org-default-priority))))))
14109 (t (user-error "Invalid action")))
14110 (when (or (< (upcase new) org-highest-priority)
14111 (> (upcase new) org-lowest-priority))
14112 (if (and (memq action '(up down))
14113 (not have) (not (eq last-command this-command)))
14114 ;; `new' is from default priority
14115 (error
14116 "The default can not be set, see `org-default-priority' why")
14117 ;; normal cycling: `new' is beyond highest/lowest priority
14118 ;; and is wrapped around to the empty priority
14119 (setq remove t)))
14120 (setq news (format "%c" new))
14121 (if have
14122 (if remove
14123 (replace-match "" t t nil 1)
14124 (replace-match news t t nil 2))
14125 (if remove
14126 (user-error "No priority cookie found in line")
14127 (let ((case-fold-search nil))
14128 (looking-at org-todo-line-regexp))
14129 (if (match-end 2)
14130 (progn
14131 (goto-char (match-end 2))
14132 (insert " [#" news "]"))
14133 (goto-char (match-beginning 3))
14134 (insert "[#" news "] "))))
14135 (org-set-tags nil 'align))
14136 (if remove
14137 (message "Priority removed")
14138 (message "Priority of current item set to %s" news)))))
14140 (defun org-show-priority ()
14141 "Show the priority of the current item.
14142 This priority is composed of the main priority given with the [#A] cookies,
14143 and by additional input from the age of a schedules or deadline entry."
14144 (interactive)
14145 (let ((pri (if (eq major-mode 'org-agenda-mode)
14146 (org-get-at-bol 'priority)
14147 (save-excursion
14148 (save-match-data
14149 (beginning-of-line)
14150 (and (looking-at org-heading-regexp)
14151 (org-get-priority (match-string 0))))))))
14152 (message "Priority is %d" (if pri pri -1000))))
14154 (defun org-get-priority (s)
14155 "Find priority cookie and return priority."
14156 (save-match-data
14157 (if (functionp org-get-priority-function)
14158 (funcall org-get-priority-function)
14159 (if (not (string-match org-priority-regexp s))
14160 (* 1000 (- org-lowest-priority org-default-priority))
14161 (* 1000 (- org-lowest-priority
14162 (string-to-char (match-string 2 s))))))))
14164 ;;;; Tags
14166 (defvar org-agenda-archives-mode)
14167 (defvar org-map-continue-from nil
14168 "Position from where mapping should continue.
14169 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14171 (defvar org-scanner-tags nil
14172 "The current tag list while the tags scanner is running.")
14173 (defvar org-trust-scanner-tags nil
14174 "Should `org-get-tags-at' use the tags for the scanner.
14175 This is for internal dynamical scoping only.
14176 When this is non-nil, the function `org-get-tags-at' will return the value
14177 of `org-scanner-tags' instead of building the list by itself. This
14178 can lead to large speed-ups when the tags scanner is used in a file with
14179 many entries, and when the list of tags is retrieved, for example to
14180 obtain a list of properties. Building the tags list for each entry in such
14181 a file becomes an N^2 operation - but with this variable set, it scales
14182 as N.")
14184 (defun org-scan-tags (action matcher todo-only &optional start-level)
14185 "Scan headline tags with inheritance and produce output ACTION.
14187 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14188 or `agenda' to produce an entry list for an agenda view. It can also be
14189 a Lisp form or a function that should be called at each matched headline, in
14190 this case the return value is a list of all return values from these calls.
14192 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14193 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14194 only lines with a not-done TODO keyword are included in the output.
14195 This should be the same variable that was scoped into
14196 and set by `org-make-tags-matcher' when it constructed MATCHER.
14198 START-LEVEL can be a string with asterisks, reducing the scope to
14199 headlines matching this string."
14200 (require 'org-agenda)
14201 (let* ((re (concat "^"
14202 (if start-level
14203 ;; Get the correct level to match
14204 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14205 org-outline-regexp)
14206 " *\\(\\<\\("
14207 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14208 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14209 (props (list 'face 'default
14210 'done-face 'org-agenda-done
14211 'undone-face 'default
14212 'mouse-face 'highlight
14213 'org-not-done-regexp org-not-done-regexp
14214 'org-todo-regexp org-todo-regexp
14215 'org-complex-heading-regexp org-complex-heading-regexp
14216 'help-echo
14217 (format "mouse-2 or RET jump to org file %s"
14218 (abbreviate-file-name
14219 (or (buffer-file-name (buffer-base-buffer))
14220 (buffer-name (buffer-base-buffer)))))))
14221 (org-map-continue-from nil)
14222 lspos tags tags-list
14223 (tags-alist (list (cons 0 org-file-tags)))
14224 (llast 0) rtn rtn1 level category i txt
14225 todo marker entry priority
14226 ts-date ts-date-type ts-date-pair)
14227 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14228 (setq action (list 'lambda nil action)))
14229 (save-excursion
14230 (goto-char (point-min))
14231 (when (eq action 'sparse-tree)
14232 (org-overview)
14233 (org-remove-occur-highlights))
14234 (while (let (case-fold-search)
14235 (re-search-forward re nil t))
14236 (setq org-map-continue-from nil)
14237 (catch :skip
14238 (setq todo
14239 ;; TODO: is the 1-2 difference a bug?
14240 (when (match-end 1) (org-match-string-no-properties 2))
14241 tags (when (match-end 4) (org-match-string-no-properties 4)))
14242 (goto-char (setq lspos (match-beginning 0)))
14243 (setq level (org-reduced-level (org-outline-level))
14244 category (org-get-category))
14245 (when (eq action 'agenda)
14246 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14247 ts-date (car ts-date-pair)
14248 ts-date-type (cdr ts-date-pair)))
14249 (setq i llast llast level)
14250 ;; remove tag lists from same and sublevels
14251 (while (>= i level)
14252 (when (setq entry (assoc i tags-alist))
14253 (setq tags-alist (delete entry tags-alist)))
14254 (setq i (1- i)))
14255 ;; add the next tags
14256 (when tags
14257 (setq tags (org-split-string tags ":")
14258 tags-alist
14259 (cons (cons level tags) tags-alist)))
14260 ;; compile tags for current headline
14261 (setq tags-list
14262 (if org-use-tag-inheritance
14263 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14264 tags)
14265 org-scanner-tags tags-list)
14266 (when org-use-tag-inheritance
14267 (setcdr (car tags-alist)
14268 (mapcar (lambda (x)
14269 (setq x (copy-sequence x))
14270 (org-add-prop-inherited x))
14271 (cdar tags-alist))))
14272 (when (and tags org-use-tag-inheritance
14273 (or (not (eq t org-use-tag-inheritance))
14274 org-tags-exclude-from-inheritance))
14275 ;; selective inheritance, remove uninherited ones
14276 (setcdr (car tags-alist)
14277 (org-remove-uninherited-tags (cdar tags-alist))))
14278 (when (and
14280 ;; eval matcher only when the todo condition is OK
14281 (and (or (not todo-only) (member todo org-not-done-keywords))
14282 (let ((case-fold-search t) (org-trust-scanner-tags t))
14283 (eval matcher)))
14285 ;; Call the skipper, but return t if it does not skip,
14286 ;; so that the `and' form continues evaluating
14287 (progn
14288 (unless (eq action 'sparse-tree) (org-agenda-skip))
14291 ;; Check if timestamps are deselecting this entry
14292 (or (not todo-only)
14293 (and (member todo org-not-done-keywords)
14294 (or (not org-agenda-tags-todo-honor-ignore-options)
14295 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14297 ;; select this headline
14298 (cond
14299 ((eq action 'sparse-tree)
14300 (and org-highlight-sparse-tree-matches
14301 (org-get-heading) (match-end 0)
14302 (org-highlight-new-match
14303 (match-beginning 1) (match-end 1)))
14304 (org-show-context 'tags-tree))
14305 ((eq action 'agenda)
14306 (setq txt (org-agenda-format-item
14308 (concat
14309 (if (eq org-tags-match-list-sublevels 'indented)
14310 (make-string (1- level) ?.) "")
14311 (org-get-heading))
14312 (make-string level ?\s)
14313 category
14314 tags-list)
14315 priority (org-get-priority txt))
14316 (goto-char lspos)
14317 (setq marker (org-agenda-new-marker))
14318 (org-add-props txt props
14319 'org-marker marker 'org-hd-marker marker 'org-category category
14320 'todo-state todo
14321 'ts-date ts-date
14322 'priority priority
14323 'type (concat "tagsmatch" ts-date-type))
14324 (push txt rtn))
14325 ((functionp action)
14326 (setq org-map-continue-from nil)
14327 (save-excursion
14328 (setq rtn1 (funcall action))
14329 (push rtn1 rtn)))
14330 (t (user-error "Invalid action")))
14332 ;; if we are to skip sublevels, jump to end of subtree
14333 (unless org-tags-match-list-sublevels
14334 (org-end-of-subtree t)
14335 (backward-char 1))))
14336 ;; Get the correct position from where to continue
14337 (if org-map-continue-from
14338 (goto-char org-map-continue-from)
14339 (and (= (point) lspos) (end-of-line 1)))))
14340 (when (and (eq action 'sparse-tree)
14341 (not org-sparse-tree-open-archived-trees))
14342 (org-hide-archived-subtrees (point-min) (point-max)))
14343 (nreverse rtn)))
14345 (defun org-remove-uninherited-tags (tags)
14346 "Remove all tags that are not inherited from the list TAGS."
14347 (cond
14348 ((eq org-use-tag-inheritance t)
14349 (if org-tags-exclude-from-inheritance
14350 (org-delete-all org-tags-exclude-from-inheritance tags)
14351 tags))
14352 ((not org-use-tag-inheritance) nil)
14353 ((stringp org-use-tag-inheritance)
14354 (delq nil (mapcar
14355 (lambda (x)
14356 (if (and (string-match org-use-tag-inheritance x)
14357 (not (member x org-tags-exclude-from-inheritance)))
14358 x nil))
14359 tags)))
14360 ((listp org-use-tag-inheritance)
14361 (delq nil (mapcar
14362 (lambda (x)
14363 (if (member x org-use-tag-inheritance) x nil))
14364 tags)))))
14366 (defun org-match-sparse-tree (&optional todo-only match)
14367 "Create a sparse tree according to tags string MATCH.
14368 MATCH can contain positive and negative selection of tags, like
14369 \"+WORK+URGENT-WITHBOSS\".
14370 If optional argument TODO-ONLY is non-nil, only select lines that are
14371 also TODO lines."
14372 (interactive "P")
14373 (org-agenda-prepare-buffers (list (current-buffer)))
14374 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14376 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14378 (defvar org-cached-props nil)
14379 (defun org-cached-entry-get (pom property)
14380 (if (or (eq t org-use-property-inheritance)
14381 (and (stringp org-use-property-inheritance)
14382 (let ((case-fold-search t))
14383 (org-string-match-p org-use-property-inheritance property)))
14384 (and (listp org-use-property-inheritance)
14385 (member-ignore-case property org-use-property-inheritance)))
14386 ;; Caching is not possible, check it directly.
14387 (org-entry-get pom property 'inherit)
14388 ;; Get all properties, so we can do complicated checks easily.
14389 (cdr (assoc-string property
14390 (or org-cached-props
14391 (setq org-cached-props (org-entry-properties pom)))
14392 t))))
14394 (defun org-global-tags-completion-table (&optional files)
14395 "Return the list of all tags in all agenda buffer/files.
14396 Optional FILES argument is a list of files which can be used
14397 instead of the agenda files."
14398 (save-excursion
14399 (org-uniquify
14400 (delq nil
14401 (apply 'append
14402 (mapcar
14403 (lambda (file)
14404 (set-buffer (find-file-noselect file))
14405 (append (org-get-buffer-tags)
14406 (mapcar (lambda (x) (if (stringp (car-safe x))
14407 (list (car-safe x)) nil))
14408 org-tag-alist)))
14409 (if (and files (car files))
14410 files
14411 (org-agenda-files))))))))
14413 (defun org-make-tags-matcher (match)
14414 "Create the TAGS/TODO matcher form for the selection string MATCH.
14416 The variable `todo-only' is scoped dynamically into this function.
14417 It will be set to t if the matcher restricts matching to TODO entries,
14418 otherwise will not be touched.
14420 Returns a cons of the selection string MATCH and the constructed
14421 lisp form implementing the matcher. The matcher is to be evaluated
14422 at an Org entry, with point on the headline, and returns t if the
14423 entry matches the selection string MATCH. The returned lisp form
14424 references two variables with information about the entry, which
14425 must be bound around the form's evaluation: todo, the TODO keyword
14426 at the entry (or nil of none); and tags-list, the list of all tags
14427 at the entry including inherited ones. Additionally, the category
14428 of the entry (if any) must be specified as the text property
14429 `org-category' on the headline.
14431 See also `org-scan-tags'.
14433 (declare (special todo-only))
14434 (unless (boundp 'todo-only)
14435 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14436 (unless match
14437 ;; Get a new match request, with completion against the global
14438 ;; tags table and the local tags in current buffer
14439 (let ((org-last-tags-completion-table
14440 (org-uniquify
14441 (delq nil (append (org-get-buffer-tags)
14442 (org-global-tags-completion-table))))))
14443 (setq match (org-completing-read-no-i
14444 "Match: " 'org-tags-completion-function nil nil nil
14445 'org-tags-history))))
14447 ;; Parse the string and create a lisp form
14448 (let ((match0 match)
14449 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14450 minus tag mm
14451 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14452 orterms term orlist re-p str-p level-p level-op time-p
14453 prop-p pn pv po gv rest (start 0) (ss 0))
14454 ;; Expand group tags
14455 (setq match (org-tags-expand match))
14457 ;; Check if there is a TODO part of this match, which would be the
14458 ;; part after a "/". TO make sure that this slash is not part of
14459 ;; a property value to be matched against, we also check that there
14460 ;; is no " after that slash.
14461 ;; First, find the last slash
14462 (while (string-match "/+" match ss)
14463 (setq start (match-beginning 0) ss (match-end 0)))
14464 (if (and (string-match "/+" match start)
14465 (not (save-match-data (string-match "\"" match start))))
14466 ;; match contains also a todo-matching request
14467 (progn
14468 (setq tagsmatch (substring match 0 (match-beginning 0))
14469 todomatch (substring match (match-end 0)))
14470 (when (string-match "^!" todomatch)
14471 (setq todo-only t todomatch (substring todomatch 1)))
14472 (when (string-match "^\\s-*$" todomatch)
14473 (setq todomatch nil)))
14474 ;; only matching tags
14475 (setq tagsmatch match todomatch nil))
14477 ;; Make the tags matcher
14478 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14479 (setq tagsmatcher t)
14480 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14481 (while (setq term (pop orterms))
14482 (while (and (equal (substring term -1) "\\") orterms)
14483 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14484 (while (string-match re term)
14485 (setq rest (substring term (match-end 0))
14486 minus (and (match-end 1)
14487 (equal (match-string 1 term) "-"))
14488 tag (save-match-data (replace-regexp-in-string
14489 "\\\\-" "-"
14490 (match-string 2 term)))
14491 re-p (equal (string-to-char tag) ?{)
14492 level-p (match-end 4)
14493 prop-p (match-end 5)
14494 mm (cond
14495 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14496 (level-p
14497 (setq level-op (org-op-to-function (match-string 3 term)))
14498 `(,level-op level ,(string-to-number
14499 (match-string 4 term))))
14500 (prop-p
14501 (setq pn (match-string 5 term)
14502 po (match-string 6 term)
14503 pv (match-string 7 term)
14504 re-p (equal (string-to-char pv) ?{)
14505 str-p (equal (string-to-char pv) ?\")
14506 time-p (save-match-data
14507 (string-match "^\"[[<].*[]>]\"$" pv))
14508 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14509 (when time-p (setq pv (org-matcher-time pv)))
14510 (setq po (org-op-to-function po (if time-p 'time str-p)))
14511 (cond
14512 ((equal pn "CATEGORY")
14513 (setq gv '(get-text-property (point) 'org-category)))
14514 ((equal pn "TODO")
14515 (setq gv 'todo))
14517 (setq gv `(org-cached-entry-get nil ,pn))))
14518 (if re-p
14519 (if (eq po 'org<>)
14520 `(not (string-match ,pv (or ,gv "")))
14521 `(string-match ,pv (or ,gv "")))
14522 (if str-p
14523 `(,po (or ,gv "") ,pv)
14524 `(,po (string-to-number (or ,gv ""))
14525 ,(string-to-number pv) ))))
14526 (t `(member ,tag tags-list)))
14527 mm (if minus (list 'not mm) mm)
14528 term rest)
14529 (push mm tagsmatcher))
14530 (push (if (> (length tagsmatcher) 1)
14531 (cons 'and tagsmatcher)
14532 (car tagsmatcher))
14533 orlist)
14534 (setq tagsmatcher nil))
14535 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14536 (setq tagsmatcher
14537 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14538 ;; Make the todo matcher
14539 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14540 (setq todomatcher t)
14541 (setq orterms (org-split-string todomatch "|") orlist nil)
14542 (dolist (term orterms)
14543 (while (string-match re term)
14544 (setq minus (and (match-end 1)
14545 (equal (match-string 1 term) "-"))
14546 kwd (match-string 2 term)
14547 re-p (equal (string-to-char kwd) ?{)
14548 term (substring term (match-end 0))
14549 mm (if re-p
14550 `(string-match ,(substring kwd 1 -1) todo)
14551 (list 'equal 'todo kwd))
14552 mm (if minus (list 'not mm) mm))
14553 (push mm todomatcher))
14554 (push (if (> (length todomatcher) 1)
14555 (cons 'and todomatcher)
14556 (car todomatcher))
14557 orlist)
14558 (setq todomatcher nil))
14559 (setq todomatcher (if (> (length orlist) 1)
14560 (cons 'or orlist) (car orlist))))
14562 ;; Return the string and lisp forms of the matcher
14563 (setq matcher (if todomatcher
14564 (list 'and tagsmatcher todomatcher)
14565 tagsmatcher))
14566 (when todo-only
14567 (setq matcher (list 'and '(member todo org-not-done-keywords)
14568 matcher)))
14569 (cons match0 matcher)))
14571 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14572 "Expand group tags in MATCH.
14574 This replaces every group tag in MATCH with a regexp tag search.
14575 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14576 will be replaced like this:
14578 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14579 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14580 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14582 Replacing by a regexp preserves the structure of the match.
14583 E.g., this expansion
14585 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14587 will match anything tagged with \"Lab\" and \"Home\", or tagged
14588 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14590 A group tag in MATCH can contain regular expressions of its own.
14591 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14592 will be replaced like this:
14594 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14596 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14597 assumed to be a single group tag, and the function will return
14598 the list of tags in this group.
14600 When DOWNCASE is non-nil, expand downcased TAGS."
14601 (if org-group-tags
14602 (let* ((case-fold-search t)
14603 (stable org-mode-syntax-table)
14604 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14605 (taggroups (if downcased
14606 (mapcar (lambda (tg) (mapcar #'downcase tg))
14607 taggroups)
14608 taggroups))
14609 (taggroups-keys (mapcar #'car taggroups))
14610 (return-match (if downcased (downcase match) match))
14611 (count 0)
14612 (work-already-expanded tags-already-expanded)
14613 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14614 ;; @ and _ are allowed as word-components in tags.
14615 (modify-syntax-entry ?@ "w" stable)
14616 (modify-syntax-entry ?_ "w" stable)
14617 ;; Temporarily replace regexp-expressions in the match-expression.
14618 (while (string-match "{.+?}" return-match)
14619 (incf count)
14620 (push (match-string 0 return-match) regexps-in-match)
14621 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14622 (while (and taggroups-keys
14623 (with-syntax-table stable
14624 (string-match
14625 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14626 (regexp-opt taggroups-keys) "\\>\\)")
14627 return-match)))
14628 (let* ((dir (match-string 1 return-match))
14629 (tag (match-string 2 return-match))
14630 (tag (if downcased (downcase tag) tag)))
14631 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14632 (member tag work-already-expanded))
14633 (setq tags-in-group (assoc tag taggroups))
14634 (push tag work-already-expanded)
14635 ;; Recursively expand each tag in the group, if the tag hasn't
14636 ;; already been expanded. Restore the match-data after all recursive calls.
14637 (save-match-data
14638 (let (tags-expanded)
14639 (dolist (x (cdr tags-in-group))
14640 (if (and (member x taggroups-keys)
14641 (not (member x work-already-expanded)))
14642 (setq tags-expanded
14643 (delete-dups
14644 (append
14645 (org-tags-expand x t downcased
14646 work-already-expanded)
14647 tags-expanded)))
14648 (setq tags-expanded
14649 (append (list x) tags-expanded)))
14650 (setq work-already-expanded
14651 (delete-dups
14652 (append tags-expanded
14653 work-already-expanded))))
14654 (setq tags-in-group
14655 (delete-dups (cons (car tags-in-group)
14656 tags-expanded)))))
14657 ;; Filter tag-regexps from tags.
14658 (setq regexp-in-group-escaped
14659 (delq nil (mapcar (lambda (x)
14660 (if (stringp x)
14661 (and (equal "{" (substring x 0 1))
14662 (equal "}" (substring x -1))
14665 tags-in-group))
14666 regexp-in-group
14667 (mapcar (lambda (x)
14668 (substring x 1 -1))
14669 regexp-in-group-escaped)
14670 tags-in-group
14671 (delq nil (mapcar (lambda (x)
14672 (if (stringp x)
14673 (and (not (equal "{" (substring x 0 1)))
14674 (not (equal "}" (substring x -1)))
14677 tags-in-group)))
14678 ;; If single-as-list, do no more in the while-loop.
14679 (if (not single-as-list)
14680 (progn
14681 (when regexp-in-group
14682 (setq regexp-in-group
14683 (concat "\\|"
14684 (mapconcat 'identity regexp-in-group
14685 "\\|"))))
14686 (setq tags-in-group
14687 (concat dir
14688 "{\\<"
14689 (regexp-opt tags-in-group)
14690 "\\>"
14691 regexp-in-group
14692 "}"))
14693 (when (stringp tags-in-group)
14694 (org-add-props tags-in-group '(grouptag t)))
14695 (setq return-match
14696 (replace-match tags-in-group t t return-match)))
14697 (setq tags-in-group
14698 (append regexp-in-group-escaped tags-in-group))))
14699 (setq taggroups-keys (delete tag taggroups-keys))))
14700 ;; Add the regular expressions back into the match-expression again.
14701 (while regexps-in-match
14702 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14703 (pop regexps-in-match)
14704 return-match t t))
14705 (decf count))
14706 (if single-as-list
14707 (if tags-in-group tags-in-group (list return-match))
14708 return-match))
14709 (if single-as-list
14710 (list (if downcased (downcase match) match))
14711 match)))
14713 (defun org-op-to-function (op &optional stringp)
14714 "Turn an operator into the appropriate function."
14715 (setq op
14716 (cond
14717 ((equal op "<" ) '(< string< org-time<))
14718 ((equal op ">" ) '(> org-string> org-time>))
14719 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14720 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14721 ((member op '("=" "==")) '(= string= org-time=))
14722 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14723 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14725 (defun org<> (a b) (not (= a b)))
14726 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14727 (defun org-string>= (a b) (not (string< a b)))
14728 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14729 (defun org-string<> (a b) (not (string= a b)))
14730 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14731 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14732 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14733 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14734 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14735 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14736 (defun org-2ft (s)
14737 "Convert S to a floating point time.
14738 If S is already a number, just return it. If it is a string, parse
14739 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14740 (cond
14741 ((numberp s) s)
14742 ((stringp s)
14743 (condition-case nil
14744 (float-time (apply 'encode-time (org-parse-time-string s)))
14745 (error 0.)))
14746 (t 0.)))
14748 (defun org-time-today ()
14749 "Time in seconds today at 0:00.
14750 Returns the float number of seconds since the beginning of the
14751 epoch to the beginning of today (00:00)."
14752 (float-time (apply 'encode-time
14753 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14755 (defun org-matcher-time (s)
14756 "Interpret a time comparison value."
14757 (save-match-data
14758 (cond
14759 ((string= s "<now>") (float-time))
14760 ((string= s "<today>") (org-time-today))
14761 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14762 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14763 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14764 (+ (org-time-today)
14765 (* (string-to-number (match-string 1 s))
14766 (cdr (assoc (match-string 2 s)
14767 '(("d" . 86400.0) ("w" . 604800.0)
14768 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14769 (t (org-2ft s)))))
14771 (defun org-match-any-p (re list)
14772 "Does re match any element of list?"
14773 (setq list (mapcar (lambda (x) (string-match re x)) list))
14774 (delq nil list))
14776 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14777 (defvar org-tags-overlay (make-overlay 1 1))
14778 (org-detach-overlay org-tags-overlay)
14780 (defun org-get-local-tags-at (&optional pos)
14781 "Get a list of tags defined in the current headline."
14782 (org-get-tags-at pos 'local))
14784 (defun org-get-local-tags ()
14785 "Get a list of tags defined in the current headline."
14786 (org-get-tags-at nil 'local))
14788 (defun org-get-tags-at (&optional pos local)
14789 "Get a list of all headline tags applicable at POS.
14790 POS defaults to point. If tags are inherited, the list contains
14791 the targets in the same sequence as the headlines appear, i.e.
14792 the tags of the current headline come last.
14793 When LOCAL is non-nil, only return tags from the current headline,
14794 ignore inherited ones."
14795 (interactive)
14796 (if (and org-trust-scanner-tags
14797 (or (not pos) (equal pos (point)))
14798 (not local))
14799 org-scanner-tags
14800 (let (tags ltags lastpos parent)
14801 (save-excursion
14802 (save-restriction
14803 (widen)
14804 (goto-char (or pos (point)))
14805 (save-match-data
14806 (catch 'done
14807 (condition-case nil
14808 (progn
14809 (org-back-to-heading t)
14810 (while (not (equal lastpos (point)))
14811 (setq lastpos (point))
14812 (when (looking-at
14813 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14814 (setq ltags (org-split-string
14815 (org-match-string-no-properties 1) ":"))
14816 (when parent
14817 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14818 (setq tags (append
14819 (if parent
14820 (org-remove-uninherited-tags ltags)
14821 ltags)
14822 tags)))
14823 (or org-use-tag-inheritance (throw 'done t))
14824 (when local (throw 'done t))
14825 (or (org-up-heading-safe) (error nil))
14826 (setq parent t)))
14827 (error nil)))))
14828 (if local
14829 tags
14830 (reverse (delete-dups
14831 (reverse (append
14832 (org-remove-uninherited-tags
14833 org-file-tags)
14834 tags)))))))))
14836 (defun org-add-prop-inherited (s)
14837 (add-text-properties 0 (length s) '(inherited t) s)
14840 (defun org-toggle-tag (tag &optional onoff)
14841 "Toggle the tag TAG for the current line.
14842 If ONOFF is `on' or `off', don't toggle but set to this state."
14843 (let (res current)
14844 (save-excursion
14845 (org-back-to-heading t)
14846 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14847 (point-at-eol) t)
14848 (progn
14849 (setq current (match-string 1))
14850 (replace-match ""))
14851 (setq current ""))
14852 (setq current (nreverse (org-split-string current ":")))
14853 (cond
14854 ((eq onoff 'on)
14855 (setq res t)
14856 (or (member tag current) (push tag current)))
14857 ((eq onoff 'off)
14858 (or (not (member tag current)) (setq current (delete tag current))))
14859 (t (if (member tag current)
14860 (setq current (delete tag current))
14861 (setq res t)
14862 (push tag current))))
14863 (end-of-line 1)
14864 (if current
14865 (progn
14866 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14867 (org-set-tags nil t))
14868 (delete-horizontal-space))
14869 (run-hooks 'org-after-tags-change-hook))
14870 res))
14872 (defun org-align-tags-here (to-col)
14873 ;; Assumes that this is a headline
14874 "Align tags on the current headline to TO-COL."
14875 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14876 (beginning-of-line 1)
14877 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14878 (< pos (match-beginning 2)))
14879 (progn
14880 (setq tags-l (- (match-end 2) (match-beginning 2)))
14881 (goto-char (match-beginning 1))
14882 (insert " ")
14883 (delete-region (point) (1+ (match-beginning 2)))
14884 (setq ncol (max (current-column)
14885 (1+ col)
14886 (if (> to-col 0)
14887 to-col
14888 (- (abs to-col) tags-l))))
14889 (setq p (point))
14890 (insert (make-string (- ncol (current-column)) ?\ ))
14891 (setq ncol (current-column))
14892 (when indent-tabs-mode (tabify p (point-at-eol)))
14893 (org-move-to-column (min ncol col)))
14894 (goto-char pos))))
14896 (defun org-set-tags-command (&optional arg just-align)
14897 "Call the set-tags command for the current entry."
14898 (interactive "P")
14899 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14900 (org-set-tags arg just-align)
14901 (save-excursion
14902 (unless (and (org-region-active-p)
14903 org-loop-over-headlines-in-active-region)
14904 (org-back-to-heading t))
14905 (org-set-tags arg just-align))))
14907 (defun org-set-tags-to (data)
14908 "Set the tags of the current entry to DATA, replacing the current tags.
14909 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14910 If DATA is nil or the empty string, any tags will be removed."
14911 (interactive "sTags: ")
14912 (setq data
14913 (cond
14914 ((eq data nil) "")
14915 ((equal data "") "")
14916 ((stringp data)
14917 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14918 ":"))
14919 ((listp data)
14920 (concat ":" (mapconcat 'identity data ":") ":"))))
14921 (when data
14922 (save-excursion
14923 (org-back-to-heading t)
14924 (when (looking-at org-complex-heading-regexp)
14925 (if (match-end 5)
14926 (progn
14927 (goto-char (match-beginning 5))
14928 (insert data)
14929 (delete-region (point) (point-at-eol))
14930 (org-set-tags nil 'align))
14931 (goto-char (point-at-eol))
14932 (insert " " data)
14933 (org-set-tags nil 'align)))
14934 (beginning-of-line 1)
14935 (when (looking-at ".*?\\([ \t]+\\)$")
14936 (delete-region (match-beginning 1) (match-end 1))))))
14938 (defun org-align-all-tags ()
14939 "Align the tags i all headings."
14940 (interactive)
14941 (save-excursion
14942 (or (ignore-errors (org-back-to-heading t))
14943 (outline-next-heading))
14944 (if (org-at-heading-p)
14945 (org-set-tags t)
14946 (message "No headings"))))
14948 (defvar org-indent-indentation-per-level)
14949 (defun org-set-tags (&optional arg just-align)
14950 "Set the tags for the current headline.
14951 With prefix ARG, realign all tags in headings in the current buffer.
14952 When JUST-ALIGN is non-nil, only align tags."
14953 (interactive "P")
14954 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14955 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14956 'region-start-level
14957 'region))
14958 org-loop-over-headlines-in-active-region)
14959 (org-map-entries
14960 ;; We don't use ARG and JUST-ALIGN here because these args
14961 ;; are not useful when looping over headlines.
14962 #'org-set-tags
14963 org-loop-over-headlines-in-active-region
14965 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14966 (let ((org-setting-tags t))
14967 (if arg
14968 (save-excursion
14969 (goto-char (point-min))
14970 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14971 (while (re-search-forward org-outline-regexp-bol nil t)
14972 (org-set-tags nil t)
14973 (end-of-line)))
14974 (message "All tags realigned to column %d" org-tags-column))
14975 (let* ((current (org-get-tags-string))
14976 (col (current-column))
14977 (tags
14978 (if just-align current
14979 ;; Get a new set of tags from the user.
14980 (save-excursion
14981 (let* ((table
14982 (setq
14983 org-last-tags-completion-table
14984 (append
14985 org-tag-persistent-alist
14986 (or org-tag-alist (org-get-buffer-tags))
14987 (and
14988 org-complete-tags-always-offer-all-agenda-tags
14989 (org-global-tags-completion-table
14990 (org-agenda-files))))))
14991 (current-tags (org-split-string current ":"))
14992 (inherited-tags
14993 (nreverse (nthcdr (length current-tags)
14994 (nreverse (org-get-tags-at))))))
14995 (replace-regexp-in-string
14996 "\\([-+&]+\\|,\\)"
14998 (if (or (eq t org-use-fast-tag-selection)
14999 (and org-use-fast-tag-selection
15000 (delq nil (mapcar #'cdr table))))
15001 (org-fast-tag-selection
15002 current-tags inherited-tags table
15003 (and org-fast-tag-selection-include-todo
15004 org-todo-key-alist))
15005 (let ((org-add-colon-after-tag-completion
15006 (< 1 (length table))))
15007 (org-trim
15008 (completing-read
15009 "Tags: "
15010 #'org-tags-completion-function
15011 nil nil current 'org-tags-history))))))))))
15013 (when org-tags-sort-function
15014 (setq tags
15015 (mapconcat
15016 #'identity
15017 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
15018 org-tags-sort-function)
15019 ":")))
15021 (if (not (org-string-nw-p tags)) (setq tags "")
15022 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15023 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15025 ;; Insert new tags at the correct column
15026 (beginning-of-line)
15027 (let ((level (if (looking-at org-outline-regexp)
15028 (- (match-end 0) (point) 1)
15029 1)))
15030 (cond
15031 ((and (equal current "") (equal tags "")))
15032 ((re-search-forward
15033 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15034 (line-end-position)
15036 (if (equal tags "") (replace-match "" t t)
15037 (goto-char (match-beginning 0))
15038 (let* ((c0 (current-column))
15039 ;; Compute offset for the case of org-indent-mode
15040 ;; active.
15041 (di (if (org-bound-and-true-p org-indent-mode)
15042 (* (1- org-indent-indentation-per-level)
15043 (1- level))
15045 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15046 (tc (+ org-tags-column
15047 (if (> org-tags-column 0) (- di) di)))
15048 (c1 (max (1+ c0)
15049 (if (> tc 0) tc
15050 (- (- tc) (string-width tags)))))
15051 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15052 (replace-match rpl t t)
15053 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15054 (tabify p0 (point))))))
15055 (t (error "Tags alignment failed"))))
15056 (org-move-to-column col))
15057 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15059 (defun org-change-tag-in-region (beg end tag off)
15060 "Add or remove TAG for each entry in the region.
15061 This works in the agenda, and also in an org-mode buffer."
15062 (interactive
15063 (list (region-beginning) (region-end)
15064 (let ((org-last-tags-completion-table
15065 (if (derived-mode-p 'org-mode)
15066 (org-uniquify
15067 (delq nil (append (org-get-buffer-tags)
15068 (org-global-tags-completion-table))))
15069 (org-global-tags-completion-table))))
15070 (org-icompleting-read
15071 "Tag: " 'org-tags-completion-function nil nil nil
15072 'org-tags-history))
15073 (progn
15074 (message "[s]et or [r]emove? ")
15075 (equal (read-char-exclusive) ?r))))
15076 (when (fboundp 'deactivate-mark) (deactivate-mark))
15077 (let ((agendap (equal major-mode 'org-agenda-mode))
15078 l1 l2 m buf pos newhead (cnt 0))
15079 (goto-char end)
15080 (setq l2 (1- (org-current-line)))
15081 (goto-char beg)
15082 (setq l1 (org-current-line))
15083 (loop for l from l1 to l2 do
15084 (org-goto-line l)
15085 (setq m (get-text-property (point) 'org-hd-marker))
15086 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15087 (and agendap m))
15088 (setq buf (if agendap (marker-buffer m) (current-buffer))
15089 pos (if agendap m (point)))
15090 (with-current-buffer buf
15091 (save-excursion
15092 (save-restriction
15093 (goto-char pos)
15094 (setq cnt (1+ cnt))
15095 (org-toggle-tag tag (if off 'off 'on))
15096 (setq newhead (org-get-heading)))))
15097 (and agendap (org-agenda-change-all-lines newhead m))))
15098 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15100 (defun org-tags-completion-function (string predicate &optional flag)
15101 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15102 (confirm (lambda (x) (stringp (car x)))))
15103 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15104 (setq s1 (match-string 1 string)
15105 s2 (match-string 2 string))
15106 (setq s1 "" s2 string))
15107 (cond
15108 ((eq flag nil)
15109 ;; try completion
15110 (setq rtn (try-completion s2 ctable confirm))
15111 (when (stringp rtn)
15112 (setq rtn
15113 (concat s1 s2 (substring rtn (length s2))
15114 (if (and org-add-colon-after-tag-completion
15115 (assoc rtn ctable))
15116 ":" ""))))
15117 rtn)
15118 ((eq flag t)
15119 ;; all-completions
15120 (all-completions s2 ctable confirm))
15121 ((eq flag 'lambda)
15122 ;; exact match?
15123 (assoc s2 ctable)))))
15125 (defun org-fast-tag-insert (kwd tags face &optional end)
15126 "Insert KDW, and the TAGS, the latter with face FACE.
15127 Also insert END."
15128 (insert (format "%-12s" (concat kwd ":"))
15129 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15130 (or end "")))
15132 (defun org-fast-tag-show-exit (flag)
15133 (save-excursion
15134 (org-goto-line 3)
15135 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15136 (replace-match ""))
15137 (when flag
15138 (end-of-line 1)
15139 (org-move-to-column (- (window-width) 19) t)
15140 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15142 (defun org-set-current-tags-overlay (current prefix)
15143 "Add an overlay to CURRENT tag with PREFIX."
15144 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15145 (if (featurep 'xemacs)
15146 (org-overlay-display org-tags-overlay (concat prefix s)
15147 'secondary-selection)
15148 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15149 (org-overlay-display org-tags-overlay (concat prefix s)))))
15151 (defvar org-last-tag-selection-key nil)
15152 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15153 "Fast tag selection with single keys.
15154 CURRENT is the current list of tags in the headline, INHERITED is the
15155 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15156 possibly with grouping information. TODO-TABLE is a similar table with
15157 TODO keywords, should these have keys assigned to them.
15158 If the keys are nil, a-z are automatically assigned.
15159 Returns the new tags string, or nil to not change the current settings."
15160 (let* ((fulltable (append table todo-table))
15161 (maxlen (apply 'max (mapcar
15162 (lambda (x)
15163 (if (stringp (car x)) (string-width (car x)) 0))
15164 fulltable)))
15165 (buf (current-buffer))
15166 (expert (eq org-fast-tag-selection-single-key 'expert))
15167 (buffer-tags nil)
15168 (fwidth (+ maxlen 3 1 3))
15169 (ncol (/ (- (window-width) 4) fwidth))
15170 (i-face 'org-done)
15171 (c-face 'org-todo)
15172 tg cnt e c char c1 c2 ntable tbl rtn
15173 ov-start ov-end ov-prefix
15174 (exit-after-next org-fast-tag-selection-single-key)
15175 (done-keywords org-done-keywords)
15176 groups ingroup intaggroup)
15177 (save-excursion
15178 (beginning-of-line 1)
15179 (if (looking-at
15180 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15181 (setq ov-start (match-beginning 1)
15182 ov-end (match-end 1)
15183 ov-prefix "")
15184 (setq ov-start (1- (point-at-eol))
15185 ov-end (1+ ov-start))
15186 (skip-chars-forward "^\n\r")
15187 (setq ov-prefix
15188 (concat
15189 (buffer-substring (1- (point)) (point))
15190 (if (> (current-column) org-tags-column)
15192 (make-string (- org-tags-column (current-column)) ?\ ))))))
15193 (move-overlay org-tags-overlay ov-start ov-end)
15194 (save-window-excursion
15195 (if expert
15196 (set-buffer (get-buffer-create " *Org tags*"))
15197 (delete-other-windows)
15198 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15199 (org-switch-to-buffer-other-window " *Org tags*"))
15200 (erase-buffer)
15201 (setq-local org-done-keywords done-keywords)
15202 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15203 (org-fast-tag-insert "Current" current c-face "\n\n")
15204 (org-fast-tag-show-exit exit-after-next)
15205 (org-set-current-tags-overlay current ov-prefix)
15206 (setq tbl fulltable char ?a cnt 0)
15207 (while (setq e (pop tbl))
15208 (cond
15209 ((eq (car e) :startgroup)
15210 (push '() groups) (setq ingroup t)
15211 (unless (zerop cnt)
15212 (setq cnt 0)
15213 (insert "\n"))
15214 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15215 ((eq (car e) :endgroup)
15216 (setq ingroup nil cnt 0)
15217 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15218 ((eq (car e) :startgrouptag)
15219 (setq intaggroup t)
15220 (unless (zerop cnt)
15221 (setq cnt 0)
15222 (insert "\n"))
15223 (insert "[ "))
15224 ((eq (car e) :endgrouptag)
15225 (setq intaggroup nil cnt 0)
15226 (insert "]\n"))
15227 ((equal e '(:newline))
15228 (unless (zerop cnt)
15229 (setq cnt 0)
15230 (insert "\n")
15231 (setq e (car tbl))
15232 (while (equal (car tbl) '(:newline))
15233 (insert "\n")
15234 (setq tbl (cdr tbl)))))
15235 ((equal e '(:grouptags)) (insert " : "))
15237 (setq tg (copy-sequence (car e)) c2 nil)
15238 (if (cdr e)
15239 (setq c (cdr e))
15240 ;; automatically assign a character.
15241 (setq c1 (string-to-char
15242 (downcase (substring
15243 tg (if (= (string-to-char tg) ?@) 1 0)))))
15244 (if (or (rassoc c1 ntable) (rassoc c1 table))
15245 (while (or (rassoc char ntable) (rassoc char table))
15246 (setq char (1+ char)))
15247 (setq c2 c1))
15248 (setq c (or c2 char)))
15249 (when ingroup (push tg (car groups)))
15250 (setq tg (org-add-props tg nil 'face
15251 (cond
15252 ((not (assoc tg table))
15253 (org-get-todo-face tg))
15254 ((member tg current) c-face)
15255 ((member tg inherited) i-face))))
15256 (when (equal (caar tbl) :grouptags)
15257 (org-add-props tg nil 'face 'org-tag-group))
15258 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15259 (insert "[" c "] " tg (make-string
15260 (- fwidth 4 (length tg)) ?\ ))
15261 (push (cons tg c) ntable)
15262 (when (= (incf cnt) ncol)
15263 (insert "\n")
15264 (when (or ingroup intaggroup) (insert " "))
15265 (setq cnt 0)))))
15266 (setq ntable (nreverse ntable))
15267 (insert "\n")
15268 (goto-char (point-min))
15269 (unless expert (org-fit-window-to-buffer))
15270 (setq rtn
15271 (catch 'exit
15272 (while t
15273 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15274 (if (not groups) "no " "")
15275 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15276 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15277 (setq org-last-tag-selection-key c)
15278 (cond
15279 ((= c ?\r) (throw 'exit t))
15280 ((= c ?!)
15281 (setq groups (not groups))
15282 (goto-char (point-min))
15283 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15284 ((= c ?\C-c)
15285 (if (not expert)
15286 (org-fast-tag-show-exit
15287 (setq exit-after-next (not exit-after-next)))
15288 (setq expert nil)
15289 (delete-other-windows)
15290 (set-window-buffer (split-window-vertically) " *Org tags*")
15291 (org-switch-to-buffer-other-window " *Org tags*")
15292 (org-fit-window-to-buffer)))
15293 ((or (= c ?\C-g)
15294 (and (= c ?q) (not (rassoc c ntable))))
15295 (org-detach-overlay org-tags-overlay)
15296 (setq quit-flag t))
15297 ((= c ?\ )
15298 (setq current nil)
15299 (when exit-after-next (setq exit-after-next 'now)))
15300 ((= c ?\t)
15301 (condition-case nil
15302 (setq tg (org-icompleting-read
15303 "Tag: "
15304 (or buffer-tags
15305 (with-current-buffer buf
15306 (setq buffer-tags
15307 (org-get-buffer-tags))))))
15308 (quit (setq tg "")))
15309 (when (string-match "\\S-" tg)
15310 (add-to-list 'buffer-tags (list tg))
15311 (if (member tg current)
15312 (setq current (delete tg current))
15313 (push tg current)))
15314 (when exit-after-next (setq exit-after-next 'now)))
15315 ((setq e (rassoc c todo-table) tg (car e))
15316 (with-current-buffer buf
15317 (save-excursion (org-todo tg)))
15318 (when exit-after-next (setq exit-after-next 'now)))
15319 ((setq e (rassoc c ntable) tg (car e))
15320 (if (member tg current)
15321 (setq current (delete tg current))
15322 (loop for g in groups do
15323 (when (member tg g)
15324 (dolist (x g) (setq current (delete x current)))))
15325 (push tg current))
15326 (when exit-after-next (setq exit-after-next 'now))))
15328 ;; Create a sorted list
15329 (setq current
15330 (sort current
15331 (lambda (a b)
15332 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15333 (when (eq exit-after-next 'now) (throw 'exit t))
15334 (goto-char (point-min))
15335 (beginning-of-line 2)
15336 (delete-region (point) (point-at-eol))
15337 (org-fast-tag-insert "Current" current c-face)
15338 (org-set-current-tags-overlay current ov-prefix)
15339 (while (re-search-forward
15340 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15341 (setq tg (match-string 1))
15342 (add-text-properties
15343 (match-beginning 1) (match-end 1)
15344 (list 'face
15345 (cond
15346 ((member tg current) c-face)
15347 ((member tg inherited) i-face)
15348 (t (get-text-property (match-beginning 1) 'face))))))
15349 (goto-char (point-min)))))
15350 (org-detach-overlay org-tags-overlay)
15351 (if rtn
15352 (mapconcat 'identity current ":")
15353 nil))))
15355 (defun org-get-tags-string ()
15356 "Get the TAGS string in the current headline."
15357 (unless (org-at-heading-p t)
15358 (user-error "Not on a heading"))
15359 (save-excursion
15360 (beginning-of-line 1)
15361 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15362 (org-match-string-no-properties 1)
15363 "")))
15365 (defun org-get-tags ()
15366 "Get the list of tags specified in the current headline."
15367 (org-split-string (org-get-tags-string) ":"))
15369 (defun org-get-buffer-tags ()
15370 "Get a table of all tags used in the buffer, for completion."
15371 (org-with-wide-buffer
15372 (goto-char (point-min))
15373 (let ((tag-re (concat org-outline-regexp-bol
15374 "\\(?:.*?[ \t]\\)?"
15375 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15376 tags)
15377 (while (re-search-forward tag-re nil t)
15378 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15379 (push tag tags)))
15380 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15382 ;;;; The mapping API
15384 (defun org-map-entries (func &optional match scope &rest skip)
15385 "Call FUNC at each headline selected by MATCH in SCOPE.
15387 FUNC is a function or a lisp form. The function will be called without
15388 arguments, with the cursor positioned at the beginning of the headline.
15389 The return values of all calls to the function will be collected and
15390 returned as a list.
15392 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15393 does not need to preserve point. After evaluation, the cursor will be
15394 moved to the end of the line (presumably of the headline of the
15395 processed entry) and search continues from there. Under some
15396 circumstances, this may not produce the wanted results. For example,
15397 if you have removed (e.g. archived) the current (sub)tree it could
15398 mean that the next entry will be skipped entirely. In such cases, you
15399 can specify the position from where search should continue by making
15400 FUNC set the variable `org-map-continue-from' to the desired buffer
15401 position.
15403 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15404 Only headlines that are matched by this query will be considered during
15405 the iteration. When MATCH is nil or t, all headlines will be
15406 visited by the iteration.
15408 SCOPE determines the scope of this command. It can be any of:
15410 nil The current buffer, respecting the restriction if any
15411 tree The subtree started with the entry at point
15412 region The entries within the active region, if any
15413 region-start-level
15414 The entries within the active region, but only those at
15415 the same level than the first one.
15416 file The current buffer, without restriction
15417 file-with-archives
15418 The current buffer, and any archives associated with it
15419 agenda All agenda files
15420 agenda-with-archives
15421 All agenda files with any archive files associated with them
15422 \(file1 file2 ...)
15423 If this is a list, all files in the list will be scanned
15425 The remaining args are treated as settings for the skipping facilities of
15426 the scanner. The following items can be given here:
15428 archive skip trees with the archive tag
15429 comment skip trees with the COMMENT keyword
15430 function or Emacs Lisp form:
15431 will be used as value for `org-agenda-skip-function', so
15432 whenever the function returns a position, FUNC will not be
15433 called for that entry and search will continue from the
15434 position returned
15436 If your function needs to retrieve the tags including inherited tags
15437 at the *current* entry, you can use the value of the variable
15438 `org-scanner-tags' which will be much faster than getting the value
15439 with `org-get-tags-at'. If your function gets properties with
15440 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15441 to t around the call to `org-entry-properties' to get the same speedup.
15442 Note that if your function moves around to retrieve tags and properties at
15443 a *different* entry, you cannot use these techniques."
15444 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15445 (not (org-region-active-p)))
15446 (let* ((org-agenda-archives-mode nil) ; just to make sure
15447 (org-agenda-skip-archived-trees (memq 'archive skip))
15448 (org-agenda-skip-comment-trees (memq 'comment skip))
15449 (org-agenda-skip-function
15450 (car (org-delete-all '(comment archive) skip)))
15451 (org-tags-match-list-sublevels t)
15452 (start-level (eq scope 'region-start-level))
15453 matcher file res
15454 org-todo-keywords-for-agenda
15455 org-done-keywords-for-agenda
15456 org-todo-keyword-alist-for-agenda
15457 org-tag-alist-for-agenda
15458 todo-only)
15460 (cond
15461 ((eq match t) (setq matcher t))
15462 ((eq match nil) (setq matcher t))
15463 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15465 (save-excursion
15466 (save-restriction
15467 (cond ((eq scope 'tree)
15468 (org-back-to-heading t)
15469 (org-narrow-to-subtree)
15470 (setq scope nil))
15471 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15472 (org-region-active-p))
15473 ;; If needed, set start-level to a string like "2"
15474 (when start-level
15475 (save-excursion
15476 (goto-char (region-beginning))
15477 (unless (org-at-heading-p) (outline-next-heading))
15478 (setq start-level (org-current-level))))
15479 (narrow-to-region (region-beginning)
15480 (save-excursion
15481 (goto-char (region-end))
15482 (unless (and (bolp) (org-at-heading-p))
15483 (outline-next-heading))
15484 (point)))
15485 (setq scope nil)))
15487 (if (not scope)
15488 (progn
15489 (org-agenda-prepare-buffers
15490 (and buffer-file-name (list buffer-file-name)))
15491 (setq res (org-scan-tags func matcher todo-only start-level)))
15492 ;; Get the right scope
15493 (cond
15494 ((and scope (listp scope) (symbolp (car scope)))
15495 (setq scope (eval scope)))
15496 ((eq scope 'agenda)
15497 (setq scope (org-agenda-files t)))
15498 ((eq scope 'agenda-with-archives)
15499 (setq scope (org-agenda-files t))
15500 (setq scope (org-add-archive-files scope)))
15501 ((eq scope 'file)
15502 (setq scope (and buffer-file-name (list buffer-file-name))))
15503 ((eq scope 'file-with-archives)
15504 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15505 (org-agenda-prepare-buffers scope)
15506 (dolist (file scope)
15507 (with-current-buffer (org-find-base-buffer-visiting file)
15508 (save-excursion
15509 (save-restriction
15510 (widen)
15511 (goto-char (point-min))
15512 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15513 res)))
15515 ;;; Properties API
15517 (defconst org-special-properties
15518 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15519 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15520 "The special properties valid in Org mode.
15521 These are properties that are not defined in the property drawer,
15522 but in some other way.")
15524 (defconst org-default-properties
15525 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15526 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15527 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15528 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15529 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15530 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15531 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15532 "Some properties that are used by Org mode for various purposes.
15533 Being in this list makes sure that they are offered for completion.")
15535 (defun org--valid-property-p (property)
15536 "Non nil when string PROPERTY is a valid property name."
15537 (not
15538 (or (equal property "")
15539 (org-string-match-p "\\s-" property))))
15541 (defun org--update-property-plist (key val props)
15542 "Associate KEY to VAL in alist PROPS.
15543 Modifications are made by side-effect. Return new alist."
15544 (let* ((appending (string= (substring key -1) "+"))
15545 (key (if appending (substring key 0 -1) key))
15546 (old (assoc-string key props t)))
15547 (if (not old) (cons (cons key val) props)
15548 (setcdr old (if appending (concat (cdr old) " " val) val))
15549 props)))
15551 (defun org-get-property-block (&optional beg force)
15552 "Return the (beg . end) range of the body of the property drawer.
15553 BEG is the beginning of the current subtree, or of the part
15554 before the first headline. If it is not given, it will be found.
15555 If the drawer does not exist, create it if FORCE is non-nil, or
15556 return nil."
15557 (org-with-wide-buffer
15558 (when beg (goto-char beg))
15559 (unless (org-before-first-heading-p)
15560 (let ((beg (cond (beg)
15561 ((or (not (featurep 'org-inlinetask))
15562 (org-inlinetask-in-task-p))
15563 (org-back-to-heading t))
15564 (t (org-with-limited-levels (org-back-to-heading t))))))
15565 (forward-line)
15566 (when (org-looking-at-p org-planning-line-re) (forward-line))
15567 (cond ((looking-at org-property-drawer-re)
15568 (forward-line)
15569 (cons (point) (progn (goto-char (match-end 0))
15570 (line-beginning-position))))
15571 (force
15572 (goto-char beg)
15573 (org-insert-property-drawer)
15574 (let ((pos (save-excursion (search-forward ":END:")
15575 (line-beginning-position))))
15576 (cons pos pos))))))))
15578 (defun org-at-property-p ()
15579 "Non-nil when point is inside a property drawer.
15580 See `org-property-re' for match data, if applicable."
15581 (save-excursion
15582 (beginning-of-line)
15583 (and (looking-at org-property-re)
15584 (let ((property-drawer (save-match-data (org-get-property-block))))
15585 (and property-drawer
15586 (>= (point) (car property-drawer))
15587 (< (point) (cdr property-drawer)))))))
15589 (defun org-property-action ()
15590 "Do an action on properties."
15591 (interactive)
15592 (unless (org-at-property-p) (user-error "Not at a property"))
15593 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15594 (let ((c (read-char-exclusive)))
15595 (case c
15596 (?s (call-interactively #'org-set-property))
15597 (?d (call-interactively #'org-delete-property))
15598 (?D (call-interactively #'org-delete-property-globally))
15599 (?c (call-interactively #'org-compute-property-at-point))
15600 (otherwise (user-error "No such property action %c" c)))))
15602 (defun org-inc-effort ()
15603 "Increment the value of the effort property in the current entry."
15604 (interactive)
15605 (org-set-effort nil t))
15607 (defvar org-clock-effort) ; Defined in org-clock.el.
15608 (defvar org-clock-current-task) ; Defined in org-clock.el.
15609 (defun org-set-effort (&optional value increment)
15610 "Set the effort property of the current entry.
15611 With numerical prefix arg, use the nth allowed value, 0 stands for the
15612 10th allowed value.
15614 When INCREMENT is non-nil, set the property to the next allowed value."
15615 (interactive "P")
15616 (when (equal value 0) (setq value 10))
15617 (let* ((completion-ignore-case t)
15618 (prop org-effort-property)
15619 (cur (org-entry-get nil prop))
15620 (allowed (org-property-get-allowed-values nil prop 'table))
15621 (existing (mapcar 'list (org-property-values prop)))
15622 (heading (nth 4 (org-heading-components)))
15624 (val (cond
15625 ((stringp value) value)
15626 ((and allowed (integerp value))
15627 (or (car (nth (1- value) allowed))
15628 (car (org-last allowed))))
15629 ((and allowed increment)
15630 (or (caadr (member (list cur) allowed))
15631 (user-error "Allowed effort values are not set")))
15632 (allowed
15633 (message "Select 1-9,0, [RET%s]: %s"
15634 (if cur (concat "=" cur) "")
15635 (mapconcat 'car allowed " "))
15636 (setq rpl (read-char-exclusive))
15637 (if (equal rpl ?\r)
15639 (setq rpl (- rpl ?0))
15640 (when (equal rpl 0) (setq rpl 10))
15641 (if (and (> rpl 0) (<= rpl (length allowed)))
15642 (car (nth (1- rpl) allowed))
15643 (org-completing-read "Effort: " allowed nil))))
15645 (let (org-completion-use-ido org-completion-use-iswitchb)
15646 (org-completing-read
15647 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15648 (concat "[" cur "]") "")
15649 ": ")
15650 existing nil nil "" nil cur))))))
15651 (unless (equal (org-entry-get nil prop) val)
15652 (org-entry-put nil prop val))
15653 (org-refresh-property
15654 '((effort . identity)
15655 (effort-minutes . org-duration-string-to-minutes))
15656 val)
15657 (when (string= heading org-clock-current-task)
15658 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15659 (org-clock-update-mode-line))
15660 (message "%s is now %s" prop val)))
15662 (defun org-entry-properties (&optional pom which)
15663 "Get all properties of the current entry.
15665 When POM is a buffer position, get all properties from the entry
15666 there instead.
15668 This includes the TODO keyword, the tags, time strings for
15669 deadline, scheduled, and clocking, and any additional properties
15670 defined in the entry.
15672 If WHICH is nil or `all', get all properties. If WHICH is
15673 `special' or `standard', only get that subclass. If WHICH is
15674 a string, only get that property.
15676 Return value is an alist. Keys are properties, as upcased
15677 strings."
15678 (org-with-point-at pom
15679 (when (and (derived-mode-p 'org-mode)
15680 (ignore-errors (org-back-to-heading t)))
15681 (catch 'exit
15682 (let* ((beg (point))
15683 (specific (and (stringp which) (upcase which)))
15684 (which (cond ((not specific) which)
15685 ((member specific org-special-properties) 'special)
15686 (t 'standard)))
15687 props)
15688 ;; Get the special properties, like TODO and TAGS.
15689 (when (memq which '(nil all special))
15690 (when (or (not specific) (string= specific "CLOCKSUM"))
15691 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15692 (when clocksum
15693 (push (cons "CLOCKSUM"
15694 (org-columns-number-to-string
15695 (/ (float clocksum) 60.) 'add_times))
15696 props)))
15697 (when specific (throw 'exit props)))
15698 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15699 (let ((clocksumt (get-text-property (point)
15700 :org-clock-minutes-today)))
15701 (when clocksumt
15702 (push (cons "CLOCKSUM_T"
15703 (org-columns-number-to-string
15704 (/ (float clocksumt) 60.) 'add_times))
15705 props)))
15706 (when specific (throw 'exit props)))
15707 (when (or (not specific) (string= specific "ITEM"))
15708 (when (looking-at org-complex-heading-regexp)
15709 (push (cons "ITEM"
15710 (concat
15711 (org-match-string-no-properties 1)
15712 (let ((title (org-match-string-no-properties 4)))
15713 (when (org-string-nw-p title)
15714 (concat " " (org-remove-tabs title))))))
15715 props))
15716 (when specific (throw 'exit props)))
15717 (when (or (not specific) (string= specific "TODO"))
15718 (let ((case-fold-search nil))
15719 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15720 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15721 (when specific (throw 'exit props)))
15722 (when (or (not specific) (string= specific "PRIORITY"))
15723 (push (cons "PRIORITY"
15724 (if (looking-at org-priority-regexp)
15725 (org-match-string-no-properties 2)
15726 (char-to-string org-default-priority)))
15727 props)
15728 (when specific (throw 'exit props)))
15729 (when (or (not specific) (string= specific "FILE"))
15730 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15731 props)
15732 (when specific (throw 'exit props)))
15733 (when (or (not specific) (string= specific "TAGS"))
15734 (let ((value (org-string-nw-p (org-get-tags-string))))
15735 (when value (push (cons "TAGS" value) props)))
15736 (when specific (throw 'exit props)))
15737 (when (or (not specific) (string= specific "ALLTAGS"))
15738 (let ((value (org-get-tags-at)))
15739 (when value
15740 (push (cons "ALLTAGS"
15741 (format ":%s:" (mapconcat #'identity value ":")))
15742 props)))
15743 (when specific (throw 'exit props)))
15744 (when (or (not specific) (string= specific "BLOCKED"))
15745 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15746 (when specific (throw 'exit props)))
15747 (when (or (not specific)
15748 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15749 (forward-line)
15750 (when (org-looking-at-p org-planning-line-re)
15751 (end-of-line)
15752 (let ((bol (line-beginning-position))
15753 ;; Backward compatibility: time keywords used to
15754 ;; be configurable (before 8.3). Make sure we
15755 ;; get the correct keyword.
15756 (key-assoc `(("CLOSED" . ,org-closed-string)
15757 ("DEADLINE" . ,org-deadline-string)
15758 ("SCHEDULED" . ,org-scheduled-string))))
15759 (dolist (pair (if specific (list (assoc specific key-assoc))
15760 key-assoc))
15761 (save-excursion
15762 (when (search-backward (cdr pair) bol t)
15763 (goto-char (match-end 0))
15764 (skip-chars-forward " \t")
15765 (and (looking-at org-ts-regexp-both)
15766 (push (cons (car pair)
15767 (org-match-string-no-properties 0))
15768 props)))))))
15769 (when specific (throw 'exit props)))
15770 (when (or (not specific)
15771 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15772 (let ((find-ts
15773 (lambda (end ts)
15774 (let ((regexp (cond
15775 ((string= specific "TIMESTAMP")
15776 org-ts-regexp)
15777 ((string= specific "TIMESTAMP_IA")
15778 org-ts-regexp-inactive)
15779 ((assoc "TIMESTAMP_IA" ts)
15780 org-ts-regexp)
15781 ((assoc "TIMESTAMP" ts)
15782 org-ts-regexp-inactive)
15783 (t org-ts-regexp-both))))
15784 (catch 'next
15785 (while (re-search-forward regexp end t)
15786 (backward-char)
15787 (let ((object (org-element-context)))
15788 ;; Accept to match timestamps in node
15789 ;; properties, too.
15790 (when (memq (org-element-type object)
15791 '(node-property timestamp))
15792 (let ((type
15793 (org-element-property :type object)))
15794 (cond
15795 ((and (memq type '(active active-range))
15796 (not (equal specific "TIMESTAMP_IA")))
15797 (unless (assoc "TIMESTAMP" ts)
15798 (push (cons "TIMESTAMP"
15799 (org-element-property
15800 :raw-value object))
15802 (when specific (throw 'exit ts))))
15803 ((and (memq type '(inactive inactive-range))
15804 (not (string= specific "TIMESTAMP")))
15805 (unless (assoc "TIMESTAMP_IA" ts)
15806 (push (cons "TIMESTAMP_IA"
15807 (org-element-property
15808 :raw-value object))
15810 (when specific (throw 'exit ts))))))
15811 ;; Both timestamp types are found,
15812 ;; move to next part.
15813 (when (= (length ts) 2) (throw 'next ts)))))
15814 ts)))))
15815 (goto-char beg)
15816 ;; First look for timestamps within headline.
15817 (let ((ts (funcall find-ts (line-end-position) nil)))
15818 (if (= (length ts) 2) (setq props (nconc ts props))
15819 (forward-line)
15820 ;; Then find timestamps in the section, skipping
15821 ;; planning line.
15822 (when (org-looking-at-p org-planning-line-re)
15823 (forward-line))
15824 (let ((end (save-excursion (outline-next-heading))))
15825 (setq props (nconc (funcall find-ts end ts) props))))))))
15826 ;; Get the standard properties, like :PROP:.
15827 (when (memq which '(nil all standard))
15828 ;; If we are looking after a specific property, delegate
15829 ;; to `org-entry-get', which is faster. However, make an
15830 ;; exception for "CATEGORY", since it can be also set
15831 ;; through keywords (i.e. #+CATEGORY).
15832 (if (and specific (not (equal specific "CATEGORY")))
15833 (let ((value (org-entry-get beg specific nil t)))
15834 (throw 'exit (and value (list (cons specific value)))))
15835 (let ((range (org-get-property-block beg)))
15836 (when range
15837 (let ((end (cdr range)) seen-base)
15838 (goto-char (car range))
15839 ;; Unlike to `org--update-property-plist', we
15840 ;; handle the case where base values is found
15841 ;; after its extension. We also forbid standard
15842 ;; properties to be named as special properties.
15843 (while (re-search-forward org-property-re end t)
15844 (let* ((key (upcase (org-match-string-no-properties 2)))
15845 (extendp (org-string-match-p "\\+\\'" key))
15846 (key-base (if extendp (substring key 0 -1) key))
15847 (value (org-match-string-no-properties 3)))
15848 (cond
15849 ((member-ignore-case key-base org-special-properties))
15850 (extendp
15851 (setq props
15852 (org--update-property-plist key value props)))
15853 ((member key seen-base))
15854 (t (push key seen-base)
15855 (let ((p (assoc-string key props t)))
15856 (if p (setcdr p (concat value " " (cdr p)))
15857 (push (cons key value) props))))))))))))
15858 (unless (assoc "CATEGORY" props)
15859 (push (cons "CATEGORY" (org-get-category beg)) props)
15860 (when (string= specific "CATEGORY") (throw 'exit props)))
15861 ;; Return value.
15862 props)))))
15864 (defun org-property--local-values (property literal-nil)
15865 "Return value for PROPERTY in current entry.
15866 Value is a list whose care is the base value for PROPERTY and cdr
15867 a list of accumulated values. Return nil if neither is found in
15868 the entry. Also return nil when PROPERTY is set to \"nil\",
15869 unless LITERAL-NIL is non-nil."
15870 (let ((range (org-get-property-block)))
15871 (when range
15872 (goto-char (car range))
15873 (let* ((case-fold-search t)
15874 (end (cdr range))
15875 (value
15876 ;; Base value.
15877 (save-excursion
15878 (let ((v (and (re-search-forward
15879 (org-re-property property nil t) end t)
15880 (org-match-string-no-properties 3))))
15881 (list (if literal-nil v (org-not-nil v)))))))
15882 ;; Find additional values.
15883 (let* ((property+ (org-re-property (concat property "+") nil t)))
15884 (while (re-search-forward property+ end t)
15885 (push (org-match-string-no-properties 3) value)))
15886 ;; Return final values.
15887 (and (not (equal value '(nil))) (nreverse value))))))
15889 (defun org-entry-get (pom property &optional inherit literal-nil)
15890 "Get value of PROPERTY for entry or content at point-or-marker POM.
15892 If INHERIT is non-nil and the entry does not have the property,
15893 then also check higher levels of the hierarchy. If INHERIT is
15894 the symbol `selective', use inheritance only if the setting in
15895 `org-use-property-inheritance' selects PROPERTY for inheritance.
15897 If the property is present but empty, the return value is the
15898 empty string. If the property is not present at all, nil is
15899 returned. In any other case, return the value as a string.
15900 Search is case-insensitive.
15902 If LITERAL-NIL is set, return the string value \"nil\" as
15903 a string, do not interpret it as the list atom nil. This is used
15904 for inheritance when a \"nil\" value can supersede a non-nil
15905 value higher up the hierarchy."
15906 (org-with-point-at pom
15907 (cond
15908 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15909 ;; We need a special property. Use `org-entry-properties' to
15910 ;; retrieve it, but specify the wanted property.
15911 (cdr (assoc-string property (org-entry-properties nil property))))
15912 ((and inherit
15913 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15914 (org-entry-get-with-inheritance property literal-nil))
15916 (let* ((local (org-property--local-values property literal-nil))
15917 (value (and local (mapconcat #'identity (delq nil local) " "))))
15918 (if literal-nil value (org-not-nil value)))))))
15920 (defun org-property-or-variable-value (var &optional inherit)
15921 "Check if there is a property fixing the value of VAR.
15922 If yes, return this value. If not, return the current value of the variable."
15923 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15924 (if (and prop (stringp prop) (string-match "\\S-" prop))
15925 (read prop)
15926 (symbol-value var))))
15928 (defun org-entry-delete (pom property)
15929 "Delete PROPERTY from entry at point-or-marker POM.
15930 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15931 non-nil when a property was removed."
15932 (unless (member property org-special-properties)
15933 (org-with-point-at pom
15934 (let ((range (org-get-property-block)))
15935 (when range
15936 (let* ((begin (car range))
15937 (origin (cdr range))
15938 (end (copy-marker origin))
15939 (re (org-re-property
15940 (concat (regexp-quote property) "\\+?") t t)))
15941 (goto-char begin)
15942 (while (re-search-forward re end t)
15943 (delete-region (match-beginning 0) (line-beginning-position 2)))
15944 ;; If drawer is empty, remove it altogether.
15945 (when (= begin end)
15946 (delete-region (line-beginning-position 0)
15947 (line-beginning-position 2)))
15948 ;; Return non-nil if some property was removed.
15949 (prog1 (/= end origin) (set-marker end nil))))))))
15951 ;; Multi-values properties are properties that contain multiple values
15952 ;; These values are assumed to be single words, separated by whitespace.
15953 (defun org-entry-add-to-multivalued-property (pom property value)
15954 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15955 (let* ((old (org-entry-get pom property))
15956 (values (and old (org-split-string old "[ \t]"))))
15957 (setq value (org-entry-protect-space value))
15958 (unless (member value values)
15959 (setq values (append values (list value)))
15960 (org-entry-put pom property
15961 (mapconcat 'identity values " ")))))
15963 (defun org-entry-remove-from-multivalued-property (pom property value)
15964 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15965 (let* ((old (org-entry-get pom property))
15966 (values (and old (org-split-string old "[ \t]"))))
15967 (setq value (org-entry-protect-space value))
15968 (when (member value values)
15969 (setq values (delete value values))
15970 (org-entry-put pom property
15971 (mapconcat 'identity values " ")))))
15973 (defun org-entry-member-in-multivalued-property (pom property value)
15974 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15975 (let* ((old (org-entry-get pom property))
15976 (values (and old (org-split-string old "[ \t]"))))
15977 (setq value (org-entry-protect-space value))
15978 (member value values)))
15980 (defun org-entry-get-multivalued-property (pom property)
15981 "Return a list of values in a multivalued property."
15982 (let* ((value (org-entry-get pom property))
15983 (values (and value (org-split-string value "[ \t]"))))
15984 (mapcar 'org-entry-restore-space values)))
15986 (defun org-entry-put-multivalued-property (pom property &rest values)
15987 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15988 VALUES should be a list of strings. Spaces will be protected."
15989 (org-entry-put pom property
15990 (mapconcat 'org-entry-protect-space values " "))
15991 (let* ((value (org-entry-get pom property))
15992 (values (and value (org-split-string value "[ \t]"))))
15993 (mapcar 'org-entry-restore-space values)))
15995 (defun org-entry-protect-space (s)
15996 "Protect spaces and newline in string S."
15997 (while (string-match " " s)
15998 (setq s (replace-match "%20" t t s)))
15999 (while (string-match "\n" s)
16000 (setq s (replace-match "%0A" t t s)))
16003 (defun org-entry-restore-space (s)
16004 "Restore spaces and newline in string S."
16005 (while (string-match "%20" s)
16006 (setq s (replace-match " " t t s)))
16007 (while (string-match "%0A" s)
16008 (setq s (replace-match "\n" t t s)))
16011 (defvar org-entry-property-inherited-from (make-marker)
16012 "Marker pointing to the entry from where a property was inherited.
16013 Each call to `org-entry-get-with-inheritance' will set this marker to the
16014 location of the entry where the inheritance search matched. If there was
16015 no match, the marker will point nowhere.
16016 Note that also `org-entry-get' calls this function, if the INHERIT flag
16017 is set.")
16019 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16020 "Get PROPERTY of entry or content at point, search higher levels if needed.
16021 The search will stop at the first ancestor which has the property defined.
16022 If the value found is \"nil\", return nil to show that the property
16023 should be considered as undefined (this is the meaning of nil here).
16024 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16025 (move-marker org-entry-property-inherited-from nil)
16026 (org-with-wide-buffer
16027 (let (value)
16028 (catch 'exit
16029 (while t
16030 (let ((v (org-property--local-values property literal-nil)))
16031 (when v
16032 (setq value
16033 (concat (mapconcat #'identity (delq nil v) " ")
16034 (and value " ")
16035 value)))
16036 (cond
16037 ((car v)
16038 (org-back-to-heading t)
16039 (move-marker org-entry-property-inherited-from (point))
16040 (throw 'exit nil))
16041 ((org-up-heading-safe))
16043 (let ((global
16044 (cdr (or (assoc-string property org-file-properties t)
16045 (assoc-string property org-global-properties t)
16046 (assoc-string property org-global-properties-fixed t)))))
16047 (cond ((not global))
16048 (value (setq value (concat global " " value)))
16049 (t (setq value global))))
16050 (throw 'exit nil))))))
16051 (if literal-nil value (org-not-nil value)))))
16053 (defvar org-property-changed-functions nil
16054 "Hook called when the value of a property has changed.
16055 Each hook function should accept two arguments, the name of the property
16056 and the new value.")
16058 (defun org-entry-put (pom property value)
16059 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16061 If the value is nil, it is converted to the empty string. If it
16062 is not a string, an error is raised. Also raise an error on
16063 invalid property names.
16065 PROPERTY can be any regular property (see
16066 `org-special-properties'). It can also be \"TODO\",
16067 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16069 For the last two properties, VALUE may have any of the special
16070 values \"earlier\" and \"later\". The function then increases or
16071 decreases scheduled or deadline date by one day."
16072 (cond ((null value) (setq value ""))
16073 ((not (stringp value)) (error "Properties values should be strings"))
16074 ((not (org--valid-property-p property))
16075 (user-error "Invalid property name: \"%s\"" property)))
16076 (org-with-point-at pom
16077 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16078 (org-back-to-heading t)
16079 (org-with-limited-levels (org-back-to-heading t)))
16080 (let ((beg (point)))
16081 (cond
16082 ((equal property "TODO")
16083 (cond ((not (org-string-nw-p value)) (setq value 'none))
16084 ((not (member value org-todo-keywords-1))
16085 (user-error "\"%s\" is not a valid TODO state" value)))
16086 (org-todo value)
16087 (org-set-tags nil 'align))
16088 ((equal property "PRIORITY")
16089 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16090 (org-set-tags nil 'align))
16091 ((equal property "SCHEDULED")
16092 (forward-line)
16093 (if (and (org-looking-at-p org-planning-line-re)
16094 (re-search-forward
16095 org-scheduled-time-regexp (line-end-position) t))
16096 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16097 ((string= value "later") (org-timestamp-change 1 'day))
16098 ((string= value "") (org-schedule '(4)))
16099 (t (org-schedule nil value)))
16100 (if (member value '("earlier" "later" ""))
16101 (call-interactively #'org-schedule)
16102 (org-schedule nil value))))
16103 ((equal property "DEADLINE")
16104 (forward-line)
16105 (if (and (org-looking-at-p org-planning-line-re)
16106 (re-search-forward
16107 org-deadline-time-regexp (line-end-position) t))
16108 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16109 ((string= value "later") (org-timestamp-change 1 'day))
16110 ((string= value "") (org-deadline '(4)))
16111 (t (org-deadline nil value)))
16112 (if (member value '("earlier" "later" ""))
16113 (call-interactively #'org-deadline)
16114 (org-deadline nil value))))
16115 ((member property org-special-properties)
16116 (error "The %s property cannot be set with `org-entry-put'" property))
16118 (let* ((range (org-get-property-block beg 'force))
16119 (end (cdr range))
16120 (case-fold-search t))
16121 (goto-char (car range))
16122 (if (re-search-forward (org-re-property property nil t) end t)
16123 (progn (delete-region (match-beginning 0) (match-end 0))
16124 (goto-char (match-beginning 0)))
16125 (goto-char end)
16126 (insert "\n")
16127 (backward-char))
16128 (insert ":" property ":")
16129 (when value (insert " " value))
16130 (org-indent-line)))))
16131 (run-hook-with-args 'org-property-changed-functions property value)))
16133 (defun org-buffer-property-keys
16134 (&optional specials defaults columns ignore-malformed)
16135 "Get all property keys in the current buffer.
16137 When SPECIALS is non-nil, also list the special properties that
16138 reflect things like tags and TODO state.
16140 When DEFAULTS is non-nil, also include properties that has
16141 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16142 DESCRIPTION, LOCATION, and LOGGING and others.
16144 When COLUMNS in non-nil, also include property names given in
16145 COLUMN formats in the current buffer.
16147 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16148 automatically performed, such drawers will be silently ignored."
16149 (let ((case-fold-search t)
16150 (props (append
16151 (and specials org-special-properties)
16152 (and defaults (cons org-effort-property org-default-properties))
16153 nil)))
16154 (org-with-wide-buffer
16155 (goto-char (point-min))
16156 (while (re-search-forward org-property-start-re nil t)
16157 (let ((range (org-get-property-block)))
16158 (catch 'skip
16159 (unless range
16160 (when (and (not ignore-malformed)
16161 (not (org-before-first-heading-p))
16162 (y-or-n-p (format "Malformed drawer at %d, repair?"
16163 (line-beginning-position))))
16164 (org-get-property-block nil t))
16165 (throw 'skip nil))
16166 (goto-char (car range))
16167 (let ((begin (car range))
16168 (end (cdr range)))
16169 ;; Make sure that found property block is not located
16170 ;; before current point, as it would generate an infloop.
16171 ;; It can happen, for example, in the following
16172 ;; situation:
16174 ;; * Headline
16175 ;; :PROPERTIES:
16176 ;; ...
16177 ;; :END:
16178 ;; *************** Inlinetask
16179 ;; #+BEGIN_EXAMPLE
16180 ;; :PROPERTIES:
16181 ;; #+END_EXAMPLE
16183 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16184 (while (< (point) end)
16185 (let ((p (progn (looking-at org-property-re)
16186 (org-match-string-no-properties 2))))
16187 ;; Only add true property name, not extension symbol.
16188 (add-to-list 'props
16189 (if (not (org-string-match-p "\\+\\'" p)) p
16190 (substring p 0 -1))))
16191 (forward-line))))
16192 (outline-next-heading)))
16193 (when columns
16194 (goto-char (point-min))
16195 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16196 (let ((element (org-element-at-point)))
16197 (when (memq (org-element-type element) '(keyword node-property))
16198 (let ((value (org-element-property :value element))
16199 (start 0))
16200 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16201 (setq start (match-end 0))
16202 (let ((p (org-match-string-no-properties 1 value)))
16203 (unless (member-ignore-case p org-special-properties)
16204 (add-to-list 'props p))))))))))
16205 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16207 (defun org-property-values (key)
16208 "List all non-nil values of property KEY in current buffer."
16209 (org-with-wide-buffer
16210 (goto-char (point-min))
16211 (let ((case-fold-search t)
16212 (re (org-re-property key))
16213 values)
16214 (while (re-search-forward re nil t)
16215 (add-to-list 'values (org-entry-get (point) key)))
16216 values)))
16218 (defun org-insert-property-drawer ()
16219 "Insert a property drawer into the current entry."
16220 (org-with-wide-buffer
16221 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16222 (org-back-to-heading t)
16223 (org-with-limited-levels (org-back-to-heading t)))
16224 (forward-line)
16225 (when (org-looking-at-p org-planning-line-re) (forward-line))
16226 (unless (org-looking-at-p org-property-drawer-re)
16227 ;; Make sure we start editing a line from current entry, not from
16228 ;; next one. It prevents extending text properties or overlays
16229 ;; belonging to the latter.
16230 (when (bolp) (backward-char))
16231 (let ((begin (1+ (point)))
16232 (inhibit-read-only t))
16233 (insert "\n:PROPERTIES:\n:END:")
16234 (when (eobp) (insert "\n"))
16235 (org-indent-region begin (point))))))
16237 (defun org-insert-drawer (&optional arg drawer)
16238 "Insert a drawer at point.
16240 When optional argument ARG is non-nil, insert a property drawer.
16242 Optional argument DRAWER, when non-nil, is a string representing
16243 drawer's name. Otherwise, the user is prompted for a name.
16245 If a region is active, insert the drawer around that region
16246 instead.
16248 Point is left between drawer's boundaries."
16249 (interactive "P")
16250 (let* ((drawer (if arg "PROPERTIES"
16251 (or drawer (read-from-minibuffer "Drawer: ")))))
16252 (cond
16253 ;; With C-u, fall back on `org-insert-property-drawer'
16254 (arg (org-insert-property-drawer))
16255 ;; Check validity of suggested drawer's name.
16256 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16257 (user-error "Invalid drawer name"))
16258 ;; With an active region, insert a drawer at point.
16259 ((not (org-region-active-p))
16260 (progn
16261 (unless (bolp) (insert "\n"))
16262 (insert (format ":%s:\n\n:END:\n" drawer))
16263 (forward-line -2)))
16264 ;; Otherwise, insert the drawer at point
16266 (let ((rbeg (region-beginning))
16267 (rend (copy-marker (region-end))))
16268 (unwind-protect
16269 (progn
16270 (goto-char rbeg)
16271 (beginning-of-line)
16272 (when (save-excursion
16273 (re-search-forward org-outline-regexp-bol rend t))
16274 (user-error "Drawers cannot contain headlines"))
16275 ;; Position point at the beginning of the first
16276 ;; non-blank line in region. Insert drawer's opening
16277 ;; there, then indent it.
16278 (org-skip-whitespace)
16279 (beginning-of-line)
16280 (insert ":" drawer ":\n")
16281 (forward-line -1)
16282 (indent-for-tab-command)
16283 ;; Move point to the beginning of the first blank line
16284 ;; after the last non-blank line in region. Insert
16285 ;; drawer's closing, then indent it.
16286 (goto-char rend)
16287 (skip-chars-backward " \r\t\n")
16288 (insert "\n:END:")
16289 (deactivate-mark t)
16290 (indent-for-tab-command)
16291 (unless (eolp) (insert "\n")))
16292 ;; Clear marker, whatever the outcome of insertion is.
16293 (set-marker rend nil)))))))
16295 (defvar org-property-set-functions-alist nil
16296 "Property set function alist.
16297 Each entry should have the following format:
16299 (PROPERTY . READ-FUNCTION)
16301 The read function will be called with the same argument as
16302 `org-completing-read'.")
16304 (defun org-set-property-function (property)
16305 "Get the function that should be used to set PROPERTY.
16306 This is computed according to `org-property-set-functions-alist'."
16307 (or (cdr (assoc property org-property-set-functions-alist))
16308 'org-completing-read))
16310 (defun org-read-property-value (property)
16311 "Read PROPERTY value from user."
16312 (let* ((completion-ignore-case t)
16313 (allowed (org-property-get-allowed-values nil property 'table))
16314 (cur (org-entry-get nil property))
16315 (prompt (concat property " value"
16316 (if (and cur (string-match "\\S-" cur))
16317 (concat " [" cur "]") "") ": "))
16318 (set-function (org-set-property-function property))
16319 (val (if allowed
16320 (funcall set-function prompt allowed nil
16321 (not (get-text-property 0 'org-unrestricted
16322 (caar allowed))))
16323 (let (org-completion-use-ido org-completion-use-iswitchb)
16324 (funcall set-function prompt
16325 (mapcar 'list (org-property-values property))
16326 nil nil "" nil cur)))))
16327 (org-trim val)))
16329 (defvar org-last-set-property nil)
16330 (defvar org-last-set-property-value nil)
16331 (defun org-read-property-name ()
16332 "Read a property name."
16333 (let ((completion-ignore-case t)
16334 (default-prop (or (and (org-at-property-p)
16335 (org-match-string-no-properties 2))
16336 org-last-set-property)))
16337 (org-completing-read
16338 (concat "Property"
16339 (if default-prop (concat " [" default-prop "]") "")
16340 ": ")
16341 (mapcar #'list (org-buffer-property-keys nil t t))
16342 nil nil nil nil default-prop)))
16344 (defun org-set-property-and-value (use-last)
16345 "Allow to set [PROPERTY]: [value] direction from prompt.
16346 When use-default, don't even ask, just use the last
16347 \"[PROPERTY]: [value]\" string from the history."
16348 (interactive "P")
16349 (let* ((completion-ignore-case t)
16350 (pv (or (and use-last org-last-set-property-value)
16351 (org-completing-read
16352 "Enter a \"[Property]: [value]\" pair: "
16353 nil nil nil nil nil
16354 org-last-set-property-value)))
16355 prop val)
16356 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16357 (setq prop (match-string 1 pv)
16358 val (match-string 2 pv))
16359 (org-set-property prop val))))
16361 (defun org-set-property (property value)
16362 "In the current entry, set PROPERTY to VALUE.
16364 When called interactively, this will prompt for a property name, offering
16365 completion on existing and default properties. And then it will prompt
16366 for a value, offering completion either on allowed values (via an inherited
16367 xxx_ALL property) or on existing values in other instances of this property
16368 in the current file.
16370 Throw an error when trying to set a property with an invalid name."
16371 (interactive (list nil nil))
16372 (let ((property (or property (org-read-property-name))))
16373 ;; `org-entry-put' also makes the following check, but this one
16374 ;; avoids polluting `org-last-set-property' and
16375 ;; `org-last-set-property-value' needlessly.
16376 (unless (org--valid-property-p property)
16377 (user-error "Invalid property name: \"%s\"" property))
16378 (let ((value (or value (org-read-property-value property)))
16379 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16380 (setq org-last-set-property property)
16381 (setq org-last-set-property-value (concat property ": " value))
16382 ;; Possibly postprocess the inserted value:
16383 (when fn (setq value (funcall fn value)))
16384 (unless (equal (org-entry-get nil property) value)
16385 (org-entry-put nil property value)))))
16387 (defun org-find-property (property &optional value)
16388 "Find first entry in buffer that sets PROPERTY.
16390 When optional argument VALUE is non-nil, only consider an entry
16391 if it contains PROPERTY set to this value. If PROPERTY should be
16392 explicitly set to nil, use string \"nil\" for VALUE.
16394 Return position where the entry begins, or nil if there is no
16395 such entry. If narrowing is in effect, only search the visible
16396 part of the buffer."
16397 (save-excursion
16398 (goto-char (point-min))
16399 (let ((case-fold-search t)
16400 (re (org-re-property property nil (not value) value)))
16401 (catch 'exit
16402 (while (re-search-forward re nil t)
16403 (when (if value (org-at-property-p)
16404 (org-entry-get (point) property nil t))
16405 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16407 (defun org-delete-property (property)
16408 "In the current entry, delete PROPERTY."
16409 (interactive
16410 (let* ((completion-ignore-case t)
16411 (cat (org-entry-get (point) "CATEGORY"))
16412 (props0 (org-entry-properties nil 'standard))
16413 (props (if cat props0
16414 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16415 (prop (if (< 1 (length props))
16416 (org-icompleting-read "Property: " props nil t)
16417 (caar props))))
16418 (list prop)))
16419 (if (not property)
16420 (message "No property to delete in this entry")
16421 (org-entry-delete nil property)
16422 (message "Property \"%s\" deleted" property)))
16424 (defun org-delete-property-globally (property)
16425 "Remove PROPERTY globally, from all entries.
16426 This function ignores narrowing, if any."
16427 (interactive
16428 (let* ((completion-ignore-case t)
16429 (prop (org-icompleting-read
16430 "Globally remove property: "
16431 (mapcar #'list (org-buffer-property-keys)))))
16432 (list prop)))
16433 (org-with-wide-buffer
16434 (goto-char (point-min))
16435 (let ((count 0)
16436 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16437 (while (re-search-forward re nil t)
16438 (when (org-entry-delete (point) property) (incf count)))
16439 (message "Property \"%s\" removed from %d entries" property count))))
16441 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16443 (defun org-compute-property-at-point ()
16444 "Compute the property at point.
16445 This looks for an enclosing column format, extracts the operator and
16446 then applies it to the property in the column format's scope."
16447 (interactive)
16448 (unless (org-at-property-p)
16449 (user-error "Not at a property"))
16450 (let ((prop (org-match-string-no-properties 2)))
16451 (org-columns-get-format-and-top-level)
16452 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16453 (user-error "No operator defined for property %s" prop))
16454 (org-columns-compute prop)))
16456 (defvar org-property-allowed-value-functions nil
16457 "Hook for functions supplying allowed values for a specific property.
16458 The functions must take a single argument, the name of the property, and
16459 return a flat list of allowed values. If \":ETC\" is one of
16460 the values, this means that these values are intended as defaults for
16461 completion, but that other values should be allowed too.
16462 The functions must return nil if they are not responsible for this
16463 property.")
16465 (defun org-property-get-allowed-values (pom property &optional table)
16466 "Get allowed values for the property PROPERTY.
16467 When TABLE is non-nil, return an alist that can directly be used for
16468 completion."
16469 (let (vals)
16470 (cond
16471 ((equal property "TODO")
16472 (setq vals (org-with-point-at pom
16473 (append org-todo-keywords-1 '("")))))
16474 ((equal property "PRIORITY")
16475 (let ((n org-lowest-priority))
16476 (while (>= n org-highest-priority)
16477 (push (char-to-string n) vals)
16478 (setq n (1- n)))))
16479 ((equal property "CATEGORY"))
16480 ((member property org-special-properties))
16481 ((setq vals (run-hook-with-args-until-success
16482 'org-property-allowed-value-functions property)))
16484 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16485 (when (and vals (string-match "\\S-" vals))
16486 (setq vals (car (read-from-string (concat "(" vals ")"))))
16487 (setq vals (mapcar (lambda (x)
16488 (cond ((stringp x) x)
16489 ((numberp x) (number-to-string x))
16490 ((symbolp x) (symbol-name x))
16491 (t "???")))
16492 vals)))))
16493 (when (member ":ETC" vals)
16494 (setq vals (remove ":ETC" vals))
16495 (org-add-props (car vals) '(org-unrestricted t)))
16496 (if table (mapcar 'list vals) vals)))
16498 (defun org-property-previous-allowed-value (&optional previous)
16499 "Switch to the next allowed value for this property."
16500 (interactive)
16501 (org-property-next-allowed-value t))
16503 (defun org-property-next-allowed-value (&optional previous)
16504 "Switch to the next allowed value for this property."
16505 (interactive)
16506 (unless (org-at-property-p)
16507 (user-error "Not at a property"))
16508 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16509 (key (match-string 2))
16510 (value (match-string 3))
16511 (allowed (or (org-property-get-allowed-values (point) key)
16512 (and (member value '("[ ]" "[-]" "[X]"))
16513 '("[ ]" "[X]"))))
16514 (heading (save-match-data (nth 4 (org-heading-components))))
16515 nval)
16516 (unless allowed
16517 (user-error "Allowed values for this property have not been defined"))
16518 (when previous (setq allowed (reverse allowed)))
16519 (when (member value allowed)
16520 (setq nval (car (cdr (member value allowed)))))
16521 (setq nval (or nval (car allowed)))
16522 (when (equal nval value)
16523 (user-error "Only one allowed value for this property"))
16524 (org-at-property-p)
16525 (replace-match (concat " :" key ": " nval) t t)
16526 (org-indent-line)
16527 (beginning-of-line 1)
16528 (skip-chars-forward " \t")
16529 (when (equal prop org-effort-property)
16530 (org-refresh-property
16531 '((effort . identity)
16532 (effort-minutes . org-duration-string-to-minutes))
16533 nval)
16534 (when (string= org-clock-current-task heading)
16535 (setq org-clock-effort nval)
16536 (org-clock-update-mode-line)))
16537 (run-hook-with-args 'org-property-changed-functions key nval)))
16539 (defun org-find-olp (path &optional this-buffer)
16540 "Return a marker pointing to the entry at outline path OLP.
16541 If anything goes wrong, throw an error.
16542 You can wrap this call to catch the error like this:
16544 (condition-case msg
16545 (org-mobile-locate-entry (match-string 4))
16546 (error (nth 1 msg)))
16548 The return value will then be either a string with the error message,
16549 or a marker if everything is OK.
16551 If THIS-BUFFER is set, the outline path does not contain a file,
16552 only headings."
16553 (let* ((file (if this-buffer buffer-file-name (pop path)))
16554 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16555 (level 1)
16556 (lmin 1)
16557 (lmax 1)
16558 limit re end found pos heading cnt flevel)
16559 (unless buffer (error "File not found :%s" file))
16560 (with-current-buffer buffer
16561 (save-excursion
16562 (save-restriction
16563 (widen)
16564 (setq limit (point-max))
16565 (goto-char (point-min))
16566 (dolist (heading path)
16567 (setq re (format org-complex-heading-regexp-format
16568 (regexp-quote heading)))
16569 (setq cnt 0 pos (point))
16570 (while (re-search-forward re end t)
16571 (setq level (- (match-end 1) (match-beginning 1)))
16572 (when (and (>= level lmin) (<= level lmax))
16573 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16574 (when (= cnt 0) (error "Heading not found on level %d: %s"
16575 lmax heading))
16576 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16577 lmax heading))
16578 (goto-char found)
16579 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16580 (setq end (save-excursion (org-end-of-subtree t t))))
16581 (when (org-at-heading-p)
16582 (point-marker)))))))
16584 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16585 "Find node HEADING in BUFFER.
16586 Return a marker to the heading if it was found, or nil if not.
16587 If POS-ONLY is set, return just the position instead of a marker.
16589 The heading text must match exact, but it may have a TODO keyword,
16590 a priority cookie and tags in the standard locations."
16591 (with-current-buffer (or buffer (current-buffer))
16592 (save-excursion
16593 (save-restriction
16594 (widen)
16595 (goto-char (point-min))
16596 (let (case-fold-search)
16597 (when (re-search-forward
16598 (format org-complex-heading-regexp-format
16599 (regexp-quote heading)) nil t)
16600 (if pos-only
16601 (match-beginning 0)
16602 (move-marker (make-marker) (match-beginning 0)))))))))
16604 (defun org-find-exact-heading-in-directory (heading &optional dir)
16605 "Find Org node headline HEADING in all .org files in directory DIR.
16606 When the target headline is found, return a marker to this location."
16607 (let ((files (directory-files (or dir default-directory)
16608 t "\\`[^.#].*\\.org\\'"))
16609 visiting m buffer)
16610 (catch 'found
16611 (dolist (file files)
16612 (message "trying %s" file)
16613 (setq visiting (org-find-base-buffer-visiting file))
16614 (setq buffer (or visiting (find-file-noselect file)))
16615 (setq m (org-find-exact-headline-in-buffer
16616 heading buffer))
16617 (when (and (not m) (not visiting)) (kill-buffer buffer))
16618 (and m (throw 'found m))))))
16620 (defun org-find-entry-with-id (ident)
16621 "Locate the entry that contains the ID property with exact value IDENT.
16622 IDENT can be a string, a symbol or a number, this function will search for
16623 the string representation of it.
16624 Return the position where this entry starts, or nil if there is no such entry."
16625 (interactive "sID: ")
16626 (let ((id (cond
16627 ((stringp ident) ident)
16628 ((symbolp ident) (symbol-name ident))
16629 ((numberp ident) (number-to-string ident))
16630 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16631 (org-with-wide-buffer (org-find-property "ID" id))))
16633 ;;;; Timestamps
16635 (defvar org-last-changed-timestamp nil)
16636 (defvar org-last-inserted-timestamp nil
16637 "The last time stamp inserted with `org-insert-time-stamp'.")
16638 (defvar org-ts-what) ; dynamically scoped parameter
16640 (defun org-time-stamp (arg &optional inactive)
16641 "Prompt for a date/time and insert a time stamp.
16643 If the user specifies a time like HH:MM or if this command is
16644 called with at least one prefix argument, the time stamp contains
16645 the date and the time. Otherwise, only the date is included.
16647 All parts of a date not specified by the user are filled in from
16648 the timestamp at point, if any, or the current date/time
16649 otherwise.
16651 If there is already a timestamp at the cursor, it is replaced.
16653 With two universal prefix arguments, insert an active timestamp
16654 with the current time without prompting the user.
16656 When called from lisp, the timestamp is inactive if INACTIVE is
16657 non-nil."
16658 (interactive "P")
16659 (let* ((ts (cond
16660 ((org-at-date-range-p t)
16661 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16662 ((org-at-timestamp-p t) (match-string 0))))
16663 ;; Default time is either the timestamp at point or today.
16664 ;; When entering a range, only the range start is considered.
16665 (default-time (if (not ts) (current-time)
16666 (apply #'encode-time (org-parse-time-string ts))))
16667 (default-input (and ts (org-get-compact-tod ts)))
16668 (repeater (and ts
16669 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16670 (match-string 0 ts)))
16671 org-time-was-given
16672 org-end-time-was-given
16673 (time
16674 (and (if (equal arg '(16)) (current-time)
16675 ;; Preserve `this-command' and `last-command'.
16676 (let ((this-command this-command)
16677 (last-command last-command))
16678 (org-read-date
16679 arg 'totime nil nil default-time default-input
16680 inactive))))))
16681 (cond
16682 ((and ts
16683 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16684 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16685 (insert "--")
16686 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16688 ;; Make sure we're on a timestamp. When in the middle of a date
16689 ;; range, move arbitrarily to range end.
16690 (unless (org-at-timestamp-p t)
16691 (skip-chars-forward "-")
16692 (org-at-timestamp-p t))
16693 (replace-match "")
16694 (setq org-last-changed-timestamp
16695 (org-insert-time-stamp
16696 time (or org-time-was-given arg)
16697 inactive nil nil (list org-end-time-was-given)))
16698 (when repeater
16699 (backward-char)
16700 (insert " " repeater)
16701 (setq org-last-changed-timestamp
16702 (concat (substring org-last-inserted-timestamp 0 -1)
16703 " " repeater ">")))
16704 (message "Timestamp updated"))
16705 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16706 (t (org-insert-time-stamp
16707 time (or org-time-was-given arg) inactive nil nil
16708 (list org-end-time-was-given))))))
16710 ;; FIXME: can we use this for something else, like computing time differences?
16711 (defun org-get-compact-tod (s)
16712 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16713 (let* ((t1 (match-string 1 s))
16714 (h1 (string-to-number (match-string 2 s)))
16715 (m1 (string-to-number (match-string 3 s)))
16716 (t2 (and (match-end 4) (match-string 5 s)))
16717 (h2 (and t2 (string-to-number (match-string 6 s))))
16718 (m2 (and t2 (string-to-number (match-string 7 s))))
16719 dh dm)
16720 (if (not t2)
16722 (setq dh (- h2 h1) dm (- m2 m1))
16723 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16724 (concat t1 "+" (number-to-string dh)
16725 (and (/= 0 dm) (format ":%02d" dm)))))))
16727 (defun org-time-stamp-inactive (&optional arg)
16728 "Insert an inactive time stamp.
16729 An inactive time stamp is enclosed in square brackets instead of angle
16730 brackets. It is inactive in the sense that it does not trigger agenda entries,
16731 does not link to the calendar and cannot be changed with the S-cursor keys.
16732 So these are more for recording a certain time/date."
16733 (interactive "P")
16734 (org-time-stamp arg 'inactive))
16736 (defvar org-date-ovl (make-overlay 1 1))
16737 (overlay-put org-date-ovl 'face 'org-date-selected)
16738 (org-detach-overlay org-date-ovl)
16740 (defvar org-ans1) ; dynamically scoped parameter
16741 (defvar org-ans2) ; dynamically scoped parameter
16743 (defvar org-plain-time-of-day-regexp) ; defined below
16745 (defvar org-overriding-default-time nil) ; dynamically scoped
16746 (defvar org-read-date-overlay nil)
16747 (defvar org-dcst nil) ; dynamically scoped
16748 (defvar org-read-date-history nil)
16749 (defvar org-read-date-final-answer nil)
16750 (defvar org-read-date-analyze-futurep nil)
16751 (defvar org-read-date-analyze-forced-year nil)
16752 (defvar org-read-date-inactive)
16754 (defvar org-read-date-minibuffer-local-map
16755 (let* ((map (make-sparse-keymap)))
16756 (set-keymap-parent map minibuffer-local-map)
16757 (org-defkey map (kbd ".")
16758 (lambda () (interactive)
16759 ;; Are we at the beginning of the prompt?
16760 (if (org-looking-back "^[^:]+: "
16761 (let ((inhibit-field-text-motion t))
16762 (line-beginning-position)))
16763 (org-eval-in-calendar '(calendar-goto-today))
16764 (insert "."))))
16765 (org-defkey map (kbd "C-.")
16766 (lambda () (interactive)
16767 (org-eval-in-calendar '(calendar-goto-today))))
16768 (org-defkey map [(meta shift left)]
16769 (lambda () (interactive)
16770 (org-eval-in-calendar '(calendar-backward-month 1))))
16771 (org-defkey map [(meta shift right)]
16772 (lambda () (interactive)
16773 (org-eval-in-calendar '(calendar-forward-month 1))))
16774 (org-defkey map [(meta shift up)]
16775 (lambda () (interactive)
16776 (org-eval-in-calendar '(calendar-backward-year 1))))
16777 (org-defkey map [(meta shift down)]
16778 (lambda () (interactive)
16779 (org-eval-in-calendar '(calendar-forward-year 1))))
16780 (org-defkey map [?\e (shift left)]
16781 (lambda () (interactive)
16782 (org-eval-in-calendar '(calendar-backward-month 1))))
16783 (org-defkey map [?\e (shift right)]
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-forward-month 1))))
16786 (org-defkey map [?\e (shift up)]
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-backward-year 1))))
16789 (org-defkey map [?\e (shift down)]
16790 (lambda () (interactive)
16791 (org-eval-in-calendar '(calendar-forward-year 1))))
16792 (org-defkey map [(shift up)]
16793 (lambda () (interactive)
16794 (org-eval-in-calendar '(calendar-backward-week 1))))
16795 (org-defkey map [(shift down)]
16796 (lambda () (interactive)
16797 (org-eval-in-calendar '(calendar-forward-week 1))))
16798 (org-defkey map [(shift left)]
16799 (lambda () (interactive)
16800 (org-eval-in-calendar '(calendar-backward-day 1))))
16801 (org-defkey map [(shift right)]
16802 (lambda () (interactive)
16803 (org-eval-in-calendar '(calendar-forward-day 1))))
16804 (org-defkey map "!"
16805 (lambda () (interactive)
16806 (org-eval-in-calendar '(diary-view-entries))
16807 (message "")))
16808 (org-defkey map ">"
16809 (lambda () (interactive)
16810 (org-eval-in-calendar '(calendar-scroll-left 1))))
16811 (org-defkey map "<"
16812 (lambda () (interactive)
16813 (org-eval-in-calendar '(calendar-scroll-right 1))))
16814 (org-defkey map "\C-v"
16815 (lambda () (interactive)
16816 (org-eval-in-calendar
16817 '(calendar-scroll-left-three-months 1))))
16818 (org-defkey map "\M-v"
16819 (lambda () (interactive)
16820 (org-eval-in-calendar
16821 '(calendar-scroll-right-three-months 1))))
16822 map)
16823 "Keymap for minibuffer commands when using `org-read-date'.")
16825 (defvar org-def)
16826 (defvar org-defdecode)
16827 (defvar org-with-time)
16829 (defun org-read-date (&optional org-with-time to-time from-string prompt
16830 default-time default-input inactive)
16831 "Read a date, possibly a time, and make things smooth for the user.
16832 The prompt will suggest to enter an ISO date, but you can also enter anything
16833 which will at least partially be understood by `parse-time-string'.
16834 Unrecognized parts of the date will default to the current day, month, year,
16835 hour and minute. If this command is called to replace a timestamp at point,
16836 or to enter the second timestamp of a range, the default time is taken
16837 from the existing stamp. Furthermore, the command prefers the future,
16838 so if you are giving a date where the year is not given, and the day-month
16839 combination is already past in the current year, it will assume you
16840 mean next year. For details, see the manual. A few examples:
16842 3-2-5 --> 2003-02-05
16843 feb 15 --> currentyear-02-15
16844 2/15 --> currentyear-02-15
16845 sep 12 9 --> 2009-09-12
16846 12:45 --> today 12:45
16847 22 sept 0:34 --> currentyear-09-22 0:34
16848 12 --> currentyear-currentmonth-12
16849 Fri --> nearest Friday after today
16850 -Tue --> last Tuesday
16851 etc.
16853 Furthermore you can specify a relative date by giving, as the *first* thing
16854 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16855 change in days weeks, months, years.
16856 With a single plus or minus, the date is relative to today. With a double
16857 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16858 +4d --> four days from today
16859 +4 --> same as above
16860 +2w --> two weeks from today
16861 ++5 --> five days from default date
16863 The function understands only English month and weekday abbreviations.
16865 While prompting, a calendar is popped up - you can also select the
16866 date with the mouse (button 1). The calendar shows a period of three
16867 months. To scroll it to other months, use the keys `>' and `<'.
16868 If you don't like the calendar, turn it off with
16869 (setq org-read-date-popup-calendar nil)
16871 With optional argument TO-TIME, the date will immediately be converted
16872 to an internal time.
16873 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16874 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16875 still enter a time, and this function will inform the calling routine
16876 about this change. The calling routine may then choose to change the
16877 format used to insert the time stamp into the buffer to include the time.
16878 With optional argument FROM-STRING, read from this string instead from
16879 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16880 the time/date that is used for everything that is not specified by the
16881 user."
16882 (require 'parse-time)
16883 (let* ((org-time-stamp-rounding-minutes
16884 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16885 (org-dcst org-display-custom-times)
16886 (ct (org-current-time))
16887 (org-def (or org-overriding-default-time default-time ct))
16888 (org-defdecode (decode-time org-def))
16889 (dummy (progn
16890 (when (< (nth 2 org-defdecode) org-extend-today-until)
16891 (setcar (nthcdr 2 org-defdecode) -1)
16892 (setcar (nthcdr 1 org-defdecode) 59)
16893 (setq org-def (apply 'encode-time org-defdecode)
16894 org-defdecode (decode-time org-def)))))
16895 (cur-frame (selected-frame))
16896 (mouse-autoselect-window nil) ; Don't let the mouse jump
16897 (calendar-frame-setup nil)
16898 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16899 (calendar-move-hook nil)
16900 (calendar-view-diary-initially-flag nil)
16901 (calendar-view-holidays-initially-flag nil)
16902 (timestr (format-time-string
16903 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16904 (prompt (concat (if prompt (concat prompt " ") "")
16905 (format "Date+time [%s]: " timestr)))
16906 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16908 (cond
16909 (from-string (setq ans from-string))
16910 (org-read-date-popup-calendar
16911 (save-excursion
16912 (save-window-excursion
16913 (calendar)
16914 (when (eq calendar-setup 'calendar-only)
16915 (setq cal-frame
16916 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16917 (select-frame cal-frame))
16918 (org-eval-in-calendar '(setq cursor-type nil) t)
16919 (unwind-protect
16920 (progn
16921 (calendar-forward-day (- (time-to-days org-def)
16922 (calendar-absolute-from-gregorian
16923 (calendar-current-date))))
16924 (org-eval-in-calendar nil t)
16925 (let* ((old-map (current-local-map))
16926 (map (copy-keymap calendar-mode-map))
16927 (minibuffer-local-map
16928 (copy-keymap org-read-date-minibuffer-local-map)))
16929 (org-defkey map (kbd "RET") 'org-calendar-select)
16930 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16931 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16932 (unwind-protect
16933 (progn
16934 (use-local-map map)
16935 (setq org-read-date-inactive inactive)
16936 (add-hook 'post-command-hook 'org-read-date-display)
16937 (setq org-ans0 (read-string prompt default-input
16938 'org-read-date-history nil))
16939 ;; org-ans0: from prompt
16940 ;; org-ans1: from mouse click
16941 ;; org-ans2: from calendar motion
16942 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16943 (remove-hook 'post-command-hook 'org-read-date-display)
16944 (use-local-map old-map)
16945 (when org-read-date-overlay
16946 (delete-overlay org-read-date-overlay)
16947 (setq org-read-date-overlay nil)))))
16948 (bury-buffer "*Calendar*")
16949 (when cal-frame
16950 (delete-frame cal-frame)
16951 (select-frame-set-input-focus cur-frame))))))
16953 (t ; Naked prompt only
16954 (unwind-protect
16955 (setq ans (read-string prompt default-input
16956 'org-read-date-history timestr))
16957 (when org-read-date-overlay
16958 (delete-overlay org-read-date-overlay)
16959 (setq org-read-date-overlay nil)))))
16961 (setq final (org-read-date-analyze ans org-def org-defdecode))
16963 (when org-read-date-analyze-forced-year
16964 (message "Year was forced into %s"
16965 (if org-read-date-force-compatible-dates
16966 "compatible range (1970-2037)"
16967 "range representable on this machine"))
16968 (ding))
16970 ;; One round trip to get rid of 34th of August and stuff like that....
16971 (setq final (decode-time (apply 'encode-time final)))
16973 (setq org-read-date-final-answer ans)
16975 (if to-time
16976 (apply 'encode-time final)
16977 (if (and (boundp 'org-time-was-given) org-time-was-given)
16978 (format "%04d-%02d-%02d %02d:%02d"
16979 (nth 5 final) (nth 4 final) (nth 3 final)
16980 (nth 2 final) (nth 1 final))
16981 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16983 (defun org-read-date-display ()
16984 "Display the current date prompt interpretation in the minibuffer."
16985 (when org-read-date-display-live
16986 (when org-read-date-overlay
16987 (delete-overlay org-read-date-overlay))
16988 (when (minibufferp (current-buffer))
16989 (save-excursion
16990 (end-of-line 1)
16991 (while (not (equal (buffer-substring
16992 (max (point-min) (- (point) 4)) (point))
16993 " "))
16994 (insert " ")))
16995 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16996 " " (or org-ans1 org-ans2)))
16997 (org-end-time-was-given nil)
16998 (f (org-read-date-analyze ans org-def org-defdecode))
16999 (fmts (if org-dcst
17000 org-time-stamp-custom-formats
17001 org-time-stamp-formats))
17002 (fmt (if (or org-with-time
17003 (and (boundp 'org-time-was-given) org-time-was-given))
17004 (cdr fmts)
17005 (car fmts)))
17006 (txt (format-time-string fmt (apply 'encode-time f)))
17007 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17008 (txt (concat "=> " txt)))
17009 (when (and org-end-time-was-given
17010 (string-match org-plain-time-of-day-regexp txt))
17011 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17012 org-end-time-was-given
17013 (substring txt (match-end 0)))))
17014 (when org-read-date-analyze-futurep
17015 (setq txt (concat txt " (=>F)")))
17016 (setq org-read-date-overlay
17017 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17018 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17020 (defun org-read-date-analyze (ans org-def org-defdecode)
17021 "Analyze the combined answer of the date prompt."
17022 ;; FIXME: cleanup and comment
17023 ;; Pass `current-time' result to `decode-time' (instead of calling
17024 ;; without arguments) so that only `current-time' has to be
17025 ;; overriden in tests.
17026 (let ((nowdecode (decode-time (current-time)))
17027 delta deltan deltaw deltadef year month day
17028 hour minute second wday pm h2 m2 tl wday1
17029 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
17030 (setq org-read-date-analyze-futurep nil
17031 org-read-date-analyze-forced-year nil)
17032 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17033 (setq ans "+0"))
17035 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17036 (setq ans (replace-match "" t t ans)
17037 deltan (car delta)
17038 deltaw (nth 1 delta)
17039 deltadef (nth 2 delta)))
17041 ;; Check if there is an iso week date in there. If yes, store the
17042 ;; info and postpone interpreting it until the rest of the parsing
17043 ;; is done.
17044 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17045 (setq iso-year (when (match-end 1)
17046 (org-small-year-to-year
17047 (string-to-number (match-string 1 ans))))
17048 iso-weekday (when (match-end 3)
17049 (string-to-number (match-string 3 ans)))
17050 iso-week (string-to-number (match-string 2 ans)))
17051 (setq ans (replace-match "" t t ans)))
17053 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17054 (when (string-match
17055 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17056 (setq year (if (match-end 2)
17057 (string-to-number (match-string 2 ans))
17058 (progn (setq kill-year t)
17059 (string-to-number (format-time-string "%Y"))))
17060 month (string-to-number (match-string 3 ans))
17061 day (string-to-number (match-string 4 ans)))
17062 (when (< year 100) (setq year (+ 2000 year)))
17063 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17064 t nil ans)))
17066 ;; Help matching dotted european dates
17067 (when (string-match
17068 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17069 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17070 (setq kill-year t)
17071 (string-to-number (format-time-string "%Y")))
17072 day (string-to-number (match-string 1 ans))
17073 month (string-to-number (match-string 2 ans))
17074 ans (replace-match (format "%04d-%02d-%02d" year month day)
17075 t nil ans)))
17077 ;; Help matching american dates, like 5/30 or 5/30/7
17078 (when (string-match
17079 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17080 (setq year (if (match-end 4)
17081 (string-to-number (match-string 4 ans))
17082 (progn (setq kill-year t)
17083 (string-to-number (format-time-string "%Y"))))
17084 month (string-to-number (match-string 1 ans))
17085 day (string-to-number (match-string 2 ans)))
17086 (when (< year 100) (setq year (+ 2000 year)))
17087 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17088 t nil ans)))
17089 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17090 ;; If there is a time with am/pm, and *no* time without it, we convert
17091 ;; so that matching will be successful.
17092 (loop for i from 1 to 2 do ; twice, for end time as well
17093 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17094 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17095 (setq hour (string-to-number (match-string 1 ans))
17096 minute (if (match-end 3)
17097 (string-to-number (match-string 3 ans))
17099 pm (equal ?p
17100 (string-to-char (downcase (match-string 4 ans)))))
17101 (if (and (= hour 12) (not pm))
17102 (setq hour 0)
17103 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17104 (setq ans (replace-match (format "%02d:%02d" hour minute)
17105 t t ans))))
17107 ;; Check if a time range is given as a duration
17108 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17109 (setq hour (string-to-number (match-string 1 ans))
17110 h2 (+ hour (string-to-number (match-string 3 ans)))
17111 minute (string-to-number (match-string 2 ans))
17112 m2 (+ minute (if (match-end 5) (string-to-number
17113 (match-string 5 ans))0)))
17114 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17115 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17116 t t ans)))
17118 ;; Check if there is a time range
17119 (when (boundp 'org-end-time-was-given)
17120 (setq org-time-was-given nil)
17121 (when (and (string-match org-plain-time-of-day-regexp ans)
17122 (match-end 8))
17123 (setq org-end-time-was-given (match-string 8 ans))
17124 (setq ans (concat (substring ans 0 (match-beginning 7))
17125 (substring ans (match-end 7))))))
17127 (setq tl (parse-time-string ans)
17128 day (or (nth 3 tl) (nth 3 org-defdecode))
17129 month
17130 (cond ((nth 4 tl))
17131 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17132 ;; Day was specified. Make sure DAY+MONTH
17133 ;; combination happens in the future.
17134 ((nth 3 tl)
17135 (setq futurep t)
17136 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17137 (nth 4 nowdecode)))
17138 (t (nth 4 org-defdecode)))
17139 year
17140 (cond ((and (not kill-year) (nth 5 tl)))
17141 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17142 ;; Month was guessed in the future and is at least
17143 ;; equal to NOWDECODE's. Fix year accordingly.
17144 (futurep
17145 (if (or (> month (nth 4 nowdecode))
17146 (>= day (nth 3 nowdecode)))
17147 (nth 5 nowdecode)
17148 (1+ (nth 5 nowdecode))))
17149 ;; Month was specified. Make sure MONTH+YEAR
17150 ;; combination happens in the future.
17151 ((nth 4 tl)
17152 (setq futurep t)
17153 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17154 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17155 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17156 (t (nth 5 nowdecode))))
17157 (t (nth 5 org-defdecode)))
17158 hour (or (nth 2 tl) (nth 2 org-defdecode))
17159 minute (or (nth 1 tl) (nth 1 org-defdecode))
17160 second (or (nth 0 tl) 0)
17161 wday (nth 6 tl))
17163 (when (and (eq org-read-date-prefer-future 'time)
17164 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17165 (equal day (nth 3 nowdecode))
17166 (equal month (nth 4 nowdecode))
17167 (equal year (nth 5 nowdecode))
17168 (nth 2 tl)
17169 (or (< (nth 2 tl) (nth 2 nowdecode))
17170 (and (= (nth 2 tl) (nth 2 nowdecode))
17171 (nth 1 tl)
17172 (< (nth 1 tl) (nth 1 nowdecode)))))
17173 (setq day (1+ day)
17174 futurep t))
17176 ;; Special date definitions below
17177 (cond
17178 (iso-week
17179 ;; There was an iso week
17180 (require 'cal-iso)
17181 (setq futurep nil)
17182 (setq year (or iso-year year)
17183 day (or iso-weekday wday 1)
17184 wday nil ; to make sure that the trigger below does not match
17185 iso-date (calendar-gregorian-from-absolute
17186 (calendar-iso-to-absolute
17187 (list iso-week day year))))
17188 ; FIXME: Should we also push ISO weeks into the future?
17189 ; (when (and org-read-date-prefer-future
17190 ; (not iso-year)
17191 ; (< (calendar-absolute-from-gregorian iso-date)
17192 ; (time-to-days (current-time))))
17193 ; (setq year (1+ year)
17194 ; iso-date (calendar-gregorian-from-absolute
17195 ; (calendar-iso-to-absolute
17196 ; (list iso-week day year)))))
17197 (setq month (car iso-date)
17198 year (nth 2 iso-date)
17199 day (nth 1 iso-date)))
17200 (deltan
17201 (setq futurep nil)
17202 (unless deltadef
17203 ;; Pass `current-time' result to `decode-time' (instead of
17204 ;; calling without arguments) so that only `current-time' has
17205 ;; to be overriden in tests.
17206 (let ((now (decode-time (current-time))))
17207 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17208 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17209 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17210 ((equal deltaw "m") (setq month (+ month deltan)))
17211 ((equal deltaw "y") (setq year (+ year deltan)))))
17212 ((and wday (not (nth 3 tl)))
17213 ;; Weekday was given, but no day, so pick that day in the week
17214 ;; on or after the derived date.
17215 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17216 (unless (equal wday wday1)
17217 (setq day (+ day (% (- wday wday1 -7) 7))))))
17218 (when (and (boundp 'org-time-was-given)
17219 (nth 2 tl))
17220 (setq org-time-was-given t))
17221 (when (< year 100) (setq year (+ 2000 year)))
17222 ;; Check of the date is representable
17223 (if org-read-date-force-compatible-dates
17224 (progn
17225 (when (< year 1970)
17226 (setq year 1970 org-read-date-analyze-forced-year t))
17227 (when (> year 2037)
17228 (setq year 2037 org-read-date-analyze-forced-year t)))
17229 (condition-case nil
17230 (ignore (encode-time second minute hour day month year))
17231 (error
17232 (setq year (nth 5 org-defdecode))
17233 (setq org-read-date-analyze-forced-year t))))
17234 (setq org-read-date-analyze-futurep futurep)
17235 (list second minute hour day month year)))
17237 (defvar parse-time-weekdays)
17238 (defun org-read-date-get-relative (s today default)
17239 "Check string S for special relative date string.
17240 TODAY and DEFAULT are internal times, for today and for a default.
17241 Return shift list (N what def-flag)
17242 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17243 N is the number of WHATs to shift.
17244 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17245 the DEFAULT date rather than TODAY."
17246 (require 'parse-time)
17247 (when (and
17248 (string-match
17249 (concat
17250 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17251 "\\([0-9]+\\)?"
17252 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17253 "\\([ \t]\\|$\\)") s)
17254 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17255 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17256 (string-to-char (substring (match-string 1 s) -1))
17257 ?+))
17258 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17259 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17260 (what (if (match-end 3) (match-string 3 s) "d"))
17261 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17262 (date (if rel default today))
17263 (wday (nth 6 (decode-time date)))
17264 delta)
17265 (if wday1
17266 (progn
17267 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17268 (when (= delta 0) (setq delta 7))
17269 (when (= dir ?-)
17270 (setq delta (- delta 7))
17271 (when (= delta 0) (setq delta -7)))
17272 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17273 (list delta "d" rel))
17274 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17276 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17277 "Turn a user-specified date into the internal representation.
17278 The internal representation needed by the calendar is (month day year).
17279 This is a wrapper to handle the brain-dead convention in calendar that
17280 user function argument order change dependent on argument order."
17281 (if (boundp 'calendar-date-style)
17282 (cond
17283 ((eq calendar-date-style 'american)
17284 (list arg1 arg2 arg3))
17285 ((eq calendar-date-style 'european)
17286 (list arg2 arg1 arg3))
17287 ((eq calendar-date-style 'iso)
17288 (list arg2 arg3 arg1)))
17289 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17290 (if (org-bound-and-true-p european-calendar-style)
17291 (list arg2 arg1 arg3)
17292 (list arg1 arg2 arg3)))))
17294 (defun org-eval-in-calendar (form &optional keepdate)
17295 "Eval FORM in the calendar window and return to current window.
17296 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17297 otherwise stick to the current value of `org-ans2'."
17298 (let ((sf (selected-frame))
17299 (sw (selected-window)))
17300 (select-window (get-buffer-window "*Calendar*" t))
17301 (eval form)
17302 (when (and (not keepdate) (calendar-cursor-to-date))
17303 (let* ((date (calendar-cursor-to-date))
17304 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17305 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17306 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17307 (select-window sw)
17308 (org-select-frame-set-input-focus sf)))
17310 (defun org-calendar-select ()
17311 "Return to `org-read-date' with the date currently selected.
17312 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17313 (interactive)
17314 (when (calendar-cursor-to-date)
17315 (let* ((date (calendar-cursor-to-date))
17316 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17317 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17318 (when (active-minibuffer-window) (exit-minibuffer))))
17320 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17321 "Insert a date stamp for the date given by the internal TIME.
17322 See `format-time-string' for the format of TIME.
17323 WITH-HM means use the stamp format that includes the time of the day.
17324 INACTIVE means use square brackets instead of angular ones, so that the
17325 stamp will not contribute to the agenda.
17326 PRE and POST are optional strings to be inserted before and after the
17327 stamp.
17328 The command returns the inserted time stamp."
17329 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17330 stamp)
17331 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17332 (insert-before-markers (or pre ""))
17333 (when (listp extra)
17334 (setq extra (car extra))
17335 (if (and (stringp extra)
17336 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17337 (setq extra (format "-%02d:%02d"
17338 (string-to-number (match-string 1 extra))
17339 (string-to-number (match-string 2 extra))))
17340 (setq extra nil)))
17341 (when extra
17342 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17343 (insert-before-markers (setq stamp (format-time-string fmt time)))
17344 (insert-before-markers (or post ""))
17345 (setq org-last-inserted-timestamp stamp)))
17347 (defun org-toggle-time-stamp-overlays ()
17348 "Toggle the use of custom time stamp formats."
17349 (interactive)
17350 (setq org-display-custom-times (not org-display-custom-times))
17351 (unless org-display-custom-times
17352 (let ((p (point-min)) (bmp (buffer-modified-p)))
17353 (while (setq p (next-single-property-change p 'display))
17354 (when (and (get-text-property p 'display)
17355 (eq (get-text-property p 'face) 'org-date))
17356 (remove-text-properties
17357 p (setq p (next-single-property-change p 'display))
17358 '(display t))))
17359 (set-buffer-modified-p bmp)))
17360 (when (featurep 'xemacs)
17361 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17362 (org-restart-font-lock)
17363 (setq org-table-may-need-update t)
17364 (if org-display-custom-times
17365 (message "Time stamps are overlaid with custom format")
17366 (message "Time stamp overlays removed")))
17368 (defun org-display-custom-time (beg end)
17369 "Overlay modified time stamp format over timestamp between BEG and END."
17370 (let* ((ts (buffer-substring beg end))
17371 t1 w1 with-hm tf time str w2 (off 0))
17372 (save-match-data
17373 (setq t1 (org-parse-time-string ts t))
17374 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17375 (setq off (- (match-end 0) (match-beginning 0)))))
17376 (setq end (- end off))
17377 (setq w1 (- end beg)
17378 with-hm (and (nth 1 t1) (nth 2 t1))
17379 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17380 time (org-fix-decoded-time t1)
17381 str (org-add-props
17382 (format-time-string
17383 (substring tf 1 -1) (apply 'encode-time time))
17384 nil 'mouse-face 'highlight)
17385 w2 (length str))
17386 (unless (= w2 w1)
17387 (add-text-properties (1+ beg) (+ 2 beg)
17388 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17389 (if (featurep 'xemacs)
17390 (progn
17391 (put-text-property beg end 'invisible t)
17392 (put-text-property beg end 'end-glyph (make-glyph str)))
17393 (put-text-property beg end 'display str))))
17395 (defun org-fix-decoded-time (time)
17396 "Set 0 instead of nil for the first 6 elements of time.
17397 Don't touch the rest."
17398 (let ((n 0))
17399 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17401 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17403 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17404 "Difference between TIMESTAMP-STRING and now in days.
17405 If SECONDS is non-nil, return the difference in seconds."
17406 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17407 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17408 (funcall fdiff (current-time)))))
17410 (defun org-deadline-close (timestamp-string &optional ndays)
17411 "Is the time in TIMESTAMP-STRING close to the current date?"
17412 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17413 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17414 (not (org-entry-is-done-p))))
17416 (defun org-get-wdays (ts &optional delay zero-delay)
17417 "Get the deadline lead time appropriate for timestring TS.
17418 When DELAY is non-nil, get the delay time for scheduled items
17419 instead of the deadline lead time. When ZERO-DELAY is non-nil
17420 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17421 don't try to find the delay cookie in the scheduled timestamp."
17422 (let ((tv (if delay org-scheduled-delay-days
17423 org-deadline-warning-days)))
17424 (cond
17425 ((or (and delay (< tv 0))
17426 (and delay zero-delay (<= tv 0))
17427 (and (not delay) (<= tv 0)))
17428 ;; Enforce this value no matter what
17429 (- tv))
17430 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17431 ;; lead time is specified.
17432 (floor (* (string-to-number (match-string 1 ts))
17433 (cdr (assoc (match-string 2 ts)
17434 '(("d" . 1) ("w" . 7)
17435 ("m" . 30.4) ("y" . 365.25)
17436 ("h" . 0.041667)))))))
17437 ;; go for the default.
17438 (t tv))))
17440 (defun org-calendar-select-mouse (ev)
17441 "Return to `org-read-date' with the date currently selected.
17442 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17443 (interactive "e")
17444 (mouse-set-point ev)
17445 (when (calendar-cursor-to-date)
17446 (let* ((date (calendar-cursor-to-date))
17447 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17448 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17449 (when (active-minibuffer-window) (exit-minibuffer))))
17451 (defun org-check-deadlines (ndays)
17452 "Check if there are any deadlines due or past due.
17453 A deadline is considered due if it happens within `org-deadline-warning-days'
17454 days from today's date. If the deadline appears in an entry marked DONE,
17455 it is not shown. The prefix arg NDAYS can be used to test that many
17456 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17457 (interactive "P")
17458 (let* ((org-warn-days
17459 (cond
17460 ((equal ndays '(4)) 100000)
17461 (ndays (prefix-numeric-value ndays))
17462 (t (abs org-deadline-warning-days))))
17463 (case-fold-search nil)
17464 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17465 (callback
17466 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17467 (message "%d deadlines past-due or due within %d days"
17468 (org-occur regexp nil callback)
17469 org-warn-days)))
17471 (defsubst org-re-timestamp (type)
17472 "Return a regexp for timestamp TYPE.
17473 Allowed values for TYPE are:
17475 all: all timestamps
17476 active: only active timestamps (<...>)
17477 inactive: only inactive timestamps ([...])
17478 scheduled: only scheduled timestamps
17479 deadline: only deadline timestamps
17480 closed: only closed time-stamps
17482 When TYPE is nil, fall back on returning a regexp that matches
17483 both scheduled and deadline timestamps."
17484 (case type
17485 (all org-ts-regexp-both)
17486 (active org-ts-regexp)
17487 (inactive org-ts-regexp-inactive)
17488 (scheduled org-scheduled-time-regexp)
17489 (deadline org-deadline-time-regexp)
17490 (closed org-closed-time-regexp)
17491 (otherwise
17492 (concat "\\<"
17493 (regexp-opt (list org-deadline-string org-scheduled-string))
17494 " *<\\([^>]+\\)>"))))
17496 (defun org-check-before-date (date)
17497 "Check if there are deadlines or scheduled entries before DATE."
17498 (interactive (list (org-read-date)))
17499 (let ((case-fold-search nil)
17500 (regexp (org-re-timestamp org-ts-type))
17501 (callback
17502 `(lambda ()
17503 (let ((match (match-string 1)))
17504 (and ,(if (memq org-ts-type '(active inactive all))
17505 '(eq (org-element-type (org-element-context)) 'timestamp)
17506 '(org-at-planning-p))
17507 (time-less-p
17508 (org-time-string-to-time match)
17509 (org-time-string-to-time date)))))))
17510 (message "%d entries before %s"
17511 (org-occur regexp nil callback) date)))
17513 (defun org-check-after-date (date)
17514 "Check if there are deadlines or scheduled entries after DATE."
17515 (interactive (list (org-read-date)))
17516 (let ((case-fold-search nil)
17517 (regexp (org-re-timestamp org-ts-type))
17518 (callback
17519 `(lambda ()
17520 (let ((match (match-string 1)))
17521 (and ,(if (memq org-ts-type '(active inactive all))
17522 '(eq (org-element-type (org-element-context)) 'timestamp)
17523 '(org-at-planning-p))
17524 (not (time-less-p
17525 (org-time-string-to-time match)
17526 (org-time-string-to-time date))))))))
17527 (message "%d entries after %s"
17528 (org-occur regexp nil callback) date)))
17530 (defun org-check-dates-range (start-date end-date)
17531 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17532 (interactive (list (org-read-date nil nil nil "Range starts")
17533 (org-read-date nil nil nil "Range end")))
17534 (let ((case-fold-search nil)
17535 (regexp (org-re-timestamp org-ts-type))
17536 (callback
17537 `(lambda ()
17538 (let ((match (match-string 1)))
17539 (and
17540 ,(if (memq org-ts-type '(active inactive all))
17541 '(eq (org-element-type (org-element-context)) 'timestamp)
17542 '(org-at-planning-p))
17543 (not (time-less-p
17544 (org-time-string-to-time match)
17545 (org-time-string-to-time start-date)))
17546 (time-less-p
17547 (org-time-string-to-time match)
17548 (org-time-string-to-time end-date)))))))
17549 (message "%d entries between %s and %s"
17550 (org-occur regexp nil callback) start-date end-date)))
17552 (defun org-evaluate-time-range (&optional to-buffer)
17553 "Evaluate a time range by computing the difference between start and end.
17554 Normally the result is just printed in the echo area, but with prefix arg
17555 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17556 If the time range is actually in a table, the result is inserted into the
17557 next column.
17558 For time difference computation, a year is assumed to be exactly 365
17559 days in order to avoid rounding problems."
17560 (interactive "P")
17562 (org-clock-update-time-maybe)
17563 (save-excursion
17564 (unless (org-at-date-range-p t)
17565 (goto-char (point-at-bol))
17566 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17567 (unless (org-at-date-range-p t)
17568 (user-error "Not at a time-stamp range, and none found in current line")))
17569 (let* ((ts1 (match-string 1))
17570 (ts2 (match-string 2))
17571 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17572 (match-end (match-end 0))
17573 (time1 (org-time-string-to-time ts1))
17574 (time2 (org-time-string-to-time ts2))
17575 (t1 (org-float-time time1))
17576 (t2 (org-float-time time2))
17577 (diff (abs (- t2 t1)))
17578 (negative (< (- t2 t1) 0))
17579 ;; (ys (floor (* 365 24 60 60)))
17580 (ds (* 24 60 60))
17581 (hs (* 60 60))
17582 (fy "%dy %dd %02d:%02d")
17583 (fy1 "%dy %dd")
17584 (fd "%dd %02d:%02d")
17585 (fd1 "%dd")
17586 (fh "%02d:%02d")
17587 y d h m align)
17588 (if havetime
17589 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17591 d (floor (/ diff ds)) diff (mod diff ds)
17592 h (floor (/ diff hs)) diff (mod diff hs)
17593 m (floor (/ diff 60)))
17594 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17596 d (floor (+ (/ diff ds) 0.5))
17597 h 0 m 0))
17598 (if (not to-buffer)
17599 (message "%s" (org-make-tdiff-string y d h m))
17600 (if (org-at-table-p)
17601 (progn
17602 (goto-char match-end)
17603 (setq align t)
17604 (and (looking-at " *|") (goto-char (match-end 0))))
17605 (goto-char match-end))
17606 (when (looking-at
17607 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17608 (replace-match ""))
17609 (when negative (insert " -"))
17610 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17611 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17612 (insert " " (format fh h m))))
17613 (when align (org-table-align))
17614 (message "Time difference inserted")))))
17616 (defun org-make-tdiff-string (y d h m)
17617 (let ((fmt "")
17618 (l nil))
17619 (when (> y 0)
17620 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17621 (push y l))
17622 (when (> d 0)
17623 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17624 (push d l))
17625 (when (> h 0)
17626 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17627 (push h l))
17628 (when (> m 0)
17629 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17630 (push m l))
17631 (apply 'format fmt (nreverse l))))
17633 (defun org-time-string-to-time (s &optional buffer pos)
17634 "Convert a timestamp string into internal time."
17635 (condition-case errdata
17636 (apply 'encode-time (org-parse-time-string s))
17637 (error (error "Bad timestamp `%s'%s\nError was: %s"
17638 s (if (not (and buffer pos))
17640 (format-message " at %d in buffer `%s'" pos buffer))
17641 (cdr errdata)))))
17643 (defun org-time-string-to-seconds (s)
17644 "Convert a timestamp string to a number of seconds."
17645 (org-float-time (org-time-string-to-time s)))
17647 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17649 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17650 "Convert time stamp S to an absolute day number.
17652 If DAYNR in non-nil, and there is a specifier for a cyclic time
17653 stamp, get the closest date to DAYNR. If PREFER is
17654 `past' (respectively `future') return a date past (respectively
17655 after) or equal to DAYNR.
17657 POS is the location of time stamp S, as a buffer position in
17658 BUFFER.
17660 Diary sexp timestamps are matched against DAYNR, when non-nil.
17661 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17662 signalled."
17663 (cond
17664 ((string-match "\\`%%\\((.*)\\)" s)
17665 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17666 ;; only able to match individual dates. If it fails, raise an
17667 ;; error.
17668 (if (and daynr
17669 (org-diary-sexp-entry
17670 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17671 daynr
17672 (signal 'org-diary-sexp-no-match (list s))))
17673 ((and daynr show-all) (org-closest-date s daynr prefer))
17674 (t (time-to-days
17675 (condition-case errdata
17676 (apply #'encode-time (org-parse-time-string s))
17677 (error (error "Bad timestamp `%s'%s\nError was: %s"
17679 (if (not (and buffer pos)) ""
17680 (format-message " at %d in buffer `%s'" pos buffer))
17681 (cdr errdata))))))))
17683 (defun org-days-to-iso-week (days)
17684 "Return the iso week number."
17685 (require 'cal-iso)
17686 (car (calendar-iso-from-absolute days)))
17688 (defun org-small-year-to-year (year)
17689 "Convert 2-digit years into 4-digit years.
17690 YEAR is expanded into one of the 30 next years, if possible, or
17691 into a past one. Any year larger than 99 is returned unchanged."
17692 (if (>= year 100) year
17693 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17694 (century (/ current 100))
17695 (offset (- year (% current 100))))
17696 (cond ((> offset 30) (+ (* (1- century) 100) year))
17697 ((> offset -70) (+ (* century 100) year))
17698 (t (+ (* (1+ century) 100) year))))))
17700 (defun org-time-from-absolute (d)
17701 "Return the time corresponding to date D.
17702 D may be an absolute day number, or a calendar-type list (month day year)."
17703 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17704 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17706 (defun org-calendar-holiday ()
17707 "List of holidays, for Diary display in Org-mode."
17708 (require 'holidays)
17709 (let ((hl (funcall
17710 (if (fboundp 'calendar-check-holidays)
17711 'calendar-check-holidays 'check-calendar-holidays) date)))
17712 (when hl (mapconcat 'identity hl "; "))))
17714 (defun org-diary-sexp-entry (sexp entry date)
17715 "Process a SEXP diary ENTRY for DATE."
17716 (require 'diary-lib)
17717 (let ((result (if calendar-debug-sexp
17718 (let ((stack-trace-on-error t))
17719 (eval (car (read-from-string sexp))))
17720 (condition-case nil
17721 (eval (car (read-from-string sexp)))
17722 (error
17723 (beep)
17724 (message "Bad sexp at line %d in %s: %s"
17725 (org-current-line)
17726 (buffer-file-name) sexp)
17727 (sleep-for 2))))))
17728 (cond ((stringp result) (split-string result "; "))
17729 ((and (consp result)
17730 (not (consp (cdr result)))
17731 (stringp (cdr result))) (cdr result))
17732 ((and (consp result)
17733 (stringp (car result))) result)
17734 (result entry))))
17736 (defun org-diary-to-ical-string (frombuf)
17737 "Get iCalendar entries from diary entries in buffer FROMBUF.
17738 This uses the icalendar.el library."
17739 (let* ((tmpdir (if (featurep 'xemacs)
17740 (temp-directory)
17741 temporary-file-directory))
17742 (tmpfile (make-temp-name
17743 (expand-file-name "orgics" tmpdir)))
17744 buf rtn b e)
17745 (with-current-buffer frombuf
17746 (icalendar-export-region (point-min) (point-max) tmpfile)
17747 (setq buf (find-buffer-visiting tmpfile))
17748 (set-buffer buf)
17749 (goto-char (point-min))
17750 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17751 (setq b (match-beginning 0)))
17752 (goto-char (point-max))
17753 (when (re-search-backward "^END:VEVENT" nil t)
17754 (setq e (match-end 0)))
17755 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17756 (kill-buffer buf)
17757 (delete-file tmpfile)
17758 rtn))
17760 (defun org-closest-date (start current prefer)
17761 "Return closest date to CURRENT starting from START.
17763 CURRENT and START are both time stamps.
17765 When PREFER is `past', return a date that is either CURRENT or
17766 past. When PREFER is `future', return a date that is either
17767 CURRENT or future.
17769 Only time stamps with a repeater are modified. Any other time
17770 stamp stay unchanged. In any case, return value is an absolute
17771 day number."
17772 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17773 ;; No repeater. Do not shift time stamp.
17774 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17775 (let ((value (string-to-number (match-string 1 start)))
17776 (type (match-string 2 start)))
17777 (if (= 0 value)
17778 ;; Repeater with a 0-value is considered as void.
17779 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17780 (let* ((base (org-date-to-gregorian start))
17781 (target (org-date-to-gregorian current))
17782 (sday (calendar-absolute-from-gregorian base))
17783 (cday (calendar-absolute-from-gregorian target))
17784 n1 n2)
17785 ;; If START is already past CURRENT, just return START.
17786 (if (<= cday sday) sday
17787 ;; Compute closest date before (N1) and closest date past
17788 ;; (N2) CURRENT.
17789 (pcase type
17790 ("h"
17791 (let ((missing-hours
17792 (mod (+ (- (* 24 (- cday sday))
17793 (nth 2 (org-parse-time-string start)))
17794 org-extend-today-until)
17795 value)))
17796 (setf n1 (if (= missing-hours 0) cday
17797 (- cday (1+ (/ missing-hours 24)))))
17798 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17799 ((or "d" "w")
17800 (let ((value (if (equal type "w") (* 7 value) value)))
17801 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17802 (setf n2 (+ n1 value))))
17803 ("m"
17804 (let* ((add-months
17805 (lambda (date n)
17806 ;; Add N months to gregorian DATE, i.e.,
17807 ;; a list (MONTH DAY YEAR). Return a valid
17808 ;; gregorian date.
17809 (let ((m (+ (nth 0 date) n)))
17810 (list (mod m 12)
17811 (nth 1 date)
17812 (+ (/ m 12) (nth 2 date))))))
17813 (months ; Complete months to TARGET.
17814 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17815 (- (nth 0 target) (nth 0 base))
17816 ;; If START's day is greater than
17817 ;; TARGET's, remove incomplete month.
17818 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17819 value)
17820 value))
17821 (before (funcall add-months base months)))
17822 (setf n1 (calendar-absolute-from-gregorian before))
17823 (setf n2
17824 (calendar-absolute-from-gregorian
17825 (funcall add-months before value)))))
17827 (let* ((d (nth 1 base))
17828 (m (nth 0 base))
17829 (y (nth 2 base))
17830 (years ; Complete years to TARGET.
17831 (* (/ (- (nth 2 target)
17833 ;; If START's month and day are
17834 ;; greater than TARGET's, remove
17835 ;; incomplete year.
17836 (if (or (> (nth 0 target) m)
17837 (and (= (nth 0 target) m)
17838 (> (nth 1 target) d)))
17841 value)
17842 value))
17843 (before (list m d (+ y years))))
17844 (setf n1 (calendar-absolute-from-gregorian before))
17845 (setf n2 (calendar-absolute-from-gregorian
17846 (list m d (+ (nth 2 before) value)))))))
17847 ;; Handle PREFER parameter, if any.
17848 (cond
17849 ((eq prefer 'past) (if (= cday n2) n2 n1))
17850 ((eq prefer 'future) (if (= cday n1) n1 n2))
17851 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17853 (defun org-date-to-gregorian (date)
17854 "Turn any specification of DATE into a Gregorian date for the calendar."
17855 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17856 ((and (listp date) (= (length date) 3)) date)
17857 ((stringp date)
17858 (setq date (org-parse-time-string date))
17859 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17860 ((listp date)
17861 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17863 (defun org-parse-time-string (s &optional nodefault)
17864 "Parse the standard Org-mode time string.
17865 This should be a lot faster than the normal `parse-time-string'.
17866 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17867 hour and minute fields will be nil if not given."
17868 (cond ((string-match org-ts-regexp0 s)
17869 (list 0
17870 (when (or (match-beginning 8) (not nodefault))
17871 (string-to-number (or (match-string 8 s) "0")))
17872 (when (or (match-beginning 7) (not nodefault))
17873 (string-to-number (or (match-string 7 s) "0")))
17874 (string-to-number (match-string 4 s))
17875 (string-to-number (match-string 3 s))
17876 (string-to-number (match-string 2 s))
17877 nil nil nil))
17878 ((string-match "^<[^>]+>$" s)
17879 (decode-time (seconds-to-time (org-matcher-time s))))
17880 (t (error "Not a standard Org-mode time string: %s" s))))
17882 (defun org-timestamp-up (&optional arg)
17883 "Increase the date item at the cursor by one.
17884 If the cursor is on the year, change the year. If it is on the month,
17885 the day or the time, change that.
17886 With prefix ARG, change by that many units."
17887 (interactive "p")
17888 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17890 (defun org-timestamp-down (&optional arg)
17891 "Decrease the date item at the cursor by one.
17892 If the cursor is on the year, change the year. If it is on the month,
17893 the day or the time, change that.
17894 With prefix ARG, change by that many units."
17895 (interactive "p")
17896 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17898 (defun org-timestamp-up-day (&optional arg)
17899 "Increase the date in the time stamp by one day.
17900 With prefix ARG, change that many days."
17901 (interactive "p")
17902 (if (and (not (org-at-timestamp-p t))
17903 (org-at-heading-p))
17904 (org-todo 'up)
17905 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17907 (defun org-timestamp-down-day (&optional arg)
17908 "Decrease the date in the time stamp by one day.
17909 With prefix ARG, change that many days."
17910 (interactive "p")
17911 (if (and (not (org-at-timestamp-p t))
17912 (org-at-heading-p))
17913 (org-todo 'down)
17914 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17916 (defun org-at-timestamp-p (&optional inactive-ok)
17917 "Non-nil if point is inside a timestamp.
17919 When optional argument INACTIVE-OK is non-nil, also consider
17920 inactive timestamps.
17922 When this function returns a non-nil value, match data is set
17923 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17924 INACTIVE-OK."
17925 (interactive)
17926 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17927 (pos (point))
17928 (ans (or (looking-at tsr)
17929 (save-excursion
17930 (skip-chars-backward "^[<\n\r\t")
17931 (when (> (point) (point-min)) (backward-char 1))
17932 (and (looking-at tsr)
17933 (> (- (match-end 0) pos) -1))))))
17934 (and ans
17935 (boundp 'org-ts-what)
17936 (setq org-ts-what
17937 (cond
17938 ((= pos (match-beginning 0)) 'bracket)
17939 ;; Point is considered to be "on the bracket" whether
17940 ;; it's really on it or right after it.
17941 ((= pos (1- (match-end 0))) 'bracket)
17942 ((= pos (match-end 0)) 'after)
17943 ((org-pos-in-match-range pos 2) 'year)
17944 ((org-pos-in-match-range pos 3) 'month)
17945 ((org-pos-in-match-range pos 7) 'hour)
17946 ((org-pos-in-match-range pos 8) 'minute)
17947 ((or (org-pos-in-match-range pos 4)
17948 (org-pos-in-match-range pos 5)) 'day)
17949 ((and (> pos (or (match-end 8) (match-end 5)))
17950 (< pos (match-end 0)))
17951 (- pos (or (match-end 8) (match-end 5))))
17952 (t 'day))))
17953 ans))
17955 (defun org-toggle-timestamp-type ()
17956 "Toggle the type (<active> or [inactive]) of a time stamp."
17957 (interactive)
17958 (when (org-at-timestamp-p t)
17959 (let ((beg (match-beginning 0)) (end (match-end 0))
17960 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17961 (save-excursion
17962 (goto-char beg)
17963 (while (re-search-forward "[][<>]" end t)
17964 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17965 t t)))
17966 (message "Timestamp is now %sactive"
17967 (if (equal (char-after beg) ?<) "" "in")))))
17969 (defun org-at-clock-log-p nil
17970 "Is the cursor on the clock log line?"
17971 (save-excursion
17972 (move-beginning-of-line 1)
17973 (looking-at org-clock-line-re)))
17975 (defvar org-clock-history) ; defined in org-clock.el
17976 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17977 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17978 "Change the date in the time stamp at point.
17979 The date will be changed by N times WHAT. WHAT can be `day', `month',
17980 `year', `minute', `second'. If WHAT is not given, the cursor position
17981 in the timestamp determines what will be changed.
17982 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17983 (let ((origin (point)) origin-cat
17984 with-hm inactive
17985 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17986 org-ts-what
17987 extra rem
17988 ts time time0 fixnext clrgx)
17989 (unless (org-at-timestamp-p t)
17990 (user-error "Not at a timestamp"))
17991 (if (and (not what) (eq org-ts-what 'bracket))
17992 (org-toggle-timestamp-type)
17993 ;; Point isn't on brackets. Remember the part of the time-stamp
17994 ;; the point was in. Indeed, size of time-stamps may change,
17995 ;; but point must be kept in the same category nonetheless.
17996 (setq origin-cat org-ts-what)
17997 (when (and (not what) (not (eq org-ts-what 'day))
17998 org-display-custom-times
17999 (get-text-property (point) 'display)
18000 (not (get-text-property (1- (point)) 'display)))
18001 (setq org-ts-what 'day))
18002 (setq org-ts-what (or what org-ts-what)
18003 inactive (= (char-after (match-beginning 0)) ?\[)
18004 ts (match-string 0))
18005 (replace-match "")
18006 (when (string-match
18007 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18009 (setq extra (match-string 1 ts))
18010 (when suppress-tmp-delay
18011 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18012 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18013 (setq with-hm t))
18014 (setq time0 (org-parse-time-string ts))
18015 (when (and updown
18016 (eq org-ts-what 'minute)
18017 (not current-prefix-arg))
18018 ;; This looks like s-up and s-down. Change by one rounding step.
18019 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18020 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18021 (setcar (cdr time0) (+ (nth 1 time0)
18022 (if (> n 0) (- rem) (- dm rem))))))
18023 (setq time
18024 (encode-time (or (car time0) 0)
18025 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18026 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18027 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18028 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18029 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18030 (nthcdr 6 time0)))
18031 (when (and (member org-ts-what '(hour minute))
18032 extra
18033 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18034 (setq extra (org-modify-ts-extra
18035 extra
18036 (if (eq org-ts-what 'hour) 2 5)
18037 n dm)))
18038 (when (integerp org-ts-what)
18039 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18040 (when (eq what 'calendar)
18041 (let ((cal-date (org-get-date-from-calendar)))
18042 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18043 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18044 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18045 (setcar time0 (or (car time0) 0))
18046 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18047 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18048 (setq time (apply 'encode-time time0))))
18049 ;; Insert the new time-stamp, and ensure point stays in the same
18050 ;; category as before (i.e. not after the last position in that
18051 ;; category).
18052 (let ((pos (point)))
18053 ;; Stay before inserted string. `save-excursion' is of no use.
18054 (setq org-last-changed-timestamp
18055 (org-insert-time-stamp time with-hm inactive nil nil extra))
18056 (goto-char pos))
18057 (save-match-data
18058 (looking-at org-ts-regexp3)
18059 (goto-char (cond
18060 ;; `day' category ends before `hour' if any, or at
18061 ;; the end of the day name.
18062 ((eq origin-cat 'day)
18063 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18064 ((eq origin-cat 'hour) (min (match-end 7) origin))
18065 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18066 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18067 ;; `year' and `month' have both fixed size: point
18068 ;; couldn't have moved into another part.
18069 (t origin))))
18070 ;; Update clock if on a CLOCK line.
18071 (org-clock-update-time-maybe)
18072 ;; Maybe adjust the closest clock in `org-clock-history'
18073 (when org-clock-adjust-closest
18074 (if (not (and (org-at-clock-log-p)
18075 (< 1 (length (delq nil (mapcar 'marker-position
18076 org-clock-history))))))
18077 (message "No clock to adjust")
18078 (cond ((save-excursion ; fix previous clock?
18079 (re-search-backward org-ts-regexp0 nil t)
18080 (org-looking-back (concat org-clock-string " \\[")
18081 (line-beginning-position)))
18082 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18083 ((save-excursion ; fix next clock?
18084 (re-search-backward org-ts-regexp0 nil t)
18085 (looking-at (concat org-ts-regexp0 "\\] =>")))
18086 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18087 (save-window-excursion
18088 ;; Find closest clock to point, adjust the previous/next one in history
18089 (let* ((p (save-excursion (org-back-to-heading t)))
18090 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18091 (clfixnth
18092 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18093 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18094 (if (not clfixpos)
18095 (message "No clock to adjust")
18096 (save-excursion
18097 (org-goto-marker-or-bmk clfixpos)
18098 (org-show-subtree)
18099 (when (re-search-forward clrgx nil t)
18100 (goto-char (match-beginning 1))
18101 (let (org-clock-adjust-closest)
18102 (org-timestamp-change n org-ts-what updown))
18103 (message "Clock adjusted in %s for heading: %s"
18104 (file-name-nondirectory (buffer-file-name))
18105 (org-get-heading t t)))))))))
18106 ;; Try to recenter the calendar window, if any.
18107 (when (and org-calendar-follow-timestamp-change
18108 (get-buffer-window "*Calendar*" t)
18109 (memq org-ts-what '(day month year)))
18110 (org-recenter-calendar (time-to-days time))))))
18112 (defun org-modify-ts-extra (s pos n dm)
18113 "Change the different parts of the lead-time and repeat fields in timestamp."
18114 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18115 ng h m new rem)
18116 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18117 (cond
18118 ((or (org-pos-in-match-range pos 2)
18119 (org-pos-in-match-range pos 3))
18120 (setq m (string-to-number (match-string 3 s))
18121 h (string-to-number (match-string 2 s)))
18122 (if (org-pos-in-match-range pos 2)
18123 (setq h (+ h n))
18124 (setq n (* dm (org-no-warnings (signum n))))
18125 (unless (= 0 (setq rem (% m dm)))
18126 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18127 (setq m (+ m n)))
18128 (when (< m 0) (setq m (+ m 60) h (1- h)))
18129 (when (> m 59) (setq m (- m 60) h (1+ h)))
18130 (setq h (mod h 24))
18131 (setq ng 1 new (format "-%02d:%02d" h m)))
18132 ((org-pos-in-match-range pos 6)
18133 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18134 ((org-pos-in-match-range pos 5)
18135 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18137 ((org-pos-in-match-range pos 9)
18138 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18139 ((org-pos-in-match-range pos 8)
18140 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18142 (when ng
18143 (setq s (concat
18144 (substring s 0 (match-beginning ng))
18146 (substring s (match-end ng))))))
18149 (defun org-recenter-calendar (date)
18150 "If the calendar is visible, recenter it to DATE."
18151 (let ((cwin (get-buffer-window "*Calendar*" t)))
18152 (when cwin
18153 (let ((calendar-move-hook nil))
18154 (with-selected-window cwin
18155 (calendar-goto-date (if (listp date) date
18156 (calendar-gregorian-from-absolute date))))))))
18158 (defun org-goto-calendar (&optional arg)
18159 "Go to the Emacs calendar at the current date.
18160 If there is a time stamp in the current line, go to that date.
18161 A prefix ARG can be used to force the current date."
18162 (interactive "P")
18163 (let ((tsr org-ts-regexp) diff
18164 (calendar-move-hook nil)
18165 (calendar-view-holidays-initially-flag nil)
18166 (calendar-view-diary-initially-flag nil))
18167 (when (or (org-at-timestamp-p)
18168 (save-excursion
18169 (beginning-of-line 1)
18170 (looking-at (concat ".*" tsr))))
18171 (let ((d1 (time-to-days (current-time)))
18172 (d2 (time-to-days
18173 (org-time-string-to-time (match-string 1)))))
18174 (setq diff (- d2 d1))))
18175 (calendar)
18176 (calendar-goto-today)
18177 (when (and diff (not arg)) (calendar-forward-day diff))))
18179 (defun org-get-date-from-calendar ()
18180 "Return a list (month day year) of date at point in calendar."
18181 (with-current-buffer "*Calendar*"
18182 (save-match-data
18183 (calendar-cursor-to-date))))
18185 (defun org-date-from-calendar ()
18186 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18187 If there is already a time stamp at the cursor position, update it."
18188 (interactive)
18189 (if (org-at-timestamp-p t)
18190 (org-timestamp-change 0 'calendar)
18191 (let ((cal-date (org-get-date-from-calendar)))
18192 (org-insert-time-stamp
18193 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18195 (defcustom org-effort-durations
18196 `(("min" . 1)
18197 ("h" . 60)
18198 ("d" . ,(* 60 8))
18199 ("w" . ,(* 60 8 5))
18200 ("m" . ,(* 60 8 5 4))
18201 ("y" . ,(* 60 8 5 40)))
18202 "Conversion factor to minutes for an effort modifier.
18204 Each entry has the form (MODIFIER . MINUTES).
18206 In an effort string, a number followed by MODIFIER is multiplied
18207 by the specified number of MINUTES to obtain an effort in
18208 minutes.
18210 For example, if the value of this variable is ((\"hours\" . 60)), then an
18211 effort string \"2hours\" is equivalent to 120 minutes."
18212 :group 'org-agenda
18213 :version "25.1"
18214 :package-version '(Org . "8.3")
18215 :type '(alist :key-type (string :tag "Modifier")
18216 :value-type (number :tag "Minutes")))
18218 (defun org-minutes-to-clocksum-string (m)
18219 "Format number of minutes as a clocksum string.
18220 The format is determined by `org-time-clocksum-format',
18221 `org-time-clocksum-use-fractional' and
18222 `org-time-clocksum-fractional-format' and
18223 `org-time-clocksum-use-effort-durations'."
18224 (let ((clocksum "")
18225 (m (round m)) ; Don't allow fractions of minutes
18226 h d w mo y fmt n)
18227 (setq h (if org-time-clocksum-use-effort-durations
18228 (cdr (assoc "h" org-effort-durations)) 60)
18229 d (if org-time-clocksum-use-effort-durations
18230 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18231 w (if org-time-clocksum-use-effort-durations
18232 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18233 mo (if org-time-clocksum-use-effort-durations
18234 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18235 y (if org-time-clocksum-use-effort-durations
18236 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18237 ;; fractional format
18238 (if org-time-clocksum-use-fractional
18239 (cond
18240 ;; single format string
18241 ((stringp org-time-clocksum-fractional-format)
18242 (format org-time-clocksum-fractional-format (/ m (float h))))
18243 ;; choice of fractional formats for different time units
18244 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18245 (> (/ (truncate m) (* y d h)) 0))
18246 (format fmt (/ m (* y d (float h)))))
18247 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18248 (> (/ (truncate m) (* mo d h)) 0))
18249 (format fmt (/ m (* mo d (float h)))))
18250 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18251 (> (/ (truncate m) (* w d h)) 0))
18252 (format fmt (/ m (* w d (float h)))))
18253 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18254 (> (/ (truncate m) (* d h)) 0))
18255 (format fmt (/ m (* d (float h)))))
18256 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18257 (> (/ (truncate m) h) 0))
18258 (format fmt (/ m (float h))))
18259 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18260 (format fmt m))
18261 ;; fall back to smallest time unit with a format
18262 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18263 (format fmt (/ m (float h))))
18264 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18265 (format fmt (/ m (* d (float h)))))
18266 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18267 (format fmt (/ m (* w d (float h)))))
18268 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18269 (format fmt (/ m (* mo d (float h)))))
18270 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18271 (format fmt (/ m (* y d (float h))))))
18272 ;; standard (non-fractional) format, with single format string
18273 (if (stringp org-time-clocksum-format)
18274 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18275 ;; separate formats components
18276 (and (setq fmt (plist-get org-time-clocksum-format :years))
18277 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18278 (plist-get org-time-clocksum-format :require-years))
18279 (setq clocksum (concat clocksum (format fmt n))
18280 m (- m (* n y d h))))
18281 (and (setq fmt (plist-get org-time-clocksum-format :months))
18282 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18283 (plist-get org-time-clocksum-format :require-months))
18284 (setq clocksum (concat clocksum (format fmt n))
18285 m (- m (* n mo d h))))
18286 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18287 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18288 (plist-get org-time-clocksum-format :require-weeks))
18289 (setq clocksum (concat clocksum (format fmt n))
18290 m (- m (* n w d h))))
18291 (and (setq fmt (plist-get org-time-clocksum-format :days))
18292 (or (> (setq n (/ (truncate m) (* d h))) 0)
18293 (plist-get org-time-clocksum-format :require-days))
18294 (setq clocksum (concat clocksum (format fmt n))
18295 m (- m (* n d h))))
18296 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18297 (or (> (setq n (/ (truncate m) h)) 0)
18298 (plist-get org-time-clocksum-format :require-hours))
18299 (setq clocksum (concat clocksum (format fmt n))
18300 m (- m (* n h))))
18301 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18302 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18303 (setq clocksum (concat clocksum (format fmt m))))
18304 ;; return formatted time duration
18305 clocksum))))
18307 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18308 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18309 "Org mode version 8.0")
18311 (defun org-hours-to-clocksum-string (n)
18312 (org-minutes-to-clocksum-string (* n 60)))
18314 (defun org-hh:mm-string-to-minutes (s)
18315 "Convert a string H:MM to a number of minutes.
18316 If the string is just a number, interpret it as minutes.
18317 In fact, the first hh:mm or number in the string will be taken,
18318 there can be extra stuff in the string.
18319 If no number is found, the return value is 0."
18320 (cond
18321 ((integerp s) s)
18322 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18323 (+ (* (string-to-number (match-string 1 s)) 60)
18324 (string-to-number (match-string 2 s))))
18325 ((string-match "\\([0-9]+\\)" s)
18326 (string-to-number (match-string 1 s)))
18327 (t 0)))
18329 (defcustom org-image-actual-width t
18330 "Should we use the actual width of images when inlining them?
18332 When set to t, always use the image width.
18334 When set to a number, use imagemagick (when available) to set
18335 the image's width to this value.
18337 When set to a number in a list, try to get the width from any
18338 #+ATTR.* keyword if it matches a width specification like
18340 #+ATTR_HTML: :width 300px
18342 and fall back on that number if none is found.
18344 When set to nil, try to get the width from an #+ATTR.* keyword
18345 and fall back on the original width if none is found.
18347 This requires Emacs >= 24.1, build with imagemagick support."
18348 :group 'org-appearance
18349 :version "24.4"
18350 :package-version '(Org . "8.0")
18351 :type '(choice
18352 (const :tag "Use the image width" t)
18353 (integer :tag "Use a number of pixels")
18354 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18355 (const :tag "Use #+ATTR* or don't resize" nil)))
18357 (defcustom org-agenda-inhibit-startup nil
18358 "Inhibit startup when preparing agenda buffers.
18359 When this variable is t, the initialization of the Org agenda
18360 buffers is inhibited: e.g. the visibility state is not set, the
18361 tables are not re-aligned, etc."
18362 :type 'boolean
18363 :version "24.3"
18364 :group 'org-agenda)
18366 (define-obsolete-variable-alias
18367 'org-agenda-ignore-drawer-properties
18368 'org-agenda-ignore-properties "25.1")
18370 (defcustom org-agenda-ignore-properties nil
18371 "Avoid updating text properties when building the agenda.
18372 Properties are used to prepare buffers for effort estimates,
18373 appointments, statistics and subtree-local categories.
18374 If you don't use these in the agenda, you can add them to this
18375 list and agenda building will be a bit faster.
18376 The value is a list, with zero or more of the symbols `effort', `appt',
18377 `stats' or `category'."
18378 :type '(set :greedy t
18379 (const effort)
18380 (const appt)
18381 (const stats)
18382 (const category))
18383 :version "25.1"
18384 :package-version '(Org . "8.3")
18385 :group 'org-agenda)
18387 (defun org-duration-string-to-minutes (s &optional output-to-string)
18388 "Convert a duration string S to minutes.
18390 A bare number is interpreted as minutes, modifiers can be set by
18391 customizing `org-effort-durations' (which see).
18393 Entries containing a colon are interpreted as H:MM by
18394 `org-hh:mm-string-to-minutes'."
18395 (let ((result 0)
18396 (re (concat "\\([0-9.]+\\) *\\("
18397 (regexp-opt (mapcar 'car org-effort-durations))
18398 "\\)")))
18399 (while (string-match re s)
18400 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18401 (string-to-number (match-string 1 s))))
18402 (setq s (replace-match "" nil t s)))
18403 (setq result (floor result))
18404 (incf result (org-hh:mm-string-to-minutes s))
18405 (if output-to-string (number-to-string result) result)))
18407 ;;;; Files
18409 (defun org-save-all-org-buffers ()
18410 "Save all Org-mode buffers without user confirmation."
18411 (interactive)
18412 (message "Saving all Org-mode buffers...")
18413 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18414 (when (featurep 'org-id) (org-id-locations-save))
18415 (message "Saving all Org-mode buffers... done"))
18417 (defun org-revert-all-org-buffers ()
18418 "Revert all Org-mode buffers.
18419 Prompt for confirmation when there are unsaved changes.
18420 Be sure you know what you are doing before letting this function
18421 overwrite your changes.
18423 This function is useful in a setup where one tracks org files
18424 with a version control system, to revert on one machine after pulling
18425 changes from another. I believe the procedure must be like this:
18427 1. M-x org-save-all-org-buffers
18428 2. Pull changes from the other machine, resolve conflicts
18429 3. M-x org-revert-all-org-buffers"
18430 (interactive)
18431 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18432 (user-error "Abort"))
18433 (save-excursion
18434 (save-window-excursion
18435 (mapc
18436 (lambda (b)
18437 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18438 (with-current-buffer b buffer-file-name))
18439 (org-pop-to-buffer-same-window b)
18440 (revert-buffer t 'no-confirm)))
18441 (buffer-list))
18442 (when (and (featurep 'org-id) org-id-track-globally)
18443 (org-id-locations-load)))))
18445 ;;;; Agenda files
18447 ;;;###autoload
18448 (defun org-switchb (&optional arg)
18449 "Switch between Org buffers.
18450 With one prefix argument, restrict available buffers to files.
18451 With two prefix arguments, restrict available buffers to agenda files.
18453 Defaults to `iswitchb' for buffer name completion.
18454 Set `org-completion-use-ido' to make it use ido instead."
18455 (interactive "P")
18456 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18457 ((equal arg '(16)) (org-buffer-list 'agenda))
18458 (t (org-buffer-list))))
18459 (org-completion-use-iswitchb org-completion-use-iswitchb)
18460 (org-completion-use-ido org-completion-use-ido))
18461 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18462 (setq org-completion-use-iswitchb t))
18463 (org-pop-to-buffer-same-window
18464 (org-icompleting-read "Org buffer: "
18465 (mapcar 'list (mapcar 'buffer-name blist))
18466 nil t))))
18468 ;;; Define some older names previously used for this functionality
18469 ;;;###autoload
18470 (defalias 'org-ido-switchb 'org-switchb)
18471 ;;;###autoload
18472 (defalias 'org-iswitchb 'org-switchb)
18474 (defun org-buffer-list (&optional predicate exclude-tmp)
18475 "Return a list of Org buffers.
18476 PREDICATE can be `export', `files' or `agenda'.
18478 export restrict the list to Export buffers.
18479 files restrict the list to buffers visiting Org files.
18480 agenda restrict the list to buffers visiting agenda files.
18482 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18483 (let* ((bfn nil)
18484 (agenda-files (and (eq predicate 'agenda)
18485 (mapcar 'file-truename (org-agenda-files t))))
18486 (filter
18487 (cond
18488 ((eq predicate 'files)
18489 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18490 ((eq predicate 'export)
18491 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18492 ((eq predicate 'agenda)
18493 (lambda (b)
18494 (with-current-buffer b
18495 (and (derived-mode-p 'org-mode)
18496 (setq bfn (buffer-file-name b))
18497 (member (file-truename bfn) agenda-files)))))
18498 (t (lambda (b) (with-current-buffer b
18499 (or (derived-mode-p 'org-mode)
18500 (string-match "\\*Org .*Export"
18501 (buffer-name b)))))))))
18502 (delq nil
18503 (mapcar
18504 (lambda(b)
18505 (if (and (funcall filter b)
18506 (or (not exclude-tmp)
18507 (not (string-match "tmp" (buffer-name b)))))
18509 nil))
18510 (buffer-list)))))
18512 (defun org-agenda-files (&optional unrestricted archives)
18513 "Get the list of agenda files.
18514 Optional UNRESTRICTED means return the full list even if a restriction
18515 is currently in place.
18516 When ARCHIVES is t, include all archive files that are really being
18517 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18518 `org-agenda-archives-mode' is t."
18519 (let ((files
18520 (cond
18521 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18522 ((stringp org-agenda-files) (org-read-agenda-file-list))
18523 ((listp org-agenda-files) org-agenda-files)
18524 (t (error "Invalid value of `org-agenda-files'")))))
18525 (setq files (apply 'append
18526 (mapcar (lambda (f)
18527 (if (file-directory-p f)
18528 (directory-files
18529 f t org-agenda-file-regexp)
18530 (list f)))
18531 files)))
18532 (when org-agenda-skip-unavailable-files
18533 (setq files (delq nil
18534 (mapcar (function
18535 (lambda (file)
18536 (and (file-readable-p file) file)))
18537 files))))
18538 (when (or (eq archives t)
18539 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18540 (setq files (org-add-archive-files files)))
18541 files))
18543 (defun org-agenda-file-p (&optional file)
18544 "Return non-nil, if FILE is an agenda file.
18545 If FILE is omitted, use the file associated with the current
18546 buffer."
18547 (let ((fname (or file (buffer-file-name))))
18548 (and fname
18549 (member (file-truename fname)
18550 (mapcar #'file-truename (org-agenda-files t))))))
18552 (defun org-edit-agenda-file-list ()
18553 "Edit the list of agenda files.
18554 Depending on setup, this either uses customize to edit the variable
18555 `org-agenda-files', or it visits the file that is holding the list. In the
18556 latter case, the buffer is set up in a way that saving it automatically kills
18557 the buffer and restores the previous window configuration."
18558 (interactive)
18559 (if (stringp org-agenda-files)
18560 (let ((cw (current-window-configuration)))
18561 (find-file org-agenda-files)
18562 (setq-local org-window-configuration cw)
18563 (org-add-hook 'after-save-hook
18564 (lambda ()
18565 (set-window-configuration
18566 (prog1 org-window-configuration
18567 (kill-buffer (current-buffer))))
18568 (org-install-agenda-files-menu)
18569 (message "New agenda file list installed"))
18570 nil 'local)
18571 (message "%s" (substitute-command-keys
18572 "Edit list and finish with \\[save-buffer]")))
18573 (customize-variable 'org-agenda-files)))
18575 (defun org-store-new-agenda-file-list (list)
18576 "Set new value for the agenda file list and save it correctly."
18577 (if (stringp org-agenda-files)
18578 (let ((fe (org-read-agenda-file-list t)) b u)
18579 (while (setq b (find-buffer-visiting org-agenda-files))
18580 (kill-buffer b))
18581 (with-temp-file org-agenda-files
18582 (insert
18583 (mapconcat
18584 (lambda (f) ;; Keep un-expanded entries.
18585 (if (setq u (assoc f fe))
18586 (cdr u)
18588 list "\n")
18589 "\n")))
18590 (let ((org-mode-hook nil) (org-inhibit-startup t)
18591 (org-insert-mode-line-in-empty-file nil))
18592 (setq org-agenda-files list)
18593 (customize-save-variable 'org-agenda-files org-agenda-files))))
18595 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18596 "Read the list of agenda files from a file.
18597 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18598 filenames, used by `org-store-new-agenda-file-list' to write back
18599 un-expanded file names."
18600 (when (file-directory-p org-agenda-files)
18601 (error "`org-agenda-files' cannot be a single directory"))
18602 (when (stringp org-agenda-files)
18603 (with-temp-buffer
18604 (insert-file-contents org-agenda-files)
18605 (mapcar
18606 (lambda (f)
18607 (let ((e (expand-file-name (substitute-in-file-name f)
18608 org-directory)))
18609 (if pair-with-expansion
18610 (cons e f)
18611 e)))
18612 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18614 ;;;###autoload
18615 (defun org-cycle-agenda-files ()
18616 "Cycle through the files in `org-agenda-files'.
18617 If the current buffer visits an agenda file, find the next one in the list.
18618 If the current buffer does not, find the first agenda file."
18619 (interactive)
18620 (let* ((fs (or (org-agenda-files t)
18621 (user-error "No agenda files")))
18622 (files (copy-sequence fs))
18623 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18624 file)
18625 (when tcf
18626 (while (and (setq file (pop files))
18627 (not (equal (file-truename file) tcf)))))
18628 (find-file (car (or files fs)))
18629 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18631 (defun org-agenda-file-to-front (&optional to-end)
18632 "Move/add the current file to the top of the agenda file list.
18633 If the file is not present in the list, it is added to the front. If it is
18634 present, it is moved there. With optional argument TO-END, add/move to the
18635 end of the list."
18636 (interactive "P")
18637 (let ((org-agenda-skip-unavailable-files nil)
18638 (file-alist (mapcar (lambda (x)
18639 (cons (file-truename x) x))
18640 (org-agenda-files t)))
18641 (ctf (file-truename
18642 (or buffer-file-name
18643 (user-error "Please save the current buffer to a file"))))
18644 x had)
18645 (setq x (assoc ctf file-alist) had x)
18647 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18648 (if to-end
18649 (setq file-alist (append (delq x file-alist) (list x)))
18650 (setq file-alist (cons x (delq x file-alist))))
18651 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18652 (org-install-agenda-files-menu)
18653 (message "File %s to %s of agenda file list"
18654 (if had "moved" "added") (if to-end "end" "front"))))
18656 (defun org-remove-file (&optional file)
18657 "Remove current file from the list of files in variable `org-agenda-files'.
18658 These are the files which are being checked for agenda entries.
18659 Optional argument FILE means use this file instead of the current."
18660 (interactive)
18661 (let* ((org-agenda-skip-unavailable-files nil)
18662 (file (or file buffer-file-name
18663 (user-error "Current buffer does not visit a file")))
18664 (true-file (file-truename file))
18665 (afile (abbreviate-file-name file))
18666 (files (delq nil (mapcar
18667 (lambda (x)
18668 (unless (equal true-file
18669 (file-truename x))
18671 (org-agenda-files t)))))
18672 (if (not (= (length files) (length (org-agenda-files t))))
18673 (progn
18674 (org-store-new-agenda-file-list files)
18675 (org-install-agenda-files-menu)
18676 (message "Removed from Org Agenda list: %s" afile))
18677 (message "File was not in list: %s (not removed)" afile))))
18679 (defun org-file-menu-entry (file)
18680 (vector file (list 'find-file file) t))
18682 (defun org-check-agenda-file (file)
18683 "Make sure FILE exists. If not, ask user what to do."
18684 (unless (file-exists-p file)
18685 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18686 (abbreviate-file-name file))
18687 (let ((r (downcase (read-char-exclusive))))
18688 (cond
18689 ((equal r ?r)
18690 (org-remove-file file)
18691 (throw 'nextfile t))
18692 (t (user-error "Abort"))))))
18694 (defun org-get-agenda-file-buffer (file)
18695 "Get an agenda buffer visiting FILE.
18696 If the buffer needs to be created, add it to the list of buffers
18697 which might be released later."
18698 (let ((buf (org-find-base-buffer-visiting file)))
18699 (if buf
18700 buf ; just return it
18701 ;; Make a new buffer and remember it
18702 (setq buf (find-file-noselect file))
18703 (when buf (push buf org-agenda-new-buffers))
18704 buf)))
18706 (defun org-release-buffers (blist)
18707 "Release all buffers in list, asking the user for confirmation when needed.
18708 When a buffer is unmodified, it is just killed. When modified, it is saved
18709 \(if the user agrees) and then killed."
18710 (let (file)
18711 (dolist (buf blist)
18712 (setq file (buffer-file-name buf))
18713 (when (and (buffer-modified-p buf)
18714 file
18715 (y-or-n-p (format "Save file %s? " file)))
18716 (with-current-buffer buf (save-buffer)))
18717 (kill-buffer buf))))
18719 (defun org-agenda-prepare-buffers (files)
18720 "Create buffers for all agenda files, protect archived trees and comments."
18721 (interactive)
18722 (let ((pa '(:org-archived t))
18723 (pc '(:org-comment t))
18724 (pall '(:org-archived t :org-comment t))
18725 (inhibit-read-only t)
18726 (org-inhibit-startup org-agenda-inhibit-startup)
18727 (rea (concat ":" org-archive-tag ":"))
18728 file re pos)
18729 (setq org-tag-alist-for-agenda nil
18730 org-tag-groups-alist-for-agenda nil)
18731 (save-excursion
18732 (save-restriction
18733 (dolist (file files)
18734 (catch 'nextfile
18735 (if (bufferp file)
18736 (set-buffer file)
18737 (org-check-agenda-file file)
18738 (set-buffer (org-get-agenda-file-buffer file)))
18739 (widen)
18740 (org-set-regexps-and-options 'tags-only)
18741 (setq pos (point))
18742 (or (memq 'category org-agenda-ignore-properties)
18743 (org-refresh-category-properties))
18744 (or (memq 'stats org-agenda-ignore-properties)
18745 (org-refresh-stats-properties))
18746 (or (memq 'effort org-agenda-ignore-properties)
18747 (org-refresh-effort-properties))
18748 (or (memq 'appt org-agenda-ignore-properties)
18749 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18750 (setq org-todo-keywords-for-agenda
18751 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18752 (setq org-done-keywords-for-agenda
18753 (append org-done-keywords-for-agenda org-done-keywords))
18754 (setq org-todo-keyword-alist-for-agenda
18755 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18756 (setq org-tag-alist-for-agenda
18757 (org-uniquify
18758 (append org-tag-alist-for-agenda
18759 org-tag-alist
18760 org-tag-persistent-alist)))
18761 (when org-group-tags
18762 (setq org-tag-groups-alist-for-agenda
18763 (org-uniquify-alist
18764 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18765 (org-with-silent-modifications
18766 (save-excursion
18767 (remove-text-properties (point-min) (point-max) pall)
18768 (when org-agenda-skip-archived-trees
18769 (goto-char (point-min))
18770 (while (re-search-forward rea nil t)
18771 (when (org-at-heading-p t)
18772 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18773 (goto-char (point-min))
18774 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18775 (while (re-search-forward re nil t)
18776 (when (save-match-data (org-in-commented-heading-p t))
18777 (add-text-properties
18778 (match-beginning 0) (org-end-of-subtree t) pc)))))
18779 (goto-char pos)))))
18780 (setq org-todo-keywords-for-agenda
18781 (org-uniquify org-todo-keywords-for-agenda))
18782 (setq org-todo-keyword-alist-for-agenda
18783 (org-uniquify org-todo-keyword-alist-for-agenda))))
18786 ;;;; CDLaTeX minor mode
18788 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18789 "Keymap for the minor `org-cdlatex-mode'.")
18791 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18792 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18793 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18794 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18795 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18797 (defvar org-cdlatex-texmathp-advice-is-done nil
18798 "Flag remembering if we have applied the advice to texmathp already.")
18800 (define-minor-mode org-cdlatex-mode
18801 "Toggle the minor `org-cdlatex-mode'.
18802 This mode supports entering LaTeX environment and math in LaTeX fragments
18803 in Org-mode.
18804 \\{org-cdlatex-mode-map}"
18805 nil " OCDL" nil
18806 (when org-cdlatex-mode
18807 (require 'cdlatex)
18808 (run-hooks 'cdlatex-mode-hook)
18809 (cdlatex-compute-tables))
18810 (unless org-cdlatex-texmathp-advice-is-done
18811 (setq org-cdlatex-texmathp-advice-is-done t)
18812 (defadvice texmathp (around org-math-always-on activate)
18813 "Always return t in org-mode buffers.
18814 This is because we want to insert math symbols without dollars even outside
18815 the LaTeX math segments. If Orgmode thinks that point is actually inside
18816 an embedded LaTeX fragment, let texmathp do its job.
18817 \\[org-cdlatex-mode-map]"
18818 (interactive)
18819 (let (p)
18820 (cond
18821 ((not (derived-mode-p 'org-mode)) ad-do-it)
18822 ((eq this-command 'cdlatex-math-symbol)
18823 (setq ad-return-value t
18824 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18826 (let ((p (org-inside-LaTeX-fragment-p)))
18827 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18828 (setq ad-return-value t
18829 texmathp-why '("Org-mode embedded math" . 0))
18830 (when p ad-do-it)))))))))
18832 (defun turn-on-org-cdlatex ()
18833 "Unconditionally turn on `org-cdlatex-mode'."
18834 (org-cdlatex-mode 1))
18836 (defun org-try-cdlatex-tab ()
18837 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18838 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18839 - inside a LaTeX fragment, or
18840 - after the first word in a line, where an abbreviation expansion could
18841 insert a LaTeX environment."
18842 (when org-cdlatex-mode
18843 (cond
18844 ;; Before any word on the line: No expansion possible.
18845 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18846 ;; Just after first word on the line: Expand it. Make sure it
18847 ;; cannot happen on headlines, though.
18848 ((save-excursion
18849 (skip-chars-backward "a-zA-Z0-9*")
18850 (skip-chars-backward " \t")
18851 (and (bolp) (not (org-at-heading-p))))
18852 (cdlatex-tab) t)
18853 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18855 (defun org-cdlatex-underscore-caret (&optional arg)
18856 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18857 Revert to the normal definition outside of these fragments."
18858 (interactive "P")
18859 (if (org-inside-LaTeX-fragment-p)
18860 (call-interactively 'cdlatex-sub-superscript)
18861 (let (org-cdlatex-mode)
18862 (call-interactively (key-binding (vector last-input-event))))))
18864 (defun org-cdlatex-math-modify (&optional arg)
18865 "Execute `cdlatex-math-modify' in LaTeX fragments.
18866 Revert to the normal definition outside of these fragments."
18867 (interactive "P")
18868 (if (org-inside-LaTeX-fragment-p)
18869 (call-interactively 'cdlatex-math-modify)
18870 (let (org-cdlatex-mode)
18871 (call-interactively (key-binding (vector last-input-event))))))
18873 (defun org-cdlatex-environment-indent (&optional environment item)
18874 "Execute `cdlatex-environment' and indent the inserted environment.
18876 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18878 The inserted environment is indented to current indentation
18879 unless point is at the beginning of the line, in which the
18880 environment remains unintended."
18881 (interactive)
18882 ;; cdlatex-environment always return nil. Therefore, capture output
18883 ;; first and determine if an environment was selected.
18884 (let* ((beg (point-marker))
18885 (end (copy-marker (point) t))
18886 (inserted (progn
18887 (ignore-errors (cdlatex-environment environment item))
18888 (< beg end)))
18889 ;; Figure out how many lines to move forward after the
18890 ;; environment has been inserted.
18891 (lines (when inserted
18892 (save-excursion
18893 (- (loop while (< beg (point))
18894 with x = 0
18895 do (forward-line -1)
18896 (incf x)
18897 finally return x)
18898 (if (progn (goto-char beg)
18899 (and (progn (skip-chars-forward " \t") (eolp))
18900 (progn (skip-chars-backward " \t") (bolp))))
18901 1 0)))))
18902 (env (org-trim (delete-and-extract-region beg end))))
18903 (when inserted
18904 ;; Get indentation of next line unless at column 0.
18905 (let ((ind (if (bolp) 0
18906 (save-excursion
18907 (org-return-indent)
18908 (prog1 (org-get-indentation)
18909 (when (progn (skip-chars-forward " \t") (eolp))
18910 (delete-region beg (point)))))))
18911 (bol (progn (skip-chars-backward " \t") (bolp))))
18912 ;; Insert a newline before environment unless at column zero
18913 ;; to "escape" the current line. Insert a newline if
18914 ;; something is one the same line as \end{ENVIRONMENT}.
18915 (insert
18916 (concat (unless bol "\n") env
18917 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18918 (unless (zerop ind)
18919 (save-excursion
18920 (goto-char beg)
18921 (while (< (point) end)
18922 (unless (eolp) (org-indent-line-to ind))
18923 (forward-line))))
18924 (goto-char beg)
18925 (forward-line lines)
18926 (org-indent-line-to ind)))
18927 (set-marker beg nil)
18928 (set-marker end nil)))
18931 ;;;; LaTeX fragments
18933 (defun org-inside-LaTeX-fragment-p ()
18934 "Test if point is inside a LaTeX fragment.
18935 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18936 sequence appearing also before point.
18937 Even though the matchers for math are configurable, this function assumes
18938 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18939 delimiters are skipped when they have been removed by customization.
18940 The return value is nil, or a cons cell with the delimiter and the
18941 position of this delimiter.
18943 This function does a reasonably good job, but can locally be fooled by
18944 for example currency specifications. For example it will assume being in
18945 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18946 fragments that are properly closed, but during editing, we have to live
18947 with the uncertainty caused by missing closing delimiters. This function
18948 looks only before point, not after."
18949 (catch 'exit
18950 (let ((pos (point))
18951 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18952 (lim (progn
18953 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18954 (point)))
18955 dd-on str (start 0) m re)
18956 (goto-char pos)
18957 (when dodollar
18958 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18959 re (nth 1 (assoc "$" org-latex-regexps)))
18960 (while (string-match re str start)
18961 (cond
18962 ((= (match-end 0) (length str))
18963 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18964 ((= (match-end 0) (- (length str) 5))
18965 (throw 'exit nil))
18966 (t (setq start (match-end 0))))))
18967 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18968 (goto-char pos)
18969 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18970 (and (match-beginning 2) (throw 'exit nil))
18971 ;; count $$
18972 (while (re-search-backward "\\$\\$" lim t)
18973 (setq dd-on (not dd-on)))
18974 (goto-char pos)
18975 (when dd-on (cons "$$" m))))))
18977 (defun org-inside-latex-macro-p ()
18978 "Is point inside a LaTeX macro or its arguments?"
18979 (save-match-data
18980 (org-in-regexp
18981 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18983 (defvar-local org-latex-fragment-image-overlays nil
18984 "List of overlays carrying the images of latex fragments.")
18986 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18987 "Remove all overlays with LaTeX fragment images in current buffer.
18988 When optional arguments BEG and END are non-nil, remove all
18989 overlays between them instead. Return t when some overlays were
18990 removed, nil otherwise."
18991 (let (removedp)
18992 (setq org-latex-fragment-image-overlays
18993 (let ((beg (or beg (point-min)))
18994 (end (or end (point-max))))
18995 (cl-remove-if
18996 (lambda (o)
18997 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18998 ((and (>= (overlay-start o) beg)
18999 (<= (overlay-end o) end))
19000 (delete-overlay o)
19001 (unless removedp (setq removedp t)))
19002 (t nil)))
19003 org-latex-fragment-image-overlays)))
19004 removedp))
19006 (define-obsolete-function-alias
19007 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19008 (defun org-toggle-latex-fragment (&optional arg)
19009 "Preview the LaTeX fragment at point, or all locally or globally.
19011 If the cursor is on a LaTeX fragment, create the image and overlay
19012 it over the source code, if there is none. Remove it otherwise.
19013 If there is no fragment at point, display all fragments in the
19014 current section.
19016 With prefix ARG, preview or clear image for all fragments in the
19017 current subtree or in the whole buffer when used before the first
19018 headline. With a double prefix ARG \\[universal-argument] \
19019 \\[universal-argument] preview or clear images
19020 for all fragments in the buffer."
19021 (interactive "P")
19022 (unless (buffer-file-name (buffer-base-buffer))
19023 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
19024 (when (display-graphic-p)
19025 (catch 'exit
19026 (save-excursion
19027 (let ((window-start (window-start)) msg)
19028 (save-restriction
19029 (cond
19030 ((or (equal arg '(16))
19031 (and (equal arg '(4))
19032 (org-with-limited-levels (org-before-first-heading-p))))
19033 (if (org-remove-latex-fragment-image-overlays)
19034 (progn (message "LaTeX fragments images removed from buffer")
19035 (throw 'exit nil))
19036 (setq msg "Creating images for buffer...")))
19037 ((equal arg '(4))
19038 (org-with-limited-levels (org-back-to-heading t))
19039 (let ((beg (point))
19040 (end (progn (org-end-of-subtree t) (point))))
19041 (if (org-remove-latex-fragment-image-overlays beg end)
19042 (progn
19043 (message "LaTeX fragment images removed from subtree")
19044 (throw 'exit nil))
19045 (setq msg "Creating images for subtree...")
19046 (narrow-to-region beg end))))
19047 ((let ((datum (org-element-context)))
19048 (when (memq (org-element-type datum)
19049 '(latex-environment latex-fragment))
19050 (let* ((beg (org-element-property :begin datum))
19051 (end (org-element-property :end datum)))
19052 (if (org-remove-latex-fragment-image-overlays beg end)
19053 (progn (message "LaTeX fragment image removed")
19054 (throw 'exit nil))
19055 (narrow-to-region beg end)
19056 (setq msg "Creating image..."))))))
19058 (org-with-limited-levels
19059 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19060 (outline-previous-heading)
19061 (point)))
19062 (end (progn (outline-next-heading) (point))))
19063 (if (org-remove-latex-fragment-image-overlays beg end)
19064 (progn
19065 (message "LaTeX fragment images removed from section")
19066 (throw 'exit nil))
19067 (setq msg "Creating images for section...")
19068 (narrow-to-region beg end))))))
19069 (let ((file (buffer-file-name (buffer-base-buffer))))
19070 (org-format-latex
19071 (concat org-latex-preview-ltxpng-directory
19072 (file-name-sans-extension (file-name-nondirectory file)))
19073 ;; Emacs cannot overlay images from remote hosts.
19074 ;; Create it in `temporary-file-directory' instead.
19075 (if (file-remote-p file) temporary-file-directory
19076 default-directory)
19077 'overlays msg 'forbuffer
19078 org-latex-create-formula-image-program)))
19079 ;; Work around a bug that doesn't restore window's start
19080 ;; when widening back the buffer.
19081 (set-window-start nil window-start)
19082 (message (concat msg "done")))))))
19084 (defun org-format-latex
19085 (prefix &optional dir overlays msg forbuffer processing-type)
19086 "Replace LaTeX fragments with links to an image, and produce images.
19088 When optional argument OVERLAYS is non-nil, display the image on
19089 top of the fragment instead of replacing it.
19091 PROCESSING-TYPE is the conversion method to use, as a symbol.
19093 Some of the options can be changed using the variable
19094 `org-format-latex-options', which see."
19095 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19096 (unless (eq processing-type 'verbatim)
19097 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19098 (cnt 0)
19099 checkdir-flag)
19100 (goto-char (point-min))
19101 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19102 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19103 (overlay-recenter (point-max)))
19104 (while (re-search-forward math-regexp nil t)
19105 (unless (and overlays
19106 (eq (get-char-property (point) 'org-overlay-type)
19107 'org-latex-overlay))
19108 (let* ((context (org-element-context))
19109 (type (org-element-type context)))
19110 (when (memq type '(latex-environment latex-fragment))
19111 (let ((block-type (eq type 'latex-environment))
19112 (value (org-element-property :value context))
19113 (beg (org-element-property :begin context))
19114 (end (save-excursion
19115 (goto-char (org-element-property :end context))
19116 (skip-chars-backward " \r\t\n")
19117 (point))))
19118 (case processing-type
19119 (mathjax
19120 ;; Prepare for MathJax processing.
19121 (if (eq (char-after beg) ?$)
19122 (save-excursion
19123 (delete-region beg end)
19124 (insert "\\(" (substring value 1 -1) "\\)"))
19125 (goto-char end)))
19126 ((dvipng imagemagick)
19127 ;; Process to an image.
19128 (incf cnt)
19129 (goto-char beg)
19130 (let* ((face (face-at-point))
19131 ;; Get the colors from the face at point.
19133 (let ((color (plist-get org-format-latex-options
19134 :foreground)))
19135 (if (and forbuffer (eq color 'auto))
19136 (face-attribute face :foreground nil 'default)
19137 color)))
19139 (let ((color (plist-get org-format-latex-options
19140 :background)))
19141 (if (and forbuffer (eq color 'auto))
19142 (face-attribute face :background nil 'default)
19143 color)))
19144 (hash (sha1 (prin1-to-string
19145 (list org-format-latex-header
19146 org-latex-default-packages-alist
19147 org-latex-packages-alist
19148 org-format-latex-options
19149 forbuffer value fg bg))))
19150 (absprefix (expand-file-name prefix dir))
19151 (linkfile (format "%s_%s.png" prefix hash))
19152 (movefile (format "%s_%s.png" absprefix hash))
19153 (sep (and block-type "\n\n"))
19154 (link (concat sep "[[file:" linkfile "]]" sep))
19155 (options
19156 (org-combine-plists
19157 org-format-latex-options
19158 `(:foreground ,fg :background ,bg))))
19159 (when msg (message msg cnt))
19160 (unless checkdir-flag ; Ensure the directory exists.
19161 (setq checkdir-flag t)
19162 (let ((todir (file-name-directory absprefix)))
19163 (unless (file-directory-p todir)
19164 (make-directory todir t))))
19165 (unless (file-exists-p movefile)
19166 (org-create-formula-image
19167 value movefile options forbuffer processing-type))
19168 (if overlays
19169 (progn
19170 (dolist (o (overlays-in beg end))
19171 (when (eq (overlay-get o 'org-overlay-type)
19172 'org-latex-overlay)
19173 (delete-overlay o)))
19174 (let ((ov (make-overlay beg end)))
19175 (overlay-put ov
19176 'org-overlay-type
19177 'org-latex-overlay)
19178 (overlay-put ov 'evaporate t)
19179 (if (featurep 'xemacs)
19180 (progn
19181 (overlay-put ov 'invisible t)
19182 (overlay-put
19183 ov 'end-glyph
19184 (make-glyph
19185 (vector 'png :file movefile))))
19186 (overlay-put
19187 ov 'display
19188 (list 'image
19189 :type 'png
19190 :file movefile
19191 :ascent 'center)))
19192 (push ov org-latex-fragment-image-overlays))
19193 (goto-char end))
19194 (delete-region beg end)
19195 (insert
19196 (org-add-props link
19197 (list 'org-latex-src
19198 (replace-regexp-in-string "\"" "" value)
19199 'org-latex-src-embed-type
19200 (if block-type 'paragraph 'character)))))))
19201 (mathml
19202 ;; Process to MathML.
19203 (unless (org-format-latex-mathml-available-p)
19204 (user-error "LaTeX to MathML converter not configured"))
19205 (incf cnt)
19206 (when msg (message msg cnt))
19207 (goto-char beg)
19208 (delete-region beg end)
19209 (insert (org-format-latex-as-mathml
19210 value block-type prefix dir)))
19211 (otherwise
19212 (error "Unknown conversion type %s for LaTeX fragments"
19213 processing-type)))))))))))
19215 (defun org-create-math-formula (latex-frag &optional mathml-file)
19216 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19217 Use `org-latex-to-mathml-convert-command'. If the conversion is
19218 sucessful, return the portion between \"<math...> </math>\"
19219 elements otherwise return nil. When MATHML-FILE is specified,
19220 write the results in to that file. When invoked as an
19221 interactive command, prompt for LATEX-FRAG, with initial value
19222 set to the current active region and echo the results for user
19223 inspection."
19224 (interactive (list (let ((frag (when (org-region-active-p)
19225 (buffer-substring-no-properties
19226 (region-beginning) (region-end)))))
19227 (read-string "LaTeX Fragment: " frag nil frag))))
19228 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19229 (let* ((tmp-in-file (file-relative-name
19230 (make-temp-name (expand-file-name "ltxmathml-in"))))
19231 (ignore (write-region latex-frag nil tmp-in-file))
19232 (tmp-out-file (file-relative-name
19233 (make-temp-name (expand-file-name "ltxmathml-out"))))
19234 (cmd (format-spec
19235 org-latex-to-mathml-convert-command
19236 `((?j . ,(and org-latex-to-mathml-jar-file
19237 (shell-quote-argument
19238 (expand-file-name
19239 org-latex-to-mathml-jar-file))))
19240 (?I . ,(shell-quote-argument tmp-in-file))
19241 (?i . ,latex-frag)
19242 (?o . ,(shell-quote-argument tmp-out-file)))))
19243 mathml shell-command-output)
19244 (when (org-called-interactively-p 'any)
19245 (unless (org-format-latex-mathml-available-p)
19246 (user-error "LaTeX to MathML converter not configured")))
19247 (message "Running %s" cmd)
19248 (setq shell-command-output (shell-command-to-string cmd))
19249 (setq mathml
19250 (when (file-readable-p tmp-out-file)
19251 (with-current-buffer (find-file-noselect tmp-out-file t)
19252 (goto-char (point-min))
19253 (when (re-search-forward
19254 (concat
19255 (regexp-quote
19256 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19257 "[^>]*?>"
19258 "\\(.\\|\n\\)*"
19259 "</math>")
19260 nil t)
19261 (prog1 (match-string 0) (kill-buffer))))))
19262 (cond
19263 (mathml
19264 (setq mathml
19265 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19266 (when mathml-file
19267 (write-region mathml nil mathml-file))
19268 (when (org-called-interactively-p 'any)
19269 (message mathml)))
19270 ((message "LaTeX to MathML conversion failed")
19271 (message shell-command-output)))
19272 (delete-file tmp-in-file)
19273 (when (file-exists-p tmp-out-file)
19274 (delete-file tmp-out-file))
19275 mathml))
19277 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19278 prefix &optional dir)
19279 "Use `org-create-math-formula' but check local cache first."
19280 (let* ((absprefix (expand-file-name prefix dir))
19281 (print-length nil) (print-level nil)
19282 (formula-id (concat
19283 "formula-"
19284 (sha1
19285 (prin1-to-string
19286 (list latex-frag
19287 org-latex-to-mathml-convert-command)))))
19288 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19289 (formula-cache-dir (file-name-directory formula-cache)))
19291 (unless (file-directory-p formula-cache-dir)
19292 (make-directory formula-cache-dir t))
19294 (unless (file-exists-p formula-cache)
19295 (org-create-math-formula latex-frag formula-cache))
19297 (if (file-exists-p formula-cache)
19298 ;; Successful conversion. Return the link to MathML file.
19299 (org-add-props
19300 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19301 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19302 'org-latex-src-embed-type (if latex-frag-type
19303 'paragraph 'character)))
19304 ;; Failed conversion. Return the LaTeX fragment verbatim
19305 latex-frag)))
19307 (defun org-create-formula-image (string tofile options buffer &optional type)
19308 "Create an image from LaTeX source using dvipng or convert.
19309 This function calls either `org-create-formula-image-with-dvipng'
19310 or `org-create-formula-image-with-imagemagick' depending on the
19311 value of `org-latex-create-formula-image-program' or on the value
19312 of the optional TYPE variable.
19314 Note: ultimately these two function should be combined as they
19315 share a good deal of logic."
19316 (org-check-external-command
19317 "latex" "needed to convert LaTeX fragments to images")
19318 (funcall
19319 (case (or type org-latex-create-formula-image-program)
19320 (dvipng
19321 (org-check-external-command
19322 "dvipng" "needed to convert LaTeX fragments to images")
19323 #'org-create-formula-image-with-dvipng)
19324 (imagemagick
19325 (org-check-external-command
19326 "convert" "you need to install imagemagick")
19327 #'org-create-formula-image-with-imagemagick)
19328 (t (error
19329 "Invalid value of `org-latex-create-formula-image-program'")))
19330 string tofile options buffer))
19332 (declare-function org-export-get-backend "ox" (name))
19333 (declare-function org-export--get-global-options "ox" (&optional backend))
19334 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19335 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19336 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19337 (defun org-create-formula--latex-header ()
19338 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19339 (let ((info (org-combine-plists (org-export--get-global-options
19340 (org-export-get-backend 'latex))
19341 (org-export--get-inbuffer-options
19342 (org-export-get-backend 'latex)))))
19343 (org-latex-guess-babel-language
19344 (org-latex-guess-inputenc
19345 (org-splice-latex-header
19346 org-format-latex-header
19347 org-latex-default-packages-alist
19348 org-latex-packages-alist t
19349 (plist-get info :latex-header)))
19350 info)))
19352 (defun org--get-display-dpi ()
19353 "Get the DPI of the display.
19355 Assumes that the display has the same pixel width in the
19356 horizontal and vertical directions."
19357 (if (display-graphic-p)
19358 (round (/ (display-pixel-height)
19359 (/ (display-mm-height) 25.4)))
19360 (error "Attempt to calculate the dpi of a non-graphic display")))
19362 ;; This function borrows from Ganesh Swami's latex2png.el
19363 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19364 "This calls dvipng."
19365 (require 'ox-latex)
19366 (let* ((tmpdir (if (featurep 'xemacs)
19367 (temp-directory)
19368 temporary-file-directory))
19369 (texfilebase (make-temp-name
19370 (expand-file-name "orgtex" tmpdir)))
19371 (texfile (concat texfilebase ".tex"))
19372 (dvifile (concat texfilebase ".dvi"))
19373 (pngfile (concat texfilebase ".png"))
19374 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19375 ;; This assumes that the display has the same pixel width in
19376 ;; the horizontal and vertical directions
19377 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19378 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19379 "Black"))
19380 (bg (or (plist-get options (if buffer :background :html-background))
19381 "Transparent")))
19382 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19383 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19384 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19385 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19386 (let ((latex-header (org-create-formula--latex-header)))
19387 (with-temp-file texfile
19388 (insert latex-header)
19389 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19390 (let ((dir default-directory))
19391 (ignore-errors
19392 (cd tmpdir)
19393 (call-process "latex" nil nil nil texfile))
19394 (cd dir))
19395 (if (not (file-exists-p dvifile))
19396 (progn (message "Failed to create dvi file from %s" texfile) nil)
19397 (ignore-errors
19398 (if (featurep 'xemacs)
19399 (call-process "dvipng" nil nil nil
19400 "-fg" fg "-bg" bg
19401 "-T" "tight"
19402 "-o" pngfile
19403 dvifile)
19404 (call-process "dvipng" nil nil nil
19405 "-fg" fg "-bg" bg
19406 "-D" dpi
19407 ;;"-x" scale "-y" scale
19408 "-T" "tight"
19409 "-o" pngfile
19410 dvifile)))
19411 (if (not (file-exists-p pngfile))
19412 (if org-format-latex-signal-error
19413 (error "Failed to create png file from %s" texfile)
19414 (message "Failed to create png file from %s" texfile)
19415 nil)
19416 ;; Use the requested file name and clean up
19417 (copy-file pngfile tofile 'replace)
19418 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19419 (when (file-exists-p (concat texfilebase e))
19420 (delete-file (concat texfilebase e))))
19421 pngfile))))
19423 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19424 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19425 "This calls convert, which is included into imagemagick."
19426 (require 'ox-latex)
19427 (let* ((tmpdir (if (featurep 'xemacs)
19428 (temp-directory)
19429 temporary-file-directory))
19430 (texfilebase (make-temp-name
19431 (expand-file-name "orgtex" tmpdir)))
19432 (texfile (concat texfilebase ".tex"))
19433 (pdffile (concat texfilebase ".pdf"))
19434 (pngfile (concat texfilebase ".png"))
19435 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19436 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19437 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19438 "black"))
19439 (bg (or (plist-get options (if buffer :background :html-background))
19440 "white")))
19441 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19442 (setq fg (org-latex-color-format fg)))
19443 (if (eq bg 'default) (setq bg (org-latex-color :background))
19444 (setq bg (org-latex-color-format
19445 (if (string= bg "Transparent") "white" bg))))
19446 (let ((latex-header (org-create-formula--latex-header)))
19447 (with-temp-file texfile
19448 (insert latex-header)
19449 (insert "\n\\begin{document}\n"
19450 "\\definecolor{fg}{rgb}{" fg "}\n"
19451 "\\definecolor{bg}{rgb}{" bg "}\n"
19452 "\n\\pagecolor{bg}\n"
19453 "\n{\\color{fg}\n"
19454 string
19455 "\n}\n"
19456 "\n\\end{document}\n")))
19457 (org-latex-compile texfile t)
19458 (if (not (file-exists-p pdffile))
19459 (progn (message "Failed to create pdf file from %s" texfile) nil)
19460 (ignore-errors
19461 (if (featurep 'xemacs)
19462 (call-process "convert" nil nil nil
19463 "-density" "96"
19464 "-trim"
19465 "-antialias"
19466 pdffile
19467 "-quality" "100"
19468 ;; "-sharpen" "0x1.0"
19469 pngfile)
19470 (call-process "convert" nil nil nil
19471 "-density" dpi
19472 "-trim"
19473 "-antialias"
19474 pdffile
19475 "-quality" "100"
19476 ;; "-sharpen" "0x1.0"
19477 pngfile)))
19478 (if (not (file-exists-p pngfile))
19479 (if org-format-latex-signal-error
19480 (error "Failed to create png file from %s" texfile)
19481 (message "Failed to create png file from %s" texfile)
19482 nil)
19483 ;; Use the requested file name and clean up
19484 (copy-file pngfile tofile 'replace)
19485 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19486 (when (file-exists-p (concat texfilebase e))
19487 (delete-file (concat texfilebase e))))
19488 pngfile))))
19490 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19491 "Fill a LaTeX header template TPL.
19492 In the template, the following place holders will be recognized:
19494 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19495 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19496 [PACKAGES] \\usepackage statements for PKG
19497 [NO-PACKAGES] do not include PKG
19498 [EXTRA] the string EXTRA
19499 [NO-EXTRA] do not include EXTRA
19501 For backward compatibility, if both the positive and the negative place
19502 holder is missing, the positive one (without the \"NO-\") will be
19503 assumed to be present at the end of the template.
19504 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19505 EXTRA is a string.
19506 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19507 (let (rpl (end ""))
19508 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19509 (setq rpl (if (or (match-end 1) (not def-pkg))
19510 "" (org-latex-packages-to-string def-pkg snippets-p t))
19511 tpl (replace-match rpl t t tpl))
19512 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19514 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19515 (setq rpl (if (or (match-end 1) (not pkg))
19516 "" (org-latex-packages-to-string pkg snippets-p t))
19517 tpl (replace-match rpl t t tpl))
19518 (when pkg (setq end
19519 (concat end "\n"
19520 (org-latex-packages-to-string pkg snippets-p)))))
19522 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19523 (setq rpl (if (or (match-end 1) (not extra))
19524 "" (concat extra "\n"))
19525 tpl (replace-match rpl t t tpl))
19526 (when (and extra (string-match "\\S-" extra))
19527 (setq end (concat end "\n" extra))))
19529 (if (string-match "\\S-" end)
19530 (concat tpl "\n" end)
19531 tpl)))
19533 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19534 "Turn an alist of packages into a string with the \\usepackage macros."
19535 (setq pkg (mapconcat (lambda(p)
19536 (cond
19537 ((stringp p) p)
19538 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19539 (format "%% Package %s omitted" (cadr p)))
19540 ((equal "" (car p))
19541 (format "\\usepackage{%s}" (cadr p)))
19543 (format "\\usepackage[%s]{%s}"
19544 (car p) (cadr p)))))
19546 "\n"))
19547 (if newline (concat pkg "\n") pkg))
19549 (defun org-dvipng-color (attr)
19550 "Return a RGB color specification for dvipng."
19551 (apply 'format "rgb %s %s %s"
19552 (mapcar 'org-normalize-color
19553 (if (featurep 'xemacs)
19554 (color-rgb-components
19555 (face-property 'default
19556 (cond ((eq attr :foreground) 'foreground)
19557 ((eq attr :background) 'background))))
19558 (color-values (face-attribute 'default attr nil))))))
19560 (defun org-dvipng-color-format (color-name)
19561 "Convert COLOR-NAME to a RGB color value for dvipng."
19562 (apply 'format "rgb %s %s %s"
19563 (mapcar 'org-normalize-color
19564 (color-values color-name))))
19566 (defun org-latex-color (attr)
19567 "Return a RGB color for the LaTeX color package."
19568 (apply 'format "%s,%s,%s"
19569 (mapcar 'org-normalize-color
19570 (if (featurep 'xemacs)
19571 (color-rgb-components
19572 (face-property 'default
19573 (cond ((eq attr :foreground) 'foreground)
19574 ((eq attr :background) 'background))))
19575 (color-values (face-attribute 'default attr nil))))))
19577 (defun org-latex-color-format (color-name)
19578 "Convert COLOR-NAME to a RGB color value."
19579 (apply 'format "%s,%s,%s"
19580 (mapcar 'org-normalize-color
19581 (color-values color-name))))
19583 (defun org-normalize-color (value)
19584 "Return string to be used as color value for an RGB component."
19585 (format "%g" (/ value 65535.0)))
19589 ;; Image display
19591 (defvar-local org-inline-image-overlays nil)
19593 (defun org-toggle-inline-images (&optional include-linked)
19594 "Toggle the display of inline images.
19595 INCLUDE-LINKED is passed to `org-display-inline-images'."
19596 (interactive "P")
19597 (if org-inline-image-overlays
19598 (progn
19599 (org-remove-inline-images)
19600 (when (org-called-interactively-p 'interactive)
19601 (message "Inline image display turned off")))
19602 (org-display-inline-images include-linked)
19603 (when (org-called-interactively-p 'interactive)
19604 (message (if org-inline-image-overlays
19605 (format "%d images displayed inline"
19606 (length org-inline-image-overlays))
19607 "No images to display inline")))))
19609 (defun org-redisplay-inline-images ()
19610 "Refresh the display of inline images."
19611 (interactive)
19612 (if (not org-inline-image-overlays)
19613 (org-toggle-inline-images)
19614 (org-toggle-inline-images)
19615 (org-toggle-inline-images)))
19617 (defun org-display-inline-images (&optional include-linked refresh beg end)
19618 "Display inline images.
19620 An inline image is a link which follows either of these
19621 conventions:
19623 1. Its path is a file with an extension matching return value
19624 from `image-file-name-regexp' and it has no contents.
19626 2. Its description consists in a single link of the previous
19627 type.
19629 When optional argument INCLUDE-LINKED is non-nil, also links with
19630 a text description part will be inlined. This can be nice for
19631 a quick look at those images, but it does not reflect what
19632 exported files will look like.
19634 When optional argument REFRESH is non-nil, refresh existing
19635 images between BEG and END. This will create new image displays
19636 only if necessary. BEG and END default to the buffer
19637 boundaries."
19638 (interactive "P")
19639 (when (display-graphic-p)
19640 (unless refresh
19641 (org-remove-inline-images)
19642 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19643 (org-with-wide-buffer
19644 (goto-char (or beg (point-min)))
19645 (let ((case-fold-search t)
19646 (file-extension-re (image-file-name-regexp)))
19647 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19648 (let ((link (save-match-data (org-element-context))))
19649 ;; Check if we're at an inline image.
19650 (when (and (equal (org-element-property :type link) "file")
19651 (or include-linked
19652 (not (org-element-property :contents-begin link)))
19653 (let ((parent (org-element-property :parent link)))
19654 (or (not (eq (org-element-type parent) 'link))
19655 (not (cdr (org-element-contents parent)))))
19656 (org-string-match-p file-extension-re
19657 (org-element-property :path link)))
19658 (let ((file (expand-file-name
19659 (org-link-unescape
19660 (org-element-property :path link)))))
19661 (when (file-exists-p file)
19662 (let ((width
19663 ;; Apply `org-image-actual-width' specifications.
19664 (cond
19665 ((not (image-type-available-p 'imagemagick)) nil)
19666 ((eq org-image-actual-width t) nil)
19667 ((listp org-image-actual-width)
19669 ;; First try to find a width among
19670 ;; attributes associated to the paragraph
19671 ;; containing link.
19672 (let ((paragraph
19673 (let ((e link))
19674 (while (and (setq e (org-element-property
19675 :parent e))
19676 (not (eq (org-element-type e)
19677 'paragraph))))
19678 e)))
19679 (when paragraph
19680 (save-excursion
19681 (goto-char (org-element-property :begin paragraph))
19682 (when
19683 (re-search-forward
19684 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19685 (org-element-property
19686 :post-affiliated paragraph)
19688 (string-to-number (match-string 1))))))
19689 ;; Otherwise, fall-back to provided number.
19690 (car org-image-actual-width)))
19691 ((numberp org-image-actual-width)
19692 org-image-actual-width)))
19693 (old (get-char-property-and-overlay
19694 (org-element-property :begin link)
19695 'org-image-overlay)))
19696 (if (and (car-safe old) refresh)
19697 (image-refresh (overlay-get (cdr old) 'display))
19698 (let ((image (create-image file
19699 (and width 'imagemagick)
19701 :width width)))
19702 (when image
19703 (let* ((link
19704 ;; If inline image is the description
19705 ;; of another link, be sure to
19706 ;; consider the latter as the one to
19707 ;; apply the overlay on.
19708 (let ((parent
19709 (org-element-property :parent link)))
19710 (if (eq (org-element-type parent) 'link)
19711 parent
19712 link)))
19713 (ov (make-overlay
19714 (org-element-property :begin link)
19715 (progn
19716 (goto-char
19717 (org-element-property :end link))
19718 (skip-chars-backward " \t")
19719 (point)))))
19720 (overlay-put ov 'display image)
19721 (overlay-put ov 'face 'default)
19722 (overlay-put ov 'org-image-overlay t)
19723 (overlay-put
19724 ov 'modification-hooks
19725 (list 'org-display-inline-remove-overlay))
19726 (push ov org-inline-image-overlays)))))))))))))))
19728 (define-obsolete-function-alias
19729 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19731 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19732 "Remove inline-display overlay if a corresponding region is modified."
19733 (let ((inhibit-modification-hooks t))
19734 (when (and ov after)
19735 (delete ov org-inline-image-overlays)
19736 (delete-overlay ov))))
19738 (defun org-remove-inline-images ()
19739 "Remove inline display of images."
19740 (interactive)
19741 (mapc 'delete-overlay org-inline-image-overlays)
19742 (setq org-inline-image-overlays nil))
19744 ;;;; Key bindings
19746 ;; Outline functions from `outline-mode-prefix-map'
19747 ;; that can be remapped in Org:
19748 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19749 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19750 (define-key org-mode-map [remap outline-forward-same-level]
19751 'org-forward-heading-same-level)
19752 (define-key org-mode-map [remap outline-backward-same-level]
19753 'org-backward-heading-same-level)
19754 (define-key org-mode-map [remap outline-show-branches]
19755 'org-kill-note-or-show-branches)
19756 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19757 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19758 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19759 (define-key org-mode-map [remap outline-next-visible-heading]
19760 'org-next-visible-heading)
19761 (define-key org-mode-map [remap outline-previous-visible-heading]
19762 'org-previous-visible-heading)
19763 (define-key org-mode-map [remap show-children] 'org-show-children)
19765 ;; Outline functions from `outline-mode-prefix-map' that can not
19766 ;; be remapped in Org:
19768 ;; - the column "key binding" shows whether the Outline function is still
19769 ;; available in Org mode on the same key that it has been bound to in
19770 ;; Outline mode:
19771 ;; - "overridden": key used for a different functionality in Org mode
19772 ;; - else: key still bound to the same Outline function in Org mode
19774 ;; | Outline function | key binding | Org replacement |
19775 ;; |------------------------------------+-------------+--------------------------|
19776 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19777 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19778 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19779 ;; | `show-entry' | overridden | no replacement |
19780 ;; | `show-branches' | `C-c C-k' | still same function |
19781 ;; | `show-subtree' | overridden | visibility cycling |
19782 ;; | `show-all' | overridden | no replacement |
19783 ;; | `hide-subtree' | overridden | visibility cycling |
19784 ;; | `hide-body' | overridden | no replacement |
19785 ;; | `hide-entry' | overridden | visibility cycling |
19786 ;; | `hide-leaves' | overridden | no replacement |
19787 ;; | `hide-sublevels' | overridden | no replacement |
19788 ;; | `hide-other' | overridden | no replacement |
19790 ;; Make `C-c C-x' a prefix key
19791 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19793 ;; TAB key with modifiers
19794 (org-defkey org-mode-map "\C-i" 'org-cycle)
19795 (org-defkey org-mode-map [(tab)] 'org-cycle)
19796 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19797 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19798 ;; The following line is necessary under Suse GNU/Linux
19799 (unless (featurep 'xemacs)
19800 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19801 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19802 (define-key org-mode-map [backtab] 'org-shifttab)
19804 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19805 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19806 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19808 ;; Cursor keys with modifiers
19809 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19810 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19811 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19812 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19814 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19815 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19816 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19817 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19818 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19819 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19821 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19822 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19823 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19824 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19826 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19827 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19828 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19829 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19831 ;; Babel keys
19832 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19833 (mapc (lambda (pair)
19834 (define-key org-babel-map (car pair) (cdr pair)))
19835 org-babel-key-bindings)
19837 ;;; Extra keys for tty access.
19838 ;; We only set them when really needed because otherwise the
19839 ;; menus don't show the simple keys
19841 (when (or org-use-extra-keys
19842 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19843 (not window-system))
19844 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19845 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19846 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19847 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19848 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19849 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19850 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19851 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19852 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19853 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19854 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19855 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19856 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19857 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19858 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19859 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19860 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19861 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19862 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19863 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19864 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19865 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19866 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19867 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19868 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19869 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19870 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19871 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19873 ;; All the other keys
19875 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19876 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19877 (if (boundp 'narrow-map)
19878 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19879 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19880 (if (boundp 'narrow-map)
19881 (org-defkey narrow-map "b" 'org-narrow-to-block)
19882 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19883 (if (boundp 'narrow-map)
19884 (org-defkey narrow-map "e" 'org-narrow-to-element)
19885 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19886 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19887 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19888 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19889 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19890 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19891 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19892 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19893 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19894 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19895 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19896 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19897 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19898 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19899 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19900 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19901 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19902 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19903 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19904 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19905 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19906 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19907 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19908 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19909 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19910 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19911 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19912 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19913 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19914 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19915 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19916 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19917 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19918 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19919 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19920 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19921 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19922 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19923 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19924 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19925 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19926 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19927 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19928 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19929 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19930 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19931 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19932 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19933 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19934 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19935 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19936 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19937 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19938 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19939 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19940 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19941 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19942 (org-defkey org-mode-map "\C-c^" 'org-sort)
19943 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19944 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19945 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19946 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19947 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19948 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19949 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19950 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19951 (org-defkey org-mode-map "\C-m" 'org-return)
19952 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19953 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19954 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19955 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19956 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19957 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19958 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19959 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19960 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19961 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19962 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19963 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19964 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19965 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19966 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19967 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19968 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19969 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19970 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19971 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19972 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19973 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19974 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19975 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19976 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19978 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19979 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19980 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19982 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19983 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19984 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19985 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19986 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19987 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19988 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19989 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19990 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19991 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19992 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19993 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19994 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19995 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19996 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19997 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19998 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19999 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20000 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20001 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20002 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
20003 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20005 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20006 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20007 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20008 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20009 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20011 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20013 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20015 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20016 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20018 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20021 (when (featurep 'xemacs)
20022 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20025 (defconst org-speed-commands-default
20027 ("Outline Navigation")
20028 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20029 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20030 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20031 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20032 ("F" . org-next-block)
20033 ("B" . org-previous-block)
20034 ("u" . (org-speed-move-safe 'outline-up-heading))
20035 ("j" . org-goto)
20036 ("g" . (org-refile t))
20037 ("Outline Visibility")
20038 ("c" . org-cycle)
20039 ("C" . org-shifttab)
20040 (" " . org-display-outline-path)
20041 ("s" . org-narrow-to-subtree)
20042 ("=" . org-columns)
20043 ("Outline Structure Editing")
20044 ("U" . org-metaup)
20045 ("D" . org-metadown)
20046 ("r" . org-metaright)
20047 ("l" . org-metaleft)
20048 ("R" . org-shiftmetaright)
20049 ("L" . org-shiftmetaleft)
20050 ("i" . (progn (forward-char 1) (call-interactively
20051 'org-insert-heading-respect-content)))
20052 ("^" . org-sort)
20053 ("w" . org-refile)
20054 ("a" . org-archive-subtree-default-with-confirmation)
20055 ("@" . org-mark-subtree)
20056 ("#" . org-toggle-comment)
20057 ("Clock Commands")
20058 ("I" . org-clock-in)
20059 ("O" . org-clock-out)
20060 ("Meta Data Editing")
20061 ("t" . org-todo)
20062 ("," . (org-priority))
20063 ("0" . (org-priority ?\ ))
20064 ("1" . (org-priority ?A))
20065 ("2" . (org-priority ?B))
20066 ("3" . (org-priority ?C))
20067 (":" . org-set-tags-command)
20068 ("e" . org-set-effort)
20069 ("E" . org-inc-effort)
20070 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20071 (org-entry-put (point) "APPT_WARNTIME" m)))
20072 ("Agenda Views etc")
20073 ("v" . org-agenda)
20074 ("/" . org-sparse-tree)
20075 ("Misc")
20076 ("o" . org-open-at-point)
20077 ("?" . org-speed-command-help)
20078 ("<" . (org-agenda-set-restriction-lock 'subtree))
20079 (">" . (org-agenda-remove-restriction-lock))
20081 "The default speed commands.")
20083 (defun org-print-speed-command (e)
20084 (if (> (length (car e)) 1)
20085 (progn
20086 (princ "\n")
20087 (princ (car e))
20088 (princ "\n")
20089 (princ (make-string (length (car e)) ?-))
20090 (princ "\n"))
20091 (princ (car e))
20092 (princ " ")
20093 (if (symbolp (cdr e))
20094 (princ (symbol-name (cdr e)))
20095 (prin1 (cdr e)))
20096 (princ "\n")))
20098 (defun org-speed-command-help ()
20099 "Show the available speed commands."
20100 (interactive)
20101 (if (not org-use-speed-commands)
20102 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20103 (with-output-to-temp-buffer "*Help*"
20104 (princ "User-defined Speed commands\n===========================\n")
20105 (mapc 'org-print-speed-command org-speed-commands-user)
20106 (princ "\n")
20107 (princ "Built-in Speed commands\n=======================\n")
20108 (mapc 'org-print-speed-command org-speed-commands-default))
20109 (with-current-buffer "*Help*"
20110 (setq truncate-lines t))))
20112 (defun org-speed-move-safe (cmd)
20113 "Execute CMD, but make sure that the cursor always ends up in a headline.
20114 If not, return to the original position and throw an error."
20115 (interactive)
20116 (let ((pos (point)))
20117 (call-interactively cmd)
20118 (unless (and (bolp) (org-at-heading-p))
20119 (goto-char pos)
20120 (error "Boundary reached while executing %s" cmd))))
20122 (defvar org-self-insert-command-undo-counter 0)
20124 (defvar org-table-auto-blank-field) ; defined in org-table.el
20125 (defvar org-speed-command nil)
20127 (define-obsolete-function-alias
20128 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20130 (defun org-speed-command-activate (keys)
20131 "Hook for activating single-letter speed commands.
20132 `org-speed-commands-default' specifies a minimal command set.
20133 Use `org-speed-commands-user' for further customization."
20134 (when (or (and (bolp) (looking-at org-outline-regexp))
20135 (and (functionp org-use-speed-commands)
20136 (funcall org-use-speed-commands)))
20137 (cdr (assoc keys (append org-speed-commands-user
20138 org-speed-commands-default)))))
20140 (define-obsolete-function-alias
20141 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20143 (defun org-babel-speed-command-activate (keys)
20144 "Hook for activating single-letter code block commands."
20145 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20146 (cdr (assoc keys org-babel-key-bindings))))
20148 (defcustom org-speed-command-hook
20149 '(org-speed-command-default-hook org-babel-speed-command-hook)
20150 "Hook for activating speed commands at strategic locations.
20151 Hook functions are called in sequence until a valid handler is
20152 found.
20154 Each hook takes a single argument, a user-pressed command key
20155 which is also a `self-insert-command' from the global map.
20157 Within the hook, examine the cursor position and the command key
20158 and return nil or a valid handler as appropriate. Handler could
20159 be one of an interactive command, a function, or a form.
20161 Set `org-use-speed-commands' to non-nil value to enable this
20162 hook. The default setting is `org-speed-command-activate'."
20163 :group 'org-structure
20164 :version "24.1"
20165 :type 'hook)
20167 (defun org-self-insert-command (N)
20168 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20169 If the cursor is in a table looking at whitespace, the whitespace is
20170 overwritten, and the table is not marked as requiring realignment."
20171 (interactive "p")
20172 (org-check-before-invisible-edit 'insert)
20173 (cond
20174 ((and org-use-speed-commands
20175 (let ((kv (this-command-keys-vector)))
20176 (setq org-speed-command
20177 (run-hook-with-args-until-success
20178 'org-speed-command-hook
20179 (make-string 1 (aref kv (1- (length kv))))))))
20180 (cond
20181 ((commandp org-speed-command)
20182 (setq this-command org-speed-command)
20183 (call-interactively org-speed-command))
20184 ((functionp org-speed-command)
20185 (funcall org-speed-command))
20186 ((and org-speed-command (listp org-speed-command))
20187 (eval org-speed-command))
20188 (t (let (org-use-speed-commands)
20189 (call-interactively 'org-self-insert-command)))))
20190 ((and
20191 (org-at-table-p)
20192 (progn
20193 ;; Check if we blank the field, and if that triggers align.
20194 (and (featurep 'org-table) org-table-auto-blank-field
20195 (memq last-command
20196 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20197 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20198 ;; Got extra space, this field does not determine
20199 ;; column width.
20200 (let (org-table-may-need-update) (org-table-blank-field))
20201 ;; No extra space, this field may determine column
20202 ;; width.
20203 (org-table-blank-field)))
20205 (eq N 1)
20206 (looking-at "[^|\n]* \\( \\)|"))
20207 ;; There is room for insertion without re-aligning the table.
20208 (delete-region (match-beginning 1) (match-end 1))
20209 (self-insert-command N))
20211 (setq org-table-may-need-update t)
20212 (self-insert-command N)
20213 (org-fix-tags-on-the-fly)
20214 (when org-self-insert-cluster-for-undo
20215 (if (not (eq last-command 'org-self-insert-command))
20216 (setq org-self-insert-command-undo-counter 1)
20217 (if (>= org-self-insert-command-undo-counter 20)
20218 (setq org-self-insert-command-undo-counter 1)
20219 (and (> org-self-insert-command-undo-counter 0)
20220 buffer-undo-list (listp buffer-undo-list)
20221 (not (cadr buffer-undo-list)) ; remove nil entry
20222 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20223 (setq org-self-insert-command-undo-counter
20224 (1+ org-self-insert-command-undo-counter))))))))
20226 (defun org-check-before-invisible-edit (kind)
20227 "Check is editing if kind KIND would be dangerous with invisible text around.
20228 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20229 ;; First, try to get out of here as quickly as possible, to reduce overhead
20230 (when (and org-catch-invisible-edits
20231 (or (not (boundp 'visible-mode)) (not visible-mode))
20232 (or (get-char-property (point) 'invisible)
20233 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20234 ;; OK, we need to take a closer look
20235 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20236 (invisible-before-point (unless (bobp) (get-char-property
20237 (1- (point)) 'invisible)))
20238 (border-and-ok-direction
20240 ;; Check if we are acting predictably before invisible text
20241 (and invisible-at-point (not invisible-before-point)
20242 (memq kind '(insert delete-backward)))
20243 ;; Check if we are acting predictably after invisible text
20244 ;; This works not well, and I have turned it off. It seems
20245 ;; better to always show and stop after invisible text.
20246 ;; (and (not invisible-at-point) invisible-before-point
20247 ;; (memq kind '(insert delete)))
20249 (when (or (memq invisible-at-point '(outline org-hide-block t))
20250 (memq invisible-before-point '(outline org-hide-block t)))
20251 (when (eq org-catch-invisible-edits 'error)
20252 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20253 (if (and org-custom-properties-overlays
20254 (y-or-n-p "Display invisible properties in this buffer? "))
20255 (org-toggle-custom-properties-visibility)
20256 ;; Make the area visible
20257 (save-excursion
20258 (when invisible-before-point
20259 (goto-char (previous-single-char-property-change
20260 (point) 'invisible)))
20261 (outline-show-subtree))
20262 (cond
20263 ((eq org-catch-invisible-edits 'show)
20264 ;; That's it, we do the edit after showing
20265 (message
20266 "Unfolding invisible region around point before editing")
20267 (sit-for 1))
20268 ((and (eq org-catch-invisible-edits 'smart)
20269 border-and-ok-direction)
20270 (message "Unfolding invisible region around point before editing"))
20272 ;; Don't do the edit, make the user repeat it in full visibility
20273 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20275 (defun org-fix-tags-on-the-fly ()
20276 (when (and (equal (char-after (point-at-bol)) ?*)
20277 (org-at-heading-p))
20278 (org-align-tags-here org-tags-column)))
20280 (defun org-delete-backward-char (N)
20281 "Like `delete-backward-char', insert whitespace at field end in tables.
20282 When deleting backwards, in tables this function will insert whitespace in
20283 front of the next \"|\" separator, to keep the table aligned. The table will
20284 still be marked for re-alignment if the field did fill the entire column,
20285 because, in this case the deletion might narrow the column."
20286 (interactive "p")
20287 (save-match-data
20288 (org-check-before-invisible-edit 'delete-backward)
20289 (if (and (org-at-table-p)
20290 (eq N 1)
20291 (string-match "|" (buffer-substring (point-at-bol) (point)))
20292 (looking-at ".*?|"))
20293 (let ((pos (point))
20294 (noalign (looking-at "[^|\n\r]* |"))
20295 (c org-table-may-need-update))
20296 (backward-delete-char N)
20297 (unless overwrite-mode
20298 (skip-chars-forward "^|")
20299 (insert " ")
20300 (goto-char (1- pos)))
20301 ;; noalign: if there were two spaces at the end, this field
20302 ;; does not determine the width of the column.
20303 (when noalign (setq org-table-may-need-update c)))
20304 (backward-delete-char N)
20305 (org-fix-tags-on-the-fly))))
20307 (defun org-delete-char (N)
20308 "Like `delete-char', but insert whitespace at field end in tables.
20309 When deleting characters, in tables this function will insert whitespace in
20310 front of the next \"|\" separator, to keep the table aligned. The table will
20311 still be marked for re-alignment if the field did fill the entire column,
20312 because, in this case the deletion might narrow the column."
20313 (interactive "p")
20314 (save-match-data
20315 (org-check-before-invisible-edit 'delete)
20316 (if (and (org-at-table-p)
20317 (not (bolp))
20318 (not (= (char-after) ?|))
20319 (eq N 1))
20320 (if (looking-at ".*?|")
20321 (let ((pos (point))
20322 (noalign (looking-at "[^|\n\r]* |"))
20323 (c org-table-may-need-update))
20324 (replace-match
20325 (concat (substring (match-string 0) 1 -1) " |") nil t)
20326 (goto-char pos)
20327 ;; noalign: if there were two spaces at the end, this field
20328 ;; does not determine the width of the column.
20329 (when noalign (setq org-table-may-need-update c)))
20330 (delete-char N))
20331 (delete-char N)
20332 (org-fix-tags-on-the-fly))))
20334 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20335 (put 'org-self-insert-command 'delete-selection
20336 (lambda ()
20337 (not (run-hook-with-args-until-success
20338 'self-insert-uses-region-functions))))
20339 (put 'orgtbl-self-insert-command 'delete-selection
20340 (lambda ()
20341 (not (run-hook-with-args-until-success
20342 'self-insert-uses-region-functions))))
20343 (put 'org-delete-char 'delete-selection 'supersede)
20344 (put 'org-delete-backward-char 'delete-selection 'supersede)
20345 (put 'org-yank 'delete-selection 'yank)
20347 ;; Make `flyspell-mode' delay after some commands
20348 (put 'org-self-insert-command 'flyspell-delayed t)
20349 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20350 (put 'org-delete-char 'flyspell-delayed t)
20351 (put 'org-delete-backward-char 'flyspell-delayed t)
20353 ;; Make pabbrev-mode expand after org-mode commands
20354 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20355 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20357 (defun org-remap (map &rest commands)
20358 "In MAP, remap the functions given in COMMANDS.
20359 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20360 (let (new old)
20361 (while commands
20362 (setq old (pop commands) new (pop commands))
20363 (if (fboundp 'command-remapping)
20364 (org-defkey map (vector 'remap old) new)
20365 (substitute-key-definition old new map global-map)))))
20367 (defun org-transpose-words ()
20368 "Transpose words for Org.
20369 This uses the `org-mode-transpose-word-syntax-table' syntax
20370 table, which interprets characters in `org-emphasis-alist' as
20371 word constituents."
20372 (interactive)
20373 (with-syntax-table org-mode-transpose-word-syntax-table
20374 (call-interactively 'transpose-words)))
20375 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20377 (when (eq org-enable-table-editor 'optimized)
20378 ;; If the user wants maximum table support, we need to hijack
20379 ;; some standard editing functions
20380 (org-remap org-mode-map
20381 'self-insert-command 'org-self-insert-command
20382 'delete-char 'org-delete-char
20383 'delete-backward-char 'org-delete-backward-char)
20384 (org-defkey org-mode-map "|" 'org-force-self-insert))
20386 (defvar org-ctrl-c-ctrl-c-hook nil
20387 "Hook for functions attaching themselves to `C-c C-c'.
20389 This can be used to add additional functionality to the C-c C-c
20390 key which executes context-dependent commands. This hook is run
20391 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20392 run after the last test.
20394 Each function will be called with no arguments. The function
20395 must check if the context is appropriate for it to act. If yes,
20396 it should do its thing and then return a non-nil value. If the
20397 context is wrong, just do nothing and return nil.")
20399 (defvar org-ctrl-c-ctrl-c-final-hook nil
20400 "Hook for functions attaching themselves to `C-c C-c'.
20402 This can be used to add additional functionality to the C-c C-c
20403 key which executes context-dependent commands. This hook is run
20404 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20405 before the first test.
20407 Each function will be called with no arguments. The function
20408 must check if the context is appropriate for it to act. If yes,
20409 it should do its thing and then return a non-nil value. If the
20410 context is wrong, just do nothing and return nil.")
20412 (defvar org-tab-first-hook nil
20413 "Hook for functions to attach themselves to TAB.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.
20415 This hook runs as the first action when TAB is pressed, even before
20416 `org-cycle' messes around with the `outline-regexp' to cater for
20417 inline tasks and plain list item folding.
20418 If any function in this hook returns t, any other actions that
20419 would have been caused by TAB (such as table field motion or visibility
20420 cycling) will not occur.")
20422 (defvar org-tab-after-check-for-table-hook nil
20423 "Hook for functions to attach themselves to TAB.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.
20425 This hook runs after it has been established that the cursor is not in a
20426 table, but before checking if the cursor is in a headline or if global cycling
20427 should be done.
20428 If any function in this hook returns t, not other actions like visibility
20429 cycling will be done.")
20431 (defvar org-tab-after-check-for-cycling-hook nil
20432 "Hook for functions to attach themselves to TAB.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.
20434 This hook runs after it has been established that not table field motion and
20435 not visibility should be done because of current context. This is probably
20436 the place where a package like yasnippets can hook in.")
20438 (defvar org-tab-before-tab-emulation-hook nil
20439 "Hook for functions to attach themselves to TAB.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.
20441 This hook runs after every other options for TAB have been exhausted, but
20442 before indentation and \t insertion takes place.")
20444 (defvar org-metaleft-hook nil
20445 "Hook for functions attaching themselves to `M-left'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-metaright-hook nil
20448 "Hook for functions attaching themselves to `M-right'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-metaup-hook nil
20451 "Hook for functions attaching themselves to `M-up'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-metadown-hook nil
20454 "Hook for functions attaching themselves to `M-down'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftmetaleft-hook nil
20457 "Hook for functions attaching themselves to `M-S-left'.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftmetaright-hook nil
20460 "Hook for functions attaching themselves to `M-S-right'.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftmetaup-hook nil
20463 "Hook for functions attaching themselves to `M-S-up'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftmetadown-hook nil
20466 "Hook for functions attaching themselves to `M-S-down'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-metareturn-hook nil
20469 "Hook for functions attaching themselves to `M-RET'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-shiftup-hook nil
20472 "Hook for functions attaching themselves to `S-up'.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.")
20474 (defvar org-shiftup-final-hook nil
20475 "Hook for functions attaching themselves to `S-up'.
20476 This one runs after all other options except shift-select have been excluded.
20477 See `org-ctrl-c-ctrl-c-hook' for more information.")
20478 (defvar org-shiftdown-hook nil
20479 "Hook for functions attaching themselves to `S-down'.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.")
20481 (defvar org-shiftdown-final-hook nil
20482 "Hook for functions attaching themselves to `S-down'.
20483 This one runs after all other options except shift-select have been excluded.
20484 See `org-ctrl-c-ctrl-c-hook' for more information.")
20485 (defvar org-shiftleft-hook nil
20486 "Hook for functions attaching themselves to `S-left'.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.")
20488 (defvar org-shiftleft-final-hook nil
20489 "Hook for functions attaching themselves to `S-left'.
20490 This one runs after all other options except shift-select have been excluded.
20491 See `org-ctrl-c-ctrl-c-hook' for more information.")
20492 (defvar org-shiftright-hook nil
20493 "Hook for functions attaching themselves to `S-right'.
20494 See `org-ctrl-c-ctrl-c-hook' for more information.")
20495 (defvar org-shiftright-final-hook nil
20496 "Hook for functions attaching themselves to `S-right'.
20497 This one runs after all other options except shift-select have been excluded.
20498 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defun org-modifier-cursor-error ()
20501 "Throw an error, a modified cursor command was applied in wrong context."
20502 (user-error "This command is active in special context like tables, headlines or items"))
20504 (defun org-shiftselect-error ()
20505 "Throw an error because Shift-Cursor command was applied in wrong context."
20506 (if (and (boundp 'shift-select-mode) shift-select-mode)
20507 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20508 (user-error "This command works only in special context like headlines or timestamps")))
20510 (defun org-call-for-shift-select (cmd)
20511 (let ((this-command-keys-shift-translated t))
20512 (call-interactively cmd)))
20514 (defun org-shifttab (&optional arg)
20515 "Global visibility cycling or move to previous table field.
20516 Call `org-table-previous-field' within a table.
20517 When ARG is nil, cycle globally through visibility states.
20518 When ARG is a numeric prefix, show contents of this level."
20519 (interactive "P")
20520 (cond
20521 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20522 ((integerp arg)
20523 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20524 (message "Content view to level: %d" arg)
20525 (org-content (prefix-numeric-value arg2))
20526 (org-cycle-show-empty-lines t)
20527 (setq org-cycle-global-status 'overview)))
20528 (t (call-interactively 'org-global-cycle))))
20530 (defun org-shiftmetaleft ()
20531 "Promote subtree or delete table column.
20532 Calls `org-promote-subtree', `org-outdent-item-tree', or
20533 `org-table-delete-column', depending on context. See the
20534 individual commands for more information."
20535 (interactive)
20536 (cond
20537 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20538 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20539 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20540 ((if (not (org-region-active-p)) (org-at-item-p)
20541 (save-excursion (goto-char (region-beginning))
20542 (org-at-item-p)))
20543 (call-interactively 'org-outdent-item-tree))
20544 (t (org-modifier-cursor-error))))
20546 (defun org-shiftmetaright ()
20547 "Demote subtree or insert table column.
20548 Calls `org-demote-subtree', `org-indent-item-tree', or
20549 `org-table-insert-column', depending on context. See the
20550 individual commands for more information."
20551 (interactive)
20552 (cond
20553 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20554 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20555 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20556 ((if (not (org-region-active-p)) (org-at-item-p)
20557 (save-excursion (goto-char (region-beginning))
20558 (org-at-item-p)))
20559 (call-interactively 'org-indent-item-tree))
20560 (t (org-modifier-cursor-error))))
20562 (defun org-shiftmetaup (&optional arg)
20563 "Drag the line at point up.
20564 In a table, kill the current row.
20565 On a clock timestamp, update the value of the timestamp like `S-<up>'
20566 but also adjust the previous clocked item in the clock history.
20567 Everywhere else, drag the line at point up."
20568 (interactive "P")
20569 (cond
20570 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20571 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20572 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20573 (call-interactively 'org-timestamp-up)))
20574 (t (call-interactively 'org-drag-line-backward))))
20576 (defun org-shiftmetadown (&optional arg)
20577 "Drag the line at point down.
20578 In a table, insert an empty row at the current line.
20579 On a clock timestamp, update the value of the timestamp like `S-<down>'
20580 but also adjust the previous clocked item in the clock history.
20581 Everywhere else, drag the line at point down."
20582 (interactive "P")
20583 (cond
20584 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20585 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20586 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20587 (call-interactively 'org-timestamp-down)))
20588 (t (call-interactively 'org-drag-line-forward))))
20590 (defsubst org-hidden-tree-error ()
20591 (user-error
20592 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20594 (defun org-metaleft (&optional arg)
20595 "Promote heading, list item at point or move table column left.
20597 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20598 depending on context. With no specific context, calls the Emacs
20599 default `backward-word'. See the individual commands for more
20600 information.
20602 This function runs the hook `org-metaleft-hook' as a first step,
20603 and returns at first non-nil value."
20604 (interactive "P")
20605 (cond
20606 ((run-hook-with-args-until-success 'org-metaleft-hook))
20607 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20608 ((org-with-limited-levels
20609 (or (org-at-heading-p)
20610 (and (org-region-active-p)
20611 (save-excursion
20612 (goto-char (region-beginning))
20613 (org-at-heading-p)))))
20614 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20615 (call-interactively 'org-do-promote))
20616 ;; At an inline task.
20617 ((org-at-heading-p)
20618 (call-interactively 'org-inlinetask-promote))
20619 ((or (org-at-item-p)
20620 (and (org-region-active-p)
20621 (save-excursion
20622 (goto-char (region-beginning))
20623 (org-at-item-p))))
20624 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20625 (call-interactively 'org-outdent-item))
20626 (t (call-interactively 'backward-word))))
20628 (defun org-metaright (&optional arg)
20629 "Demote heading, list item at point or move table column right.
20631 In front of a drawer or a block keyword, indent it correctly.
20633 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20634 `org-indnet-drawer' or `org-indent-block' depending on context.
20635 With no specific context, calls the Emacs default `forward-word'.
20636 See the individual commands for more information.
20638 This function runs the hook `org-metaright-hook' as a first step,
20639 and returns at first non-nil value."
20640 (interactive "P")
20641 (cond
20642 ((run-hook-with-args-until-success 'org-metaright-hook))
20643 ((org-at-table-p) (call-interactively 'org-table-move-column))
20644 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20645 ((org-at-block-p) (call-interactively 'org-indent-block))
20646 ((org-with-limited-levels
20647 (or (org-at-heading-p)
20648 (and (org-region-active-p)
20649 (save-excursion
20650 (goto-char (region-beginning))
20651 (org-at-heading-p)))))
20652 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20653 (call-interactively 'org-do-demote))
20654 ;; At an inline task.
20655 ((org-at-heading-p)
20656 (call-interactively 'org-inlinetask-demote))
20657 ((or (org-at-item-p)
20658 (and (org-region-active-p)
20659 (save-excursion
20660 (goto-char (region-beginning))
20661 (org-at-item-p))))
20662 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20663 (call-interactively 'org-indent-item))
20664 (t (call-interactively 'forward-word))))
20666 (defun org-check-for-hidden (what)
20667 "Check if there are hidden headlines/items in the current visual line.
20668 WHAT can be either `headlines' or `items'. If the current line is
20669 an outline or item heading and it has a folded subtree below it,
20670 this function returns t, nil otherwise."
20671 (let ((re (cond
20672 ((eq what 'headlines) org-outline-regexp-bol)
20673 ((eq what 'items) (org-item-beginning-re))
20674 (t (error "This should not happen"))))
20675 beg end)
20676 (save-excursion
20677 (catch 'exit
20678 (unless (org-region-active-p)
20679 (setq beg (point-at-bol))
20680 (beginning-of-line 2)
20681 (while (and (not (eobp)) ;; this is like `next-line'
20682 (get-char-property (1- (point)) 'invisible))
20683 (beginning-of-line 2))
20684 (setq end (point))
20685 (goto-char beg)
20686 (goto-char (point-at-eol))
20687 (setq end (max end (point)))
20688 (while (re-search-forward re end t)
20689 (when (get-char-property (match-beginning 0) 'invisible)
20690 (throw 'exit t))))
20691 nil))))
20693 (defun org-metaup (&optional arg)
20694 "Move subtree up or move table row up.
20695 Calls `org-move-subtree-up' or `org-table-move-row' or
20696 `org-move-item-up', depending on context. See the individual commands
20697 for more information."
20698 (interactive "P")
20699 (cond
20700 ((run-hook-with-args-until-success 'org-metaup-hook))
20701 ((org-region-active-p)
20702 (let* ((a (min (region-beginning) (region-end)))
20703 (b (1- (max (region-beginning) (region-end))))
20704 (c (save-excursion (goto-char a)
20705 (move-beginning-of-line 0)))
20706 (d (save-excursion (goto-char a)
20707 (move-end-of-line 0) (point))))
20708 (transpose-regions a b c d)
20709 (goto-char c)))
20710 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20711 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20712 ((org-at-item-p) (call-interactively 'org-move-item-up))
20713 (t (org-drag-element-backward))))
20715 (defun org-metadown (&optional arg)
20716 "Move subtree down or move table row down.
20717 Calls `org-move-subtree-down' or `org-table-move-row' or
20718 `org-move-item-down', depending on context. See the individual
20719 commands for more information."
20720 (interactive "P")
20721 (cond
20722 ((run-hook-with-args-until-success 'org-metadown-hook))
20723 ((org-region-active-p)
20724 (let* ((a (min (region-beginning) (region-end)))
20725 (b (max (region-beginning) (region-end)))
20726 (c (save-excursion (goto-char b)
20727 (move-beginning-of-line 1)))
20728 (d (save-excursion (goto-char b)
20729 (move-end-of-line 1) (1+ (point)))))
20730 (transpose-regions a b c d)
20731 (goto-char d)))
20732 ((org-at-table-p) (call-interactively 'org-table-move-row))
20733 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20734 ((org-at-item-p) (call-interactively 'org-move-item-down))
20735 (t (org-drag-element-forward))))
20737 (defun org-shiftup (&optional arg)
20738 "Increase item in timestamp or increase priority of current headline.
20739 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20740 depending on context. See the individual commands for more information."
20741 (interactive "P")
20742 (cond
20743 ((run-hook-with-args-until-success 'org-shiftup-hook))
20744 ((and org-support-shift-select (org-region-active-p))
20745 (org-call-for-shift-select 'previous-line))
20746 ((org-at-timestamp-p t)
20747 (call-interactively (if org-edit-timestamp-down-means-later
20748 'org-timestamp-down 'org-timestamp-up)))
20749 ((and (not (eq org-support-shift-select 'always))
20750 org-enable-priority-commands
20751 (org-at-heading-p))
20752 (call-interactively 'org-priority-up))
20753 ((and (not org-support-shift-select) (org-at-item-p))
20754 (call-interactively 'org-previous-item))
20755 ((org-clocktable-try-shift 'up arg))
20756 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20757 (org-support-shift-select
20758 (org-call-for-shift-select 'previous-line))
20759 (t (org-shiftselect-error))))
20761 (defun org-shiftdown (&optional arg)
20762 "Decrease item in timestamp or decrease priority of current headline.
20763 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20764 depending on context. See the individual commands for more information."
20765 (interactive "P")
20766 (cond
20767 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20768 ((and org-support-shift-select (org-region-active-p))
20769 (org-call-for-shift-select 'next-line))
20770 ((org-at-timestamp-p t)
20771 (call-interactively (if org-edit-timestamp-down-means-later
20772 'org-timestamp-up 'org-timestamp-down)))
20773 ((and (not (eq org-support-shift-select 'always))
20774 org-enable-priority-commands
20775 (org-at-heading-p))
20776 (call-interactively 'org-priority-down))
20777 ((and (not org-support-shift-select) (org-at-item-p))
20778 (call-interactively 'org-next-item))
20779 ((org-clocktable-try-shift 'down arg))
20780 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20781 (org-support-shift-select
20782 (org-call-for-shift-select 'next-line))
20783 (t (org-shiftselect-error))))
20785 (defun org-shiftright (&optional arg)
20786 "Cycle the thing at point or in the current line, depending on context.
20787 Depending on context, this does one of the following:
20789 - switch a timestamp at point one day into the future
20790 - on a headline, switch to the next TODO keyword.
20791 - on an item, switch entire list to the next bullet type
20792 - on a property line, switch to the next allowed value
20793 - on a clocktable definition line, move time block into the future"
20794 (interactive "P")
20795 (cond
20796 ((run-hook-with-args-until-success 'org-shiftright-hook))
20797 ((and org-support-shift-select (org-region-active-p))
20798 (org-call-for-shift-select 'forward-char))
20799 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20800 ((and (not (eq org-support-shift-select 'always))
20801 (org-at-heading-p))
20802 (let ((org-inhibit-logging
20803 (not org-treat-S-cursor-todo-selection-as-state-change))
20804 (org-inhibit-blocking
20805 (not org-treat-S-cursor-todo-selection-as-state-change)))
20806 (org-call-with-arg 'org-todo 'right)))
20807 ((or (and org-support-shift-select
20808 (not (eq org-support-shift-select 'always))
20809 (org-at-item-bullet-p))
20810 (and (not org-support-shift-select) (org-at-item-p)))
20811 (org-call-with-arg 'org-cycle-list-bullet nil))
20812 ((and (not (eq org-support-shift-select 'always))
20813 (org-at-property-p))
20814 (call-interactively 'org-property-next-allowed-value))
20815 ((org-clocktable-try-shift 'right arg))
20816 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20817 (org-support-shift-select
20818 (org-call-for-shift-select 'forward-char))
20819 (t (org-shiftselect-error))))
20821 (defun org-shiftleft (&optional arg)
20822 "Cycle the thing at point or in the current line, depending on context.
20823 Depending on context, this does one of the following:
20825 - switch a timestamp at point one day into the past
20826 - on a headline, switch to the previous TODO keyword.
20827 - on an item, switch entire list to the previous bullet type
20828 - on a property line, switch to the previous allowed value
20829 - on a clocktable definition line, move time block into the past"
20830 (interactive "P")
20831 (cond
20832 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20833 ((and org-support-shift-select (org-region-active-p))
20834 (org-call-for-shift-select 'backward-char))
20835 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20836 ((and (not (eq org-support-shift-select 'always))
20837 (org-at-heading-p))
20838 (let ((org-inhibit-logging
20839 (not org-treat-S-cursor-todo-selection-as-state-change))
20840 (org-inhibit-blocking
20841 (not org-treat-S-cursor-todo-selection-as-state-change)))
20842 (org-call-with-arg 'org-todo 'left)))
20843 ((or (and org-support-shift-select
20844 (not (eq org-support-shift-select 'always))
20845 (org-at-item-bullet-p))
20846 (and (not org-support-shift-select) (org-at-item-p)))
20847 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20848 ((and (not (eq org-support-shift-select 'always))
20849 (org-at-property-p))
20850 (call-interactively 'org-property-previous-allowed-value))
20851 ((org-clocktable-try-shift 'left arg))
20852 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20853 (org-support-shift-select
20854 (org-call-for-shift-select 'backward-char))
20855 (t (org-shiftselect-error))))
20857 (defun org-shiftcontrolright ()
20858 "Switch to next TODO set."
20859 (interactive)
20860 (cond
20861 ((and org-support-shift-select (org-region-active-p))
20862 (org-call-for-shift-select 'forward-word))
20863 ((and (not (eq org-support-shift-select 'always))
20864 (org-at-heading-p))
20865 (org-call-with-arg 'org-todo 'nextset))
20866 (org-support-shift-select
20867 (org-call-for-shift-select 'forward-word))
20868 (t (org-shiftselect-error))))
20870 (defun org-shiftcontrolleft ()
20871 "Switch to previous TODO set."
20872 (interactive)
20873 (cond
20874 ((and org-support-shift-select (org-region-active-p))
20875 (org-call-for-shift-select 'backward-word))
20876 ((and (not (eq org-support-shift-select 'always))
20877 (org-at-heading-p))
20878 (org-call-with-arg 'org-todo 'previousset))
20879 (org-support-shift-select
20880 (org-call-for-shift-select 'backward-word))
20881 (t (org-shiftselect-error))))
20883 (defun org-shiftcontrolup (&optional n)
20884 "Change timestamps synchronously up in CLOCK log lines.
20885 Optional argument N tells to change by that many units."
20886 (interactive "P")
20887 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20888 (let (org-support-shift-select)
20889 (org-clock-timestamps-up n))
20890 (user-error "Not at a clock log")))
20892 (defun org-shiftcontroldown (&optional n)
20893 "Change timestamps synchronously down in CLOCK log lines.
20894 Optional argument N tells to change by that many units."
20895 (interactive "P")
20896 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20897 (let (org-support-shift-select)
20898 (org-clock-timestamps-down n))
20899 (user-error "Not at a clock log")))
20901 (defun org-increase-number-at-point (&optional inc)
20902 "Increment the number at point.
20903 With an optional prefix numeric argument INC, increment using
20904 this numeric value."
20905 (interactive "p")
20906 (if (not (number-at-point))
20907 (user-error "Not on a number")
20908 (unless inc (setq inc 1))
20909 (let ((pos (point))
20910 (beg (skip-chars-backward "-+^/*0-9eE."))
20911 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20912 (setq nap (buffer-substring-no-properties
20913 (+ pos beg) (+ pos beg end)))
20914 (delete-region (+ pos beg) (+ pos beg end))
20915 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20916 (when (org-at-table-p)
20917 (org-table-align)
20918 (org-table-end-of-field 1))))
20920 (defun org-decrease-number-at-point (&optional inc)
20921 "Decrement the number at point.
20922 With an optional prefix numeric argument INC, decrement using
20923 this numeric value."
20924 (interactive "p")
20925 (org-increase-number-at-point (- (or inc 1))))
20927 (defun org-ctrl-c-ret ()
20928 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20929 (interactive)
20930 (cond
20931 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20932 (t (call-interactively 'org-insert-heading))))
20934 (defun org-find-visible ()
20935 (let ((s (point)))
20936 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20937 (get-char-property s 'invisible)))
20939 (defun org-find-invisible ()
20940 (let ((s (point)))
20941 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20942 (not (get-char-property s 'invisible))))
20945 (defun org-copy-visible (beg end)
20946 "Copy the visible parts of the region."
20947 (interactive "r")
20948 (let (snippets s)
20949 (save-excursion
20950 (save-restriction
20951 (narrow-to-region beg end)
20952 (setq s (goto-char (point-min)))
20953 (while (not (= (point) (point-max)))
20954 (goto-char (org-find-invisible))
20955 (push (buffer-substring s (point)) snippets)
20956 (setq s (goto-char (org-find-visible))))))
20957 (kill-new (apply 'concat (nreverse snippets)))))
20959 (defun org-copy-special ()
20960 "Copy region in table or copy current subtree.
20961 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20962 See the individual commands for more information."
20963 (interactive)
20964 (call-interactively
20965 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20967 (defun org-cut-special ()
20968 "Cut region in table or cut current subtree.
20969 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20970 See the individual commands for more information."
20971 (interactive)
20972 (call-interactively
20973 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20975 (defun org-paste-special (arg)
20976 "Paste rectangular region into table, or past subtree relative to level.
20977 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20978 See the individual commands for more information."
20979 (interactive "P")
20980 (if (org-at-table-p)
20981 (org-table-paste-rectangle)
20982 (org-paste-subtree arg)))
20984 (defsubst org-in-fixed-width-region-p ()
20985 "Is point in a fixed-width region?"
20986 (save-match-data
20987 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20989 (defun org-edit-special (&optional arg)
20990 "Call a special editor for the element at point.
20991 When at a table, call the formula editor with `org-table-edit-formulas'.
20992 When in a source code block, call `org-edit-src-code'.
20993 When in a fixed-width region, call `org-edit-fixed-width-region'.
20994 When in an export block, call `org-edit-export-block'.
20995 When at an #+INCLUDE keyword, visit the included file.
20996 When at a footnote reference, call `org-edit-footnote-reference'
20997 On a link, call `ffap' to visit the link at point.
20998 Otherwise, return a user error."
20999 (interactive "P")
21000 (let ((element (org-element-at-point)))
21001 (assert (not buffer-read-only) nil
21002 "Buffer is read-only: %s" (buffer-name))
21003 (pcase (org-element-type element)
21004 (`src-block
21005 (if (not arg) (org-edit-src-code)
21006 (let* ((info (org-babel-get-src-block-info))
21007 (lang (nth 0 info))
21008 (params (nth 2 info))
21009 (session (cdr (assq :session params))))
21010 (if (not session) (org-edit-src-code)
21011 ;; At a src-block with a session and function called with
21012 ;; an ARG: switch to the buffer related to the inferior
21013 ;; process.
21014 (switch-to-buffer
21015 (funcall (intern (concat "org-babel-prep-session:" lang))
21016 session params))))))
21017 (`keyword
21018 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21019 (org-open-link-from-string
21020 (format "[[%s]]"
21021 (expand-file-name
21022 (let ((value (org-element-property :value element)))
21023 (cond ((not (org-string-nw-p value))
21024 (user-error "No file to edit"))
21025 ((string-match "\\`\"\\(.*?\\)\"" value)
21026 (match-string 1 value))
21027 ((string-match "\\`[^ \t\"]\\S-*" value)
21028 (match-string 0 value))
21029 (t (user-error "No valid file specified")))))))
21030 (user-error "No special environment to edit here")))
21031 (`table
21032 (if (eq (org-element-property :type element) 'table.el)
21033 (org-edit-table.el)
21034 (call-interactively 'org-table-edit-formulas)))
21035 ;; Only Org tables contain `table-row' type elements.
21036 (`table-row (call-interactively 'org-table-edit-formulas))
21037 (`example-block (org-edit-src-code))
21038 (`export-block (org-edit-export-block))
21039 (`fixed-width (org-edit-fixed-width-region))
21041 ;; No notable element at point. Though, we may be at a link or
21042 ;; a footnote reference, which are objects. Thus, scan deeper.
21043 (let ((context (org-element-context element)))
21044 (pcase (org-element-type context)
21045 (`footnote-reference (org-edit-footnote-reference))
21046 (`inline-src-block (org-edit-inline-src-code))
21047 (`link (call-interactively #'ffap))
21048 (_ (user-error "No special environment to edit here"))))))))
21050 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21051 (defun org-ctrl-c-ctrl-c (&optional arg)
21052 "Set tags in headline, or update according to changed information at point.
21054 This command does many different things, depending on context:
21056 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21057 this is what we do.
21059 - If the cursor is on a statistics cookie, update it.
21061 - If the cursor is in a headline, prompt for tags and insert them
21062 into the current line, aligned to `org-tags-column'. When called
21063 with prefix arg, realign all tags in the current buffer.
21065 - If the cursor is in one of the special #+KEYWORD lines, this
21066 triggers scanning the buffer for these lines and updating the
21067 information.
21069 - If the cursor is inside a table, realign the table. This command
21070 works even if the automatic table editor has been turned off.
21072 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21073 the entire table.
21075 - If the cursor is at a footnote reference or definition, jump to
21076 the corresponding definition or references, respectively.
21078 - If the cursor is a the beginning of a dynamic block, update it.
21080 - If the current buffer is a capture buffer, close note and file it.
21082 - If the cursor is on a <<<target>>>, update radio targets and
21083 corresponding links in this buffer.
21085 - If the cursor is on a numbered item in a plain list, renumber the
21086 ordered list.
21088 - If the cursor is on a checkbox, toggle it.
21090 - If the cursor is on a code block, evaluate it. The variable
21091 `org-confirm-babel-evaluate' can be used to control prompting
21092 before code block evaluation, by default every code block
21093 evaluation requires confirmation. Code block evaluation can be
21094 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21095 (interactive "P")
21096 (cond
21097 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21098 org-occur-highlights)
21099 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21100 (org-remove-occur-highlights)
21101 (message "Temporary highlights/overlays removed from current buffer"))
21102 ((and (local-variable-p 'org-finish-function (current-buffer))
21103 (fboundp org-finish-function))
21104 (funcall org-finish-function))
21105 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21107 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21108 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21109 (user-error "C-c C-c can do nothing useful at this location"))
21110 (let* ((context (org-element-context))
21111 (type (org-element-type context)))
21112 (case type
21113 ;; When at a link, act according to the parent instead.
21114 (link (setq context (org-element-property :parent context))
21115 (setq type (org-element-type context)))
21116 ;; Unsupported object types: refer to the first supported
21117 ;; element or object containing it.
21118 ((bold code entity export-snippet inline-babel-call inline-src-block
21119 italic latex-fragment line-break macro strike-through subscript
21120 superscript underline verbatim)
21121 (setq context
21122 (org-element-lineage
21123 context '(radio-target paragraph verse-block table-cell)))))
21124 ;; For convenience: at the first line of a paragraph on the
21125 ;; same line as an item, apply function on that item instead.
21126 (when (eq type 'paragraph)
21127 (let ((parent (org-element-property :parent context)))
21128 (when (and (eq (org-element-type parent) 'item)
21129 (= (line-beginning-position)
21130 (org-element-property :begin parent)))
21131 (setq context parent type 'item))))
21132 ;; Act according to type of element or object at point.
21133 (case type
21134 (clock (org-clock-update-time-maybe))
21135 (dynamic-block
21136 (save-excursion
21137 (goto-char (org-element-property :post-affiliated context))
21138 (org-update-dblock)))
21139 (footnote-definition
21140 (goto-char (org-element-property :post-affiliated context))
21141 (call-interactively 'org-footnote-action))
21142 (footnote-reference (call-interactively 'org-footnote-action))
21143 ((headline inlinetask)
21144 (save-excursion (goto-char (org-element-property :begin context))
21145 (call-interactively 'org-set-tags)))
21146 (item
21147 ;; At an item: a double C-u set checkbox to "[-]"
21148 ;; unconditionally, whereas a single one will toggle its
21149 ;; presence. Without a universal argument, if the item
21150 ;; has a checkbox, toggle it. Otherwise repair the list.
21151 (let* ((box (org-element-property :checkbox context))
21152 (struct (org-element-property :structure context))
21153 (old-struct (copy-tree struct))
21154 (parents (org-list-parents-alist struct))
21155 (prevs (org-list-prevs-alist struct))
21156 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21157 (org-list-set-checkbox
21158 (org-element-property :begin context) struct
21159 (cond ((equal arg '(16)) "[-]")
21160 ((and (not box) (equal arg '(4))) "[ ]")
21161 ((or (not box) (equal arg '(4))) nil)
21162 ((eq box 'on) "[ ]")
21163 (t "[X]")))
21164 ;; Mimic `org-list-write-struct' but with grabbing
21165 ;; a return value from `org-list-struct-fix-box'.
21166 (org-list-struct-fix-ind struct parents 2)
21167 (org-list-struct-fix-item-end struct)
21168 (org-list-struct-fix-bul struct prevs)
21169 (org-list-struct-fix-ind struct parents)
21170 (let ((block-item
21171 (org-list-struct-fix-box struct parents prevs orderedp)))
21172 (if (and box (equal struct old-struct))
21173 (if (equal arg '(16))
21174 (message "Checkboxes already reset")
21175 (user-error "Cannot toggle this checkbox: %s"
21176 (if (eq box 'on)
21177 "all subitems checked"
21178 "unchecked subitems")))
21179 (org-list-struct-apply-struct struct old-struct)
21180 (org-update-checkbox-count-maybe))
21181 (when block-item
21182 (message "Checkboxes were removed due to empty box at line %d"
21183 (org-current-line block-item))))))
21184 (keyword
21185 (let ((org-inhibit-startup-visibility-stuff t)
21186 (org-startup-align-all-tables nil))
21187 (when (boundp 'org-table-coordinate-overlays)
21188 (mapc 'delete-overlay org-table-coordinate-overlays)
21189 (setq org-table-coordinate-overlays nil))
21190 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21191 (message "Local setup has been refreshed"))
21192 (plain-list
21193 ;; At a plain list, with a double C-u argument, set
21194 ;; checkboxes of each item to "[-]", whereas a single one
21195 ;; will toggle their presence according to the state of the
21196 ;; first item in the list. Without an argument, repair the
21197 ;; list.
21198 (let* ((begin (org-element-property :contents-begin context))
21199 (beginm (move-marker (make-marker) begin))
21200 (struct (org-element-property :structure context))
21201 (old-struct (copy-tree struct))
21202 (first-box (save-excursion
21203 (goto-char begin)
21204 (looking-at org-list-full-item-re)
21205 (match-string-no-properties 3)))
21206 (new-box (cond ((equal arg '(16)) "[-]")
21207 ((equal arg '(4)) (unless first-box "[ ]"))
21208 ((equal first-box "[X]") "[ ]")
21209 (t "[X]"))))
21210 (cond
21211 (arg
21212 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
21213 (org-list-get-all-items
21214 begin struct (org-list-prevs-alist struct))))
21215 ((and first-box (eq (point) begin))
21216 ;; For convenience, when point is at bol on the first
21217 ;; item of the list and no argument is provided, simply
21218 ;; toggle checkbox of that item, if any.
21219 (org-list-set-checkbox begin struct new-box)))
21220 (org-list-write-struct
21221 struct (org-list-parents-alist struct) old-struct)
21222 (org-update-checkbox-count-maybe)
21223 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21224 ((property-drawer node-property)
21225 (call-interactively 'org-property-action))
21226 ((radio-target target)
21227 (call-interactively 'org-update-radio-target-regexp))
21228 (statistics-cookie
21229 (call-interactively 'org-update-statistics-cookies))
21230 ((table table-cell table-row)
21231 ;; At a table, recalculate every field and align it. Also
21232 ;; send the table if necessary. If the table has
21233 ;; a `table.el' type, just give up. At a table row or
21234 ;; cell, maybe recalculate line but always align table.
21235 (if (eq (org-element-property :type context) 'table.el)
21236 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21237 Use \\[org-edit-special] to edit table.el tables"))
21238 (let ((org-enable-table-editor t))
21239 (if (or (eq type 'table)
21240 ;; Check if point is at a TBLFM line.
21241 (and (eq type 'table-row)
21242 (= (point) (org-element-property :end context))))
21243 (save-excursion
21244 (if (org-at-TBLFM-p)
21245 (progn (require 'org-table)
21246 (org-table-calc-current-TBLFM))
21247 (goto-char (org-element-property :contents-begin context))
21248 (org-call-with-arg 'org-table-recalculate (or arg t))
21249 (orgtbl-send-table 'maybe)))
21250 (org-table-maybe-eval-formula)
21251 (cond (arg (call-interactively 'org-table-recalculate))
21252 ((org-table-maybe-recalculate-line))
21253 (t (org-table-align)))))))
21254 (timestamp (org-timestamp-change 0 'day))
21255 (otherwise
21256 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21257 (user-error
21258 "C-c C-c can do nothing useful at this location")))))))))
21260 (defun org-mode-restart ()
21261 (interactive)
21262 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21263 (funcall major-mode)
21264 (hack-local-variables)
21265 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21266 (org-indent-mode -1)))
21267 (message "%s restarted" major-mode))
21269 (defun org-kill-note-or-show-branches ()
21270 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21271 (interactive)
21272 (if (not org-finish-function)
21273 (progn
21274 (outline-hide-subtree)
21275 (call-interactively 'outline-show-branches))
21276 (let ((org-note-abort t))
21277 (funcall org-finish-function))))
21279 (defun org-delete-indentation (&optional ARG)
21280 "Join current line to previous and fix whitespace at join.
21282 If previous line is a headline add to headline title. Otherwise
21283 the function calls `delete-indentation'.
21285 With argument, join this line to following line."
21286 (interactive "*P")
21287 (if (save-excursion
21288 (if ARG (beginning-of-line)
21289 (forward-line -1))
21290 (looking-at org-complex-heading-regexp))
21291 ;; At headline.
21292 (let ((tags-column (when (match-beginning 5)
21293 (save-excursion (goto-char (match-beginning 5))
21294 (current-column))))
21295 (string (concat " " (progn (when ARG (forward-line 1))
21296 (org-trim (delete-and-extract-region
21297 (line-beginning-position)
21298 (line-end-position)))))))
21299 (unless (bobp) (delete-region (point) (1- (point))))
21300 (goto-char (or (match-end 4)
21301 (match-beginning 5)
21302 (match-end 0)))
21303 (skip-chars-backward " \t")
21304 (save-excursion (insert string))
21305 ;; Adjust alignment of tags.
21306 (when tags-column
21307 (org-align-tags-here (if org-auto-align-tags
21308 org-tags-column
21309 tags-column))))
21310 (delete-indentation ARG)))
21312 (defun org-open-line (n)
21313 "Insert a new row in tables, call `open-line' elsewhere.
21314 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21315 (interactive "*p")
21316 (cond
21317 ((not org-special-ctrl-o)
21318 (open-line n))
21319 ((org-at-table-p)
21320 (org-table-insert-row))
21322 (open-line n))))
21324 (defun org-return (&optional indent)
21325 "Goto next table row or insert a newline.
21327 Calls `org-table-next-row' or `newline', depending on context.
21329 When optional INDENT argument is non-nil, call
21330 `newline-and-indent' instead of `newline'.
21332 When `org-return-follows-link' is non-nil and point is on
21333 a timestamp or a link, call `org-open-at-point'. However, it
21334 will not happen if point is in a table or on a \"dead\"
21335 object (e.g., within a comment). In these case, you need to use
21336 `org-open-at-point' directly."
21337 (interactive)
21338 (let ((context (if org-return-follows-link (org-element-context)
21339 (org-element-at-point))))
21340 (cond
21341 ;; In a table, call `org-table-next-row'.
21342 ((or (and (eq (org-element-type context) 'table)
21343 (>= (point) (org-element-property :contents-begin context))
21344 (< (point) (org-element-property :contents-end context)))
21345 (org-element-lineage context '(table-row table-cell) t))
21346 (org-table-justify-field-maybe)
21347 (call-interactively #'org-table-next-row))
21348 ;; On a link or a timestamp, call `org-open-at-point' if
21349 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21350 ;; locations, e.g., in a comment, as `org-open-at-point'.
21351 ((and org-return-follows-link
21352 (or (org-in-regexp org-ts-regexp-both nil t)
21353 (org-in-regexp org-tsr-regexp-both nil t)
21354 (org-in-regexp org-any-link-re nil t)))
21355 (call-interactively #'org-open-at-point))
21356 ;; Insert newline in heading, but preserve tags.
21357 ((and (not (bolp))
21358 (save-excursion (beginning-of-line)
21359 (looking-at org-complex-heading-regexp)))
21360 ;; At headline. Split line. However, if point is on keyword,
21361 ;; priority cookie or tags, do not break any of them: add
21362 ;; a newline after the headline instead.
21363 (let ((tags-column (and (match-beginning 5)
21364 (save-excursion (goto-char (match-beginning 5))
21365 (current-column))))
21366 (string
21367 (when (and (match-end 4)
21368 (>= (point)
21369 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21370 (<= (point) (match-end 4)))
21371 (delete-and-extract-region (point) (match-end 4)))))
21372 (when (and tags-column string) ; Adjust tag alignment.
21373 (org-align-tags-here
21374 (if org-auto-align-tags org-tags-column tags-column)))
21375 (end-of-line)
21376 (org-show-entry)
21377 (if indent (newline-and-indent) (newline))
21378 (when string (save-excursion (insert (org-trim string))))))
21379 ;; In a list, make sure indenting keeps trailing text within.
21380 ((and indent
21381 (not (eolp))
21382 (org-element-lineage context '(item)))
21383 (let ((trailing-data
21384 (delete-and-extract-region (point) (line-end-position))))
21385 (newline-and-indent)
21386 (save-excursion (insert trailing-data))))
21387 (t (if indent (newline-and-indent) (newline))))))
21389 (defun org-return-indent ()
21390 "Goto next table row or insert a newline and indent.
21391 Calls `org-table-next-row' or `newline-and-indent', depending on
21392 context. See the individual commands for more information."
21393 (interactive)
21394 (org-return t))
21396 (defun org-ctrl-c-star ()
21397 "Compute table, or change heading status of lines.
21398 Calls `org-table-recalculate' or `org-toggle-heading',
21399 depending on context."
21400 (interactive)
21401 (cond
21402 ((org-at-table-p)
21403 (call-interactively 'org-table-recalculate))
21405 ;; Convert all lines in region to list items
21406 (call-interactively 'org-toggle-heading))))
21408 (defun org-ctrl-c-minus ()
21409 "Insert separator line in table or modify bullet status of line.
21410 Also turns a plain line or a region of lines into list items.
21411 Calls `org-table-insert-hline', `org-toggle-item', or
21412 `org-cycle-list-bullet', depending on context."
21413 (interactive)
21414 (cond
21415 ((org-at-table-p)
21416 (call-interactively 'org-table-insert-hline))
21417 ((org-region-active-p)
21418 (call-interactively 'org-toggle-item))
21419 ((org-in-item-p)
21420 (call-interactively 'org-cycle-list-bullet))
21422 (call-interactively 'org-toggle-item))))
21424 (defun org-toggle-item (arg)
21425 "Convert headings or normal lines to items, items to normal lines.
21426 If there is no active region, only the current line is considered.
21428 If the first non blank line in the region is a headline, convert
21429 all headlines to items, shifting text accordingly.
21431 If it is an item, convert all items to normal lines.
21433 If it is normal text, change region into a list of items.
21434 With a prefix argument ARG, change the region in a single item."
21435 (interactive "P")
21436 (let ((shift-text
21437 (function
21438 ;; Shift text in current section to IND, from point to END.
21439 ;; The function leaves point to END line.
21440 (lambda (ind end)
21441 (let ((min-i 1000) (end (copy-marker end)))
21442 ;; First determine the minimum indentation (MIN-I) of
21443 ;; the text.
21444 (save-excursion
21445 (catch 'exit
21446 (while (< (point) end)
21447 (let ((i (org-get-indentation)))
21448 (cond
21449 ;; Skip blank lines and inline tasks.
21450 ((looking-at "^[ \t]*$"))
21451 ((looking-at org-outline-regexp-bol))
21452 ;; We can't find less than 0 indentation.
21453 ((zerop i) (throw 'exit (setq min-i 0)))
21454 ((< i min-i) (setq min-i i))))
21455 (forward-line))))
21456 ;; Then indent each line so that a line indented to
21457 ;; MIN-I becomes indented to IND. Ignore blank lines
21458 ;; and inline tasks in the process.
21459 (let ((delta (- ind min-i)))
21460 (while (< (point) end)
21461 (unless (or (looking-at "^[ \t]*$")
21462 (looking-at org-outline-regexp-bol))
21463 (org-indent-line-to (+ (org-get-indentation) delta)))
21464 (forward-line)))))))
21465 (skip-blanks
21466 (function
21467 ;; Return beginning of first non-blank line, starting from
21468 ;; line at POS.
21469 (lambda (pos)
21470 (save-excursion
21471 (goto-char pos)
21472 (skip-chars-forward " \r\t\n")
21473 (point-at-bol)))))
21474 beg end)
21475 ;; Determine boundaries of changes.
21476 (if (org-region-active-p)
21477 (setq beg (funcall skip-blanks (region-beginning))
21478 end (copy-marker (region-end)))
21479 (setq beg (funcall skip-blanks (point-at-bol))
21480 end (copy-marker (point-at-eol))))
21481 ;; Depending on the starting line, choose an action on the text
21482 ;; between BEG and END.
21483 (org-with-limited-levels
21484 (save-excursion
21485 (goto-char beg)
21486 (cond
21487 ;; Case 1. Start at an item: de-itemize. Note that it only
21488 ;; happens when a region is active: `org-ctrl-c-minus'
21489 ;; would call `org-cycle-list-bullet' otherwise.
21490 ((org-at-item-p)
21491 (while (< (point) end)
21492 (when (org-at-item-p)
21493 (skip-chars-forward " \t")
21494 (delete-region (point) (match-end 0)))
21495 (forward-line)))
21496 ;; Case 2. Start at an heading: convert to items.
21497 ((org-at-heading-p)
21498 (let* ((bul (org-list-bullet-string "-"))
21499 (bul-len (length bul))
21500 (done (org-entry-is-done-p))
21501 (todo (org-entry-is-todo-p))
21502 ;; Indentation of the first heading. It should be
21503 ;; relative to the indentation of its parent, if any.
21504 (start-ind (save-excursion
21505 (cond
21506 ((not org-adapt-indentation) 0)
21507 ((not (outline-previous-heading)) 0)
21508 (t (length (match-string 0))))))
21509 ;; Level of first heading. Further headings will be
21510 ;; compared to it to determine hierarchy in the list.
21511 (ref-level (org-reduced-level (org-outline-level))))
21512 (when (or done todo) (org-todo ""))
21513 (while (< (point) end)
21514 (let* ((level (org-reduced-level (org-outline-level)))
21515 (delta (max 0 (- level ref-level))))
21516 ;; If current headline is less indented than the first
21517 ;; one, set it as reference, in order to preserve
21518 ;; subtrees.
21519 (when (< level ref-level) (setq ref-level level))
21520 (replace-match bul t t)
21521 (org-indent-line-to (+ start-ind (* delta bul-len)))
21522 (when (or done todo)
21523 (let* ((struct (org-list-struct))
21524 (old (copy-tree struct)))
21525 (org-list-set-checkbox (line-beginning-position)
21526 struct
21527 (if done "[X]" "[ ]"))
21528 (org-list-write-struct struct
21529 (org-list-parents-alist struct)
21530 old)))
21531 ;; Ensure all text down to END (or SECTION-END) belongs
21532 ;; to the newly created item.
21533 (let ((section-end (save-excursion
21534 (or (outline-next-heading) (point)))))
21535 (forward-line)
21536 (funcall shift-text
21537 (+ start-ind (* (1+ delta) bul-len))
21538 (min end section-end)))))))
21539 ;; Case 3. Normal line with ARG: make the first line of region
21540 ;; an item, and shift indentation of others lines to
21541 ;; set them as item's body.
21542 (arg (let* ((bul (org-list-bullet-string "-"))
21543 (bul-len (length bul))
21544 (ref-ind (org-get-indentation)))
21545 (skip-chars-forward " \t")
21546 (insert bul)
21547 (forward-line)
21548 (while (< (point) end)
21549 ;; Ensure that lines less indented than first one
21550 ;; still get included in item body.
21551 (funcall shift-text
21552 (+ ref-ind bul-len)
21553 (min end (save-excursion (or (outline-next-heading)
21554 (point)))))
21555 (forward-line))))
21556 ;; Case 4. Normal line without ARG: turn each non-item line
21557 ;; into an item.
21559 (while (< (point) end)
21560 (unless (or (org-at-heading-p) (org-at-item-p))
21561 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21562 (replace-match
21563 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21564 (forward-line))))))))
21566 (defun org-toggle-heading (&optional nstars)
21567 "Convert headings to normal text, or items or text to headings.
21568 If there is no active region, only convert the current line.
21570 With a \\[universal-argument] prefix, convert the whole list at
21571 point into heading.
21573 In a region:
21575 - If the first non blank line is a headline, remove the stars
21576 from all headlines in the region.
21578 - If it is a normal line, turn each and every normal line (i.e.,
21579 not an heading or an item) in the region into headings. If you
21580 want to convert only the first line of this region, use one
21581 universal prefix argument.
21583 - If it is a plain list item, turn all plain list items into headings.
21585 When converting a line into a heading, the number of stars is chosen
21586 such that the lines become children of the current entry. However,
21587 when a numeric prefix argument is given, its value determines the
21588 number of stars to add."
21589 (interactive "P")
21590 (let ((skip-blanks
21591 (function
21592 ;; Return beginning of first non-blank line, starting from
21593 ;; line at POS.
21594 (lambda (pos)
21595 (save-excursion
21596 (goto-char pos)
21597 (while (org-at-comment-p) (forward-line))
21598 (skip-chars-forward " \r\t\n")
21599 (point-at-bol)))))
21600 beg end toggled)
21601 ;; Determine boundaries of changes. If a universal prefix has
21602 ;; been given, put the list in a region. If region ends at a bol,
21603 ;; do not consider the last line to be in the region.
21605 (when (and current-prefix-arg (org-at-item-p))
21606 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21607 (org-mark-element))
21609 (if (org-region-active-p)
21610 (setq beg (funcall skip-blanks (region-beginning))
21611 end (copy-marker (save-excursion
21612 (goto-char (region-end))
21613 (if (bolp) (point) (point-at-eol)))))
21614 (setq beg (funcall skip-blanks (point-at-bol))
21615 end (copy-marker (point-at-eol))))
21616 ;; Ensure inline tasks don't count as headings.
21617 (org-with-limited-levels
21618 (save-excursion
21619 (goto-char beg)
21620 (cond
21621 ;; Case 1. Started at an heading: de-star headings.
21622 ((org-at-heading-p)
21623 (while (< (point) end)
21624 (when (org-at-heading-p t)
21625 (looking-at org-outline-regexp) (replace-match "")
21626 (setq toggled t))
21627 (forward-line)))
21628 ;; Case 2. Started at an item: change items into headlines.
21629 ;; One star will be added by `org-list-to-subtree'.
21630 ((org-at-item-p)
21631 (while (< (point) end)
21632 (when (org-at-item-p)
21633 ;; Pay attention to cases when region ends before list.
21634 (let* ((struct (org-list-struct))
21635 (list-end
21636 (min (org-list-get-bottom-point struct) (1+ end))))
21637 (save-restriction
21638 (narrow-to-region (point) list-end)
21639 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21640 (setq toggled t))
21641 (forward-line)))
21642 ;; Case 3. Started at normal text: make every line an heading,
21643 ;; skipping headlines and items.
21644 (t (let* ((stars
21645 (make-string
21646 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21647 (add-stars
21648 (cond (nstars "") ; stars from prefix only
21649 ((equal stars "") "*") ; before first heading
21650 (org-odd-levels-only "**") ; inside heading, odd
21651 (t "*"))) ; inside heading, oddeven
21652 (rpl (concat stars add-stars " "))
21653 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21654 (while (< (point) (if (equal nstars '(4)) lend end))
21655 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21656 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21657 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21658 (forward-line)))))))
21659 (unless toggled (message "Cannot toggle heading from here"))))
21661 (defun org-meta-return (&optional _arg)
21662 "Insert a new heading or wrap a region in a table.
21663 Calls `org-insert-heading' or `org-table-wrap-region', depending
21664 on context. See the individual commands for more information."
21665 (interactive)
21666 (org-check-before-invisible-edit 'insert)
21667 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21668 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21669 #'org-insert-heading))))
21671 ;;; Menu entries
21673 (defsubst org-in-subtree-not-table-p ()
21674 "Are we in a subtree and not in a table?"
21675 (and (not (org-before-first-heading-p))
21676 (not (org-at-table-p))))
21678 ;; Define the Org-mode menus
21679 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21680 '("Tbl"
21681 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21682 ["Next Field" org-cycle (org-at-table-p)]
21683 ["Previous Field" org-shifttab (org-at-table-p)]
21684 ["Next Row" org-return (org-at-table-p)]
21685 "--"
21686 ["Blank Field" org-table-blank-field (org-at-table-p)]
21687 ["Edit Field" org-table-edit-field (org-at-table-p)]
21688 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21689 "--"
21690 ("Column"
21691 ["Move Column Left" org-metaleft (org-at-table-p)]
21692 ["Move Column Right" org-metaright (org-at-table-p)]
21693 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21694 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21695 ("Row"
21696 ["Move Row Up" org-metaup (org-at-table-p)]
21697 ["Move Row Down" org-metadown (org-at-table-p)]
21698 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21699 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21700 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21701 "--"
21702 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21703 ("Rectangle"
21704 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21705 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21706 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21707 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21708 "--"
21709 ("Calculate"
21710 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21711 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21712 ["Edit Formulas" org-edit-special (org-at-table-p)]
21713 "--"
21714 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21715 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21716 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21717 "--"
21718 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21719 "--"
21720 ["Sum Column/Rectangle" org-table-sum
21721 (or (org-at-table-p) (org-region-active-p))]
21722 ["Which Column?" org-table-current-column (org-at-table-p)])
21723 ["Debug Formulas"
21724 org-table-toggle-formula-debugger
21725 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21726 ["Show Col/Row Numbers"
21727 org-table-toggle-coordinate-overlays
21728 :style toggle
21729 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21730 "--"
21731 ["Create" org-table-create (and (not (org-at-table-p))
21732 org-enable-table-editor)]
21733 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21734 ["Import from File" org-table-import (not (org-at-table-p))]
21735 ["Export to File" org-table-export (org-at-table-p)]
21736 "--"
21737 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21738 "--"
21739 ("Plot"
21740 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21741 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21743 (easy-menu-define org-org-menu org-mode-map "Org menu"
21744 '("Org"
21745 ("Show/Hide"
21746 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21747 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21748 ["Sparse Tree..." org-sparse-tree t]
21749 ["Reveal Context" org-reveal t]
21750 ["Show All" outline-show-all t]
21751 "--"
21752 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21753 "--"
21754 ["New Heading" org-insert-heading t]
21755 ("Navigate Headings"
21756 ["Up" outline-up-heading t]
21757 ["Next" outline-next-visible-heading t]
21758 ["Previous" outline-previous-visible-heading t]
21759 ["Next Same Level" outline-forward-same-level t]
21760 ["Previous Same Level" outline-backward-same-level t]
21761 "--"
21762 ["Jump" org-goto t])
21763 ("Edit Structure"
21764 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21765 "--"
21766 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21767 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21768 "--"
21769 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21770 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21771 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21772 "--"
21773 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21774 "--"
21775 ["Copy visible text" org-copy-visible t]
21776 "--"
21777 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21778 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21779 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21780 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21781 "--"
21782 ["Sort Region/Children" org-sort t]
21783 "--"
21784 ["Convert to odd levels" org-convert-to-odd-levels t]
21785 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21786 ("Editing"
21787 ["Emphasis..." org-emphasize t]
21788 ["Edit Source Example" org-edit-special t]
21789 "--"
21790 ["Footnote new/jump" org-footnote-action t]
21791 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21792 ("Archive"
21793 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21794 "--"
21795 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21796 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21797 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21799 "--"
21800 ("Hyperlinks"
21801 ["Store Link (Global)" org-store-link t]
21802 ["Find existing link to here" org-occur-link-in-agenda-files t]
21803 ["Insert Link" org-insert-link t]
21804 ["Follow Link" org-open-at-point t]
21805 "--"
21806 ["Next link" org-next-link t]
21807 ["Previous link" org-previous-link t]
21808 "--"
21809 ["Descriptive Links"
21810 org-toggle-link-display
21811 :style radio
21812 :selected org-descriptive-links
21814 ["Literal Links"
21815 org-toggle-link-display
21816 :style radio
21817 :selected (not org-descriptive-links)])
21818 "--"
21819 ("TODO Lists"
21820 ["TODO/DONE/-" org-todo t]
21821 ("Select keyword"
21822 ["Next keyword" org-shiftright (org-at-heading-p)]
21823 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21824 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21825 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21826 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21827 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21828 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21829 "--"
21830 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21831 :selected org-enforce-todo-dependencies :style toggle :active t]
21832 "Settings for tree at point"
21833 ["Do Children sequentially" org-toggle-ordered-property :style radio
21834 :selected (org-entry-get nil "ORDERED")
21835 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21836 ["Do Children parallel" org-toggle-ordered-property :style radio
21837 :selected (not (org-entry-get nil "ORDERED"))
21838 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21839 "--"
21840 ["Set Priority" org-priority t]
21841 ["Priority Up" org-shiftup t]
21842 ["Priority Down" org-shiftdown t]
21843 "--"
21844 ["Get news from all feeds" org-feed-update-all t]
21845 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21846 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21847 ("TAGS and Properties"
21848 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21849 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21850 "--"
21851 ["Set property" org-set-property (not (org-before-first-heading-p))]
21852 ["Column view of properties" org-columns t]
21853 ["Insert Column View DBlock" org-insert-columns-dblock t])
21854 ("Dates and Scheduling"
21855 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21856 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21857 ("Change Date"
21858 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21859 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21860 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21861 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21862 ["Compute Time Range" org-evaluate-time-range t]
21863 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21864 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21865 "--"
21866 ["Custom time format" org-toggle-time-stamp-overlays
21867 :style radio :selected org-display-custom-times]
21868 "--"
21869 ["Goto Calendar" org-goto-calendar t]
21870 ["Date from Calendar" org-date-from-calendar t]
21871 "--"
21872 ["Start/Restart Timer" org-timer-start t]
21873 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21874 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21875 ["Insert Timer String" org-timer t]
21876 ["Insert Timer Item" org-timer-item t])
21877 ("Logging work"
21878 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21879 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21880 ["Clock out" org-clock-out t]
21881 ["Clock cancel" org-clock-cancel t]
21882 "--"
21883 ["Mark as default task" org-clock-mark-default-task t]
21884 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21885 ["Goto running clock" org-clock-goto t]
21886 "--"
21887 ["Display times" org-clock-display t]
21888 ["Create clock table" org-clock-report t]
21889 "--"
21890 ["Record DONE time"
21891 (progn (setq org-log-done (not org-log-done))
21892 (message "Switching to %s will %s record a timestamp"
21893 (car org-done-keywords)
21894 (if org-log-done "automatically" "not")))
21895 :style toggle :selected org-log-done])
21896 "--"
21897 ["Agenda Command..." org-agenda t]
21898 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21899 ("File List for Agenda")
21900 ("Special views current file"
21901 ["TODO Tree" org-show-todo-tree t]
21902 ["Check Deadlines" org-check-deadlines t]
21903 ["Timeline" org-timeline t]
21904 ["Tags/Property tree" org-match-sparse-tree t])
21905 "--"
21906 ["Export/Publish..." org-export-dispatch t]
21907 ("LaTeX"
21908 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21909 :selected org-cdlatex-mode]
21910 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21911 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21912 ["Modify math symbol" org-cdlatex-math-modify
21913 (org-inside-LaTeX-fragment-p)]
21914 ["Insert citation" org-reftex-citation t]
21915 "--"
21916 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21917 "--"
21918 ("MobileOrg"
21919 ["Push Files and Views" org-mobile-push t]
21920 ["Get Captured and Flagged" org-mobile-pull t]
21921 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21922 "--"
21923 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21924 "--"
21925 ("Documentation"
21926 ["Show Version" org-version t]
21927 ["Info Documentation" org-info t])
21928 ("Customize"
21929 ["Browse Org Group" org-customize t]
21930 "--"
21931 ["Expand This Menu" org-create-customize-menu
21932 (fboundp 'customize-menu-create)])
21933 ["Send bug report" org-submit-bug-report t]
21934 "--"
21935 ("Refresh/Reload"
21936 ["Refresh setup current buffer" org-mode-restart t]
21937 ["Reload Org (after update)" org-reload t]
21938 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21941 (defun org-info (&optional node)
21942 "Read documentation for Org-mode in the info system.
21943 With optional NODE, go directly to that node."
21944 (interactive)
21945 (info (format "(org)%s" (or node ""))))
21947 ;;;###autoload
21948 (defun org-submit-bug-report ()
21949 "Submit a bug report on Org-mode via mail.
21951 Don't hesitate to report any problems or inaccurate documentation.
21953 If you don't have setup sending mail from (X)Emacs, please copy the
21954 output buffer into your mail program, as it gives us important
21955 information about your Org-mode version and configuration."
21956 (interactive)
21957 (require 'reporter)
21958 (defvar reporter-prompt-for-summary-p)
21959 (org-load-modules-maybe)
21960 (org-require-autoloaded-modules)
21961 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21962 (reporter-submit-bug-report
21963 "emacs-orgmode@gnu.org"
21964 (org-version nil 'full)
21965 (let (list)
21966 (save-window-excursion
21967 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21968 (delete-other-windows)
21969 (erase-buffer)
21970 (insert "You are about to submit a bug report to the Org-mode mailing list.
21972 We would like to add your full Org-mode and Outline configuration to the
21973 bug report. This greatly simplifies the work of the maintainer and
21974 other experts on the mailing list.
21976 HOWEVER, some variables you have customized may contain private
21977 information. The names of customers, colleagues, or friends, might
21978 appear in the form of file names, tags, todo states, or search strings.
21979 If you answer yes to the prompt, you might want to check and remove
21980 such private information before sending the email.")
21981 (add-text-properties (point-min) (point-max) '(face org-warning))
21982 (when (yes-or-no-p "Include your Org-mode configuration ")
21983 (mapatoms
21984 (lambda (v)
21985 (and (boundp v)
21986 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21987 (or (and (symbol-value v)
21988 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21989 (and
21990 (get v 'custom-type) (get v 'standard-value)
21991 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21992 (push v list)))))
21993 (kill-buffer (get-buffer "*Warn about privacy*"))
21994 list))
21995 nil nil
21996 "Remember to cover the basics, that is, what you expected to happen and
21997 what in fact did happen. You don't know how to make a good report? See
21999 http://orgmode.org/manual/Feedback.html#Feedback
22001 Your bug report will be posted to the Org-mode mailing list.
22002 ------------------------------------------------------------------------")
22003 (save-excursion
22004 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
22005 (replace-match "\\1Bug: \\3 [\\2]")))))
22008 (defun org-install-agenda-files-menu ()
22009 (let ((bl (buffer-list)))
22010 (save-excursion
22011 (while bl
22012 (set-buffer (pop bl))
22013 (when (derived-mode-p 'org-mode) (setq bl nil)))
22014 (when (derived-mode-p 'org-mode)
22015 (easy-menu-change
22016 '("Org") "File List for Agenda"
22017 (append
22018 (list
22019 ["Edit File List" (org-edit-agenda-file-list) t]
22020 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22021 ["Remove Current File from List" org-remove-file t]
22022 ["Cycle through agenda files" org-cycle-agenda-files t]
22023 ["Occur in all agenda files" org-occur-in-agenda-files t]
22024 "--")
22025 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22027 ;;;; Documentation
22029 (defun org-require-autoloaded-modules ()
22030 (interactive)
22031 (mapc 'require
22032 '(org-agenda org-archive org-attach org-clock org-colview org-id
22033 org-table org-timer)))
22035 ;;;###autoload
22036 (defun org-reload (&optional uncompiled)
22037 "Reload all org lisp files.
22038 With prefix arg UNCOMPILED, load the uncompiled versions."
22039 (interactive "P")
22040 (require 'loadhist)
22041 (let* ((org-dir (org-find-library-dir "org"))
22042 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22043 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22044 (remove-re (mapconcat 'identity
22045 (mapcar (lambda (f) (concat "^" f "$"))
22046 (list (if (featurep 'xemacs)
22047 "org-colview"
22048 "org-colview-xemacs")
22049 "org" "org-loaddefs" "org-version"))
22050 "\\|"))
22051 (feats (delete-dups
22052 (mapcar 'file-name-sans-extension
22053 (mapcar 'file-name-nondirectory
22054 (delq nil
22055 (mapcar 'feature-file
22056 features))))))
22057 (lfeat (append
22058 (sort
22059 (setq feats
22060 (delq nil (mapcar
22061 (lambda (f)
22062 (if (and (string-match feature-re f)
22063 (not (string-match remove-re f)))
22064 f nil))
22065 feats)))
22066 'string-lessp)
22067 (list "org-version" "org")))
22068 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22069 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22070 load-uncore load-misses)
22071 (setq load-misses
22072 (delq 't
22073 (mapcar (lambda (f)
22074 (or (org-load-noerror-mustsuffix (concat org-dir f))
22075 (and (string= org-dir contrib-dir)
22076 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22077 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22078 (add-to-list 'load-uncore f 'append)
22081 lfeat)))
22082 (when load-uncore
22083 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22084 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22085 (if load-misses
22086 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22087 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22088 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22090 ;;;###autoload
22091 (defun org-customize ()
22092 "Call the customize function with org as argument."
22093 (interactive)
22094 (org-load-modules-maybe)
22095 (org-require-autoloaded-modules)
22096 (customize-browse 'org))
22098 (defun org-create-customize-menu ()
22099 "Create a full customization menu for Org-mode, insert it into the menu."
22100 (interactive)
22101 (org-load-modules-maybe)
22102 (org-require-autoloaded-modules)
22103 (if (fboundp 'customize-menu-create)
22104 (progn
22105 (easy-menu-change
22106 '("Org") "Customize"
22107 `(["Browse Org group" org-customize t]
22108 "--"
22109 ,(customize-menu-create 'org)
22110 ["Set" Custom-set t]
22111 ["Save" Custom-save t]
22112 ["Reset to Current" Custom-reset-current t]
22113 ["Reset to Saved" Custom-reset-saved t]
22114 ["Reset to Standard Settings" Custom-reset-standard t]))
22115 (message "\"Org\"-menu now contains full customization menu"))
22116 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22118 ;;;; Miscellaneous stuff
22120 ;;; Generally useful functions
22122 (defsubst org-get-at-eol (property n)
22123 "Get text property PROPERTY at the end of line less N characters."
22124 (get-text-property (- (point-at-eol) n) property))
22126 (defun org-find-text-property-in-string (prop s)
22127 "Return the first non-nil value of property PROP in string S."
22128 (or (get-text-property 0 prop s)
22129 (get-text-property (or (next-single-property-change 0 prop s) 0)
22130 prop s)))
22132 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22133 "Display the given MESSAGE as a warning."
22134 (if (fboundp 'display-warning)
22135 (display-warning 'org message
22136 (if (featurep 'xemacs) 'warning :warning))
22137 (let ((buf (get-buffer-create "*Org warnings*")))
22138 (with-current-buffer buf
22139 (goto-char (point-max))
22140 (insert "Warning (Org): " message)
22141 (unless (bolp)
22142 (newline)))
22143 (display-buffer buf)
22144 (sit-for 0))))
22146 (defun org-eval (form)
22147 "Eval FORM and return result."
22148 (condition-case error
22149 (eval form)
22150 (error (format "%%![Error: %s]" error))))
22152 (defun org-in-clocktable-p ()
22153 "Check if the cursor is in a clocktable."
22154 (let ((pos (point)) start)
22155 (save-excursion
22156 (end-of-line 1)
22157 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22158 (setq start (match-beginning 0))
22159 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22160 (>= (match-end 0) pos)
22161 start))))
22163 (defun org-in-verbatim-emphasis ()
22164 (save-match-data
22165 (and (org-in-regexp org-emph-re 2)
22166 (>= (point) (match-beginning 3))
22167 (<= (point) (match-end 4))
22168 (member (match-string 3) '("=" "~")))))
22170 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22171 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22172 (if (and marker (marker-buffer marker)
22173 (buffer-live-p (marker-buffer marker)))
22174 (progn
22175 (org-pop-to-buffer-same-window (marker-buffer marker))
22176 (when (or (> marker (point-max)) (< marker (point-min)))
22177 (widen))
22178 (goto-char marker)
22179 (org-show-context 'org-goto))
22180 (if bookmark
22181 (bookmark-jump bookmark)
22182 (error "Cannot find location"))))
22184 (defun org-quote-csv-field (s)
22185 "Quote field for inclusion in CSV material."
22186 (if (string-match "[\",]" s)
22187 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22190 (defun org-force-self-insert (N)
22191 "Needed to enforce self-insert under remapping."
22192 (interactive "p")
22193 (self-insert-command N))
22195 (defun org-string-width (s)
22196 "Compute width of string, ignoring invisible characters.
22197 This ignores character with invisibility property `org-link', and also
22198 characters with property `org-cwidth', because these will become invisible
22199 upon the next fontification round."
22200 (let (b l)
22201 (when (or (eq t buffer-invisibility-spec)
22202 (assq 'org-link buffer-invisibility-spec))
22203 (while (setq b (text-property-any 0 (length s)
22204 'invisible 'org-link s))
22205 (setq s (concat (substring s 0 b)
22206 (substring s (or (next-single-property-change
22207 b 'invisible s)
22208 (length s)))))))
22209 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22210 (setq s (concat (substring s 0 b)
22211 (substring s (or (next-single-property-change
22212 b 'org-cwidth s)
22213 (length s))))))
22214 (setq l (string-width s) b -1)
22215 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22216 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22219 (defun org-shorten-string (s maxlength)
22220 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22221 If the string is shorter or has length MAXLENGTH, just return the
22222 original string. If it is longer, the functions finds a space in the
22223 string, breaks this string off at that locations and adds three dots
22224 as ellipsis. Including the ellipsis, the string will not be longer
22225 than MAXLENGTH. If finding a good breaking point in the string does
22226 not work, the string is just chopped off in the middle of a word
22227 if necessary."
22228 (if (<= (length s) maxlength)
22230 (let* ((n (max (- maxlength 4) 1))
22231 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22232 (if (string-match re s)
22233 (concat (match-string 1 s) "...")
22234 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22236 (defun org-get-indentation (&optional line)
22237 "Get the indentation of the current line, interpreting tabs.
22238 When LINE is given, assume it represents a line and compute its indentation."
22239 (if line
22240 (when (string-match "^ *" (org-remove-tabs line))
22241 (match-end 0))
22242 (save-excursion
22243 (beginning-of-line 1)
22244 (skip-chars-forward " \t")
22245 (current-column))))
22247 (defun org-get-string-indentation (s)
22248 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22249 (let ((n -1) (i 0) (w tab-width) c)
22250 (catch 'exit
22251 (while (< (setq n (1+ n)) (length s))
22252 (setq c (aref s n))
22253 (cond ((= c ?\ ) (setq i (1+ i)))
22254 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22255 (t (throw 'exit t)))))
22258 (defun org-remove-tabs (s &optional width)
22259 "Replace tabulators in S with spaces.
22260 Assumes that s is a single line, starting in column 0."
22261 (setq width (or width tab-width))
22262 (while (string-match "\t" s)
22263 (setq s (replace-match
22264 (make-string
22265 (- (* width (/ (+ (match-beginning 0) width) width))
22266 (match-beginning 0)) ?\ )
22267 t t s)))
22270 (defun org-fix-indentation (line ind)
22271 "Fix indentation in LINE.
22272 IND is a cons cell with target and minimum indentation.
22273 If the current indentation in LINE is smaller than the minimum,
22274 leave it alone. If it is larger than ind, set it to the target."
22275 (let* ((l (org-remove-tabs line))
22276 (i (org-get-indentation l))
22277 (i1 (car ind)) (i2 (cdr ind)))
22278 (when (>= i i2) (setq l (substring line i2)))
22279 (if (> i1 0)
22280 (concat (make-string i1 ?\ ) l)
22281 l)))
22283 (defun org-remove-indentation (code &optional n)
22284 "Remove maximum common indentation in string CODE and return it.
22285 N may optionally be the number of columns to remove. Return CODE
22286 as-is if removal failed."
22287 (with-temp-buffer
22288 (insert code)
22289 (if (org-do-remove-indentation n) (buffer-string) code)))
22291 (defun org-do-remove-indentation (&optional n)
22292 "Remove the maximum common indentation from the buffer.
22293 When optional argument N is a positive integer, remove exactly
22294 that much characters from indentation, if possible. Return nil
22295 if it fails."
22296 (catch :exit
22297 (goto-char (point-min))
22298 ;; Find maximum common indentation, if not specified.
22299 (let ((n (or n
22300 (let ((min-ind (point-max)))
22301 (save-excursion
22302 (while (re-search-forward "^[ \t]*\\S-" nil t)
22303 (let ((ind (1- (current-column))))
22304 (if (zerop ind) (throw :exit nil)
22305 (setq min-ind (min min-ind ind))))))
22306 min-ind))))
22307 (if (zerop n) (throw :exit nil)
22308 ;; Remove exactly N indentation, but give up if not possible.
22309 (while (not (eobp))
22310 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22311 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22312 ((< ind n) (throw :exit nil))
22313 (t (org-indent-line-to (- ind n))))
22314 (forward-line)))
22315 ;; Signal success.
22316 t))))
22318 (defun org-fill-template (template alist)
22319 "Find each %key of ALIST in TEMPLATE and replace it."
22320 (let ((case-fold-search nil))
22321 (dolist (entry (sort (copy-sequence alist)
22322 (lambda (a b) (< (length (car a)) (length (car b))))))
22323 (setq template
22324 (replace-regexp-in-string
22325 (concat "%" (regexp-quote (car entry)))
22326 (or (cdr entry) "") template t t)))
22327 template))
22329 (defun org-base-buffer (buffer)
22330 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22331 (if (not buffer)
22332 buffer
22333 (or (buffer-base-buffer buffer)
22334 buffer)))
22336 (defun org-wrap (string &optional width lines)
22337 "Wrap string to either a number of lines, or a width in characters.
22338 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22339 that costs. If there is a word longer than WIDTH, the text is actually
22340 wrapped to the length of that word.
22341 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22342 many lines, whatever width that takes.
22343 The return value is a list of lines, without newlines at the end."
22344 (let* ((words (org-split-string string "[ \t\n]+"))
22345 (maxword (apply 'max (mapcar 'org-string-width words)))
22346 w ll)
22347 (cond (width
22348 (org-do-wrap words (max maxword width)))
22349 (lines
22350 (setq w maxword)
22351 (setq ll (org-do-wrap words maxword))
22352 (if (<= (length ll) lines)
22354 (setq ll words)
22355 (while (> (length ll) lines)
22356 (setq w (1+ w))
22357 (setq ll (org-do-wrap words w)))
22358 ll))
22359 (t (error "Cannot wrap this")))))
22361 (defun org-do-wrap (words width)
22362 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22363 (let (lines line)
22364 (while words
22365 (setq line (pop words))
22366 (while (and words (< (+ (length line) (length (car words))) width))
22367 (setq line (concat line " " (pop words))))
22368 (setq lines (push line lines)))
22369 (nreverse lines)))
22371 (defun org-split-string (string &optional separators)
22372 "Splits STRING into substrings at SEPARATORS.
22373 SEPARATORS is a regular expression.
22374 No empty strings are returned if there are matches at the beginning
22375 and end of string."
22376 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22377 (let ((start 0) notfirst list)
22378 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22379 (if (and notfirst
22380 (= start (match-beginning 0))
22381 (< start (length string)))
22382 (1+ start) start))
22383 (< (match-beginning 0) (length string)))
22384 (setq notfirst t)
22385 (or (eq (match-beginning 0) 0)
22386 (and (eq (match-beginning 0) (match-end 0))
22387 (eq (match-beginning 0) start))
22388 (push (substring string start (match-beginning 0)) list))
22389 (setq start (match-end 0)))
22390 (or (eq start (length string))
22391 (push (substring string start) list))
22392 (nreverse list)))
22394 (defun org-quote-vert (s)
22395 "Replace \"|\" with \"\\vert\"."
22396 (while (string-match "|" s)
22397 (setq s (replace-match "\\vert" t t s)))
22400 (defun org-uuidgen-p (s)
22401 "Is S an ID created by UUIDGEN?"
22402 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22404 (defun org-in-src-block-p (&optional inside)
22405 "Whether point is in a code source block.
22406 When INSIDE is non-nil, don't consider we are within a src block
22407 when point is at #+BEGIN_SRC or #+END_SRC."
22408 (let ((case-fold-search t) ov)
22409 (or (and (eq (get-char-property (point) 'src-block) t))
22410 (and (not inside)
22411 (save-match-data
22412 (save-excursion
22413 (beginning-of-line)
22414 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22416 (defun org-context ()
22417 "Return a list of contexts of the current cursor position.
22418 If several contexts apply, all are returned.
22419 Each context entry is a list with a symbol naming the context, and
22420 two positions indicating start and end of the context. Possible
22421 contexts are:
22423 :headline anywhere in a headline
22424 :headline-stars on the leading stars in a headline
22425 :todo-keyword on a TODO keyword (including DONE) in a headline
22426 :tags on the TAGS in a headline
22427 :priority on the priority cookie in a headline
22428 :item on the first line of a plain list item
22429 :item-bullet on the bullet/number of a plain list item
22430 :checkbox on the checkbox in a plain list item
22431 :table in an org-mode table
22432 :table-special on a special filed in a table
22433 :table-table in a table.el table
22434 :clocktable in a clocktable
22435 :src-block in a source block
22436 :link on a hyperlink
22437 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22438 :target on a <<target>>
22439 :radio-target on a <<<radio-target>>>
22440 :latex-fragment on a LaTeX fragment
22441 :latex-preview on a LaTeX fragment with overlaid preview image
22443 This function expects the position to be visible because it uses font-lock
22444 faces as a help to recognize the following contexts: :table-special, :link,
22445 and :keyword."
22446 (let* ((f (get-text-property (point) 'face))
22447 (faces (if (listp f) f (list f)))
22448 (case-fold-search t)
22449 (p (point)) clist o)
22450 ;; First the large context
22451 (cond
22452 ((org-at-heading-p t)
22453 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22454 (when (progn
22455 (beginning-of-line 1)
22456 (looking-at org-todo-line-tags-regexp))
22457 (push (org-point-in-group p 1 :headline-stars) clist)
22458 (push (org-point-in-group p 2 :todo-keyword) clist)
22459 (push (org-point-in-group p 4 :tags) clist))
22460 (goto-char p)
22461 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22462 (when (looking-at "\\[#[A-Z0-9]\\]")
22463 (push (org-point-in-group p 0 :priority) clist)))
22465 ((org-at-item-p)
22466 (push (org-point-in-group p 2 :item-bullet) clist)
22467 (push (list :item (point-at-bol)
22468 (save-excursion (org-end-of-item) (point)))
22469 clist)
22470 (and (org-at-item-checkbox-p)
22471 (push (org-point-in-group p 0 :checkbox) clist)))
22473 ((org-at-table-p)
22474 (push (list :table (org-table-begin) (org-table-end)) clist)
22475 (when (memq 'org-formula faces)
22476 (push (list :table-special
22477 (previous-single-property-change p 'face)
22478 (next-single-property-change p 'face)) clist)))
22479 ((org-at-table-p 'any)
22480 (push (list :table-table) clist)))
22481 (goto-char p)
22483 (let ((case-fold-search t))
22484 ;; New the "medium" contexts: clocktables, source blocks
22485 (cond ((org-in-clocktable-p)
22486 (push (list :clocktable
22487 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22488 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22489 (match-beginning 1))
22490 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22491 (match-end 0))) clist))
22492 ((org-in-src-block-p)
22493 (push (list :src-block
22494 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22495 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22496 (match-beginning 1))
22497 (and (search-forward "#+END_SRC" nil t)
22498 (match-beginning 0))) clist))))
22499 (goto-char p)
22501 ;; Now the small context
22502 (cond
22503 ((org-at-timestamp-p)
22504 (push (org-point-in-group p 0 :timestamp) clist))
22505 ((memq 'org-link faces)
22506 (push (list :link
22507 (previous-single-property-change p 'face)
22508 (next-single-property-change p 'face)) clist))
22509 ((memq 'org-special-keyword faces)
22510 (push (list :keyword
22511 (previous-single-property-change p 'face)
22512 (next-single-property-change p 'face)) clist))
22513 ((org-at-target-p)
22514 (push (org-point-in-group p 0 :target) clist)
22515 (goto-char (1- (match-beginning 0)))
22516 (when (looking-at org-radio-target-regexp)
22517 (push (org-point-in-group p 0 :radio-target) clist))
22518 (goto-char p))
22519 ((setq o (car (delq nil
22520 (mapcar
22521 (lambda (x)
22522 (when (memq x org-latex-fragment-image-overlays) x))
22523 (overlays-at (point))))))
22524 (push (list :latex-fragment
22525 (overlay-start o) (overlay-end o)) clist)
22526 (push (list :latex-preview
22527 (overlay-start o) (overlay-end o)) clist))
22528 ((org-inside-LaTeX-fragment-p)
22529 ;; FIXME: positions wrong.
22530 (push (list :latex-fragment (point) (point)) clist)))
22532 (setq clist (nreverse (delq nil clist)))
22533 clist))
22535 (defun org-in-regexp (regexp &optional nlines visually)
22536 "Check if point is inside a match of REGEXP.
22538 Normally only the current line is checked, but you can include
22539 NLINES extra lines around point into the search. If VISUALLY is
22540 set, require that the cursor is not after the match but really
22541 on, so that the block visually is on the match.
22543 Return nil or a cons cell (BEG . END) where BEG and END are,
22544 respectively, the positions at the beginning and the end of the
22545 match."
22546 (catch :exit
22547 (let ((pos (point))
22548 (eol (line-end-position (if nlines (1+ nlines) 1))))
22549 (save-excursion
22550 (beginning-of-line (- 1 (or nlines 0)))
22551 (while (and (re-search-forward regexp eol t)
22552 (<= (match-beginning 0) pos))
22553 (let ((end (match-end 0)))
22554 (when (or (> end pos) (and (= end pos) (not visually)))
22555 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22556 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22557 "Org mode 8.3")
22559 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22560 "Non-nil when point is between matches of START-RE and END-RE.
22562 Also return a non-nil value when point is on one of the matches.
22564 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22565 buffer positions. Default values are the positions of headlines
22566 surrounding the point.
22568 The functions returns a cons cell whose car (resp. cdr) is the
22569 position before START-RE (resp. after END-RE)."
22570 (save-match-data
22571 (let ((pos (point))
22572 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22573 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22574 beg end)
22575 (save-excursion
22576 ;; Point is on a block when on START-RE or if START-RE can be
22577 ;; found before it...
22578 (and (or (org-in-regexp start-re)
22579 (re-search-backward start-re limit-up t))
22580 (setq beg (match-beginning 0))
22581 ;; ... and END-RE after it...
22582 (goto-char (match-end 0))
22583 (re-search-forward end-re limit-down t)
22584 (> (setq end (match-end 0)) pos)
22585 ;; ... without another START-RE in-between.
22586 (goto-char (match-beginning 0))
22587 (not (re-search-backward start-re (1+ beg) t))
22588 ;; Return value.
22589 (cons beg end))))))
22591 (defun org-in-block-p (names)
22592 "Non-nil when point belongs to a block whose name belongs to NAMES.
22594 NAMES is a list of strings containing names of blocks.
22596 Return first block name matched, or nil. Beware that in case of
22597 nested blocks, the returned name may not belong to the closest
22598 block from point."
22599 (save-match-data
22600 (catch 'exit
22601 (let ((case-fold-search t)
22602 (lim-up (save-excursion (outline-previous-heading)))
22603 (lim-down (save-excursion (outline-next-heading))))
22604 (mapc (lambda (name)
22605 (let ((n (regexp-quote name)))
22606 (when (org-between-regexps-p
22607 (concat "^[ \t]*#\\+begin_" n)
22608 (concat "^[ \t]*#\\+end_" n)
22609 lim-up lim-down)
22610 (throw 'exit n))))
22611 names))
22612 nil)))
22614 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22615 "Call `multi-occur' with buffers for all agenda files."
22616 (interactive "sOrg-files matching: ")
22617 (let* ((files (org-agenda-files))
22618 (tnames (mapcar #'file-truename files))
22619 (extra org-agenda-text-search-extra-files))
22620 (when (eq (car extra) 'agenda-archives)
22621 (setq extra (cdr extra))
22622 (setq files (org-add-archive-files files)))
22623 (dolist (f extra)
22624 (unless (member (file-truename f) tnames)
22625 (unless (member f files) (setq files (append files (list f))))
22626 (setq tnames (append tnames (list (file-truename f))))))
22627 (multi-occur
22628 (mapcar (lambda (x)
22629 (with-current-buffer
22630 ;; FIXME: Why not just (find-file-noselect x)?
22631 ;; Is it to avoid the "revert buffer" prompt?
22632 (or (get-file-buffer x) (find-file-noselect x))
22633 (widen)
22634 (current-buffer)))
22635 files)
22636 regexp)))
22638 (if (boundp 'occur-mode-find-occurrence-hook)
22639 ;; Emacs 23
22640 (add-hook 'occur-mode-find-occurrence-hook
22641 (lambda ()
22642 (when (derived-mode-p 'org-mode)
22643 (org-reveal))))
22644 ;; Emacs 22
22645 (defadvice occur-mode-goto-occurrence
22646 (after org-occur-reveal activate)
22647 (and (derived-mode-p 'org-mode) (org-reveal)))
22648 (defadvice occur-mode-goto-occurrence-other-window
22649 (after org-occur-reveal activate)
22650 (and (derived-mode-p 'org-mode) (org-reveal)))
22651 (defadvice occur-mode-display-occurrence
22652 (after org-occur-reveal activate)
22653 (when (derived-mode-p 'org-mode)
22654 (let ((pos (occur-mode-find-occurrence)))
22655 (with-current-buffer (marker-buffer pos)
22656 (save-excursion
22657 (goto-char pos)
22658 (org-reveal)))))))
22660 (defun org-occur-link-in-agenda-files ()
22661 "Create a link and search for it in the agendas.
22662 The link is not stored in `org-stored-links', it is just created
22663 for the search purpose."
22664 (interactive)
22665 (let ((link (condition-case nil
22666 (org-store-link nil)
22667 (error "Unable to create a link to here"))))
22668 (org-occur-in-agenda-files (regexp-quote link))))
22670 (defun org-reverse-string (string)
22671 "Return the reverse of STRING."
22672 (apply 'string (reverse (string-to-list string))))
22674 ;; defsubst org-uniquify must be defined before first use
22676 (defun org-uniquify-alist (alist)
22677 "Merge elements of ALIST with the same key.
22679 For example, in this alist:
22681 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22682 => \\='((a 1 3) (b 2))
22684 merge (a 1) and (a 3) into (a 1 3).
22686 The function returns the new ALIST."
22687 (let (rtn)
22688 (mapc
22689 (lambda (e)
22690 (let (n)
22691 (if (not (assoc (car e) rtn))
22692 (push e rtn)
22693 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22694 (setq rtn (assq-delete-all (car e) rtn))
22695 (push n rtn))))
22696 alist)
22697 rtn))
22699 (defun org-delete-all (elts list)
22700 "Remove all elements in ELTS from LIST."
22701 (while elts
22702 (setq list (delete (pop elts) list)))
22703 list)
22705 (defun org-back-over-empty-lines ()
22706 "Move backwards over whitespace, to the beginning of the first empty line.
22707 Returns the number of empty lines passed."
22708 (let ((pos (point)))
22709 (if (cdr (assoc 'heading org-blank-before-new-entry))
22710 (skip-chars-backward " \t\n\r")
22711 (unless (eobp)
22712 (forward-line -1)))
22713 (beginning-of-line 2)
22714 (goto-char (min (point) pos))
22715 (count-lines (point) pos)))
22717 (defun org-skip-whitespace ()
22718 (skip-chars-forward " \t\n\r"))
22720 (defun org-point-in-group (point group &optional context)
22721 "Check if POINT is in match-group GROUP.
22722 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22723 match. If the match group does not exist or point is not inside it,
22724 return nil."
22725 (and (match-beginning group)
22726 (>= point (match-beginning group))
22727 (<= point (match-end group))
22728 (if context
22729 (list context (match-beginning group) (match-end group))
22730 t)))
22732 (defun org-switch-to-buffer-other-window (&rest args)
22733 "Switch to buffer in a second window on the current frame.
22734 In particular, do not allow pop-up frames.
22735 Returns the newly created buffer."
22736 (org-no-popups
22737 (apply 'switch-to-buffer-other-window args)))
22739 (defun org-combine-plists (&rest plists)
22740 "Create a single property list from all plists in PLISTS.
22741 The process starts by copying the first list, and then setting properties
22742 from the other lists. Settings in the last list are the most significant
22743 ones and overrule settings in the other lists."
22744 (let ((rtn (copy-sequence (pop plists)))
22745 p v ls)
22746 (while plists
22747 (setq ls (pop plists))
22748 (while ls
22749 (setq p (pop ls) v (pop ls))
22750 (setq rtn (plist-put rtn p v))))
22751 rtn))
22753 (defun org-replace-escapes (string table)
22754 "Replace %-escapes in STRING with values in TABLE.
22755 TABLE is an association list with keys like \"%a\" and string values.
22756 The sequences in STRING may contain normal field width and padding information,
22757 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22758 so values can contain further %-escapes if they are define later in TABLE."
22759 (let ((tbl (copy-alist table))
22760 (case-fold-search nil)
22761 (pchg 0)
22762 e re rpl)
22763 (dolist (e tbl)
22764 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22765 (when (and (cdr e) (string-match re (cdr e)))
22766 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22767 (safe "SREF"))
22768 (add-text-properties 0 3 (list 'sref sref) safe)
22769 (setcdr e (replace-match safe t t (cdr e)))))
22770 (while (string-match re string)
22771 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22772 (cdr e)))
22773 (setq string (replace-match rpl t t string))))
22774 (while (setq pchg (next-property-change pchg string))
22775 (let ((sref (get-text-property pchg 'sref string)))
22776 (when (and sref (string-match "SREF" string pchg))
22777 (setq string (replace-match sref t t string)))))
22778 string))
22780 (defun org-sublist (list start end)
22781 "Return a section of LIST, from START to END.
22783 Counting starts at 1."
22784 (cl-subseq list (1- start) end))
22785 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22787 (defun org-find-base-buffer-visiting (file)
22788 "Like `find-buffer-visiting' but always return the base buffer and
22789 not an indirect buffer."
22790 (let ((buf (or (get-file-buffer file)
22791 (find-buffer-visiting file))))
22792 (if buf
22793 (or (buffer-base-buffer buf) buf)
22794 nil)))
22796 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22797 "Org 9.0")
22799 ;;; TODO: Only called once, from ox-odt which should probably use
22800 ;;; org-export-inline-image-p or something.
22801 (defun org-file-image-p (file)
22802 "Return non-nil if FILE is an image."
22803 (save-match-data
22804 (string-match (image-file-name-regexp) file)))
22806 (defun org-get-cursor-date (&optional with-time)
22807 "Return the date at cursor in as a time.
22808 This works in the calendar and in the agenda, anywhere else it just
22809 returns the current time.
22810 If WITH-TIME is non-nil, returns the time of the event at point (in
22811 the agenda) or the current time of the day."
22812 (let (date day defd tp hod mod)
22813 (when with-time
22814 (setq tp (get-text-property (point) 'time))
22815 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22816 (setq hod (string-to-number (match-string 1 tp))
22817 mod (string-to-number (match-string 2 tp))))
22818 (or tp (let ((now (decode-time)))
22819 (setq hod (nth 2 now)
22820 mod (nth 1 now)))))
22821 (cond
22822 ((eq major-mode 'calendar-mode)
22823 (setq date (calendar-cursor-to-date)
22824 defd (encode-time 0 (or mod 0) (or hod 0)
22825 (nth 1 date) (nth 0 date) (nth 2 date))))
22826 ((eq major-mode 'org-agenda-mode)
22827 (setq day (get-text-property (point) 'day))
22828 (when day
22829 (setq date (calendar-gregorian-from-absolute day)
22830 defd (encode-time 0 (or mod 0) (or hod 0)
22831 (nth 1 date) (nth 0 date) (nth 2 date))))))
22832 (or defd (current-time))))
22834 (defun org-mark-subtree (&optional up)
22835 "Mark the current subtree.
22836 This puts point at the start of the current subtree, and mark at
22837 the end. If a numeric prefix UP is given, move up into the
22838 hierarchy of headlines by UP levels before marking the subtree."
22839 (interactive "P")
22840 (org-with-limited-levels
22841 (cond ((org-at-heading-p) (beginning-of-line))
22842 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22843 (t (outline-previous-visible-heading 1))))
22844 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22845 (if (org-called-interactively-p 'any)
22846 (call-interactively 'org-mark-element)
22847 (org-mark-element)))
22850 ;;; Indentation
22852 (defun org--get-expected-indentation (element contentsp)
22853 "Expected indentation column for current line, according to ELEMENT.
22854 ELEMENT is an element containing point. CONTENTSP is non-nil
22855 when indentation is to be computed according to contents of
22856 ELEMENT."
22857 (let ((type (org-element-type element))
22858 (start (org-element-property :begin element))
22859 (post-affiliated (org-element-property :post-affiliated element)))
22860 (org-with-wide-buffer
22861 (cond
22862 (contentsp
22863 (case type
22864 ((diary-sexp footnote-definition) 0)
22865 ((headline inlinetask nil)
22866 (if (not org-adapt-indentation) 0
22867 (let ((level (org-current-level)))
22868 (if level (1+ level) 0))))
22869 ((item plain-list) (org-list-item-body-column post-affiliated))
22871 (goto-char start)
22872 (org-get-indentation))))
22873 ((memq type '(headline inlinetask nil))
22874 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22875 (org--get-expected-indentation element t)
22877 ((memq type '(diary-sexp footnote-definition)) 0)
22878 ;; First paragraph of a footnote definition or an item.
22879 ;; Indent like parent.
22880 ((< (line-beginning-position) start)
22881 (org--get-expected-indentation
22882 (org-element-property :parent element) t))
22883 ;; At first line: indent according to previous sibling, if any,
22884 ;; ignoring footnote definitions and inline tasks, or parent's
22885 ;; contents.
22886 ((= (line-beginning-position) start)
22887 (catch 'exit
22888 (while t
22889 (if (= (point-min) start) (throw 'exit 0)
22890 (goto-char (1- start))
22891 (let* ((previous (org-element-at-point))
22892 (parent previous))
22893 (while (and parent (<= (org-element-property :end parent) start))
22894 (setq previous parent
22895 parent (org-element-property :parent parent)))
22896 (cond
22897 ((not previous) (throw 'exit 0))
22898 ((> (org-element-property :end previous) start)
22899 (throw 'exit (org--get-expected-indentation previous t)))
22900 ((memq (org-element-type previous)
22901 '(footnote-definition inlinetask))
22902 (setq start (org-element-property :begin previous)))
22903 (t (goto-char (org-element-property :begin previous))
22904 (throw 'exit
22905 (if (bolp) (org-get-indentation)
22906 ;; At first paragraph in an item or
22907 ;; a footnote definition.
22908 (org--get-expected-indentation
22909 (org-element-property :parent previous) t))))))))))
22910 ;; Otherwise, move to the first non-blank line above.
22912 (beginning-of-line)
22913 (let ((pos (point)))
22914 (skip-chars-backward " \r\t\n")
22915 (cond
22916 ;; Two blank lines end a footnote definition or a plain
22917 ;; list. When we indent an empty line after them, the
22918 ;; containing list or footnote definition is over, so it
22919 ;; qualifies as a previous sibling. Therefore, we indent
22920 ;; like its first line.
22921 ((and (memq type '(footnote-definition plain-list))
22922 (> (count-lines (point) pos) 2))
22923 (goto-char start)
22924 (org-get-indentation))
22925 ;; Line above is the first one of a paragraph at the
22926 ;; beginning of an item or a footnote definition. Indent
22927 ;; like parent.
22928 ((< (line-beginning-position) start)
22929 (org--get-expected-indentation
22930 (org-element-property :parent element) t))
22931 ;; Line above is the beginning of an element, i.e., point
22932 ;; was originally on the blank lines between element's start
22933 ;; and contents.
22934 ((= (line-beginning-position) post-affiliated)
22935 (org--get-expected-indentation element t))
22936 ;; POS is after contents in a greater element. Indent like
22937 ;; the beginning of the element.
22939 ;; As a special case, if point is at the end of a footnote
22940 ;; definition or an item, indent like the very last element
22941 ;; within.
22942 ((and (not (eq type 'paragraph))
22943 (let ((cend (org-element-property :contents-end element)))
22944 (and cend (<= cend pos))))
22945 (if (memq type '(footnote-definition item plain-list))
22946 (let ((last (org-element-at-point)))
22947 (org--get-expected-indentation
22948 last
22949 (memq (org-element-type last)
22950 '(footnote-definition item plain-list))))
22951 (goto-char start)
22952 (org-get-indentation)))
22953 ;; In any other case, indent like the current line.
22954 (t (org-get-indentation)))))))))
22956 (defun org--align-node-property ()
22957 "Align node property at point.
22958 Alignment is done according to `org-property-format', which see."
22959 (when (save-excursion
22960 (beginning-of-line)
22961 (looking-at org-property-re))
22962 (replace-match
22963 (concat (match-string 4)
22964 (org-trim
22965 (format org-property-format (match-string 1) (match-string 3))))
22966 t t)))
22968 (defun org-indent-line ()
22969 "Indent line depending on context.
22971 Indentation is done according to the following rules:
22973 - Footnote definitions, diary sexps, headlines and inline tasks
22974 have to start at column 0.
22976 - On the very first line of an element, consider, in order, the
22977 next rules until one matches:
22979 1. If there's a sibling element before, ignoring footnote
22980 definitions and inline tasks, indent like its first line.
22982 2. If element has a parent, indent like its contents. More
22983 precisely, if parent is an item, indent after the
22984 description part, if any, or the bullet (see
22985 `org-list-description-max-indent'). Else, indent like
22986 parent's first line.
22988 3. Otherwise, indent relatively to current level, if
22989 `org-adapt-indentation' is non-nil, or to left margin.
22991 - On a blank line at the end of an element, indent according to
22992 the type of the element. More precisely
22994 1. If element is a plain list, an item, or a footnote
22995 definition, indent like the very last element within.
22997 2. If element is a paragraph, indent like its last non blank
22998 line.
23000 3. Otherwise, indent like its very first line.
23002 - In the code part of a source block, use language major mode
23003 to indent current line if `org-src-tab-acts-natively' is
23004 non-nil. If it is nil, do nothing.
23006 - Otherwise, indent like the first non-blank line above.
23008 The function doesn't indent an item as it could break the whole
23009 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23010 \\[org-shiftmetaright].
23012 Also align node properties according to `org-property-format'."
23013 (interactive)
23014 (cond
23015 (orgstruct-is-++
23016 (let ((indent-line-function
23017 (cadadr (assq 'indent-line-function org-fb-vars))))
23018 (indent-according-to-mode)))
23019 ((org-at-heading-p) 'noindent)
23021 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23022 (type (org-element-type element)))
23023 (cond ((and (memq type '(plain-list item))
23024 (= (line-beginning-position)
23025 (org-element-property :post-affiliated element)))
23026 'noindent)
23027 ((and (eq type 'src-block)
23028 org-src-tab-acts-natively
23029 (> (line-beginning-position)
23030 (org-element-property :post-affiliated element))
23031 (< (line-beginning-position)
23032 (org-with-wide-buffer
23033 (goto-char (org-element-property :end element))
23034 (skip-chars-backward " \r\t\n")
23035 (line-beginning-position))))
23036 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23038 (let ((column (org--get-expected-indentation element nil)))
23039 ;; Preserve current column.
23040 (if (<= (current-column) (current-indentation))
23041 (org-indent-line-to column)
23042 (save-excursion (org-indent-line-to column))))
23043 ;; Align node property. Also preserve current column.
23044 (when (eq type 'node-property)
23045 (let ((column (current-column)))
23046 (org--align-node-property)
23047 (org-move-to-column column)))))))))
23049 (defun org-indent-region (start end)
23050 "Indent each non-blank line in the region.
23051 Called from a program, START and END specify the region to
23052 indent. The function will not indent contents of example blocks,
23053 verse blocks and export blocks as leading white spaces are
23054 assumed to be significant there."
23055 (interactive "r")
23056 (save-excursion
23057 (goto-char start)
23058 (skip-chars-forward " \r\t\n")
23059 (unless (eobp) (beginning-of-line))
23060 (let ((indent-to
23061 (lambda (ind pos)
23062 ;; Set IND as indentation for all lines between point and
23063 ;; POS or END, whichever comes first. Blank lines are
23064 ;; ignored. Leave point after POS once done.
23065 (let ((limit (copy-marker (min end pos))))
23066 (while (< (point) limit)
23067 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23068 (forward-line))
23069 (set-marker limit nil))))
23070 (end (copy-marker end)))
23071 (while (< (point) end)
23072 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23073 (let* ((element (org-element-at-point))
23074 (type (org-element-type element))
23075 (element-end (copy-marker (org-element-property :end element)))
23076 (ind (org--get-expected-indentation element nil)))
23077 (cond
23078 ((or (memq type '(paragraph table table-row))
23079 (not (or (org-element-property :contents-begin element)
23080 (memq type
23081 '(example-block export-block src-block)))))
23082 ;; Elements here are indented as a single block. Also
23083 ;; align node properties.
23084 (when (eq type 'node-property)
23085 (org--align-node-property)
23086 (beginning-of-line))
23087 (funcall indent-to ind element-end))
23089 ;; Elements in this category consist of three parts:
23090 ;; before the contents, the contents, and after the
23091 ;; contents. The contents are treated specially,
23092 ;; according to the element type, or not indented at
23093 ;; all. Other parts are indented as a single block.
23094 (let* ((post (copy-marker
23095 (org-element-property :post-affiliated element)))
23096 (cbeg
23097 (copy-marker
23098 (cond
23099 ((not (org-element-property :contents-begin element))
23100 ;; Fake contents for source blocks.
23101 (org-with-wide-buffer
23102 (goto-char post)
23103 (forward-line)
23104 (point)))
23105 ((memq type '(footnote-definition item plain-list))
23106 ;; Contents in these elements could start on
23107 ;; the same line as the beginning of the
23108 ;; element. Make sure we start indenting
23109 ;; from the second line.
23110 (org-with-wide-buffer
23111 (goto-char post)
23112 (end-of-line)
23113 (skip-chars-forward " \r\t\n")
23114 (if (eobp) (point) (line-beginning-position))))
23115 (t (org-element-property :contents-begin element)))))
23116 (cend (copy-marker
23117 (or (org-element-property :contents-end element)
23118 ;; Fake contents for source blocks.
23119 (org-with-wide-buffer
23120 (goto-char element-end)
23121 (skip-chars-backward " \r\t\n")
23122 (line-beginning-position)))
23123 t)))
23124 ;; Do not change items indentation individually as it
23125 ;; might break the list as a whole. On the other
23126 ;; hand, when at a plain list, indent it as a whole.
23127 (cond ((eq type 'plain-list)
23128 (let ((offset (- ind (org-get-indentation))))
23129 (unless (zerop offset)
23130 (indent-rigidly (org-element-property :begin element)
23131 (org-element-property :end element)
23132 offset))
23133 (goto-char cbeg)))
23134 ((eq type 'item) (goto-char cbeg))
23135 (t (funcall indent-to ind cbeg)))
23136 (when (< (point) end)
23137 (case type
23138 ((example-block export-block verse-block))
23139 (src-block
23140 ;; In a source block, indent source code
23141 ;; according to language major mode, but only if
23142 ;; `org-src-tab-acts-natively' is non-nil.
23143 (when (and (< (point) end) org-src-tab-acts-natively)
23144 (ignore-errors
23145 (org-babel-do-in-edit-buffer
23146 (indent-region (point-min) (point-max))))))
23147 (t (org-indent-region (point) (min cend end))))
23148 (goto-char (min cend end))
23149 (when (< (point) end) (funcall indent-to ind element-end)))
23150 (set-marker post nil)
23151 (set-marker cbeg nil)
23152 (set-marker cend nil))))
23153 (set-marker element-end nil))))
23154 (set-marker end nil))))
23156 (defun org-indent-drawer ()
23157 "Indent the drawer at point."
23158 (interactive)
23159 (unless (save-excursion
23160 (beginning-of-line)
23161 (org-looking-at-p org-drawer-regexp))
23162 (user-error "Not at a drawer"))
23163 (let ((element (org-element-at-point)))
23164 (unless (memq (org-element-type element) '(drawer property-drawer))
23165 (user-error "Not at a drawer"))
23166 (org-with-wide-buffer
23167 (org-indent-region (org-element-property :begin element)
23168 (org-element-property :end element))))
23169 (message "Drawer at point indented"))
23171 (defun org-indent-block ()
23172 "Indent the block at point."
23173 (interactive)
23174 (unless (save-excursion
23175 (beginning-of-line)
23176 (let ((case-fold-search t))
23177 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23178 (user-error "Not at a block"))
23179 (let ((element (org-element-at-point)))
23180 (unless (memq (org-element-type element)
23181 '(comment-block center-block dynamic-block example-block
23182 export-block quote-block special-block
23183 src-block verse-block))
23184 (user-error "Not at a block"))
23185 (org-with-wide-buffer
23186 (org-indent-region (org-element-property :begin element)
23187 (org-element-property :end element))))
23188 (message "Block at point indented"))
23191 ;;; Filling
23193 ;; We use our own fill-paragraph and auto-fill functions.
23195 ;; `org-fill-paragraph' relies on adaptive filling and context
23196 ;; checking. Appropriate `fill-prefix' is computed with
23197 ;; `org-adaptive-fill-function'.
23199 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23200 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23201 ;; `org-adaptive-fill-function' value. Internally,
23202 ;; `org-comment-line-break-function' breaks the line.
23204 ;; `org-setup-filling' installs filling and auto-filling related
23205 ;; variables during `org-mode' initialization.
23207 (defvar org-element-paragraph-separate) ; org-element.el
23208 (defun org-setup-filling ()
23209 (require 'org-element)
23210 ;; Prevent auto-fill from inserting unwanted new items.
23211 (when (boundp 'fill-nobreak-predicate)
23212 (setq-local
23213 fill-nobreak-predicate
23214 (org-uniquify
23215 (append fill-nobreak-predicate
23216 '(org-fill-line-break-nobreak-p
23217 org-fill-paragraph-with-timestamp-nobreak-p)))))
23218 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23219 (setq-local paragraph-start paragraph-ending)
23220 (setq-local paragraph-separate paragraph-ending))
23221 (setq-local fill-paragraph-function 'org-fill-paragraph)
23222 (setq-local auto-fill-inhibit-regexp nil)
23223 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23224 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23225 (setq-local comment-line-break-function 'org-comment-line-break-function))
23227 (defun org-fill-line-break-nobreak-p ()
23228 "Non-nil when a new line at point would create an Org line break."
23229 (save-excursion
23230 (skip-chars-backward "[ \t]")
23231 (skip-chars-backward "\\\\")
23232 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23234 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23235 "Non-nil when a new line at point would split a timestamp."
23236 (and (org-at-timestamp-p t)
23237 (not (looking-at org-ts-regexp-both))))
23239 (declare-function message-in-body-p "message" ())
23240 (defvar orgtbl-line-start-regexp) ; From org-table.el
23241 (defun org-adaptive-fill-function ()
23242 "Compute a fill prefix for the current line.
23243 Return fill prefix, as a string, or nil if current line isn't
23244 meant to be filled. For convenience, if `adaptive-fill-regexp'
23245 matches in paragraphs or comments, use it."
23246 (catch 'exit
23247 (when (derived-mode-p 'message-mode)
23248 (save-excursion
23249 (beginning-of-line)
23250 (cond ((not (message-in-body-p)) (throw 'exit nil))
23251 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23252 ((looking-at message-cite-prefix-regexp)
23253 (throw 'exit (match-string-no-properties 0)))
23254 ((looking-at org-outline-regexp)
23255 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23256 (org-with-wide-buffer
23257 (unless (org-at-heading-p)
23258 (let* ((p (line-beginning-position))
23259 (element (save-excursion
23260 (beginning-of-line)
23261 (org-element-at-point)))
23262 (type (org-element-type element))
23263 (post-affiliated (org-element-property :post-affiliated element)))
23264 (unless (< p post-affiliated)
23265 (case type
23266 (comment
23267 (save-excursion
23268 (beginning-of-line)
23269 (looking-at "[ \t]*")
23270 (concat (match-string 0) "# ")))
23271 (footnote-definition "")
23272 ((item plain-list)
23273 (make-string (org-list-item-body-column post-affiliated) ?\s))
23274 (paragraph
23275 ;; Fill prefix is usually the same as the current line,
23276 ;; unless the paragraph is at the beginning of an item.
23277 (let ((parent (org-element-property :parent element)))
23278 (save-excursion
23279 (beginning-of-line)
23280 (cond ((eq (org-element-type parent) 'item)
23281 (make-string (org-list-item-body-column
23282 (org-element-property :begin parent))
23283 ?\s))
23284 ((and adaptive-fill-regexp
23285 ;; Locally disable
23286 ;; `adaptive-fill-function' to let
23287 ;; `fill-context-prefix' handle
23288 ;; `adaptive-fill-regexp' variable.
23289 (let (adaptive-fill-function)
23290 (fill-context-prefix
23291 post-affiliated
23292 (org-element-property :end element)))))
23293 ((looking-at "[ \t]+") (match-string 0))
23294 (t "")))))
23295 (comment-block
23296 ;; Only fill contents if P is within block boundaries.
23297 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23298 (forward-line)
23299 (point)))
23300 (cend (save-excursion
23301 (goto-char (org-element-property :end element))
23302 (skip-chars-backward " \r\t\n")
23303 (line-beginning-position))))
23304 (when (and (>= p cbeg) (< p cend))
23305 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23306 (match-string 0)
23307 "")))))))))))
23309 (declare-function message-goto-body "message" ())
23310 (defvar message-cite-prefix-regexp) ; From message.el
23311 (defun org-fill-paragraph (&optional justify)
23312 "Fill element at point, when applicable.
23314 This function only applies to comment blocks, comments, example
23315 blocks and paragraphs. Also, as a special case, re-align table
23316 when point is at one.
23318 If JUSTIFY is non-nil (interactively, with prefix argument),
23319 justify as well. If `sentence-end-double-space' is non-nil, then
23320 period followed by one space does not end a sentence, so don't
23321 break a line there. The variable `fill-column' controls the
23322 width for filling.
23324 For convenience, when point is at a plain list, an item or
23325 a footnote definition, try to fill the first paragraph within."
23326 (interactive)
23327 (if (and (derived-mode-p 'message-mode)
23328 (or (not (message-in-body-p))
23329 (save-excursion (move-beginning-of-line 1)
23330 (looking-at message-cite-prefix-regexp))))
23331 ;; First ensure filling is correct in message-mode.
23332 (let ((fill-paragraph-function
23333 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23334 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23335 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23336 (paragraph-separate
23337 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23338 (fill-paragraph nil))
23339 (with-syntax-table org-mode-transpose-word-syntax-table
23340 ;; Move to end of line in order to get the first paragraph
23341 ;; within a plain list or a footnote definition.
23342 (let ((element (save-excursion
23343 (end-of-line)
23344 (or (ignore-errors (org-element-at-point))
23345 (user-error "An element cannot be parsed line %d"
23346 (line-number-at-pos (point)))))))
23347 ;; First check if point is in a blank line at the beginning of
23348 ;; the buffer. In that case, ignore filling.
23349 (case (org-element-type element)
23350 ;; Use major mode filling function is src blocks.
23351 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23352 ;; Align Org tables, leave table.el tables as-is.
23353 (table-row (org-table-align) t)
23354 (table
23355 (when (eq (org-element-property :type element) 'org)
23356 (save-excursion
23357 (goto-char (org-element-property :post-affiliated element))
23358 (org-table-align)))
23360 (paragraph
23361 ;; Paragraphs may contain `line-break' type objects.
23362 (let ((beg (max (point-min)
23363 (org-element-property :contents-begin element)))
23364 (end (min (point-max)
23365 (org-element-property :contents-end element))))
23366 ;; Do nothing if point is at an affiliated keyword.
23367 (if (< (line-end-position) beg) t
23368 (when (derived-mode-p 'message-mode)
23369 ;; In `message-mode', do not fill following citation
23370 ;; in current paragraph nor text before message body.
23371 (let ((body-start (save-excursion (message-goto-body))))
23372 (when body-start (setq beg (max body-start beg))))
23373 (when (save-excursion
23374 (re-search-forward
23375 (concat "^" message-cite-prefix-regexp) end t))
23376 (setq end (match-beginning 0))))
23377 ;; Fill paragraph, taking line breaks into account.
23378 (save-excursion
23379 (goto-char beg)
23380 (let ((cuts (list beg)))
23381 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23382 (when (eq 'line-break
23383 (org-element-type
23384 (save-excursion (backward-char)
23385 (org-element-context))))
23386 (push (point) cuts)))
23387 (dolist (c (delq end cuts))
23388 (fill-region-as-paragraph c end justify)
23389 (setq end c))))
23390 t)))
23391 ;; Contents of `comment-block' type elements should be
23392 ;; filled as plain text, but only if point is within block
23393 ;; markers.
23394 (comment-block
23395 (let* ((case-fold-search t)
23396 (beg (save-excursion
23397 (goto-char (org-element-property :begin element))
23398 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23399 (forward-line)
23400 (point)))
23401 (end (save-excursion
23402 (goto-char (org-element-property :end element))
23403 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23404 (line-beginning-position))))
23405 (if (or (< (point) beg) (> (point) end)) t
23406 (fill-region-as-paragraph
23407 (save-excursion (end-of-line)
23408 (re-search-backward "^[ \t]*$" beg 'move)
23409 (line-beginning-position))
23410 (save-excursion (beginning-of-line)
23411 (re-search-forward "^[ \t]*$" end 'move)
23412 (line-beginning-position))
23413 justify))))
23414 ;; Fill comments.
23415 (comment
23416 (let ((begin (org-element-property :post-affiliated element))
23417 (end (org-element-property :end element)))
23418 (when (and (>= (point) begin) (<= (point) end))
23419 (let ((begin (save-excursion
23420 (end-of-line)
23421 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23422 (progn (forward-line) (point))
23423 begin)))
23424 (end (save-excursion
23425 (end-of-line)
23426 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23427 (1- (line-beginning-position))
23428 (skip-chars-backward " \r\t\n")
23429 (line-end-position)))))
23430 ;; Do not fill comments when at a blank line.
23431 (when (> end begin)
23432 (let ((fill-prefix
23433 (save-excursion
23434 (beginning-of-line)
23435 (looking-at "[ \t]*#")
23436 (let ((comment-prefix (match-string 0)))
23437 (goto-char (match-end 0))
23438 (if (looking-at adaptive-fill-regexp)
23439 (concat comment-prefix (match-string 0))
23440 (concat comment-prefix " "))))))
23441 (save-excursion
23442 (fill-region-as-paragraph begin end justify))))))
23444 ;; Ignore every other element.
23445 (otherwise t))))))
23447 (defun org-auto-fill-function ()
23448 "Auto-fill function."
23449 ;; Check if auto-filling is meaningful.
23450 (let ((fc (current-fill-column)))
23451 (when (and fc (> (current-column) fc))
23452 (let* ((fill-prefix (org-adaptive-fill-function))
23453 ;; Enforce empty fill prefix, if required. Otherwise, it
23454 ;; will be computed again.
23455 (adaptive-fill-mode (not (equal fill-prefix ""))))
23456 (when fill-prefix (do-auto-fill))))))
23458 (defun org-comment-line-break-function (&optional soft)
23459 "Break line at point and indent, continuing comment if within one.
23460 The inserted newline is marked hard if variable
23461 `use-hard-newlines' is true, unless optional argument SOFT is
23462 non-nil."
23463 (if soft (insert-and-inherit ?\n) (newline 1))
23464 (save-excursion (forward-char -1) (delete-horizontal-space))
23465 (delete-horizontal-space)
23466 (indent-to-left-margin)
23467 (insert-before-markers-and-inherit fill-prefix))
23470 ;;; Fixed Width Areas
23472 (defun org-toggle-fixed-width ()
23473 "Toggle fixed-width markup.
23475 Add or remove fixed-width markup on current line, whenever it
23476 makes sense. Return an error otherwise.
23478 If a region is active and if it contains only fixed-width areas
23479 or blank lines, remove all fixed-width markup in it. If the
23480 region contains anything else, convert all non-fixed-width lines
23481 to fixed-width ones.
23483 Blank lines at the end of the region are ignored unless the
23484 region only contains such lines."
23485 (interactive)
23486 (if (not (org-region-active-p))
23487 ;; No region:
23489 ;; Remove fixed width marker only in a fixed-with element.
23491 ;; Add fixed width maker in paragraphs, in blank lines after
23492 ;; elements or at the beginning of a headline or an inlinetask,
23493 ;; and before any one-line elements (e.g., a clock).
23494 (progn
23495 (beginning-of-line)
23496 (let* ((element (org-element-at-point))
23497 (type (org-element-type element)))
23498 (cond
23499 ((and (eq type 'fixed-width)
23500 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23501 (replace-match
23502 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23503 ((and (memq type '(babel-call clock comment diary-sexp headline
23504 horizontal-rule keyword paragraph
23505 planning))
23506 (<= (org-element-property :post-affiliated element) (point)))
23507 (skip-chars-forward " \t")
23508 (insert ": "))
23509 ((and (org-looking-at-p "[ \t]*$")
23510 (or (eq type 'inlinetask)
23511 (save-excursion
23512 (skip-chars-forward " \r\t\n")
23513 (<= (org-element-property :end element) (point)))))
23514 (delete-region (point) (line-end-position))
23515 (org-indent-line)
23516 (insert ": "))
23517 (t (user-error "Cannot insert a fixed-width line here")))))
23518 ;; Region active.
23519 (let* ((begin (save-excursion
23520 (goto-char (region-beginning))
23521 (line-beginning-position)))
23522 (end (copy-marker
23523 (save-excursion
23524 (goto-char (region-end))
23525 (unless (eolp) (beginning-of-line))
23526 (if (save-excursion (re-search-backward "\\S-" begin t))
23527 (progn (skip-chars-backward " \r\t\n") (point))
23528 (point)))))
23529 (all-fixed-width-p
23530 (catch 'not-all-p
23531 (save-excursion
23532 (goto-char begin)
23533 (skip-chars-forward " \r\t\n")
23534 (when (eobp) (throw 'not-all-p nil))
23535 (while (< (point) end)
23536 (let ((element (org-element-at-point)))
23537 (if (eq (org-element-type element) 'fixed-width)
23538 (goto-char (org-element-property :end element))
23539 (throw 'not-all-p nil))))
23540 t))))
23541 (if all-fixed-width-p
23542 (save-excursion
23543 (goto-char begin)
23544 (while (< (point) end)
23545 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23546 (replace-match
23547 "" nil nil nil
23548 (if (= (line-end-position) (match-end 0)) 0 1)))
23549 (forward-line)))
23550 (let ((min-ind (point-max)))
23551 ;; Find minimum indentation across all lines.
23552 (save-excursion
23553 (goto-char begin)
23554 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23555 (setq min-ind 0)
23556 (catch 'zerop
23557 (while (< (point) end)
23558 (unless (org-looking-at-p "[ \t]*$")
23559 (let ((ind (org-get-indentation)))
23560 (setq min-ind (min min-ind ind))
23561 (when (zerop ind) (throw 'zerop t))))
23562 (forward-line)))))
23563 ;; Loop over all lines and add fixed-width markup everywhere
23564 ;; but in fixed-width lines.
23565 (save-excursion
23566 (goto-char begin)
23567 (while (< (point) end)
23568 (cond
23569 ((org-at-heading-p)
23570 (insert ": ")
23571 (forward-line)
23572 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23573 (insert ":")
23574 (forward-line)))
23575 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23576 (let* ((element (org-element-at-point))
23577 (element-end (org-element-property :end element)))
23578 (if (eq (org-element-type element) 'fixed-width)
23579 (progn (goto-char element-end)
23580 (skip-chars-backward " \r\t\n")
23581 (forward-line))
23582 (let ((limit (min end element-end)))
23583 (while (< (point) limit)
23584 (org-move-to-column min-ind t)
23585 (insert ": ")
23586 (forward-line))))))
23588 (org-move-to-column min-ind t)
23589 (insert ": ")
23590 (forward-line)))))))
23591 (set-marker end nil))))
23594 ;;; Comments
23596 ;; Org comments syntax is quite complex. It requires the entire line
23597 ;; to be just a comment. Also, even with the right syntax at the
23598 ;; beginning of line, some some elements (i.e. verse-block or
23599 ;; example-block) don't accept comments. Usual Emacs comment commands
23600 ;; cannot cope with those requirements. Therefore, Org replaces them.
23602 ;; Org still relies on `comment-dwim', but cannot trust
23603 ;; `comment-only-p'. So, `comment-region-function' and
23604 ;; `uncomment-region-function' both point
23605 ;; to`org-comment-or-uncomment-region'. Eventually,
23606 ;; `org-insert-comment' takes care of insertion of comments at the
23607 ;; beginning of line.
23609 ;; `org-setup-comments-handling' install comments related variables
23610 ;; during `org-mode' initialization.
23612 (defun org-setup-comments-handling ()
23613 (interactive)
23614 (setq-local comment-use-syntax nil)
23615 (setq-local comment-start "# ")
23616 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23617 (setq-local comment-insert-comment-function 'org-insert-comment)
23618 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23619 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23621 (defun org-insert-comment ()
23622 "Insert an empty comment above current line.
23623 If the line is empty, insert comment at its beginning. When
23624 point is within a source block, comment according to the related
23625 major mode."
23626 (if (let ((element (org-element-at-point)))
23627 (and (eq (org-element-type element) 'src-block)
23628 (< (save-excursion
23629 (goto-char (org-element-property :post-affiliated element))
23630 (line-end-position))
23631 (point))
23632 (> (save-excursion
23633 (goto-char (org-element-property :end element))
23634 (skip-chars-backward " \r\t\n")
23635 (line-beginning-position))
23636 (point))))
23637 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23638 (beginning-of-line)
23639 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23640 (open-line 1))
23641 (org-indent-line)
23642 (insert "# ")))
23644 (defvar comment-empty-lines) ; From newcomment.el.
23645 (defun org-comment-or-uncomment-region (beg end &rest _)
23646 "Comment or uncomment each non-blank line in the region.
23647 Uncomment each non-blank line between BEG and END if it only
23648 contains commented lines. Otherwise, comment them. If region is
23649 strictly within a source block, use appropriate comment syntax."
23650 (if (let ((element (org-element-at-point)))
23651 (and (eq (org-element-type element) 'src-block)
23652 (< (save-excursion
23653 (goto-char (org-element-property :post-affiliated element))
23654 (line-end-position))
23655 beg)
23656 (>= (save-excursion
23657 (goto-char (org-element-property :end element))
23658 (skip-chars-backward " \r\t\n")
23659 (line-beginning-position))
23660 end)))
23661 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23662 (save-restriction
23663 ;; Restrict region
23664 (narrow-to-region (save-excursion (goto-char beg)
23665 (skip-chars-forward " \r\t\n" end)
23666 (line-beginning-position))
23667 (save-excursion (goto-char end)
23668 (skip-chars-backward " \r\t\n" beg)
23669 (line-end-position)))
23670 (let ((uncommentp
23671 ;; UNCOMMENTP is non-nil when every non blank line between
23672 ;; BEG and END is a comment.
23673 (save-excursion
23674 (goto-char (point-min))
23675 (while (and (not (eobp))
23676 (let ((element (org-element-at-point)))
23677 (and (eq (org-element-type element) 'comment)
23678 (goto-char (min (point-max)
23679 (org-element-property
23680 :end element)))))))
23681 (eobp))))
23682 (if uncommentp
23683 ;; Only blank lines and comments in region: uncomment it.
23684 (save-excursion
23685 (goto-char (point-min))
23686 (while (not (eobp))
23687 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23688 (replace-match "" nil nil nil 1))
23689 (forward-line)))
23690 ;; Comment each line in region.
23691 (let ((min-indent (point-max)))
23692 ;; First find the minimum indentation across all lines.
23693 (save-excursion
23694 (goto-char (point-min))
23695 (while (and (not (eobp)) (not (zerop min-indent)))
23696 (unless (looking-at "[ \t]*$")
23697 (setq min-indent (min min-indent (current-indentation))))
23698 (forward-line)))
23699 ;; Then loop over all lines.
23700 (save-excursion
23701 (goto-char (point-min))
23702 (while (not (eobp))
23703 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23704 ;; Don't get fooled by invisible text (e.g. link path)
23705 ;; when moving to column MIN-INDENT.
23706 (let ((buffer-invisibility-spec nil))
23707 (org-move-to-column min-indent t))
23708 (insert comment-start))
23709 (forward-line)))))))))
23711 (defun org-comment-dwim (arg)
23712 "Call `comment-dwim' within a source edit buffer if needed."
23713 (interactive "*P")
23714 (if (org-in-src-block-p)
23715 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23716 (call-interactively 'comment-dwim)))
23719 ;;; Timestamps API
23721 ;; This section contains tools to operate on timestamp objects, as
23722 ;; returned by, e.g. `org-element-context'.
23724 (defun org-timestamp--to-internal-time (timestamp &optional end)
23725 "Encode TIMESTAMP object into Emacs internal time.
23726 Use end of date range or time range when END is non-nil."
23727 (apply #'encode-time
23728 (cons 0
23729 (mapcar
23730 (lambda (prop) (or (org-element-property prop timestamp) 0))
23731 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23732 '(:minute-start :hour-start :day-start :month-start
23733 :year-start))))))
23735 (defun org-timestamp-has-time-p (timestamp)
23736 "Non-nil when TIMESTAMP has a time specified."
23737 (org-element-property :hour-start timestamp))
23739 (defun org-timestamp-format (timestamp format &optional end utc)
23740 "Format a TIMESTAMP object into a string.
23742 FORMAT is a format specifier to be passed to
23743 `format-time-string'.
23745 When optional argument END is non-nil, use end of date-range or
23746 time-range, if possible.
23748 When optional argument UTC is non-nil, time will be expressed as
23749 Universal Time."
23750 (format-time-string
23751 format (org-timestamp--to-internal-time timestamp end) utc))
23753 (defun org-timestamp-split-range (timestamp &optional end)
23754 "Extract a TIMESTAMP object from a date or time range.
23756 END, when non-nil, means extract the end of the range.
23757 Otherwise, extract its start.
23759 Return a new timestamp object."
23760 (let ((type (org-element-property :type timestamp)))
23761 (if (memq type '(active inactive diary)) timestamp
23762 (let ((split-ts (org-element-copy timestamp)))
23763 ;; Set new type.
23764 (org-element-put-property
23765 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23766 ;; Copy start properties over end properties if END is
23767 ;; non-nil. Otherwise, copy end properties over `start' ones.
23768 (let ((p-alist '((:minute-start . :minute-end)
23769 (:hour-start . :hour-end)
23770 (:day-start . :day-end)
23771 (:month-start . :month-end)
23772 (:year-start . :year-end))))
23773 (dolist (p-cell p-alist)
23774 (org-element-put-property
23775 split-ts
23776 (funcall (if end #'car #'cdr) p-cell)
23777 (org-element-property
23778 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23779 ;; Eventually refresh `:raw-value'.
23780 (org-element-put-property split-ts :raw-value nil)
23781 (org-element-put-property
23782 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23784 (defun org-timestamp-translate (timestamp &optional boundary)
23785 "Translate TIMESTAMP object to custom format.
23787 Format string is defined in `org-time-stamp-custom-formats',
23788 which see.
23790 When optional argument BOUNDARY is non-nil, it is either the
23791 symbol `start' or `end'. In this case, only translate the
23792 starting or ending part of TIMESTAMP if it is a date or time
23793 range. Otherwise, translate both parts.
23795 Return timestamp as-is if `org-display-custom-times' is nil or if
23796 it has a `diary' type."
23797 (let ((type (org-element-property :type timestamp)))
23798 (if (or (not org-display-custom-times) (eq type 'diary))
23799 (org-element-interpret-data timestamp)
23800 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23801 org-time-stamp-custom-formats)))
23802 (if (and (not boundary) (memq type '(active-range inactive-range)))
23803 (concat (org-timestamp-format timestamp fmt)
23804 "--"
23805 (org-timestamp-format timestamp fmt t))
23806 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23810 ;;; Other stuff.
23812 (defvar reftex-docstruct-symbol)
23813 (defvar reftex-cite-format)
23814 (defvar org--rds)
23816 (defun org-reftex-citation ()
23817 "Use reftex-citation to insert a citation into the buffer.
23818 This looks for a line like
23820 #+BIBLIOGRAPHY: foo plain option:-d
23822 and derives from it that foo.bib is the bibliography file relevant
23823 for this document. It then installs the necessary environment for RefTeX
23824 to work in this buffer and calls `reftex-citation' to insert a citation
23825 into the buffer.
23827 Export of such citations to both LaTeX and HTML is handled by the contributed
23828 package ox-bibtex by Taru Karttunen."
23829 (interactive)
23830 (let ((reftex-docstruct-symbol 'org--rds)
23831 (reftex-cite-format "\\cite{%l}")
23832 org--rds bib)
23833 (save-excursion
23834 (save-restriction
23835 (widen)
23836 (let ((case-fold-search t)
23837 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23838 (if (not (save-excursion
23839 (or (re-search-forward re nil t)
23840 (re-search-backward re nil t))))
23841 (user-error "No bibliography defined in file")
23842 (setq bib (concat (match-string 1) ".bib")
23843 org--rds (list (list 'bib bib)))))))
23844 (call-interactively 'reftex-citation)))
23846 ;;;; Functions extending outline functionality
23848 (defun org-beginning-of-line (&optional arg)
23849 "Go to the beginning of the current line. If that is invisible, continue
23850 to a visible line beginning. This makes the function of C-a more intuitive.
23851 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23852 first attempt, and only move to after the tags when the cursor is already
23853 beyond the end of the headline."
23854 (interactive "P")
23855 (let ((pos (point))
23856 (special (if (consp org-special-ctrl-a/e)
23857 (car org-special-ctrl-a/e)
23858 org-special-ctrl-a/e))
23859 deactivate-mark refpos)
23860 (if (org-bound-and-true-p visual-line-mode)
23861 (beginning-of-visual-line 1)
23862 (beginning-of-line 1))
23863 (if (and arg (fboundp 'move-beginning-of-line))
23864 (call-interactively 'move-beginning-of-line)
23865 (unless (bobp)
23866 (backward-char 1)
23867 (if (org-truely-invisible-p)
23868 (while (and (not (bobp)) (org-truely-invisible-p))
23869 (backward-char 1)
23870 (beginning-of-line 1))
23871 (forward-char 1))))
23872 (when special
23873 (cond
23874 ((and (looking-at org-complex-heading-regexp)
23875 (eq (char-after (match-end 1)) ?\s))
23876 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23877 (point-at-eol)))
23878 (goto-char
23879 (if (eq special t)
23880 (cond ((> pos refpos) refpos)
23881 ((= pos (point)) refpos)
23882 (t (point)))
23883 (cond ((> pos (point)) (point))
23884 ((not (eq last-command this-command)) (point))
23885 (t refpos)))))
23886 ((org-at-item-p)
23887 ;; Being at an item and not looking at an the item means point
23888 ;; was previously moved to beginning of a visual line, which
23889 ;; doesn't contain the item. Therefore, do nothing special,
23890 ;; just stay here.
23891 (when (looking-at org-list-full-item-re)
23892 ;; Set special position at first white space character after
23893 ;; bullet, and check-box, if any.
23894 (let ((after-bullet
23895 (let ((box (match-end 3)))
23896 (if (not box) (match-end 1)
23897 (let ((after (char-after box)))
23898 (if (and after (= after ? )) (1+ box) box))))))
23899 ;; Special case: Move point to special position when
23900 ;; currently after it or at beginning of line.
23901 (if (eq special t)
23902 (when (or (> pos after-bullet) (= (point) pos))
23903 (goto-char after-bullet))
23904 ;; Reversed case: Move point to special position when
23905 ;; point was already at beginning of line and command is
23906 ;; repeated.
23907 (when (and (= (point) pos) (eq last-command this-command))
23908 (goto-char after-bullet))))))))
23909 (org-no-warnings
23910 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23911 (setq disable-point-adjustment
23912 (or (not (invisible-p (point)))
23913 (not (invisible-p (max (point-min) (1- (point))))))))
23915 (defun org-end-of-line (&optional arg)
23916 "Go to the end of the line.
23917 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23918 tags on the first attempt, and only move to after the tags when
23919 the cursor is already beyond the end of the headline."
23920 (interactive "P")
23921 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23922 org-special-ctrl-a/e))
23923 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23924 'end-of-visual-line)
23925 ((fboundp 'move-end-of-line) 'move-end-of-line)
23926 (t 'end-of-line)))
23927 deactivate-mark)
23928 (if (or (not special) arg) (call-interactively move-fun)
23929 (let* ((element (save-excursion (beginning-of-line)
23930 (org-element-at-point)))
23931 (type (org-element-type element)))
23932 (cond
23933 ((memq type '(headline inlinetask))
23934 (let ((pos (point)))
23935 (beginning-of-line 1)
23936 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23937 (if (eq special t)
23938 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23939 (goto-char (match-beginning 1))
23940 (goto-char (match-end 0)))
23941 (if (or (< pos (match-end 0))
23942 (not (eq this-command last-command)))
23943 (goto-char (match-end 0))
23944 (goto-char (match-beginning 1))))
23945 (call-interactively move-fun))))
23946 ((outline-invisible-p (line-end-position))
23947 ;; If element is hidden, `move-end-of-line' would put point
23948 ;; after it. Use `end-of-line' to stay on current line.
23949 (call-interactively 'end-of-line))
23950 (t (call-interactively move-fun)))))
23951 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23952 (setq disable-point-adjustment
23953 (or (not (invisible-p (point)))
23954 (not (invisible-p (max (point-min) (1- (point))))))))
23956 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23957 (define-key org-mode-map "\C-e" 'org-end-of-line)
23959 (defun org-backward-sentence (&optional _arg)
23960 "Go to beginning of sentence, or beginning of table field.
23961 This will call `backward-sentence' or `org-table-beginning-of-field',
23962 depending on context."
23963 (interactive)
23964 (let* ((element (org-element-at-point))
23965 (contents-begin (org-element-property :contents-begin element))
23966 (table (org-element-lineage element '(table) t)))
23967 (if (and table
23968 (> (point) contents-begin)
23969 (<= (point) (org-element-property :contents-end table)))
23970 (call-interactively #'org-table-beginning-of-field)
23971 (save-restriction
23972 (when (and contents-begin
23973 (< (point-min) contents-begin)
23974 (> (point) contents-begin))
23975 (narrow-to-region contents-begin
23976 (org-element-property :contents-end element)))
23977 (call-interactively #'backward-sentence)))))
23979 (defun org-forward-sentence (&optional _arg)
23980 "Go to end of sentence, or end of table field.
23981 This will call `forward-sentence' or `org-table-end-of-field',
23982 depending on context."
23983 (interactive)
23984 (let* ((element (org-element-at-point))
23985 (contents-end (org-element-property :contents-end element))
23986 (table (org-element-lineage element '(table) t)))
23987 (if (and table
23988 (>= (point) (org-element-property :contents-begin table))
23989 (< (point) contents-end))
23990 (call-interactively #'org-table-end-of-field)
23991 (save-restriction
23992 (when (and contents-end
23993 (> (point-max) contents-end)
23994 ;; Skip blank lines between elements.
23995 (< (org-element-property :end element)
23996 (save-excursion (goto-char contents-end)
23997 (skip-chars-forward " \r\t\n"))))
23998 (narrow-to-region (org-element-property :contents-begin element)
23999 contents-end))
24000 (call-interactively #'forward-sentence)))))
24002 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24003 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24005 (defun org-kill-line (&optional _arg)
24006 "Kill line, to tags or end of line."
24007 (interactive)
24008 (cond
24009 ((or (not org-special-ctrl-k)
24010 (bolp)
24011 (not (org-at-heading-p)))
24012 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24013 org-ctrl-k-protect-subtree
24014 (or (eq org-ctrl-k-protect-subtree 'error)
24015 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
24016 (user-error "C-k aborted as it would kill a hidden subtree"))
24017 (call-interactively
24018 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24019 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
24020 (kill-region (point) (match-beginning 1))
24021 (org-set-tags nil t))
24022 (t (kill-region (point) (point-at-eol)))))
24024 (define-key org-mode-map "\C-k" 'org-kill-line)
24026 (defun org-yank (&optional arg)
24027 "Yank. If the kill is a subtree, treat it specially.
24028 This command will look at the current kill and check if is a single
24029 subtree, or a series of subtrees[1]. If it passes the test, and if the
24030 cursor is at the beginning of a line or after the stars of a currently
24031 empty headline, then the yank is handled specially. How exactly depends
24032 on the value of the following variables, both set by default.
24034 `org-yank-folded-subtrees'
24035 When set, the subtree(s) will be folded after insertion, but only
24036 if doing so would now swallow text after the yanked text.
24038 `org-yank-adjusted-subtrees'
24039 When set, the subtree will be promoted or demoted in order to
24040 fit into the local outline tree structure, which means that the
24041 level will be adjusted so that it becomes the smaller one of the
24042 two *visible* surrounding headings.
24044 Any prefix to this command will cause `yank' to be called directly with
24045 no special treatment. In particular, a simple \\[universal-argument] prefix \
24046 will just
24047 plainly yank the text as it is.
24049 \[1] The test checks if the first non-white line is a heading
24050 and if there are no other headings with fewer stars."
24051 (interactive "P")
24052 (org-yank-generic 'yank arg))
24054 (defun org-yank-generic (command arg)
24055 "Perform some yank-like command.
24057 This function implements the behavior described in the `org-yank'
24058 documentation. However, it has been generalized to work for any
24059 interactive command with similar behavior."
24061 ;; pretend to be command COMMAND
24062 (setq this-command command)
24064 (if arg
24065 (call-interactively command)
24067 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24068 (and (org-kill-is-subtree-p)
24069 (or (bolp)
24070 (and (looking-at "[ \t]*$")
24071 (string-match
24072 "\\`\\*+\\'"
24073 (buffer-substring (point-at-bol) (point)))))))
24074 swallowp)
24075 (cond
24076 ((and subtreep org-yank-folded-subtrees)
24077 (let ((beg (point))
24078 end)
24079 (if (and subtreep org-yank-adjusted-subtrees)
24080 (org-paste-subtree nil nil 'for-yank)
24081 (call-interactively command))
24083 (setq end (point))
24084 (goto-char beg)
24085 (when (and (bolp) subtreep
24086 (not (setq swallowp
24087 (org-yank-folding-would-swallow-text beg end))))
24088 (org-with-limited-levels
24089 (or (looking-at org-outline-regexp)
24090 (re-search-forward org-outline-regexp-bol end t))
24091 (while (and (< (point) end) (looking-at org-outline-regexp))
24092 (outline-hide-subtree)
24093 (org-cycle-show-empty-lines 'folded)
24094 (condition-case nil
24095 (outline-forward-same-level 1)
24096 (error (goto-char end))))))
24097 (when swallowp
24098 (message
24099 "Inserted text not folded because that would swallow text"))
24101 (goto-char end)
24102 (skip-chars-forward " \t\n\r")
24103 (beginning-of-line 1)
24104 (push-mark beg 'nomsg)))
24105 ((and subtreep org-yank-adjusted-subtrees)
24106 (let ((beg (point-at-bol)))
24107 (org-paste-subtree nil nil 'for-yank)
24108 (push-mark beg 'nomsg)))
24110 (call-interactively command))))))
24112 (defun org-yank-folding-would-swallow-text (beg end)
24113 "Would hide-subtree at BEG swallow any text after END?"
24114 (let (level)
24115 (org-with-limited-levels
24116 (save-excursion
24117 (goto-char beg)
24118 (when (or (looking-at org-outline-regexp)
24119 (re-search-forward org-outline-regexp-bol end t))
24120 (setq level (org-outline-level)))
24121 (goto-char end)
24122 (skip-chars-forward " \t\r\n\v\f")
24123 (not (or (eobp)
24124 (and (bolp) (looking-at-p org-outline-regexp)
24125 (<= (org-outline-level) level))))))))
24127 (define-key org-mode-map "\C-y" 'org-yank)
24129 (defun org-truely-invisible-p ()
24130 "Check if point is at a character currently not visible.
24131 This version does not only check the character property, but also
24132 `visible-mode'."
24133 ;; Early versions of noutline don't have `outline-invisible-p'.
24134 (unless (org-bound-and-true-p visible-mode)
24135 (outline-invisible-p)))
24137 (defun org-invisible-p2 ()
24138 "Check if point is at a character currently not visible."
24139 (save-excursion
24140 (when (and (eolp) (not (bobp))) (backward-char 1))
24141 ;; Early versions of noutline don't have `outline-invisible-p'.
24142 (outline-invisible-p)))
24144 (defun org-back-to-heading (&optional invisible-ok)
24145 "Call `outline-back-to-heading', but provide a better error message."
24146 (condition-case nil
24147 (outline-back-to-heading invisible-ok)
24148 (error (error "Before first headline at position %d in buffer %s"
24149 (point) (current-buffer)))))
24151 (defun org-before-first-heading-p ()
24152 "Before first heading?"
24153 (save-excursion
24154 (end-of-line)
24155 (null (re-search-backward org-outline-regexp-bol nil t))))
24157 (defun org-at-heading-p (&optional ignored)
24158 (outline-on-heading-p t))
24159 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24160 ;;; warning was only added in Org 9.0, which should be taken into
24161 ;;; account when deciding when to remove the alias.
24162 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24164 (defun org-in-commented-heading-p (&optional no-inheritance)
24165 "Non-nil if point is under a commented heading.
24166 This function also checks ancestors of the current headline,
24167 unless optional argument NO-INHERITANCE is non-nil."
24168 (cond
24169 ((org-before-first-heading-p) nil)
24170 ((let ((headline (nth 4 (org-heading-components))))
24171 (and headline
24172 (let ((case-fold-search nil))
24173 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24174 headline)))))
24175 (no-inheritance nil)
24177 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24179 (defun org-at-comment-p nil
24180 "Is cursor in a commented line?"
24181 (save-excursion
24182 (save-match-data
24183 (beginning-of-line)
24184 (looking-at "^[ \t]*# "))))
24186 (defun org-at-drawer-p nil
24187 "Is cursor at a drawer keyword?"
24188 (save-excursion
24189 (move-beginning-of-line 1)
24190 (looking-at org-drawer-regexp)))
24192 (defun org-at-block-p nil
24193 "Is cursor at a block keyword?"
24194 (save-excursion
24195 (move-beginning-of-line 1)
24196 (looking-at org-block-regexp)))
24198 (defun org-point-at-end-of-empty-headline ()
24199 "If point is at the end of an empty headline, return t, else nil.
24200 If the heading only contains a TODO keyword, it is still still considered
24201 empty."
24202 (and (looking-at "[ \t]*$")
24203 (when org-todo-line-regexp
24204 (save-excursion
24205 (beginning-of-line 1)
24206 (let ((case-fold-search nil))
24207 (looking-at org-todo-line-regexp)
24208 (string= (match-string 3) ""))))))
24210 (defun org-at-heading-or-item-p ()
24211 (or (org-at-heading-p) (org-at-item-p)))
24213 (defun org-at-target-p ()
24214 (or (org-in-regexp org-radio-target-regexp)
24215 (org-in-regexp org-target-regexp)))
24216 ;; Compatibility alias with Org versions < 7.8.03
24217 (defalias 'org-on-target-p 'org-at-target-p)
24219 (defun org-up-heading-all (arg)
24220 "Move to the heading line of which the present line is a subheading.
24221 This function considers both visible and invisible heading lines.
24222 With argument, move up ARG levels."
24223 (if (fboundp 'outline-up-heading-all)
24224 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24225 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24227 (defun org-up-heading-safe ()
24228 "Move to the heading line of which the present line is a subheading.
24229 This version will not throw an error. It will return the level of the
24230 headline found, or nil if no higher level is found.
24232 Also, this function will be a lot faster than `outline-up-heading',
24233 because it relies on stars being the outline starters. This can really
24234 make a significant difference in outlines with very many siblings."
24235 (when (ignore-errors (org-back-to-heading t))
24236 (let ((level-up (1- (funcall outline-level))))
24237 (and (> level-up 0)
24238 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24239 (funcall outline-level)))))
24241 (defun org-first-sibling-p ()
24242 "Is this heading the first child of its parents?"
24243 (interactive)
24244 (let ((re org-outline-regexp-bol)
24245 level l)
24246 (unless (org-at-heading-p t)
24247 (user-error "Not at a heading"))
24248 (setq level (funcall outline-level))
24249 (save-excursion
24250 (if (not (re-search-backward re nil t))
24252 (setq l (funcall outline-level))
24253 (< l level)))))
24255 (defun org-goto-sibling (&optional previous)
24256 "Goto the next sibling, even if it is invisible.
24257 When PREVIOUS is set, go to the previous sibling instead. Returns t
24258 when a sibling was found. When none is found, return nil and don't
24259 move point."
24260 (let ((fun (if previous 're-search-backward 're-search-forward))
24261 (pos (point))
24262 (re org-outline-regexp-bol)
24263 level l)
24264 (when (ignore-errors (org-back-to-heading t))
24265 (setq level (funcall outline-level))
24266 (catch 'exit
24267 (or previous (forward-char 1))
24268 (while (funcall fun re nil t)
24269 (setq l (funcall outline-level))
24270 (when (< l level) (goto-char pos) (throw 'exit nil))
24271 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24272 (goto-char pos)
24273 nil))))
24275 (defun org-show-siblings ()
24276 "Show all siblings of the current headline."
24277 (save-excursion
24278 (while (org-goto-sibling) (org-flag-heading nil)))
24279 (save-excursion
24280 (while (org-goto-sibling 'previous)
24281 (org-flag-heading nil))))
24283 (defun org-goto-first-child ()
24284 "Goto the first child, even if it is invisible.
24285 Return t when a child was found. Otherwise don't move point and
24286 return nil."
24287 (let (level (pos (point)) (re org-outline-regexp-bol))
24288 (when (ignore-errors (org-back-to-heading t))
24289 (setq level (outline-level))
24290 (forward-char 1)
24291 (if (and (re-search-forward re nil t) (> (outline-level) level))
24292 (progn (goto-char (match-beginning 0)) t)
24293 (goto-char pos) nil))))
24295 (defun org-show-hidden-entry ()
24296 "Show an entry where even the heading is hidden."
24297 (save-excursion
24298 (org-show-entry)))
24300 (defun org-flag-heading (flag &optional entry)
24301 "Flag the current heading. FLAG non-nil means make invisible.
24302 When ENTRY is non-nil, show the entire entry."
24303 (save-excursion
24304 (org-back-to-heading t)
24305 ;; Check if we should show the entire entry
24306 (if entry
24307 (progn
24308 (org-show-entry)
24309 (save-excursion
24310 (and (outline-next-heading)
24311 (org-flag-heading nil))))
24312 (outline-flag-region (max (point-min) (1- (point)))
24313 (save-excursion (outline-end-of-heading) (point))
24314 flag))))
24316 (defun org-get-next-sibling ()
24317 "Move to next heading of the same level, and return point.
24318 If there is no such heading, return nil.
24319 This is like outline-next-sibling, but invisible headings are ok."
24320 (let ((level (funcall outline-level)))
24321 (outline-next-heading)
24322 (while (and (not (eobp)) (> (funcall outline-level) level))
24323 (outline-next-heading))
24324 (unless (or (eobp) (< (funcall outline-level) level))
24325 (point))))
24327 (defun org-get-last-sibling ()
24328 "Move to previous heading of the same level, and return point.
24329 If there is no such heading, return nil."
24330 (let ((opoint (point))
24331 (level (funcall outline-level)))
24332 (outline-previous-heading)
24333 (when (and (/= (point) opoint) (outline-on-heading-p t))
24334 (while (and (> (funcall outline-level) level)
24335 (not (bobp)))
24336 (outline-previous-heading))
24337 (unless (< (funcall outline-level) level)
24338 (point)))))
24340 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24341 "Goto to the end of a subtree."
24342 ;; This contains an exact copy of the original function, but it uses
24343 ;; `org-back-to-heading', to make it work also in invisible
24344 ;; trees. And is uses an invisible-ok argument.
24345 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24346 ;; Furthermore, when used inside Org, finding the end of a large subtree
24347 ;; with many children and grandchildren etc, this can be much faster
24348 ;; than the outline version.
24349 (org-back-to-heading invisible-ok)
24350 (let ((first t)
24351 (level (funcall outline-level)))
24352 (if (and (derived-mode-p 'org-mode) (< level 1000))
24353 ;; A true heading (not a plain list item), in Org-mode
24354 ;; This means we can easily find the end by looking
24355 ;; only for the right number of stars. Using a regexp to do
24356 ;; this is so much faster than using a Lisp loop.
24357 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24358 (forward-char 1)
24359 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24360 ;; something else, do it the slow way
24361 (while (and (not (eobp))
24362 (or first (> (funcall outline-level) level)))
24363 (setq first nil)
24364 (outline-next-heading)))
24365 (unless to-heading
24366 (when (memq (preceding-char) '(?\n ?\^M))
24367 ;; Go to end of line before heading
24368 (forward-char -1)
24369 (when (memq (preceding-char) '(?\n ?\^M))
24370 ;; leave blank line before heading
24371 (forward-char -1)))))
24372 (point))
24374 (defun org-end-of-meta-data (&optional full)
24375 "Skip planning line and properties drawer in current entry.
24376 When optional argument FULL is non-nil, also skip empty lines,
24377 clocking lines and regular drawers at the beginning of the
24378 entry."
24379 (org-back-to-heading t)
24380 (forward-line)
24381 (when (org-looking-at-p org-planning-line-re) (forward-line))
24382 (when (looking-at org-property-drawer-re)
24383 (goto-char (match-end 0))
24384 (forward-line))
24385 (when (and full (not (org-at-heading-p)))
24386 (catch 'exit
24387 (let ((end (save-excursion (outline-next-heading) (point)))
24388 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24389 (while (not (eobp))
24390 (cond ((org-looking-at-p org-drawer-regexp)
24391 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24392 (forward-line)
24393 (throw 'exit t)))
24394 ((org-looking-at-p re) (forward-line))
24395 (t (throw 'exit t))))))))
24397 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24398 "Move forward to the ARG'th subheading at same level as this one.
24399 Stop at the first and last subheadings of a superior heading.
24400 Normally this only looks at visible headings, but when INVISIBLE-OK is
24401 non-nil it will also look at invisible ones."
24402 (interactive "p")
24403 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24404 (if (and arg (< arg 0))
24405 (goto-char (point-min))
24406 (outline-next-heading))
24407 (org-at-heading-p)
24408 (let ((level (- (match-end 0) (match-beginning 0) 1))
24409 (f (if (and arg (< arg 0))
24410 're-search-backward
24411 're-search-forward))
24412 (count (if arg (abs arg) 1))
24413 (result (point)))
24414 (while (and (prog1 (> count 0)
24415 (forward-char (if (and arg (< arg 0)) -1 1)))
24416 (funcall f org-outline-regexp-bol nil 'move))
24417 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24418 (cond ((< l level) (setq count 0))
24419 ((and (= l level)
24420 (or invisible-ok
24421 (progn
24422 (goto-char (line-beginning-position))
24423 (not (outline-invisible-p)))))
24424 (setq count (1- count))
24425 (when (eq l level)
24426 (setq result (point)))))))
24427 (goto-char result))
24428 (beginning-of-line 1)))
24430 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24431 "Move backward to the ARG'th subheading at same level as this one.
24432 Stop at the first and last subheadings of a superior heading."
24433 (interactive "p")
24434 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24436 (defun org-next-visible-heading (arg)
24437 "Move to the next visible heading.
24439 This function wraps `outline-next-visible-heading' with
24440 `org-with-limited-levels' in order to skip over inline tasks and
24441 respect customization of `org-odd-levels-only'."
24442 (interactive "p")
24443 (org-with-limited-levels
24444 (outline-next-visible-heading arg)))
24446 (defun org-previous-visible-heading (arg)
24447 "Move to the next visible heading.
24449 This function wraps `outline-previous-visible-heading' with
24450 `org-with-limited-levels' in order to skip over inline tasks and
24451 respect customization of `org-odd-levels-only'."
24452 (interactive "p")
24453 (org-with-limited-levels
24454 (outline-previous-visible-heading arg)))
24456 (defun org-next-block (arg &optional backward block-regexp)
24457 "Jump to the next block.
24459 With a prefix argument ARG, jump forward ARG many blocks.
24461 When BACKWARD is non-nil, jump to the previous block.
24463 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24464 Match data is set according to this regexp when the function
24465 returns.
24467 Return point at beginning of the opening line of found block.
24468 Throw an error if no block is found."
24469 (interactive "p")
24470 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24471 (case-fold-search t)
24472 (search-fn (if backward #'re-search-backward #'re-search-forward))
24473 (count (or arg 1))
24474 (origin (point))
24475 last-element)
24476 (if backward (beginning-of-line) (end-of-line))
24477 (while (and (> count 0) (funcall search-fn re nil t))
24478 (let ((element (save-excursion
24479 (goto-char (match-beginning 0))
24480 (save-match-data (org-element-at-point)))))
24481 (when (and (memq (org-element-type element)
24482 '(center-block comment-block dynamic-block
24483 example-block export-block quote-block
24484 special-block src-block verse-block))
24485 (<= (match-beginning 0)
24486 (org-element-property :post-affiliated element)))
24487 (setq last-element element)
24488 (decf count))))
24489 (if (= count 0)
24490 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24491 (save-match-data (org-show-context)))
24492 (goto-char origin)
24493 (user-error "No %s code blocks" (if backward "previous" "further")))))
24495 (defun org-previous-block (arg &optional block-regexp)
24496 "Jump to the previous block.
24497 With a prefix argument ARG, jump backward ARG many source blocks.
24498 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24499 (interactive "p")
24500 (org-next-block arg t block-regexp))
24502 (defun org-forward-paragraph ()
24503 "Move forward to beginning of next paragraph or equivalent.
24505 The function moves point to the beginning of the next visible
24506 structural element, which can be a paragraph, a table, a list
24507 item, etc. It also provides some special moves for convenience:
24509 - On an affiliated keyword, jump to the beginning of the
24510 relative element.
24511 - On an item or a footnote definition, move to the second
24512 element inside, if any.
24513 - On a table or a property drawer, jump after it.
24514 - On a verse or source block, stop after blank lines."
24515 (interactive)
24516 (when (eobp) (user-error "Cannot move further down"))
24517 (let* ((deactivate-mark nil)
24518 (element (org-element-at-point))
24519 (type (org-element-type element))
24520 (post-affiliated (org-element-property :post-affiliated element))
24521 (contents-begin (org-element-property :contents-begin element))
24522 (contents-end (org-element-property :contents-end element))
24523 (end (let ((end (org-element-property :end element)) (parent element))
24524 (while (and (setq parent (org-element-property :parent parent))
24525 (= (org-element-property :contents-end parent) end))
24526 (setq end (org-element-property :end parent)))
24527 end)))
24528 (cond ((not element)
24529 (skip-chars-forward " \r\t\n")
24530 (or (eobp) (beginning-of-line)))
24531 ;; On affiliated keywords, move to element's beginning.
24532 ((< (point) post-affiliated)
24533 (goto-char post-affiliated))
24534 ;; At a table row, move to the end of the table. Similarly,
24535 ;; at a node property, move to the end of the property
24536 ;; drawer.
24537 ((memq type '(node-property table-row))
24538 (goto-char (org-element-property
24539 :end (org-element-property :parent element))))
24540 ((memq type '(property-drawer table)) (goto-char end))
24541 ;; Consider blank lines as separators in verse and source
24542 ;; blocks to ease editing.
24543 ((memq type '(src-block verse-block))
24544 (when (eq type 'src-block)
24545 (setq contents-end
24546 (save-excursion (goto-char end)
24547 (skip-chars-backward " \r\t\n")
24548 (line-beginning-position))))
24549 (beginning-of-line)
24550 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24551 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24552 (goto-char end)
24553 (skip-chars-forward " \r\t\n")
24554 (if (= (point) contents-end) (goto-char end)
24555 (beginning-of-line))))
24556 ;; With no contents, just skip element.
24557 ((not contents-begin) (goto-char end))
24558 ;; If contents are invisible, skip the element altogether.
24559 ((outline-invisible-p (line-end-position))
24560 (case type
24561 (headline
24562 (org-with-limited-levels (outline-next-visible-heading 1)))
24563 ;; At a plain list, make sure we move to the next item
24564 ;; instead of skipping the whole list.
24565 (plain-list (forward-char)
24566 (org-forward-paragraph))
24567 (otherwise (goto-char end))))
24568 ((>= (point) contents-end) (goto-char end))
24569 ((>= (point) contents-begin)
24570 ;; This can only happen on paragraphs and plain lists.
24571 (case type
24572 (paragraph (goto-char end))
24573 ;; At a plain list, try to move to second element in
24574 ;; first item, if possible.
24575 (plain-list (end-of-line)
24576 (org-forward-paragraph))))
24577 ;; When contents start on the middle of a line (e.g. in
24578 ;; items and footnote definitions), try to reach first
24579 ;; element starting after current line.
24580 ((> (line-end-position) contents-begin)
24581 (end-of-line)
24582 (org-forward-paragraph))
24583 (t (goto-char contents-begin)))))
24585 (defun org-backward-paragraph ()
24586 "Move backward to start of previous paragraph or equivalent.
24588 The function moves point to the beginning of the current
24589 structural element, which can be a paragraph, a table, a list
24590 item, etc., or to the beginning of the previous visible one if
24591 point is already there. It also provides some special moves for
24592 convenience:
24594 - On an affiliated keyword, jump to the first one.
24595 - On a table or a property drawer, move to its beginning.
24596 - On a verse or source block, stop before blank lines."
24597 (interactive)
24598 (when (bobp) (user-error "Cannot move further up"))
24599 (let* ((deactivate-mark nil)
24600 (element (org-element-at-point))
24601 (type (org-element-type element))
24602 (contents-begin (org-element-property :contents-begin element))
24603 (contents-end (org-element-property :contents-end element))
24604 (post-affiliated (org-element-property :post-affiliated element))
24605 (begin (org-element-property :begin element)))
24606 (cond
24607 ((not element) (goto-char (point-min)))
24608 ((= (point) begin)
24609 (backward-char)
24610 (org-backward-paragraph))
24611 ((<= (point) post-affiliated) (goto-char begin))
24612 ((memq type '(node-property table-row))
24613 (goto-char (org-element-property
24614 :post-affiliated (org-element-property :parent element))))
24615 ((memq type '(property-drawer table)) (goto-char begin))
24616 ((memq type '(src-block verse-block))
24617 (when (eq type 'src-block)
24618 (setq contents-begin
24619 (save-excursion (goto-char begin) (forward-line) (point))))
24620 (if (= (point) contents-begin) (goto-char post-affiliated)
24621 ;; Inside a verse block, see blank lines as paragraph
24622 ;; separators.
24623 (let ((origin (point)))
24624 (skip-chars-backward " \r\t\n" contents-begin)
24625 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24626 (skip-chars-forward " \r\t\n" origin)
24627 (if (= (point) origin) (goto-char contents-begin)
24628 (beginning-of-line))))))
24629 ((not contents-begin) (goto-char (or post-affiliated begin)))
24630 ((eq type 'paragraph)
24631 (goto-char contents-begin)
24632 ;; When at first paragraph in an item or a footnote definition,
24633 ;; move directly to beginning of line.
24634 (let ((parent-contents
24635 (org-element-property
24636 :contents-begin (org-element-property :parent element))))
24637 (when (and parent-contents (= parent-contents contents-begin))
24638 (beginning-of-line))))
24639 ;; At the end of a greater element, move to the beginning of the
24640 ;; last element within.
24641 ((>= (point) contents-end)
24642 (goto-char (1- contents-end))
24643 (org-backward-paragraph))
24644 (t (goto-char (or post-affiliated begin))))
24645 ;; Ensure we never leave point invisible.
24646 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24648 (defun org-forward-element ()
24649 "Move forward by one element.
24650 Move to the next element at the same level, when possible."
24651 (interactive)
24652 (cond ((eobp) (user-error "Cannot move further down"))
24653 ((org-with-limited-levels (org-at-heading-p))
24654 (let ((origin (point)))
24655 (goto-char (org-end-of-subtree nil t))
24656 (unless (org-with-limited-levels (org-at-heading-p))
24657 (goto-char origin)
24658 (user-error "Cannot move further down"))))
24660 (let* ((elem (org-element-at-point))
24661 (end (org-element-property :end elem))
24662 (parent (org-element-property :parent elem)))
24663 (cond ((and parent (= (org-element-property :contents-end parent) end))
24664 (goto-char (org-element-property :end parent)))
24665 ((integer-or-marker-p end) (goto-char end))
24666 (t (message "No element at point")))))))
24668 (defun org-backward-element ()
24669 "Move backward by one element.
24670 Move to the previous element at the same level, when possible."
24671 (interactive)
24672 (cond ((bobp) (user-error "Cannot move further up"))
24673 ((org-with-limited-levels (org-at-heading-p))
24674 ;; At a headline, move to the previous one, if any, or stay
24675 ;; here.
24676 (let ((origin (point)))
24677 (org-with-limited-levels (org-backward-heading-same-level 1))
24678 ;; When current headline has no sibling above, move to its
24679 ;; parent.
24680 (when (= (point) origin)
24681 (or (org-with-limited-levels (org-up-heading-safe))
24682 (progn (goto-char origin)
24683 (user-error "Cannot move further up"))))))
24685 (let* ((elem (org-element-at-point))
24686 (beg (org-element-property :begin elem)))
24687 (cond
24688 ;; Move to beginning of current element if point isn't
24689 ;; there already.
24690 ((null beg) (message "No element at point"))
24691 ((/= (point) beg) (goto-char beg))
24692 (t (goto-char beg)
24693 (skip-chars-backward " \r\t\n")
24694 (unless (bobp)
24695 (let ((prev (org-element-at-point)))
24696 (goto-char (org-element-property :begin prev))
24697 (while (and (setq prev (org-element-property :parent prev))
24698 (<= (org-element-property :end prev) beg))
24699 (goto-char (org-element-property :begin prev)))))))))))
24701 (defun org-up-element ()
24702 "Move to upper element."
24703 (interactive)
24704 (if (org-with-limited-levels (org-at-heading-p))
24705 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24706 (let* ((elem (org-element-at-point))
24707 (parent (org-element-property :parent elem)))
24708 (if parent (goto-char (org-element-property :begin parent))
24709 (if (org-with-limited-levels (org-before-first-heading-p))
24710 (user-error "No surrounding element")
24711 (org-with-limited-levels (org-back-to-heading)))))))
24713 (defvar org-element-greater-elements)
24714 (defun org-down-element ()
24715 "Move to inner element."
24716 (interactive)
24717 (let ((element (org-element-at-point)))
24718 (cond
24719 ((memq (org-element-type element) '(plain-list table))
24720 (goto-char (org-element-property :contents-begin element))
24721 (forward-char))
24722 ((memq (org-element-type element) org-element-greater-elements)
24723 ;; If contents are hidden, first disclose them.
24724 (when (outline-invisible-p (line-end-position)) (org-cycle))
24725 (goto-char (or (org-element-property :contents-begin element)
24726 (user-error "No content for this element"))))
24727 (t (user-error "No inner element")))))
24729 (defun org-drag-element-backward ()
24730 "Move backward element at point."
24731 (interactive)
24732 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24733 (let* ((elem (org-element-at-point))
24734 (prev-elem
24735 (save-excursion
24736 (goto-char (org-element-property :begin elem))
24737 (skip-chars-backward " \r\t\n")
24738 (unless (bobp)
24739 (let* ((beg (org-element-property :begin elem))
24740 (prev (org-element-at-point))
24741 (up prev))
24742 (while (and (setq up (org-element-property :parent up))
24743 (<= (org-element-property :end up) beg))
24744 (setq prev up))
24745 prev)))))
24746 ;; Error out if no previous element or previous element is
24747 ;; a parent of the current one.
24748 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24749 (user-error "Cannot drag element backward")
24750 (let ((pos (point)))
24751 (org-element-swap-A-B prev-elem elem)
24752 (goto-char (+ (org-element-property :begin prev-elem)
24753 (- pos (org-element-property :begin elem)))))))))
24755 (defun org-drag-element-forward ()
24756 "Move forward element at point."
24757 (interactive)
24758 (let* ((pos (point))
24759 (elem (org-element-at-point)))
24760 (when (= (point-max) (org-element-property :end elem))
24761 (user-error "Cannot drag element forward"))
24762 (goto-char (org-element-property :end elem))
24763 (let ((next-elem (org-element-at-point)))
24764 (when (or (org-element-nested-p elem next-elem)
24765 (and (eq (org-element-type next-elem) 'headline)
24766 (not (eq (org-element-type elem) 'headline))))
24767 (goto-char pos)
24768 (user-error "Cannot drag element forward"))
24769 ;; Compute new position of point: it's shifted by NEXT-ELEM
24770 ;; body's length (without final blanks) and by the length of
24771 ;; blanks between ELEM and NEXT-ELEM.
24772 (let ((size-next (- (save-excursion
24773 (goto-char (org-element-property :end next-elem))
24774 (skip-chars-backward " \r\t\n")
24775 (forward-line)
24776 ;; Small correction if buffer doesn't end
24777 ;; with a newline character.
24778 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24779 (org-element-property :begin next-elem)))
24780 (size-blank (- (org-element-property :end elem)
24781 (save-excursion
24782 (goto-char (org-element-property :end elem))
24783 (skip-chars-backward " \r\t\n")
24784 (forward-line)
24785 (point)))))
24786 (org-element-swap-A-B elem next-elem)
24787 (goto-char (+ pos size-next size-blank))))))
24789 (defun org-drag-line-forward (arg)
24790 "Drag the line at point ARG lines forward."
24791 (interactive "p")
24792 (dotimes (n (abs arg))
24793 (let ((c (current-column)))
24794 (if (< 0 arg)
24795 (progn
24796 (beginning-of-line 2)
24797 (transpose-lines 1)
24798 (beginning-of-line 0))
24799 (transpose-lines 1)
24800 (beginning-of-line -1))
24801 (org-move-to-column c))))
24803 (defun org-drag-line-backward (arg)
24804 "Drag the line at point ARG lines backward."
24805 (interactive "p")
24806 (org-drag-line-forward (- arg)))
24808 (defun org-mark-element ()
24809 "Put point at beginning of this element, mark at end.
24811 Interactively, if this command is repeated or (in Transient Mark
24812 mode) if the mark is active, it marks the next element after the
24813 ones already marked."
24814 (interactive)
24815 (let (deactivate-mark)
24816 (if (and (org-called-interactively-p 'any)
24817 (or (and (eq last-command this-command) (mark t))
24818 (and transient-mark-mode mark-active)))
24819 (set-mark
24820 (save-excursion
24821 (goto-char (mark))
24822 (goto-char (org-element-property :end (org-element-at-point)))))
24823 (let ((element (org-element-at-point)))
24824 (end-of-line)
24825 (push-mark (org-element-property :end element) t t)
24826 (goto-char (org-element-property :begin element))))))
24828 (defun org-narrow-to-element ()
24829 "Narrow buffer to current element."
24830 (interactive)
24831 (let ((elem (org-element-at-point)))
24832 (cond
24833 ((eq (car elem) 'headline)
24834 (narrow-to-region
24835 (org-element-property :begin elem)
24836 (org-element-property :end elem)))
24837 ((memq (car elem) org-element-greater-elements)
24838 (narrow-to-region
24839 (org-element-property :contents-begin elem)
24840 (org-element-property :contents-end elem)))
24842 (narrow-to-region
24843 (org-element-property :begin elem)
24844 (org-element-property :end elem))))))
24846 (defun org-transpose-element ()
24847 "Transpose current and previous elements, keeping blank lines between.
24848 Point is moved after both elements."
24849 (interactive)
24850 (org-skip-whitespace)
24851 (let ((end (org-element-property :end (org-element-at-point))))
24852 (org-drag-element-backward)
24853 (goto-char end)))
24855 (defun org-unindent-buffer ()
24856 "Un-indent the visible part of the buffer.
24857 Relative indentation (between items, inside blocks, etc.) isn't
24858 modified."
24859 (interactive)
24860 (unless (eq major-mode 'org-mode)
24861 (user-error "Cannot un-indent a buffer not in Org mode"))
24862 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24863 unindent-tree ; For byte-compiler.
24864 (unindent-tree
24865 (function
24866 (lambda (contents)
24867 (mapc
24868 (lambda (element)
24869 (if (memq (org-element-type element) '(headline section))
24870 (funcall unindent-tree (org-element-contents element))
24871 (save-excursion
24872 (save-restriction
24873 (narrow-to-region
24874 (org-element-property :begin element)
24875 (org-element-property :end element))
24876 (org-do-remove-indentation)))))
24877 (reverse contents))))))
24878 (funcall unindent-tree (org-element-contents parse-tree))))
24880 (defun org-show-children (&optional level)
24881 "Show all direct subheadings of this heading.
24882 Prefix arg LEVEL is how many levels below the current level
24883 should be shown. Default is enough to cause the following
24884 heading to appear."
24885 (interactive "p")
24886 ;; If `orgstruct-mode' is active, use the slower version.
24887 (if orgstruct-mode (call-interactively #'outline-show-children)
24888 (save-excursion
24889 (org-back-to-heading t)
24890 (let* ((current-level (funcall outline-level))
24891 (max-level (org-get-valid-level
24892 current-level
24893 (if level (prefix-numeric-value level) 1)))
24894 (end (save-excursion (org-end-of-subtree t t)))
24895 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24896 (past-first-child nil)
24897 ;; Make sure to skip inlinetasks.
24898 (re (format regexp-fmt
24899 current-level
24900 (cond
24901 ((not (featurep 'org-inlinetask)) "")
24902 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24904 (t (1- org-inlinetask-min-level))))))
24905 ;; Display parent heading.
24906 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24907 (forward-line)
24908 ;; Display children. First child may be deeper than expected
24909 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24910 ;; MAX-LEVEL accordingly.
24911 (while (re-search-forward re end t)
24912 (unless past-first-child
24913 (setq re (format regexp-fmt
24914 current-level
24915 (max (funcall outline-level) max-level)))
24916 (setq past-first-child t))
24917 (outline-flag-region
24918 (line-end-position 0) (line-end-position) nil))))))
24920 (defun org-show-subtree ()
24921 "Show everything after this heading at deeper levels."
24922 (interactive)
24923 (outline-flag-region
24924 (point)
24925 (save-excursion
24926 (org-end-of-subtree t t))
24927 nil))
24929 (defun org-show-entry ()
24930 "Show the body directly following this heading.
24931 Show the heading too, if it is currently invisible."
24932 (interactive)
24933 (save-excursion
24934 (ignore-errors
24935 (org-back-to-heading t)
24936 (outline-flag-region
24937 (max (point-min) (1- (point)))
24938 (save-excursion
24939 (if (re-search-forward
24940 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24941 (match-beginning 1)
24942 (point-max)))
24943 nil)
24944 (org-cycle-hide-drawers 'children))))
24946 (defun org-make-options-regexp (kwds &optional extra)
24947 "Make a regular expression for keyword lines.
24948 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24949 when non-nil, is a regexp matching keywords names."
24950 (concat "^[ \t]*#\\+\\("
24951 (regexp-opt kwds)
24952 (and extra (concat (and kwds "\\|") extra))
24953 "\\):[ \t]*\\(.*\\)"))
24955 ;; Make isearch reveal the necessary context
24956 (defun org-isearch-end ()
24957 "Reveal context after isearch exits."
24958 (when isearch-success ; only if search was successful
24959 (if (featurep 'xemacs)
24960 ;; Under XEmacs, the hook is run in the correct place,
24961 ;; we directly show the context.
24962 (org-show-context 'isearch)
24963 ;; In Emacs the hook runs *before* restoring the overlays.
24964 ;; So we have to use a one-time post-command-hook to do this.
24965 ;; (Emacs 22 has a special variable, see function `org-mode')
24966 (unless (and (boundp 'isearch-mode-end-hook-quit)
24967 isearch-mode-end-hook-quit)
24968 ;; Only when the isearch was not quitted.
24969 (org-add-hook 'post-command-hook 'org-isearch-post-command
24970 'append 'local)))))
24972 (defun org-isearch-post-command ()
24973 "Remove self from hook, and show context."
24974 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24975 (org-show-context 'isearch))
24978 ;;;; Integration with and fixes for other packages
24980 ;;; Imenu support
24982 (defvar-local org-imenu-markers nil
24983 "All markers currently used by Imenu.")
24985 (defun org-imenu-new-marker (&optional pos)
24986 "Return a new marker for use by Imenu, and remember the marker."
24987 (let ((m (make-marker)))
24988 (move-marker m (or pos (point)))
24989 (push m org-imenu-markers)
24992 (defun org-imenu-get-tree ()
24993 "Produce the index for Imenu."
24994 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24995 (setq org-imenu-markers nil)
24996 (let* ((n org-imenu-depth)
24997 (re (concat "^" (org-get-limited-outline-regexp)))
24998 (subs (make-vector (1+ n) nil))
24999 (last-level 0)
25000 m level head0 head)
25001 (save-excursion
25002 (save-restriction
25003 (widen)
25004 (goto-char (point-max))
25005 (while (re-search-backward re nil t)
25006 (setq level (org-reduced-level (funcall outline-level)))
25007 (when (and (<= level n)
25008 (looking-at org-complex-heading-regexp)
25009 (setq head0 (org-match-string-no-properties 4)))
25010 (setq head (org-link-display-format head0)
25011 m (org-imenu-new-marker))
25012 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25013 (if (>= level last-level)
25014 (push (cons head m) (aref subs level))
25015 (push (cons head (aref subs (1+ level))) (aref subs level))
25016 (loop for i from (1+ level) to n do (aset subs i nil)))
25017 (setq last-level level)))))
25018 (aref subs 1)))
25020 (eval-after-load "imenu"
25021 '(progn
25022 (add-hook 'imenu-after-jump-hook
25023 (lambda ()
25024 (when (derived-mode-p 'org-mode)
25025 (org-show-context 'org-goto))))))
25027 (defun org-link-display-format (link)
25028 "Replace a link with its the description.
25029 If there is no description, use the link target."
25030 (save-match-data
25031 (if (string-match org-bracket-link-analytic-regexp link)
25032 (replace-match (if (match-end 5)
25033 (match-string 5 link)
25034 (concat (match-string 1 link)
25035 (match-string 3 link)))
25036 nil t link)
25037 link)))
25039 (defun org-toggle-link-display ()
25040 "Toggle the literal or descriptive display of links."
25041 (interactive)
25042 (if org-descriptive-links
25043 (progn (org-remove-from-invisibility-spec '(org-link))
25044 (org-restart-font-lock)
25045 (setq org-descriptive-links nil))
25046 (progn (add-to-invisibility-spec '(org-link))
25047 (org-restart-font-lock)
25048 (setq org-descriptive-links t))))
25050 ;; Speedbar support
25052 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25053 "Overlay marking the agenda restriction line in speedbar.")
25054 (overlay-put org-speedbar-restriction-lock-overlay
25055 'face 'org-agenda-restriction-lock)
25056 (overlay-put org-speedbar-restriction-lock-overlay
25057 'help-echo "Agendas are currently limited to this item.")
25058 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25060 (defun org-speedbar-set-agenda-restriction ()
25061 "Restrict future agenda commands to the location at point in speedbar.
25062 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25063 (interactive)
25064 (require 'org-agenda)
25065 (let (p m tp np dir txt)
25066 (cond
25067 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25068 'org-imenu t))
25069 (setq m (get-text-property p 'org-imenu-marker))
25070 (with-current-buffer (marker-buffer m)
25071 (goto-char m)
25072 (org-agenda-set-restriction-lock 'subtree)))
25073 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25074 'speedbar-function 'speedbar-find-file))
25075 (setq tp (previous-single-property-change
25076 (1+ p) 'speedbar-function)
25077 np (next-single-property-change
25078 tp 'speedbar-function)
25079 dir (speedbar-line-directory)
25080 txt (buffer-substring-no-properties (or tp (point-min))
25081 (or np (point-max))))
25082 (with-current-buffer (find-file-noselect
25083 (let ((default-directory dir))
25084 (expand-file-name txt)))
25085 (unless (derived-mode-p 'org-mode)
25086 (user-error "Cannot restrict to non-Org-mode file"))
25087 (org-agenda-set-restriction-lock 'file)))
25088 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25089 (move-overlay org-speedbar-restriction-lock-overlay
25090 (point-at-bol) (point-at-eol))
25091 (setq current-prefix-arg nil)
25092 (org-agenda-maybe-redo)))
25094 (defvar speedbar-file-key-map)
25095 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25096 (eval-after-load "speedbar"
25097 '(progn
25098 (speedbar-add-supported-extension ".org")
25099 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25100 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25101 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25102 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25103 (add-hook 'speedbar-visiting-tag-hook
25104 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25106 ;;; Fixes and Hacks for problems with other packages
25108 (defun org--flyspell-object-check-p (element)
25109 "Non-nil when Flyspell can check object at point.
25110 ELEMENT is the element at point."
25111 (let ((object (save-excursion
25112 (when (org-looking-at-p "\\>") (backward-char))
25113 (org-element-context element))))
25114 (case (org-element-type object)
25115 ;; Prevent checks in links due to keybinding conflict with
25116 ;; Flyspell.
25117 ((code entity export-snippet inline-babel-call
25118 inline-src-block line-break latex-fragment link macro
25119 statistics-cookie target timestamp verbatim)
25120 nil)
25121 (footnote-reference
25122 ;; Only in inline footnotes, within the definition.
25123 (and (eq (org-element-property :type object) 'inline)
25124 (< (save-excursion
25125 (goto-char (org-element-property :begin object))
25126 (search-forward ":" nil t 2))
25127 (point))))
25128 (otherwise t))))
25130 (defun org-mode-flyspell-verify ()
25131 "Function used for `flyspell-generic-check-word-predicate'."
25132 (if (org-at-heading-p)
25133 ;; At a headline or an inlinetask, check title only. This is
25134 ;; faster than relying on `org-element-at-point'.
25135 (and (save-excursion (beginning-of-line)
25136 (and (let ((case-fold-search t))
25137 (not (looking-at "\\*+ END[ \t]*$")))
25138 (looking-at org-complex-heading-regexp)))
25139 (match-beginning 4)
25140 (>= (point) (match-beginning 4))
25141 (or (not (match-beginning 5))
25142 (< (point) (match-beginning 5))))
25143 (let* ((element (org-element-at-point))
25144 (post-affiliated (org-element-property :post-affiliated element)))
25145 (cond
25146 ;; Ignore checks in all affiliated keywords but captions.
25147 ((< (point) post-affiliated)
25148 (and (save-excursion
25149 (beginning-of-line)
25150 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25151 (> (point) (match-end 0))
25152 (org--flyspell-object-check-p element)))
25153 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25154 ((let ((log (org-log-into-drawer)))
25155 (and log
25156 (let ((drawer (org-element-lineage element '(drawer))))
25157 (and drawer
25158 (eq (compare-strings
25159 log nil nil
25160 (org-element-property :drawer-name drawer) nil nil t)
25161 t)))))
25162 nil)
25164 (case (org-element-type element)
25165 ((comment quote-section) t)
25166 (comment-block
25167 ;; Allow checks between block markers, not on them.
25168 (and (> (line-beginning-position) post-affiliated)
25169 (save-excursion
25170 (end-of-line)
25171 (skip-chars-forward " \r\t\n")
25172 (< (point) (org-element-property :end element)))))
25173 ;; Arbitrary list of keywords where checks are meaningful.
25174 ;; Make sure point is on the value part of the element.
25175 (keyword
25176 (and (member (org-element-property :key element)
25177 '("DESCRIPTION" "TITLE"))
25178 (save-excursion
25179 (search-backward ":" (line-beginning-position) t))))
25180 ;; Check is globally allowed in paragraphs verse blocks and
25181 ;; table rows (after affiliated keywords) but some objects
25182 ;; must not be affected.
25183 ((paragraph table-row verse-block)
25184 (let ((cbeg (org-element-property :contents-begin element))
25185 (cend (org-element-property :contents-end element)))
25186 (and cbeg (>= (point) cbeg) (< (point) cend)
25187 (org--flyspell-object-check-p element))))))))))
25188 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25190 (defun org-remove-flyspell-overlays-in (beg end)
25191 "Remove flyspell overlays in region."
25192 (and (org-bound-and-true-p flyspell-mode)
25193 (fboundp 'flyspell-delete-region-overlays)
25194 (flyspell-delete-region-overlays beg end)))
25196 (defvar flyspell-delayed-commands)
25197 (eval-after-load "flyspell"
25198 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25200 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25201 (eval-after-load "bookmark"
25202 '(if (boundp 'bookmark-after-jump-hook)
25203 ;; We can use the hook
25204 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25205 ;; Hook not available, use advice
25206 (defadvice bookmark-jump (after org-make-visible activate)
25207 "Make the position visible."
25208 (org-bookmark-jump-unhide))))
25210 ;; Make sure saveplace shows the location if it was hidden
25211 (eval-after-load "saveplace"
25212 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25213 "Make the position visible."
25214 (org-bookmark-jump-unhide)))
25216 ;; Make sure ecb shows the location if it was hidden
25217 (eval-after-load "ecb"
25218 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25219 "Make hierarchy visible when jumping into location from ECB tree buffer."
25220 (when (derived-mode-p 'org-mode)
25221 (org-show-context))))
25223 (defun org-bookmark-jump-unhide ()
25224 "Unhide the current position, to show the bookmark location."
25225 (and (derived-mode-p 'org-mode)
25226 (or (outline-invisible-p)
25227 (save-excursion (goto-char (max (point-min) (1- (point))))
25228 (outline-invisible-p)))
25229 (org-show-context 'bookmark-jump)))
25231 (defun org-mark-jump-unhide ()
25232 "Make the point visible with `org-show-context' after jumping to the mark."
25233 (when (and (derived-mode-p 'org-mode)
25234 (outline-invisible-p))
25235 (org-show-context 'mark-goto)))
25237 (eval-after-load "simple"
25238 '(defadvice pop-to-mark-command (after org-make-visible activate)
25239 "Make the point visible with `org-show-context'."
25240 (org-mark-jump-unhide)))
25242 (eval-after-load "simple"
25243 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25244 "Make the point visible with `org-show-context'."
25245 (org-mark-jump-unhide)))
25247 (eval-after-load "simple"
25248 '(defadvice pop-global-mark (after org-make-visible activate)
25249 "Make the point visible with `org-show-context'."
25250 (org-mark-jump-unhide)))
25252 ;; Make session.el ignore our circular variable
25253 (defvar session-globals-exclude)
25254 (eval-after-load "session"
25255 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25257 ;;;; Finish up
25259 (provide 'org)
25261 (run-hooks 'org-load-hook)
25263 ;;; org.el ends here