Fix property inheritance with extended values
[org-mode.git] / lisp / org.el
blobf2dfbbcaa9ef2e9c66ffe33ebe85bba9821396eb
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 org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
114 (unless (boundp 'calendar-view-holidays-initially-flag)
115 (org-defvaralias 'calendar-view-holidays-initially-flag
116 'view-calendar-holidays-initially))
117 (unless (boundp 'calendar-view-diary-initially-flag)
118 (org-defvaralias 'calendar-view-diary-initially-flag
119 'view-diary-entries-initially))
120 (unless (boundp 'diary-fancy-buffer)
121 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
123 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
124 (declare-function org-add-archive-files "org-archive" (files))
125 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
126 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
127 (declare-function org-agenda-redo "org-agenda" (&optional all))
128 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
129 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
133 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
134 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
135 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
136 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
137 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
138 (declare-function org-clock-update-time-maybe "org-clock" ())
139 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-element-at-point "org-element" ())
141 (declare-function org-element-cache-refresh "org-element" (pos))
142 (declare-function org-element-cache-reset "org-element" (&optional all))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-copy "org-element" (datum))
146 (declare-function org-element-interpret-data "org-element" (data &optional parent))
147 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element" (element property value))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element-type "org-element" (element))
154 (declare-function org-element-update-syntax "org-element" ())
155 (declare-function org-id-find-id-file "org-id" (id))
156 (declare-function org-id-get-create "org-id" (&optional force))
157 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
158 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
159 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
160 (declare-function org-plot/gnuplot "org-plot" (&optional params))
161 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
162 (declare-function org-table-align "org-table" ())
163 (declare-function org-table-begin "org-table" (&optional table-type))
164 (declare-function org-table-beginning-of-field "org-table" (&optional n))
165 (declare-function org-table-blank-field "org-table" ())
166 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
167 (declare-function org-table-edit-field "org-table" (arg))
168 (declare-function org-table-end "org-table" (&optional table-type))
169 (declare-function org-table-end-of-field "org-table" (&optional n))
170 (declare-function org-table-insert-row "org-table" (&optional arg))
171 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
172 (declare-function org-table-maybe-eval-formula "org-table" ())
173 (declare-function org-table-maybe-recalculate-line "org-table" ())
174 (declare-function org-table-next-row "org-table" ())
175 (declare-function org-table-paste-rectangle "org-table" ())
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (defsubst org-uniquify (list)
182 "Non-destructively remove duplicate elements from LIST."
183 (let ((res (copy-sequence list))) (delete-dups res)))
185 (defsubst org-get-at-bol (property)
186 "Get text property PROPERTY at the beginning of line."
187 (get-text-property (point-at-bol) property))
189 (defsubst org-trim (s)
190 "Remove whitespace at the beginning and the end of string S."
191 (replace-regexp-in-string
192 "\\`[ \t\n\r]+" ""
193 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
195 ;; load languages based on value of `org-babel-load-languages'
196 (defvar org-babel-load-languages)
198 ;;;###autoload
199 (defun org-babel-do-load-languages (sym value)
200 "Load the languages defined in `org-babel-load-languages'."
201 (set-default sym value)
202 (mapc (lambda (pair)
203 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
204 (if active
205 (progn
206 (require (intern (concat "ob-" lang))))
207 (progn
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-execute:" lang)))
210 (funcall 'fmakunbound
211 (intern (concat "org-babel-expand-body:" lang)))))))
212 org-babel-load-languages))
214 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
215 ;;;###autoload
216 (defun org-babel-load-file (file &optional compile)
217 "Load Emacs Lisp source code blocks in the Org-mode FILE.
218 This function exports the source code using `org-babel-tangle'
219 and then loads the resulting file using `load-file'. With prefix
220 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
221 file to byte-code before it is loaded."
222 (interactive "fFile to load: \nP")
223 (let* ((age (lambda (file)
224 (float-time
225 (time-subtract (current-time)
226 (nth 5 (or (file-attributes (file-truename file))
227 (file-attributes file)))))))
228 (base-name (file-name-sans-extension file))
229 (exported-file (concat base-name ".el")))
230 ;; tangle if the org-mode file is newer than the elisp file
231 (unless (and (file-exists-p exported-file)
232 (> (funcall age file) (funcall age exported-file)))
233 ;; Tangle-file traversal returns reversed list of tangled files
234 ;; and we want to evaluate the first target.
235 (setq exported-file
236 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
237 (message "%s %s"
238 (if compile
239 (progn (byte-compile-file exported-file 'load)
240 "Compiled and loaded")
241 (progn (load-file exported-file) "Loaded"))
242 exported-file)))
244 (defcustom org-babel-load-languages '((emacs-lisp . t))
245 "Languages which can be evaluated in Org-mode buffers.
246 This list can be used to load support for any of the languages
247 below, note that each language will depend on a different set of
248 system executables and/or Emacs modes. When a language is
249 \"loaded\", then code blocks in that language can be evaluated
250 with `org-babel-execute-src-block' bound by default to C-c
251 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
252 be set to remove code block evaluation from the C-c C-c
253 keybinding. By default only Emacs Lisp (which has no
254 requirements) is loaded."
255 :group 'org-babel
256 :set 'org-babel-do-load-languages
257 :version "24.1"
258 :type '(alist :tag "Babel Languages"
259 :key-type
260 (choice
261 (const :tag "Awk" awk)
262 (const :tag "C" C)
263 (const :tag "R" R)
264 (const :tag "Asymptote" asymptote)
265 (const :tag "Calc" calc)
266 (const :tag "Clojure" clojure)
267 (const :tag "CSS" css)
268 (const :tag "Ditaa" ditaa)
269 (const :tag "Dot" dot)
270 (const :tag "Emacs Lisp" emacs-lisp)
271 (const :tag "Forth" forth)
272 (const :tag "Fortran" fortran)
273 (const :tag "Gnuplot" gnuplot)
274 (const :tag "Haskell" haskell)
275 (const :tag "IO" io)
276 (const :tag "J" J)
277 (const :tag "Java" java)
278 (const :tag "Javascript" js)
279 (const :tag "LaTeX" latex)
280 (const :tag "Ledger" ledger)
281 (const :tag "Lilypond" lilypond)
282 (const :tag "Lisp" lisp)
283 (const :tag "Makefile" makefile)
284 (const :tag "Maxima" maxima)
285 (const :tag "Matlab" matlab)
286 (const :tag "Mscgen" mscgen)
287 (const :tag "Ocaml" ocaml)
288 (const :tag "Octave" octave)
289 (const :tag "Org" org)
290 (const :tag "Perl" perl)
291 (const :tag "Pico Lisp" picolisp)
292 (const :tag "PlantUML" plantuml)
293 (const :tag "Python" python)
294 (const :tag "Ruby" ruby)
295 (const :tag "Sass" sass)
296 (const :tag "Scala" scala)
297 (const :tag "Scheme" scheme)
298 (const :tag "Screen" screen)
299 (const :tag "Shell Script" shell)
300 (const :tag "Shen" shen)
301 (const :tag "Sql" sql)
302 (const :tag "Sqlite" sqlite)
303 (const :tag "ebnf2ps" ebnf2ps))
304 :value-type (boolean :tag "Activate" :value t)))
306 ;;;; Customization variables
307 (defcustom org-clone-delete-id nil
308 "Remove ID property of clones of a subtree.
309 When non-nil, clones of a subtree don't inherit the ID property.
310 Otherwise they inherit the ID property with a new unique
311 identifier."
312 :type 'boolean
313 :version "24.1"
314 :group 'org-id)
316 ;;; Version
317 (org-check-version)
319 ;;;###autoload
320 (defun org-version (&optional here full message)
321 "Show the org-mode version.
322 Interactively, or when MESSAGE is non-nil, show it in echo area.
323 With prefix argument, or when HERE is non-nil, insert it at point.
324 In non-interactive uses, a reduced version string is output unless
325 FULL is given."
326 (interactive (list current-prefix-arg t (not current-prefix-arg)))
327 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
328 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
329 (load-suffixes (list ".el"))
330 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
331 (org-trash (or
332 (and (fboundp 'org-release) (fboundp 'org-git-version))
333 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
334 (load-suffixes save-load-suffixes)
335 (org-version (org-release))
336 (git-version (org-git-version))
337 (version (format "Org-mode version %s (%s @ %s)"
338 org-version
339 git-version
340 (if org-install-dir
341 (if (string= org-dir org-install-dir)
342 org-install-dir
343 (concat "mixed installation! " org-install-dir " and " org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version org-version)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 A deadline is this string, followed by a time stamp. Should be a word,
379 terminated by a colon. You can insert a schedule keyword and
380 a timestamp with \\[org-deadline].")
382 (defvar org-scheduled-string "SCHEDULED:"
383 "String to mark scheduled TODO entries.
384 A schedule is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-schedule].")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 An entry can be toggled between COMMENT and normal with
528 \\[org-toggle-comment].")
531 ;;;; LaTeX Environments and Fragments
533 (defconst org-latex-regexps
534 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
535 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
536 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
537 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
538 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
540 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
541 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
542 "Regular expressions for matching embedded LaTeX.")
544 ;;;; Node Property
546 (defconst org-effort-property "Effort"
547 "The property that is being used to keep track of effort estimates.
548 Effort estimates given in this property need to have the format H:MM.")
550 ;;;; Table
552 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
553 "Detect an org-type or table-type table.")
555 (defconst org-table-line-regexp "^[ \t]*|"
556 "Detect an org-type table line.")
558 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
559 "Detect an org-type table line.")
561 (defconst org-table-hline-regexp "^[ \t]*|-"
562 "Detect an org-type table hline.")
564 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
565 "Detect a table-type table hline.")
567 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
568 "Detect the first line outside a table when searching from within it.
569 This works for both table types.")
571 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
572 "Detect a #+TBLFM line.")
574 ;;;; Timestamp
576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp-inactive
580 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
581 "Regular expression for fast inactive time stamp matching.")
583 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
584 "Regular expression for fast time stamp matching.")
586 (defconst org-ts-regexp0
587 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.
589 This one does not require the space after the date, so it can be used
590 on a string that terminates immediately after the date.")
592 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.")
595 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
596 "Regular expression matching time stamps, with groups.")
598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
599 "Regular expression matching time stamps (also [..]), with groups.")
601 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
602 "Regular expression matching a time stamp range.")
604 (defconst org-tr-regexp-both
605 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
609 org-ts-regexp "\\)?")
610 "Regular expression matching a time stamp or time stamp range.")
612 (defconst org-tsr-regexp-both
613 (concat org-ts-regexp-both "\\(--?-?"
614 org-ts-regexp-both "\\)?")
615 "Regular expression matching a time stamp or time stamp range.
616 The time stamps may be either active or inactive.")
618 (defconst org-repeat-re
619 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
620 "Regular expression for specifying repeated events.
621 After a match, group 1 contains the repeat expression.")
623 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
624 "Formats for `format-time-string' which are used for time stamps.")
627 ;;; The custom variables
629 (defgroup org nil
630 "Outline-based notes management and organizer."
631 :tag "Org"
632 :group 'outlines
633 :group 'calendar)
635 (defcustom org-mode-hook nil
636 "Mode hook for Org-mode, run after the mode was turned on."
637 :group 'org
638 :type 'hook)
640 (defcustom org-load-hook nil
641 "Hook that is run after org.el has been loaded."
642 :group 'org
643 :type 'hook)
645 (defcustom org-log-buffer-setup-hook nil
646 "Hook that is run after an Org log buffer is created."
647 :group 'org
648 :version "24.1"
649 :type 'hook)
651 (defvar org-modules) ; defined below
652 (defvar org-modules-loaded nil
653 "Have the modules been loaded already?")
655 (defun org-load-modules-maybe (&optional force)
656 "Load all extensions listed in `org-modules'."
657 (when (or force (not org-modules-loaded))
658 (mapc (lambda (ext)
659 (condition-case nil (require ext)
660 (error (message "Problems while trying to load feature `%s'" ext))))
661 org-modules)
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 \(provide 'org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
698 (const :tag " habit: Track your consistency with habits" org-habit)
699 (const :tag " id: Global IDs for identifying entries" org-id)
700 (const :tag " info: Links to Info nodes" org-info)
701 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
702 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
703 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
704 (const :tag " mouse: Additional mouse support" org-mouse)
705 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
706 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
707 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
709 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
710 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
711 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
717 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C eww: Store link to url of eww" org-eww)
722 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
723 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
724 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
725 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
726 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
727 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org-mode links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
742 (const :tag "C track: Keep up with Org-mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend))
752 (defcustom org-export-backends '(ascii html icalendar latex)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 \(progn
769 \(setq org-export-registered-backends
770 \(org-remove-if-not
771 \(lambda (backend)
772 \(let ((name (org-export-backend-name backend)))
773 \(or (memq name val)
774 \(catch 'parentp
775 \(dolist (b val)
776 \(and (org-export-derived-backend-p b name)
777 \(throw 'parentp t)))))))
778 org-export-registered-backends))
779 \(let ((new-list (mapcar #'org-export-backend-name
780 org-export-registered-backends)))
781 \(dolist (backend val)
782 \(cond
783 \((not (load (format \"ox-%s\" backend) t t))
784 \(message \"Problems while trying to load export back-end `%s'\"
785 backend))
786 \((not (memq backend new-list)) (push backend new-list))))
787 \(set-default 'org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "24.4"
794 :package-version '(Org . "8.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (org-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(mapc
845 (lambda (backend)
846 (condition-case nil (require (intern (format "ox-%s" backend)))
847 (error (message "Problems while trying to load export back-end `%s'"
848 backend))))
849 org-export-backends))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org-mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org-mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands: `C-c C-t'
880 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
881 can be used to switch TODO sets, `C-c -' to cycle item bullet
882 types, and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up.
887 XEmacs user should have this variable set to nil, because
888 `shift-select-mode' is in Emacs 23 or later only."
889 :group 'org
890 :type '(choice
891 (const :tag "Never" nil)
892 (const :tag "When outside special context" t)
893 (const :tag "Everywhere except timestamps" always)))
895 (defcustom org-loop-over-headlines-in-active-region nil
896 "Shall some commands act upon headlines in the active region?
898 When set to `t', some commands will be performed in all headlines
899 within the active region.
901 When set to `start-level', some commands will be performed in all
902 headlines within the active region, provided that these headlines
903 are of the same level than the first one.
905 When set to a string, those commands will be performed on the
906 matching headlines within the active region. Such string must be
907 a tags/property/todo match as it is used in the agenda tags view.
909 The list of commands is: `org-schedule', `org-deadline',
910 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
911 `org-archive-to-archive-sibling'. The archiving commands skip
912 already archived entries."
913 :type '(choice (const :tag "Don't loop" nil)
914 (const :tag "All headlines in active region" t)
915 (const :tag "In active region, headlines at the same level than the first one" start-level)
916 (string :tag "Tags/Property/Todo matcher"))
917 :version "24.1"
918 :group 'org-todo
919 :group 'org-archive)
921 (defgroup org-startup nil
922 "Options concerning startup of Org-mode."
923 :tag "Org Startup"
924 :group 'org)
926 (defcustom org-startup-folded t
927 "Non-nil means entering Org-mode will switch to OVERVIEW.
928 This can also be configured on a per-file basis by adding one of
929 the following lines anywhere in the buffer:
931 #+STARTUP: fold (or `overview', this is equivalent)
932 #+STARTUP: nofold (or `showall', this is equivalent)
933 #+STARTUP: content
934 #+STARTUP: showeverything
936 By default, this option is ignored when Org opens agenda files
937 for the first time. If you want the agenda to honor the startup
938 option, set `org-agenda-inhibit-startup' to nil."
939 :group 'org-startup
940 :type '(choice
941 (const :tag "nofold: show all" nil)
942 (const :tag "fold: overview" t)
943 (const :tag "content: all headlines" content)
944 (const :tag "show everything, even drawers" showeverything)))
946 (defcustom org-startup-truncated t
947 "Non-nil means entering Org-mode will set `truncate-lines'.
948 This is useful since some lines containing links can be very long and
949 uninteresting. Also tables look terrible when wrapped."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-startup-indented nil
954 "Non-nil means turn on `org-indent-mode' on startup.
955 This can also be configured on a per-file basis by adding one of
956 the following lines anywhere in the buffer:
958 #+STARTUP: indent
959 #+STARTUP: noindent"
960 :group 'org-structure
961 :type '(choice
962 (const :tag "Not" nil)
963 (const :tag "Globally (slow on startup in large files)" t)))
965 (defcustom org-use-sub-superscripts t
966 "Non-nil means interpret \"_\" and \"^\" for display.
968 If you want to control how Org exports those characters, see
969 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
970 used to be an alias for `org-export-with-sub-superscripts' in
971 Org <8.0, it is not anymore.
973 When this option is turned on, you can use TeX-like syntax for
974 sub- and superscripts within the buffer. Several characters after
975 \"_\" or \"^\" will be considered as a single item - so grouping
976 with {} is normally not needed. For example, the following things
977 will be parsed as single sub- or superscripts:
979 10^24 or 10^tau several digits will be considered 1 item.
980 10^-12 or 10^-tau a leading sign with digits or a word
981 x^2-y^3 will be read as x^2 - y^3, because items are
982 terminated by almost any nonword/nondigit char.
983 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
985 Still, ambiguity is possible. So when in doubt, use {} to enclose
986 the sub/superscript. If you set this variable to the symbol `{}',
987 the braces are *required* in order to trigger interpretations as
988 sub/superscript. This can be helpful in documents that need \"_\"
989 frequently in plain text."
990 :group 'org-startup
991 :version "24.4"
992 :package-version '(Org . "8.0")
993 :type '(choice
994 (const :tag "Always interpret" t)
995 (const :tag "Only with braces" {})
996 (const :tag "Never interpret" nil)))
998 (defcustom org-startup-with-beamer-mode nil
999 "Non-nil means turn on `org-beamer-mode' on startup.
1000 This can also be configured on a per-file basis by adding one of
1001 the following lines anywhere in the buffer:
1003 #+STARTUP: beamer"
1004 :group 'org-startup
1005 :version "24.1"
1006 :type 'boolean)
1008 (defcustom org-startup-align-all-tables nil
1009 "Non-nil means align all tables when visiting a file.
1010 This is useful when the column width in tables is forced with <N> cookies
1011 in table fields. Such tables will look correct only after the first re-align.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-with-inline-images nil
1020 "Non-nil means show inline images when loading a new Org file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: inlineimages
1024 #+STARTUP: noinlineimages"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-with-latex-preview nil
1030 "Non-nil means preview LaTeX fragments when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: latexpreview
1035 #+STARTUP: nolatexpreview"
1036 :group 'org-startup
1037 :version "24.4"
1038 :package-version '(Org . "8.0")
1039 :type 'boolean)
1041 (defcustom org-insert-mode-line-in-empty-file nil
1042 "Non-nil means insert the first line setting Org-mode in empty files.
1043 When the function `org-mode' is called interactively in an empty file, this
1044 normally means that the file name does not automatically trigger Org-mode.
1045 To ensure that the file will always be in Org-mode in the future, a
1046 line enforcing Org-mode will be inserted into the buffer, if this option
1047 has been set."
1048 :group 'org-startup
1049 :type 'boolean)
1051 (defcustom org-replace-disputed-keys nil
1052 "Non-nil means use alternative key bindings for some keys.
1053 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1054 These keys are also used by other packages like shift-selection-mode'
1055 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1056 If you want to use Org-mode together with one of these other modes,
1057 or more generally if you would like to move some Org-mode commands to
1058 other keys, set this variable and configure the keys with the variable
1059 `org-disputed-keys'.
1061 This option is only relevant at load-time of Org-mode, and must be set
1062 *before* org.el is loaded. Changing it requires a restart of Emacs to
1063 become effective."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-use-extra-keys nil
1068 "Non-nil means use extra key sequence definitions for certain commands.
1069 This happens automatically if you run XEmacs or if `window-system'
1070 is nil. This variable lets you do the same manually. You must
1071 set it before loading org.
1073 Example: on Carbon Emacs 22 running graphically, with an external
1074 keyboard on a Powerbook, the default way of setting M-left might
1075 not work for either Alt or ESC. Setting this variable will make
1076 it work for ESC."
1077 :group 'org-startup
1078 :type 'boolean)
1080 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1082 (defcustom org-disputed-keys
1083 '(([(shift up)] . [(meta p)])
1084 ([(shift down)] . [(meta n)])
1085 ([(shift left)] . [(meta -)])
1086 ([(shift right)] . [(meta +)])
1087 ([(control shift right)] . [(meta shift +)])
1088 ([(control shift left)] . [(meta shift -)]))
1089 "Keys for which Org-mode and other modes compete.
1090 This is an alist, cars are the default keys, second element specifies
1091 the alternative to use when `org-replace-disputed-keys' is t.
1093 Keys can be specified in any syntax supported by `define-key'.
1094 The value of this option takes effect only at Org-mode's startup,
1095 therefore you'll have to restart Emacs to apply it after changing."
1096 :group 'org-startup
1097 :type 'alist)
1099 (defun org-key (key)
1100 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1101 Or return the original if not disputed.
1102 Also apply the translations defined in `org-xemacs-key-equivalents'."
1103 (when org-replace-disputed-keys
1104 (let* ((nkey (key-description key))
1105 (x (org-find-if (lambda (x)
1106 (equal (key-description (car x)) nkey))
1107 org-disputed-keys)))
1108 (setq key (if x (cdr x) key))))
1109 (when (featurep 'xemacs)
1110 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1111 key)
1113 (defun org-find-if (predicate seq)
1114 (catch 'exit
1115 (while seq
1116 (if (funcall predicate (car seq))
1117 (throw 'exit (car seq))
1118 (pop seq)))))
1120 (defun org-defkey (keymap key def)
1121 "Define a key, possibly translated, as returned by `org-key'."
1122 (define-key keymap (org-key key) def))
1124 (defcustom org-ellipsis nil
1125 "The ellipsis to use in the Org-mode outline.
1126 When nil, just use the standard three dots.
1127 When a string, use that string instead.
1128 When a face, use the standard 3 dots, but with the specified face.
1129 The change affects only Org-mode (which will then use its own display table).
1130 Changing this requires executing \\[org-mode] in a buffer to become
1131 effective."
1132 :group 'org-startup
1133 :type '(choice (const :tag "Default" nil)
1134 (face :tag "Face" :value org-warning)
1135 (string :tag "String" :value "...#")))
1137 (defvar org-display-table nil
1138 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1140 (defgroup org-keywords nil
1141 "Keywords in Org-mode."
1142 :tag "Org Keywords"
1143 :group 'org)
1145 (defcustom org-closed-keep-when-no-todo nil
1146 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1147 :group 'org-todo
1148 :group 'org-keywords
1149 :version "24.4"
1150 :package-version '(Org . "8.0")
1151 :type 'boolean)
1153 (defgroup org-structure nil
1154 "Options concerning the general structure of Org-mode files."
1155 :tag "Org Structure"
1156 :group 'org)
1158 (defgroup org-reveal-location nil
1159 "Options about how to make context of a location visible."
1160 :tag "Org Reveal Location"
1161 :group 'org-structure)
1163 (defcustom org-show-context-detail '((isearch . lineage)
1164 (bookmark-jump . lineage)
1165 (default . ancestors))
1166 "Alist between context and visibility span when revealing a location.
1168 \\<org-mode-map>Some actions may move point into invisible
1169 locations. As a consequence, Org always expose a neighborhood
1170 around point. How much is shown depends on the initial action,
1171 or context. Valid contexts are
1173 agenda when exposing an entry from the agenda
1174 org-goto when using the command `org-goto' (\\[org-goto])
1175 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1176 tags-tree when constructing a sparse tree based on tags matches
1177 link-search when exposing search matches associated with a link
1178 mark-goto when exposing the jump goal of a mark
1179 bookmark-jump when exposing a bookmark location
1180 isearch when exiting from an incremental search
1181 default default for all contexts not set explicitly
1183 Allowed visibility spans are
1185 minimal show current headline; if point is not on headline,
1186 also show entry
1188 local show current headline, entry and next headline
1190 ancestors show current headline and its direct ancestors; if
1191 point is not on headline, also show entry
1193 lineage show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and first child
1197 tree show current headline, its direct ancestors and all
1198 their children; if point is not on headline, also show
1199 entry and all children
1201 canonical show current headline, its direct ancestors along with
1202 their entries and children; if point is not located on
1203 the headline, also show current entry and all children
1205 As special cases, a nil or t value means show all contexts in
1206 `minimal' or `canonical' view, respectively.
1208 Some views can make displayed information very compact, but also
1209 make it harder to edit the location of the match. In such
1210 a case, use the command `org-reveal' (\\[org-reveal]) to show
1211 more context."
1212 :group 'org-reveal-location
1213 :version "25.1"
1214 :package-version '(Org . "8.3")
1215 :type '(choice
1216 (const :tag "Canonical" t)
1217 (const :tag "Minimal" nil)
1218 (repeat :greedy t :tag "Individual contexts"
1219 (cons
1220 (choice :tag "Context"
1221 (const agenda)
1222 (const org-goto)
1223 (const occur-tree)
1224 (const tags-tree)
1225 (const link-search)
1226 (const mark-goto)
1227 (const bookmark-jump)
1228 (const isearch)
1229 (const default))
1230 (choice :tag "Detail level"
1231 (const minimal)
1232 (const local)
1233 (const ancestors)
1234 (const lineage)
1235 (const tree)
1236 (const canonical))))))
1238 (defcustom org-indirect-buffer-display 'other-window
1239 "How should indirect tree buffers be displayed?
1240 This applies to indirect buffers created with the commands
1241 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1242 Valid values are:
1243 current-window Display in the current window
1244 other-window Just display in another window.
1245 dedicated-frame Create one new frame, and re-use it each time.
1246 new-frame Make a new frame each time. Note that in this case
1247 previously-made indirect buffers are kept, and you need to
1248 kill these buffers yourself."
1249 :group 'org-structure
1250 :group 'org-agenda-windows
1251 :type '(choice
1252 (const :tag "In current window" current-window)
1253 (const :tag "In current frame, other window" other-window)
1254 (const :tag "Each time a new frame" new-frame)
1255 (const :tag "One dedicated frame" dedicated-frame)))
1257 (defcustom org-use-speed-commands nil
1258 "Non-nil means activate single letter commands at beginning of a headline.
1259 This may also be a function to test for appropriate locations where speed
1260 commands should be active.
1262 For example, to activate speed commands when the point is on any
1263 star at the beginning of the headline, you can do this:
1265 (setq org-use-speed-commands
1266 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1267 :group 'org-structure
1268 :type '(choice
1269 (const :tag "Never" nil)
1270 (const :tag "At beginning of headline stars" t)
1271 (function)))
1273 (defcustom org-speed-commands-user nil
1274 "Alist of additional speed commands.
1275 This list will be checked before `org-speed-commands-default'
1276 when the variable `org-use-speed-commands' is non-nil
1277 and when the cursor is at the beginning of a headline.
1278 The car if each entry is a string with a single letter, which must
1279 be assigned to `self-insert-command' in the global map.
1280 The cdr is either a command to be called interactively, a function
1281 to be called, or a form to be evaluated.
1282 An entry that is just a list with a single string will be interpreted
1283 as a descriptive headline that will be added when listing the speed
1284 commands in the Help buffer using the `?' speed command."
1285 :group 'org-structure
1286 :type '(repeat :value ("k" . ignore)
1287 (choice :value ("k" . ignore)
1288 (list :tag "Descriptive Headline" (string :tag "Headline"))
1289 (cons :tag "Letter and Command"
1290 (string :tag "Command letter")
1291 (choice
1292 (function)
1293 (sexp))))))
1295 (defcustom org-bookmark-names-plist
1296 '(:last-capture "org-capture-last-stored"
1297 :last-refile "org-refile-last-stored"
1298 :last-capture-marker "org-capture-last-stored-marker")
1299 "Names for bookmarks automatically set by some Org commands.
1300 This can provide strings as names for a number of bookmarks Org sets
1301 automatically. The following keys are currently implemented:
1302 :last-capture
1303 :last-capture-marker
1304 :last-refile
1305 When a key does not show up in the property list, the corresponding bookmark
1306 is not set."
1307 :group 'org-structure
1308 :type 'plist)
1310 (defgroup org-cycle nil
1311 "Options concerning visibility cycling in Org-mode."
1312 :tag "Org Cycle"
1313 :group 'org-structure)
1315 (defcustom org-cycle-skip-children-state-if-no-children t
1316 "Non-nil means skip CHILDREN state in entries that don't have any."
1317 :group 'org-cycle
1318 :type 'boolean)
1320 (defcustom org-cycle-max-level nil
1321 "Maximum level which should still be subject to visibility cycling.
1322 Levels higher than this will, for cycling, be treated as text, not a headline.
1323 When `org-odd-levels-only' is set, a value of N in this variable actually
1324 means 2N-1 stars as the limiting headline.
1325 When nil, cycle all levels.
1326 Note that the limiting level of cycling is also influenced by
1327 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1328 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1329 than its value."
1330 :group 'org-cycle
1331 :type '(choice
1332 (const :tag "No limit" nil)
1333 (integer :tag "Maximum level")))
1335 (defcustom org-hide-block-startup nil
1336 "Non-nil means entering Org-mode will fold all blocks.
1337 This can also be set in on a per-file basis with
1339 #+STARTUP: hideblocks
1340 #+STARTUP: showblocks"
1341 :group 'org-startup
1342 :group 'org-cycle
1343 :type 'boolean)
1345 (defcustom org-cycle-global-at-bob nil
1346 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use S-TAB or
1348 \\[universal-argument] TAB. For this special case to work, the first line
1349 of the buffer must not be a headline -- it may be empty or some other text.
1350 When used in this way, `org-cycle-hook' is disabled temporarily to make
1351 sure the cursor stays at the beginning of the buffer. When this option is
1352 nil, don't do anything special at the beginning of the buffer."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-level-after-item/entry-creation t
1357 "Non-nil means cycle entry level or item indentation in new empty entries.
1359 When the cursor is at the end of an empty headline, i.e., with only stars
1360 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1361 and then all possible ancestor states, before returning to the original state.
1362 This makes data entry extremely fast: M-RET to create a new headline,
1363 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1365 When the cursor is at the end of an empty plain list item, one TAB will
1366 make it a subitem, two or more tabs will back up to make this an item
1367 higher up in the item hierarchy."
1368 :group 'org-cycle
1369 :type 'boolean)
1371 (defcustom org-cycle-emulate-tab t
1372 "Where should `org-cycle' emulate TAB.
1373 nil Never
1374 white Only in completely white lines
1375 whitestart Only at the beginning of lines, before the first non-white char
1376 t Everywhere except in headlines
1377 exc-hl-bol Everywhere except at the start of a headline
1378 If TAB is used in a place where it does not emulate TAB, the current subtree
1379 visibility is cycled."
1380 :group 'org-cycle
1381 :type '(choice (const :tag "Never" nil)
1382 (const :tag "Only in completely white lines" white)
1383 (const :tag "Before first char in a line" whitestart)
1384 (const :tag "Everywhere except in headlines" t)
1385 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1387 (defcustom org-cycle-separator-lines 2
1388 "Number of empty lines needed to keep an empty line between collapsed trees.
1389 If you leave an empty line between the end of a subtree and the following
1390 headline, this empty line is hidden when the subtree is folded.
1391 Org-mode will leave (exactly) one empty line visible if the number of
1392 empty lines is equal or larger to the number given in this variable.
1393 So the default 2 means at least 2 empty lines after the end of a subtree
1394 are needed to produce free space between a collapsed subtree and the
1395 following headline.
1397 If the number is negative, and the number of empty lines is at least -N,
1398 all empty lines are shown.
1400 Special case: when 0, never leave empty lines in collapsed view."
1401 :group 'org-cycle
1402 :type 'integer)
1403 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1405 (defcustom org-pre-cycle-hook nil
1406 "Hook that is run before visibility cycling is happening.
1407 The function(s) in this hook must accept a single argument which indicates
1408 the new state that will be set right after running this hook. The
1409 argument is a symbol. Before a global state change, it can have the values
1410 `overview', `content', or `all'. Before a local state change, it can have
1411 the values `folded', `children', or `subtree'."
1412 :group 'org-cycle
1413 :type 'hook)
1415 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1416 org-cycle-hide-drawers
1417 org-cycle-show-empty-lines
1418 org-optimize-window-after-visibility-change)
1419 "Hook that is run after `org-cycle' has changed the buffer visibility.
1420 The function(s) in this hook must accept a single argument which indicates
1421 the new state that was set by the most recent `org-cycle' command. The
1422 argument is a symbol. After a global state change, it can have the values
1423 `overview', `contents', or `all'. After a local state change, it can have
1424 the values `folded', `children', or `subtree'."
1425 :group 'org-cycle
1426 :type 'hook
1427 :version "25.1"
1428 :package-version '(Org . "8.3"))
1430 (defgroup org-edit-structure nil
1431 "Options concerning structure editing in Org-mode."
1432 :tag "Org Edit Structure"
1433 :group 'org-structure)
1435 (defcustom org-odd-levels-only nil
1436 "Non-nil means skip even levels and only use odd levels for the outline.
1437 This has the effect that two stars are being added/taken away in
1438 promotion/demotion commands. It also influences how levels are
1439 handled by the exporters.
1440 Changing it requires restart of `font-lock-mode' to become effective
1441 for fontification also in regions already fontified.
1442 You may also set this on a per-file basis by adding one of the following
1443 lines to the buffer:
1445 #+STARTUP: odd
1446 #+STARTUP: oddeven"
1447 :group 'org-edit-structure
1448 :group 'org-appearance
1449 :type 'boolean)
1451 (defcustom org-adapt-indentation t
1452 "Non-nil means adapt indentation to outline node level.
1454 When this variable is set, Org assumes that you write outlines by
1455 indenting text in each node to align with the headline (after the
1456 stars). The following issues are influenced by this variable:
1458 - The indentation is increased by one space in a demotion
1459 command, and decreased by one in a promotion command. However,
1460 in the latter case, if shifting some line in the entry body
1461 would alter document structure (e.g., insert a new headline),
1462 indentation is not changed at all.
1464 - Property drawers and planning information is inserted indented
1465 when this variable is set. When nil, they will not be indented.
1467 - TAB indents a line relative to current level. The lines below
1468 a headline will be indented when this variable is set.
1470 Note that this is all about true indentation, by adding and
1471 removing space characters. See also `org-indent.el' which does
1472 level-dependent indentation in a virtual way, i.e. at display
1473 time in Emacs."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-special-ctrl-a/e nil
1478 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1480 When t, `C-a' will bring back the cursor to the beginning of the
1481 headline text, i.e. after the stars and after a possible TODO
1482 keyword. In an item, this will be the position after bullet and
1483 check-box, if any. When the cursor is already at that position,
1484 another `C-a' will bring it to the beginning of the line.
1486 `C-e' will jump to the end of the headline, ignoring the presence
1487 of tags in the headline. A second `C-e' will then jump to the
1488 true end of the line, after any tags. This also means that, when
1489 this variable is non-nil, `C-e' also will never jump beyond the
1490 end of the heading of a folded section, i.e. not after the
1491 ellipses.
1493 When set to the symbol `reversed', the first `C-a' or `C-e' works
1494 normally, going to the true line boundary first. Only a directly
1495 following, identical keypress will bring the cursor to the
1496 special positions.
1498 This may also be a cons cell where the behavior for `C-a' and
1499 `C-e' is set separately."
1500 :group 'org-edit-structure
1501 :type '(choice
1502 (const :tag "off" nil)
1503 (const :tag "on: after stars/bullet and before tags first" t)
1504 (const :tag "reversed: true line boundary first" reversed)
1505 (cons :tag "Set C-a and C-e separately"
1506 (choice :tag "Special C-a"
1507 (const :tag "off" nil)
1508 (const :tag "on: after stars/bullet first" t)
1509 (const :tag "reversed: before stars/bullet first" reversed))
1510 (choice :tag "Special C-e"
1511 (const :tag "off" nil)
1512 (const :tag "on: before tags first" t)
1513 (const :tag "reversed: after tags first" reversed)))))
1514 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1516 (defcustom org-special-ctrl-k nil
1517 "Non-nil means `C-k' will behave specially in headlines.
1518 When nil, `C-k' will call the default `kill-line' command.
1519 When t, the following will happen while the cursor is in the headline:
1521 - When the cursor is at the beginning of a headline, kill the entire
1522 line and possible the folded subtree below the line.
1523 - When in the middle of the headline text, kill the headline up to the tags.
1524 - When after the headline text, kill the tags."
1525 :group 'org-edit-structure
1526 :type 'boolean)
1528 (defcustom org-ctrl-k-protect-subtree nil
1529 "Non-nil means, do not delete a hidden subtree with C-k.
1530 When set to the symbol `error', simply throw an error when C-k is
1531 used to kill (part-of) a headline that has hidden text behind it.
1532 Any other non-nil value will result in a query to the user, if it is
1533 OK to kill that hidden subtree. When nil, kill without remorse."
1534 :group 'org-edit-structure
1535 :version "24.1"
1536 :type '(choice
1537 (const :tag "Do not protect hidden subtrees" nil)
1538 (const :tag "Protect hidden subtrees with a security query" t)
1539 (const :tag "Never kill a hidden subtree with C-k" error)))
1541 (defcustom org-special-ctrl-o t
1542 "Non-nil means, make `C-o' insert a row in tables."
1543 :group 'org-edit-structure
1544 :type 'boolean)
1546 (defcustom org-catch-invisible-edits nil
1547 "Check if in invisible region before inserting or deleting a character.
1548 Valid values are:
1550 nil Do not check, so just do invisible edits.
1551 error Throw an error and do nothing.
1552 show Make point visible, and do the requested edit.
1553 show-and-error Make point visible, then throw an error and abort the edit.
1554 smart Make point visible, and do insertion/deletion if it is
1555 adjacent to visible text and the change feels predictable.
1556 Never delete a previously invisible character or add in the
1557 middle or right after an invisible region. Basically, this
1558 allows insertion and backward-delete right before ellipses.
1559 FIXME: maybe in this case we should not even show?"
1560 :group 'org-edit-structure
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Do not check" nil)
1564 (const :tag "Throw error when trying to edit" error)
1565 (const :tag "Unhide, but do not do the edit" show-and-error)
1566 (const :tag "Show invisible part and do the edit" show)
1567 (const :tag "Be smart and do the right thing" smart)))
1569 (defcustom org-yank-folded-subtrees t
1570 "Non-nil means when yanking subtrees, fold them.
1571 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1572 it starts with a heading and all other headings in it are either children
1573 or siblings, then fold all the subtrees. However, do this only if no
1574 text after the yank would be swallowed into a folded tree by this action."
1575 :group 'org-edit-structure
1576 :type 'boolean)
1578 (defcustom org-yank-adjusted-subtrees nil
1579 "Non-nil means when yanking subtrees, adjust the level.
1580 With this setting, `org-paste-subtree' is used to insert the subtree, see
1581 this function for details."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-M-RET-may-split-line '((default . t))
1586 "Non-nil means M-RET will split the line at the cursor position.
1587 When nil, it will go to the end of the line before making a
1588 new line.
1589 You may also set this option in a different way for different
1590 contexts. Valid contexts are:
1592 headline when creating a new headline
1593 item when creating a new item
1594 table in a table field
1595 default the value to be used for all contexts not explicitly
1596 customized"
1597 :group 'org-structure
1598 :group 'org-table
1599 :type '(choice
1600 (const :tag "Always" t)
1601 (const :tag "Never" nil)
1602 (repeat :greedy t :tag "Individual contexts"
1603 (cons
1604 (choice :tag "Context"
1605 (const headline)
1606 (const item)
1607 (const table)
1608 (const default))
1609 (boolean)))))
1612 (defcustom org-insert-heading-respect-content nil
1613 "Non-nil means insert new headings after the current subtree.
1614 When nil, the new heading is created directly after the current line.
1615 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1616 this variable on for the duration of the command."
1617 :group 'org-structure
1618 :type 'boolean)
1620 (defcustom org-blank-before-new-entry '((heading . auto)
1621 (plain-list-item . auto))
1622 "Should `org-insert-heading' leave a blank line before new heading/item?
1623 The value is an alist, with `heading' and `plain-list-item' as CAR,
1624 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1625 which case Org will look at the surrounding headings/items and try to
1626 make an intelligent decision whether to insert a blank line or not.
1628 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1629 the setting here is ignored and no empty line is inserted to avoid breaking
1630 the list structure."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defcustom org-goto-auto-isearch t
1655 "Non-nil means typing characters in `org-goto' starts incremental search.
1656 When nil, you can use these keybindings to navigate the buffer:
1658 q Quit the org-goto interface
1659 n Go to the next visible heading
1660 p Go to the previous visible heading
1661 f Go one heading forward on same level
1662 b Go one heading backward on same level
1663 u Go one heading up"
1664 :group 'org-edit-structure
1665 :type 'boolean)
1667 (defgroup org-sparse-trees nil
1668 "Options concerning sparse trees in Org-mode."
1669 :tag "Org Sparse Trees"
1670 :group 'org-structure)
1672 (defcustom org-highlight-sparse-tree-matches t
1673 "Non-nil means highlight all matches that define a sparse tree.
1674 The highlights will automatically disappear the next time the buffer is
1675 changed by an edit command."
1676 :group 'org-sparse-trees
1677 :type 'boolean)
1679 (defcustom org-remove-highlights-with-change t
1680 "Non-nil means any change to the buffer will remove temporary highlights.
1681 Such highlights are created by `org-occur' and `org-clock-display'.
1682 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1683 The highlights created by `org-toggle-latex-fragment' always need
1684 `C-c C-x C-l' to be removed."
1685 :group 'org-sparse-trees
1686 :group 'org-time
1687 :type 'boolean)
1690 (defcustom org-occur-hook '(org-first-headline-recenter)
1691 "Hook that is run after `org-occur' has constructed a sparse tree.
1692 This can be used to recenter the window to show as much of the structure
1693 as possible."
1694 :group 'org-sparse-trees
1695 :type 'hook)
1697 (defgroup org-imenu-and-speedbar nil
1698 "Options concerning imenu and speedbar in Org-mode."
1699 :tag "Org Imenu and Speedbar"
1700 :group 'org-structure)
1702 (defcustom org-imenu-depth 2
1703 "The maximum level for Imenu access to Org-mode headlines.
1704 This also applied for speedbar access."
1705 :group 'org-imenu-and-speedbar
1706 :type 'integer)
1708 (defgroup org-table nil
1709 "Options concerning tables in Org-mode."
1710 :tag "Org Table"
1711 :group 'org)
1713 (defcustom org-enable-table-editor 'optimized
1714 "Non-nil means lines starting with \"|\" are handled by the table editor.
1715 When nil, such lines will be treated like ordinary lines.
1717 When equal to the symbol `optimized', the table editor will be optimized to
1718 do the following:
1719 - Automatic overwrite mode in front of whitespace in table fields.
1720 This makes the structure of the table stay in tact as long as the edited
1721 field does not exceed the column width.
1722 - Minimize the number of realigns. Normally, the table is aligned each time
1723 TAB or RET are pressed to move to another field. With optimization this
1724 happens only if changes to a field might have changed the column width.
1725 Optimization requires replacing the functions `self-insert-command',
1726 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1727 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1728 very good at guessing when a re-align will be necessary, but you can always
1729 force one with \\[org-ctrl-c-ctrl-c].
1731 If you would like to use the optimized version in Org-mode, but the
1732 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1734 This variable can be used to turn on and off the table editor during a session,
1735 but in order to toggle optimization, a restart is required.
1737 See also the variable `org-table-auto-blank-field'."
1738 :group 'org-table
1739 :type '(choice
1740 (const :tag "off" nil)
1741 (const :tag "on" t)
1742 (const :tag "on, optimized" optimized)))
1744 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1745 (version<= emacs-version "24.1"))
1746 "Non-nil means cluster self-insert commands for undo when possible.
1747 If this is set, then, like in the Emacs command loop, 20 consecutive
1748 characters will be undone together.
1749 This is configurable, because there is some impact on typing performance."
1750 :group 'org-table
1751 :type 'boolean)
1753 (defcustom org-table-tab-recognizes-table.el t
1754 "Non-nil means TAB will automatically notice a table.el table.
1755 When it sees such a table, it moves point into it and - if necessary -
1756 calls `table-recognize-table'."
1757 :group 'org-table-editing
1758 :type 'boolean)
1760 (defgroup org-link nil
1761 "Options concerning links in Org-mode."
1762 :tag "Org Link"
1763 :group 'org)
1765 (defvar org-link-abbrev-alist-local nil
1766 "Buffer-local version of `org-link-abbrev-alist', which see.
1767 The value of this is taken from the #+LINK lines.")
1768 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1770 (defcustom org-link-abbrev-alist nil
1771 "Alist of link abbreviations.
1772 The car of each element is a string, to be replaced at the start of a link.
1773 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1774 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1776 [[linkkey:tag][description]]
1778 The 'linkkey' must be a word word, starting with a letter, followed
1779 by letters, numbers, '-' or '_'.
1781 If REPLACE is a string, the tag will simply be appended to create the link.
1782 If the string contains \"%s\", the tag will be inserted there. If the string
1783 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1784 at that point (see the function `url-hexify-string'). If the string contains
1785 the specifier \"%(my-function)\", then the custom function `my-function' will
1786 be invoked: this function takes the tag as its only argument and must return
1787 a string.
1789 REPLACE may also be a function that will be called with the tag as the
1790 only argument to create the link, which should be returned as a string.
1792 See the manual for examples."
1793 :group 'org-link
1794 :type '(repeat
1795 (cons
1796 (string :tag "Protocol")
1797 (choice
1798 (string :tag "Format")
1799 (function)))))
1801 (defcustom org-descriptive-links t
1802 "Non-nil means Org will display descriptive links.
1803 E.g. [[http://orgmode.org][Org website]] will be displayed as
1804 \"Org Website\", hiding the link itself and just displaying its
1805 description. When set to `nil', Org will display the full links
1806 literally.
1808 You can interactively set the value of this variable by calling
1809 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1810 :group 'org-link
1811 :type 'boolean)
1813 (defcustom org-link-file-path-type 'adaptive
1814 "How the path name in file links should be stored.
1815 Valid values are:
1817 relative Relative to the current directory, i.e. the directory of the file
1818 into which the link is being inserted.
1819 absolute Absolute path, if possible with ~ for home directory.
1820 noabbrev Absolute path, no abbreviation of home directory.
1821 adaptive Use relative path for files in the current directory and sub-
1822 directories of it. For other files, use an absolute path."
1823 :group 'org-link
1824 :type '(choice
1825 (const relative)
1826 (const absolute)
1827 (const noabbrev)
1828 (const adaptive)))
1830 (defvaralias 'org-activate-links 'org-highlight-links)
1831 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1832 "Types of links that should be highlighted in Org-mode files.
1834 This is a list of symbols, each one of them leading to the
1835 highlighting of a certain link type.
1837 You can still open links that are not highlighted.
1839 In principle, it does not hurt to turn on highlighting for all
1840 link types. There may be a small gain when turning off unused
1841 link types. The types are:
1843 bracket The recommended [[link][description]] or [[link]] links with hiding.
1844 angle Links in angular brackets that may contain whitespace like
1845 <bbdb:Carsten Dominik>.
1846 plain Plain links in normal text, no whitespace, like http://google.com.
1847 radio Text that is matched by a radio target, see manual for details.
1848 tag Tag settings in a headline (link to tag search).
1849 date Time stamps (link to calendar).
1850 footnote Footnote labels.
1852 If you set this variable during an Emacs session, use `org-mode-restart'
1853 in the Org buffer so that the change takes effect."
1854 :group 'org-link
1855 :group 'org-appearance
1856 :type '(set :greedy t
1857 (const :tag "Double bracket links" bracket)
1858 (const :tag "Angular bracket links" angle)
1859 (const :tag "Plain text links" plain)
1860 (const :tag "Radio target matches" radio)
1861 (const :tag "Tags" tag)
1862 (const :tag "Timestamps" date)
1863 (const :tag "Footnotes" footnote)))
1865 (defcustom org-make-link-description-function nil
1866 "Function to use for generating link descriptions from links.
1867 When nil, the link location will be used. This function must take
1868 two parameters: the first one is the link, the second one is the
1869 description generated by `org-insert-link'. The function should
1870 return the description to use."
1871 :group 'org-link
1872 :type '(choice (const nil) (function)))
1874 (defgroup org-link-store nil
1875 "Options concerning storing links in Org-mode."
1876 :tag "Org Store Link"
1877 :group 'org-link)
1879 (defcustom org-url-hexify-p t
1880 "When non-nil, hexify URL when creating a link."
1881 :type 'boolean
1882 :version "24.3"
1883 :group 'org-link-store)
1885 (defcustom org-email-link-description-format "Email %c: %.30s"
1886 "Format of the description part of a link to an email or usenet message.
1887 The following %-escapes will be replaced by corresponding information:
1889 %F full \"From\" field
1890 %f name, taken from \"From\" field, address if no name
1891 %T full \"To\" field
1892 %t first name in \"To\" field, address if no name
1893 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1894 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1895 %s subject
1896 %d date
1897 %m message-id.
1899 You may use normal field width specification between the % and the letter.
1900 This is for example useful to limit the length of the subject.
1902 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1903 :group 'org-link-store
1904 :type 'string)
1906 (defcustom org-from-is-user-regexp
1907 (let (r1 r2)
1908 (when (and user-mail-address (not (string= user-mail-address "")))
1909 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1910 (when (and user-full-name (not (string= user-full-name "")))
1911 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1912 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1913 "Regexp matched against the \"From:\" header of an email or usenet message.
1914 It should match if the message is from the user him/herself."
1915 :group 'org-link-store
1916 :type 'regexp)
1918 (defcustom org-context-in-file-links t
1919 "Non-nil means file links from `org-store-link' contain context.
1920 A search string will be added to the file name with :: as separator and
1921 used to find the context when the link is activated by the command
1922 `org-open-at-point'. When this option is t, the entire active region
1923 will be placed in the search string of the file link. If set to a
1924 positive integer, only the first n lines of context will be stored.
1926 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1927 negates this setting for the duration of the command."
1928 :group 'org-link-store
1929 :type '(choice boolean integer))
1931 (defcustom org-keep-stored-link-after-insertion nil
1932 "Non-nil means keep link in list for entire session.
1934 The command `org-store-link' adds a link pointing to the current
1935 location to an internal list. These links accumulate during a session.
1936 The command `org-insert-link' can be used to insert links into any
1937 Org-mode file (offering completion for all stored links). When this
1938 option is nil, every link which has been inserted once using \\[org-insert-link]
1939 will be removed from the list, to make completing the unused links
1940 more efficient."
1941 :group 'org-link-store
1942 :type 'boolean)
1944 (defgroup org-link-follow nil
1945 "Options concerning following links in Org-mode."
1946 :tag "Org Follow Link"
1947 :group 'org-link)
1949 (defcustom org-link-translation-function nil
1950 "Function to translate links with different syntax to Org syntax.
1951 This can be used to translate links created for example by the Planner
1952 or emacs-wiki packages to Org syntax.
1953 The function must accept two parameters, a TYPE containing the link
1954 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1955 which is everything after the link protocol. It should return a cons
1956 with possibly modified values of type and path.
1957 Org contains a function for this, so if you set this variable to
1958 `org-translate-link-from-planner', you should be able follow many
1959 links created by planner."
1960 :group 'org-link-follow
1961 :type '(choice (const nil) (function)))
1963 (defcustom org-follow-link-hook nil
1964 "Hook that is run after a link has been followed."
1965 :group 'org-link-follow
1966 :type 'hook)
1968 (defcustom org-tab-follows-link nil
1969 "Non-nil means on links TAB will follow the link.
1970 Needs to be set before org.el is loaded.
1971 This really should not be used, it does not make sense, and the
1972 implementation is bad."
1973 :group 'org-link-follow
1974 :type 'boolean)
1976 (defcustom org-return-follows-link nil
1977 "Non-nil means on links RET will follow the link.
1978 In tables, the special behavior of RET has precedence."
1979 :group 'org-link-follow
1980 :type 'boolean)
1982 (defcustom org-mouse-1-follows-link
1983 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1984 "Non-nil means mouse-1 on a link will follow the link.
1985 A longer mouse click will still set point. Does not work on XEmacs.
1986 Needs to be set before org.el is loaded."
1987 :group 'org-link-follow
1988 :version "24.4"
1989 :package-version '(Org . "8.3")
1990 :type '(choice
1991 (const :tag "A double click follows the link" double)
1992 (const :tag "Unconditionally follow the link with mouse-1" t)
1993 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1995 (defcustom org-mark-ring-length 4
1996 "Number of different positions to be recorded in the ring.
1997 Changing this requires a restart of Emacs to work correctly."
1998 :group 'org-link-follow
1999 :type 'integer)
2001 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2002 "Non-nil means internal links in Org files must exactly match a headline.
2003 When nil, the link search tries to match a phrase with all words
2004 in the search text."
2005 :group 'org-link-follow
2006 :version "24.1"
2007 :type '(choice
2008 (const :tag "Use fuzzy text search" nil)
2009 (const :tag "Match only exact headline" t)
2010 (const :tag "Match exact headline or query to create it"
2011 query-to-create)))
2013 (defcustom org-link-frame-setup
2014 '((vm . vm-visit-folder-other-frame)
2015 (vm-imap . vm-visit-imap-folder-other-frame)
2016 (gnus . org-gnus-no-new-news)
2017 (file . find-file-other-window)
2018 (wl . wl-other-frame))
2019 "Setup the frame configuration for following links.
2020 When following a link with Emacs, it may often be useful to display
2021 this link in another window or frame. This variable can be used to
2022 set this up for the different types of links.
2023 For VM, use any of
2024 `vm-visit-folder'
2025 `vm-visit-folder-other-window'
2026 `vm-visit-folder-other-frame'
2027 For Gnus, use any of
2028 `gnus'
2029 `gnus-other-frame'
2030 `org-gnus-no-new-news'
2031 For FILE, use any of
2032 `find-file'
2033 `find-file-other-window'
2034 `find-file-other-frame'
2035 For Wanderlust use any of
2036 `wl'
2037 `wl-other-frame'
2038 For the calendar, use the variable `calendar-setup'.
2039 For BBDB, it is currently only possible to display the matches in
2040 another window."
2041 :group 'org-link-follow
2042 :type '(list
2043 (cons (const vm)
2044 (choice
2045 (const vm-visit-folder)
2046 (const vm-visit-folder-other-window)
2047 (const vm-visit-folder-other-frame)))
2048 (cons (const vm-imap)
2049 (choice
2050 (const vm-visit-imap-folder)
2051 (const vm-visit-imap-folder-other-window)
2052 (const vm-visit-imap-folder-other-frame)))
2053 (cons (const gnus)
2054 (choice
2055 (const gnus)
2056 (const gnus-other-frame)
2057 (const org-gnus-no-new-news)))
2058 (cons (const file)
2059 (choice
2060 (const find-file)
2061 (const find-file-other-window)
2062 (const find-file-other-frame)))
2063 (cons (const wl)
2064 (choice
2065 (const wl)
2066 (const wl-other-frame)))))
2068 (defcustom org-display-internal-link-with-indirect-buffer nil
2069 "Non-nil means use indirect buffer to display infile links.
2070 Activating internal links (from one location in a file to another location
2071 in the same file) normally just jumps to the location. When the link is
2072 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2073 is displayed in
2074 another window. When this option is set, the other window actually displays
2075 an indirect buffer clone of the current buffer, to avoid any visibility
2076 changes to the current buffer."
2077 :group 'org-link-follow
2078 :type 'boolean)
2080 (defcustom org-open-non-existing-files nil
2081 "Non-nil means `org-open-file' will open non-existing files.
2082 When nil, an error will be generated.
2083 This variable applies only to external applications because they
2084 might choke on non-existing files. If the link is to a file that
2085 will be opened in Emacs, the variable is ignored."
2086 :group 'org-link-follow
2087 :type 'boolean)
2089 (defcustom org-open-directory-means-index-dot-org nil
2090 "Non-nil means a link to a directory really means to index.org.
2091 When nil, following a directory link will run dired or open a finder/explorer
2092 window on that directory."
2093 :group 'org-link-follow
2094 :type 'boolean)
2096 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2097 "Non-nil means ask for confirmation before executing shell links.
2098 Shell links can be dangerous: just think about a link
2100 [[shell:rm -rf ~/*][Google Search]]
2102 This link would show up in your Org-mode document as \"Google Search\",
2103 but really it would remove your entire home directory.
2104 Therefore we advise against setting this variable to nil.
2105 Just change it to `y-or-n-p' if you want to confirm with a
2106 single keystroke rather than having to type \"yes\"."
2107 :group 'org-link-follow
2108 :type '(choice
2109 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2110 (const :tag "with y-or-n (faster)" y-or-n-p)
2111 (const :tag "no confirmation (dangerous)" nil)))
2112 (put 'org-confirm-shell-link-function
2113 'safe-local-variable
2114 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2116 (defcustom org-confirm-shell-link-not-regexp ""
2117 "A regexp to skip confirmation for shell links."
2118 :group 'org-link-follow
2119 :version "24.1"
2120 :type 'regexp)
2122 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2123 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2124 Elisp links can be dangerous: just think about a link
2126 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2128 This link would show up in your Org-mode document as \"Google Search\",
2129 but really it would remove your entire home directory.
2130 Therefore we advise against setting this variable to nil.
2131 Just change it to `y-or-n-p' if you want to confirm with a
2132 single keystroke rather than having to type \"yes\"."
2133 :group 'org-link-follow
2134 :type '(choice
2135 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2136 (const :tag "with y-or-n (faster)" y-or-n-p)
2137 (const :tag "no confirmation (dangerous)" nil)))
2138 (put 'org-confirm-shell-link-function
2139 'safe-local-variable
2140 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2142 (defcustom org-confirm-elisp-link-not-regexp ""
2143 "A regexp to skip confirmation for Elisp links."
2144 :group 'org-link-follow
2145 :version "24.1"
2146 :type 'regexp)
2148 (defconst org-file-apps-defaults-gnu
2149 '((remote . emacs)
2150 (system . mailcap)
2151 (t . mailcap))
2152 "Default file applications on a UNIX or GNU/Linux system.
2153 See `org-file-apps'.")
2155 (defconst org-file-apps-defaults-macosx
2156 '((remote . emacs)
2157 (t . "open %s")
2158 (system . "open %s")
2159 ("ps.gz" . "gv %s")
2160 ("eps.gz" . "gv %s")
2161 ("dvi" . "xdvi %s")
2162 ("fig" . "xfig %s"))
2163 "Default file applications on a MacOS X system.
2164 The system \"open\" is known as a default, but we use X11 applications
2165 for some files for which the OS does not have a good default.
2166 See `org-file-apps'.")
2168 (defconst org-file-apps-defaults-windowsnt
2169 (list
2170 '(remote . emacs)
2171 (cons t
2172 (list (if (featurep 'xemacs)
2173 'mswindows-shell-execute
2174 'w32-shell-execute)
2175 "open" 'file))
2176 (cons 'system
2177 (list (if (featurep 'xemacs)
2178 'mswindows-shell-execute
2179 'w32-shell-execute)
2180 "open" 'file)))
2181 "Default file applications on a Windows NT system.
2182 The system \"open\" is used for most files.
2183 See `org-file-apps'.")
2185 (defcustom org-file-apps
2186 '((auto-mode . emacs)
2187 ("\\.mm\\'" . default)
2188 ("\\.x?html?\\'" . default)
2189 ("\\.pdf\\'" . default))
2190 "External applications for opening `file:path' items in a document.
2191 Org-mode uses system defaults for different file types, but
2192 you can use this variable to set the application for a given file
2193 extension. The entries in this list are cons cells where the car identifies
2194 files and the cdr the corresponding command. Possible values for the
2195 file identifier are
2196 \"string\" A string as a file identifier can be interpreted in different
2197 ways, depending on its contents:
2199 - Alphanumeric characters only:
2200 Match links with this file extension.
2201 Example: (\"pdf\" . \"evince %s\")
2202 to open PDFs with evince.
2204 - Regular expression: Match links where the
2205 filename matches the regexp. If you want to
2206 use groups here, use shy groups.
2208 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2209 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2210 to open *.html and *.xhtml with firefox.
2212 - Regular expression which contains (non-shy) groups:
2213 Match links where the whole link, including \"::\", and
2214 anything after that, matches the regexp.
2215 In a custom command string, %1, %2, etc. are replaced with
2216 the parts of the link that were matched by the groups.
2217 For backwards compatibility, if a command string is given
2218 that does not use any of the group matches, this case is
2219 handled identically to the second one (i.e. match against
2220 file name only).
2221 In a custom lisp form, you can access the group matches with
2222 (match-string n link).
2224 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2225 to open [[file:document.pdf::5]] with evince at page 5.
2227 `directory' Matches a directory
2228 `remote' Matches a remote file, accessible through tramp or efs.
2229 Remote files most likely should be visited through Emacs
2230 because external applications cannot handle such paths.
2231 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2232 so all files Emacs knows how to handle. Using this with
2233 command `emacs' will open most files in Emacs. Beware that this
2234 will also open html files inside Emacs, unless you add
2235 (\"html\" . default) to the list as well.
2236 t Default for files not matched by any of the other options.
2237 `system' The system command to open files, like `open' on Windows
2238 and Mac OS X, and mailcap under GNU/Linux. This is the command
2239 that will be selected if you call `C-c C-o' with a double
2240 \\[universal-argument] \\[universal-argument] prefix.
2242 Possible values for the command are:
2243 `emacs' The file will be visited by the current Emacs process.
2244 `default' Use the default application for this file type, which is the
2245 association for t in the list, most likely in the system-specific
2246 part.
2247 This can be used to overrule an unwanted setting in the
2248 system-specific variable.
2249 `system' Use the system command for opening files, like \"open\".
2250 This command is specified by the entry whose car is `system'.
2251 Most likely, the system-specific version of this variable
2252 does define this command, but you can overrule/replace it
2253 here.
2254 string A command to be executed by a shell; %s will be replaced
2255 by the path to the file.
2256 sexp A Lisp form which will be evaluated. The file path will
2257 be available in the Lisp variable `file'.
2258 For more examples, see the system specific constants
2259 `org-file-apps-defaults-macosx'
2260 `org-file-apps-defaults-windowsnt'
2261 `org-file-apps-defaults-gnu'."
2262 :group 'org-link-follow
2263 :type '(repeat
2264 (cons (choice :value ""
2265 (string :tag "Extension")
2266 (const :tag "System command to open files" system)
2267 (const :tag "Default for unrecognized files" t)
2268 (const :tag "Remote file" remote)
2269 (const :tag "Links to a directory" directory)
2270 (const :tag "Any files that have Emacs modes"
2271 auto-mode))
2272 (choice :value ""
2273 (const :tag "Visit with Emacs" emacs)
2274 (const :tag "Use default" default)
2275 (const :tag "Use the system command" system)
2276 (string :tag "Command")
2277 (sexp :tag "Lisp form")))))
2279 (defcustom org-doi-server-url "http://dx.doi.org/"
2280 "The URL of the DOI server."
2281 :type 'string
2282 :version "24.3"
2283 :group 'org-link-follow)
2285 (defgroup org-refile nil
2286 "Options concerning refiling entries in Org-mode."
2287 :tag "Org Refile"
2288 :group 'org)
2290 (defcustom org-directory "~/org"
2291 "Directory with org files.
2292 This is just a default location to look for Org files. There is no need
2293 at all to put your files into this directory. It is only used in the
2294 following situations:
2296 1. When a capture template specifies a target file that is not an
2297 absolute path. The path will then be interpreted relative to
2298 `org-directory'
2299 2. When a capture note is filed away in an interactive way (when exiting the
2300 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2301 with `org-directory' as the default path."
2302 :group 'org-refile
2303 :group 'org-capture
2304 :type 'directory)
2306 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2307 "Default target for storing notes.
2308 Used as a fall back file for org-capture.el, for templates that
2309 do not specify a target file."
2310 :group 'org-refile
2311 :group 'org-capture
2312 :type 'file)
2314 (defcustom org-goto-interface 'outline
2315 "The default interface to be used for `org-goto'.
2316 Allowed values are:
2317 outline The interface shows an outline of the relevant file
2318 and the correct heading is found by moving through
2319 the outline or by searching with incremental search.
2320 outline-path-completion Headlines in the current buffer are offered via
2321 completion. This is the interface also used by
2322 the refile command."
2323 :group 'org-refile
2324 :type '(choice
2325 (const :tag "Outline" outline)
2326 (const :tag "Outline-path-completion" outline-path-completion)))
2328 (defcustom org-goto-max-level 5
2329 "Maximum target level when running `org-goto' with refile interface."
2330 :group 'org-refile
2331 :type 'integer)
2333 (defcustom org-reverse-note-order nil
2334 "Non-nil means store new notes at the beginning of a file or entry.
2335 When nil, new notes will be filed to the end of a file or entry.
2336 This can also be a list with cons cells of regular expressions that
2337 are matched against file names, and values."
2338 :group 'org-capture
2339 :group 'org-refile
2340 :type '(choice
2341 (const :tag "Reverse always" t)
2342 (const :tag "Reverse never" nil)
2343 (repeat :tag "By file name regexp"
2344 (cons regexp boolean))))
2346 (defcustom org-log-refile nil
2347 "Information to record when a task is refiled.
2349 Possible values are:
2351 nil Don't add anything
2352 time Add a time stamp to the task
2353 note Prompt for a note and add it with template `org-log-note-headings'
2355 This option can also be set with on a per-file-basis with
2357 #+STARTUP: nologrefile
2358 #+STARTUP: logrefile
2359 #+STARTUP: lognoterefile
2361 You can have local logging settings for a subtree by setting the LOGGING
2362 property to one or more of these keywords.
2364 When bulk-refiling from the agenda, the value `note' is forbidden and
2365 will temporarily be changed to `time'."
2366 :group 'org-refile
2367 :group 'org-progress
2368 :version "24.1"
2369 :type '(choice
2370 (const :tag "No logging" nil)
2371 (const :tag "Record timestamp" time)
2372 (const :tag "Record timestamp with note." note)))
2374 (defcustom org-refile-targets nil
2375 "Targets for refiling entries with \\[org-refile].
2376 This is a list of cons cells. Each cell contains:
2377 - a specification of the files to be considered, either a list of files,
2378 or a symbol whose function or variable value will be used to retrieve
2379 a file name or a list of file names. If you use `org-agenda-files' for
2380 that, all agenda files will be scanned for targets. Nil means consider
2381 headings in the current buffer.
2382 - A specification of how to find candidate refile targets. This may be
2383 any of:
2384 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2385 This tag has to be present in all target headlines, inheritance will
2386 not be considered.
2387 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2388 todo keyword.
2389 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2390 headlines that are refiling targets.
2391 - a cons cell (:level . N). Any headline of level N is considered a target.
2392 Note that, when `org-odd-levels-only' is set, level corresponds to
2393 order in hierarchy, not to the number of stars.
2394 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2395 Note that, when `org-odd-levels-only' is set, level corresponds to
2396 order in hierarchy, not to the number of stars.
2398 Each element of this list generates a set of possible targets.
2399 The union of these sets is presented (with completion) to
2400 the user by `org-refile'.
2402 You can set the variable `org-refile-target-verify-function' to a function
2403 to verify each headline found by the simple criteria above.
2405 When this variable is nil, all top-level headlines in the current buffer
2406 are used, equivalent to the value `((nil . (:level . 1))'."
2407 :group 'org-refile
2408 :type '(repeat
2409 (cons
2410 (choice :value org-agenda-files
2411 (const :tag "All agenda files" org-agenda-files)
2412 (const :tag "Current buffer" nil)
2413 (function) (variable) (file))
2414 (choice :tag "Identify target headline by"
2415 (cons :tag "Specific tag" (const :value :tag) (string))
2416 (cons :tag "TODO keyword" (const :value :todo) (string))
2417 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2418 (cons :tag "Level number" (const :value :level) (integer))
2419 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2421 (defcustom org-refile-target-verify-function nil
2422 "Function to verify if the headline at point should be a refile target.
2423 The function will be called without arguments, with point at the
2424 beginning of the headline. It should return t and leave point
2425 where it is if the headline is a valid target for refiling.
2427 If the target should not be selected, the function must return nil.
2428 In addition to this, it may move point to a place from where the search
2429 should be continued. For example, the function may decide that the entire
2430 subtree of the current entry should be excluded and move point to the end
2431 of the subtree."
2432 :group 'org-refile
2433 :type '(choice
2434 (const nil)
2435 (function)))
2437 (defcustom org-refile-use-cache nil
2438 "Non-nil means cache refile targets to speed up the process.
2439 The cache for a particular file will be updated automatically when
2440 the buffer has been killed, or when any of the marker used for flagging
2441 refile targets no longer points at a live buffer.
2442 If you have added new entries to a buffer that might themselves be targets,
2443 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2444 find that easier, `C-u C-u C-u C-c C-w'."
2445 :group 'org-refile
2446 :version "24.1"
2447 :type 'boolean)
2449 (defcustom org-refile-use-outline-path nil
2450 "Non-nil means provide refile targets as paths.
2451 So a level 3 headline will be available as level1/level2/level3.
2453 When the value is `file', also include the file name (without directory)
2454 into the path. In this case, you can also stop the completion after
2455 the file name, to get entries inserted as top level in the file.
2457 When `full-file-path', include the full file path."
2458 :group 'org-refile
2459 :type '(choice
2460 (const :tag "Not" nil)
2461 (const :tag "Yes" t)
2462 (const :tag "Start with file name" file)
2463 (const :tag "Start with full file path" full-file-path)))
2465 (defcustom org-outline-path-complete-in-steps t
2466 "Non-nil means complete the outline path in hierarchical steps.
2467 When Org-mode uses the refile interface to select an outline path
2468 \(see variable `org-refile-use-outline-path'), the completion of
2469 the path can be done in a single go, or it can be done in steps down
2470 the headline hierarchy. Going in steps is probably the best if you
2471 do not use a special completion package like `ido' or `icicles'.
2472 However, when using these packages, going in one step can be very
2473 fast, while still showing the whole path to the entry."
2474 :group 'org-refile
2475 :type 'boolean)
2477 (defcustom org-refile-allow-creating-parent-nodes nil
2478 "Non-nil means allow to create new nodes as refile targets.
2479 New nodes are then created by adding \"/new node name\" to the completion
2480 of an existing node. When the value of this variable is `confirm',
2481 new node creation must be confirmed by the user (recommended).
2482 When nil, the completion must match an existing entry.
2484 Note that, if the new heading is not seen by the criteria
2485 listed in `org-refile-targets', multiple instances of the same
2486 heading would be created by trying again to file under the new
2487 heading."
2488 :group 'org-refile
2489 :type '(choice
2490 (const :tag "Never" nil)
2491 (const :tag "Always" t)
2492 (const :tag "Prompt for confirmation" confirm)))
2494 (defcustom org-refile-active-region-within-subtree nil
2495 "Non-nil means also refile active region within a subtree.
2497 By default `org-refile' doesn't allow refiling regions if they
2498 don't contain a set of subtrees, but it might be convenient to
2499 do so sometimes: in that case, the first line of the region is
2500 converted to a headline before refiling."
2501 :group 'org-refile
2502 :version "24.1"
2503 :type 'boolean)
2505 (defgroup org-todo nil
2506 "Options concerning TODO items in Org-mode."
2507 :tag "Org TODO"
2508 :group 'org)
2510 (defgroup org-progress nil
2511 "Options concerning Progress logging in Org-mode."
2512 :tag "Org Progress"
2513 :group 'org-time)
2515 (defvar org-todo-interpretation-widgets
2516 '((:tag "Sequence (cycling hits every state)" sequence)
2517 (:tag "Type (cycling directly to DONE)" type))
2518 "The available interpretation symbols for customizing `org-todo-keywords'.
2519 Interested libraries should add to this list.")
2521 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2522 "List of TODO entry keyword sequences and their interpretation.
2523 \\<org-mode-map>This is a list of sequences.
2525 Each sequence starts with a symbol, either `sequence' or `type',
2526 indicating if the keywords should be interpreted as a sequence of
2527 action steps, or as different types of TODO items. The first
2528 keywords are states requiring action - these states will select a headline
2529 for inclusion into the global TODO list Org-mode produces. If one of
2530 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2531 signify that no further action is necessary. If \"|\" is not found,
2532 the last keyword is treated as the only DONE state of the sequence.
2534 The command \\[org-todo] cycles an entry through these states, and one
2535 additional state where no keyword is present. For details about this
2536 cycling, see the manual.
2538 TODO keywords and interpretation can also be set on a per-file basis with
2539 the special #+SEQ_TODO and #+TYP_TODO lines.
2541 Each keyword can optionally specify a character for fast state selection
2542 \(in combination with the variable `org-use-fast-todo-selection')
2543 and specifiers for state change logging, using the same syntax that
2544 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2545 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2546 indicates to record a time stamp each time this state is selected.
2548 Each keyword may also specify if a timestamp or a note should be
2549 recorded when entering or leaving the state, by adding additional
2550 characters in the parenthesis after the keyword. This looks like this:
2551 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2552 record only the time of the state change. With X and Y being either
2553 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2554 Y when leaving the state if and only if the *target* state does not
2555 define X. You may omit any of the fast-selection key or X or /Y,
2556 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2558 For backward compatibility, this variable may also be just a list
2559 of keywords. In this case the interpretation (sequence or type) will be
2560 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2561 :group 'org-todo
2562 :group 'org-keywords
2563 :type '(choice
2564 (repeat :tag "Old syntax, just keywords"
2565 (string :tag "Keyword"))
2566 (repeat :tag "New syntax"
2567 (cons
2568 (choice
2569 :tag "Interpretation"
2570 ;;Quick and dirty way to see
2571 ;;`org-todo-interpretations'. This takes the
2572 ;;place of item arguments
2573 :convert-widget
2574 (lambda (widget)
2575 (widget-put widget
2576 :args (mapcar
2577 (lambda (x)
2578 (widget-convert
2579 (cons 'const x)))
2580 org-todo-interpretation-widgets))
2581 widget))
2582 (repeat
2583 (string :tag "Keyword"))))))
2585 (defvar org-todo-keywords-1 nil
2586 "All TODO and DONE keywords active in a buffer.")
2587 (make-variable-buffer-local 'org-todo-keywords-1)
2588 (defvar org-todo-keywords-for-agenda nil)
2589 (defvar org-done-keywords-for-agenda nil)
2590 (defvar org-todo-keyword-alist-for-agenda nil)
2591 (defvar org-tag-alist-for-agenda nil
2592 "Alist of all tags from all agenda files.")
2593 (defvar org-tag-groups-alist-for-agenda nil
2594 "Alist of all groups tags from all current agenda files.")
2595 (defvar org-tag-groups-alist nil)
2596 (make-variable-buffer-local 'org-tag-groups-alist)
2597 (defvar org-agenda-contributing-files nil)
2598 (defvar org-not-done-keywords nil)
2599 (make-variable-buffer-local 'org-not-done-keywords)
2600 (defvar org-done-keywords nil)
2601 (make-variable-buffer-local 'org-done-keywords)
2602 (defvar org-todo-heads nil)
2603 (make-variable-buffer-local 'org-todo-heads)
2604 (defvar org-todo-sets nil)
2605 (make-variable-buffer-local 'org-todo-sets)
2606 (defvar org-todo-log-states nil)
2607 (make-variable-buffer-local 'org-todo-log-states)
2608 (defvar org-todo-kwd-alist nil)
2609 (make-variable-buffer-local 'org-todo-kwd-alist)
2610 (defvar org-todo-key-alist nil)
2611 (make-variable-buffer-local 'org-todo-key-alist)
2612 (defvar org-todo-key-trigger nil)
2613 (make-variable-buffer-local 'org-todo-key-trigger)
2615 (defcustom org-todo-interpretation 'sequence
2616 "Controls how TODO keywords are interpreted.
2617 This variable is in principle obsolete and is only used for
2618 backward compatibility, if the interpretation of todo keywords is
2619 not given already in `org-todo-keywords'. See that variable for
2620 more information."
2621 :group 'org-todo
2622 :group 'org-keywords
2623 :type '(choice (const sequence)
2624 (const type)))
2626 (defcustom org-use-fast-todo-selection t
2627 "Non-nil means use the fast todo selection scheme with C-c C-t.
2628 This variable describes if and under what circumstances the cycling
2629 mechanism for TODO keywords will be replaced by a single-key, direct
2630 selection scheme.
2632 When nil, fast selection is never used.
2634 When the symbol `prefix', it will be used when `org-todo' is called
2635 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2636 `C-u t' in an agenda buffer.
2638 When t, fast selection is used by default. In this case, the prefix
2639 argument forces cycling instead.
2641 In all cases, the special interface is only used if access keys have
2642 actually been assigned by the user, i.e. if keywords in the configuration
2643 are followed by a letter in parenthesis, like TODO(t)."
2644 :group 'org-todo
2645 :type '(choice
2646 (const :tag "Never" nil)
2647 (const :tag "By default" t)
2648 (const :tag "Only with C-u C-c C-t" prefix)))
2650 (defcustom org-provide-todo-statistics t
2651 "Non-nil means update todo statistics after insert and toggle.
2652 ALL-HEADLINES means update todo statistics by including headlines
2653 with no TODO keyword as well, counting them as not done.
2654 A list of TODO keywords means the same, but skip keywords that are
2655 not in this list.
2656 When set to a list of two lists, the first list contains keywords
2657 to consider as TODO keywords, the second list contains keywords
2658 to consider as DONE keywords.
2660 When this is set, todo statistics is updated in the parent of the
2661 current entry each time a todo state is changed."
2662 :group 'org-todo
2663 :type '(choice
2664 (const :tag "Yes, only for TODO entries" t)
2665 (const :tag "Yes, including all entries" all-headlines)
2666 (repeat :tag "Yes, for TODOs in this list"
2667 (string :tag "TODO keyword"))
2668 (list :tag "Yes, for TODOs and DONEs in these lists"
2669 (repeat (string :tag "TODO keyword"))
2670 (repeat (string :tag "DONE keyword")))
2671 (other :tag "No TODO statistics" nil)))
2673 (defcustom org-hierarchical-todo-statistics t
2674 "Non-nil means TODO statistics covers just direct children.
2675 When nil, all entries in the subtree are considered.
2676 This has only an effect if `org-provide-todo-statistics' is set.
2677 To set this to nil for only a single subtree, use a COOKIE_DATA
2678 property and include the word \"recursive\" into the value."
2679 :group 'org-todo
2680 :type 'boolean)
2682 (defcustom org-after-todo-state-change-hook nil
2683 "Hook which is run after the state of a TODO item was changed.
2684 The new state (a string with a TODO keyword, or nil) is available in the
2685 Lisp variable `org-state'."
2686 :group 'org-todo
2687 :type 'hook)
2689 (defvar org-blocker-hook nil
2690 "Hook for functions that are allowed to block a state change.
2692 Functions in this hook should not modify the buffer.
2693 Each function gets as its single argument a property list,
2694 see `org-trigger-hook' for more information about this list.
2696 If any of the functions in this hook returns nil, the state change
2697 is blocked.")
2699 (defvar org-trigger-hook nil
2700 "Hook for functions that are triggered by a state change.
2702 Each function gets as its single argument a property list with at
2703 least the following elements:
2705 (:type type-of-change :position pos-at-entry-start
2706 :from old-state :to new-state)
2708 Depending on the type, more properties may be present.
2710 This mechanism is currently implemented for:
2712 TODO state changes
2713 ------------------
2714 :type todo-state-change
2715 :from previous state (keyword as a string), or nil, or a symbol
2716 'todo' or 'done', to indicate the general type of state.
2717 :to new state, like in :from")
2719 (defcustom org-enforce-todo-dependencies nil
2720 "Non-nil means undone TODO entries will block switching the parent to DONE.
2721 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2722 be blocked if any prior sibling is not yet done.
2723 Finally, if the parent is blocked because of ordered siblings of its own,
2724 the child will also be blocked."
2725 :set (lambda (var val)
2726 (set var val)
2727 (if val
2728 (add-hook 'org-blocker-hook
2729 'org-block-todo-from-children-or-siblings-or-parent)
2730 (remove-hook 'org-blocker-hook
2731 'org-block-todo-from-children-or-siblings-or-parent)))
2732 :group 'org-todo
2733 :type 'boolean)
2735 (defcustom org-enforce-todo-checkbox-dependencies nil
2736 "Non-nil means unchecked boxes will block switching the parent to DONE.
2737 When this is nil, checkboxes have no influence on switching TODO states.
2738 When non-nil, you first need to check off all check boxes before the TODO
2739 entry can be switched to DONE.
2740 This variable needs to be set before org.el is loaded, and you need to
2741 restart Emacs after a change to make the change effective. The only way
2742 to change is while Emacs is running is through the customize interface."
2743 :set (lambda (var val)
2744 (set var val)
2745 (if val
2746 (add-hook 'org-blocker-hook
2747 'org-block-todo-from-checkboxes)
2748 (remove-hook 'org-blocker-hook
2749 'org-block-todo-from-checkboxes)))
2750 :group 'org-todo
2751 :type 'boolean)
2753 (defcustom org-treat-insert-todo-heading-as-state-change nil
2754 "Non-nil means inserting a TODO heading is treated as state change.
2755 So when the command \\[org-insert-todo-heading] is used, state change
2756 logging will apply if appropriate. When nil, the new TODO item will
2757 be inserted directly, and no logging will take place."
2758 :group 'org-todo
2759 :type 'boolean)
2761 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2762 "Non-nil means switching TODO states with S-cursor counts as state change.
2763 This is the default behavior. However, setting this to nil allows a
2764 convenient way to select a TODO state and bypass any logging associated
2765 with that."
2766 :group 'org-todo
2767 :type 'boolean)
2769 (defcustom org-todo-state-tags-triggers nil
2770 "Tag changes that should be triggered by TODO state changes.
2771 This is a list. Each entry is
2773 (state-change (tag . flag) .......)
2775 State-change can be a string with a state, and empty string to indicate the
2776 state that has no TODO keyword, or it can be one of the symbols `todo'
2777 or `done', meaning any not-done or done state, respectively."
2778 :group 'org-todo
2779 :group 'org-tags
2780 :type '(repeat
2781 (cons (choice :tag "When changing to"
2782 (const :tag "Not-done state" todo)
2783 (const :tag "Done state" done)
2784 (string :tag "State"))
2785 (repeat
2786 (cons :tag "Tag action"
2787 (string :tag "Tag")
2788 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2790 (defcustom org-log-done nil
2791 "Information to record when a task moves to the DONE state.
2793 Possible values are:
2795 nil Don't add anything, just change the keyword
2796 time Add a time stamp to the task
2797 note Prompt for a note and add it with template `org-log-note-headings'
2799 This option can also be set with on a per-file-basis with
2801 #+STARTUP: nologdone
2802 #+STARTUP: logdone
2803 #+STARTUP: lognotedone
2805 You can have local logging settings for a subtree by setting the LOGGING
2806 property to one or more of these keywords."
2807 :group 'org-todo
2808 :group 'org-progress
2809 :type '(choice
2810 (const :tag "No logging" nil)
2811 (const :tag "Record CLOSED timestamp" time)
2812 (const :tag "Record CLOSED timestamp with note." note)))
2814 ;; Normalize old uses of org-log-done.
2815 (cond
2816 ((eq org-log-done t) (setq org-log-done 'time))
2817 ((and (listp org-log-done) (memq 'done org-log-done))
2818 (setq org-log-done 'note)))
2820 (defcustom org-log-reschedule nil
2821 "Information to record when the scheduling date of a tasks is modified.
2823 Possible values are:
2825 nil Don't add anything, just change the date
2826 time Add a time stamp to the task
2827 note Prompt for a note and add it with template `org-log-note-headings'
2829 This option can also be set with on a per-file-basis with
2831 #+STARTUP: nologreschedule
2832 #+STARTUP: logreschedule
2833 #+STARTUP: lognotereschedule"
2834 :group 'org-todo
2835 :group 'org-progress
2836 :type '(choice
2837 (const :tag "No logging" nil)
2838 (const :tag "Record timestamp" time)
2839 (const :tag "Record timestamp with note." note)))
2841 (defcustom org-log-redeadline nil
2842 "Information to record when the deadline date of a tasks is modified.
2844 Possible values are:
2846 nil Don't add anything, just change the date
2847 time Add a time stamp to the task
2848 note Prompt for a note and add it with template `org-log-note-headings'
2850 This option can also be set with on a per-file-basis with
2852 #+STARTUP: nologredeadline
2853 #+STARTUP: logredeadline
2854 #+STARTUP: lognoteredeadline
2856 You can have local logging settings for a subtree by setting the LOGGING
2857 property to one or more of these keywords."
2858 :group 'org-todo
2859 :group 'org-progress
2860 :type '(choice
2861 (const :tag "No logging" nil)
2862 (const :tag "Record timestamp" time)
2863 (const :tag "Record timestamp with note." note)))
2865 (defcustom org-log-note-clock-out nil
2866 "Non-nil means record a note when clocking out of an item.
2867 This can also be configured on a per-file basis by adding one of
2868 the following lines anywhere in the buffer:
2870 #+STARTUP: lognoteclock-out
2871 #+STARTUP: nolognoteclock-out"
2872 :group 'org-todo
2873 :group 'org-progress
2874 :type 'boolean)
2876 (defcustom org-log-done-with-time t
2877 "Non-nil means the CLOSED time stamp will contain date and time.
2878 When nil, only the date will be recorded."
2879 :group 'org-progress
2880 :type 'boolean)
2882 (defcustom org-log-note-headings
2883 '((done . "CLOSING NOTE %t")
2884 (state . "State %-12s from %-12S %t")
2885 (note . "Note taken on %t")
2886 (reschedule . "Rescheduled from %S on %t")
2887 (delschedule . "Not scheduled, was %S on %t")
2888 (redeadline . "New deadline from %S on %t")
2889 (deldeadline . "Removed deadline, was %S on %t")
2890 (refile . "Refiled on %t")
2891 (clock-out . ""))
2892 "Headings for notes added to entries.
2894 The value is an alist, with the car being a symbol indicating the
2895 note context, and the cdr is the heading to be used. The heading
2896 may also be the empty string. The following placeholders can be
2897 used:
2899 %t a time stamp.
2900 %T an active time stamp instead the default inactive one
2901 %d a short-format time stamp.
2902 %D an active short-format time stamp.
2903 %s the new TODO state or time stamp (inactive), in double quotes.
2904 %S the old TODO state or time stamp (inactive), in double quotes.
2905 %u the user name.
2906 %U full user name.
2908 In fact, it is not a good idea to change the `state' entry,
2909 because Agenda Log mode depends on the format of these entries."
2910 :group 'org-todo
2911 :group 'org-progress
2912 :type '(list :greedy t
2913 (cons (const :tag "Heading when closing an item" done) string)
2914 (cons (const :tag
2915 "Heading when changing todo state (todo sequence only)"
2916 state) string)
2917 (cons (const :tag "Heading when just taking a note" note) string)
2918 (cons (const :tag "Heading when rescheduling" reschedule) string)
2919 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2920 (cons (const :tag "Heading when changing deadline" redeadline) string)
2921 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2922 (cons (const :tag "Heading when refiling" refile) string)
2923 (cons (const :tag "Heading when clocking out" clock-out) string)))
2925 (unless (assq 'note org-log-note-headings)
2926 (push '(note . "%t") org-log-note-headings))
2928 (defcustom org-log-into-drawer nil
2929 "Non-nil means insert state change notes and time stamps into a drawer.
2930 When nil, state changes notes will be inserted after the headline and
2931 any scheduling and clock lines, but not inside a drawer.
2933 The value of this variable should be the name of the drawer to use.
2934 LOGBOOK is proposed as the default drawer for this purpose, you can
2935 also set this to a string to define the drawer of your choice.
2937 A value of t is also allowed, representing \"LOGBOOK\".
2939 A value of t or nil can also be set with on a per-file-basis with
2941 #+STARTUP: logdrawer
2942 #+STARTUP: nologdrawer
2944 If this variable is set, `org-log-state-notes-insert-after-drawers'
2945 will be ignored.
2947 You can set the property LOG_INTO_DRAWER to overrule this setting for
2948 a subtree.
2950 Do not check directly this variable in a Lisp program. Call
2951 function `org-log-into-drawer' instead."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "Not into a drawer" nil)
2956 (const :tag "LOGBOOK" t)
2957 (string :tag "Other")))
2959 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2961 (defun org-log-into-drawer ()
2962 "Name of the log drawer, as a string, or nil.
2963 This is the value of `org-log-into-drawer'. However, if the
2964 current entry has or inherits a LOG_INTO_DRAWER property, it will
2965 be used instead of the default value."
2966 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2967 (cond ((equal p "nil") nil)
2968 ((equal p "t") "LOGBOOK")
2969 ((stringp p) p)
2970 (p "LOGBOOK")
2971 ((stringp org-log-into-drawer) org-log-into-drawer)
2972 (org-log-into-drawer "LOGBOOK"))))
2974 (defcustom org-log-state-notes-insert-after-drawers nil
2975 "Non-nil means insert state change notes after any drawers in entry.
2976 Only the drawers that *immediately* follow the headline and the
2977 deadline/scheduled line are skipped.
2978 When nil, insert notes right after the heading and perhaps the line
2979 with deadline/scheduling if present.
2981 This variable will have no effect if `org-log-into-drawer' is
2982 set."
2983 :group 'org-todo
2984 :group 'org-progress
2985 :type 'boolean)
2987 (defcustom org-log-states-order-reversed t
2988 "Non-nil means the latest state note will be directly after heading.
2989 When nil, the state change notes will be ordered according to time.
2991 This option can also be set with on a per-file-basis with
2993 #+STARTUP: logstatesreversed
2994 #+STARTUP: nologstatesreversed"
2995 :group 'org-todo
2996 :group 'org-progress
2997 :type 'boolean)
2999 (defcustom org-todo-repeat-to-state nil
3000 "The TODO state to which a repeater should return the repeating task.
3001 By default this is the first task in a TODO sequence, or the previous state
3002 in a TODO_TYP set. But you can specify another task here.
3003 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3004 :group 'org-todo
3005 :version "24.1"
3006 :type '(choice (const :tag "Head of sequence" nil)
3007 (string :tag "Specific state")))
3009 (defcustom org-log-repeat 'time
3010 "Non-nil means record moving through the DONE state when triggering repeat.
3011 An auto-repeating task is immediately switched back to TODO when
3012 marked DONE. If you are not logging state changes (by adding \"@\"
3013 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3014 record a closing note, there will be no record of the task moving
3015 through DONE. This variable forces taking a note anyway.
3017 nil Don't force a record
3018 time Record a time stamp
3019 note Prompt for a note and add it with template `org-log-note-headings'
3021 This option can also be set with on a per-file-basis with
3023 #+STARTUP: nologrepeat
3024 #+STARTUP: logrepeat
3025 #+STARTUP: lognoterepeat
3027 You can have local logging settings for a subtree by setting the LOGGING
3028 property to one or more of these keywords."
3029 :group 'org-todo
3030 :group 'org-progress
3031 :type '(choice
3032 (const :tag "Don't force a record" nil)
3033 (const :tag "Force recording the DONE state" time)
3034 (const :tag "Force recording a note with the DONE state" note)))
3037 (defgroup org-priorities nil
3038 "Priorities in Org-mode."
3039 :tag "Org Priorities"
3040 :group 'org-todo)
3042 (defcustom org-enable-priority-commands t
3043 "Non-nil means priority commands are active.
3044 When nil, these commands will be disabled, so that you never accidentally
3045 set a priority."
3046 :group 'org-priorities
3047 :type 'boolean)
3049 (defcustom org-highest-priority ?A
3050 "The highest priority of TODO items. A character like ?A, ?B etc.
3051 Must have a smaller ASCII number than `org-lowest-priority'."
3052 :group 'org-priorities
3053 :type 'character)
3055 (defcustom org-lowest-priority ?C
3056 "The lowest priority of TODO items. A character like ?A, ?B etc.
3057 Must have a larger ASCII number than `org-highest-priority'."
3058 :group 'org-priorities
3059 :type 'character)
3061 (defcustom org-default-priority ?B
3062 "The default priority of TODO items.
3063 This is the priority an item gets if no explicit priority is given.
3064 When starting to cycle on an empty priority the first step in the cycle
3065 depends on `org-priority-start-cycle-with-default'. The resulting first
3066 step priority must not exceed the range from `org-highest-priority' to
3067 `org-lowest-priority' which means that `org-default-priority' has to be
3068 in this range exclusive or inclusive the range boundaries. Else the
3069 first step refuses to set the default and the second will fall back
3070 to (depending on the command used) the highest or lowest priority."
3071 :group 'org-priorities
3072 :type 'character)
3074 (defcustom org-priority-start-cycle-with-default t
3075 "Non-nil means start with default priority when starting to cycle.
3076 When this is nil, the first step in the cycle will be (depending on the
3077 command used) one higher or lower than the default priority.
3078 See also `org-default-priority'."
3079 :group 'org-priorities
3080 :type 'boolean)
3082 (defcustom org-get-priority-function nil
3083 "Function to extract the priority from a string.
3084 The string is normally the headline. If this is nil Org computes the
3085 priority from the priority cookie like [#A] in the headline. It returns
3086 an integer, increasing by 1000 for each priority level.
3087 The user can set a different function here, which should take a string
3088 as an argument and return the numeric priority."
3089 :group 'org-priorities
3090 :version "24.1"
3091 :type '(choice
3092 (const nil)
3093 (function)))
3095 (defgroup org-time nil
3096 "Options concerning time stamps and deadlines in Org-mode."
3097 :tag "Org Time"
3098 :group 'org)
3100 (defcustom org-time-stamp-rounding-minutes '(0 5)
3101 "Number of minutes to round time stamps to.
3102 These are two values, the first applies when first creating a time stamp.
3103 The second applies when changing it with the commands `S-up' and `S-down'.
3104 When changing the time stamp, this means that it will change in steps
3105 of N minutes, as given by the second value.
3107 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3108 numbers should be factors of 60, so for example 5, 10, 15.
3110 When this is larger than 1, you can still force an exact time stamp by using
3111 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3112 and by using a prefix arg to `S-up/down' to specify the exact number
3113 of minutes to shift."
3114 :group 'org-time
3115 :get (lambda (var) ; Make sure both elements are there
3116 (if (integerp (default-value var))
3117 (list (default-value var) 5)
3118 (default-value var)))
3119 :type '(list
3120 (integer :tag "when inserting times")
3121 (integer :tag "when modifying times")))
3123 ;; Normalize old customizations of this variable.
3124 (when (integerp org-time-stamp-rounding-minutes)
3125 (setq org-time-stamp-rounding-minutes
3126 (list org-time-stamp-rounding-minutes
3127 org-time-stamp-rounding-minutes)))
3129 (defcustom org-display-custom-times nil
3130 "Non-nil means overlay custom formats over all time stamps.
3131 The formats are defined through the variable `org-time-stamp-custom-formats'.
3132 To turn this on on a per-file basis, insert anywhere in the file:
3133 #+STARTUP: customtime"
3134 :group 'org-time
3135 :set 'set-default
3136 :type 'sexp)
3137 (make-variable-buffer-local 'org-display-custom-times)
3139 (defcustom org-time-stamp-custom-formats
3140 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3141 "Custom formats for time stamps. See `format-time-string' for the syntax.
3142 These are overlaid over the default ISO format if the variable
3143 `org-display-custom-times' is set. Time like %H:%M should be at the
3144 end of the second format. The custom formats are also honored by export
3145 commands, if custom time display is turned on at the time of export."
3146 :group 'org-time
3147 :type 'sexp)
3149 (defun org-time-stamp-format (&optional long inactive)
3150 "Get the right format for a time string."
3151 (let ((f (if long (cdr org-time-stamp-formats)
3152 (car org-time-stamp-formats))))
3153 (if inactive
3154 (concat "[" (substring f 1 -1) "]")
3155 f)))
3157 (defcustom org-time-clocksum-format
3158 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3159 "The format string used when creating CLOCKSUM lines.
3160 This is also used when Org mode generates a time duration.
3162 The value can be a single format string containing two
3163 %-sequences, which will be filled with the number of hours and
3164 minutes in that order.
3166 Alternatively, the value can be a plist associating any of the
3167 keys :years, :months, :weeks, :days, :hours or :minutes with
3168 format strings. The time duration is formatted using only the
3169 time components that are needed and concatenating the results.
3170 If a time unit in absent, it falls back to the next smallest
3171 unit.
3173 The keys :require-years, :require-months, :require-days,
3174 :require-weeks, :require-hours, :require-minutes are also
3175 meaningful. A non-nil value for these keys indicates that the
3176 corresponding time component should always be included, even if
3177 its value is 0.
3180 For example,
3182 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3183 :require-minutes t)
3185 means durations longer than a day will be expressed in days,
3186 hours and minutes, and durations less than a day will always be
3187 expressed in hours and minutes (even for durations less than an
3188 hour).
3190 The value
3192 \(:days \"%dd\" :minutes \"%dm\")
3194 means durations longer than a day will be expressed in days and
3195 minutes, and durations less than a day will be expressed entirely
3196 in minutes (even for durations longer than an hour)."
3197 :group 'org-time
3198 :group 'org-clock
3199 :version "24.4"
3200 :package-version '(Org . "8.0")
3201 :type '(choice (string :tag "Format string")
3202 (set :tag "Plist"
3203 (group :inline t (const :tag "Years" :years)
3204 (string :tag "Format string"))
3205 (group :inline t
3206 (const :tag "Always show years" :require-years)
3207 (const t))
3208 (group :inline t (const :tag "Months" :months)
3209 (string :tag "Format string"))
3210 (group :inline t
3211 (const :tag "Always show months" :require-months)
3212 (const t))
3213 (group :inline t (const :tag "Weeks" :weeks)
3214 (string :tag "Format string"))
3215 (group :inline t
3216 (const :tag "Always show weeks" :require-weeks)
3217 (const t))
3218 (group :inline t (const :tag "Days" :days)
3219 (string :tag "Format string"))
3220 (group :inline t
3221 (const :tag "Always show days" :require-days)
3222 (const t))
3223 (group :inline t (const :tag "Hours" :hours)
3224 (string :tag "Format string"))
3225 (group :inline t
3226 (const :tag "Always show hours" :require-hours)
3227 (const t))
3228 (group :inline t (const :tag "Minutes" :minutes)
3229 (string :tag "Format string"))
3230 (group :inline t
3231 (const :tag "Always show minutes" :require-minutes)
3232 (const t)))))
3234 (defcustom org-time-clocksum-use-fractional nil
3235 "When non-nil, \\[org-clock-display] uses fractional times.
3236 See `org-time-clocksum-format' for more on time clock formats."
3237 :group 'org-time
3238 :group 'org-clock
3239 :version "24.3"
3240 :type 'boolean)
3242 (defcustom org-time-clocksum-use-effort-durations nil
3243 "When non-nil, \\[org-clock-display] uses effort durations.
3244 E.g. by default, one day is considered to be a 8 hours effort,
3245 so a task that has been clocked for 16 hours will be displayed
3246 as during 2 days in the clock display or in the clocktable.
3248 See `org-effort-durations' on how to set effort durations
3249 and `org-time-clocksum-format' for more on time clock formats."
3250 :group 'org-time
3251 :group 'org-clock
3252 :version "24.4"
3253 :package-version '(Org . "8.0")
3254 :type 'boolean)
3256 (defcustom org-time-clocksum-fractional-format "%.2f"
3257 "The format string used when creating CLOCKSUM lines,
3258 or when Org mode generates a time duration, if
3259 `org-time-clocksum-use-fractional' is enabled.
3261 The value can be a single format string containing one
3262 %-sequence, which will be filled with the number of hours as
3263 a float.
3265 Alternatively, the value can be a plist associating any of the
3266 keys :years, :months, :weeks, :days, :hours or :minutes with
3267 a format string. The time duration is formatted using the
3268 largest time unit which gives a non-zero integer part. If all
3269 specified formats have zero integer part, the smallest time unit
3270 is used."
3271 :group 'org-time
3272 :type '(choice (string :tag "Format string")
3273 (set (group :inline t (const :tag "Years" :years)
3274 (string :tag "Format string"))
3275 (group :inline t (const :tag "Months" :months)
3276 (string :tag "Format string"))
3277 (group :inline t (const :tag "Weeks" :weeks)
3278 (string :tag "Format string"))
3279 (group :inline t (const :tag "Days" :days)
3280 (string :tag "Format string"))
3281 (group :inline t (const :tag "Hours" :hours)
3282 (string :tag "Format string"))
3283 (group :inline t (const :tag "Minutes" :minutes)
3284 (string :tag "Format string")))))
3286 (defcustom org-deadline-warning-days 14
3287 "Number of days before expiration during which a deadline becomes active.
3288 This variable governs the display in sparse trees and in the agenda.
3289 When 0 or negative, it means use this number (the absolute value of it)
3290 even if a deadline has a different individual lead time specified.
3292 Custom commands can set this variable in the options section."
3293 :group 'org-time
3294 :group 'org-agenda-daily/weekly
3295 :type 'integer)
3297 (defcustom org-scheduled-delay-days 0
3298 "Number of days before a scheduled item becomes active.
3299 This variable governs the display in sparse trees and in the agenda.
3300 The default value (i.e. 0) means: don't delay scheduled item.
3301 When negative, it means use this number (the absolute value of it)
3302 even if a scheduled item has a different individual delay time
3303 specified.
3305 Custom commands can set this variable in the options section."
3306 :group 'org-time
3307 :group 'org-agenda-daily/weekly
3308 :version "24.4"
3309 :package-version '(Org . "8.0")
3310 :type 'integer)
3312 (defcustom org-read-date-prefer-future t
3313 "Non-nil means assume future for incomplete date input from user.
3314 This affects the following situations:
3315 1. The user gives a month but not a year.
3316 For example, if it is April and you enter \"feb 2\", this will be read
3317 as Feb 2, *next* year. \"May 5\", however, will be this year.
3318 2. The user gives a day, but no month.
3319 For example, if today is the 15th, and you enter \"3\", Org-mode will
3320 read this as the third of *next* month. However, if you enter \"17\",
3321 it will be considered as *this* month.
3323 If you set this variable to the symbol `time', then also the following
3324 will work:
3326 3. If the user gives a time.
3327 If the time is before now, it will be interpreted as tomorrow.
3329 Currently none of this works for ISO week specifications.
3331 When this option is nil, the current day, month and year will always be
3332 used as defaults.
3334 See also `org-agenda-jump-prefer-future'."
3335 :group 'org-time
3336 :type '(choice
3337 (const :tag "Never" nil)
3338 (const :tag "Check month and day" t)
3339 (const :tag "Check month, day, and time" time)))
3341 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3342 "Should the agenda jump command prefer the future for incomplete dates?
3343 The default is to do the same as configured in `org-read-date-prefer-future'.
3344 But you can also set a deviating value here.
3345 This may t or nil, or the symbol `org-read-date-prefer-future'."
3346 :group 'org-agenda
3347 :group 'org-time
3348 :version "24.1"
3349 :type '(choice
3350 (const :tag "Use org-read-date-prefer-future"
3351 org-read-date-prefer-future)
3352 (const :tag "Never" nil)
3353 (const :tag "Always" t)))
3355 (defcustom org-read-date-force-compatible-dates t
3356 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3358 Depending on the system Emacs is running on, certain dates cannot
3359 be represented with the type used internally to represent time.
3360 Dates between 1970-1-1 and 2038-1-1 can always be represented
3361 correctly. Some systems allow for earlier dates, some for later,
3362 some for both. One way to find out it to insert any date into an
3363 Org buffer, putting the cursor on the year and hitting S-up and
3364 S-down to test the range.
3366 When this variable is set to t, the date/time prompt will not let
3367 you specify dates outside the 1970-2037 range, so it is certain that
3368 these dates will work in whatever version of Emacs you are
3369 running, and also that you can move a file from one Emacs implementation
3370 to another. WHenever Org is forcing the year for you, it will display
3371 a message and beep.
3373 When this variable is nil, Org will check if the date is
3374 representable in the specific Emacs implementation you are using.
3375 If not, it will force a year, usually the current year, and beep
3376 to remind you. Currently this setting is not recommended because
3377 the likelihood that you will open your Org files in an Emacs that
3378 has limited date range is not negligible.
3380 A workaround for this problem is to use diary sexp dates for time
3381 stamps outside of this range."
3382 :group 'org-time
3383 :version "24.1"
3384 :type 'boolean)
3386 (defcustom org-read-date-display-live t
3387 "Non-nil means display current interpretation of date prompt live.
3388 This display will be in an overlay, in the minibuffer."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defcustom org-read-date-popup-calendar t
3393 "Non-nil means pop up a calendar when prompting for a date.
3394 In the calendar, the date can be selected with mouse-1. However, the
3395 minibuffer will also be active, and you can simply enter the date as well.
3396 When nil, only the minibuffer will be available."
3397 :group 'org-time
3398 :type 'boolean)
3399 (org-defvaralias 'org-popup-calendar-for-date-prompt
3400 'org-read-date-popup-calendar)
3402 (make-obsolete-variable
3403 'org-read-date-minibuffer-setup-hook
3404 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3405 (defcustom org-read-date-minibuffer-setup-hook nil
3406 "Hook to be used to set up keys for the date/time interface.
3407 Add key definitions to `minibuffer-local-map', which will be a
3408 temporary copy.
3410 WARNING: This option is obsolete, you should use
3411 `org-read-date-minibuffer-local-map' to set up keys."
3412 :group 'org-time
3413 :type 'hook)
3415 (defcustom org-extend-today-until 0
3416 "The hour when your day really ends. Must be an integer.
3417 This has influence for the following applications:
3418 - When switching the agenda to \"today\". It it is still earlier than
3419 the time given here, the day recognized as TODAY is actually yesterday.
3420 - When a date is read from the user and it is still before the time given
3421 here, the current date and time will be assumed to be yesterday, 23:59.
3422 Also, timestamps inserted in capture templates follow this rule.
3424 IMPORTANT: This is a feature whose implementation is and likely will
3425 remain incomplete. Really, it is only here because past midnight seems to
3426 be the favorite working time of John Wiegley :-)"
3427 :group 'org-time
3428 :type 'integer)
3430 (defcustom org-use-effective-time nil
3431 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3432 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3433 \"effective time\" of any timestamps between midnight and 8am will be
3434 23:59 of the previous day."
3435 :group 'org-time
3436 :version "24.1"
3437 :type 'boolean)
3439 (defcustom org-use-last-clock-out-time-as-effective-time nil
3440 "When non-nil, use the last clock out time for `org-todo'.
3441 Note that this option has precedence over the combined use of
3442 `org-use-effective-time' and `org-extend-today-until'."
3443 :group 'org-time
3444 :version "24.4"
3445 :package-version '(Org . "8.0")
3446 :type 'boolean)
3448 (defcustom org-edit-timestamp-down-means-later nil
3449 "Non-nil means S-down will increase the time in a time stamp.
3450 When nil, S-up will increase."
3451 :group 'org-time
3452 :type 'boolean)
3454 (defcustom org-calendar-follow-timestamp-change t
3455 "Non-nil means make the calendar window follow timestamp changes.
3456 When a timestamp is modified and the calendar window is visible, it will be
3457 moved to the new date."
3458 :group 'org-time
3459 :type 'boolean)
3461 (defgroup org-tags nil
3462 "Options concerning tags in Org-mode."
3463 :tag "Org Tags"
3464 :group 'org)
3466 (defcustom org-tag-alist nil
3467 "List of tags allowed in Org-mode files.
3468 When this list is nil, Org-mode will base TAG input on what is already in the
3469 buffer.
3470 The value of this variable is an alist, the car of each entry must be a
3471 keyword as a string, the cdr may be a character that is used to select
3472 that tag through the fast-tag-selection interface.
3473 See the manual for details."
3474 :group 'org-tags
3475 :type '(repeat
3476 (choice
3477 (cons (string :tag "Tag name")
3478 (character :tag "Access char"))
3479 (list :tag "Start radio group"
3480 (const :startgroup)
3481 (option (string :tag "Group description")))
3482 (list :tag "Start tag group, non distinct"
3483 (const :startgrouptag)
3484 (option (string :tag "Group description")))
3485 (list :tag "Group tags delimiter"
3486 (const :grouptags))
3487 (list :tag "End radio group"
3488 (const :endgroup)
3489 (option (string :tag "Group description")))
3490 (list :tag "End tag group, non distinct"
3491 (const :endgrouptag)
3492 (option (string :tag "Group description")))
3493 (const :tag "New line" (:newline)))))
3495 (defcustom org-tag-persistent-alist nil
3496 "List of tags that will always appear in all Org-mode files.
3497 This is in addition to any in buffer settings or customizations
3498 of `org-tag-alist'.
3499 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3500 The value of this variable is an alist, the car of each entry must be a
3501 keyword as a string, the cdr may be a character that is used to select
3502 that tag through the fast-tag-selection interface.
3503 See the manual for details.
3504 To disable these tags on a per-file basis, insert anywhere in the file:
3505 #+STARTUP: noptag"
3506 :group 'org-tags
3507 :type '(repeat
3508 (choice
3509 (cons (string :tag "Tag name")
3510 (character :tag "Access char"))
3511 (const :tag "Start radio group" (:startgroup))
3512 (const :tag "Group tags delimiter" (:grouptags))
3513 (const :tag "End radio group" (:endgroup))
3514 (const :tag "New line" (:newline)))))
3516 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3517 "If non-nil, always offer completion for all tags of all agenda files.
3518 Instead of customizing this variable directly, you might want to
3519 set it locally for capture buffers, because there no list of
3520 tags in that file can be created dynamically (there are none).
3522 (add-hook 'org-capture-mode-hook
3523 (lambda ()
3524 (set (make-local-variable
3525 'org-complete-tags-always-offer-all-agenda-tags)
3526 t)))"
3527 :group 'org-tags
3528 :version "24.1"
3529 :type 'boolean)
3531 (defvar org-file-tags nil
3532 "List of tags that can be inherited by all entries in the file.
3533 The tags will be inherited if the variable `org-use-tag-inheritance'
3534 says they should be.
3535 This variable is populated from #+FILETAGS lines.")
3537 (defcustom org-use-fast-tag-selection 'auto
3538 "Non-nil means use fast tag selection scheme.
3539 This is a special interface to select and deselect tags with single keys.
3540 When nil, fast selection is never used.
3541 When the symbol `auto', fast selection is used if and only if selection
3542 characters for tags have been configured, either through the variable
3543 `org-tag-alist' or through a #+TAGS line in the buffer.
3544 When t, fast selection is always used and selection keys are assigned
3545 automatically if necessary."
3546 :group 'org-tags
3547 :type '(choice
3548 (const :tag "Always" t)
3549 (const :tag "Never" nil)
3550 (const :tag "When selection characters are configured" auto)))
3552 (defcustom org-fast-tag-selection-single-key nil
3553 "Non-nil means fast tag selection exits after first change.
3554 When nil, you have to press RET to exit it.
3555 During fast tag selection, you can toggle this flag with `C-c'.
3556 This variable can also have the value `expert'. In this case, the window
3557 displaying the tags menu is not even shown, until you press C-c again."
3558 :group 'org-tags
3559 :type '(choice
3560 (const :tag "No" nil)
3561 (const :tag "Yes" t)
3562 (const :tag "Expert" expert)))
3564 (defvar org-fast-tag-selection-include-todo nil
3565 "Non-nil means fast tags selection interface will also offer TODO states.
3566 This is an undocumented feature, you should not rely on it.")
3568 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3569 "The column to which tags should be indented in a headline.
3570 If this number is positive, it specifies the column. If it is negative,
3571 it means that the tags should be flushright to that column. For example,
3572 -80 works well for a normal 80 character screen.
3573 When 0, place tags directly after headline text, with only one space in
3574 between."
3575 :group 'org-tags
3576 :type 'integer)
3578 (defcustom org-auto-align-tags t
3579 "Non-nil keeps tags aligned when modifying headlines.
3580 Some operations (i.e. demoting) change the length of a headline and
3581 therefore shift the tags around. With this option turned on, after
3582 each such operation the tags are again aligned to `org-tags-column'."
3583 :group 'org-tags
3584 :type 'boolean)
3586 (defcustom org-use-tag-inheritance t
3587 "Non-nil means tags in levels apply also for sublevels.
3588 When nil, only the tags directly given in a specific line apply there.
3589 This may also be a list of tags that should be inherited, or a regexp that
3590 matches tags that should be inherited. Additional control is possible
3591 with the variable `org-tags-exclude-from-inheritance' which gives an
3592 explicit list of tags to be excluded from inheritance, even if the value of
3593 `org-use-tag-inheritance' would select it for inheritance.
3595 If this option is t, a match early-on in a tree can lead to a large
3596 number of matches in the subtree when constructing the agenda or creating
3597 a sparse tree. If you only want to see the first match in a tree during
3598 a search, check out the variable `org-tags-match-list-sublevels'."
3599 :group 'org-tags
3600 :type '(choice
3601 (const :tag "Not" nil)
3602 (const :tag "Always" t)
3603 (repeat :tag "Specific tags" (string :tag "Tag"))
3604 (regexp :tag "Tags matched by regexp")))
3606 (defcustom org-tags-exclude-from-inheritance nil
3607 "List of tags that should never be inherited.
3608 This is a way to exclude a few tags from inheritance. For way to do
3609 the opposite, to actively allow inheritance for selected tags,
3610 see the variable `org-use-tag-inheritance'."
3611 :group 'org-tags
3612 :type '(repeat (string :tag "Tag")))
3614 (defun org-tag-inherit-p (tag)
3615 "Check if TAG is one that should be inherited."
3616 (cond
3617 ((member tag org-tags-exclude-from-inheritance) nil)
3618 ((eq org-use-tag-inheritance t) t)
3619 ((not org-use-tag-inheritance) nil)
3620 ((stringp org-use-tag-inheritance)
3621 (string-match org-use-tag-inheritance tag))
3622 ((listp org-use-tag-inheritance)
3623 (member tag org-use-tag-inheritance))
3624 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3626 (defcustom org-tags-match-list-sublevels t
3627 "Non-nil means list also sublevels of headlines matching a search.
3628 This variable applies to tags/property searches, and also to stuck
3629 projects because this search is based on a tags match as well.
3631 When set to the symbol `indented', sublevels are indented with
3632 leading dots.
3634 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3635 the sublevels of a headline matching a tag search often also match
3636 the same search. Listing all of them can create very long lists.
3637 Setting this variable to nil causes subtrees of a match to be skipped.
3639 This variable is semi-obsolete and probably should always be true. It
3640 is better to limit inheritance to certain tags using the variables
3641 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3642 :group 'org-tags
3643 :type '(choice
3644 (const :tag "No, don't list them" nil)
3645 (const :tag "Yes, do list them" t)
3646 (const :tag "List them, indented with leading dots" indented)))
3648 (defcustom org-tags-sort-function nil
3649 "When set, tags are sorted using this function as a comparator."
3650 :group 'org-tags
3651 :type '(choice
3652 (const :tag "No sorting" nil)
3653 (const :tag "Alphabetical" string<)
3654 (const :tag "Reverse alphabetical" string>)
3655 (function :tag "Custom function" nil)))
3657 (defvar org-tags-history nil
3658 "History of minibuffer reads for tags.")
3659 (defvar org-last-tags-completion-table nil
3660 "The last used completion table for tags.")
3661 (defvar org-after-tags-change-hook nil
3662 "Hook that is run after the tags in a line have changed.")
3664 (defgroup org-properties nil
3665 "Options concerning properties in Org-mode."
3666 :tag "Org Properties"
3667 :group 'org)
3669 (defcustom org-property-format "%-10s %s"
3670 "How property key/value pairs should be formatted by `indent-line'.
3671 When `indent-line' hits a property definition, it will format the line
3672 according to this format, mainly to make sure that the values are
3673 lined-up with respect to each other."
3674 :group 'org-properties
3675 :type 'string)
3677 (defcustom org-properties-postprocess-alist nil
3678 "Alist of properties and functions to adjust inserted values.
3679 Elements of this alist must be of the form
3681 ([string] [function])
3683 where [string] must be a property name and [function] must be a
3684 lambda expression: this lambda expression must take one argument,
3685 the value to adjust, and return the new value as a string.
3687 For example, this element will allow the property \"Remaining\"
3688 to be updated wrt the relation between the \"Effort\" property
3689 and the clock summary:
3691 ((\"Remaining\" (lambda(value)
3692 (let ((clocksum (org-clock-sum-current-item))
3693 (effort (org-duration-string-to-minutes
3694 (org-entry-get (point) \"Effort\"))))
3695 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3696 :group 'org-properties
3697 :version "24.1"
3698 :type '(alist :key-type (string :tag "Property")
3699 :value-type (function :tag "Function")))
3701 (defcustom org-use-property-inheritance nil
3702 "Non-nil means properties apply also for sublevels.
3704 This setting is chiefly used during property searches. Turning it on can
3705 cause significant overhead when doing a search, which is why it is not
3706 on by default.
3708 When nil, only the properties directly given in the current entry count.
3709 When t, every property is inherited. The value may also be a list of
3710 properties that should have inheritance, or a regular expression matching
3711 properties that should be inherited.
3713 However, note that some special properties use inheritance under special
3714 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3715 and the properties ending in \"_ALL\" when they are used as descriptor
3716 for valid values of a property.
3718 Note for programmers:
3719 When querying an entry with `org-entry-get', you can control if inheritance
3720 should be used. By default, `org-entry-get' looks only at the local
3721 properties. You can request inheritance by setting the inherit argument
3722 to t (to force inheritance) or to `selective' (to respect the setting
3723 in this variable)."
3724 :group 'org-properties
3725 :type '(choice
3726 (const :tag "Not" nil)
3727 (const :tag "Always" t)
3728 (repeat :tag "Specific properties" (string :tag "Property"))
3729 (regexp :tag "Properties matched by regexp")))
3731 (defun org-property-inherit-p (property)
3732 "Check if PROPERTY is one that should be inherited."
3733 (cond
3734 ((eq org-use-property-inheritance t) t)
3735 ((not org-use-property-inheritance) nil)
3736 ((stringp org-use-property-inheritance)
3737 (string-match org-use-property-inheritance property))
3738 ((listp org-use-property-inheritance)
3739 (member property org-use-property-inheritance))
3740 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3742 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3743 "The default column format, if no other format has been defined.
3744 This variable can be set on the per-file basis by inserting a line
3746 #+COLUMNS: %25ITEM ....."
3747 :group 'org-properties
3748 :type 'string)
3750 (defcustom org-columns-ellipses ".."
3751 "The ellipses to be used when a field in column view is truncated.
3752 When this is the empty string, as many characters as possible are shown,
3753 but then there will be no visual indication that the field has been truncated.
3754 When this is a string of length N, the last N characters of a truncated
3755 field are replaced by this string. If the column is narrower than the
3756 ellipses string, only part of the ellipses string will be shown."
3757 :group 'org-properties
3758 :type 'string)
3760 (defcustom org-columns-modify-value-for-display-function nil
3761 "Function that modifies values for display in column view.
3762 For example, it can be used to cut out a certain part from a time stamp.
3763 The function must take 2 arguments:
3765 column-title The title of the column (*not* the property name)
3766 value The value that should be modified.
3768 The function should return the value that should be displayed,
3769 or nil if the normal value should be used."
3770 :group 'org-properties
3771 :type '(choice (const nil) (function)))
3773 (defconst org-global-properties-fixed
3774 '(("VISIBILITY_ALL" . "folded children content all")
3775 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3776 "List of property/value pairs that can be inherited by any entry.
3778 These are fixed values, for the preset properties. The user variable
3779 that can be used to add to this list is `org-global-properties'.
3781 The entries in this list are cons cells where the car is a property
3782 name and cdr is a string with the value. If the value represents
3783 multiple items like an \"_ALL\" property, separate the items by
3784 spaces.")
3786 (defcustom org-global-properties nil
3787 "List of property/value pairs that can be inherited by any entry.
3789 This list will be combined with the constant `org-global-properties-fixed'.
3791 The entries in this list are cons cells where the car is a property
3792 name and cdr is a string with the value.
3794 You can set buffer-local values for the same purpose in the variable
3795 `org-file-properties' this by adding lines like
3797 #+PROPERTY: NAME VALUE"
3798 :group 'org-properties
3799 :type '(repeat
3800 (cons (string :tag "Property")
3801 (string :tag "Value"))))
3803 (defvar org-file-properties nil
3804 "List of property/value pairs that can be inherited by any entry.
3805 Valid for the current buffer.
3806 This variable is populated from #+PROPERTY lines.")
3807 (make-variable-buffer-local 'org-file-properties)
3809 (defgroup org-agenda nil
3810 "Options concerning agenda views in Org-mode."
3811 :tag "Org Agenda"
3812 :group 'org)
3814 (defvar org-category nil
3815 "Variable used by org files to set a category for agenda display.
3816 Such files should use a file variable to set it, for example
3818 # -*- mode: org; org-category: \"ELisp\"
3820 or contain a special line
3822 #+CATEGORY: ELisp
3824 If the file does not specify a category, then file's base name
3825 is used instead.")
3826 (make-variable-buffer-local 'org-category)
3827 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3829 (defcustom org-agenda-files nil
3830 "The files to be used for agenda display.
3831 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3832 \\[org-remove-file]. You can also use customize to edit the list.
3834 If an entry is a directory, all files in that directory that are matched by
3835 `org-agenda-file-regexp' will be part of the file list.
3837 If the value of the variable is not a list but a single file name, then
3838 the list of agenda files is actually stored and maintained in that file, one
3839 agenda file per line. In this file paths can be given relative to
3840 `org-directory'. Tilde expansion and environment variable substitution
3841 are also made."
3842 :group 'org-agenda
3843 :type '(choice
3844 (repeat :tag "List of files and directories" file)
3845 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3847 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3848 "Regular expression to match files for `org-agenda-files'.
3849 If any element in the list in that variable contains a directory instead
3850 of a normal file, all files in that directory that are matched by this
3851 regular expression will be included."
3852 :group 'org-agenda
3853 :type 'regexp)
3855 (defcustom org-agenda-text-search-extra-files nil
3856 "List of extra files to be searched by text search commands.
3857 These files will be searched in addition to the agenda files by the
3858 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3859 Note that these files will only be searched for text search commands,
3860 not for the other agenda views like todo lists, tag searches or the weekly
3861 agenda. This variable is intended to list notes and possibly archive files
3862 that should also be searched by these two commands.
3863 In fact, if the first element in the list is the symbol `agenda-archives',
3864 then all archive files of all agenda files will be added to the search
3865 scope."
3866 :group 'org-agenda
3867 :type '(set :greedy t
3868 (const :tag "Agenda Archives" agenda-archives)
3869 (repeat :inline t (file))))
3871 (org-defvaralias 'org-agenda-multi-occur-extra-files
3872 'org-agenda-text-search-extra-files)
3874 (defcustom org-agenda-skip-unavailable-files nil
3875 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3876 A nil value means to remove them, after a query, from the list."
3877 :group 'org-agenda
3878 :type 'boolean)
3880 (defcustom org-calendar-to-agenda-key [?c]
3881 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3882 The command `org-calendar-goto-agenda' will be bound to this key. The
3883 default is the character `c' because then `c' can be used to switch back and
3884 forth between agenda and calendar."
3885 :group 'org-agenda
3886 :type 'sexp)
3888 (defcustom org-calendar-insert-diary-entry-key [?i]
3889 "The key to be installed in `calendar-mode-map' for adding diary entries.
3890 This option is irrelevant until `org-agenda-diary-file' has been configured
3891 to point to an Org-mode file. When that is the case, the command
3892 `org-agenda-diary-entry' will be bound to the key given here, by default
3893 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3894 if you want to continue doing this, you need to change this to a different
3895 key."
3896 :group 'org-agenda
3897 :type 'sexp)
3899 (defcustom org-agenda-diary-file 'diary-file
3900 "File to which to add new entries with the `i' key in agenda and calendar.
3901 When this is the symbol `diary-file', the functionality in the Emacs
3902 calendar will be used to add entries to the `diary-file'. But when this
3903 points to a file, `org-agenda-diary-entry' will be used instead."
3904 :group 'org-agenda
3905 :type '(choice
3906 (const :tag "The standard Emacs diary file" diary-file)
3907 (file :tag "Special Org file diary entries")))
3909 (eval-after-load "calendar"
3910 '(progn
3911 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3912 'org-calendar-goto-agenda)
3913 (add-hook 'calendar-mode-hook
3914 (lambda ()
3915 (unless (eq org-agenda-diary-file 'diary-file)
3916 (define-key calendar-mode-map
3917 org-calendar-insert-diary-entry-key
3918 'org-agenda-diary-entry))))))
3920 (defgroup org-latex nil
3921 "Options for embedding LaTeX code into Org-mode."
3922 :tag "Org LaTeX"
3923 :group 'org)
3925 (defcustom org-format-latex-options
3926 '(:foreground default :background default :scale 1.0
3927 :html-foreground "Black" :html-background "Transparent"
3928 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3929 "Options for creating images from LaTeX fragments.
3930 This is a property list with the following properties:
3931 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3932 `default' means use the foreground of the default face.
3933 `auto' means use the foreground from the text face.
3934 :background the background color, or \"Transparent\".
3935 `default' means use the background of the default face.
3936 `auto' means use the background from the text face.
3937 :scale a scaling factor for the size of the images, to get more pixels
3938 :html-foreground, :html-background, :html-scale
3939 the same numbers for HTML export.
3940 :matchers a list indicating which matchers should be used to
3941 find LaTeX fragments. Valid members of this list are:
3942 \"begin\" find environments
3943 \"$1\" find single characters surrounded by $.$
3944 \"$\" find math expressions surrounded by $...$
3945 \"$$\" find math expressions surrounded by $$....$$
3946 \"\\(\" find math expressions surrounded by \\(...\\)
3947 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3948 :group 'org-latex
3949 :type 'plist)
3951 (defcustom org-format-latex-signal-error t
3952 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3953 When nil, just push out a message."
3954 :group 'org-latex
3955 :version "24.1"
3956 :type 'boolean)
3958 (defcustom org-latex-to-mathml-jar-file nil
3959 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3960 Use this to specify additional executable file say a jar file.
3962 When using MathToWeb as the converter, specify the full-path to
3963 your mathtoweb.jar file."
3964 :group 'org-latex
3965 :version "24.1"
3966 :type '(choice
3967 (const :tag "None" nil)
3968 (file :tag "JAR file" :must-match t)))
3970 (defcustom org-latex-to-mathml-convert-command nil
3971 "Command to convert LaTeX fragments to MathML.
3972 Replace format-specifiers in the command as noted below and use
3973 `shell-command' to convert LaTeX to MathML.
3974 %j: Executable file in fully expanded form as specified by
3975 `org-latex-to-mathml-jar-file'.
3976 %I: Input LaTeX file in fully expanded form.
3977 %i: The latex fragment to be converted.
3978 %o: Output MathML file.
3979 This command is used by `org-create-math-formula'.
3981 When using MathToWeb as the converter, set this to
3982 \"java -jar %j -unicode -force -df %o %I\".
3984 When using LaTeXML set this to
3985 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3986 :group 'org-latex
3987 :version "24.1"
3988 :type '(choice
3989 (const :tag "None" nil)
3990 (string :tag "\nShell command")))
3992 (defcustom org-latex-create-formula-image-program 'dvipng
3993 "Program to convert LaTeX fragments with.
3995 dvipng Process the LaTeX fragments to dvi file, then convert
3996 dvi files to png files using dvipng.
3997 This will also include processing of non-math environments.
3998 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3999 to convert pdf files to png files"
4000 :group 'org-latex
4001 :version "24.1"
4002 :type '(choice
4003 (const :tag "dvipng" dvipng)
4004 (const :tag "imagemagick" imagemagick)))
4006 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4007 "Path to store latex preview images.
4008 A relative path here creates many directories relative to the
4009 processed org files paths. An absolute path puts all preview
4010 images at the same place."
4011 :group 'org-latex
4012 :version "24.3"
4013 :type 'string)
4015 (defun org-format-latex-mathml-available-p ()
4016 "Return t if `org-latex-to-mathml-convert-command' is usable."
4017 (save-match-data
4018 (when (and (boundp 'org-latex-to-mathml-convert-command)
4019 org-latex-to-mathml-convert-command)
4020 (let ((executable (car (split-string
4021 org-latex-to-mathml-convert-command))))
4022 (when (executable-find executable)
4023 (if (string-match
4024 "%j" org-latex-to-mathml-convert-command)
4025 (file-readable-p org-latex-to-mathml-jar-file)
4026 t))))))
4028 (defcustom org-format-latex-header "\\documentclass{article}
4029 \\usepackage[usenames]{color}
4030 \[PACKAGES]
4031 \[DEFAULT-PACKAGES]
4032 \\pagestyle{empty} % do not remove
4033 % The settings below are copied from fullpage.sty
4034 \\setlength{\\textwidth}{\\paperwidth}
4035 \\addtolength{\\textwidth}{-3cm}
4036 \\setlength{\\oddsidemargin}{1.5cm}
4037 \\addtolength{\\oddsidemargin}{-2.54cm}
4038 \\setlength{\\evensidemargin}{\\oddsidemargin}
4039 \\setlength{\\textheight}{\\paperheight}
4040 \\addtolength{\\textheight}{-\\headheight}
4041 \\addtolength{\\textheight}{-\\headsep}
4042 \\addtolength{\\textheight}{-\\footskip}
4043 \\addtolength{\\textheight}{-3cm}
4044 \\setlength{\\topmargin}{1.5cm}
4045 \\addtolength{\\topmargin}{-2.54cm}"
4046 "The document header used for processing LaTeX fragments.
4047 It is imperative that this header make sure that no page number
4048 appears on the page. The package defined in the variables
4049 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4050 will either replace the placeholder \"[PACKAGES]\" in this
4051 header, or they will be appended."
4052 :group 'org-latex
4053 :type 'string)
4055 (defun org-set-packages-alist (var val)
4056 "Set the packages alist and make sure it has 3 elements per entry."
4057 (set var (mapcar (lambda (x)
4058 (if (and (consp x) (= (length x) 2))
4059 (list (car x) (nth 1 x) t)
4061 val)))
4063 (defun org-get-packages-alist (var)
4064 "Get the packages alist and make sure it has 3 elements per entry."
4065 (mapcar (lambda (x)
4066 (if (and (consp x) (= (length x) 2))
4067 (list (car x) (nth 1 x) t)
4069 (default-value var)))
4071 (defcustom org-latex-default-packages-alist
4072 '(("AUTO" "inputenc" t)
4073 ("T1" "fontenc" t)
4074 ("" "fixltx2e" nil)
4075 ("" "graphicx" t)
4076 ("" "grffile" t)
4077 ("" "longtable" nil)
4078 ("" "wrapfig" nil)
4079 ("" "rotating" nil)
4080 ("normalem" "ulem" t)
4081 ("" "amsmath" t)
4082 ("" "textcomp" t)
4083 ("" "marvosym" t)
4084 ("" "wasysym" t)
4085 ("" "amssymb" t)
4086 ("" "capt-of" nil)
4087 ("" "hyperref" nil)
4088 "\\tolerance=1000")
4089 "Alist of default packages to be inserted in the header.
4091 Change this only if one of the packages here causes an
4092 incompatibility with another package you are using.
4094 The packages in this list are needed by one part or another of
4095 Org mode to function properly:
4097 - inputenc, fontenc: for basic font and character selection
4098 - fixltx2e: Important patches of LaTeX itself
4099 - graphicx: for including images
4100 - grffile: allow periods and spaces in graphics file names
4101 - longtable: For multipage tables
4102 - wrapfig: for figure placement
4103 - rotating: for sideways figures and tables
4104 - ulem: for underline and strike-through
4105 - amsmath: for subscript and superscript and math environments
4106 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4107 for interpreting the entities in `org-entities'. You can skip
4108 some of these packages if you don't use any of their symbols.
4109 - capt-of: for captions outside of floats
4110 - hyperref: for cross references
4112 Therefore you should not modify this variable unless you know
4113 what you are doing. The one reason to change it anyway is that
4114 you might be loading some other package that conflicts with one
4115 of the default packages. Each element is either a cell or
4116 a string.
4118 A cell is of the format:
4120 \( \"options\" \"package\" SNIPPET-FLAG).
4122 If SNIPPET-FLAG is non-nil, the package also needs to be included
4123 when compiling LaTeX snippets into images for inclusion into
4124 non-LaTeX output.
4126 A string will be inserted as-is in the header of the document."
4127 :group 'org-latex
4128 :group 'org-export-latex
4129 :set 'org-set-packages-alist
4130 :get 'org-get-packages-alist
4131 :version "24.1"
4132 :type '(repeat
4133 (choice
4134 (list :tag "options/package pair"
4135 (string :tag "options")
4136 (string :tag "package")
4137 (boolean :tag "Snippet"))
4138 (string :tag "A line of LaTeX"))))
4140 (defcustom org-latex-packages-alist nil
4141 "Alist of packages to be inserted in every LaTeX header.
4143 These will be inserted after `org-latex-default-packages-alist'.
4144 Each element is either a cell or a string.
4146 A cell is of the format:
4148 \(\"options\" \"package\" SNIPPET-FLAG)
4150 SNIPPET-FLAG, when non-nil, indicates that this package is also
4151 needed when turning LaTeX snippets into images for inclusion into
4152 non-LaTeX output.
4154 A string will be inserted as-is in the header of the document.
4156 Make sure that you only list packages here which:
4158 - you want in every file;
4159 - do not conflict with the setup in `org-format-latex-header';
4160 - do not conflict with the default packages in
4161 `org-latex-default-packages-alist'."
4162 :group 'org-latex
4163 :group 'org-export-latex
4164 :set 'org-set-packages-alist
4165 :get 'org-get-packages-alist
4166 :type '(repeat
4167 (choice
4168 (list :tag "options/package pair"
4169 (string :tag "options")
4170 (string :tag "package")
4171 (boolean :tag "Snippet"))
4172 (string :tag "A line of LaTeX"))))
4174 (defgroup org-appearance nil
4175 "Settings for Org-mode appearance."
4176 :tag "Org Appearance"
4177 :group 'org)
4179 (defcustom org-level-color-stars-only nil
4180 "Non-nil means fontify only the stars in each headline.
4181 When nil, the entire headline is fontified.
4182 Changing it requires restart of `font-lock-mode' to become effective
4183 also in regions already fontified."
4184 :group 'org-appearance
4185 :type 'boolean)
4187 (defcustom org-hide-leading-stars nil
4188 "Non-nil means hide the first N-1 stars in a headline.
4189 This works by using the face `org-hide' for these stars. This
4190 face is white for a light background, and black for a dark
4191 background. You may have to customize the face `org-hide' to
4192 make this work.
4193 Changing it requires restart of `font-lock-mode' to become effective
4194 also in regions already fontified.
4195 You may also set this on a per-file basis by adding one of the following
4196 lines to the buffer:
4198 #+STARTUP: hidestars
4199 #+STARTUP: showstars"
4200 :group 'org-appearance
4201 :type 'boolean)
4203 (defcustom org-hidden-keywords nil
4204 "List of symbols corresponding to keywords to be hidden the org buffer.
4205 For example, a value '(title) for this list will make the document's title
4206 appear in the buffer without the initial #+TITLE: keyword."
4207 :group 'org-appearance
4208 :version "24.1"
4209 :type '(set (const :tag "#+AUTHOR" author)
4210 (const :tag "#+DATE" date)
4211 (const :tag "#+EMAIL" email)
4212 (const :tag "#+TITLE" title)))
4214 (defcustom org-custom-properties nil
4215 "List of properties (as strings) with a special meaning.
4216 The default use of these custom properties is to let the user
4217 hide them with `org-toggle-custom-properties-visibility'."
4218 :group 'org-properties
4219 :group 'org-appearance
4220 :version "24.3"
4221 :type '(repeat (string :tag "Property Name")))
4223 (defcustom org-fontify-done-headline nil
4224 "Non-nil means change the face of a headline if it is marked DONE.
4225 Normally, only the TODO/DONE keyword indicates the state of a headline.
4226 When this is non-nil, the headline after the keyword is set to the
4227 `org-headline-done' as an additional indication."
4228 :group 'org-appearance
4229 :type 'boolean)
4231 (defcustom org-fontify-emphasized-text t
4232 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4233 Changing this variable requires a restart of Emacs to take effect."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-fontify-whole-heading-line nil
4238 "Non-nil means fontify the whole line for headings.
4239 This is useful when setting a background color for the
4240 org-level-* faces."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-highlight-latex-and-related nil
4245 "Non-nil means highlight LaTeX related syntax in the buffer.
4246 When non nil, the value should be a list containing any of the
4247 following symbols:
4248 `latex' Highlight LaTeX snippets and environments.
4249 `script' Highlight subscript and superscript.
4250 `entities' Highlight entities."
4251 :group 'org-appearance
4252 :version "24.4"
4253 :package-version '(Org . "8.0")
4254 :type '(choice
4255 (const :tag "No highlighting" nil)
4256 (set :greedy t :tag "Highlight"
4257 (const :tag "LaTeX snippets and environments" latex)
4258 (const :tag "Subscript and superscript" script)
4259 (const :tag "Entities" entities))))
4261 (defcustom org-hide-emphasis-markers nil
4262 "Non-nil mean font-lock should hide the emphasis marker characters."
4263 :group 'org-appearance
4264 :type 'boolean)
4266 (defcustom org-hide-macro-markers nil
4267 "Non-nil mean font-lock should hide the brackets marking macro calls."
4268 :group 'org-appearance
4269 :type 'boolean)
4271 (defcustom org-pretty-entities nil
4272 "Non-nil means show entities as UTF8 characters.
4273 When nil, the \\name form remains in the buffer."
4274 :group 'org-appearance
4275 :version "24.1"
4276 :type 'boolean)
4278 (defcustom org-pretty-entities-include-sub-superscripts t
4279 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4280 :group 'org-appearance
4281 :version "24.1"
4282 :type 'boolean)
4284 (defvar org-emph-re nil
4285 "Regular expression for matching emphasis.
4286 After a match, the match groups contain these elements:
4287 0 The match of the full regular expression, including the characters
4288 before and after the proper match
4289 1 The character before the proper match, or empty at beginning of line
4290 2 The proper match, including the leading and trailing markers
4291 3 The leading marker like * or /, indicating the type of highlighting
4292 4 The text between the emphasis markers, not including the markers
4293 5 The character after the match, empty at the end of a line")
4294 (defvar org-verbatim-re nil
4295 "Regular expression for matching verbatim text.")
4296 (defvar org-emphasis-regexp-components) ; defined just below
4297 (defvar org-emphasis-alist) ; defined just below
4298 (defun org-set-emph-re (var val)
4299 "Set variable and compute the emphasis regular expression."
4300 (set var val)
4301 (when (and (boundp 'org-emphasis-alist)
4302 (boundp 'org-emphasis-regexp-components)
4303 org-emphasis-alist org-emphasis-regexp-components)
4304 (let* ((e org-emphasis-regexp-components)
4305 (pre (car e))
4306 (post (nth 1 e))
4307 (border (nth 2 e))
4308 (body (nth 3 e))
4309 (nl (nth 4 e))
4310 (body1 (concat body "*?"))
4311 (markers (mapconcat 'car org-emphasis-alist ""))
4312 (vmarkers (mapconcat
4313 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4314 org-emphasis-alist "")))
4315 ;; make sure special characters appear at the right position in the class
4316 (if (string-match "\\^" markers)
4317 (setq markers (concat (replace-match "" t t markers) "^")))
4318 (if (string-match "-" markers)
4319 (setq markers (concat (replace-match "" t t markers) "-")))
4320 (if (string-match "\\^" vmarkers)
4321 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4322 (if (string-match "-" vmarkers)
4323 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4324 (if (> nl 0)
4325 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4326 (int-to-string nl) "\\}")))
4327 ;; Make the regexp
4328 (setq org-emph-re
4329 (concat "\\([" pre "]\\|^\\)"
4330 "\\("
4331 "\\([" markers "]\\)"
4332 "\\("
4333 "[^" border "]\\|"
4334 "[^" border "]"
4335 body1
4336 "[^" border "]"
4337 "\\)"
4338 "\\3\\)"
4339 "\\([" post "]\\|$\\)"))
4340 (setq org-verbatim-re
4341 (concat "\\([" pre "]\\|^\\)"
4342 "\\("
4343 "\\([" vmarkers "]\\)"
4344 "\\("
4345 "[^" border "]\\|"
4346 "[^" border "]"
4347 body1
4348 "[^" border "]"
4349 "\\)"
4350 "\\3\\)"
4351 "\\([" post "]\\|$\\)")))))
4353 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4354 ;; set this option proved cumbersome. See this message/thread:
4355 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4356 (defvar org-emphasis-regexp-components
4357 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4358 "Components used to build the regular expression for emphasis.
4359 This is a list with five entries. Terminology: In an emphasis string
4360 like \" *strong word* \", we call the initial space PREMATCH, the final
4361 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4362 and \"trong wor\" is the body. The different components in this variable
4363 specify what is allowed/forbidden in each part:
4365 pre Chars allowed as prematch. Beginning of line will be allowed too.
4366 post Chars allowed as postmatch. End of line will be allowed too.
4367 border The chars *forbidden* as border characters.
4368 body-regexp A regexp like \".\" to match a body character. Don't use
4369 non-shy groups here, and don't allow newline here.
4370 newline The maximum number of newlines allowed in an emphasis exp.
4372 You need to reload Org or to restart Emacs after customizing this.")
4374 (defcustom org-emphasis-alist
4375 `(("*" bold)
4376 ("/" italic)
4377 ("_" underline)
4378 ("=" org-verbatim verbatim)
4379 ("~" org-code verbatim)
4380 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4381 "Alist of characters and faces to emphasize text.
4382 Text starting and ending with a special character will be emphasized,
4383 for example *bold*, _underlined_ and /italic/. This variable sets the
4384 marker characters and the face to be used by font-lock for highlighting
4385 in Org-mode Emacs buffers.
4387 You need to reload Org or to restart Emacs after customizing this."
4388 :group 'org-appearance
4389 :set 'org-set-emph-re
4390 :version "24.4"
4391 :package-version '(Org . "8.0")
4392 :type '(repeat
4393 (list
4394 (string :tag "Marker character")
4395 (choice
4396 (face :tag "Font-lock-face")
4397 (plist :tag "Face property list"))
4398 (option (const verbatim)))))
4400 (defvar org-protecting-blocks
4401 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4402 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4403 This is needed for font-lock setup.")
4405 ;;; Miscellaneous options
4407 (defgroup org-completion nil
4408 "Completion in Org-mode."
4409 :tag "Org Completion"
4410 :group 'org)
4412 (defcustom org-completion-use-ido nil
4413 "Non-nil means use ido completion wherever possible.
4414 Note that `ido-mode' must be active for this variable to be relevant.
4415 If you decide to turn this variable on, you might well want to turn off
4416 `org-outline-path-complete-in-steps'.
4417 See also `org-completion-use-iswitchb'."
4418 :group 'org-completion
4419 :type 'boolean)
4421 (defcustom org-completion-use-iswitchb nil
4422 "Non-nil means use iswitchb completion wherever possible.
4423 Note that `iswitchb-mode' must be active for this variable to be relevant.
4424 If you decide to turn this variable on, you might well want to turn off
4425 `org-outline-path-complete-in-steps'.
4426 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4427 :group 'org-completion
4428 :type 'boolean)
4430 (defcustom org-completion-fallback-command 'hippie-expand
4431 "The expansion command called by \\[pcomplete] in normal context.
4432 Normal means, no org-mode-specific context."
4433 :group 'org-completion
4434 :type 'function)
4436 ;;; Functions and variables from their packages
4437 ;; Declared here to avoid compiler warnings
4439 ;; XEmacs only
4440 (defvar outline-mode-menu-heading)
4441 (defvar outline-mode-menu-show)
4442 (defvar outline-mode-menu-hide)
4443 (defvar zmacs-regions) ; XEmacs regions
4445 ;; Emacs only
4446 (defvar mark-active)
4448 ;; Various packages
4449 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4450 (declare-function calendar-forward-day "cal-move" (arg))
4451 (declare-function calendar-goto-date "cal-move" (date))
4452 (declare-function calendar-goto-today "cal-move" ())
4453 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4454 (defvar calc-embedded-close-formula)
4455 (defvar calc-embedded-open-formula)
4456 (declare-function cdlatex-tab "ext:cdlatex" ())
4457 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4458 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4459 (defvar font-lock-unfontify-region-function)
4460 (declare-function iswitchb-read-buffer "iswitchb"
4461 (prompt &optional default require-match start matches-set))
4462 (defvar iswitchb-temp-buflist)
4463 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4464 (defvar org-agenda-tags-todo-honor-ignore-options)
4465 (declare-function org-agenda-skip "org-agenda" ())
4466 (declare-function
4467 org-agenda-format-item "org-agenda"
4468 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4469 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4470 (declare-function org-agenda-change-all-lines "org-agenda"
4471 (newhead hdmarker &optional fixface just-this))
4472 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4473 (declare-function org-agenda-maybe-redo "org-agenda" ())
4474 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4475 (beg end))
4476 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4477 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4478 "org-agenda" (&optional end))
4479 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4480 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4481 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4482 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4483 (declare-function org-indent-mode "org-indent" (&optional arg))
4484 (declare-function parse-time-string "parse-time" (string))
4485 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4486 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4487 (defvar remember-data-file)
4488 (defvar texmathp-why)
4489 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4490 (declare-function table--at-cell-p "table" (position &optional object at-column))
4491 (declare-function calc-eval "calc" (str &optional separator &rest args))
4493 ;;;###autoload
4494 (defun turn-on-orgtbl ()
4495 "Unconditionally turn on `orgtbl-mode'."
4496 (require 'org-table)
4497 (orgtbl-mode 1))
4499 (defun org-at-table-p (&optional table-type)
4500 "Non-nil if the cursor is inside an Org table.
4501 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4502 If `org-enable-table-editor' is nil, return nil unconditionally."
4503 (and org-enable-table-editor
4504 (save-excursion
4505 (beginning-of-line)
4506 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4507 (let ((element (org-element-lineage (org-element-at-point) '(table) t)))
4508 (and element
4509 (or table-type (eq (org-element-property :type element) 'org))))))
4510 (defsubst org-table-p () (org-at-table-p))
4512 (defun org-at-table.el-p ()
4513 "Non-nil when point is at a table.el table."
4514 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4515 (let ((element (org-element-at-point)))
4516 (and (eq (org-element-type element) 'table)
4517 (eq (org-element-property :type element) 'table.el)))))
4519 (defun org-table-recognize-table.el ()
4520 "If there is a table.el table nearby, recognize it and move into it."
4521 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4522 (beginning-of-line)
4523 (unless (or (looking-at org-table-dataline-regexp)
4524 (not (looking-at org-table1-hline-regexp)))
4525 (forward-line)
4526 (when (looking-at org-table-any-border-regexp)
4527 (forward-line -2)))
4528 (if (re-search-forward "|" (org-table-end t) t)
4529 (progn
4530 (require 'table)
4531 (if (table--at-cell-p (point)) t
4532 (message "recognizing table.el table...")
4533 (table-recognize-table)
4534 (message "recognizing table.el table...done")))
4535 (error "This should not happen"))))
4537 (defun org-at-table-hline-p ()
4538 "Non-nil when point is inside a hline in a table.
4539 Assume point is already in a table. If `org-enable-table-editor'
4540 is nil, return nil unconditionally."
4541 (and org-enable-table-editor
4542 (save-excursion
4543 (beginning-of-line)
4544 (looking-at org-table-hline-regexp))))
4546 (defun org-table-map-tables (function &optional quietly)
4547 "Apply FUNCTION to the start of all tables in the buffer."
4548 (save-excursion
4549 (save-restriction
4550 (widen)
4551 (goto-char (point-min))
4552 (while (re-search-forward org-table-any-line-regexp nil t)
4553 (unless quietly
4554 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4555 (beginning-of-line 1)
4556 (when (and (looking-at org-table-line-regexp)
4557 ;; Exclude tables in src/example/verbatim/clocktable blocks
4558 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4559 (save-excursion (funcall function))
4560 (or (looking-at org-table-line-regexp)
4561 (forward-char 1)))
4562 (re-search-forward org-table-any-border-regexp nil 1))))
4563 (unless quietly (message "Mapping tables: done")))
4565 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4566 (declare-function org-clock-update-mode-line "org-clock" ())
4567 (declare-function org-resolve-clocks "org-clock"
4568 (&optional also-non-dangling-p prompt last-valid))
4570 (defun org-at-TBLFM-p (&optional pos)
4571 "Non-nil when point (or POS) is in #+TBLFM line."
4572 (save-excursion
4573 (goto-char (or pos (point)))
4574 (beginning-of-line)
4575 (and (eq (org-element-type (org-element-at-point)) 'table)
4576 (looking-at org-TBLFM-regexp))))
4578 (defvar org-clock-start-time)
4579 (defvar org-clock-marker (make-marker)
4580 "Marker recording the last clock-in.")
4581 (defvar org-clock-hd-marker (make-marker)
4582 "Marker recording the last clock-in, but the headline position.")
4583 (defvar org-clock-heading ""
4584 "The heading of the current clock entry.")
4585 (defun org-clock-is-active ()
4586 "Return the buffer where the clock is currently running.
4587 Return nil if no clock is running."
4588 (marker-buffer org-clock-marker))
4590 (defun org-check-running-clock ()
4591 "Check if the current buffer contains the running clock.
4592 If yes, offer to stop it and to save the buffer with the changes."
4593 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4594 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4595 (buffer-name))))
4596 (org-clock-out)
4597 (when (y-or-n-p "Save changed buffer?")
4598 (save-buffer))))
4600 (defun org-clocktable-try-shift (dir n)
4601 "Check if this line starts a clock table, if yes, shift the time block."
4602 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4603 (org-clocktable-shift dir n)))
4605 ;;;###autoload
4606 (defun org-clock-persistence-insinuate ()
4607 "Set up hooks for clock persistence."
4608 (require 'org-clock)
4609 (add-hook 'org-mode-hook 'org-clock-load)
4610 (add-hook 'kill-emacs-hook 'org-clock-save))
4612 (defgroup org-archive nil
4613 "Options concerning archiving in Org-mode."
4614 :tag "Org Archive"
4615 :group 'org-structure)
4617 (defcustom org-archive-location "%s_archive::"
4618 "The location where subtrees should be archived.
4620 The value of this variable is a string, consisting of two parts,
4621 separated by a double-colon. The first part is a filename and
4622 the second part is a headline.
4624 When the filename is omitted, archiving happens in the same file.
4625 %s in the filename will be replaced by the current file
4626 name (without the directory part). Archiving to a different file
4627 is useful to keep archived entries from contributing to the
4628 Org-mode Agenda.
4630 The archived entries will be filed as subtrees of the specified
4631 headline. When the headline is omitted, the subtrees are simply
4632 filed away at the end of the file, as top-level entries. Also in
4633 the heading you can use %s to represent the file name, this can be
4634 useful when using the same archive for a number of different files.
4636 Here are a few examples:
4637 \"%s_archive::\"
4638 If the current file is Projects.org, archive in file
4639 Projects.org_archive, as top-level trees. This is the default.
4641 \"::* Archived Tasks\"
4642 Archive in the current file, under the top-level headline
4643 \"* Archived Tasks\".
4645 \"~/org/archive.org::\"
4646 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4648 \"~/org/archive.org::* From %s\"
4649 Archive in file ~/org/archive.org (absolute path), under headlines
4650 \"From FILENAME\" where file name is the current file name.
4652 \"~/org/datetree.org::datetree/* Finished Tasks\"
4653 The \"datetree/\" string is special, signifying to archive
4654 items to the datetree. Items are placed in either the CLOSED
4655 date of the item, or the current date if there is no CLOSED date.
4656 The heading will be a subentry to the current date. There doesn't
4657 need to be a heading, but there always needs to be a slash after
4658 datetree. For example, to store archived items directly in the
4659 datetree, use \"~/org/datetree.org::datetree/\".
4661 \"basement::** Finished Tasks\"
4662 Archive in file ./basement (relative path), as level 3 trees
4663 below the level 2 heading \"** Finished Tasks\".
4665 You may set this option on a per-file basis by adding to the buffer a
4666 line like
4668 #+ARCHIVE: basement::** Finished Tasks
4670 You may also define it locally for a subtree by setting an ARCHIVE property
4671 in the entry. If such a property is found in an entry, or anywhere up
4672 the hierarchy, it will be used."
4673 :group 'org-archive
4674 :type 'string)
4676 (defcustom org-agenda-skip-archived-trees t
4677 "Non-nil means the agenda will skip any items located in archived trees.
4678 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4679 variable is no longer recommended, you should leave it at the value t.
4680 Instead, use the key `v' to cycle the archives-mode in the agenda."
4681 :group 'org-archive
4682 :group 'org-agenda-skip
4683 :type 'boolean)
4685 (defcustom org-columns-skip-archived-trees t
4686 "Non-nil means ignore archived trees when creating column view."
4687 :group 'org-archive
4688 :group 'org-properties
4689 :type 'boolean)
4691 (defcustom org-cycle-open-archived-trees nil
4692 "Non-nil means `org-cycle' will open archived trees.
4693 An archived tree is a tree marked with the tag ARCHIVE.
4694 When nil, archived trees will stay folded. You can still open them with
4695 normal outline commands like `show-all', but not with the cycling commands."
4696 :group 'org-archive
4697 :group 'org-cycle
4698 :type 'boolean)
4700 (defcustom org-sparse-tree-open-archived-trees nil
4701 "Non-nil means sparse tree construction shows matches in archived trees.
4702 When nil, matches in these trees are highlighted, but the trees are kept in
4703 collapsed state."
4704 :group 'org-archive
4705 :group 'org-sparse-trees
4706 :type 'boolean)
4708 (defcustom org-sparse-tree-default-date-type nil
4709 "The default date type when building a sparse tree.
4710 When this is nil, a date is a scheduled or a deadline timestamp.
4711 Otherwise, these types are allowed:
4713 all: all timestamps
4714 active: only active timestamps (<...>)
4715 inactive: only inactive timestamps ([...])
4716 scheduled: only scheduled timestamps
4717 deadline: only deadline timestamps"
4718 :type '(choice (const :tag "Scheduled or deadline" nil)
4719 (const :tag "All timestamps" all)
4720 (const :tag "Only active timestamps" active)
4721 (const :tag "Only inactive timestamps" inactive)
4722 (const :tag "Only scheduled timestamps" scheduled)
4723 (const :tag "Only deadline timestamps" deadline)
4724 (const :tag "Only closed timestamps" closed))
4725 :version "25.1"
4726 :package-version '(Org . "8.3")
4727 :group 'org-sparse-trees)
4729 (defun org-cycle-hide-archived-subtrees (state)
4730 "Re-hide all archived subtrees after a visibility state change."
4731 (when (and (not org-cycle-open-archived-trees)
4732 (not (memq state '(overview folded))))
4733 (save-excursion
4734 (let* ((globalp (memq state '(contents all)))
4735 (beg (if globalp (point-min) (point)))
4736 (end (if globalp (point-max) (org-end-of-subtree t))))
4737 (org-hide-archived-subtrees beg end)
4738 (goto-char beg)
4739 (if (looking-at (concat ".*:" org-archive-tag ":"))
4740 (message "%s" (substitute-command-keys
4741 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4743 (defun org-force-cycle-archived ()
4744 "Cycle subtree even if it is archived."
4745 (interactive)
4746 (setq this-command 'org-cycle)
4747 (let ((org-cycle-open-archived-trees t))
4748 (call-interactively 'org-cycle)))
4750 (defun org-hide-archived-subtrees (beg end)
4751 "Re-hide all archived subtrees after a visibility state change."
4752 (org-with-wide-buffer
4753 (let ((case-fold-search nil)
4754 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4755 (goto-char beg)
4756 (while (and (< (point) end) (re-search-forward re end t))
4757 (when (member org-archive-tag (org-get-tags))
4758 (org-flag-subtree t)
4759 (org-end-of-subtree t))))))
4761 (declare-function outline-end-of-heading "outline" ())
4762 (declare-function outline-flag-region "outline" (from to flag))
4763 (defun org-flag-subtree (flag)
4764 (save-excursion
4765 (org-back-to-heading t)
4766 (outline-end-of-heading)
4767 (outline-flag-region (point)
4768 (progn (org-end-of-subtree t) (point))
4769 flag)))
4771 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4773 ;; Declare Column View Code
4775 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4776 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4777 (declare-function org-columns-compute "org-colview" (property))
4779 ;; Declare ID code
4781 (declare-function org-id-store-link "org-id")
4782 (declare-function org-id-locations-load "org-id")
4783 (declare-function org-id-locations-save "org-id")
4784 (defvar org-id-track-globally)
4786 ;;; Variables for pre-computed regular expressions, all buffer local
4788 (defvar org-todo-regexp nil
4789 "Matches any of the TODO state keywords.")
4790 (make-variable-buffer-local 'org-todo-regexp)
4791 (defvar org-not-done-regexp nil
4792 "Matches any of the TODO state keywords except the last one.")
4793 (make-variable-buffer-local 'org-not-done-regexp)
4794 (defvar org-not-done-heading-regexp nil
4795 "Matches a TODO headline that is not done.")
4796 (make-variable-buffer-local 'org-not-done-heading-regexp)
4797 (defvar org-todo-line-regexp nil
4798 "Matches a headline and puts TODO state into group 2 if present.")
4799 (make-variable-buffer-local 'org-todo-line-regexp)
4800 (defvar org-complex-heading-regexp nil
4801 "Matches a headline and puts everything into groups:
4802 group 1: the stars
4803 group 2: The todo keyword, maybe
4804 group 3: Priority cookie
4805 group 4: True headline
4806 group 5: Tags")
4807 (make-variable-buffer-local 'org-complex-heading-regexp)
4808 (defvar 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 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4814 (defvar org-todo-line-tags-regexp nil
4815 "Matches a headline and puts TODO state into group 2 if present.
4816 Also put tags into group 4 if tags are present.")
4817 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4819 (defconst org-plain-time-of-day-regexp
4820 (concat
4821 "\\(\\<[012]?[0-9]"
4822 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4823 "\\(--?"
4824 "\\(\\<[012]?[0-9]"
4825 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4826 "\\)?")
4827 "Regular expression to match a plain time or time range.
4828 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4829 groups carry important information:
4830 0 the full match
4831 1 the first time, range or not
4832 8 the second time, if it is a range.")
4834 (defconst org-plain-time-extension-regexp
4835 (concat
4836 "\\(\\<[012]?[0-9]"
4837 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4838 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4839 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4840 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4841 groups carry important information:
4842 0 the full match
4843 7 hours of duration
4844 9 minutes of duration")
4846 (defconst org-stamp-time-of-day-regexp
4847 (concat
4848 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4849 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4850 "\\(--?"
4851 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4852 "Regular expression to match a timestamp time or time range.
4853 After a match, the following groups carry important information:
4854 0 the full match
4855 1 date plus weekday, for back referencing to make sure both times are on the same day
4856 2 the first time, range or not
4857 4 the second time, if it is a range.")
4859 (defconst org-startup-options
4860 '(("fold" org-startup-folded t)
4861 ("overview" org-startup-folded t)
4862 ("nofold" org-startup-folded nil)
4863 ("showall" org-startup-folded nil)
4864 ("showeverything" org-startup-folded showeverything)
4865 ("content" org-startup-folded content)
4866 ("indent" org-startup-indented t)
4867 ("noindent" org-startup-indented nil)
4868 ("hidestars" org-hide-leading-stars t)
4869 ("showstars" org-hide-leading-stars nil)
4870 ("odd" org-odd-levels-only t)
4871 ("oddeven" org-odd-levels-only nil)
4872 ("align" org-startup-align-all-tables t)
4873 ("noalign" org-startup-align-all-tables nil)
4874 ("inlineimages" org-startup-with-inline-images t)
4875 ("noinlineimages" org-startup-with-inline-images nil)
4876 ("latexpreview" org-startup-with-latex-preview t)
4877 ("nolatexpreview" org-startup-with-latex-preview nil)
4878 ("customtime" org-display-custom-times t)
4879 ("logdone" org-log-done time)
4880 ("lognotedone" org-log-done note)
4881 ("nologdone" org-log-done nil)
4882 ("lognoteclock-out" org-log-note-clock-out t)
4883 ("nolognoteclock-out" org-log-note-clock-out nil)
4884 ("logrepeat" org-log-repeat state)
4885 ("lognoterepeat" org-log-repeat note)
4886 ("logdrawer" org-log-into-drawer t)
4887 ("nologdrawer" org-log-into-drawer nil)
4888 ("logstatesreversed" org-log-states-order-reversed t)
4889 ("nologstatesreversed" org-log-states-order-reversed nil)
4890 ("nologrepeat" org-log-repeat nil)
4891 ("logreschedule" org-log-reschedule time)
4892 ("lognotereschedule" org-log-reschedule note)
4893 ("nologreschedule" org-log-reschedule nil)
4894 ("logredeadline" org-log-redeadline time)
4895 ("lognoteredeadline" org-log-redeadline note)
4896 ("nologredeadline" org-log-redeadline nil)
4897 ("logrefile" org-log-refile time)
4898 ("lognoterefile" org-log-refile note)
4899 ("nologrefile" org-log-refile nil)
4900 ("fninline" org-footnote-define-inline t)
4901 ("nofninline" org-footnote-define-inline nil)
4902 ("fnlocal" org-footnote-section nil)
4903 ("fnauto" org-footnote-auto-label t)
4904 ("fnprompt" org-footnote-auto-label nil)
4905 ("fnconfirm" org-footnote-auto-label confirm)
4906 ("fnplain" org-footnote-auto-label plain)
4907 ("fnadjust" org-footnote-auto-adjust t)
4908 ("nofnadjust" org-footnote-auto-adjust nil)
4909 ("constcgs" constants-unit-system cgs)
4910 ("constSI" constants-unit-system SI)
4911 ("noptag" org-tag-persistent-alist nil)
4912 ("hideblocks" org-hide-block-startup t)
4913 ("nohideblocks" org-hide-block-startup nil)
4914 ("beamer" org-startup-with-beamer-mode t)
4915 ("entitiespretty" org-pretty-entities t)
4916 ("entitiesplain" org-pretty-entities nil))
4917 "Variable associated with STARTUP options for org-mode.
4918 Each element is a list of three items: the startup options (as written
4919 in the #+STARTUP line), the corresponding variable, and the value to set
4920 this variable to if the option is found. An optional forth element PUSH
4921 means to push this value onto the list in the variable.")
4923 (defcustom org-group-tags t
4924 "When non-nil (the default), use group tags.
4925 This can be turned on/off through `org-toggle-tags-groups'."
4926 :group 'org-tags
4927 :group 'org-startup
4928 :type 'boolean)
4930 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4932 (defun org-toggle-tags-groups ()
4933 "Toggle support for group tags.
4934 Support for group tags is controlled by the option
4935 `org-group-tags', which is non-nil by default."
4936 (interactive)
4937 (setq org-group-tags (not org-group-tags))
4938 (cond ((and (derived-mode-p 'org-agenda-mode)
4939 org-group-tags)
4940 (org-agenda-redo))
4941 ((derived-mode-p 'org-mode)
4942 (let ((org-inhibit-startup t)) (org-mode))))
4943 (message "Groups tags support has been turned %s"
4944 (if org-group-tags "on" "off")))
4946 (defun org-set-regexps-and-options (&optional tags-only)
4947 "Precompute regular expressions used in the current buffer.
4948 When optional argument TAGS-ONLY is non-nil, only compute tags
4949 related expressions."
4950 (when (derived-mode-p 'org-mode)
4951 (let ((alist (org--setup-collect-keywords
4952 (org-make-options-regexp
4953 (append '("FILETAGS" "TAGS" "SETUPFILE")
4954 (and (not tags-only)
4955 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4956 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4957 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4958 (org--setup-process-tags
4959 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4960 (unless tags-only
4961 ;; File properties.
4962 (org-set-local 'org-file-properties (cdr (assq 'property alist)))
4963 ;; Archive location.
4964 (let ((archive (cdr (assq 'archive alist))))
4965 (when archive (org-set-local 'org-archive-location archive)))
4966 ;; Category.
4967 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4968 (when cat
4969 (org-set-local 'org-category (intern cat))
4970 (org-set-local 'org-file-properties
4971 (org--update-property-plist
4972 "CATEGORY" cat org-file-properties))))
4973 ;; Columns.
4974 (let ((column (cdr (assq 'columns alist))))
4975 (when column (org-set-local 'org-columns-default-format column)))
4976 ;; Constants.
4977 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4978 ;; Link abbreviations.
4979 (let ((links (cdr (assq 'link alist))))
4980 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4981 ;; Priorities.
4982 (let ((priorities (cdr (assq 'priorities alist))))
4983 (when priorities
4984 (org-set-local 'org-highest-priority (nth 0 priorities))
4985 (org-set-local 'org-lowest-priority (nth 1 priorities))
4986 (org-set-local 'org-default-priority (nth 2 priorities))))
4987 ;; Scripts.
4988 (let ((scripts (assq 'scripts alist)))
4989 (when scripts
4990 (org-set-local 'org-use-sub-superscripts (cdr scripts))))
4991 ;; Startup options.
4992 (let ((startup (cdr (assq 'startup alist))))
4993 (dolist (option startup)
4994 (let ((entry (assoc-string option org-startup-options t)))
4995 (when entry
4996 (let ((var (nth 1 entry))
4997 (val (nth 2 entry)))
4998 (if (not (nth 3 entry)) (org-set-local var val)
4999 (unless (listp (symbol-value var))
5000 (org-set-local var nil))
5001 (add-to-list var val)))))))
5002 ;; TODO keywords.
5003 (org-set-local 'org-todo-kwd-alist nil)
5004 (org-set-local 'org-todo-key-alist nil)
5005 (org-set-local 'org-todo-key-trigger nil)
5006 (org-set-local 'org-todo-keywords-1 nil)
5007 (org-set-local 'org-done-keywords nil)
5008 (org-set-local 'org-todo-heads nil)
5009 (org-set-local 'org-todo-sets nil)
5010 (org-set-local 'org-todo-log-states nil)
5011 (let ((todo-sequences
5012 (or (nreverse (cdr (assq 'todo alist)))
5013 (let ((d (default-value 'org-todo-keywords)))
5014 (if (not (stringp (car d))) d
5015 ;; XXX: Backward compatibility code.
5016 (list (cons org-todo-interpretation d)))))))
5017 (dolist (sequence todo-sequences)
5018 (let* ((sequence (or (run-hook-with-args-until-success
5019 'org-todo-setup-filter-hook sequence)
5020 sequence))
5021 (sequence-type (car sequence))
5022 (keywords (cdr sequence))
5023 (sep (member "|" keywords))
5024 names alist)
5025 (dolist (k (remove "|" keywords))
5026 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5028 (error "Invalid TODO keyword %s" k))
5029 (let ((name (match-string 1 k))
5030 (key (match-string 2 k))
5031 (log (org-extract-log-state-settings k)))
5032 (push name names)
5033 (push (cons name (and key (string-to-char key))) alist)
5034 (when log (push log org-todo-log-states))))
5035 (let* ((names (nreverse names))
5036 (done (if sep (org-remove-keyword-keys (cdr sep))
5037 (last names)))
5038 (head (car names))
5039 (tail (list sequence-type head (car done) (org-last done))))
5040 (add-to-list 'org-todo-heads head 'append)
5041 (push names org-todo-sets)
5042 (setq org-done-keywords (append org-done-keywords done nil))
5043 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5044 (setq org-todo-key-alist
5045 (append org-todo-key-alist
5046 (and alist
5047 (append '((:startgroup))
5048 (nreverse alist)
5049 '((:endgroup))))))
5050 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5051 (setq org-todo-sets (nreverse org-todo-sets)
5052 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5053 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5054 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5055 ;; Compute the regular expressions and other local variables.
5056 ;; Using `org-outline-regexp-bol' would complicate them much,
5057 ;; because of the fixed white space at the end of that string.
5058 (if (not org-done-keywords)
5059 (setq org-done-keywords
5060 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5061 (setq org-not-done-keywords
5062 (org-delete-all org-done-keywords
5063 (copy-sequence org-todo-keywords-1))
5064 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5065 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5066 org-not-done-heading-regexp
5067 (format org-heading-keyword-regexp-format org-not-done-regexp)
5068 org-todo-line-regexp
5069 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5070 org-complex-heading-regexp
5071 (concat "^\\(\\*+\\)"
5072 "\\(?: +" org-todo-regexp "\\)?"
5073 "\\(?: +\\(\\[#.\\]\\)\\)?"
5074 "\\(?: +\\(.*?\\)\\)??"
5075 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5076 "[ \t]*$")
5077 org-complex-heading-regexp-format
5078 (concat "^\\(\\*+\\)"
5079 "\\(?: +" org-todo-regexp "\\)?"
5080 "\\(?: +\\(\\[#.\\]\\)\\)?"
5081 "\\(?: +"
5082 ;; Stats cookies can be stuck to body.
5083 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5084 "\\(%s\\)"
5085 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5086 "\\)"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5088 "[ \t]*$")
5089 org-todo-line-tags-regexp
5090 (concat "^\\(\\*+\\)"
5091 "\\(?: +" org-todo-regexp "\\)?"
5092 "\\(?: +\\(.*?\\)\\)??"
5093 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5094 "[ \t]*$"))
5095 (org-compute-latex-and-related-regexp)))))
5097 (defun org--setup-collect-keywords (regexp &optional files alist)
5098 "Return setup keywords values as an alist.
5100 REGEXP matches a subset of setup keywords. FILES is a list of
5101 file names already visited. It is used to avoid circular setup
5102 files. ALIST, when non-nil, is the alist computed so far.
5104 Return value contains the following keys: `archive', `category',
5105 `columns', `constants', `filetags', `link', `priorities',
5106 `property', `scripts', `startup', `tags' and `todo'."
5107 (org-with-wide-buffer
5108 (goto-char (point-min))
5109 (let ((case-fold-search t))
5110 (while (re-search-forward regexp nil t)
5111 (let ((element (org-element-at-point)))
5112 (when (eq (org-element-type element) 'keyword)
5113 (let ((key (org-element-property :key element))
5114 (value (org-element-property :value element)))
5115 (cond
5116 ((equal key "ARCHIVE")
5117 (when (org-string-nw-p value)
5118 (push (cons 'archive value) alist)))
5119 ((equal key "CATEGORY") (push (cons 'category value) alist))
5120 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5121 ((equal key "CONSTANTS")
5122 (let* ((constants (assq 'constants alist))
5123 (store (cdr constants)))
5124 (dolist (pair (org-split-string value))
5125 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5126 pair)
5127 (let* ((name (match-string 1 pair))
5128 (value (match-string 2 pair))
5129 (old (assoc name store)))
5130 (if old (setcdr old value)
5131 (push (cons name value) store)))))
5132 (if constants (setcdr constants store)
5133 (push (cons 'constants store) alist))))
5134 ((equal key "FILETAGS")
5135 (when (org-string-nw-p value)
5136 (let ((old (assq 'filetags alist))
5137 (new (apply #'nconc
5138 (mapcar (lambda (x) (org-split-string x ":"))
5139 (org-split-string value)))))
5140 (if old (setcdr old (append new (cdr old)))
5141 (push (cons 'filetags new) alist)))))
5142 ((equal key "LINK")
5143 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5144 (let ((links (assq 'link alist))
5145 (pair (cons (org-match-string-no-properties 1 value)
5146 (org-match-string-no-properties 2 value))))
5147 (if links (push pair (cdr links))
5148 (push (list 'link pair) alist)))))
5149 ((equal key "OPTIONS")
5150 (when (and (org-string-nw-p value)
5151 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5152 (push (cons 'scripts (read (match-string 1 value))) alist)))
5153 ((equal key "PRIORITIES")
5154 (push (cons 'priorities
5155 (let ((prio (org-split-string value)))
5156 (if (< (length prio) 3) '(?A ?C ?B)
5157 (mapcar #'string-to-char prio))))
5158 alist))
5159 ((equal key "PROPERTY")
5160 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5161 (let* ((property (assq 'property alist))
5162 (value (org--update-property-plist
5163 (org-match-string-no-properties 1 value)
5164 (org-match-string-no-properties 2 value)
5165 (cdr property))))
5166 (if property (setcdr property value)
5167 (push (cons 'property value) alist)))))
5168 ((equal key "STARTUP")
5169 (let ((startup (assq 'startup alist)))
5170 (if startup
5171 (setcdr startup
5172 (append (cdr startup) (org-split-string value)))
5173 (push (cons 'startup (org-split-string value)) alist))))
5174 ((equal key "TAGS")
5175 (let ((tag-cell (assq 'tags alist)))
5176 (if tag-cell
5177 (setcdr tag-cell
5178 (append (cdr tag-cell)
5179 '("\\n")
5180 (org-split-string value)))
5181 (push (cons 'tags (org-split-string value)) alist))))
5182 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5183 (let ((todo (assq 'todo alist))
5184 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5185 (org-split-string value))))
5186 (if todo (push value (cdr todo))
5187 (push (list 'todo value) alist))))
5188 ((equal key "SETUPFILE")
5189 (unless buffer-read-only ; Do not check in Gnus messages.
5190 (let ((f (and (org-string-nw-p value)
5191 (expand-file-name
5192 (org-remove-double-quotes value)))))
5193 (when (and f (file-readable-p f) (not (member f files)))
5194 (with-temp-buffer
5195 (insert-file-contents f)
5196 (setq alist
5197 ;; Fake Org mode to benefit from cache
5198 ;; without recurring needlessly.
5199 (let ((major-mode 'org-mode))
5200 (org--setup-collect-keywords
5201 regexp (cons f files) alist)))))))))))))))
5202 alist)
5204 (defun org--setup-process-tags (tags filetags)
5205 "Precompute variables used for tags.
5206 TAGS is a list of tags and tag group symbols, as strings.
5207 FILETAGS is a list of tags, as strings."
5208 ;; Process the file tags.
5209 (org-set-local 'org-file-tags
5210 (mapcar #'org-add-prop-inherited filetags))
5211 ;; Provide default tags if no local tags are found.
5212 (when (and (not tags) org-tag-alist)
5213 (setq tags
5214 (mapcar (lambda (tag)
5215 (case (car tag)
5216 (:startgroup "{")
5217 (:endgroup "}")
5218 (:startgrouptag "[")
5219 (:endgrouptag "]")
5220 (:grouptags ":")
5221 (:newline "\\n")
5222 (otherwise (concat (car tag)
5223 (and (characterp (cdr tag))
5224 (format "(%c)" (cdr tag)))))))
5225 org-tag-alist)))
5226 ;; Process the tags.
5227 (org-set-local 'org-tag-groups-alist nil)
5228 (org-set-local 'org-tag-alist nil)
5229 (let (group-flag)
5230 (while tags
5231 (let ((e (car tags)))
5232 (setq tags (cdr tags))
5233 (cond
5234 ((equal e "{")
5235 (push '(:startgroup) org-tag-alist)
5236 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5237 ((equal e "}")
5238 (push '(:endgroup) org-tag-alist)
5239 (setq group-flag nil))
5240 ((equal e "[")
5241 (push '(:startgrouptag) org-tag-alist)
5242 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5243 ((equal e "]")
5244 (push '(:endgrouptag) org-tag-alist)
5245 (setq group-flag nil))
5246 ((equal e ":")
5247 (push '(:grouptags) org-tag-alist)
5248 (setq group-flag 'append))
5249 ((equal e "\\n") (push '(:newline) org-tag-alist))
5250 ((string-match
5251 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5252 "\\|{.+?}\\)" ; regular expression
5253 "\\(?:(\\(.\\))\\)?\\'")) e)
5254 (let ((tag (match-string 1 e))
5255 (key (and (match-beginning 2)
5256 (string-to-char (match-string 2 e)))))
5257 (cond ((eq group-flag 'append)
5258 (setcar org-tag-groups-alist
5259 (append (car org-tag-groups-alist) (list tag))))
5260 (group-flag (push (list tag) org-tag-groups-alist)))
5261 ;; Push all tags in groups, no matter if they already exist.
5262 (unless (and (not group-flag) (assoc tag org-tag-alist))
5263 (push (cons tag key) org-tag-alist))))))))
5264 (setq org-tag-alist (nreverse org-tag-alist)))
5266 (defun org-file-contents (file &optional noerror)
5267 "Return the contents of FILE, as a string."
5268 (if (and file (file-readable-p file))
5269 (with-temp-buffer
5270 (insert-file-contents file)
5271 (buffer-string))
5272 (funcall (if noerror 'message 'error)
5273 "Cannot read file \"%s\"%s"
5274 file
5275 (let ((from (buffer-file-name (buffer-base-buffer))))
5276 (if from (concat " (referenced in file \"" from "\")") "")))))
5278 (defun org-extract-log-state-settings (x)
5279 "Extract the log state setting from a TODO keyword string.
5280 This will extract info from a string like \"WAIT(w@/!)\"."
5281 (let (kw key log1 log2)
5282 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5283 (setq kw (match-string 1 x)
5284 key (and (match-end 2) (match-string 2 x))
5285 log1 (and (match-end 3) (match-string 3 x))
5286 log2 (and (match-end 4) (match-string 4 x)))
5287 (and (or log1 log2)
5288 (list kw
5289 (and log1 (if (equal log1 "!") 'time 'note))
5290 (and log2 (if (equal log2 "!") 'time 'note)))))))
5292 (defun org-remove-keyword-keys (list)
5293 "Remove a pair of parenthesis at the end of each string in LIST."
5294 (mapcar (lambda (x)
5295 (if (string-match "(.*)$" x)
5296 (substring x 0 (match-beginning 0))
5298 list))
5300 (defun org-assign-fast-keys (alist)
5301 "Assign fast keys to a keyword-key alist.
5302 Respect keys that are already there."
5303 (let (new e (alt ?0))
5304 (while (setq e (pop alist))
5305 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5306 (cdr e)) ;; Key already assigned.
5307 (push e new)
5308 (let ((clist (string-to-list (downcase (car e))))
5309 (used (append new alist)))
5310 (when (= (car clist) ?@)
5311 (pop clist))
5312 (while (and clist (rassoc (car clist) used))
5313 (pop clist))
5314 (unless clist
5315 (while (rassoc alt used)
5316 (incf alt)))
5317 (push (cons (car e) (or (car clist) alt)) new))))
5318 (nreverse new)))
5320 ;;; Some variables used in various places
5322 (defvar org-window-configuration nil
5323 "Used in various places to store a window configuration.")
5324 (defvar org-selected-window nil
5325 "Used in various places to store a window configuration.")
5326 (defvar org-finish-function nil
5327 "Function to be called when `C-c C-c' is used.
5328 This is for getting out of special buffers like capture.")
5331 ;; FIXME: Occasionally check by commenting these, to make sure
5332 ;; no other functions uses these, forgetting to let-bind them.
5333 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5334 (defvar org-last-state)
5335 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5337 ;; Defined somewhere in this file, but used before definition.
5338 (defvar org-entities) ;; defined in org-entities.el
5339 (defvar org-struct-menu)
5340 (defvar org-org-menu)
5341 (defvar org-tbl-menu)
5343 ;;;; Define the Org-mode
5345 ;; We use a before-change function to check if a table might need
5346 ;; an update.
5347 (defvar org-table-may-need-update t
5348 "Indicates that a table might need an update.
5349 This variable is set by `org-before-change-function'.
5350 `org-table-align' sets it back to nil.")
5351 (defun org-before-change-function (beg end)
5352 "Every change indicates that a table might need an update."
5353 (setq org-table-may-need-update t))
5354 (defvar org-mode-map)
5355 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5356 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5357 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5358 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5359 (defvar org-table-buffer-is-an nil)
5361 (defvar bidi-paragraph-direction)
5362 (defvar buffer-face-mode-face)
5364 (require 'outline)
5365 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5366 (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"))
5367 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5369 ;; Other stuff we need.
5370 (require 'time-date)
5371 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5372 (require 'easymenu)
5373 (autoload 'easy-menu-add "easymenu")
5374 (require 'overlay)
5376 ;; (require 'org-macs) moved higher up in the file before it is first used
5377 (require 'org-entities)
5378 ;; (require 'org-compat) moved higher up in the file before it is first used
5379 (require 'org-faces)
5380 (require 'org-list)
5381 (require 'org-pcomplete)
5382 (require 'org-src)
5383 (require 'org-footnote)
5384 (require 'org-macro)
5386 ;; babel
5387 (require 'ob)
5389 ;;;###autoload
5390 (define-derived-mode org-mode outline-mode "Org"
5391 "Outline-based notes management and organizer, alias
5392 \"Carsten's outline-mode for keeping track of everything.\"
5394 Org-mode develops organizational tasks around a NOTES file which
5395 contains information about projects as plain text. Org-mode is
5396 implemented on top of outline-mode, which is ideal to keep the content
5397 of large files well structured. It supports ToDo items, deadlines and
5398 time stamps, which magically appear in the diary listing of the Emacs
5399 calendar. Tables are easily created with a built-in table editor.
5400 Plain text URL-like links connect to websites, emails (VM), Usenet
5401 messages (Gnus), BBDB entries, and any files related to the project.
5402 For printing and sharing of notes, an Org-mode file (or a part of it)
5403 can be exported as a structured ASCII or HTML file.
5405 The following commands are available:
5407 \\{org-mode-map}"
5409 ;; Get rid of Outline menus, they are not needed
5410 ;; Need to do this here because define-derived-mode sets up
5411 ;; the keymap so late. Still, it is a waste to call this each time
5412 ;; we switch another buffer into org-mode.
5413 (if (featurep 'xemacs)
5414 (when (boundp 'outline-mode-menu-heading)
5415 ;; Assume this is Greg's port, it uses easymenu
5416 (easy-menu-remove outline-mode-menu-heading)
5417 (easy-menu-remove outline-mode-menu-show)
5418 (easy-menu-remove outline-mode-menu-hide))
5419 (define-key org-mode-map [menu-bar headings] 'undefined)
5420 (define-key org-mode-map [menu-bar hide] 'undefined)
5421 (define-key org-mode-map [menu-bar show] 'undefined))
5423 (org-load-modules-maybe)
5424 (easy-menu-add org-org-menu)
5425 (easy-menu-add org-tbl-menu)
5426 (org-install-agenda-files-menu)
5427 (if 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 (org-set-local 'line-move-ignore-invisible t))
5432 (org-set-local 'outline-regexp org-outline-regexp)
5433 (org-set-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 (org-set-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 (if org-startup-truncated (setq truncate-lines t))
5460 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5461 (org-set-local 'font-lock-unfontify-region-function
5462 'org-unfontify-region)
5463 ;; Activate before-change-function
5464 (org-set-local 'org-table-may-need-update t)
5465 (org-add-hook 'before-change-functions 'org-before-change-function nil
5466 'local)
5467 ;; Check for running clock before killing a buffer
5468 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5469 ;; Initialize macros templates.
5470 (org-macro-initialize-templates)
5471 ;; Initialize radio targets.
5472 (org-update-radio-target-regexp)
5473 ;; Indentation.
5474 (org-set-local 'indent-line-function 'org-indent-line)
5475 (org-set-local 'indent-region-function 'org-indent-region)
5476 ;; Filling and auto-filling.
5477 (org-setup-filling)
5478 ;; Comments.
5479 (org-setup-comments-handling)
5480 ;; Initialize cache.
5481 (org-element-cache-reset)
5482 ;; Beginning/end of defun
5483 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5484 (org-set-local 'end-of-defun-function
5485 (lambda ()
5486 (if (not (org-at-heading-p))
5487 (org-forward-element)
5488 (org-forward-element)
5489 (forward-char -1))))
5490 ;; Next error for sparse trees
5491 (org-set-local 'next-error-function 'org-occur-next-match)
5492 ;; Make sure dependence stuff works reliably, even for users who set it
5493 ;; too late :-(
5494 (if org-enforce-todo-dependencies
5495 (add-hook 'org-blocker-hook
5496 'org-block-todo-from-children-or-siblings-or-parent)
5497 (remove-hook 'org-blocker-hook
5498 'org-block-todo-from-children-or-siblings-or-parent))
5499 (if org-enforce-todo-checkbox-dependencies
5500 (add-hook 'org-blocker-hook
5501 'org-block-todo-from-checkboxes)
5502 (remove-hook 'org-blocker-hook
5503 'org-block-todo-from-checkboxes))
5505 ;; Align options lines
5506 (org-set-local
5507 'align-mode-rules-list
5508 '((org-in-buffer-settings
5509 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5510 (modes . '(org-mode)))))
5512 ;; Imenu
5513 (org-set-local 'imenu-create-index-function
5514 'org-imenu-get-tree)
5516 ;; Make isearch reveal context
5517 (if (or (featurep 'xemacs)
5518 (not (boundp 'outline-isearch-open-invisible-function)))
5519 ;; Emacs 21 and XEmacs make use of the hook
5520 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5521 ;; Emacs 22 deals with this through a special variable
5522 (org-set-local 'outline-isearch-open-invisible-function
5523 (lambda (&rest ignore) (org-show-context 'isearch))))
5525 ;; Setup the pcomplete hooks
5526 (set (make-local-variable 'pcomplete-command-completion-function)
5527 'org-pcomplete-initial)
5528 (set (make-local-variable 'pcomplete-command-name-function)
5529 'org-command-at-point)
5530 (set (make-local-variable 'pcomplete-default-completion-function)
5531 'ignore)
5532 (set (make-local-variable 'pcomplete-parse-arguments-function)
5533 'org-parse-arguments)
5534 (set (make-local-variable 'pcomplete-termination-string) "")
5535 (when (>= emacs-major-version 23)
5536 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5538 ;; If empty file that did not turn on org-mode automatically, make it to.
5539 (if (and org-insert-mode-line-in-empty-file
5540 (org-called-interactively-p 'any)
5541 (= (point-min) (point-max)))
5542 (insert "# -*- mode: org -*-\n\n"))
5543 (unless org-inhibit-startup
5544 (org-unmodified
5545 (and org-startup-with-beamer-mode (org-beamer-mode))
5546 (when org-startup-align-all-tables
5547 (org-table-map-tables 'org-table-align 'quietly))
5548 (when org-startup-with-inline-images
5549 (org-display-inline-images))
5550 (when org-startup-with-latex-preview
5551 (org-toggle-latex-fragment))
5552 (unless org-inhibit-startup-visibility-stuff
5553 (org-set-startup-visibility))
5554 (org-refresh-effort-properties)))
5555 ;; Try to set org-hide correctly
5556 (let ((foreground (org-find-invisible-foreground)))
5557 (if foreground
5558 (set-face-foreground 'org-hide foreground))))
5560 ;; Update `customize-package-emacs-version-alist'
5561 (add-to-list 'customize-package-emacs-version-alist
5562 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5563 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5564 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5566 (defvar org-mode-transpose-word-syntax-table
5567 (let ((st (make-syntax-table text-mode-syntax-table)))
5568 (mapc (lambda(c) (modify-syntax-entry
5569 (string-to-char (car c)) "w p" st))
5570 org-emphasis-alist)
5571 st))
5573 (when (fboundp 'abbrev-table-put)
5574 (abbrev-table-put org-mode-abbrev-table
5575 :parents (list text-mode-abbrev-table)))
5577 (defun org-find-invisible-foreground ()
5578 (let ((candidates (remove
5579 "unspecified-bg"
5580 (nconc
5581 (list (face-background 'default)
5582 (face-background 'org-default))
5583 (mapcar
5584 (lambda (alist)
5585 (when (boundp alist)
5586 (cdr (assoc 'background-color (symbol-value alist)))))
5587 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5588 (list (face-foreground 'org-hide))))))
5589 (car (remove nil candidates))))
5591 (defun org-current-time (&optional rounding-minutes past)
5592 "Current time, possibly rounded to ROUNDING-MINUTES.
5593 When ROUNDING-MINUTES is not an integer, fall back on the car of
5594 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5595 the rounding returns a past time."
5596 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5597 (car org-time-stamp-rounding-minutes)))
5598 (time (decode-time)) res)
5599 (if (< r 1)
5600 (current-time)
5601 (setq res
5602 (apply 'encode-time
5603 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5604 (nthcdr 2 time))))
5605 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5606 (seconds-to-time (- (org-float-time res) (* r 60)))
5607 res))))
5609 (defun org-today ()
5610 "Return today date, considering `org-extend-today-until'."
5611 (time-to-days
5612 (time-subtract (current-time)
5613 (list 0 (* 3600 org-extend-today-until) 0))))
5615 ;;;; Font-Lock stuff, including the activators
5617 (defvar org-mouse-map (make-sparse-keymap))
5618 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5619 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5620 (when org-mouse-1-follows-link
5621 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5622 (when org-tab-follows-link
5623 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5624 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5626 (require 'font-lock)
5628 (defconst org-non-link-chars "]\t\n\r<>")
5629 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5630 "file+sys" "news" "shell" "elisp" "doi" "message"
5631 "help"))
5632 (defvar org-link-types-re nil
5633 "Matches a link that has a url-like prefix like \"http:\"")
5634 (defvar org-link-re-with-space nil
5635 "Matches a link with spaces, optional angular brackets around it.")
5636 (defvar org-link-re-with-space2 nil
5637 "Matches a link with spaces, optional angular brackets around it.")
5638 (defvar org-link-re-with-space3 nil
5639 "Matches a link with spaces, only for internal part in bracket links.")
5640 (defvar org-angle-link-re nil
5641 "Matches link with angular brackets, spaces are allowed.")
5642 (defvar org-plain-link-re nil
5643 "Matches plain link, without spaces.")
5644 (defvar org-bracket-link-regexp nil
5645 "Matches a link in double brackets.")
5646 (defvar org-bracket-link-analytic-regexp nil
5647 "Regular expression used to analyze links.
5648 Here is what the match groups contain after a match:
5649 1: http:
5650 2: http
5651 3: path
5652 4: [desc]
5653 5: desc")
5654 (defvar org-bracket-link-analytic-regexp++ nil
5655 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5656 (defvar org-any-link-re nil
5657 "Regular expression matching any link.")
5659 (defconst org-match-sexp-depth 3
5660 "Number of stacked braces for sub/superscript matching.")
5662 (defun org-create-multibrace-regexp (left right n)
5663 "Create a regular expression which will match a balanced sexp.
5664 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5665 as single character strings.
5666 The regexp returned will match the entire expression including the
5667 delimiters. It will also define a single group which contains the
5668 match except for the outermost delimiters. The maximum depth of
5669 stacked delimiters is N. Escaping delimiters is not possible."
5670 (let* ((nothing (concat "[^" left right "]*?"))
5671 (or "\\|")
5672 (re nothing)
5673 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5674 (while (> n 1)
5675 (setq n (1- n)
5676 re (concat re or next)
5677 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5678 (concat left "\\(" re "\\)" right)))
5680 (defconst org-match-substring-regexp
5681 (concat
5682 "\\(\\S-\\)\\([_^]\\)\\("
5683 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5684 "\\|"
5685 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5686 "\\|"
5687 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5688 "The regular expression matching a sub- or superscript.")
5690 (defconst org-match-substring-with-braces-regexp
5691 (concat
5692 "\\(\\S-\\)\\([_^]\\)"
5693 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5694 "The regular expression matching a sub- or superscript, forcing braces.")
5696 (defun org-make-link-regexps ()
5697 "Update the link regular expressions.
5698 This should be called after the variable `org-link-types' has changed."
5699 (let ((types-re (regexp-opt org-link-types t)))
5700 (setq org-link-types-re
5701 (concat "\\`" types-re ":")
5702 org-link-re-with-space
5703 (concat "<?" types-re ":"
5704 "\\([^" org-non-link-chars " ]"
5705 "[^" org-non-link-chars "]*"
5706 "[^" org-non-link-chars " ]\\)>?")
5707 org-link-re-with-space2
5708 (concat "<?" types-re ":"
5709 "\\([^" org-non-link-chars " ]"
5710 "[^\t\n\r]*"
5711 "[^" org-non-link-chars " ]\\)>?")
5712 org-link-re-with-space3
5713 (concat "<?" types-re ":"
5714 "\\([^" org-non-link-chars " ]"
5715 "[^\t\n\r]*\\)")
5716 org-angle-link-re
5717 (concat "<" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^" org-non-link-chars "]*"
5720 "\\)>")
5721 org-plain-link-re
5722 (concat
5723 "\\<" types-re ":"
5724 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5725 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5726 org-bracket-link-regexp
5727 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5728 org-bracket-link-analytic-regexp
5729 (concat
5730 "\\[\\["
5731 "\\(" types-re ":\\)?"
5732 "\\([^]]+\\)"
5733 "\\]"
5734 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5735 "\\]")
5736 org-bracket-link-analytic-regexp++
5737 (concat
5738 "\\[\\["
5739 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5740 "\\([^]]+\\)"
5741 "\\]"
5742 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5743 "\\]")
5744 org-any-link-re
5745 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5746 org-angle-link-re "\\)\\|\\("
5747 org-plain-link-re "\\)"))))
5749 (org-make-link-regexps)
5751 (defvar org-emph-face nil)
5753 (defun org-do-emphasis-faces (limit)
5754 "Run through the buffer and emphasize strings."
5755 (let (rtn a)
5756 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5757 (let* ((border (char-after (match-beginning 3)))
5758 (bre (regexp-quote (char-to-string border))))
5759 (if (and (not (= border (char-after (match-beginning 4))))
5760 (not (save-match-data
5761 (string-match (concat bre ".*" bre)
5762 (replace-regexp-in-string
5763 "\n" " "
5764 (substring (match-string 2) 1 -1))))))
5765 (progn
5766 (setq rtn t)
5767 (setq a (assoc (match-string 3) org-emphasis-alist))
5768 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5769 'face
5770 (nth 1 a))
5771 (and (nth 2 a)
5772 (org-remove-flyspell-overlays-in
5773 (match-beginning 0) (match-end 0)))
5774 (add-text-properties (match-beginning 2) (match-end 2)
5775 '(font-lock-multiline t org-emphasis t))
5776 (when org-hide-emphasis-markers
5777 (add-text-properties (match-end 4) (match-beginning 5)
5778 '(invisible org-link))
5779 (add-text-properties (match-beginning 3) (match-end 3)
5780 '(invisible org-link))))))
5781 (goto-char (1+ (match-beginning 0))))
5782 rtn))
5784 (defun org-emphasize (&optional char)
5785 "Insert or change an emphasis, i.e. a font like bold or italic.
5786 If there is an active region, change that region to a new emphasis.
5787 If there is no region, just insert the marker characters and position
5788 the cursor between them.
5789 CHAR should be the marker character. If it is a space, it means to
5790 remove the emphasis of the selected region.
5791 If CHAR is not given (for example in an interactive call) it will be
5792 prompted for."
5793 (interactive)
5794 (let ((erc org-emphasis-regexp-components)
5795 (prompt "")
5796 (string "") beg end move c s)
5797 (if (org-region-active-p)
5798 (setq beg (region-beginning) end (region-end)
5799 string (buffer-substring beg end))
5800 (setq move t))
5802 (unless char
5803 (message "Emphasis marker or tag: [%s]"
5804 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5805 (setq char (read-char-exclusive)))
5806 (if (equal char ?\ )
5807 (setq s "" move nil)
5808 (unless (assoc (char-to-string char) org-emphasis-alist)
5809 (user-error "No such emphasis marker: \"%c\"" char))
5810 (setq s (char-to-string char)))
5811 (while (and (> (length string) 1)
5812 (equal (substring string 0 1) (substring string -1))
5813 (assoc (substring string 0 1) org-emphasis-alist))
5814 (setq string (substring string 1 -1)))
5815 (setq string (concat s string s))
5816 (if beg (delete-region beg end))
5817 (unless (or (bolp)
5818 (string-match (concat "[" (nth 0 erc) "\n]")
5819 (char-to-string (char-before (point)))))
5820 (insert " "))
5821 (unless (or (eobp)
5822 (string-match (concat "[" (nth 1 erc) "\n]")
5823 (char-to-string (char-after (point)))))
5824 (insert " ") (backward-char 1))
5825 (insert string)
5826 (and move (backward-char 1))))
5828 (defconst org-nonsticky-props
5829 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5831 (defsubst org-rear-nonsticky-at (pos)
5832 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5834 (defun org-activate-plain-links (limit)
5835 "Add link properties for plain links."
5836 (let (f hl)
5837 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5838 (not (member 'org-tag
5839 (get-text-property (1- (match-beginning 0)) 'face)))
5840 (not (org-in-src-block-p)))
5841 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5842 (setq f (get-text-property (match-beginning 0) 'face))
5843 (setq hl (org-match-string-no-properties 0))
5844 (if (or (eq f 'org-tag)
5845 (and (listp f) (memq 'org-tag f)))
5847 (add-text-properties (match-beginning 0) (match-end 0)
5848 (list 'mouse-face 'highlight
5849 'face 'org-link
5850 'htmlize-link `(:uri ,hl)
5851 'keymap org-mouse-map))
5852 (org-rear-nonsticky-at (match-end 0)))
5853 t)))
5855 (defun org-activate-code (limit)
5856 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5857 (progn
5858 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5859 (remove-text-properties (match-beginning 0) (match-end 0)
5860 '(display t invisible t intangible t))
5861 t)))
5863 (defcustom org-src-fontify-natively t
5864 "When non-nil, fontify code in code blocks."
5865 :type 'boolean
5866 :version "24.4"
5867 :package-version '(Org . "8.3")
5868 :group 'org-appearance
5869 :group 'org-babel)
5871 (defcustom org-allow-promoting-top-level-subtree nil
5872 "When non-nil, allow promoting a top level subtree.
5873 The leading star of the top level headline will be replaced
5874 by a #."
5875 :type 'boolean
5876 :version "24.1"
5877 :group 'org-appearance)
5879 (defun org-fontify-meta-lines-and-blocks (limit)
5880 (condition-case nil
5881 (org-fontify-meta-lines-and-blocks-1 limit)
5882 (error (message "org-mode fontification error"))))
5884 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5885 "Fontify #+ lines and blocks."
5886 (let ((case-fold-search t))
5887 (if (re-search-forward
5888 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5889 limit t)
5890 (let ((beg (match-beginning 0))
5891 (block-start (match-end 0))
5892 (block-end nil)
5893 (lang (match-string 7))
5894 (beg1 (line-beginning-position 2))
5895 (dc1 (downcase (match-string 2)))
5896 (dc3 (downcase (match-string 3)))
5897 end end1 quoting block-type ovl)
5898 (cond
5899 ((and (match-end 4) (equal dc3 "+begin"))
5900 ;; Truly a block
5901 (setq block-type (downcase (match-string 5))
5902 quoting (member block-type org-protecting-blocks))
5903 (when (re-search-forward
5904 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5905 nil t) ;; on purpose, we look further than LIMIT
5906 (setq end (min (point-max) (match-end 0))
5907 end1 (min (point-max) (1- (match-beginning 0))))
5908 (setq block-end (match-beginning 0))
5909 (when quoting
5910 (org-remove-flyspell-overlays-in beg1 end1)
5911 (remove-text-properties beg end
5912 '(display t invisible t intangible t)))
5913 (add-text-properties
5914 beg end '(font-lock-fontified t font-lock-multiline t))
5915 (add-text-properties beg beg1 '(face org-meta-line))
5916 (org-remove-flyspell-overlays-in beg beg1)
5917 (add-text-properties ; For end_src
5918 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in end1 end)
5920 (cond
5921 ((and lang (not (string= lang "")) org-src-fontify-natively)
5922 (org-src-font-lock-fontify-block lang block-start block-end)
5923 (add-text-properties beg1 block-end '(src-block t)))
5924 (quoting
5925 (add-text-properties beg1 (min (point-max) (1+ end1))
5926 '(face org-block))) ; end of source block
5927 ((not org-fontify-quote-and-verse-blocks))
5928 ((string= block-type "quote")
5929 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5930 ((string= block-type "verse")
5931 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5932 (add-text-properties beg beg1 '(face org-block-begin-line))
5933 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5934 '(face org-block-end-line))
5936 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5937 (org-remove-flyspell-overlays-in
5938 (match-beginning 0)
5939 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5940 (add-text-properties
5941 beg (match-end 3)
5942 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5943 '(font-lock-fontified t invisible t)
5944 '(font-lock-fontified t face org-document-info-keyword)))
5945 (add-text-properties
5946 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5947 (if (string-equal dc1 "+title:")
5948 '(font-lock-fontified t face org-document-title)
5949 '(font-lock-fontified t face org-document-info))))
5950 ((equal dc1 "+caption:")
5951 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5952 (remove-text-properties (match-beginning 0) (match-end 0)
5953 '(display t invisible t intangible t))
5954 (add-text-properties (match-beginning 1) (match-end 3)
5955 '(font-lock-fontified t face org-meta-line))
5956 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5957 '(font-lock-fontified t face org-block))
5959 ((member dc3 '(" " ""))
5960 (org-remove-flyspell-overlays-in beg (match-end 0))
5961 (add-text-properties
5962 beg (match-end 0)
5963 '(font-lock-fontified t face font-lock-comment-face)))
5964 (t ;; just any other in-buffer setting, but not indented
5965 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5966 (remove-text-properties (match-beginning 0) (match-end 0)
5967 '(display t invisible t intangible t))
5968 (add-text-properties beg (match-end 0)
5969 '(font-lock-fontified t face org-meta-line))
5970 t))))))
5972 (defun org-fontify-drawers (limit)
5973 "Fontify drawers."
5974 (when (re-search-forward org-drawer-regexp limit t)
5975 (add-text-properties
5976 (match-beginning 0) (match-end 0)
5977 '(font-lock-fontified t face org-special-keyword))
5978 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5981 (defun org-fontify-macros (limit)
5982 "Fontify macros."
5983 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5984 (add-text-properties
5985 (match-beginning 0) (match-end 0)
5986 '(font-lock-fontified t face org-macro))
5987 (when org-hide-macro-markers
5988 (add-text-properties (match-end 2) (match-beginning 2)
5989 '(invisible t))
5990 (add-text-properties (match-beginning 1) (match-end 1)
5991 '(invisible t)))
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (defun org-activate-angle-links (limit)
5996 "Add text properties for angle links."
5997 (if (and (re-search-forward org-angle-link-re limit t)
5998 (not (org-in-src-block-p)))
5999 (progn
6000 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6001 (add-text-properties (match-beginning 0) (match-end 0)
6002 (list 'mouse-face 'highlight
6003 'keymap org-mouse-map))
6004 (org-rear-nonsticky-at (match-end 0))
6005 t)))
6007 (defun org-activate-footnote-links (limit)
6008 "Add text properties for footnotes."
6009 (let ((fn (org-footnote-next-reference-or-definition limit)))
6010 (when fn
6011 (let* ((beg (nth 1 fn))
6012 (end (nth 2 fn))
6013 (label (car fn))
6014 (referencep (/= (line-beginning-position) beg)))
6015 (when (and referencep (nth 3 fn))
6016 (save-excursion
6017 (goto-char beg)
6018 (search-forward (or label "fn:"))
6019 (org-remove-flyspell-overlays-in beg (match-end 0))))
6020 (add-text-properties beg end
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map
6023 'help-echo
6024 (if referencep "Footnote reference"
6025 "Footnote definition")
6026 'font-lock-fontified t
6027 'font-lock-multiline t
6028 'face 'org-footnote))))))
6030 (defun org-activate-bracket-links (limit)
6031 "Add text properties for bracketed links."
6032 (if (and (re-search-forward org-bracket-link-regexp limit t)
6033 (not (org-in-src-block-p)))
6034 (let* ((hl (org-match-string-no-properties 1))
6035 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6036 (ip (org-maybe-intangible
6037 (list 'invisible 'org-link
6038 'keymap org-mouse-map 'mouse-face 'highlight
6039 'font-lock-multiline t 'help-echo help
6040 'htmlize-link `(:uri ,hl))))
6041 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6042 'font-lock-multiline t 'help-echo help
6043 'htmlize-link `(:uri ,hl))))
6044 ;; We need to remove the invisible property here. Table narrowing
6045 ;; may have made some of this invisible.
6046 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6047 (remove-text-properties (match-beginning 0) (match-end 0)
6048 '(invisible nil))
6049 (if (match-end 3)
6050 (progn
6051 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6052 (org-rear-nonsticky-at (match-beginning 3))
6053 (add-text-properties (match-beginning 3) (match-end 3) vp)
6054 (org-rear-nonsticky-at (match-end 3))
6055 (add-text-properties (match-end 3) (match-end 0) ip)
6056 (org-rear-nonsticky-at (match-end 0)))
6057 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6058 (org-rear-nonsticky-at (match-beginning 1))
6059 (add-text-properties (match-beginning 1) (match-end 1) vp)
6060 (org-rear-nonsticky-at (match-end 1))
6061 (add-text-properties (match-end 1) (match-end 0) ip)
6062 (org-rear-nonsticky-at (match-end 0)))
6063 t)))
6065 (defun org-activate-dates (limit)
6066 "Add text properties for dates."
6067 (if (and (re-search-forward org-tsr-regexp-both limit t)
6068 (not (equal (char-before (match-beginning 0)) 91)))
6069 (progn
6070 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6071 (add-text-properties (match-beginning 0) (match-end 0)
6072 (list 'mouse-face 'highlight
6073 'keymap org-mouse-map))
6074 (org-rear-nonsticky-at (match-end 0))
6075 (when org-display-custom-times
6076 (if (match-end 3)
6077 (org-display-custom-time (match-beginning 3) (match-end 3)))
6078 (org-display-custom-time (match-beginning 1) (match-end 1)))
6079 t)))
6081 (defvar org-target-link-regexp nil
6082 "Regular expression matching radio targets in plain text.")
6083 (make-variable-buffer-local 'org-target-link-regexp)
6085 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6086 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6087 border border border))
6088 "Regular expression matching a link target.")
6090 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6091 "Regular expression matching a radio target.")
6093 (defconst org-any-target-regexp
6094 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6095 "Regular expression matching any target.")
6097 (defun org-activate-target-links (limit)
6098 "Add text properties for target matches."
6099 (when org-target-link-regexp
6100 (let ((case-fold-search t))
6101 (if (re-search-forward org-target-link-regexp limit t)
6102 (progn
6103 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6104 (add-text-properties (match-beginning 1) (match-end 1)
6105 (list 'mouse-face 'highlight
6106 'keymap org-mouse-map
6107 'help-echo "Radio target link"
6108 'org-linked-text t))
6109 (org-rear-nonsticky-at (match-end 1))
6110 t)))))
6112 (defun org-update-radio-target-regexp ()
6113 "Find all radio targets in this file and update the regular expression.
6114 Also refresh fontification if needed."
6115 (interactive)
6116 (let ((old-regexp org-target-link-regexp)
6117 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6118 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6119 (targets
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (let (rtn)
6123 (while (re-search-forward org-radio-target-regexp nil t)
6124 ;; Make sure point is really within the object.
6125 (backward-char)
6126 (let ((obj (org-element-context)))
6127 (when (eq (org-element-type obj) 'radio-target)
6128 (add-to-list 'rtn (org-element-property :value obj)))))
6129 rtn))))
6130 (setq org-target-link-regexp
6131 (and targets
6132 (concat before-re
6133 (mapconcat
6134 (lambda (x)
6135 (replace-regexp-in-string
6136 " +" "\\s-+" (regexp-quote x) t t))
6137 targets
6138 "\\|")
6139 after-re)))
6140 (unless (equal old-regexp org-target-link-regexp)
6141 ;; Clean-up cache.
6142 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6143 ((not org-target-link-regexp) old-regexp)
6145 (concat before-re
6146 (mapconcat
6147 (lambda (re)
6148 (substring re (length before-re)
6149 (- (length after-re))))
6150 (list old-regexp org-target-link-regexp)
6151 "\\|")
6152 after-re)))))
6153 (org-with-wide-buffer
6154 (goto-char (point-min))
6155 (while (re-search-forward regexp nil t)
6156 (org-element-cache-refresh (match-beginning 1)))))
6157 ;; Re fontify buffer.
6158 (when (memq 'radio org-highlight-links)
6159 (org-restart-font-lock)))))
6161 (defun org-hide-wide-columns (limit)
6162 (let (s e)
6163 (setq s (text-property-any (point) (or limit (point-max))
6164 'org-cwidth t))
6165 (when s
6166 (setq e (next-single-property-change s 'org-cwidth))
6167 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6168 (goto-char e)
6169 t)))
6171 (defvar org-latex-and-related-regexp nil
6172 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6174 (defun org-compute-latex-and-related-regexp ()
6175 "Compute regular expression for LaTeX, entities and sub/superscript.
6176 Result depends on variable `org-highlight-latex-and-related'."
6177 (org-set-local
6178 'org-latex-and-related-regexp
6179 (let* ((re-sub
6180 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6181 ((eq org-use-sub-superscripts '{})
6182 (list org-match-substring-with-braces-regexp))
6183 (org-use-sub-superscripts (list org-match-substring-regexp))))
6184 (re-latex
6185 (when (memq 'latex org-highlight-latex-and-related)
6186 (let ((matchers (plist-get org-format-latex-options :matchers)))
6187 (delq nil
6188 (mapcar (lambda (x)
6189 (and (member (car x) matchers) (nth 1 x)))
6190 org-latex-regexps)))))
6191 (re-entities
6192 (when (memq 'entities org-highlight-latex-and-related)
6193 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6194 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6196 (defun org-do-latex-and-related (limit)
6197 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6198 LIMIT bounds the search for syntax to highlight. Stop at first
6199 highlighted object, if any. Return t if some highlighting was
6200 done, nil otherwise."
6201 (when (org-string-nw-p org-latex-and-related-regexp)
6202 (catch 'found
6203 (while (re-search-forward org-latex-and-related-regexp limit t)
6204 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6205 'face))
6206 '(org-code org-verbatim underline))
6207 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6208 '(?_ ?^))
6210 0)))
6211 (font-lock-prepend-text-property
6212 (+ offset (match-beginning 0)) (match-end 0)
6213 'face 'org-latex-and-related)
6214 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6215 '(font-lock-multiline t)))
6216 (throw 'found t)))
6217 nil)))
6219 (defun org-restart-font-lock ()
6220 "Restart `font-lock-mode', to force refontification."
6221 (when (and (boundp 'font-lock-mode) font-lock-mode)
6222 (font-lock-mode -1)
6223 (font-lock-mode 1)))
6225 (defun org-activate-tags (limit)
6226 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6227 (progn
6228 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6229 (add-text-properties (match-beginning 1) (match-end 1)
6230 (list 'mouse-face 'highlight
6231 'keymap org-mouse-map))
6232 (org-rear-nonsticky-at (match-end 1))
6233 t)))
6235 (defun org-outline-level ()
6236 "Compute the outline level of the heading at point.
6238 If this is called at a normal headline, the level is the number
6239 of stars. Use `org-reduced-level' to remove the effect of
6240 `org-odd-levels'. Unlike to `org-current-level', this function
6241 takes into consideration inlinetasks."
6242 (org-with-wide-buffer
6243 (end-of-line)
6244 (if (re-search-backward org-outline-regexp-bol nil t)
6245 (1- (- (match-end 0) (match-beginning 0)))
6246 0)))
6248 (defvar org-font-lock-keywords nil)
6250 (defsubst org-re-property (property &optional literal allow-null value)
6251 "Return a regexp matching a PROPERTY line.
6253 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6254 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6255 non-nil, match properties even without a value.
6257 Match group 3 is set to the value when it exists. If there is no
6258 value and ALLOW-NULL is non-nil, it is set to the empty string.
6260 With optional argument VALUE, match only property lines with
6261 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6262 unless LITERAL is non-nil."
6263 (concat
6264 "^\\(?4:[ \t]*\\)"
6265 (format "\\(?1::\\(?2:%s\\):\\)"
6266 (if literal property (regexp-quote property)))
6267 (cond (value
6268 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6269 (if literal value (regexp-quote value))))
6270 (allow-null
6271 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6273 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6275 (defconst org-property-re
6276 (org-re-property "\\S-+" 'literal t)
6277 "Regular expression matching a property line.
6278 There are four matching groups:
6279 1: :PROPKEY: including the leading and trailing colon,
6280 2: PROPKEY without the leading and trailing colon,
6281 3: PROPVAL without leading or trailing spaces,
6282 4: the indentation of the current line,
6283 5: trailing whitespace.")
6285 (defvar org-font-lock-hook nil
6286 "Functions to be called for special font lock stuff.")
6288 (defvar org-font-lock-set-keywords-hook nil
6289 "Functions that can manipulate `org-font-lock-extra-keywords'.
6290 This is called after `org-font-lock-extra-keywords' is defined, but before
6291 it is installed to be used by font lock. This can be useful if something
6292 needs to be inserted at a specific position in the font-lock sequence.")
6294 (defun org-font-lock-hook (limit)
6295 "Run `org-font-lock-hook' within LIMIT."
6296 (run-hook-with-args 'org-font-lock-hook limit))
6298 (defun org-set-font-lock-defaults ()
6299 "Set font lock defaults for the current buffer."
6300 (let* ((em org-fontify-emphasized-text)
6301 (lk org-highlight-links)
6302 (org-font-lock-extra-keywords
6303 (list
6304 ;; Call the hook
6305 '(org-font-lock-hook)
6306 ;; Headlines
6307 `(,(if org-fontify-whole-heading-line
6308 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6309 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6310 (1 (org-get-level-face 1))
6311 (2 (org-get-level-face 2))
6312 (3 (org-get-level-face 3)))
6313 ;; Table lines
6314 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6315 (1 'org-table t))
6316 ;; Table internals
6317 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6318 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6319 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6320 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6321 ;; Drawers
6322 '(org-fontify-drawers)
6323 ;; Properties
6324 (list org-property-re
6325 '(1 'org-special-keyword t)
6326 '(3 'org-property-value t))
6327 ;; Links
6328 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6329 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6330 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6331 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6332 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6333 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6334 (if (memq 'footnote lk) '(org-activate-footnote-links))
6335 ;; Targets.
6336 (list org-any-target-regexp '(0 'org-target t))
6337 ;; Diary sexps.
6338 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6339 ;; Macro
6340 '(org-fontify-macros)
6341 '(org-hide-wide-columns (0 nil append))
6342 ;; TODO keyword
6343 (list (format org-heading-keyword-regexp-format
6344 org-todo-regexp)
6345 '(2 (org-get-todo-face 2) t))
6346 ;; DONE
6347 (if org-fontify-done-headline
6348 (list (format org-heading-keyword-regexp-format
6349 (concat
6350 "\\(?:"
6351 (mapconcat 'regexp-quote org-done-keywords "\\|")
6352 "\\)"))
6353 '(2 'org-headline-done t))
6354 nil)
6355 ;; Priorities
6356 '(org-font-lock-add-priority-faces)
6357 ;; Tags
6358 '(org-font-lock-add-tag-faces)
6359 ;; Tags groups
6360 (if (and org-group-tags org-tag-groups-alist)
6361 (list (concat org-outline-regexp-bol ".+\\(:"
6362 (regexp-opt (mapcar 'car org-tag-groups-alist))
6363 ":\\).*$")
6364 '(1 'org-tag-group prepend)))
6365 ;; Special keywords
6366 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6367 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6368 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6369 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6370 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6371 ;; Emphasis
6372 (if em
6373 (if (featurep 'xemacs)
6374 '(org-do-emphasis-faces (0 nil append))
6375 '(org-do-emphasis-faces)))
6376 ;; Checkboxes
6377 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6378 1 'org-checkbox prepend)
6379 (if (cdr (assq 'checkbox org-list-automatic-rules))
6380 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6381 (0 (org-get-checkbox-statistics-face) t)))
6382 ;; Description list items
6383 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6384 1 'org-list-dt prepend)
6385 ;; ARCHIVEd headings
6386 (list (concat
6387 org-outline-regexp-bol
6388 "\\(.*:" org-archive-tag ":.*\\)")
6389 '(1 'org-archived prepend))
6390 ;; Specials
6391 '(org-do-latex-and-related)
6392 '(org-fontify-entities)
6393 '(org-raise-scripts)
6394 ;; Code
6395 '(org-activate-code (1 'org-code t))
6396 ;; COMMENT
6397 (list (format
6398 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6399 org-todo-regexp
6400 org-comment-string)
6401 '(9 'org-special-keyword t))
6402 ;; Blocks and meta lines
6403 '(org-fontify-meta-lines-and-blocks))))
6404 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6405 (run-hooks 'org-font-lock-set-keywords-hook)
6406 ;; Now set the full font-lock-keywords
6407 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6408 (org-set-local 'font-lock-defaults
6409 '(org-font-lock-keywords t nil nil backward-paragraph))
6410 (kill-local-variable 'font-lock-keywords) nil))
6412 (defun org-toggle-pretty-entities ()
6413 "Toggle the composition display of entities as UTF8 characters."
6414 (interactive)
6415 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6416 (org-restart-font-lock)
6417 (if org-pretty-entities
6418 (message "Entities are now displayed as UTF8 characters")
6419 (save-restriction
6420 (widen)
6421 (org-decompose-region (point-min) (point-max))
6422 (message "Entities are now displayed as plain text"))))
6424 (defvar org-custom-properties-overlays nil
6425 "List of overlays used for custom properties.")
6426 (make-variable-buffer-local 'org-custom-properties-overlays)
6428 (defun org-toggle-custom-properties-visibility ()
6429 "Display or hide properties in `org-custom-properties'."
6430 (interactive)
6431 (if org-custom-properties-overlays
6432 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6433 (setq org-custom-properties-overlays nil))
6434 (when org-custom-properties
6435 (org-with-wide-buffer
6436 (goto-char (point-min))
6437 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6438 (while (re-search-forward regexp nil t)
6439 (let ((end (cdr (save-match-data (org-get-property-block)))))
6440 (when (and end (< (point) end))
6441 ;; Hide first custom property in current drawer.
6442 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6443 (overlay-put o 'invisible t)
6444 (overlay-put o 'org-custom-property t)
6445 (push o org-custom-properties-overlays))
6446 ;; Hide additional custom properties in the same drawer.
6447 (while (re-search-forward regexp end t)
6448 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6449 (overlay-put o 'invisible t)
6450 (overlay-put o 'org-custom-property t)
6451 (push o org-custom-properties-overlays)))))
6452 ;; Each entry is limited to a single property drawer.
6453 (outline-next-heading)))))))
6455 (defun org-fontify-entities (limit)
6456 "Find an entity to fontify."
6457 (let (ee)
6458 (when org-pretty-entities
6459 (catch 'match
6460 ;; "\_ "-family is left out on purpose. Only the first one,
6461 ;; i.e., "\_ ", could be fontified anyway, and it would be
6462 ;; confusing when adding a second white space character.
6463 (while (re-search-forward
6464 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6465 limit t)
6466 (if (and (not (org-at-comment-p))
6467 (setq ee (org-entity-get (match-string 1)))
6468 (= (length (nth 6 ee)) 1))
6469 (let*
6470 ((end (if (equal (match-string 2) "{}")
6471 (match-end 2)
6472 (match-end 1))))
6473 (add-text-properties
6474 (match-beginning 0) end
6475 (list 'font-lock-fontified t))
6476 (compose-region (match-beginning 0) end
6477 (nth 6 ee) nil)
6478 (backward-char 1)
6479 (throw 'match t))))
6480 nil))))
6482 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6483 "Fontify string S like in Org-mode."
6484 (with-temp-buffer
6485 (insert s)
6486 (let ((org-odd-levels-only odd-levels))
6487 (org-mode)
6488 (font-lock-ensure)
6489 (buffer-string))))
6491 (defvar org-m nil)
6492 (defvar org-l nil)
6493 (defvar org-f nil)
6494 (defun org-get-level-face (n)
6495 "Get the right face for match N in font-lock matching of headlines."
6496 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6497 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6498 (if org-cycle-level-faces
6499 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6500 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6501 (cond
6502 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6503 ((eq n 2) org-f)
6504 (t (if org-level-color-stars-only nil org-f))))
6507 (defun org-get-todo-face (kwd)
6508 "Get the right face for a TODO keyword KWD.
6509 If KWD is a number, get the corresponding match group."
6510 (if (numberp kwd) (setq kwd (match-string kwd)))
6511 (or (org-face-from-face-or-color
6512 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6513 (and (member kwd org-done-keywords) 'org-done)
6514 'org-todo))
6516 (defun org-face-from-face-or-color (context inherit face-or-color)
6517 "Create a face list that inherits INHERIT, but sets the foreground color.
6518 When FACE-OR-COLOR is not a string, just return it."
6519 (if (stringp face-or-color)
6520 (list :inherit inherit
6521 (cdr (assoc context org-faces-easy-properties))
6522 face-or-color)
6523 face-or-color))
6525 (defun org-font-lock-add-tag-faces (limit)
6526 "Add the special tag faces."
6527 (when (and org-tag-faces org-tags-special-faces-re)
6528 (while (re-search-forward org-tags-special-faces-re limit t)
6529 (add-text-properties (match-beginning 1) (match-end 1)
6530 (list 'face (org-get-tag-face 1)
6531 'font-lock-fontified t))
6532 (backward-char 1))))
6534 (defun org-font-lock-add-priority-faces (limit)
6535 "Add the special priority faces."
6536 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6537 (when (save-match-data (org-at-heading-p))
6538 (add-text-properties
6539 (match-beginning 0) (match-end 0)
6540 (list 'face (or (org-face-from-face-or-color
6541 'priority 'org-priority
6542 (cdr (assoc (char-after (match-beginning 1))
6543 org-priority-faces)))
6544 'org-priority)
6545 'font-lock-fontified t)))))
6547 (defun org-get-tag-face (kwd)
6548 "Get the right face for a TODO keyword KWD.
6549 If KWD is a number, get the corresponding match group."
6550 (if (numberp kwd) (setq kwd (match-string kwd)))
6551 (or (org-face-from-face-or-color
6552 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6553 'org-tag))
6555 (defun org-unfontify-region (beg end &optional maybe_loudly)
6556 "Remove fontification and activation overlays from links."
6557 (font-lock-default-unfontify-region beg end)
6558 (let* ((buffer-undo-list t)
6559 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6560 (inhibit-modification-hooks t)
6561 deactivate-mark buffer-file-name buffer-file-truename)
6562 (org-decompose-region beg end)
6563 (remove-text-properties beg end
6564 '(mouse-face t keymap t org-linked-text t
6565 invisible t intangible t
6566 org-emphasis t))
6567 (org-remove-font-lock-display-properties beg end)))
6569 (defconst org-script-display '(((raise -0.3) (height 0.7))
6570 ((raise 0.3) (height 0.7))
6571 ((raise -0.5))
6572 ((raise 0.5)))
6573 "Display properties for showing superscripts and subscripts.")
6575 (defun org-remove-font-lock-display-properties (beg end)
6576 "Remove specific display properties that have been added by font lock.
6577 The will remove the raise properties that are used to show superscripts
6578 and subscripts."
6579 (let (next prop)
6580 (while (< beg end)
6581 (setq next (next-single-property-change beg 'display nil end)
6582 prop (get-text-property beg 'display))
6583 (if (member prop org-script-display)
6584 (put-text-property beg next 'display nil))
6585 (setq beg next))))
6587 (defun org-raise-scripts (limit)
6588 "Add raise properties to sub/superscripts."
6589 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6590 (if (re-search-forward
6591 (if (eq org-use-sub-superscripts t)
6592 org-match-substring-regexp
6593 org-match-substring-with-braces-regexp)
6594 limit t)
6595 (let* ((pos (point)) table-p comment-p
6596 (mpos (match-beginning 3))
6597 (emph-p (get-text-property mpos 'org-emphasis))
6598 (link-p (get-text-property mpos 'mouse-face))
6599 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6600 (goto-char (point-at-bol))
6601 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6602 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6603 (goto-char pos)
6604 ;; Handle a_b^c
6605 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6606 (if (or comment-p emph-p link-p keyw-p)
6608 (put-text-property (match-beginning 3) (match-end 0)
6609 'display
6610 (if (equal (char-after (match-beginning 2)) ?^)
6611 (nth (if table-p 3 1) org-script-display)
6612 (nth (if table-p 2 0) org-script-display)))
6613 (add-text-properties (match-beginning 2) (match-end 2)
6614 (list 'invisible t
6615 'org-dwidth t 'org-dwidth-n 1))
6616 (if (and (eq (char-after (match-beginning 3)) ?{)
6617 (eq (char-before (match-end 3)) ?}))
6618 (progn
6619 (add-text-properties
6620 (match-beginning 3) (1+ (match-beginning 3))
6621 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6622 (add-text-properties
6623 (1- (match-end 3)) (match-end 3)
6624 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6625 t)))))
6627 ;;;; Visibility cycling, including org-goto and indirect buffer
6629 ;;; Cycling
6631 (defvar org-cycle-global-status nil)
6632 (make-variable-buffer-local 'org-cycle-global-status)
6633 (put 'org-cycle-global-status 'org-state t)
6634 (defvar org-cycle-subtree-status nil)
6635 (make-variable-buffer-local 'org-cycle-subtree-status)
6636 (put 'org-cycle-subtree-status 'org-state t)
6638 (defvar org-inlinetask-min-level)
6640 (defun org-unlogged-message (&rest args)
6641 "Display a message, but avoid logging it in the *Messages* buffer."
6642 (let ((message-log-max nil))
6643 (apply 'message args)))
6645 ;;;###autoload
6646 (defun org-cycle (&optional arg)
6647 "TAB-action and visibility cycling for Org-mode.
6649 This is the command invoked in Org-mode by the TAB key. Its main purpose
6650 is outline visibility cycling, but it also invokes other actions
6651 in special contexts.
6653 - When this function is called with a prefix argument, rotate the entire
6654 buffer through 3 states (global cycling)
6655 1. OVERVIEW: Show only top-level headlines.
6656 2. CONTENTS: Show all headlines of all levels, but no body text.
6657 3. SHOW ALL: Show everything.
6658 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6659 determined by the variable `org-startup-folded', and by any VISIBILITY
6660 properties in the buffer.
6661 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6662 including any drawers.
6664 - When inside a table, re-align the table and move to the next field.
6666 - When point is at the beginning of a headline, rotate the subtree started
6667 by this line through 3 different states (local cycling)
6668 1. FOLDED: Only the main headline is shown.
6669 2. CHILDREN: The main headline and the direct children are shown.
6670 From this state, you can move to one of the children
6671 and zoom in further.
6672 3. SUBTREE: Show the entire subtree, including body text.
6673 If there is no subtree, switch directly from CHILDREN to FOLDED.
6675 - When point is at the beginning of an empty headline and the variable
6676 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6677 of the headline by demoting and promoting it to likely levels. This
6678 speeds up creation document structure by pressing TAB once or several
6679 times right after creating a new headline.
6681 - When there is a numeric prefix, go up to a heading with level ARG, do
6682 a `show-subtree' and return to the previous cursor position. If ARG
6683 is negative, go up that many levels.
6685 - When point is not at the beginning of a headline, execute the global
6686 binding for TAB, which is re-indenting the line. See the option
6687 `org-cycle-emulate-tab' for details.
6689 - Special case: if point is at the beginning of the buffer and there is
6690 no headline in line 1, this function will act as if called with prefix arg
6691 (C-u TAB, same as S-TAB) also when called without prefix arg.
6692 But only if also the variable `org-cycle-global-at-bob' is t."
6693 (interactive "P")
6694 (org-load-modules-maybe)
6695 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6696 (and org-cycle-level-after-item/entry-creation
6697 (or (org-cycle-level)
6698 (org-cycle-item-indentation))))
6699 (let* ((limit-level
6700 (or org-cycle-max-level
6701 (and (boundp 'org-inlinetask-min-level)
6702 org-inlinetask-min-level
6703 (1- org-inlinetask-min-level))))
6704 (nstars (and limit-level
6705 (if org-odd-levels-only
6706 (and limit-level (1- (* limit-level 2)))
6707 limit-level)))
6708 (org-outline-regexp
6709 (if (not (derived-mode-p 'org-mode))
6710 outline-regexp
6711 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6712 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6713 (not (looking-at org-outline-regexp))))
6714 (org-cycle-hook
6715 (if bob-special
6716 (delq 'org-optimize-window-after-visibility-change
6717 (copy-sequence org-cycle-hook))
6718 org-cycle-hook))
6719 (pos (point)))
6721 (if (or bob-special (equal arg '(4)))
6722 ;; special case: use global cycling
6723 (setq arg t))
6725 (cond
6727 ((equal arg '(16))
6728 (setq last-command 'dummy)
6729 (org-set-startup-visibility)
6730 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6732 ((equal arg '(64))
6733 (show-all)
6734 (org-unlogged-message "Entire buffer visible, including drawers"))
6736 ;; Try cdlatex TAB completion
6737 ((org-try-cdlatex-tab))
6739 ;; Table: enter it or move to the next field.
6740 ((org-at-table-p 'any)
6741 (if (org-at-table.el-p)
6742 (message "Use C-c ' to edit table.el tables")
6743 (if arg (org-table-edit-field t)
6744 (org-table-justify-field-maybe)
6745 (call-interactively 'org-table-next-field))))
6747 ((run-hook-with-args-until-success
6748 'org-tab-after-check-for-table-hook))
6750 ;; Global cycling: delegate to `org-cycle-internal-global'.
6751 ((eq arg t) (org-cycle-internal-global))
6753 ;; Drawers: delegate to `org-flag-drawer'.
6754 ((save-excursion
6755 (beginning-of-line 1)
6756 (looking-at org-drawer-regexp))
6757 (org-flag-drawer ; toggle block visibility
6758 (not (get-char-property (match-end 0) 'invisible))))
6760 ;; Show-subtree, ARG levels up from here.
6761 ((integerp arg)
6762 (save-excursion
6763 (org-back-to-heading)
6764 (outline-up-heading (if (< arg 0) (- arg)
6765 (- (funcall outline-level) arg)))
6766 (org-show-subtree)))
6768 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6769 ((and (featurep 'org-inlinetask)
6770 (org-inlinetask-at-task-p)
6771 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6772 (org-inlinetask-toggle-visibility))
6774 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6775 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6776 (save-excursion (move-beginning-of-line 1)
6777 (looking-at org-outline-regexp)))
6778 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6779 (org-cycle-internal-local))
6781 ;; From there: TAB emulation and template completion.
6782 (buffer-read-only (org-back-to-heading))
6784 ((run-hook-with-args-until-success
6785 'org-tab-after-check-for-cycling-hook))
6787 ((org-try-structure-completion))
6789 ((run-hook-with-args-until-success
6790 'org-tab-before-tab-emulation-hook))
6792 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6793 (or (not (bolp))
6794 (not (looking-at org-outline-regexp))))
6795 (call-interactively (global-key-binding "\t")))
6797 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6798 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6799 (or (and (eq org-cycle-emulate-tab 'white)
6800 (= (match-end 0) (point-at-eol)))
6801 (and (eq org-cycle-emulate-tab 'whitestart)
6802 (>= (match-end 0) pos))))
6804 (eq org-cycle-emulate-tab t))
6805 (call-interactively (global-key-binding "\t")))
6807 (t (save-excursion
6808 (org-back-to-heading)
6809 (org-cycle)))))))
6811 (defun org-cycle-internal-global ()
6812 "Do the global cycling action."
6813 ;; Hack to avoid display of messages for .org attachments in Gnus
6814 (let ((ga (string-match "\\*fontification" (buffer-name))))
6815 (cond
6816 ((and (eq last-command this-command)
6817 (eq org-cycle-global-status 'overview))
6818 ;; We just created the overview - now do table of contents
6819 ;; This can be slow in very large buffers, so indicate action
6820 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6821 (unless ga (org-unlogged-message "CONTENTS..."))
6822 (org-content)
6823 (unless ga (org-unlogged-message "CONTENTS...done"))
6824 (setq org-cycle-global-status 'contents)
6825 (run-hook-with-args 'org-cycle-hook 'contents))
6827 ((and (eq last-command this-command)
6828 (eq org-cycle-global-status 'contents))
6829 ;; We just showed the table of contents - now show everything
6830 (run-hook-with-args 'org-pre-cycle-hook 'all)
6831 (show-all)
6832 (unless ga (org-unlogged-message "SHOW ALL"))
6833 (setq org-cycle-global-status 'all)
6834 (run-hook-with-args 'org-cycle-hook 'all))
6837 ;; Default action: go to overview
6838 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6839 (org-overview)
6840 (unless ga (org-unlogged-message "OVERVIEW"))
6841 (setq org-cycle-global-status 'overview)
6842 (run-hook-with-args 'org-cycle-hook 'overview)))))
6844 (defvar org-called-with-limited-levels nil
6845 "Non-nil when `org-with-limited-levels' is currently active.")
6847 (defun org-cycle-internal-local ()
6848 "Do the local cycling action."
6849 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6850 ;; First, determine end of headline (EOH), end of subtree or item
6851 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6852 (save-excursion
6853 (if (org-at-item-p)
6854 (progn
6855 (beginning-of-line)
6856 (setq struct (org-list-struct))
6857 (setq eoh (point-at-eol))
6858 (setq eos (org-list-get-item-end-before-blank (point) struct))
6859 (setq has-children (org-list-has-child-p (point) struct)))
6860 (org-back-to-heading)
6861 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6862 (setq eos (save-excursion (org-end-of-subtree t t)
6863 (when (bolp) (backward-char)) (point)))
6864 (setq has-children
6865 (or (save-excursion
6866 (let ((level (funcall outline-level)))
6867 (outline-next-heading)
6868 (and (org-at-heading-p t)
6869 (> (funcall outline-level) level))))
6870 (save-excursion
6871 (org-list-search-forward (org-item-beginning-re) eos t)))))
6872 ;; Determine end invisible part of buffer (EOL)
6873 (beginning-of-line 2)
6874 ;; XEmacs doesn't have `next-single-char-property-change'
6875 (if (featurep 'xemacs)
6876 (while (and (not (eobp)) ;; this is like `next-line'
6877 (get-char-property (1- (point)) 'invisible))
6878 (beginning-of-line 2))
6879 (while (and (not (eobp)) ;; this is like `next-line'
6880 (get-char-property (1- (point)) 'invisible))
6881 (goto-char (next-single-char-property-change (point) 'invisible))
6882 (and (eolp) (beginning-of-line 2))))
6883 (setq eol (point)))
6884 ;; Find out what to do next and set `this-command'
6885 (cond
6886 ((= eos eoh)
6887 ;; Nothing is hidden behind this heading
6888 (unless (org-before-first-heading-p)
6889 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6890 (org-unlogged-message "EMPTY ENTRY")
6891 (setq org-cycle-subtree-status nil)
6892 (save-excursion
6893 (goto-char eos)
6894 (outline-next-heading)
6895 (if (outline-invisible-p) (org-flag-heading nil))))
6896 ((and (or (>= eol eos)
6897 (not (string-match "\\S-" (buffer-substring eol eos))))
6898 (or has-children
6899 (not (setq children-skipped
6900 org-cycle-skip-children-state-if-no-children))))
6901 ;; Entire subtree is hidden in one line: children view
6902 (unless (org-before-first-heading-p)
6903 (run-hook-with-args 'org-pre-cycle-hook 'children))
6904 (if (org-at-item-p)
6905 (org-list-set-item-visibility (point-at-bol) struct 'children)
6906 (org-show-entry)
6907 (org-with-limited-levels (show-children))
6908 ;; FIXME: This slows down the func way too much.
6909 ;; How keep drawers hidden in subtree anyway?
6910 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6911 ;; (org-cycle-hide-drawers 'subtree))
6913 ;; Fold every list in subtree to top-level items.
6914 (when (eq org-cycle-include-plain-lists 'integrate)
6915 (save-excursion
6916 (org-back-to-heading)
6917 (while (org-list-search-forward (org-item-beginning-re) eos t)
6918 (beginning-of-line 1)
6919 (let* ((struct (org-list-struct))
6920 (prevs (org-list-prevs-alist struct))
6921 (end (org-list-get-bottom-point struct)))
6922 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6923 (org-list-get-all-items (point) struct prevs))
6924 (goto-char (if (< end eos) end eos)))))))
6925 (org-unlogged-message "CHILDREN")
6926 (save-excursion
6927 (goto-char eos)
6928 (outline-next-heading)
6929 (if (outline-invisible-p) (org-flag-heading nil)))
6930 (setq org-cycle-subtree-status 'children)
6931 (unless (org-before-first-heading-p)
6932 (run-hook-with-args 'org-cycle-hook 'children)))
6933 ((or children-skipped
6934 (and (eq last-command this-command)
6935 (eq org-cycle-subtree-status 'children)))
6936 ;; We just showed the children, or no children are there,
6937 ;; now show everything.
6938 (unless (org-before-first-heading-p)
6939 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6940 (outline-flag-region eoh eos nil)
6941 (org-unlogged-message
6942 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6943 (setq org-cycle-subtree-status 'subtree)
6944 (unless (org-before-first-heading-p)
6945 (run-hook-with-args 'org-cycle-hook 'subtree)))
6947 ;; Default action: hide the subtree.
6948 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6949 (outline-flag-region eoh eos t)
6950 (org-unlogged-message "FOLDED")
6951 (setq org-cycle-subtree-status 'folded)
6952 (unless (org-before-first-heading-p)
6953 (run-hook-with-args 'org-cycle-hook 'folded))))))
6955 ;;;###autoload
6956 (defun org-global-cycle (&optional arg)
6957 "Cycle the global visibility. For details see `org-cycle'.
6958 With \\[universal-argument] prefix arg, switch to startup visibility.
6959 With a numeric prefix, show all headlines up to that level."
6960 (interactive "P")
6961 (let ((org-cycle-include-plain-lists
6962 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6963 (cond
6964 ((integerp arg)
6965 (show-all)
6966 (hide-sublevels arg)
6967 (setq org-cycle-global-status 'contents))
6968 ((equal arg '(4))
6969 (org-set-startup-visibility)
6970 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6972 (org-cycle '(4))))))
6974 (defun org-set-startup-visibility ()
6975 "Set the visibility required by startup options and properties."
6976 (cond
6977 ((eq org-startup-folded t)
6978 (org-overview))
6979 ((eq org-startup-folded 'content)
6980 (org-content))
6981 ((or (eq org-startup-folded 'showeverything)
6982 (eq org-startup-folded nil))
6983 (show-all)))
6984 (unless (eq org-startup-folded 'showeverything)
6985 (if org-hide-block-startup (org-hide-block-all))
6986 (org-set-visibility-according-to-property 'no-cleanup)
6987 (org-cycle-hide-archived-subtrees 'all)
6988 (org-cycle-hide-drawers 'all)
6989 (org-cycle-show-empty-lines t)))
6991 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6992 "Switch subtree visibilities according to :VISIBILITY: property."
6993 (interactive)
6994 (let (org-show-entry-below)
6995 (org-with-wide-buffer
6996 (goto-char (point-min))
6997 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6998 (if (not (org-at-property-p)) (outline-next-heading)
6999 (let ((state (match-string 3)))
7000 (save-excursion
7001 (org-back-to-heading t)
7002 (hide-subtree)
7003 (org-reveal)
7004 (cond
7005 ((equal state "folded")
7006 (hide-subtree))
7007 ((equal state "children")
7008 (org-show-hidden-entry)
7009 (show-children))
7010 ((equal state "content")
7011 (save-excursion
7012 (save-restriction
7013 (org-narrow-to-subtree)
7014 (org-content))))
7015 ((member state '("all" "showall"))
7016 (show-subtree)))))))
7017 (unless no-cleanup
7018 (org-cycle-hide-archived-subtrees 'all)
7019 (org-cycle-hide-drawers 'all)
7020 (org-cycle-show-empty-lines 'all)))))
7022 ;; This function uses outline-regexp instead of the more fundamental
7023 ;; org-outline-regexp so that org-cycle-global works outside of Org
7024 ;; buffers, where outline-regexp is needed.
7025 (defun org-overview ()
7026 "Switch to overview mode, showing only top-level headlines.
7027 This shows all headlines with a level equal or greater than the level
7028 of the first headline in the buffer. This is important, because if the
7029 first headline is not level one, then (hide-sublevels 1) gives confusing
7030 results."
7031 (interactive)
7032 (save-excursion
7033 (let ((level
7034 (save-excursion
7035 (goto-char (point-min))
7036 (if (re-search-forward (concat "^" outline-regexp) nil t)
7037 (progn
7038 (goto-char (match-beginning 0))
7039 (funcall outline-level))))))
7040 (and level (hide-sublevels level)))))
7042 (defun org-content (&optional arg)
7043 "Show all headlines in the buffer, like a table of contents.
7044 With numerical argument N, show content up to level N."
7045 (interactive "P")
7046 (org-overview)
7047 (save-excursion
7048 ;; Visit all headings and show their offspring
7049 (and (integerp arg) (org-overview))
7050 (goto-char (point-max))
7051 (catch 'exit
7052 (while (and (progn (condition-case nil
7053 (outline-previous-visible-heading 1)
7054 (error (goto-char (point-min))))
7056 (looking-at org-outline-regexp))
7057 (if (integerp arg)
7058 (show-children (1- arg))
7059 (show-branches))
7060 (if (bobp) (throw 'exit nil))))))
7062 (defun org-optimize-window-after-visibility-change (state)
7063 "Adjust the window after a change in outline visibility.
7064 This function is the default value of the hook `org-cycle-hook'."
7065 (when (get-buffer-window (current-buffer))
7066 (cond
7067 ((eq state 'content) nil)
7068 ((eq state 'all) nil)
7069 ((eq state 'folded) nil)
7070 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7071 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7073 (defun org-remove-empty-overlays-at (pos)
7074 "Remove outline overlays that do not contain non-white stuff."
7075 (mapc
7076 (lambda (o)
7077 (and (eq 'outline (overlay-get o 'invisible))
7078 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7079 (overlay-end o))))
7080 (delete-overlay o)))
7081 (overlays-at pos)))
7083 (defun org-clean-visibility-after-subtree-move ()
7084 "Fix visibility issues after moving a subtree."
7085 ;; First, find a reasonable region to look at:
7086 ;; Start two siblings above, end three below
7087 (let* ((beg (save-excursion
7088 (and (org-get-last-sibling)
7089 (org-get-last-sibling))
7090 (point)))
7091 (end (save-excursion
7092 (and (org-get-next-sibling)
7093 (org-get-next-sibling)
7094 (org-get-next-sibling))
7095 (if (org-at-heading-p)
7096 (point-at-eol)
7097 (point))))
7098 (level (looking-at "\\*+"))
7099 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7100 (save-excursion
7101 (save-restriction
7102 (narrow-to-region beg end)
7103 (when re
7104 ;; Properly fold already folded siblings
7105 (goto-char (point-min))
7106 (while (re-search-forward re nil t)
7107 (if (and (not (outline-invisible-p))
7108 (save-excursion
7109 (goto-char (point-at-eol)) (outline-invisible-p)))
7110 (hide-entry))))
7111 (org-cycle-show-empty-lines 'overview)
7112 (org-cycle-hide-drawers 'overview)))))
7114 (defun org-cycle-show-empty-lines (state)
7115 "Show empty lines above all visible headlines.
7116 The region to be covered depends on STATE when called through
7117 `org-cycle-hook'. Lisp program can use t for STATE to get the
7118 entire buffer covered. Note that an empty line is only shown if there
7119 are at least `org-cycle-separator-lines' empty lines before the headline."
7120 (when (/= org-cycle-separator-lines 0)
7121 (save-excursion
7122 (let* ((n (abs org-cycle-separator-lines))
7123 (re (cond
7124 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7125 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7126 (t (let ((ns (number-to-string (- n 2))))
7127 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7128 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7129 beg end)
7130 (cond
7131 ((memq state '(overview contents t))
7132 (setq beg (point-min) end (point-max)))
7133 ((memq state '(children folded))
7134 (setq beg (point)
7135 end (progn (org-end-of-subtree t t)
7136 (line-beginning-position 2)))))
7137 (when beg
7138 (goto-char beg)
7139 (while (re-search-forward re end t)
7140 (unless (get-char-property (match-end 1) 'invisible)
7141 (let ((e (match-end 1))
7142 (b (if (>= org-cycle-separator-lines 0)
7143 (match-beginning 1)
7144 (save-excursion
7145 (goto-char (match-beginning 0))
7146 (skip-chars-backward " \t\n")
7147 (line-end-position)))))
7148 (outline-flag-region b e nil))))))))
7149 ;; Never hide empty lines at the end of the file.
7150 (save-excursion
7151 (goto-char (point-max))
7152 (outline-previous-heading)
7153 (outline-end-of-heading)
7154 (if (and (looking-at "[ \t\n]+")
7155 (= (match-end 0) (point-max)))
7156 (outline-flag-region (point) (match-end 0) nil))))
7158 (defun org-show-empty-lines-in-parent ()
7159 "Move to the parent and re-show empty lines before visible headlines."
7160 (save-excursion
7161 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7162 (org-cycle-show-empty-lines context))))
7164 (defun org-files-list ()
7165 "Return `org-agenda-files' list, plus all open org-mode files.
7166 This is useful for operations that need to scan all of a user's
7167 open and agenda-wise Org files."
7168 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7169 (dolist (buf (buffer-list))
7170 (with-current-buffer buf
7171 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7172 (let ((file (expand-file-name (buffer-file-name))))
7173 (unless (member file files)
7174 (push file files))))))
7175 files))
7177 (defsubst org-entry-beginning-position ()
7178 "Return the beginning position of the current entry."
7179 (save-excursion (outline-back-to-heading t) (point)))
7181 (defsubst org-entry-end-position ()
7182 "Return the end position of the current entry."
7183 (save-excursion (outline-next-heading) (point)))
7185 (defun org-cycle-hide-drawers (state &optional exceptions)
7186 "Re-hide all drawers after a visibility state change.
7187 When non-nil, optional argument EXCEPTIONS is a list of strings
7188 specifying which drawers should not be hidden."
7189 (when (and (derived-mode-p 'org-mode)
7190 (not (memq state '(overview folded contents))))
7191 (save-excursion
7192 (let* ((globalp (memq state '(contents all)))
7193 (beg (if globalp (point-min) (point)))
7194 (end (if globalp (point-max)
7195 (if (eq state 'children)
7196 (save-excursion (outline-next-heading) (point))
7197 (org-end-of-subtree t)))))
7198 (goto-char beg)
7199 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7200 (unless (member-ignore-case (match-string 1) exceptions)
7201 (let ((drawer (org-element-at-point)))
7202 (when (memq (org-element-type drawer) '(drawer property-drawer))
7203 (org-flag-drawer t drawer)
7204 ;; Make sure to skip drawer entirely or we might flag
7205 ;; it another time when matching its ending line with
7206 ;; `org-drawer-regexp'.
7207 (goto-char (org-element-property :end drawer))))))))))
7209 (defun org-flag-drawer (flag &optional element)
7210 "When FLAG is non-nil, hide the drawer we are at.
7211 Otherwise make it visible. When optional argument ELEMENT is
7212 a parsed drawer, as returned by `org-element-at-point', hide or
7213 show that drawer instead."
7214 (when (save-excursion
7215 (beginning-of-line)
7216 (org-looking-at-p org-drawer-regexp))
7217 (let ((drawer (or element (org-element-at-point))))
7218 (when (memq (org-element-type drawer) '(drawer property-drawer))
7219 (let ((post (org-element-property :post-affiliated drawer)))
7220 (save-excursion
7221 (outline-flag-region
7222 (progn (goto-char post) (line-end-position))
7223 (progn (goto-char (org-element-property :end drawer))
7224 (skip-chars-backward " \r\t\n")
7225 (line-end-position))
7226 flag))
7227 ;; When the drawer is hidden away, make sure point lies in
7228 ;; a visible part of the buffer.
7229 (when (and flag (> (line-beginning-position) post))
7230 (goto-char post)))))))
7232 (defun org-subtree-end-visible-p ()
7233 "Is the end of the current subtree visible?"
7234 (pos-visible-in-window-p
7235 (save-excursion (org-end-of-subtree t) (point))))
7237 (defun org-first-headline-recenter ()
7238 "Move cursor to the first headline and recenter the headline."
7239 (goto-char (point-min))
7240 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7241 (set-window-start (selected-window) (point-at-bol))))
7243 ;;; Saving and restoring visibility
7245 (defun org-outline-overlay-data (&optional use-markers)
7246 "Return a list of the locations of all outline overlays.
7247 These are overlays with the `invisible' property value `outline'.
7248 The return value is a list of cons cells, with start and stop
7249 positions for each overlay.
7250 If USE-MARKERS is set, return the positions as markers."
7251 (let (beg end)
7252 (save-excursion
7253 (save-restriction
7254 (widen)
7255 (delq nil
7256 (mapcar (lambda (o)
7257 (when (eq (overlay-get o 'invisible) 'outline)
7258 (setq beg (overlay-start o)
7259 end (overlay-end o))
7260 (and beg end (> end beg)
7261 (if use-markers
7262 (cons (copy-marker beg)
7263 (copy-marker end t))
7264 (cons beg end)))))
7265 (overlays-in (point-min) (point-max))))))))
7267 (defun org-set-outline-overlay-data (data)
7268 "Create visibility overlays for all positions in DATA.
7269 DATA should have been made by `org-outline-overlay-data'."
7270 (let (o)
7271 (save-excursion
7272 (save-restriction
7273 (widen)
7274 (show-all)
7275 (mapc (lambda (c)
7276 (outline-flag-region (car c) (cdr c) t))
7277 data)))))
7279 ;;; Folding of blocks
7281 (defvar org-hide-block-overlays nil
7282 "Overlays hiding blocks.")
7283 (make-variable-buffer-local 'org-hide-block-overlays)
7285 (defun org-block-map (function &optional start end)
7286 "Call FUNCTION at the head of all source blocks in the current buffer.
7287 Optional arguments START and END can be used to limit the range."
7288 (let ((start (or start (point-min)))
7289 (end (or end (point-max))))
7290 (save-excursion
7291 (goto-char start)
7292 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7293 (save-excursion
7294 (save-match-data
7295 (goto-char (match-beginning 0))
7296 (funcall function)))))))
7298 (defun org-hide-block-toggle-all ()
7299 "Toggle the visibility of all blocks in the current buffer."
7300 (org-block-map 'org-hide-block-toggle))
7302 (defun org-hide-block-all ()
7303 "Fold all blocks in the current buffer."
7304 (interactive)
7305 (org-show-block-all)
7306 (org-block-map 'org-hide-block-toggle-maybe))
7308 (defun org-show-block-all ()
7309 "Unfold all blocks in the current buffer."
7310 (interactive)
7311 (mapc 'delete-overlay org-hide-block-overlays)
7312 (setq org-hide-block-overlays nil))
7314 (defun org-hide-block-toggle-maybe ()
7315 "Toggle visibility of block at point.
7316 Unlike to `org-hide-block-toggle', this function does not throw
7317 an error. Return a non-nil value when toggling is successful."
7318 (interactive)
7319 (ignore-errors (org-hide-block-toggle)))
7321 (defun org-hide-block-toggle (&optional force)
7322 "Toggle the visibility of the current block.
7323 When optional argument FORCE is `off', make block visible. If it
7324 is non-nil, hide it unconditionally. Throw an error when not at
7325 a block. Return a non-nil value when toggling is successful."
7326 (interactive)
7327 (let ((element (org-element-at-point)))
7328 (unless (memq (org-element-type element)
7329 '(center-block comment-block dynamic-block example-block
7330 export-block quote-block special-block
7331 src-block verse-block))
7332 (user-error "Not at a block"))
7333 (let* ((start (save-excursion
7334 (goto-char (org-element-property :post-affiliated element))
7335 (line-end-position)))
7336 (end (save-excursion
7337 (goto-char (org-element-property :end element))
7338 (skip-chars-backward " \r\t\n")
7339 (line-end-position)))
7340 (overlays (overlays-at start)))
7341 (cond
7342 ;; Do nothing when not before or at the block opening line or
7343 ;; at the block closing line.
7344 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7345 ((and (not (eq force 'off))
7346 (not (memq t (mapcar
7347 (lambda (o)
7348 (eq (overlay-get o 'invisible) 'org-hide-block))
7349 overlays))))
7350 (let ((ov (make-overlay start end)))
7351 (overlay-put ov 'invisible 'org-hide-block)
7352 ;; Make the block accessible to `isearch'.
7353 (overlay-put
7354 ov 'isearch-open-invisible
7355 (lambda (ov)
7356 (when (memq ov org-hide-block-overlays)
7357 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7358 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7359 (delete-overlay ov))))
7360 (push ov org-hide-block-overlays)
7361 ;; When the block is hidden away, make sure point is left in
7362 ;; a visible part of the buffer.
7363 (when (> (line-beginning-position) start)
7364 (goto-char start)
7365 (beginning-of-line))
7366 ;; Signal successful toggling.
7368 ((or (not force) (eq force 'off))
7369 (dolist (ov overlays t)
7370 (when (memq ov org-hide-block-overlays)
7371 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7372 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7373 (delete-overlay ov))))))))
7375 ;; org-tab-after-check-for-cycling-hook
7376 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7377 ;; Remove overlays when changing major mode
7378 (add-hook 'org-mode-hook
7379 (lambda () (org-add-hook 'change-major-mode-hook
7380 'org-show-block-all 'append 'local)))
7382 ;;; Org-goto
7384 (defvar org-goto-window-configuration nil)
7385 (defvar org-goto-marker nil)
7386 (defvar org-goto-map)
7387 (defun org-goto-map ()
7388 "Set the keymap `org-goto'."
7389 (setq org-goto-map
7390 (let ((map (make-sparse-keymap)))
7391 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7392 mouse-drag-region universal-argument org-occur))
7393 cmd)
7394 (while (setq cmd (pop cmds))
7395 (substitute-key-definition cmd cmd map global-map)))
7396 (suppress-keymap map)
7397 (org-defkey map "\C-m" 'org-goto-ret)
7398 (org-defkey map [(return)] 'org-goto-ret)
7399 (org-defkey map [(left)] 'org-goto-left)
7400 (org-defkey map [(right)] 'org-goto-right)
7401 (org-defkey map [(control ?g)] 'org-goto-quit)
7402 (org-defkey map "\C-i" 'org-cycle)
7403 (org-defkey map [(tab)] 'org-cycle)
7404 (org-defkey map [(down)] 'outline-next-visible-heading)
7405 (org-defkey map [(up)] 'outline-previous-visible-heading)
7406 (if org-goto-auto-isearch
7407 (if (fboundp 'define-key-after)
7408 (define-key-after map [t] 'org-goto-local-auto-isearch)
7409 nil)
7410 (org-defkey map "q" 'org-goto-quit)
7411 (org-defkey map "n" 'outline-next-visible-heading)
7412 (org-defkey map "p" 'outline-previous-visible-heading)
7413 (org-defkey map "f" 'outline-forward-same-level)
7414 (org-defkey map "b" 'outline-backward-same-level)
7415 (org-defkey map "u" 'outline-up-heading))
7416 (org-defkey map "/" 'org-occur)
7417 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7418 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7419 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7420 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7421 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7422 map)))
7424 (defconst org-goto-help
7425 "Browse buffer copy, to find location or copy text.%s
7426 RET=jump to location C-g=quit and return to previous location
7427 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7429 (defvar org-goto-start-pos) ; dynamically scoped parameter
7431 (defun org-goto (&optional alternative-interface)
7432 "Look up a different location in the current file, keeping current visibility.
7434 When you want look-up or go to a different location in a
7435 document, the fastest way is often to fold the entire buffer and
7436 then dive into the tree. This method has the disadvantage, that
7437 the previous location will be folded, which may not be what you
7438 want.
7440 This command works around this by showing a copy of the current
7441 buffer in an indirect buffer, in overview mode. You can dive
7442 into the tree in that copy, use org-occur and incremental search
7443 to find a location. When pressing RET or `Q', the command
7444 returns to the original buffer in which the visibility is still
7445 unchanged. After RET it will also jump to the location selected
7446 in the indirect buffer and expose the headline hierarchy above.
7448 With a prefix argument, use the alternative interface: e.g. if
7449 `org-goto-interface' is 'outline use 'outline-path-completion."
7450 (interactive "P")
7451 (org-goto-map)
7452 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7453 (org-refile-use-outline-path t)
7454 (org-refile-target-verify-function nil)
7455 (interface
7456 (if (not alternative-interface)
7457 org-goto-interface
7458 (if (eq org-goto-interface 'outline)
7459 'outline-path-completion
7460 'outline)))
7461 (org-goto-start-pos (point))
7462 (selected-point
7463 (if (eq interface 'outline)
7464 (car (org-get-location (current-buffer) org-goto-help))
7465 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7466 (org-refile-check-position pa)
7467 (nth 3 pa)))))
7468 (if selected-point
7469 (progn
7470 (org-mark-ring-push org-goto-start-pos)
7471 (goto-char selected-point)
7472 (if (or (outline-invisible-p) (org-invisible-p2))
7473 (org-show-context 'org-goto)))
7474 (message "Quit"))))
7476 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7477 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7478 (defvar org-goto-local-auto-isearch-map) ; defined below
7480 (defun org-get-location (buf help)
7481 "Let the user select a location in the Org-mode buffer BUF.
7482 This function uses a recursive edit. It returns the selected position
7483 or nil."
7484 (org-no-popups
7485 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7486 (isearch-hide-immediately nil)
7487 (isearch-search-fun-function
7488 (lambda () 'org-goto-local-search-headings))
7489 (org-goto-selected-point org-goto-exit-command))
7490 (save-excursion
7491 (save-window-excursion
7492 (delete-other-windows)
7493 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7494 (org-pop-to-buffer-same-window
7495 (condition-case nil
7496 (make-indirect-buffer (current-buffer) "*org-goto*")
7497 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7498 (with-output-to-temp-buffer "*Org Help*"
7499 (princ (format help (if org-goto-auto-isearch
7500 " Just type for auto-isearch."
7501 " n/p/f/b/u to navigate, q to quit."))))
7502 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7503 (setq buffer-read-only nil)
7504 (let ((org-startup-truncated t)
7505 (org-startup-folded nil)
7506 (org-startup-align-all-tables nil))
7507 (org-mode)
7508 (org-overview))
7509 (setq buffer-read-only t)
7510 (if (and (boundp 'org-goto-start-pos)
7511 (integer-or-marker-p org-goto-start-pos))
7512 (progn (goto-char org-goto-start-pos)
7513 (when (outline-invisible-p)
7514 (org-show-set-visibility 'lineage)))
7515 (goto-char (point-min)))
7516 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7517 (message "Select location and press RET")
7518 (use-local-map org-goto-map)
7519 (recursive-edit)))
7520 (kill-buffer "*org-goto*")
7521 (cons org-goto-selected-point org-goto-exit-command))))
7523 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7524 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7525 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7526 (if (fboundp 'isearch-other-control-char)
7527 (progn
7528 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7529 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7530 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7531 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7532 (define-key org-goto-local-auto-isearch-map [return] nil))
7534 (defun org-goto-local-search-headings (string bound noerror)
7535 "Search and make sure that any matches are in headlines."
7536 (catch 'return
7537 (while (if isearch-forward
7538 (search-forward string bound noerror)
7539 (search-backward string bound noerror))
7540 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7541 (and (member :headline context)
7542 (not (member :tags context))))
7543 (throw 'return (point))))))
7545 (defun org-goto-local-auto-isearch ()
7546 "Start isearch."
7547 (interactive)
7548 (goto-char (point-min))
7549 (let ((keys (this-command-keys)))
7550 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7551 (isearch-mode t)
7552 (isearch-process-search-char (string-to-char keys)))))
7554 (defun org-goto-ret (&optional arg)
7555 "Finish `org-goto' by going to the new location."
7556 (interactive "P")
7557 (setq org-goto-selected-point (point)
7558 org-goto-exit-command 'return)
7559 (throw 'exit nil))
7561 (defun org-goto-left ()
7562 "Finish `org-goto' by going to the new location."
7563 (interactive)
7564 (if (org-at-heading-p)
7565 (progn
7566 (beginning-of-line 1)
7567 (setq org-goto-selected-point (point)
7568 org-goto-exit-command 'left)
7569 (throw 'exit nil))
7570 (user-error "Not on a heading")))
7572 (defun org-goto-right ()
7573 "Finish `org-goto' by going to the new location."
7574 (interactive)
7575 (if (org-at-heading-p)
7576 (progn
7577 (setq org-goto-selected-point (point)
7578 org-goto-exit-command 'right)
7579 (throw 'exit nil))
7580 (user-error "Not on a heading")))
7582 (defun org-goto-quit ()
7583 "Finish `org-goto' without cursor motion."
7584 (interactive)
7585 (setq org-goto-selected-point nil)
7586 (setq org-goto-exit-command 'quit)
7587 (throw 'exit nil))
7589 ;;; Indirect buffer display of subtrees
7591 (defvar org-indirect-dedicated-frame nil
7592 "This is the frame being used for indirect tree display.")
7593 (defvar org-last-indirect-buffer nil)
7595 (defun org-tree-to-indirect-buffer (&optional arg)
7596 "Create indirect buffer and narrow it to current subtree.
7597 With a numerical prefix ARG, go up to this level and then take that tree.
7598 If ARG is negative, go up that many levels.
7600 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7601 indirect buffer previously made with this command, to avoid proliferation of
7602 indirect buffers. However, when you call the command with a \
7603 \\[universal-argument] prefix, or
7604 when `org-indirect-buffer-display' is `new-frame', the last buffer
7605 is kept so that you can work with several indirect buffers at the same time.
7606 If `org-indirect-buffer-display' is `dedicated-frame', the \
7607 \\[universal-argument] prefix also
7608 requests that a new frame be made for the new buffer, so that the dedicated
7609 frame is not changed."
7610 (interactive "P")
7611 (let ((cbuf (current-buffer))
7612 (cwin (selected-window))
7613 (pos (point))
7614 beg end level heading ibuf)
7615 (save-excursion
7616 (org-back-to-heading t)
7617 (when (numberp arg)
7618 (setq level (org-outline-level))
7619 (if (< arg 0) (setq arg (+ level arg)))
7620 (while (> (setq level (org-outline-level)) arg)
7621 (org-up-heading-safe)))
7622 (setq beg (point)
7623 heading (org-get-heading))
7624 (org-end-of-subtree t t)
7625 (if (org-at-heading-p) (backward-char 1))
7626 (setq end (point)))
7627 (if (and (buffer-live-p org-last-indirect-buffer)
7628 (not (eq org-indirect-buffer-display 'new-frame))
7629 (not arg))
7630 (kill-buffer org-last-indirect-buffer))
7631 (setq ibuf (org-get-indirect-buffer cbuf heading)
7632 org-last-indirect-buffer ibuf)
7633 (cond
7634 ((or (eq org-indirect-buffer-display 'new-frame)
7635 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7636 (select-frame (make-frame))
7637 (delete-other-windows)
7638 (org-pop-to-buffer-same-window ibuf)
7639 (org-set-frame-title heading))
7640 ((eq org-indirect-buffer-display 'dedicated-frame)
7641 (raise-frame
7642 (select-frame (or (and org-indirect-dedicated-frame
7643 (frame-live-p org-indirect-dedicated-frame)
7644 org-indirect-dedicated-frame)
7645 (setq org-indirect-dedicated-frame (make-frame)))))
7646 (delete-other-windows)
7647 (org-pop-to-buffer-same-window ibuf)
7648 (org-set-frame-title (concat "Indirect: " heading)))
7649 ((eq org-indirect-buffer-display 'current-window)
7650 (org-pop-to-buffer-same-window ibuf))
7651 ((eq org-indirect-buffer-display 'other-window)
7652 (pop-to-buffer ibuf))
7653 (t (error "Invalid value")))
7654 (if (featurep 'xemacs)
7655 (save-excursion (org-mode) (turn-on-font-lock)))
7656 (narrow-to-region beg end)
7657 (show-all)
7658 (goto-char pos)
7659 (run-hook-with-args 'org-cycle-hook 'all)
7660 (and (window-live-p cwin) (select-window cwin))))
7662 (defun org-get-indirect-buffer (&optional buffer heading)
7663 (setq buffer (or buffer (current-buffer)))
7664 (let ((n 1) (base (buffer-name buffer)) bname)
7665 (while (buffer-live-p
7666 (get-buffer
7667 (setq bname
7668 (concat base "-"
7669 (if heading (concat heading "-" (number-to-string n))
7670 (number-to-string n))))))
7671 (setq n (1+ n)))
7672 (condition-case nil
7673 (make-indirect-buffer buffer bname 'clone)
7674 (error (make-indirect-buffer buffer bname)))))
7676 (defun org-set-frame-title (title)
7677 "Set the title of the current frame to the string TITLE."
7678 ;; FIXME: how to name a single frame in XEmacs???
7679 (unless (featurep 'xemacs)
7680 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7682 ;;;; Structure editing
7684 ;;; Inserting headlines
7686 (defun org-previous-line-empty-p (&optional next)
7687 "Is the previous line a blank line?
7688 When NEXT is non-nil, check the next line instead."
7689 (save-excursion
7690 (and (not (bobp))
7691 (or (beginning-of-line (if next 2 0)) t)
7692 (save-match-data
7693 (looking-at "[ \t]*$")))))
7695 (defun org-insert-heading (&optional arg invisible-ok top-level)
7696 "Insert a new heading or an item with the same depth at point.
7698 If point is at the beginning of a heading or a list item, insert
7699 a new heading or a new item above the current one. If point is
7700 at the beginning of a normal line, turn the line into a heading.
7702 If point is in the middle of a headline or a list item, split the
7703 headline or the item and create a new headline/item with the text
7704 in the current line after point \(see `org-M-RET-may-split-line'
7705 on how to modify this behavior).
7707 With one universal prefix argument, set the user option
7708 `org-insert-heading-respect-content' to t for the duration of
7709 the command. This modifies the behavior described above in this
7710 ways: on list items and at the beginning of normal lines, force
7711 the insertion of a heading after the current subtree.
7713 With two universal prefix arguments, insert the heading at the
7714 end of the grandparent subtree. For example, if point is within
7715 a 2nd-level heading, then it will insert a 2nd-level heading at
7716 the end of the 1st-level parent heading.
7718 If point is at the beginning of a headline, insert a sibling
7719 before the current headline. If point is not at the beginning,
7720 split the line and create a new headline with the text in the
7721 current line after point \(see `org-M-RET-may-split-line' on how
7722 to modify this behavior).
7724 If point is at the beginning of a normal line, turn this line
7725 into a heading.
7727 When INVISIBLE-OK is set, stop at invisible headlines when going
7728 back. This is important for non-interactive uses of the
7729 command.
7731 When optional argument TOP-LEVEL is non-nil, insert a level 1
7732 heading, unconditionally."
7733 (interactive "P")
7734 (if (org-called-interactively-p 'any) (org-reveal))
7735 (let ((itemp (and (not top-level) (org-in-item-p)))
7736 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7737 (respect-content (or org-insert-heading-respect-content
7738 (equal arg '(4))))
7739 (initial-content ""))
7741 (cond
7743 ((or (= (buffer-size) 0)
7744 (and (not (save-excursion
7745 (and (ignore-errors (org-back-to-heading invisible-ok))
7746 (org-at-heading-p))))
7747 (or arg (not itemp))))
7748 ;; At beginning of buffer or so high up that only a heading
7749 ;; makes sense.
7750 (cond ((and (bolp) (not respect-content)) (insert "* "))
7751 ((not respect-content)
7752 (unless may-split (end-of-line))
7753 (insert "\n* "))
7754 ((re-search-forward org-outline-regexp-bol nil t)
7755 (beginning-of-line)
7756 (insert "* \n")
7757 (backward-char))
7758 (t (goto-char (point-max))
7759 (insert "\n* ")))
7760 (run-hooks 'org-insert-heading-hook))
7762 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7765 ;; Maybe move at the end of the subtree
7766 (when (equal arg '(16))
7767 (org-up-heading-safe)
7768 (org-end-of-subtree t))
7769 ;; Insert a heading
7770 (save-restriction
7771 (widen)
7772 (let* ((level nil)
7773 (on-heading (org-at-heading-p))
7774 (empty-line-p (if on-heading
7775 (org-previous-line-empty-p)
7776 ;; We will decide later
7777 nil))
7778 ;; Get a level string to fall back on.
7779 (fix-level
7780 (if (org-before-first-heading-p) "*"
7781 (save-excursion
7782 (org-back-to-heading t)
7783 (if (org-previous-line-empty-p) (setq empty-line-p t))
7784 (looking-at org-outline-regexp)
7785 (make-string (1- (length (match-string 0))) ?*))))
7786 (stars
7787 (save-excursion
7788 (condition-case nil
7789 (if top-level "* "
7790 (org-back-to-heading invisible-ok)
7791 (when (and (not on-heading)
7792 (featurep 'org-inlinetask)
7793 (integerp org-inlinetask-min-level)
7794 (>= (length (match-string 0))
7795 org-inlinetask-min-level))
7796 ;; Find a heading level before the inline
7797 ;; task.
7798 (while (and (setq level (org-up-heading-safe))
7799 (>= level org-inlinetask-min-level)))
7800 (if (org-at-heading-p)
7801 (org-back-to-heading invisible-ok)
7802 (error "This should not happen")))
7803 (unless (and (save-excursion
7804 (save-match-data
7805 (org-backward-heading-same-level
7806 1 invisible-ok))
7807 (= (point) (match-beginning 0)))
7808 (not (org-previous-line-empty-p t)))
7809 (setq empty-line-p (or empty-line-p
7810 (org-previous-line-empty-p))))
7811 (match-string 0))
7812 (error (or fix-level "* ")))))
7813 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7814 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7815 pos hide-previous previous-pos)
7817 ;; If we insert after content, move there and clean up
7818 ;; whitespace.
7819 (when (and respect-content
7820 (not (org-looking-at-p org-outline-regexp-bol)))
7821 (if (not (org-before-first-heading-p))
7822 (org-end-of-subtree nil t)
7823 (re-search-forward org-outline-regexp-bol)
7824 (beginning-of-line 0))
7825 (skip-chars-backward " \r\t\n")
7826 (and (not (looking-back "^\\*+"))
7827 (looking-at "[ \t]+") (replace-match ""))
7828 (unless (eobp) (forward-char 1))
7829 (when (looking-at "^\\*")
7830 (unless (bobp) (backward-char 1))
7831 (insert "\n")))
7833 ;; If we are splitting, grab the text that should be moved
7834 ;; to the new headline.
7835 (when may-split
7836 (if (org-on-heading-p)
7837 ;; This is a heading: split intelligently (keeping
7838 ;; tags).
7839 (let ((pos (point)))
7840 (beginning-of-line)
7841 (unless (looking-at org-complex-heading-regexp)
7842 (error "This should not happen"))
7843 (when (and (match-beginning 4)
7844 (> pos (match-beginning 4))
7845 (< pos (match-end 4)))
7846 (setq initial-content (buffer-substring pos (match-end 4)))
7847 (goto-char pos)
7848 (delete-region (point) (match-end 4))
7849 (if (looking-at "[ \t]*$")
7850 (replace-match "")
7851 (insert (make-string (length initial-content) ?\s)))
7852 (setq initial-content (org-trim initial-content)))
7853 (goto-char pos))
7854 ;; A normal line.
7855 (setq initial-content
7856 (org-trim
7857 (delete-and-extract-region (point) (line-end-position))))))
7859 ;; If we are at the beginning of the line, insert before it.
7860 ;; Otherwise, after it.
7861 (cond
7862 ((and (bolp) (looking-at "[ \t]*$")))
7863 ((bolp) (save-excursion (insert "\n")))
7864 (t (end-of-line)
7865 (insert "\n")))
7867 ;; Insert the new heading
7868 (insert stars)
7869 (just-one-space)
7870 (insert initial-content)
7871 (unless (and blank (org-previous-line-empty-p))
7872 (org-N-empty-lines-before-current (if blank 1 0)))
7873 ;; Adjust visibility, which may be messed up if we removed
7874 ;; blank lines while previous entry was hidden.
7875 (let ((bol (line-beginning-position)))
7876 (dolist (o (overlays-at (1- bol)))
7877 (when (and (eq (overlay-get o 'invisible) 'outline)
7878 (eq (overlay-end o) bol))
7879 (move-overlay o (overlay-start o) (1- bol)))))
7880 (run-hooks 'org-insert-heading-hook)))))))
7882 (defun org-N-empty-lines-before-current (N)
7883 "Make the number of empty lines before current exactly N.
7884 So this will delete or add empty lines."
7885 (save-excursion
7886 (beginning-of-line)
7887 (let ((p (point)))
7888 (skip-chars-backward " \r\t\n")
7889 (unless (bolp) (forward-line))
7890 (delete-region (point) p))
7891 (when (> N 0) (insert (make-string N ?\n)))))
7893 (defun org-get-heading (&optional no-tags no-todo)
7894 "Return the heading of the current entry, without the stars.
7895 When NO-TAGS is non-nil, don't include tags.
7896 When NO-TODO is non-nil, don't include TODO keywords."
7897 (save-excursion
7898 (org-back-to-heading t)
7899 (cond
7900 ((and no-tags no-todo)
7901 (looking-at org-complex-heading-regexp)
7902 (match-string 4))
7903 (no-tags
7904 (looking-at (concat org-outline-regexp
7905 "\\(.*?\\)"
7906 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7907 (match-string 1))
7908 (no-todo
7909 (looking-at org-todo-line-regexp)
7910 (match-string 3))
7911 (t (looking-at org-heading-regexp)
7912 (match-string 2)))))
7914 (defvar orgstruct-mode) ; defined below
7916 (defun org-heading-components ()
7917 "Return the components of the current heading.
7918 This is a list with the following elements:
7919 - the level as an integer
7920 - the reduced level, different if `org-odd-levels-only' is set.
7921 - the TODO keyword, or nil
7922 - the priority character, like ?A, or nil if no priority is given
7923 - the headline text itself, or the tags string if no headline text
7924 - the tags string, or nil."
7925 (save-excursion
7926 (org-back-to-heading t)
7927 (if (let (case-fold-search)
7928 (looking-at
7929 (if orgstruct-mode
7930 org-heading-regexp
7931 org-complex-heading-regexp)))
7932 (if orgstruct-mode
7933 (list (length (match-string 1))
7934 (org-reduced-level (length (match-string 1)))
7937 (match-string 2)
7938 nil)
7939 (list (length (match-string 1))
7940 (org-reduced-level (length (match-string 1)))
7941 (org-match-string-no-properties 2)
7942 (and (match-end 3) (aref (match-string 3) 2))
7943 (org-match-string-no-properties 4)
7944 (org-match-string-no-properties 5))))))
7946 (defun org-get-entry ()
7947 "Get the entry text, after heading, entire subtree."
7948 (save-excursion
7949 (org-back-to-heading t)
7950 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7952 (defun org-insert-heading-after-current ()
7953 "Insert a new heading with same level as current, after current subtree."
7954 (interactive)
7955 (org-back-to-heading)
7956 (org-insert-heading)
7957 (org-move-subtree-down)
7958 (end-of-line 1))
7960 (defun org-insert-heading-respect-content (&optional invisible-ok)
7961 "Insert heading with `org-insert-heading-respect-content' set to t."
7962 (interactive)
7963 (org-insert-heading '(4) invisible-ok))
7965 (defun org-insert-todo-heading-respect-content (&optional force-state)
7966 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7967 (interactive)
7968 (org-insert-todo-heading force-state '(4)))
7970 (defun org-insert-todo-heading (arg &optional force-heading)
7971 "Insert a new heading with the same level and TODO state as current heading.
7972 If the heading has no TODO state, or if the state is DONE, use the first
7973 state (TODO by default). Also with one prefix arg, force first state. With
7974 two prefix args, force inserting at the end of the parent subtree."
7975 (interactive "P")
7976 (when (or force-heading (not (org-insert-item 'checkbox)))
7977 (org-insert-heading (or (and (equal arg '(16)) '(16))
7978 force-heading))
7979 (save-excursion
7980 (org-back-to-heading)
7981 (outline-previous-heading)
7982 (looking-at org-todo-line-regexp))
7983 (let*
7984 ((new-mark-x
7985 (if (or (equal arg '(4))
7986 (not (match-beginning 2))
7987 (member (match-string 2) org-done-keywords))
7988 (car org-todo-keywords-1)
7989 (match-string 2)))
7990 (new-mark
7992 (run-hook-with-args-until-success
7993 'org-todo-get-default-hook new-mark-x nil)
7994 new-mark-x)))
7995 (beginning-of-line 1)
7996 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7997 (if org-treat-insert-todo-heading-as-state-change
7998 (org-todo new-mark)
7999 (insert new-mark " "))))
8000 (when org-provide-todo-statistics
8001 (org-update-parent-todo-statistics))))
8003 (defun org-insert-subheading (arg)
8004 "Insert a new subheading and demote it.
8005 Works for outline headings and for plain lists alike."
8006 (interactive "P")
8007 (org-insert-heading arg)
8008 (cond
8009 ((org-at-heading-p) (org-do-demote))
8010 ((org-at-item-p) (org-indent-item))))
8012 (defun org-insert-todo-subheading (arg)
8013 "Insert a new subheading with TODO keyword or checkbox and demote it.
8014 Works for outline headings and for plain lists alike."
8015 (interactive "P")
8016 (org-insert-todo-heading arg)
8017 (cond
8018 ((org-at-heading-p) (org-do-demote))
8019 ((org-at-item-p) (org-indent-item))))
8021 ;;; Promotion and Demotion
8023 (defvar org-after-demote-entry-hook nil
8024 "Hook run after an entry has been demoted.
8025 The cursor will be at the beginning of the entry.
8026 When a subtree is being demoted, the hook will be called for each node.")
8028 (defvar org-after-promote-entry-hook nil
8029 "Hook run after an entry has been promoted.
8030 The cursor will be at the beginning of the entry.
8031 When a subtree is being promoted, the hook will be called for each node.")
8033 (defun org-promote-subtree ()
8034 "Promote the entire subtree.
8035 See also `org-promote'."
8036 (interactive)
8037 (save-excursion
8038 (org-with-limited-levels (org-map-tree 'org-promote)))
8039 (org-fix-position-after-promote))
8041 (defun org-demote-subtree ()
8042 "Demote the entire subtree. See `org-demote'.
8043 See also `org-promote'."
8044 (interactive)
8045 (save-excursion
8046 (org-with-limited-levels (org-map-tree 'org-demote)))
8047 (org-fix-position-after-promote))
8050 (defun org-do-promote ()
8051 "Promote the current heading higher up the tree.
8052 If the region is active in `transient-mark-mode', promote all headings
8053 in the region."
8054 (interactive)
8055 (save-excursion
8056 (if (org-region-active-p)
8057 (org-map-region 'org-promote (region-beginning) (region-end))
8058 (org-promote)))
8059 (org-fix-position-after-promote))
8061 (defun org-do-demote ()
8062 "Demote the current heading lower down the tree.
8063 If the region is active in `transient-mark-mode', demote all headings
8064 in the region."
8065 (interactive)
8066 (save-excursion
8067 (if (org-region-active-p)
8068 (org-map-region 'org-demote (region-beginning) (region-end))
8069 (org-demote)))
8070 (org-fix-position-after-promote))
8072 (defun org-fix-position-after-promote ()
8073 "Make sure that after pro/demotion cursor position is right."
8074 (let ((pos (point)))
8075 (when (save-excursion
8076 (beginning-of-line 1)
8077 (looking-at org-todo-line-regexp)
8078 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8079 (cond ((eobp) (insert " "))
8080 ((eolp) (insert " "))
8081 ((equal (char-after) ?\ ) (forward-char 1))))))
8083 (defun org-current-level ()
8084 "Return the level of the current entry, or nil if before the first headline.
8085 The level is the number of stars at the beginning of the
8086 headline. Use `org-reduced-level' to remove the effect of
8087 `org-odd-levels'. Unlike to `org-outline-level', this function
8088 ignores inlinetasks."
8089 (let ((level (org-with-limited-levels (org-outline-level))))
8090 (and (> level 0) level)))
8092 (defun org-get-previous-line-level ()
8093 "Return the outline depth of the last headline before the current line.
8094 Returns 0 for the first headline in the buffer, and nil if before the
8095 first headline."
8096 (and (org-current-level)
8097 (or (and (/= (line-beginning-position) (point-min))
8098 (save-excursion (beginning-of-line 0) (org-current-level)))
8099 0)))
8101 (defun org-reduced-level (l)
8102 "Compute the effective level of a heading.
8103 This takes into account the setting of `org-odd-levels-only'."
8104 (cond
8105 ((zerop l) 0)
8106 (org-odd-levels-only (1+ (floor (/ l 2))))
8107 (t l)))
8109 (defun org-level-increment ()
8110 "Return the number of stars that will be added or removed at a
8111 time to headlines when structure editing, based on the value of
8112 `org-odd-levels-only'."
8113 (if org-odd-levels-only 2 1))
8115 (defun org-get-valid-level (level &optional change)
8116 "Rectify a level change under the influence of `org-odd-levels-only'
8117 LEVEL is a current level, CHANGE is by how much the level should be
8118 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8119 even level numbers will become the next higher odd number."
8120 (if org-odd-levels-only
8121 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8122 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8123 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8124 (max 1 (+ level (or change 0)))))
8126 (if (boundp 'define-obsolete-function-alias)
8127 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8128 (define-obsolete-function-alias 'org-get-legal-level
8129 'org-get-valid-level)
8130 (define-obsolete-function-alias 'org-get-legal-level
8131 'org-get-valid-level "23.1")))
8133 (defun org-promote ()
8134 "Promote the current heading higher up 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 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8141 (diff (abs (- level (length up-head) -1))))
8142 (cond
8143 ((and (= level 1) org-allow-promoting-top-level-subtree)
8144 (replace-match "# " nil t))
8145 ((= level 1)
8146 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8147 (t (replace-match up-head nil t)))
8148 (unless (= level 1)
8149 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8150 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8151 (run-hooks 'org-after-promote-entry-hook))))
8153 (defun org-demote ()
8154 "Demote the current heading lower down the tree."
8155 (org-with-wide-buffer
8156 (org-back-to-heading t)
8157 (let* ((after-change-functions (remq 'flyspell-after-change-function
8158 after-change-functions))
8159 (level (save-match-data (funcall outline-level)))
8160 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8161 (diff (abs (- level (length down-head) -1))))
8162 (replace-match down-head nil t)
8163 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8164 (when org-adapt-indentation (org-fixup-indentation diff))
8165 (run-hooks 'org-after-demote-entry-hook))))
8167 (defun org-cycle-level ()
8168 "Cycle the level of an empty headline through possible states.
8169 This goes first to child, then to parent, level, then up the hierarchy.
8170 After top level, it switches back to sibling level."
8171 (interactive)
8172 (let ((org-adapt-indentation nil))
8173 (when (org-point-at-end-of-empty-headline)
8174 (setq this-command 'org-cycle-level) ; Only needed for caching
8175 (let ((cur-level (org-current-level))
8176 (prev-level (org-get-previous-line-level)))
8177 (cond
8178 ;; If first headline in file, promote to top-level.
8179 ((= prev-level 0)
8180 (loop repeat (/ (- cur-level 1) (org-level-increment))
8181 do (org-do-promote)))
8182 ;; If same level as prev, demote one.
8183 ((= prev-level cur-level)
8184 (org-do-demote))
8185 ;; If parent is top-level, promote to top level if not already.
8186 ((= prev-level 1)
8187 (loop repeat (/ (- cur-level 1) (org-level-increment))
8188 do (org-do-promote)))
8189 ;; If top-level, return to prev-level.
8190 ((= cur-level 1)
8191 (loop repeat (/ (- prev-level 1) (org-level-increment))
8192 do (org-do-demote)))
8193 ;; If less than prev-level, promote one.
8194 ((< cur-level prev-level)
8195 (org-do-promote))
8196 ;; If deeper than prev-level, promote until higher than
8197 ;; prev-level.
8198 ((> cur-level prev-level)
8199 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8200 do (org-do-promote))))
8201 t))))
8203 (defun org-map-tree (fun)
8204 "Call FUN for every heading underneath the current one."
8205 (org-back-to-heading)
8206 (let ((level (funcall outline-level)))
8207 (save-excursion
8208 (funcall fun)
8209 (while (and (progn
8210 (outline-next-heading)
8211 (> (funcall outline-level) level))
8212 (not (eobp)))
8213 (funcall fun)))))
8215 (defun org-map-region (fun beg end)
8216 "Call FUN for every heading between BEG and END."
8217 (let ((org-ignore-region t))
8218 (save-excursion
8219 (setq end (copy-marker end))
8220 (goto-char beg)
8221 (if (and (re-search-forward org-outline-regexp-bol nil t)
8222 (< (point) end))
8223 (funcall fun))
8224 (while (and (progn
8225 (outline-next-heading)
8226 (< (point) end))
8227 (not (eobp)))
8228 (funcall fun)))))
8230 (defun org-fixup-indentation (diff)
8231 "Change the indentation in the current entry by DIFF.
8233 DIFF is an integer. Indentation is done according to the
8234 following rules:
8236 - Planning information and property drawers are always indented
8237 according to the new level of the headline;
8239 - Footnote definitions and their contents are ignored;
8241 - Inlinetasks' boundaries are not shifted;
8243 - Empty lines are ignored;
8245 - Other lines' indentation are shifted by DIFF columns, unless
8246 it would introduce a structural change in the document, in
8247 which case no shifting is done at all.
8249 Assume point is at a heading or an inlinetask beginning."
8250 (org-with-wide-buffer
8251 (narrow-to-region (line-beginning-position)
8252 (save-excursion
8253 (if (org-with-limited-levels (org-at-heading-p))
8254 (org-with-limited-levels (outline-next-heading))
8255 (org-inlinetask-goto-end))
8256 (point)))
8257 (forward-line)
8258 ;; Indent properly planning info and property drawer.
8259 (when (org-looking-at-p org-planning-line-re)
8260 (org-indent-line)
8261 (forward-line))
8262 (when (looking-at org-property-drawer-re)
8263 (goto-char (match-end 0))
8264 (forward-line)
8265 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8266 (catch 'no-shift
8267 (when (zerop diff) (throw 'no-shift nil))
8268 ;; If DIFF is negative, first check if a shift is possible at all
8269 ;; (e.g., it doesn't break structure). This can only happen if
8270 ;; some contents are not properly indented.
8271 (let ((case-fold-search t))
8272 (when (< diff 0)
8273 (let ((diff (- diff))
8274 (forbidden-re (concat org-outline-regexp
8275 "\\|"
8276 (substring org-footnote-definition-re 1))))
8277 (save-excursion
8278 (while (not (eobp))
8279 (cond
8280 ((org-looking-at-p "[ \t]*$") (forward-line))
8281 ((and (org-looking-at-p org-footnote-definition-re)
8282 (let ((e (org-element-at-point)))
8283 (and (eq (org-element-type e) 'footnote-definition)
8284 (goto-char (org-element-property :end e))))))
8285 ((org-looking-at-p org-outline-regexp) (forward-line))
8286 ;; Give up if shifting would move before column 0 or
8287 ;; if it would introduce a headline or a footnote
8288 ;; definition.
8290 (skip-chars-forward " \t")
8291 (let ((ind (current-column)))
8292 (when (or (< ind diff)
8293 (and (= ind diff) (org-looking-at-p forbidden-re)))
8294 (throw 'no-shift nil)))
8295 ;; Ignore contents of example blocks and source
8296 ;; blocks if their indentation is meant to be
8297 ;; preserved. Jump to block's closing line.
8298 (beginning-of-line)
8299 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8300 (let ((e (org-element-at-point)))
8301 (and (memq (org-element-type e)
8302 '(example-block src-block))
8303 (or org-src-preserve-indentation
8304 (org-element-property :preserve-indent e))
8305 (goto-char (org-element-property :end e))
8306 (progn (skip-chars-backward " \r\t\n")
8307 (beginning-of-line)
8308 t))))
8309 (forward-line))))))))
8310 ;; Shift lines but footnote definitions, inlinetasks boundaries
8311 ;; by DIFF. Also skip contents of source or example blocks
8312 ;; when indentation is meant to be preserved.
8313 (while (not (eobp))
8314 (cond
8315 ((and (org-looking-at-p org-footnote-definition-re)
8316 (let ((e (org-element-at-point)))
8317 (and (eq (org-element-type e) 'footnote-definition)
8318 (goto-char (org-element-property :end e))))))
8319 ((org-looking-at-p org-outline-regexp) (forward-line))
8320 ((org-looking-at-p "[ \t]*$") (forward-line))
8322 (org-indent-line-to (+ (org-get-indentation) diff))
8323 (beginning-of-line)
8324 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8325 (let ((e (org-element-at-point)))
8326 (and (memq (org-element-type e)
8327 '(example-block src-block))
8328 (or org-src-preserve-indentation
8329 (org-element-property :preserve-indent e))
8330 (goto-char (org-element-property :end e))
8331 (progn (skip-chars-backward " \r\t\n")
8332 (beginning-of-line)
8333 t))))
8334 (forward-line)))))))))
8336 (defun org-convert-to-odd-levels ()
8337 "Convert an org-mode file with all levels allowed to one with odd levels.
8338 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8339 level 5 etc."
8340 (interactive)
8341 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8342 (let ((outline-level 'org-outline-level)
8343 (org-odd-levels-only nil) n)
8344 (save-excursion
8345 (goto-char (point-min))
8346 (while (re-search-forward "^\\*\\*+ " nil t)
8347 (setq n (- (length (match-string 0)) 2))
8348 (while (>= (setq n (1- n)) 0)
8349 (org-demote))
8350 (end-of-line 1))))))
8352 (defun org-convert-to-oddeven-levels ()
8353 "Convert an org-mode file with only odd levels to one with odd/even levels.
8354 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8355 file contains a section with an even level, conversion would
8356 destroy the structure of the file. An error is signaled in this
8357 case."
8358 (interactive)
8359 (goto-char (point-min))
8360 ;; First check if there are no even levels
8361 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8362 (org-show-set-visibility 'canonical)
8363 (error "Not all levels are odd in this file. Conversion not possible"))
8364 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8365 (let ((outline-regexp org-outline-regexp)
8366 (outline-level 'org-outline-level)
8367 (org-odd-levels-only nil) n)
8368 (save-excursion
8369 (goto-char (point-min))
8370 (while (re-search-forward "^\\*\\*+ " nil t)
8371 (setq n (/ (1- (length (match-string 0))) 2))
8372 (while (>= (setq n (1- n)) 0)
8373 (org-promote))
8374 (end-of-line 1))))))
8376 (defun org-tr-level (n)
8377 "Make N odd if required."
8378 (if org-odd-levels-only (1+ (/ n 2)) n))
8380 ;;; Vertical tree motion, cutting and pasting of subtrees
8382 (defun org-move-subtree-up (&optional arg)
8383 "Move the current subtree up past ARG headlines of the same level."
8384 (interactive "p")
8385 (org-move-subtree-down (- (prefix-numeric-value arg))))
8387 (defun org-move-subtree-down (&optional arg)
8388 "Move the current subtree down past ARG headlines of the same level."
8389 (interactive "p")
8390 (setq arg (prefix-numeric-value arg))
8391 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8392 'org-get-last-sibling))
8393 (ins-point (make-marker))
8394 (cnt (abs arg))
8395 (col (current-column))
8396 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8397 ;; Select the tree
8398 (org-back-to-heading)
8399 (setq beg0 (point))
8400 (save-excursion
8401 (setq ne-beg (org-back-over-empty-lines))
8402 (setq beg (point)))
8403 (save-match-data
8404 (save-excursion (outline-end-of-heading)
8405 (setq folded (outline-invisible-p)))
8406 (progn (org-end-of-subtree nil t)
8407 (unless (eobp) (backward-char))))
8408 (outline-next-heading)
8409 (setq ne-end (org-back-over-empty-lines))
8410 (setq end (point))
8411 (goto-char beg0)
8412 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8413 ;; include less whitespace
8414 (save-excursion
8415 (goto-char beg)
8416 (forward-line (- ne-beg ne-end))
8417 (setq beg (point))))
8418 ;; Find insertion point, with error handling
8419 (while (> cnt 0)
8420 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8421 (progn (goto-char beg0)
8422 (user-error "Cannot move past superior level or buffer limit")))
8423 (setq cnt (1- cnt)))
8424 (if (> arg 0)
8425 ;; Moving forward - still need to move over subtree
8426 (progn (org-end-of-subtree t t)
8427 (save-excursion
8428 (org-back-over-empty-lines)
8429 (or (bolp) (newline)))))
8430 (setq ne-ins (org-back-over-empty-lines))
8431 (move-marker ins-point (point))
8432 (setq txt (buffer-substring beg end))
8433 (org-save-markers-in-region beg end)
8434 (delete-region beg end)
8435 (org-remove-empty-overlays-at beg)
8436 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8437 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8438 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8439 (let ((bbb (point)))
8440 (insert-before-markers txt)
8441 (org-reinstall-markers-in-region bbb)
8442 (move-marker ins-point bbb))
8443 (or (bolp) (insert "\n"))
8444 (setq ins-end (point))
8445 (goto-char ins-point)
8446 (org-skip-whitespace)
8447 (when (and (< arg 0)
8448 (org-first-sibling-p)
8449 (> ne-ins ne-beg))
8450 ;; Move whitespace back to beginning
8451 (save-excursion
8452 (goto-char ins-end)
8453 (let ((kill-whole-line t))
8454 (kill-line (- ne-ins ne-beg)) (point)))
8455 (insert (make-string (- ne-ins ne-beg) ?\n)))
8456 (move-marker ins-point nil)
8457 (if folded
8458 (hide-subtree)
8459 (org-show-entry)
8460 (show-children)
8461 (org-cycle-hide-drawers 'children))
8462 (org-clean-visibility-after-subtree-move)
8463 ;; move back to the initial column we were at
8464 (move-to-column col)))
8466 (defvar org-subtree-clip ""
8467 "Clipboard for cut and paste of subtrees.
8468 This is actually only a copy of the kill, because we use the normal kill
8469 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8471 (defvar org-subtree-clip-folded nil
8472 "Was the last copied subtree folded?
8473 This is used to fold the tree back after pasting.")
8475 (defun org-cut-subtree (&optional n)
8476 "Cut the current subtree into the clipboard.
8477 With prefix arg N, cut this many sequential subtrees.
8478 This is a short-hand for marking the subtree and then cutting it."
8479 (interactive "p")
8480 (org-copy-subtree n 'cut))
8482 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8483 "Copy the current subtree it in the clipboard.
8484 With prefix arg N, copy this many sequential subtrees.
8485 This is a short-hand for marking the subtree and then copying it.
8486 If CUT is non-nil, actually cut the subtree.
8487 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8488 of some markers in the region, even if CUT is non-nil. This is
8489 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8490 (interactive "p")
8491 (let (beg end folded (beg0 (point)))
8492 (if (org-called-interactively-p 'any)
8493 (org-back-to-heading nil) ; take what looks like a subtree
8494 (org-back-to-heading t)) ; take what is really there
8495 (setq beg (point))
8496 (skip-chars-forward " \t\r\n")
8497 (save-match-data
8498 (if nosubtrees
8499 (outline-next-heading)
8500 (save-excursion (outline-end-of-heading)
8501 (setq folded (outline-invisible-p)))
8502 (ignore-errors (org-forward-heading-same-level (1- n) t))
8503 (org-end-of-subtree t t)))
8504 ;; Include the end of an inlinetask
8505 (when (and (featurep 'org-inlinetask)
8506 (looking-at-p (concat (org-inlinetask-outline-regexp)
8507 "END[ \t]*$")))
8508 (end-of-line))
8509 (setq end (point))
8510 (goto-char beg0)
8511 (when (> end beg)
8512 (setq org-subtree-clip-folded folded)
8513 (when (or cut force-store-markers)
8514 (org-save-markers-in-region beg end))
8515 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8516 (setq org-subtree-clip (current-kill 0))
8517 (message "%s: Subtree(s) with %d characters"
8518 (if cut "Cut" "Copied")
8519 (length org-subtree-clip)))))
8521 (defun org-paste-subtree (&optional level tree for-yank remove)
8522 "Paste the clipboard as a subtree, with modification of headline level.
8523 The entire subtree is promoted or demoted in order to match a new headline
8524 level.
8526 If the cursor is at the beginning of a headline, the same level as
8527 that headline is used to paste the tree.
8529 If not, the new level is derived from the *visible* headings
8530 before and after the insertion point, and taken to be the inferior headline
8531 level of the two. So if the previous visible heading is level 3 and the
8532 next is level 4 (or vice versa), level 4 will be used for insertion.
8533 This makes sure that the subtree remains an independent subtree and does
8534 not swallow low level entries.
8536 You can also force a different level, either by using a numeric prefix
8537 argument, or by inserting the heading marker by hand. For example, if the
8538 cursor is after \"*****\", then the tree will be shifted to level 5.
8540 If optional TREE is given, use this text instead of the kill ring.
8542 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8543 move back over whitespace before inserting, and move point to the end of
8544 the inserted text when done.
8546 When REMOVE is non-nil, remove the subtree from the clipboard."
8547 (interactive "P")
8548 (setq tree (or tree (and kill-ring (current-kill 0))))
8549 (unless (org-kill-is-subtree-p tree)
8550 (user-error "%s"
8551 (substitute-command-keys
8552 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8553 (org-with-limited-levels
8554 (let* ((visp (not (outline-invisible-p)))
8555 (txt tree)
8556 (^re_ "\\(\\*+\\)[ \t]*")
8557 (old-level (if (string-match org-outline-regexp-bol txt)
8558 (- (match-end 0) (match-beginning 0) 1)
8559 -1))
8560 (force-level (cond (level (prefix-numeric-value level))
8561 ((and (looking-at "[ \t]*$")
8562 (string-match
8563 "^\\*+$" (buffer-substring
8564 (point-at-bol) (point))))
8565 (- (match-end 0) (match-beginning 0)))
8566 ((and (bolp)
8567 (looking-at org-outline-regexp))
8568 (- (match-end 0) (point) 1))))
8569 (previous-level (save-excursion
8570 (condition-case nil
8571 (progn
8572 (outline-previous-visible-heading 1)
8573 (if (looking-at ^re_)
8574 (- (match-end 0) (match-beginning 0) 1)
8576 (error 1))))
8577 (next-level (save-excursion
8578 (condition-case nil
8579 (progn
8580 (or (looking-at org-outline-regexp)
8581 (outline-next-visible-heading 1))
8582 (if (looking-at ^re_)
8583 (- (match-end 0) (match-beginning 0) 1)
8585 (error 1))))
8586 (new-level (or force-level (max previous-level next-level)))
8587 (shift (if (or (= old-level -1)
8588 (= new-level -1)
8589 (= old-level new-level))
8591 (- new-level old-level)))
8592 (delta (if (> shift 0) -1 1))
8593 (func (if (> shift 0) 'org-demote 'org-promote))
8594 (org-odd-levels-only nil)
8595 beg end newend)
8596 ;; Remove the forced level indicator
8597 (if force-level
8598 (delete-region (point-at-bol) (point)))
8599 ;; Paste
8600 (beginning-of-line (if (bolp) 1 2))
8601 (setq beg (point))
8602 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8603 (insert-before-markers txt)
8604 (unless (string-match "\n\\'" txt) (insert "\n"))
8605 (setq newend (point))
8606 (org-reinstall-markers-in-region beg)
8607 (setq end (point))
8608 (goto-char beg)
8609 (skip-chars-forward " \t\n\r")
8610 (setq beg (point))
8611 (if (and (outline-invisible-p) visp)
8612 (save-excursion (outline-show-heading)))
8613 ;; Shift if necessary
8614 (unless (= shift 0)
8615 (save-restriction
8616 (narrow-to-region beg end)
8617 (while (not (= shift 0))
8618 (org-map-region func (point-min) (point-max))
8619 (setq shift (+ delta shift)))
8620 (goto-char (point-min))
8621 (setq newend (point-max))))
8622 (when (or (org-called-interactively-p 'interactive) for-yank)
8623 (message "Clipboard pasted as level %d subtree" new-level))
8624 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8625 kill-ring
8626 (eq org-subtree-clip (current-kill 0))
8627 org-subtree-clip-folded)
8628 ;; The tree was folded before it was killed/copied
8629 (hide-subtree))
8630 (and for-yank (goto-char newend))
8631 (and remove (setq kill-ring (cdr kill-ring))))))
8633 (defun org-kill-is-subtree-p (&optional txt)
8634 "Check if the current kill is an outline subtree, or a set of trees.
8635 Returns nil if kill does not start with a headline, or if the first
8636 headline level is not the largest headline level in the tree.
8637 So this will actually accept several entries of equal levels as well,
8638 which is OK for `org-paste-subtree'.
8639 If optional TXT is given, check this string instead of the current kill."
8640 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8641 (re (org-get-limited-outline-regexp))
8642 (^re (concat "^" re))
8643 (start-level (and kill
8644 (string-match
8645 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8646 kill)
8647 (- (match-end 2) (match-beginning 2) 1)))
8648 (start (1+ (or (match-beginning 2) -1))))
8649 (if (not start-level)
8650 (progn
8651 nil) ;; does not even start with a heading
8652 (catch 'exit
8653 (while (setq start (string-match ^re kill (1+ start)))
8654 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8655 (throw 'exit nil)))
8656 t))))
8658 (defvar org-markers-to-move nil
8659 "Markers that should be moved with a cut-and-paste operation.
8660 Those markers are stored together with their positions relative to
8661 the start of the region.")
8663 (defun org-save-markers-in-region (beg end)
8664 "Check markers in region.
8665 If these markers are between BEG and END, record their position relative
8666 to BEG, so that after moving the block of text, we can put the markers back
8667 into place.
8668 This function gets called just before an entry or tree gets cut from the
8669 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8670 called immediately, to move the markers with the entries."
8671 (setq org-markers-to-move nil)
8672 (when (featurep 'org-clock)
8673 (org-clock-save-markers-for-cut-and-paste beg end))
8674 (when (featurep 'org-agenda)
8675 (org-agenda-save-markers-for-cut-and-paste beg end)))
8677 (defun org-check-and-save-marker (marker beg end)
8678 "Check if MARKER is between BEG and END.
8679 If yes, remember the marker and the distance to BEG."
8680 (when (and (marker-buffer marker)
8681 (equal (marker-buffer marker) (current-buffer)))
8682 (if (and (>= marker beg) (< marker end))
8683 (push (cons marker (- marker beg)) org-markers-to-move))))
8685 (defun org-reinstall-markers-in-region (beg)
8686 "Move all remembered markers to their position relative to BEG."
8687 (mapc (lambda (x)
8688 (move-marker (car x) (+ beg (cdr x))))
8689 org-markers-to-move)
8690 (setq org-markers-to-move nil))
8692 (defun org-narrow-to-subtree ()
8693 "Narrow buffer to the current subtree."
8694 (interactive)
8695 (save-excursion
8696 (save-match-data
8697 (org-with-limited-levels
8698 (narrow-to-region
8699 (progn (org-back-to-heading t) (point))
8700 (progn (org-end-of-subtree t t)
8701 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8702 (point)))))))
8704 (defun org-narrow-to-block ()
8705 "Narrow buffer to the current block."
8706 (interactive)
8707 (let* ((case-fold-search t)
8708 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8709 "^[ \t]*#\\+end_.*")))
8710 (if blockp
8711 (narrow-to-region (car blockp) (cdr blockp))
8712 (user-error "Not in a block"))))
8714 (defun org-clone-subtree-with-time-shift (n &optional shift)
8715 "Clone the task (subtree) at point N times.
8716 The clones will be inserted as siblings.
8718 In interactive use, the user will be prompted for the number of
8719 clones to be produced. If the entry has a timestamp, the user
8720 will also be prompted for a time shift, which may be a repeater
8721 as used in time stamps, for example `+3d'. To disable this,
8722 you can call the function with a universal prefix argument.
8724 When a valid repeater is given and the entry contains any time
8725 stamps, the clones will become a sequence in time, with time
8726 stamps in the subtree shifted for each clone produced. If SHIFT
8727 is nil or the empty string, time stamps will be left alone. The
8728 ID property of the original subtree is removed.
8730 If the original subtree did contain time stamps with a repeater,
8731 the following will happen:
8732 - the repeater will be removed in each clone
8733 - an additional clone will be produced, with the current, unshifted
8734 date(s) in the entry.
8735 - the original entry will be placed *after* all the clones, with
8736 repeater intact.
8737 - the start days in the repeater in the original entry will be shifted
8738 to past the last clone.
8739 In this way you can spell out a number of instances of a repeating task,
8740 and still retain the repeater to cover future instances of the task.
8742 As described above, N+1 clones are produced when the original
8743 subtree has a repeater. Setting N to 0, then, can be used to
8744 remove the repeater from a subtree and create a shifted clone
8745 with the original repeater."
8746 (interactive "nNumber of clones to produce: ")
8747 (let ((shift
8748 (or shift
8749 (if (and (not (equal current-prefix-arg '(4)))
8750 (save-excursion
8751 (re-search-forward org-ts-regexp-both
8752 (save-excursion
8753 (org-end-of-subtree t)
8754 (point)) t)))
8755 (read-from-minibuffer
8756 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8757 ""))) ;; No time shift
8758 (n-no-remove -1)
8759 (drawer-re org-drawer-regexp)
8760 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8761 beg end template task idprop
8762 shift-n shift-what doshift nmin nmax)
8763 (unless (wholenump n)
8764 (user-error "Invalid number of replications %s" n))
8765 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8766 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8767 shift)))
8768 (user-error "Invalid shift specification %s" shift))
8769 (when doshift
8770 (setq shift-n (string-to-number (match-string 1 shift))
8771 shift-what (cdr (assoc (match-string 2 shift)
8772 '(("d" . day) ("w" . week)
8773 ("m" . month) ("y" . year))))))
8774 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8775 (setq nmin 1 nmax n)
8776 (org-back-to-heading t)
8777 (setq beg (point))
8778 (setq idprop (org-entry-get nil "ID"))
8779 (org-end-of-subtree t t)
8780 (or (bolp) (insert "\n"))
8781 (setq end (point))
8782 (setq template (buffer-substring beg end))
8783 (when (and doshift
8784 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8785 (delete-region beg end)
8786 (setq end beg)
8787 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8788 (goto-char end)
8789 (loop for n from nmin to nmax do
8790 ;; prepare clone
8791 (with-temp-buffer
8792 (insert template)
8793 (org-mode)
8794 (goto-char (point-min))
8795 (org-show-subtree)
8796 (and idprop (if org-clone-delete-id
8797 (org-entry-delete nil "ID")
8798 (org-id-get-create t)))
8799 (unless (= n 0)
8800 (while (re-search-forward org-clock-re nil t)
8801 (kill-whole-line))
8802 (goto-char (point-min))
8803 (while (re-search-forward drawer-re nil t)
8804 (org-remove-empty-drawer-at (point))))
8805 (goto-char (point-min))
8806 (when doshift
8807 (while (re-search-forward org-ts-regexp-both nil t)
8808 (org-timestamp-change (* n shift-n) shift-what))
8809 (unless (= n n-no-remove)
8810 (goto-char (point-min))
8811 (while (re-search-forward org-ts-regexp nil t)
8812 (save-excursion
8813 (goto-char (match-beginning 0))
8814 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8815 (delete-region (match-beginning 1) (match-end 1)))))))
8816 (setq task (buffer-string)))
8817 (insert task))
8818 (goto-char beg)))
8820 ;;; Outline Sorting
8822 (defun org-sort (with-case)
8823 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8824 Optional argument WITH-CASE means sort case-sensitively."
8825 (interactive "P")
8826 (cond
8827 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8828 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8830 (org-call-with-arg 'org-sort-entries with-case))))
8832 (defun org-sort-remove-invisible (s)
8833 "Remove invisible links from string S."
8834 (remove-text-properties 0 (length s) org-rm-props s)
8835 (while (string-match org-bracket-link-regexp s)
8836 (setq s (replace-match (if (match-end 2)
8837 (match-string 3 s)
8838 (match-string 1 s)) t t s)))
8839 (let ((st (format " %s " s)))
8840 (while (string-match org-emph-re st)
8841 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8842 (setq s (substring st 1 -1)))
8845 (defvar org-priority-regexp) ; defined later in the file
8847 (defvar org-after-sorting-entries-or-items-hook nil
8848 "Hook that is run after a bunch of entries or items have been sorted.
8849 When children are sorted, the cursor is in the parent line when this
8850 hook gets called. When a region or a plain list is sorted, the cursor
8851 will be in the first entry of the sorted region/list.")
8853 (defun org-sort-entries
8854 (&optional with-case sorting-type getkey-func compare-func property)
8855 "Sort entries on a certain level of an outline tree.
8856 If there is an active region, the entries in the region are sorted.
8857 Else, if the cursor is before the first entry, sort the top-level items.
8858 Else, the children of the entry at point are sorted.
8860 Sorting can be alphabetically, numerically, by date/time as given by
8861 a time stamp, by a property, by priority order, or by a custom function.
8863 The command prompts for the sorting type unless it has been given to the
8864 function through the SORTING-TYPE argument, which needs to be a character,
8865 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8866 the precise meaning of each character:
8868 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8869 c By creation time, which is assumed to be the first inactive time stamp
8870 at the beginning of a line.
8871 d By deadline date/time.
8872 k By clocking time.
8873 n Numerically, by converting the beginning of the entry/item to a number.
8874 o By order of TODO keywords.
8875 p By priority according to the cookie.
8876 r By the value of a property.
8877 s By scheduled date/time.
8878 t By date/time, either the first active time stamp in the entry, or, if
8879 none exist, by the first inactive one.
8881 Capital letters will reverse the sort order.
8883 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8884 called with point at the beginning of the record. It must return either
8885 a string or a number that should serve as the sorting key for that record.
8887 Comparing entries ignores case by default. However, with an optional argument
8888 WITH-CASE, the sorting considers case as well.
8890 Sorting is done against the visible part of the headlines, it ignores hidden
8891 links.
8893 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8894 (interactive "P")
8895 (let ((case-func (if with-case 'identity 'downcase))
8896 (cmstr
8897 ;; The clock marker is lost when using `sort-subr', let's
8898 ;; store the clocking string.
8899 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8900 (save-excursion
8901 (goto-char org-clock-marker)
8902 (looking-back "^.*") (match-string-no-properties 0))))
8903 start beg end stars re re2
8904 txt what tmp)
8905 ;; Find beginning and end of region to sort
8906 (cond
8907 ((org-region-active-p)
8908 ;; we will sort the region
8909 (setq end (region-end)
8910 what "region")
8911 (goto-char (region-beginning))
8912 (if (not (org-at-heading-p)) (outline-next-heading))
8913 (setq start (point)))
8914 ((or (org-at-heading-p)
8915 (ignore-errors (progn (org-back-to-heading) t)))
8916 ;; we will sort the children of the current headline
8917 (org-back-to-heading)
8918 (setq start (point)
8919 end (progn (org-end-of-subtree t t)
8920 (or (bolp) (insert "\n"))
8921 (when (>= (org-back-over-empty-lines) 1)
8922 (forward-line 1))
8923 (point))
8924 what "children")
8925 (goto-char start)
8926 (show-subtree)
8927 (outline-next-heading))
8929 ;; we will sort the top-level entries in this file
8930 (goto-char (point-min))
8931 (or (org-at-heading-p) (outline-next-heading))
8932 (setq start (point))
8933 (goto-char (point-max))
8934 (beginning-of-line 1)
8935 (when (looking-at ".*?\\S-")
8936 ;; File ends in a non-white line
8937 (end-of-line 1)
8938 (insert "\n"))
8939 (setq end (point-max))
8940 (setq what "top-level")
8941 (goto-char start)
8942 (show-all)))
8944 (setq beg (point))
8945 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8947 (looking-at "\\(\\*+\\)")
8948 (setq stars (match-string 1)
8949 re (concat "^" (regexp-quote stars) " +")
8950 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8951 txt (buffer-substring beg end))
8952 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8953 (if (and (not (equal stars "*")) (string-match re2 txt))
8954 (user-error "Region to sort contains a level above the first entry"))
8956 (unless sorting-type
8957 (message
8958 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8959 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8960 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8961 what)
8962 (setq sorting-type (read-char-exclusive))
8964 (unless getkey-func
8965 (and (= (downcase sorting-type) ?f)
8966 (setq getkey-func
8967 (org-icompleting-read "Sort using function: "
8968 obarray 'fboundp t nil nil))
8969 (setq getkey-func (intern getkey-func))))
8971 (and (= (downcase sorting-type) ?r)
8972 (not property)
8973 (setq property
8974 (org-icompleting-read "Property: "
8975 (mapcar 'list (org-buffer-property-keys t))
8976 nil t))))
8978 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8979 (message "Sorting entries...")
8981 (save-restriction
8982 (narrow-to-region start end)
8983 (let ((dcst (downcase sorting-type))
8984 (case-fold-search nil)
8985 (now (current-time)))
8986 (sort-subr
8987 (/= dcst sorting-type)
8988 ;; This function moves to the beginning character of the "record" to
8989 ;; be sorted.
8990 (lambda nil
8991 (if (re-search-forward re nil t)
8992 (goto-char (match-beginning 0))
8993 (goto-char (point-max))))
8994 ;; This function moves to the last character of the "record" being
8995 ;; sorted.
8996 (lambda nil
8997 (save-match-data
8998 (condition-case nil
8999 (outline-forward-same-level 1)
9000 (error
9001 (goto-char (point-max))))))
9002 ;; This function returns the value that gets sorted against.
9003 (lambda nil
9004 (cond
9005 ((= dcst ?n)
9006 (if (looking-at org-complex-heading-regexp)
9007 (string-to-number (org-sort-remove-invisible (match-string 4)))
9008 nil))
9009 ((= dcst ?a)
9010 (if (looking-at org-complex-heading-regexp)
9011 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9012 nil))
9013 ((= dcst ?k)
9014 (or (get-text-property (point) :org-clock-minutes) 0))
9015 ((= dcst ?t)
9016 (let ((end (save-excursion (outline-next-heading) (point))))
9017 (if (or (re-search-forward org-ts-regexp end t)
9018 (re-search-forward org-ts-regexp-both end t))
9019 (org-time-string-to-seconds (match-string 0))
9020 (org-float-time now))))
9021 ((= dcst ?c)
9022 (let ((end (save-excursion (outline-next-heading) (point))))
9023 (if (re-search-forward
9024 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9025 end t)
9026 (org-time-string-to-seconds (match-string 0))
9027 (org-float-time now))))
9028 ((= dcst ?s)
9029 (let ((end (save-excursion (outline-next-heading) (point))))
9030 (if (re-search-forward org-scheduled-time-regexp end t)
9031 (org-time-string-to-seconds (match-string 1))
9032 (org-float-time now))))
9033 ((= dcst ?d)
9034 (let ((end (save-excursion (outline-next-heading) (point))))
9035 (if (re-search-forward org-deadline-time-regexp end t)
9036 (org-time-string-to-seconds (match-string 1))
9037 (org-float-time now))))
9038 ((= dcst ?p)
9039 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9040 (string-to-char (match-string 2))
9041 org-default-priority))
9042 ((= dcst ?r)
9043 (or (org-entry-get nil property) ""))
9044 ((= dcst ?o)
9045 (if (looking-at org-complex-heading-regexp)
9046 (let* ((m (match-string 2))
9047 (s (if (member m org-done-keywords) '- '+)))
9048 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9049 ((= dcst ?f)
9050 (if getkey-func
9051 (progn
9052 (setq tmp (funcall getkey-func))
9053 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9054 tmp)
9055 (error "Invalid key function `%s'" getkey-func)))
9056 (t (error "Invalid sorting type `%c'" sorting-type))))
9058 (cond
9059 ((= dcst ?a) 'string<)
9060 ((= dcst ?f) compare-func)
9061 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9062 (run-hooks 'org-after-sorting-entries-or-items-hook)
9063 ;; Reset the clock marker if needed
9064 (when cmstr
9065 (save-excursion
9066 (goto-char start)
9067 (search-forward cmstr nil t)
9068 (move-marker org-clock-marker (point))))
9069 (message "Sorting entries...done")))
9071 ;;; The orgstruct minor mode
9073 ;; Define a minor mode which can be used in other modes in order to
9074 ;; integrate the org-mode structure editing commands.
9076 ;; This is really a hack, because the org-mode structure commands use
9077 ;; keys which normally belong to the major mode. Here is how it
9078 ;; works: The minor mode defines all the keys necessary to operate the
9079 ;; structure commands, but wraps the commands into a function which
9080 ;; tests if the cursor is currently at a headline or a plain list
9081 ;; item. If that is the case, the structure command is used,
9082 ;; temporarily setting many Org-mode variables like regular
9083 ;; expressions for filling etc. However, when any of those keys is
9084 ;; used at a different location, function uses `key-binding' to look
9085 ;; up if the key has an associated command in another currently active
9086 ;; keymap (minor modes, major mode, global), and executes that
9087 ;; command. There might be problems if any of the keys is otherwise
9088 ;; used as a prefix key.
9090 (defcustom orgstruct-heading-prefix-regexp ""
9091 "Regexp that matches the custom prefix of Org headlines in
9092 orgstruct(++)-mode."
9093 :group 'org
9094 :version "24.4"
9095 :package-version '(Org . "8.3")
9096 :type 'regexp)
9097 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9099 (defcustom orgstruct-setup-hook nil
9100 "Hook run after orgstruct-mode-map is filled."
9101 :group 'org
9102 :version "24.4"
9103 :package-version '(Org . "8.0")
9104 :type 'hook)
9106 (defvar orgstruct-initialized nil)
9108 (defvar org-local-vars nil
9109 "List of local variables, for use by `orgstruct-mode'.")
9111 ;;;###autoload
9112 (define-minor-mode orgstruct-mode
9113 "Toggle the minor mode `orgstruct-mode'.
9114 This mode is for using Org-mode structure commands in other
9115 modes. The following keys behave as if Org-mode were active, if
9116 the cursor is on a headline, or on a plain list item (both as
9117 defined by Org-mode)."
9118 nil " OrgStruct" (make-sparse-keymap)
9119 (funcall (if orgstruct-mode
9120 'add-to-invisibility-spec
9121 'remove-from-invisibility-spec)
9122 '(outline . t))
9123 (when orgstruct-mode
9124 (org-load-modules-maybe)
9125 (unless orgstruct-initialized
9126 (orgstruct-setup)
9127 (setq orgstruct-initialized t))))
9129 ;;;###autoload
9130 (defun turn-on-orgstruct ()
9131 "Unconditionally turn on `orgstruct-mode'."
9132 (orgstruct-mode 1))
9134 (defvar org-fb-vars nil)
9135 (make-variable-buffer-local 'org-fb-vars)
9136 (defun orgstruct++-mode (&optional arg)
9137 "Toggle `orgstruct-mode', the enhanced version of it.
9138 In addition to setting orgstruct-mode, this also exports all
9139 indentation and autofilling variables from org-mode into the
9140 buffer. It will also recognize item context in multiline items."
9141 (interactive "P")
9142 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9143 (if (< arg 1)
9144 (progn (orgstruct-mode -1)
9145 (mapc (lambda(v)
9146 (org-set-local (car v)
9147 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9148 org-fb-vars))
9149 (orgstruct-mode 1)
9150 (setq org-fb-vars nil)
9151 (unless org-local-vars
9152 (setq org-local-vars (org-get-local-variables)))
9153 (let (var val)
9154 (mapc
9155 (lambda (x)
9156 (when (string-match
9157 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9158 (symbol-name (car x)))
9159 (setq var (car x) val (nth 1 x))
9160 (push (list var `(quote ,(eval var))) org-fb-vars)
9161 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9162 org-local-vars)
9163 (org-set-local 'orgstruct-is-++ t))))
9165 (defvar orgstruct-is-++ nil
9166 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9167 (make-variable-buffer-local 'orgstruct-is-++)
9169 ;;;###autoload
9170 (defun turn-on-orgstruct++ ()
9171 "Unconditionally turn on `orgstruct++-mode'."
9172 (orgstruct++-mode 1))
9174 (defun orgstruct-error ()
9175 "Error when there is no default binding for a structure key."
9176 (interactive)
9177 (funcall (if (fboundp 'user-error)
9178 'user-error
9179 'error)
9180 "This key has no function outside structure elements"))
9182 (defun orgstruct-setup ()
9183 "Setup orgstruct keymap."
9184 (dolist (cell '((org-demote . t)
9185 (org-metaleft . t)
9186 (org-metaright . t)
9187 (org-promote . t)
9188 (org-shiftmetaleft . t)
9189 (org-shiftmetaright . t)
9190 org-backward-element
9191 org-backward-heading-same-level
9192 org-ctrl-c-ret
9193 org-ctrl-c-minus
9194 org-ctrl-c-star
9195 org-cycle
9196 org-forward-heading-same-level
9197 org-insert-heading
9198 org-insert-heading-respect-content
9199 org-kill-note-or-show-branches
9200 org-mark-subtree
9201 org-meta-return
9202 org-metadown
9203 org-metaup
9204 org-narrow-to-subtree
9205 org-promote-subtree
9206 org-reveal
9207 org-shiftdown
9208 org-shiftleft
9209 org-shiftmetadown
9210 org-shiftmetaup
9211 org-shiftright
9212 org-shifttab
9213 org-shifttab
9214 org-shiftup
9215 org-show-subtree
9216 org-sort
9217 org-up-element
9218 outline-demote
9219 outline-next-visible-heading
9220 outline-previous-visible-heading
9221 outline-promote
9222 outline-up-heading
9223 show-children))
9224 (let ((f (or (car-safe cell) cell))
9225 (disable-when-heading-prefix (cdr-safe cell)))
9226 (when (fboundp f)
9227 (let ((new-bindings))
9228 (dolist (binding (nconc (where-is-internal f org-mode-map)
9229 (where-is-internal f outline-mode-map)))
9230 (push binding new-bindings)
9231 ;; TODO use local-function-key-map
9232 (dolist (rep '(("<tab>" . "TAB")
9233 ("<return>" . "RET")
9234 ("<escape>" . "ESC")
9235 ("<delete>" . "DEL")))
9236 (setq binding (read-kbd-macro
9237 (let ((case-fold-search))
9238 (replace-regexp-in-string
9239 (regexp-quote (cdr rep))
9240 (car rep)
9241 (key-description binding)))))
9242 (pushnew binding new-bindings :test 'equal)))
9243 (dolist (binding new-bindings)
9244 (let ((key (lookup-key orgstruct-mode-map binding)))
9245 (when (or (not key) (numberp key))
9246 (ignore-errors
9247 (org-defkey orgstruct-mode-map
9248 binding
9249 (orgstruct-make-binding
9250 f binding disable-when-heading-prefix))))))))))
9251 (run-hooks 'orgstruct-setup-hook))
9253 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9254 "Create a function for binding in the structure minor mode.
9255 FUN is the command to call inside a table. KEY is the key that
9256 should be checked in for a command to execute outside of tables.
9257 Non-nil `disable-when-heading-prefix' means to disable the command
9258 if `orgstruct-heading-prefix-regexp' is not empty."
9259 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9260 (let ((nname name)
9261 (i 0))
9262 (while (fboundp (intern nname))
9263 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9264 (setq name (intern nname)))
9265 (eval
9266 (let ((bindings '((org-heading-regexp
9267 (concat "^"
9268 orgstruct-heading-prefix-regexp
9269 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9270 (org-outline-regexp
9271 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9272 (org-outline-regexp-bol
9273 (concat "^" org-outline-regexp))
9274 (outline-regexp org-outline-regexp)
9275 (outline-heading-end-regexp "\n")
9276 (outline-level 'org-outline-level)
9277 (outline-heading-alist))))
9278 `(defun ,name (arg)
9279 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9280 "Outside of structure, run the binding of `"
9281 (key-description key) "'."
9282 (when disable-when-heading-prefix
9283 (concat
9284 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9285 "back to the default binding due to limitations of Org's implementation of\n"
9286 "`" (symbol-name fun) "'.")))
9287 (interactive "p")
9288 (let* ((disable
9289 ,(and disable-when-heading-prefix
9290 '(not (string= orgstruct-heading-prefix-regexp ""))))
9291 (fallback
9292 (or disable
9293 (not
9294 (let* ,bindings
9295 (org-context-p 'headline 'item
9296 ,(when (memq fun
9297 '(org-insert-heading
9298 org-insert-heading-respect-content
9299 org-meta-return))
9300 '(when orgstruct-is-++
9301 'item-body))))))))
9302 (if fallback
9303 (let* ((orgstruct-mode)
9304 (binding
9305 (let ((key ,key))
9306 (catch 'exit
9307 (dolist
9308 (rep
9309 '(nil
9310 ("<\\([^>]*\\)tab>" . "\\1TAB")
9311 ("<\\([^>]*\\)return>" . "\\1RET")
9312 ("<\\([^>]*\\)escape>" . "\\1ESC")
9313 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9314 nil)
9315 (when rep
9316 (setq key (read-kbd-macro
9317 (let ((case-fold-search))
9318 (replace-regexp-in-string
9319 (car rep)
9320 (cdr rep)
9321 (key-description key))))))
9322 (when (key-binding key)
9323 (throw 'exit (key-binding key))))))))
9324 (if (keymapp binding)
9325 (org-set-transient-map binding)
9326 (let ((func (or binding
9327 (unless disable
9328 'orgstruct-error))))
9329 (when func
9330 (call-interactively func)))))
9331 (org-run-like-in-org-mode
9332 (lambda ()
9333 (interactive)
9334 (let* ,bindings
9335 (call-interactively ',fun)))))))))
9336 name))
9338 (defun org-contextualize-keys (alist contexts)
9339 "Return valid elements in ALIST depending on CONTEXTS.
9341 `org-agenda-custom-commands' or `org-capture-templates' are the
9342 values used for ALIST, and `org-agenda-custom-commands-contexts'
9343 or `org-capture-templates-contexts' are the associated contexts
9344 definitions."
9345 (let ((contexts
9346 ;; normalize contexts
9347 (mapcar
9348 (lambda(c) (cond ((listp (cadr c))
9349 (list (car c) (car c) (cadr c)))
9350 ((string= "" (cadr c))
9351 (list (car c) (car c) (caddr c)))
9352 (t c))) contexts))
9353 (a alist) c r s)
9354 ;; loop over all commands or templates
9355 (while (setq c (pop a))
9356 (let (vrules repl)
9357 (cond
9358 ((not (assoc (car c) contexts))
9359 (push c r))
9360 ((and (assoc (car c) contexts)
9361 (setq vrules (org-contextualize-validate-key
9362 (car c) contexts)))
9363 (mapc (lambda (vr)
9364 (when (not (equal (car vr) (cadr vr)))
9365 (setq repl vr))) vrules)
9366 (if (not repl) (push c r)
9367 (push (cadr repl) s)
9368 (push
9369 (cons (car c)
9370 (cdr (or (assoc (cadr repl) alist)
9371 (error "Undefined key `%s' as contextual replacement for `%s'"
9372 (cadr repl) (car c)))))
9373 r))))))
9374 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9375 (delq
9377 (delete-dups
9378 (mapcar (lambda (x)
9379 (let ((tpl (car x)))
9380 (when (not (delq
9382 (mapcar (lambda(y)
9383 (equal y tpl)) s))) x)))
9384 (reverse r))))))
9386 (defun org-contextualize-validate-key (key contexts)
9387 "Check CONTEXTS for agenda or capture KEY."
9388 (let (r rr res)
9389 (while (setq r (pop contexts))
9390 (mapc
9391 (lambda (rr)
9392 (when
9393 (and (equal key (car r))
9394 (if (functionp rr) (funcall rr)
9395 (or (and (eq (car rr) 'in-file)
9396 (buffer-file-name)
9397 (string-match (cdr rr) (buffer-file-name)))
9398 (and (eq (car rr) 'in-mode)
9399 (string-match (cdr rr) (symbol-name major-mode)))
9400 (and (eq (car rr) 'in-buffer)
9401 (string-match (cdr rr) (buffer-name)))
9402 (when (and (eq (car rr) 'not-in-file)
9403 (buffer-file-name))
9404 (not (string-match (cdr rr) (buffer-file-name))))
9405 (when (eq (car rr) 'not-in-mode)
9406 (not (string-match (cdr rr) (symbol-name major-mode))))
9407 (when (eq (car rr) 'not-in-buffer)
9408 (not (string-match (cdr rr) (buffer-name)))))))
9409 (push r res)))
9410 (car (last r))))
9411 (delete-dups (delq nil res))))
9413 (defun org-context-p (&rest contexts)
9414 "Check if local context is any of CONTEXTS.
9415 Possible values in the list of contexts are `table', `headline', and `item'."
9416 (let ((pos (point)))
9417 (goto-char (point-at-bol))
9418 (prog1 (or (and (memq 'table contexts)
9419 (looking-at "[ \t]*|"))
9420 (and (memq 'headline contexts)
9421 (looking-at org-outline-regexp))
9422 (and (memq 'item contexts)
9423 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9424 (and (memq 'item-body contexts)
9425 (org-in-item-p)))
9426 (goto-char pos))))
9428 (defun org-get-local-variables ()
9429 "Return a list of all local variables in an Org mode buffer."
9430 (let (varlist)
9431 (with-current-buffer (get-buffer-create "*Org tmp*")
9432 (erase-buffer)
9433 (org-mode)
9434 (setq varlist (buffer-local-variables)))
9435 (kill-buffer "*Org tmp*")
9436 (delq nil
9437 (mapcar
9438 (lambda (x)
9439 (setq x
9440 (if (symbolp x)
9441 (list x)
9442 (list (car x) (cdr x))))
9443 (if (and (not (get (car x) 'org-state))
9444 (string-match
9445 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9446 (symbol-name (car x))))
9447 x nil))
9448 varlist))))
9450 (defun org-clone-local-variables (from-buffer &optional regexp)
9451 "Clone local variables from FROM-BUFFER.
9452 Optional argument REGEXP selects variables to clone."
9453 (mapc
9454 (lambda (pair)
9455 (and (symbolp (car pair))
9456 (or (null regexp)
9457 (string-match regexp (symbol-name (car pair))))
9458 (set (make-local-variable (car pair))
9459 (cdr pair))))
9460 (buffer-local-variables from-buffer)))
9462 ;;;###autoload
9463 (defun org-run-like-in-org-mode (cmd)
9464 "Run a command, pretending that the current buffer is in Org-mode.
9465 This will temporarily bind local variables that are typically bound in
9466 Org-mode to the values they have in Org-mode, and then interactively
9467 call CMD."
9468 (org-load-modules-maybe)
9469 (unless org-local-vars
9470 (setq org-local-vars (org-get-local-variables)))
9471 (let (binds)
9472 (dolist (var org-local-vars)
9473 (when (or (not (boundp (car var)))
9474 (eq (symbol-value (car var))
9475 (default-value (car var))))
9476 (push (list (car var) `(quote ,(cadr var))) binds)))
9477 (eval `(let ,binds
9478 (call-interactively (quote ,cmd))))))
9480 (defun org-get-category (&optional pos force-refresh)
9481 "Get the category applying to position POS."
9482 (save-match-data
9483 (if force-refresh (org-refresh-category-properties))
9484 (let ((pos (or pos (point))))
9485 (or (get-text-property pos 'org-category)
9486 (progn (org-refresh-category-properties)
9487 (get-text-property pos 'org-category))))))
9489 ;;; Refresh properties
9491 (defun org-refresh-properties (dprop tprop)
9492 "Refresh buffer text properties.
9493 DPROP is the drawer property and TPROP is either the
9494 corresponding text property to set, or an alist with each element
9495 being a text property (as a symbol) and a function to apply to
9496 the value of the drawer property."
9497 (let ((case-fold-search t)
9498 (inhibit-read-only t))
9499 (org-with-silent-modifications
9500 (save-excursion
9501 (save-restriction
9502 (widen)
9503 (goto-char (point-min))
9504 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9505 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9507 (defun org-refresh-property (tprop p)
9508 "Refresh the buffer text property TPROP from the drawer property P.
9509 The refresh happens only for the current tree (not subtree)."
9510 (unless (org-before-first-heading-p)
9511 (save-excursion
9512 (org-back-to-heading t)
9513 (if (symbolp tprop)
9514 ;; TPROP is a text property symbol
9515 (put-text-property
9516 (point) (or (outline-next-heading) (point-max)) tprop p)
9517 ;; TPROP is an alist with (properties . function) elements
9518 (dolist (al tprop)
9519 (save-excursion
9520 (put-text-property
9521 (line-beginning-position) (or (outline-next-heading) (point-max))
9522 (car al)
9523 (funcall (cdr al) p))))))))
9525 (defun org-refresh-category-properties ()
9526 "Refresh category text properties in the buffer."
9527 (let ((case-fold-search t)
9528 (inhibit-read-only t)
9529 (default-category
9530 (cond ((null org-category)
9531 (if buffer-file-name
9532 (file-name-sans-extension
9533 (file-name-nondirectory buffer-file-name))
9534 "???"))
9535 ((symbolp org-category) (symbol-name org-category))
9536 (t org-category))))
9537 (org-with-silent-modifications
9538 (org-with-wide-buffer
9539 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9540 ;; This is the default category for the buffer. If none is
9541 ;; found, fall-back to `org-category' or buffer file name.
9542 (put-text-property
9543 (point-min) (point-max)
9544 'org-category
9545 (catch 'buffer-category
9546 (goto-char (point-max))
9547 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9548 (let ((element (org-element-at-point)))
9549 (when (eq (org-element-type element) 'keyword)
9550 (throw 'buffer-category
9551 (org-element-property :value element)))))
9552 default-category))
9553 ;; Set sub-tree specific categories.
9554 (goto-char (point-min))
9555 (let ((regexp (org-re-property "CATEGORY")))
9556 (while (re-search-forward regexp nil t)
9557 (let ((value (org-match-string-no-properties 3)))
9558 (when (org-at-property-p)
9559 (put-text-property
9560 (save-excursion (org-back-to-heading t) (point))
9561 (save-excursion (org-end-of-subtree t t) (point))
9562 'org-category
9563 value)))))))))
9565 (defun org-refresh-stats-properties ()
9566 "Refresh stats text properties in the buffer."
9567 (let (stats)
9568 (org-with-silent-modifications
9569 (save-excursion
9570 (save-restriction
9571 (widen)
9572 (goto-char (point-min))
9573 (while (re-search-forward
9574 (concat org-outline-regexp-bol ".*"
9575 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9576 nil t)
9577 (setq stats (cond ((equal (match-string 3) "0") 0)
9578 ((match-string 2)
9579 (/ (* (string-to-number (match-string 2)) 100)
9580 (string-to-number (match-string 3))))
9581 (t (string-to-number (match-string 1)))))
9582 (org-back-to-heading t)
9583 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9584 'org-stats stats)))))))
9586 (defun org-refresh-effort-properties ()
9587 "Refresh effort properties"
9588 (org-refresh-properties
9589 org-effort-property
9590 '((effort . identity)
9591 (effort-minutes . org-duration-string-to-minutes))))
9593 ;;;; Link Stuff
9595 ;;; Link abbreviations
9597 (defun org-link-expand-abbrev (link)
9598 "Apply replacements as defined in `org-link-abbrev-alist'."
9599 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9600 (let* ((key (match-string 1 link))
9601 (as (or (assoc key org-link-abbrev-alist-local)
9602 (assoc key org-link-abbrev-alist)))
9603 (tag (and (match-end 2) (match-string 3 link)))
9604 rpl)
9605 (if (not as)
9606 link
9607 (setq rpl (cdr as))
9608 (cond
9609 ((symbolp rpl) (funcall rpl tag))
9610 ((string-match "%(\\([^)]+\\))" rpl)
9611 (replace-match
9612 (save-match-data
9613 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9614 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9615 ((string-match "%h" rpl)
9616 (replace-match (url-hexify-string (or tag "")) t t rpl))
9617 (t (concat rpl tag)))))
9618 link))
9620 ;;; Storing and inserting links
9622 (defvar org-insert-link-history nil
9623 "Minibuffer history for links inserted with `org-insert-link'.")
9625 (defvar org-stored-links nil
9626 "Contains the links stored with `org-store-link'.")
9628 (defvar org-store-link-plist nil
9629 "Plist with info about the most recently link created with `org-store-link'.")
9631 (defvar org-link-protocols nil
9632 "Link protocols added to Org-mode using `org-add-link-type'.")
9634 (defvar org-store-link-functions nil
9635 "List of functions that are called to create and store a link.
9636 Each function will be called in turn until one returns a non-nil
9637 value. Each function should check if it is responsible for creating
9638 this link (for example by looking at the major mode).
9639 If not, it must exit and return nil.
9640 If yes, it should return a non-nil value after a calling
9641 `org-store-link-props' with a list of properties and values.
9642 Special properties are:
9644 :type The link prefix, like \"http\". This must be given.
9645 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9646 This is obligatory as well.
9647 :description Optional default description for the second pair
9648 of brackets in an Org-mode link. The user can still change
9649 this when inserting this link into an Org-mode buffer.
9651 In addition to these, any additional properties can be specified
9652 and then used in capture templates.")
9654 (defun org-add-link-type (type &optional follow export)
9655 "Add TYPE to the list of `org-link-types'.
9656 Re-compute all regular expressions depending on `org-link-types'
9658 FOLLOW and EXPORT are two functions.
9660 FOLLOW should take the link path as the single argument and do whatever
9661 is necessary to follow the link, for example find a file or display
9662 a mail message.
9664 EXPORT should format the link path for export to one of the export formats.
9665 It should be a function accepting three arguments:
9667 path the path of the link, the text after the prefix (like \"http:\")
9668 desc the description of the link, if any
9669 format the export format, a symbol like `html' or `latex' or `ascii'.
9671 The function may use the FORMAT information to return different values
9672 depending on the format. The return value will be put literally into
9673 the exported file. If the return value is nil, this means Org should
9674 do what it normally does with links which do not have EXPORT defined.
9676 Org mode has a built-in default for exporting links. If you are happy with
9677 this default, there is no need to define an export function for the link
9678 type. For a simple example of an export function, see `org-bbdb.el'."
9679 (add-to-list 'org-link-types type t)
9680 (org-make-link-regexps)
9681 (org-element-update-syntax)
9682 (if (assoc type org-link-protocols)
9683 (setcdr (assoc type org-link-protocols) (list follow export))
9684 (push (list type follow export) org-link-protocols)))
9686 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9687 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9689 ;;;###autoload
9690 (defun org-store-link (arg)
9691 "\\<org-mode-map>Store an org-link to the current location.
9692 This link is added to `org-stored-links' and can later be inserted
9693 into an Org buffer with \\[org-insert-link].
9695 For some link types, a prefix ARG is interpreted.
9696 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9697 For file links, ARG negates `org-context-in-file-links'.
9699 A double prefix ARG force skipping storing functions that are not
9700 part of Org's core.
9702 A triple prefix ARG force storing a link for each line in the
9703 active region."
9704 (interactive "P")
9705 (org-load-modules-maybe)
9706 (if (and (equal arg '(64)) (org-region-active-p))
9707 (save-excursion
9708 (let ((end (region-end)))
9709 (goto-char (region-beginning))
9710 (set-mark (point))
9711 (while (< (point-at-eol) end)
9712 (move-end-of-line 1) (activate-mark)
9713 (let (current-prefix-arg)
9714 (call-interactively 'org-store-link))
9715 (move-beginning-of-line 2)
9716 (set-mark (point)))))
9717 (org-with-limited-levels
9718 (setq org-store-link-plist nil)
9719 (let (link cpltxt desc description search
9720 txt custom-id agenda-link sfuns sfunsn)
9721 (cond
9723 ;; Store a link using an external link type
9724 ((and (not (equal arg '(16)))
9725 (setq sfuns
9726 (delq
9727 nil (mapcar (lambda (f)
9728 (let (fs) (if (funcall f) (push f fs))))
9729 org-store-link-functions))
9730 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9731 (or (and (cdr sfuns)
9732 (funcall (intern
9733 (completing-read
9734 "Which function for creating the link? "
9735 sfunsn nil t (car sfunsn)))))
9736 (funcall (caar sfuns)))
9737 (setq link (plist-get org-store-link-plist :link)
9738 desc (or (plist-get org-store-link-plist
9739 :description) link))))
9741 ;; Store a link from a source code buffer.
9742 ((org-src-edit-buffer-p)
9743 (cond
9744 ((save-excursion
9745 (beginning-of-line)
9746 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9747 "[ \t]*$")))
9748 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9749 ((org-called-interactively-p 'any)
9750 (let (label)
9751 (while (or (not label)
9752 (org-with-wide-buffer
9753 (goto-char (point-min))
9754 (re-search-forward
9755 (regexp-quote (format org-coderef-label-format label))
9756 nil t)))
9757 (when label (message "Label exists already") (sit-for 2))
9758 (setq label (read-string "Code line label: " label)))
9759 (end-of-line)
9760 (setq link (format org-coderef-label-format label))
9761 (let ((gc (- 79 (length link))))
9762 (if (< (current-column) gc) (org-move-to-column gc t)
9763 (insert " ")))
9764 (insert link)
9765 (setq link (concat "(" label ")") desc nil)))
9766 (t (setq link nil))))
9768 ;; We are in the agenda, link to referenced location
9769 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9770 (let ((m (or (get-text-property (point) 'org-hd-marker)
9771 (get-text-property (point) 'org-marker))))
9772 (when m
9773 (org-with-point-at m
9774 (setq agenda-link
9775 (if (org-called-interactively-p 'any)
9776 (call-interactively 'org-store-link)
9777 (org-store-link nil)))))))
9779 ((eq major-mode 'calendar-mode)
9780 (let ((cd (calendar-cursor-to-date)))
9781 (setq link
9782 (format-time-string
9783 (car org-time-stamp-formats)
9784 (apply 'encode-time
9785 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9786 nil nil nil))))
9787 (org-store-link-props :type "calendar" :date cd)))
9789 ((eq major-mode 'help-mode)
9790 (setq link (concat "help:" (save-excursion
9791 (goto-char (point-min))
9792 (looking-at "^[^ ]+")
9793 (match-string 0))))
9794 (org-store-link-props :type "help"))
9796 ((eq major-mode 'w3-mode)
9797 (setq cpltxt (if (and (buffer-name)
9798 (not (string-match "Untitled" (buffer-name))))
9799 (buffer-name)
9800 (url-view-url t))
9801 link (url-view-url t))
9802 (org-store-link-props :type "w3" :url (url-view-url t)))
9804 ((eq major-mode 'image-mode)
9805 (setq cpltxt (concat "file:"
9806 (abbreviate-file-name buffer-file-name))
9807 link cpltxt)
9808 (org-store-link-props :type "image" :file buffer-file-name))
9810 ;; In dired, store a link to the file of the current line
9811 ((derived-mode-p 'dired-mode)
9812 (let ((file (dired-get-filename nil t)))
9813 (setq file (if file
9814 (abbreviate-file-name
9815 (expand-file-name (dired-get-filename nil t)))
9816 ;; otherwise, no file so use current directory.
9817 default-directory))
9818 (setq cpltxt (concat "file:" file)
9819 link cpltxt)))
9821 ((setq search (run-hook-with-args-until-success
9822 'org-create-file-search-functions))
9823 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9824 "::" search))
9825 (setq cpltxt (or description link)))
9827 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9828 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9829 (cond
9830 ;; Store a link using the target at point
9831 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9832 (setq cpltxt
9833 (concat "file:"
9834 (abbreviate-file-name
9835 (buffer-file-name (buffer-base-buffer)))
9836 "::" (match-string 1))
9837 link cpltxt))
9838 ((and (featurep 'org-id)
9839 (or (eq org-id-link-to-org-use-id t)
9840 (and (org-called-interactively-p 'any)
9841 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9842 (and (eq org-id-link-to-org-use-id
9843 'create-if-interactive-and-no-custom-id)
9844 (not custom-id))))
9845 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9846 ;; Store a link using the ID at point
9847 (setq link (condition-case nil
9848 (prog1 (org-id-store-link)
9849 (setq desc (or (plist-get org-store-link-plist
9850 :description)
9851 "")))
9852 (error
9853 ;; Probably before first headline, link only to file
9854 (concat "file:"
9855 (abbreviate-file-name
9856 (buffer-file-name (buffer-base-buffer))))))))
9858 ;; Just link to current headline
9859 (setq cpltxt (concat "file:"
9860 (abbreviate-file-name
9861 (buffer-file-name (buffer-base-buffer)))))
9862 ;; Add a context search string
9863 (when (org-xor org-context-in-file-links arg)
9864 (let* ((ee (org-element-at-point))
9865 (et (org-element-type ee))
9866 (ev (plist-get (cadr ee) :value))
9867 (ek (plist-get (cadr ee) :key))
9868 (eok (and (stringp ek) (string-match "name" ek))))
9869 (setq txt (cond
9870 ((org-at-heading-p) nil)
9871 ((and (eq et 'keyword) eok) ev)
9872 ((org-region-active-p)
9873 (buffer-substring (region-beginning) (region-end)))))
9874 (when (or (null txt) (string-match "\\S-" txt))
9875 (setq cpltxt
9876 (concat cpltxt "::"
9877 (condition-case nil
9878 (org-make-org-heading-search-string txt)
9879 (error "")))
9880 desc (or (and (eq et 'keyword) eok ev)
9881 (nth 4 (ignore-errors (org-heading-components)))
9882 "NONE")))))
9883 (if (string-match "::\\'" cpltxt)
9884 (setq cpltxt (substring cpltxt 0 -2)))
9885 (setq link cpltxt))))
9887 ((buffer-file-name (buffer-base-buffer))
9888 ;; Just link to this file here.
9889 (setq cpltxt (concat "file:"
9890 (abbreviate-file-name
9891 (buffer-file-name (buffer-base-buffer)))))
9892 ;; Add a context string.
9893 (when (org-xor org-context-in-file-links arg)
9894 (setq txt (if (org-region-active-p)
9895 (buffer-substring (region-beginning) (region-end))
9896 (buffer-substring (point-at-bol) (point-at-eol))))
9897 ;; Only use search option if there is some text.
9898 (when (string-match "\\S-" txt)
9899 (setq cpltxt
9900 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9901 desc "NONE")))
9902 (setq link cpltxt))
9904 ((org-called-interactively-p 'interactive)
9905 (user-error "No method for storing a link from this buffer"))
9907 (t (setq link nil)))
9909 ;; We're done setting link and desc, clean up
9910 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9911 (setq link (or link cpltxt)
9912 desc (or desc cpltxt))
9913 (cond ((equal desc "NONE") (setq desc nil))
9914 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9915 (let ((d0 (match-string 3 desc))
9916 (p0 (match-string 5 desc)))
9917 (setq desc
9918 (replace-regexp-in-string
9919 org-bracket-link-regexp
9920 (concat (or p0 d0)
9921 (if (equal (length (match-string 0 desc))
9922 (length desc)) "*" "")) desc)))))
9924 ;; Return the link
9925 (if (not (and (or (org-called-interactively-p 'any)
9926 executing-kbd-macro) link))
9927 (or agenda-link (and link (org-make-link-string link desc)))
9928 (push (list link desc) org-stored-links)
9929 (message "Stored: %s" (or desc link))
9930 (when custom-id
9931 (setq link (concat "file:" (abbreviate-file-name
9932 (buffer-file-name)) "::#" custom-id))
9933 (push (list link desc) org-stored-links))
9934 (car org-stored-links))))))
9936 (defun org-store-link-props (&rest plist)
9937 "Store link properties, extract names and addresses."
9938 (let (x adr)
9939 (when (setq x (plist-get plist :from))
9940 (setq adr (mail-extract-address-components x))
9941 (setq plist (plist-put plist :fromname (car adr)))
9942 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9943 (when (setq x (plist-get plist :to))
9944 (setq adr (mail-extract-address-components x))
9945 (setq plist (plist-put plist :toname (car adr)))
9946 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9947 (let ((from (plist-get plist :from))
9948 (to (plist-get plist :to)))
9949 (when (and from to org-from-is-user-regexp)
9950 (setq plist
9951 (plist-put plist :fromto
9952 (if (string-match org-from-is-user-regexp from)
9953 (concat "to %t")
9954 (concat "from %f"))))))
9955 (setq org-store-link-plist plist))
9957 (defun org-add-link-props (&rest plist)
9958 "Add these properties to the link property list."
9959 (let (key value)
9960 (while plist
9961 (setq key (pop plist) value (pop plist))
9962 (setq org-store-link-plist
9963 (plist-put org-store-link-plist key value)))))
9965 (defun org-email-link-description (&optional fmt)
9966 "Return the description part of an email link.
9967 This takes information from `org-store-link-plist' and formats it
9968 according to FMT (default from `org-email-link-description-format')."
9969 (setq fmt (or fmt org-email-link-description-format))
9970 (let* ((p org-store-link-plist)
9971 (to (plist-get p :toaddress))
9972 (from (plist-get p :fromaddress))
9973 (table
9974 (list
9975 (cons "%c" (plist-get p :fromto))
9976 (cons "%F" (plist-get p :from))
9977 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9978 (cons "%T" (plist-get p :to))
9979 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9980 (cons "%s" (plist-get p :subject))
9981 (cons "%d" (plist-get p :date))
9982 (cons "%m" (plist-get p :message-id)))))
9983 (when (string-match "%c" fmt)
9984 ;; Check if the user wrote this message
9985 (if (and org-from-is-user-regexp from to
9986 (save-match-data (string-match org-from-is-user-regexp from)))
9987 (setq fmt (replace-match "to %t" t t fmt))
9988 (setq fmt (replace-match "from %f" t t fmt))))
9989 (org-replace-escapes fmt table)))
9991 (defun org-make-org-heading-search-string (&optional string)
9992 "Make search string for the current headline or STRING."
9993 (let ((s (or string
9994 (and (derived-mode-p 'org-mode)
9995 (save-excursion
9996 (org-back-to-heading t)
9997 (org-element-property :raw-value (org-element-at-point))))))
9998 (lines org-context-in-file-links))
9999 (or string (setq s (concat "*" s))) ; Add * for headlines
10000 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10001 (when (and string (integerp lines) (> lines 0))
10002 (let ((slines (org-split-string s "\n")))
10003 (when (< lines (length slines))
10004 (setq s (mapconcat
10005 'identity
10006 (reverse (nthcdr (- (length slines) lines)
10007 (reverse slines))) "\n")))))
10008 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10010 (defun org-make-link-string (link &optional description)
10011 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10012 (unless (org-string-nw-p link) (error "Empty link"))
10013 (let ((uri (cond ((string-match org-link-types-re link)
10014 (concat (match-string 1 link)
10015 (org-link-escape (substring link (match-end 1)))))
10016 ;; For readability, url-encode internal links only
10017 ;; when absolutely needed (i.e, when they contain
10018 ;; square brackets). File links however, are
10019 ;; encoded since, e.g., spaces are significant.
10020 ((or (file-name-absolute-p link)
10021 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10022 (org-link-escape link))
10023 (t link)))
10024 (description
10025 (and (org-string-nw-p description)
10026 ;; Remove brackets from description, as they are fatal.
10027 (replace-regexp-in-string
10028 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10029 (org-trim description)))))
10030 (format "[[%s]%s]"
10032 (if description (format "[%s]" description) ""))))
10034 (defconst org-link-escape-chars
10035 ;;%20 %5B %5D %25
10036 '(?\s ?\[ ?\] ?%)
10037 "List of characters that should be escaped in a link when stored to Org.
10038 This is the list that is used for internal purposes.")
10040 (defconst org-link-escape-chars-browser
10041 ;;%20 %22
10042 '(?\s ?\")
10043 "List of characters to be escaped before handing over to the browser.
10044 If you consider using this constant then you probably want to use
10045 the function `org-link-escape-browser' instead. See there why
10046 this constant is a candidate to be removed once Org drops support
10047 for Emacs 24.1 and 24.2.")
10049 (defun org-link-escape (text &optional table merge)
10050 "Return percent escaped representation of TEXT.
10051 TEXT is a string with the text to escape.
10052 Optional argument TABLE is a list with characters that should be
10053 escaped. When nil, `org-link-escape-chars' is used.
10054 If optional argument MERGE is set, merge TABLE into
10055 `org-link-escape-chars'."
10056 (let ((characters-to-encode
10057 (cond ((null table) org-link-escape-chars)
10058 (merge (append org-link-escape-chars table))
10059 (t table))))
10060 (mapconcat
10061 (lambda (c)
10062 (if (or (memq c characters-to-encode)
10063 (and org-url-hexify-p (or (< c 32) (> c 126))))
10064 (mapconcat (lambda (e) (format "%%%.2X" e))
10065 (or (encode-coding-char c 'utf-8)
10066 (error "Unable to percent escape character: %c" c))
10068 (char-to-string c)))
10069 text "")))
10071 (defun org-link-escape-browser (text)
10072 "Escape some characters before handing over to the browser.
10073 This function is a candidate to be removed together with the
10074 constant `org-link-escape-chars-browser' once Org drops support
10075 for Emacs 24.1 and 24.2. All calls to this function will have to
10076 be replaced with `url-encode-url' which is available since Emacs
10077 24.3.1."
10078 ;; Example with the Org link
10079 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10080 ;; to open the browser with +subject:"Release 8.2" filled into the
10081 ;; query field: In this case the variable TEXT contains the
10082 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10083 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10084 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10085 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10086 (if (fboundp 'url-encode-url)
10087 (url-encode-url text)
10088 (if (org-string-match-p
10089 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10090 text)
10091 (org-link-escape text org-link-escape-chars-browser)
10092 text)))
10094 (defun org-link-unescape (str)
10095 "Unhex hexified Unicode parts in string STR.
10096 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10097 reciprocal of `org-link-escape', which see."
10098 (if (org-string-nw-p str)
10099 (replace-regexp-in-string
10100 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10101 str))
10103 (defun org-link-unescape-compound (hex)
10104 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10105 Note: this function also decodes single byte encodings like
10106 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10107 (save-match-data
10108 (let* ((bytes (cdr (split-string hex "%")))
10109 (ret "")
10110 (eat 0)
10111 (sum 0))
10112 (while bytes
10113 (let* ((val (string-to-number (pop bytes) 16))
10114 (shift-xor
10115 (if (= 0 eat)
10116 (cond
10117 ((>= val 252) (cons 6 252))
10118 ((>= val 248) (cons 5 248))
10119 ((>= val 240) (cons 4 240))
10120 ((>= val 224) (cons 3 224))
10121 ((>= val 192) (cons 2 192))
10122 (t (cons 0 0)))
10123 (cons 6 128))))
10124 (if (>= val 192) (setq eat (car shift-xor)))
10125 (setq val (logxor val (cdr shift-xor)))
10126 (setq sum (+ (lsh sum (car shift-xor)) val))
10127 (if (> eat 0) (setq eat (- eat 1)))
10128 (cond
10129 ((= 0 eat) ;multi byte
10130 (setq ret (concat ret (org-char-to-string sum)))
10131 (setq sum 0))
10132 ((not bytes) ; single byte(s)
10133 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10134 ret)))
10136 (defun org-link-unescape-single-byte-sequence (hex)
10137 "Unhexify hex-encoded single byte character sequences."
10138 (mapconcat (lambda (byte)
10139 (char-to-string (string-to-number byte 16)))
10140 (cdr (split-string hex "%")) ""))
10142 (defun org-xor (a b)
10143 "Exclusive or."
10144 (if a (not b) b))
10146 (defun org-fixup-message-id-for-http (s)
10147 "Replace special characters in a message id, so it can be used in an http query."
10148 (when (string-match "%" s)
10149 (setq s (mapconcat (lambda (c)
10150 (if (eq c ?%)
10151 "%25"
10152 (char-to-string c)))
10153 s "")))
10154 (while (string-match "<" s)
10155 (setq s (replace-match "%3C" t t s)))
10156 (while (string-match ">" s)
10157 (setq s (replace-match "%3E" t t s)))
10158 (while (string-match "@" s)
10159 (setq s (replace-match "%40" t t s)))
10162 (defun org-link-prettify (link)
10163 "Return a human-readable representation of LINK.
10164 The car of LINK must be a raw link.
10165 The cdr of LINK must be either a link description or nil."
10166 (let ((desc (or (cadr link) "<no description>")))
10167 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10168 "<" (car link) ">")))
10170 ;;;###autoload
10171 (defun org-insert-link-global ()
10172 "Insert a link like Org-mode does.
10173 This command can be called in any mode to insert a link in Org-mode syntax."
10174 (interactive)
10175 (org-load-modules-maybe)
10176 (org-run-like-in-org-mode 'org-insert-link))
10178 (defun org-insert-all-links (arg &optional pre post)
10179 "Insert all links in `org-stored-links'.
10180 When a universal prefix, do not delete the links from `org-stored-links'.
10181 When `ARG' is a number, insert the last N link(s).
10182 `PRE' and `POST' are optional arguments to define a string to
10183 prepend or to append."
10184 (interactive "P")
10185 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10186 (links (copy-seq org-stored-links))
10187 (pr (or pre "- "))
10188 (po (or post "\n"))
10189 (cnt 1) l)
10190 (if (null org-stored-links)
10191 (message "No link to insert")
10192 (while (and (or (listp arg) (>= arg cnt))
10193 (setq l (if (listp arg)
10194 (pop links)
10195 (pop org-stored-links))))
10196 (setq cnt (1+ cnt))
10197 (insert pr)
10198 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10199 (insert po)))))
10201 (defun org-insert-last-stored-link (arg)
10202 "Insert the last link stored in `org-stored-links'."
10203 (interactive "p")
10204 (org-insert-all-links arg "" "\n"))
10206 (defun org-link-fontify-links-to-this-file ()
10207 "Fontify links to the current file in `org-stored-links'."
10208 (let ((f (buffer-file-name)) a b)
10209 (setq a (mapcar (lambda(l)
10210 (let ((ll (car l)))
10211 (when (and (string-match "^file:\\(.+\\)::" ll)
10212 (equal f (expand-file-name (match-string 1 ll))))
10213 ll)))
10214 org-stored-links))
10215 (when (featurep 'org-id)
10216 (setq b (mapcar (lambda(l)
10217 (let ((ll (car l)))
10218 (when (and (string-match "^id:\\(.+\\)$" ll)
10219 (equal f (expand-file-name
10220 (or (org-id-find-id-file
10221 (match-string 1 ll)) ""))))
10222 ll)))
10223 org-stored-links)))
10224 (mapcar (lambda(l)
10225 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10226 (delq nil (append a b)))))
10228 (defvar org-link-links-in-this-file nil)
10229 (defun org-insert-link (&optional complete-file link-location default-description)
10230 "Insert a link. At the prompt, enter the link.
10232 Completion can be used to insert any of the link protocol prefixes like
10233 http or ftp in use.
10235 The history can be used to select a link previously stored with
10236 `org-store-link'. When the empty string is entered (i.e. if you just
10237 press RET at the prompt), the link defaults to the most recently
10238 stored link. As SPC triggers completion in the minibuffer, you need to
10239 use M-SPC or C-q SPC to force the insertion of a space character.
10241 You will also be prompted for a description, and if one is given, it will
10242 be displayed in the buffer instead of the link.
10244 If there is already a link at point, this command will allow you to edit link
10245 and description parts.
10247 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10248 be selected using completion. The path to the file will be relative to the
10249 current directory if the file is in the current directory or a subdirectory.
10250 Otherwise, the link will be the absolute path as completed in the minibuffer
10251 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10252 option `org-link-file-path-type'.
10254 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10255 the current directory or below.
10257 With three \\[universal-argument] prefixes, negate the meaning of
10258 `org-keep-stored-link-after-insertion'.
10260 If `org-make-link-description-function' is non-nil, this function will be
10261 called with the link target, and the result will be the default
10262 link description.
10264 If the LINK-LOCATION parameter is non-nil, this value will be
10265 used as the link location instead of reading one interactively.
10267 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10268 be used as the default description."
10269 (interactive "P")
10270 (let* ((wcf (current-window-configuration))
10271 (origbuf (current-buffer))
10272 (region (if (org-region-active-p)
10273 (buffer-substring (region-beginning) (region-end))))
10274 (remove (and region (list (region-beginning) (region-end))))
10275 (desc region)
10276 tmphist ; byte-compile incorrectly complains about this
10277 (link link-location)
10278 (abbrevs org-link-abbrev-alist-local)
10279 entry file all-prefixes auto-desc)
10280 (cond
10281 (link-location) ; specified by arg, just use it.
10282 ((org-in-regexp org-bracket-link-regexp 1)
10283 ;; We do have a link at point, and we are going to edit it.
10284 (setq remove (list (match-beginning 0) (match-end 0)))
10285 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10286 (setq link (read-string "Link: "
10287 (org-link-unescape
10288 (org-match-string-no-properties 1)))))
10289 ((or (org-in-regexp org-angle-link-re)
10290 (org-in-regexp org-plain-link-re))
10291 ;; Convert to bracket link
10292 (setq remove (list (match-beginning 0) (match-end 0))
10293 link (read-string "Link: "
10294 (org-remove-angle-brackets (match-string 0)))))
10295 ((member complete-file '((4) (16)))
10296 ;; Completing read for file names.
10297 (setq link (org-file-complete-link complete-file)))
10299 ;; Read link, with completion for stored links.
10300 (org-link-fontify-links-to-this-file)
10301 (org-switch-to-buffer-other-window "*Org Links*")
10302 (with-current-buffer "*Org Links*"
10303 (erase-buffer)
10304 (insert "Insert a link.
10305 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10306 (when org-stored-links
10307 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10308 (insert (mapconcat 'org-link-prettify
10309 (reverse org-stored-links) "\n")))
10310 (goto-char (point-min)))
10311 (let ((cw (selected-window)))
10312 (select-window (get-buffer-window "*Org Links*" 'visible))
10313 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10314 (unless (pos-visible-in-window-p (point-max))
10315 (org-fit-window-to-buffer))
10316 (and (window-live-p cw) (select-window cw)))
10317 ;; Fake a link history, containing the stored links.
10318 (setq tmphist (append (mapcar 'car org-stored-links)
10319 org-insert-link-history))
10320 (setq all-prefixes (append (mapcar 'car abbrevs)
10321 (mapcar 'car org-link-abbrev-alist)
10322 org-link-types))
10323 (unwind-protect
10324 (progn
10325 (setq link
10326 (org-completing-read
10327 "Link: "
10328 (append
10329 (mapcar (lambda (x) (concat x ":"))
10330 all-prefixes)
10331 (mapcar 'car org-stored-links))
10332 nil nil nil
10333 'tmphist
10334 (caar org-stored-links)))
10335 (if (not (string-match "\\S-" link))
10336 (user-error "No link selected"))
10337 (mapc (lambda(l)
10338 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10339 org-stored-links)
10340 (if (or (member link all-prefixes)
10341 (and (equal ":" (substring link -1))
10342 (member (substring link 0 -1) all-prefixes)
10343 (setq link (substring link 0 -1))))
10344 (setq link (with-current-buffer origbuf
10345 (org-link-try-special-completion link)))))
10346 (set-window-configuration wcf)
10347 (kill-buffer "*Org Links*"))
10348 (setq entry (assoc link org-stored-links))
10349 (or entry (push link org-insert-link-history))
10350 (setq desc (or desc (nth 1 entry)))))
10352 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10353 (not org-keep-stored-link-after-insertion))
10354 (setq org-stored-links (delq (assoc link org-stored-links)
10355 org-stored-links)))
10357 (if (and (string-match org-plain-link-re link)
10358 (not (string-match org-ts-regexp link)))
10359 ;; URL-like link, normalize the use of angular brackets.
10360 (setq link (org-remove-angle-brackets link)))
10362 ;; Check if we are linking to the current file with a search
10363 ;; option If yes, simplify the link by using only the search
10364 ;; option.
10365 (when (and buffer-file-name
10366 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10367 (let* ((path (match-string 1 link))
10368 (case-fold-search nil)
10369 (search (match-string 2 link)))
10370 (save-match-data
10371 (if (equal (file-truename buffer-file-name) (file-truename path))
10372 ;; We are linking to this same file, with a search option
10373 (setq link search)))))
10375 ;; Check if we can/should use a relative path. If yes, simplify the link
10376 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10377 (let* ((type (match-string 1 link))
10378 (path (match-string 2 link))
10379 (origpath path)
10380 (case-fold-search nil))
10381 (cond
10382 ((or (eq org-link-file-path-type 'absolute)
10383 (equal complete-file '(16)))
10384 (setq path (abbreviate-file-name (expand-file-name path))))
10385 ((eq org-link-file-path-type 'noabbrev)
10386 (setq path (expand-file-name path)))
10387 ((eq org-link-file-path-type 'relative)
10388 (setq path (file-relative-name path)))
10390 (save-match-data
10391 (if (string-match (concat "^" (regexp-quote
10392 (expand-file-name
10393 (file-name-as-directory
10394 default-directory))))
10395 (expand-file-name path))
10396 ;; We are linking a file with relative path name.
10397 (setq path (substring (expand-file-name path)
10398 (match-end 0)))
10399 (setq path (abbreviate-file-name (expand-file-name path)))))))
10400 (setq link (concat type path))
10401 (if (equal desc origpath)
10402 (setq desc path))))
10404 (if org-make-link-description-function
10405 (setq desc
10406 (or (condition-case nil
10407 (funcall org-make-link-description-function link desc)
10408 (error (progn (message "Can't get link description from `%s'"
10409 (symbol-name org-make-link-description-function))
10410 (sit-for 2) nil)))
10411 (read-string "Description: " default-description)))
10412 (if default-description (setq desc default-description)
10413 (setq desc (or (and auto-desc desc)
10414 (read-string "Description: " desc)))))
10416 (unless (string-match "\\S-" desc) (setq desc nil))
10417 (if remove (apply 'delete-region remove))
10418 (insert (org-make-link-string link desc))))
10420 (defun org-link-try-special-completion (type)
10421 "If there is completion support for link type TYPE, offer it."
10422 (let ((fun (intern (concat "org-" type "-complete-link"))))
10423 (if (functionp fun)
10424 (funcall fun)
10425 (read-string "Link (no completion support): " (concat type ":")))))
10427 (defun org-file-complete-link (&optional arg)
10428 "Create a file link using completion."
10429 (let ((file (org-iread-file-name "File: "))
10430 (pwd (file-name-as-directory (expand-file-name ".")))
10431 (pwd1 (file-name-as-directory (abbreviate-file-name
10432 (expand-file-name ".")))))
10433 (cond ((equal arg '(16))
10434 (concat "file:"
10435 (abbreviate-file-name (expand-file-name file))))
10436 ((string-match
10437 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10438 (concat "file:" (match-string 1 file)))
10439 ((string-match
10440 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10441 (expand-file-name file))
10442 (concat "file:"
10443 (match-string 1 (expand-file-name file))))
10444 (t (concat "file:" file)))))
10446 (defun org-iread-file-name (&rest args)
10447 "Read-file-name using `ido-mode' speedup if available.
10448 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10449 See `read-file-name' for a description of parameters."
10450 (org-without-partial-completion
10451 (if (and org-completion-use-ido
10452 (fboundp 'ido-read-file-name)
10453 (org-bound-and-true-p ido-mode)
10454 (listp (nth 1 args)))
10455 (let ((ido-enter-matching-directory nil))
10456 (apply #'ido-read-file-name args))
10457 (apply #'read-file-name args))))
10459 (defun org-completing-read (&rest args)
10460 "Completing-read with SPACE being a normal character."
10461 (let ((enable-recursive-minibuffers t)
10462 (minibuffer-local-completion-map
10463 (copy-keymap minibuffer-local-completion-map)))
10464 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10465 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10466 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10467 (apply 'org-icompleting-read args)))
10469 (defun org-completing-read-no-i (&rest args)
10470 (let (org-completion-use-ido org-completion-use-iswitchb)
10471 (apply 'org-completing-read args)))
10473 (defun org-iswitchb-completing-read (prompt choices &rest args)
10474 "Use iswitch as a completing-read replacement to choose from choices.
10475 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10476 from."
10477 (let* ((iswitchb-use-virtual-buffers nil)
10478 (iswitchb-make-buflist-hook
10479 (lambda ()
10480 (setq iswitchb-temp-buflist choices))))
10481 (iswitchb-read-buffer prompt)))
10483 (defun org-icompleting-read (&rest args)
10484 "Completing-read using `ido-mode' or `iswitchb' speedups if available.
10485 Should be called like `completing-read'."
10486 (org-without-partial-completion
10487 (if (not (listp (nth 1 args)))
10488 ;; Ido only supports lists as the COLLECTION argument. Use
10489 ;; default completion function when second argument is not
10490 ;; a list.
10491 (apply #'completing-read args)
10492 (let ((ido-enter-matching-directory nil))
10493 (apply (cond ((and org-completion-use-ido
10494 (fboundp 'ido-completing-read)
10495 (org-bound-and-true-p ido-mode))
10496 #'ido-completing-read)
10497 ((and org-completion-use-iswitchb
10498 (org-bound-and-true-p iswitchb-mode))
10499 #'org-iswitchb-completing-read)
10500 (t #'completing-read))
10501 args)))))
10503 ;;; Opening/following a link
10505 (defvar org-link-search-failed nil)
10507 (defvar org-open-link-functions nil
10508 "Hook for functions finding a plain text link.
10509 These functions must take a single argument, the link content.
10510 They will be called for links that look like [[link text][description]]
10511 when LINK TEXT does not have a protocol like \"http:\" and does not look
10512 like a filename (e.g. \"./blue.png\").
10514 These functions will be called *before* Org attempts to resolve the
10515 link by doing text searches in the current buffer - so if you want a
10516 link \"[[target]]\" to still find \"<<target>>\", your function should
10517 handle this as a special case.
10519 When the function does handle the link, it must return a non-nil value.
10520 If it decides that it is not responsible for this link, it must return
10521 nil to indicate that that Org-mode can continue with other options
10522 like exact and fuzzy text search.")
10524 (defun org-next-link (&optional search-backward)
10525 "Move forward to the next link.
10526 If the link is in hidden text, expose it."
10527 (interactive "P")
10528 (when (and org-link-search-failed (eq this-command last-command))
10529 (goto-char (point-min))
10530 (message "Link search wrapped back to beginning of buffer"))
10531 (setq org-link-search-failed nil)
10532 (let* ((pos (point))
10533 (ct (org-context))
10534 (a (assoc :link ct))
10535 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10536 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10537 ((looking-at org-any-link-re)
10538 ;; Don't stay stuck at link without an org-link face
10539 (forward-char (if search-backward -1 1))))
10540 (if (funcall srch-fun org-any-link-re nil t)
10541 (progn
10542 (goto-char (match-beginning 0))
10543 (if (outline-invisible-p) (org-show-context)))
10544 (goto-char pos)
10545 (setq org-link-search-failed t)
10546 (message "No further link found"))))
10548 (defun org-previous-link ()
10549 "Move backward to the previous link.
10550 If the link is in hidden text, expose it."
10551 (interactive)
10552 (funcall 'org-next-link t))
10554 (defun org-translate-link (s)
10555 "Translate a link string if a translation function has been defined."
10556 (if (and org-link-translation-function
10557 (fboundp org-link-translation-function)
10558 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10559 (progn
10560 (setq s (funcall org-link-translation-function
10561 (match-string 1 s) (match-string 2 s)))
10562 (concat (car s) ":" (cdr s)))
10565 (defun org-translate-link-from-planner (type path)
10566 "Translate a link from Emacs Planner syntax so that Org can follow it.
10567 This is still an experimental function, your mileage may vary."
10568 (cond
10569 ((member type '("http" "https" "news" "ftp"))
10570 ;; standard Internet links are the same.
10571 nil)
10572 ((and (equal type "irc") (string-match "^//" path))
10573 ;; Planner has two / at the beginning of an irc link, we have 1.
10574 ;; We should have zero, actually....
10575 (setq path (substring path 1)))
10576 ((and (equal type "lisp") (string-match "^/" path))
10577 ;; Planner has a slash, we do not.
10578 (setq type "elisp" path (substring path 1)))
10579 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10580 ;; A typical message link. Planner has the id after the final slash,
10581 ;; we separate it with a hash mark
10582 (setq path (concat (match-string 1 path) "#"
10583 (org-remove-angle-brackets (match-string 2 path))))))
10584 (cons type path))
10586 (defun org-find-file-at-mouse (ev)
10587 "Open file link or URL at mouse."
10588 (interactive "e")
10589 (mouse-set-point ev)
10590 (org-open-at-point 'in-emacs))
10592 (defun org-open-at-mouse (ev)
10593 "Open file link or URL at mouse.
10594 See the docstring of `org-open-file' for details."
10595 (interactive "e")
10596 (mouse-set-point ev)
10597 (if (eq major-mode 'org-agenda-mode)
10598 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10599 (org-open-at-point))
10601 (defvar org-window-config-before-follow-link nil
10602 "The window configuration before following a link.
10603 This is saved in case the need arises to restore it.")
10605 (defvar org-open-link-marker (make-marker)
10606 "Marker pointing to the location where `org-open-at-point' was called.")
10608 ;;;###autoload
10609 (defun org-open-at-point-global ()
10610 "Follow a link like Org-mode does.
10611 This command can be called in any mode to follow a link that has
10612 Org-mode syntax."
10613 (interactive)
10614 (org-run-like-in-org-mode 'org-open-at-point))
10616 ;;;###autoload
10617 (defun org-open-link-from-string (s &optional arg reference-buffer)
10618 "Open a link in the string S, as if it was in Org-mode."
10619 (interactive "sLink: \nP")
10620 (let ((reference-buffer (or reference-buffer (current-buffer))))
10621 (with-temp-buffer
10622 (let ((org-inhibit-startup (not reference-buffer)))
10623 (org-mode)
10624 (insert s)
10625 (goto-char (point-min))
10626 (when reference-buffer
10627 (setq org-link-abbrev-alist-local
10628 (with-current-buffer reference-buffer
10629 org-link-abbrev-alist-local)))
10630 (org-open-at-point arg reference-buffer)))))
10632 (defvar org-open-at-point-functions nil
10633 "Hook that is run when following a link at point.
10635 Functions in this hook must return t if they identify and follow
10636 a link at point. If they don't find anything interesting at point,
10637 they must return nil.")
10639 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10640 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10641 (defun org-open-at-point (&optional arg reference-buffer)
10642 "Open link, timestamp, footnote or tags at point.
10644 When point is on a link, follow it. Normally, files will be
10645 opened by an appropriate application. If the optional prefix
10646 argument ARG is non-nil, Emacs will visit the file. With
10647 a double prefix argument, try to open outside of Emacs, in the
10648 application the system uses for this file type.
10650 When point is on a timestamp, open the agenda at the day
10651 specified.
10653 When point is a footnote definition, move to the first reference
10654 found. If it is on a reference, move to the associated
10655 definition.
10657 When point is on a headline, display a list of every link in the
10658 entry, so it is possible to pick one, or all, of them. If point
10659 is on a tag, call `org-tags-view' instead.
10661 When optional argument REFERENCE-BUFFER is non-nil, it should
10662 specify a buffer from where the link search should happen. This
10663 is used internally by `org-open-link-from-string'.
10665 On top of syntactically correct links, this function will open
10666 the link at point in comments or comment blocks and the first
10667 link in a property drawer line."
10668 (interactive "P")
10669 ;; On a code block, open block's results.
10670 (unless (call-interactively 'org-babel-open-src-block-result)
10671 (org-load-modules-maybe)
10672 (move-marker org-open-link-marker (point))
10673 (setq org-window-config-before-follow-link (current-window-configuration))
10674 (org-remove-occur-highlights nil nil t)
10675 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10676 (let* ((context
10677 ;; Only consider supported types, even if they are not
10678 ;; the closest one.
10679 (org-element-lineage
10680 (org-element-context)
10681 '(comment comment-block footnote-definition footnote-reference
10682 headline inlinetask keyword link node-property
10683 timestamp)
10685 (type (org-element-type context))
10686 (value (org-element-property :value context)))
10687 (cond
10688 ((not context) (user-error "No link found"))
10689 ;; Exception: open timestamps and links in properties
10690 ;; drawers, keywords and comments.
10691 ((memq type '(comment comment-block keyword node-property))
10692 (cond ((org-in-regexp org-any-link-re)
10693 (org-open-link-from-string (match-string-no-properties 0)))
10694 ((or (org-at-timestamp-p t) (org-at-date-range-p t))
10695 (org-follow-timestamp-link))
10696 (t (user-error "No link found"))))
10697 ;; On a headline or an inlinetask, but not on a timestamp,
10698 ;; a link, a footnote reference or on tags.
10699 ((and (memq type '(headline inlinetask))
10700 ;; Not on tags.
10701 (progn (save-excursion (beginning-of-line)
10702 (looking-at org-complex-heading-regexp))
10703 (or (not (match-beginning 5))
10704 (< (point) (match-beginning 5)))))
10705 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10706 (links (car data))
10707 (links-end (cdr data)))
10708 (if links
10709 (dolist (link (if (stringp links) (list links) links))
10710 (search-forward link nil links-end)
10711 (goto-char (match-beginning 0))
10712 (org-open-at-point))
10713 (require 'org-attach)
10714 (org-attach-reveal 'if-exists))))
10715 ;; Do nothing on white spaces after an object, unless point
10716 ;; is right after it.
10717 ((> (point)
10718 (save-excursion
10719 (goto-char (org-element-property :end context))
10720 (skip-chars-backward " \t")
10721 (point)))
10722 (user-error "No link found"))
10723 ((eq type 'timestamp) (org-follow-timestamp-link))
10724 ;; On tags within a headline or an inlinetask.
10725 ((and (memq type '(headline inlinetask))
10726 (progn (save-excursion (beginning-of-line)
10727 (looking-at org-complex-heading-regexp))
10728 (and (match-beginning 5)
10729 (>= (point) (match-beginning 5)))))
10730 (org-tags-view arg (substring (match-string 5) 0 -1)))
10731 ((eq type 'link)
10732 ;; When link is located within the description of another
10733 ;; link (e.g., an inline image), always open the parent
10734 ;; link.
10735 (let*((link (let ((up (org-element-property :parent context)))
10736 (if (eq (org-element-type up) 'link) up context)))
10737 (type (org-element-property :type link))
10738 (path (org-link-unescape (org-element-property :path link))))
10739 ;; Switch back to REFERENCE-BUFFER needed when called in
10740 ;; a temporary buffer through `org-open-link-from-string'.
10741 (with-current-buffer (or reference-buffer (current-buffer))
10742 (cond
10743 ((equal type "file")
10744 (if (string-match "[*?{]" (file-name-nondirectory path))
10745 (dired path)
10746 ;; Look into `org-link-protocols' in order to find
10747 ;; a DEDICATED-FUNCTION to open file. The function
10748 ;; will be applied on raw link instead of parsed
10749 ;; link due to the limitation in `org-add-link-type'
10750 ;; ("open" function called with a single argument).
10751 ;; If no such function is found, fallback to
10752 ;; `org-open-file'.
10754 ;; Note : "file+emacs" and "file+sys" types are
10755 ;; hard-coded in order to escape the previous
10756 ;; limitation.
10757 (let* ((option (org-element-property :search-option link))
10758 (app (org-element-property :application link))
10759 (dedicated-function
10760 (nth 1 (assoc app org-link-protocols))))
10761 (if dedicated-function
10762 (funcall dedicated-function
10763 (concat path
10764 (and option (concat "::" option))))
10765 (apply 'org-open-file
10766 path
10767 (cond (arg)
10768 ((equal app "emacs") 'emacs)
10769 ((equal app "sys") 'system))
10770 (cond ((not option) nil)
10771 ((org-string-match-p "\\`[0-9]+\\'" option)
10772 (list (string-to-number option)))
10773 (t (list nil
10774 (org-link-unescape option)))))))))
10775 ((assoc type org-link-protocols)
10776 (funcall (nth 1 (assoc type org-link-protocols)) path))
10777 ((equal type "help")
10778 (let ((f-or-v (intern path)))
10779 (cond ((fboundp f-or-v) (describe-function f-or-v))
10780 ((boundp f-or-v) (describe-variable f-or-v))
10781 (t (error "Not a known function or variable")))))
10782 ((member type '("http" "https" "ftp" "mailto" "news"))
10783 (browse-url (org-link-escape-browser (concat type ":" path))))
10784 ((equal type "doi")
10785 (browse-url
10786 (org-link-escape-browser (concat org-doi-server-url path))))
10787 ((equal type "message") (browse-url (concat type ":" path)))
10788 ((equal type "shell")
10789 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10790 (cmd path))
10791 (if (or (and (org-string-nw-p
10792 org-confirm-shell-link-not-regexp)
10793 (string-match
10794 org-confirm-shell-link-not-regexp cmd))
10795 (not org-confirm-shell-link-function)
10796 (funcall org-confirm-shell-link-function
10797 (format "Execute \"%s\" in shell? "
10798 (org-add-props cmd nil
10799 'face 'org-warning))))
10800 (progn
10801 (message "Executing %s" cmd)
10802 (shell-command cmd buf)
10803 (when (featurep 'midnight)
10804 (setq clean-buffer-list-kill-buffer-names
10805 (cons (buffer-name buf)
10806 clean-buffer-list-kill-buffer-names))))
10807 (user-error "Abort"))))
10808 ((equal type "elisp")
10809 (let ((cmd path))
10810 (if (or (and (org-string-nw-p
10811 org-confirm-elisp-link-not-regexp)
10812 (org-string-match-p
10813 org-confirm-elisp-link-not-regexp cmd))
10814 (not org-confirm-elisp-link-function)
10815 (funcall org-confirm-elisp-link-function
10816 (format "Execute \"%s\" as elisp? "
10817 (org-add-props cmd nil
10818 'face 'org-warning))))
10819 (message "%s => %s" cmd
10820 (if (eq (string-to-char cmd) ?\()
10821 (eval (read cmd))
10822 (call-interactively (read cmd))))
10823 (user-error "Abort"))))
10824 ((equal type "id")
10825 (require 'ord-id)
10826 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10827 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10828 (unless (run-hook-with-args-until-success
10829 'org-open-link-functions path)
10830 (if (not arg) (org-mark-ring-push)
10831 (switch-to-buffer-other-window
10832 (org-get-buffer-for-internal-link (current-buffer))))
10833 (let ((cmd `(org-link-search
10834 ,(if (member type '("custom-id" "coderef"))
10835 (org-element-property :raw-link link)
10836 path)
10837 ,(cond ((equal arg '(4)) 'occur)
10838 ((equal arg '(16)) 'org-occur))
10839 ,(org-element-property :begin link))))
10840 (condition-case nil
10841 (let ((org-link-search-inhibit-query t))
10842 (eval cmd))
10843 (error (progn (widen) (eval cmd)))))))
10844 (t (browse-url-at-point))))))
10845 ;; On a footnote reference or at a footnote definition's label.
10846 ((or (eq type 'footnote-reference)
10847 (and (eq type 'footnote-definition)
10848 (save-excursion
10849 ;; Do not validate action when point is on the
10850 ;; spaces right after the footnote label, in
10851 ;; order to be on par with behaviour on links.
10852 (skip-chars-forward " \t")
10853 (let ((begin
10854 (org-element-property :contents-begin context)))
10855 (if begin (< (point) begin)
10856 (= (org-element-property :post-affiliated context)
10857 (line-beginning-position)))))))
10858 (org-footnote-action))
10859 (t (user-error "No link found")))))
10860 (move-marker org-open-link-marker nil)
10861 (run-hook-with-args 'org-follow-link-hook)))
10863 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10864 "Offer links in the current entry and return the selected link.
10865 If there is only one link, return it.
10866 If NTH is an integer, return the NTH link found.
10867 If ZERO is a string, check also this string for a link, and if
10868 there is one, return it."
10869 (with-current-buffer buffer
10870 (save-excursion
10871 (save-restriction
10872 (widen)
10873 (goto-char marker)
10874 (let ((cnt ?0)
10875 (in-emacs (if (integerp nth) nil nth))
10876 have-zero end links link c)
10877 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10878 (push (match-string 0 zero) links)
10879 (setq cnt (1- cnt) have-zero t))
10880 (save-excursion
10881 (org-back-to-heading t)
10882 (setq end (save-excursion (outline-next-heading) (point)))
10883 (while (re-search-forward org-any-link-re end t)
10884 (push (match-string 0) links))
10885 (setq links (org-uniquify (reverse links))))
10886 (cond
10887 ((null links)
10888 (message "No links"))
10889 ((equal (length links) 1)
10890 (setq link (car links)))
10891 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10892 (setq link (nth (if have-zero nth (1- nth)) links)))
10893 (t ; we have to select a link
10894 (save-excursion
10895 (save-window-excursion
10896 (delete-other-windows)
10897 (with-output-to-temp-buffer "*Select Link*"
10898 (mapc (lambda (l)
10899 (if (not (string-match org-bracket-link-regexp l))
10900 (princ (format "[%c] %s\n" (incf cnt)
10901 (org-remove-angle-brackets l)))
10902 (if (match-end 3)
10903 (princ (format "[%c] %s (%s)\n" (incf cnt)
10904 (match-string 3 l) (match-string 1 l)))
10905 (princ (format "[%c] %s\n" (incf cnt)
10906 (match-string 1 l))))))
10907 links))
10908 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10909 (message "Select link to open, RET to open all:")
10910 (setq c (read-char-exclusive))
10911 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10912 (when (equal c ?q) (user-error "Abort"))
10913 (if (equal c ?\C-m)
10914 (setq link links)
10915 (setq nth (- c ?0))
10916 (if have-zero (setq nth (1+ nth)))
10917 (unless (and (integerp nth) (>= (length links) nth))
10918 (user-error "Invalid link selection"))
10919 (setq link (nth (1- nth) links)))))
10920 (cons link end))))))
10922 ;; TODO: These functions are deprecated since `org-open-at-point'
10923 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10924 (defun org-open-file-with-system (path)
10925 "Open file at PATH using the system way of opening it."
10926 (org-open-file path 'system))
10927 (defun org-open-file-with-emacs (path)
10928 "Open file at PATH in Emacs."
10929 (org-open-file path 'emacs))
10932 ;;; File search
10934 (defvar org-create-file-search-functions nil
10935 "List of functions to construct the right search string for a file link.
10936 These functions are called in turn with point at the location to
10937 which the link should point.
10939 A function in the hook should first test if it would like to
10940 handle this file type, for example by checking the `major-mode'
10941 or the file extension. If it decides not to handle this file, it
10942 should just return nil to give other functions a chance. If it
10943 does handle the file, it must return the search string to be used
10944 when following the link. The search string will be part of the
10945 file link, given after a double colon, and `org-open-at-point'
10946 will automatically search for it. If special measures must be
10947 taken to make the search successful, another function should be
10948 added to the companion hook `org-execute-file-search-functions',
10949 which see.
10951 A function in this hook may also use `setq' to set the variable
10952 `description' to provide a suggestion for the descriptive text to
10953 be used for this link when it gets inserted into an Org-mode
10954 buffer with \\[org-insert-link].")
10956 (defvar org-execute-file-search-functions nil
10957 "List of functions to execute a file search triggered by a link.
10959 Functions added to this hook must accept a single argument, the
10960 search string that was part of the file link, the part after the
10961 double colon. The function must first check if it would like to
10962 handle this search, for example by checking the `major-mode' or
10963 the file extension. If it decides not to handle this search, it
10964 should just return nil to give other functions a chance. If it
10965 does handle the search, it must return a non-nil value to keep
10966 other functions from trying.
10968 Each function can access the current prefix argument through the
10969 variable `current-prefix-arg'. Note that a single prefix is used
10970 to force opening a link in Emacs, so it may be good to only use a
10971 numeric or double prefix to guide the search function.
10973 In case this is needed, a function in this hook can also restore
10974 the window configuration before `org-open-at-point' was called using:
10976 (set-window-configuration org-window-config-before-follow-link)")
10978 (defun org-link-search (s &optional type avoid-pos stealth)
10979 "Search for a link search option.
10980 If S is surrounded by forward slashes, it is interpreted as a
10981 regular expression. In org-mode files, this will create an `org-occur'
10982 sparse tree. In ordinary files, `occur' will be used to list matches.
10983 If the current buffer is in `dired-mode', grep will be used to search
10984 in all files. If AVOID-POS is given, ignore matches near that position.
10986 When optional argument STEALTH is non-nil, do not modify
10987 visibility around point, thus ignoring `org-show-context-detail'
10988 variable."
10989 (let ((case-fold-search t)
10990 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10991 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10992 (append '(("") (" ") ("\t") ("\n"))
10993 org-emphasis-alist)
10994 "\\|") "\\)"))
10995 (pos (point))
10996 words re0 re2 re4_ re4 re5 re2a re2a_ reall)
10997 (cond
10998 ;; First check if there are any special search functions
10999 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11000 ;; Now try the builtin stuff
11001 ((and (eq (aref s0 0) ?#)
11002 (> (length s0) 1)
11003 (let ((match (org-find-property "CUSTOM_ID" (substring s0 1))))
11004 (and match (goto-char match) (setf type 'dedicated)))))
11005 ((save-excursion
11006 (goto-char (point-min))
11007 (and
11008 (re-search-forward
11009 (concat "<<" (regexp-quote s0) ">>") nil t)
11010 (setq type 'dedicated
11011 pos (match-beginning 0))))
11012 ;; There is an exact target for this
11013 (goto-char pos))
11014 ((save-excursion
11015 (goto-char (point-min))
11016 (and
11017 (re-search-forward
11018 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11019 (setq type 'dedicated pos (match-beginning 0))))
11020 ;; Found an element with a matching #+name affiliated keyword.
11021 (goto-char pos))
11022 ((and (string-match "^(\\(.*\\))$" s0)
11023 (save-excursion
11024 (goto-char (point-min))
11025 (and
11026 (re-search-forward
11027 (concat "[^[]" (regexp-quote
11028 (format org-coderef-label-format
11029 (match-string 1 s0))))
11030 nil t)
11031 (setq type 'dedicated
11032 pos (1+ (match-beginning 0))))))
11033 ;; There is a coderef target for this
11034 (goto-char pos))
11035 ((string-match "^/\\(.*\\)/$" s)
11036 ;; A regular expression
11037 (cond
11038 ((derived-mode-p 'org-mode)
11039 (org-occur (match-string 1 s)))
11040 (t (org-do-occur (match-string 1 s)))))
11041 ((and (derived-mode-p 'org-mode)
11042 (or (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11043 org-link-search-must-match-exact-headline))
11044 ;; Headline search.
11045 (goto-char (point-min))
11046 (cond
11047 ((let (case-fold-search)
11048 (re-search-forward
11049 (let* ((wspace "[ \t]")
11050 (wspaceopt (concat wspace "*"))
11051 (cookie (concat "\\(?:"
11052 wspaceopt
11053 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11054 wspaceopt
11055 "\\)"))
11056 (sep (concat "\\(?:" wspace "+\\|" cookie "+\\)")))
11057 (concat
11058 org-outline-regexp-bol
11059 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11060 "\\(?:\\[#.\\][ \t]+\\)?"
11061 "\\(?:" org-comment-string "[ \t]+\\)?"
11062 sep "*"
11063 (mapconcat #'identity
11064 (org-split-string (regexp-quote s))
11065 (concat sep "+"))
11066 sep "*"
11067 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11068 "[ \t]*$"))
11069 nil t))
11070 ;; OK, found a match
11071 (setq type 'dedicated)
11072 (goto-char (match-beginning 0)))
11073 ((and (not org-link-search-inhibit-query)
11074 (eq org-link-search-must-match-exact-headline 'query-to-create)
11075 (y-or-n-p "No match - create this as a new heading? "))
11076 (goto-char (point-max))
11077 (unless (bolp) (newline))
11078 (org-insert-heading nil t t)
11079 (insert s "\n")
11080 (beginning-of-line 0))
11082 (goto-char pos)
11083 (error "No match"))))
11085 ;; A normal search string
11086 (remove-text-properties
11087 0 (length s)
11088 '(face nil mouse-face nil keymap nil fontified nil) s)
11089 ;; Make a series of regular expressions to find a match
11090 (setq words (org-split-string s "[ \n\r\t]+")
11092 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11093 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11094 "\\)" markers)
11095 re2a_ (concat "\\(" (mapconcat 'downcase words
11096 "[ \t\r\n]+") "\\)[ \t\r\n]")
11097 re2a (concat "[ \t\r\n]" re2a_)
11098 re4_ (concat "\\(" (mapconcat 'downcase words
11099 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11100 re4 (concat "[^a-zA-Z_]" re4_)
11102 re5 (concat ".*" re4)
11103 reall (concat "\\(" re0 "\\)\\|\\(" re2 "\\)\\|\\(" re4
11104 "\\)\\|\\(" re5 "\\)"))
11105 (cond
11106 ((eq type 'org-occur) (org-occur reall))
11107 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11108 (t (goto-char (point-min))
11109 (setq type 'fuzzy)
11110 (if (or (and (org-search-not-self 1 re0 nil t)
11111 (setq type 'dedicated))
11112 (org-search-not-self 1 re2 nil t)
11113 (org-search-not-self 1 re2a nil t)
11114 (org-search-not-self 1 re4 nil t)
11115 (org-search-not-self 1 re5 nil t))
11116 (goto-char (match-beginning 1))
11117 (goto-char pos)
11118 (error "No match"))))))
11119 (and (derived-mode-p 'org-mode)
11120 (not stealth)
11121 (org-show-context 'link-search))
11122 type))
11124 (defun org-search-not-self (group &rest args)
11125 "Execute `re-search-forward', but only accept matches that do not
11126 enclose the position of `org-open-link-marker'."
11127 (let ((m org-open-link-marker))
11128 (catch 'exit
11129 (while (apply 're-search-forward args)
11130 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11131 (goto-char (match-end group))
11132 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11133 (> (match-beginning 0) (marker-position m))
11134 (< (match-end 0) (marker-position m)))
11135 (save-match-data
11136 (or (not (org-in-regexp
11137 org-bracket-link-analytic-regexp 1))
11138 (not (match-end 4)) ; no description
11139 (and (<= (match-beginning 4) (point))
11140 (>= (match-end 4) (point))))))
11141 (throw 'exit (point))))))))
11143 (defun org-get-buffer-for-internal-link (buffer)
11144 "Return a buffer to be used for displaying the link target of internal links."
11145 (cond
11146 ((not org-display-internal-link-with-indirect-buffer)
11147 buffer)
11148 ((string-match "(Clone)$" (buffer-name buffer))
11149 (message "Buffer is already a clone, not making another one")
11150 ;; we also do not modify visibility in this case
11151 buffer)
11152 (t ; make a new indirect buffer for displaying the link
11153 (let* ((bn (buffer-name buffer))
11154 (ibn (concat bn "(Clone)"))
11155 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11156 (with-current-buffer ib (org-overview))
11157 ib))))
11159 (defun org-do-occur (regexp &optional cleanup)
11160 "Call the Emacs command `occur'.
11161 If CLEANUP is non-nil, remove the printout of the regular expression
11162 in the *Occur* buffer. This is useful if the regex is long and not useful
11163 to read."
11164 (occur regexp)
11165 (when cleanup
11166 (let ((cwin (selected-window)) win beg end)
11167 (when (setq win (get-buffer-window "*Occur*"))
11168 (select-window win))
11169 (goto-char (point-min))
11170 (when (re-search-forward "match[a-z]+" nil t)
11171 (setq beg (match-end 0))
11172 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11173 (setq end (1- (match-beginning 0)))))
11174 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11175 (goto-char (point-min))
11176 (select-window cwin))))
11178 ;;; The mark ring for links jumps
11180 (defvar org-mark-ring nil
11181 "Mark ring for positions before jumps in Org-mode.")
11182 (defvar org-mark-ring-last-goto nil
11183 "Last position in the mark ring used to go back.")
11184 ;; Fill and close the ring
11185 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11186 (loop for i from 1 to org-mark-ring-length do
11187 (push (make-marker) org-mark-ring))
11188 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11189 org-mark-ring)
11191 (defun org-mark-ring-push (&optional pos buffer)
11192 "Put the current position or POS into the mark ring and rotate it."
11193 (interactive)
11194 (setq pos (or pos (point)))
11195 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11196 (move-marker (car org-mark-ring)
11197 (or pos (point))
11198 (or buffer (current-buffer)))
11199 (message "%s"
11200 (substitute-command-keys
11201 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11203 (defun org-mark-ring-goto (&optional n)
11204 "Jump to the previous position in the mark ring.
11205 With prefix arg N, jump back that many stored positions. When
11206 called several times in succession, walk through the entire ring.
11207 Org-mode commands jumping to a different position in the current file,
11208 or to another Org-mode file, automatically push the old position
11209 onto the ring."
11210 (interactive "p")
11211 (let (p m)
11212 (if (eq last-command this-command)
11213 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11214 (setq p org-mark-ring))
11215 (setq org-mark-ring-last-goto p)
11216 (setq m (car p))
11217 (org-pop-to-buffer-same-window (marker-buffer m))
11218 (goto-char m)
11219 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11221 (defun org-remove-angle-brackets (s)
11222 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11223 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11225 (defun org-add-angle-brackets (s)
11226 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11227 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11229 (defun org-remove-double-quotes (s)
11230 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11231 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11234 ;;; Following specific links
11236 (defun org-follow-timestamp-link ()
11237 "Open an agenda view for the time-stamp date/range at point."
11238 (cond
11239 ((org-at-date-range-p t)
11240 (let ((org-agenda-start-on-weekday)
11241 (t1 (match-string 1))
11242 (t2 (match-string 2)) tt1 tt2)
11243 (setq tt1 (time-to-days (org-time-string-to-time t1))
11244 tt2 (time-to-days (org-time-string-to-time t2)))
11245 (let ((org-agenda-buffer-tmp-name
11246 (format "*Org Agenda(a:%s)"
11247 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11248 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11249 ((org-at-timestamp-p t)
11250 (let ((org-agenda-buffer-tmp-name
11251 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11252 (org-agenda-list nil (time-to-days (org-time-string-to-time
11253 (substring (match-string 1) 0 10)))
11254 1)))
11255 (t (error "This should not happen"))))
11258 ;;; Following file links
11259 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11260 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11261 (declare-function mailcap-mime-info
11262 "mailcap" (string &optional request no-decode))
11263 (defvar org-wait nil)
11264 (defun org-open-file (path &optional in-emacs line search)
11265 "Open the file at PATH.
11266 First, this expands any special file name abbreviations. Then the
11267 configuration variable `org-file-apps' is checked if it contains an
11268 entry for this file type, and if yes, the corresponding command is launched.
11270 If no application is found, Emacs simply visits the file.
11272 With optional prefix argument IN-EMACS, Emacs will visit the file.
11273 With a double \\[universal-argument] \\[universal-argument] \
11274 prefix arg, Org tries to avoid opening in Emacs
11275 and to use an external application to visit the file.
11277 Optional LINE specifies a line to go to, optional SEARCH a string
11278 to search for. If LINE or SEARCH is given, the file will be
11279 opened in Emacs, unless an entry from org-file-apps that makes
11280 use of groups in a regexp matches.
11282 If you want to change the way frames are used when following a
11283 link, please customize `org-link-frame-setup'.
11285 If the file does not exist, an error is thrown."
11286 (let* ((file (if (equal path "")
11287 buffer-file-name
11288 (substitute-in-file-name (expand-file-name path))))
11289 (file-apps (append org-file-apps (org-default-apps)))
11290 (apps (org-remove-if
11291 'org-file-apps-entry-match-against-dlink-p file-apps))
11292 (apps-dlink (org-remove-if-not
11293 'org-file-apps-entry-match-against-dlink-p file-apps))
11294 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11295 (dirp (if remp nil (file-directory-p file)))
11296 (file (if (and dirp org-open-directory-means-index-dot-org)
11297 (concat (file-name-as-directory file) "index.org")
11298 file))
11299 (a-m-a-p (assq 'auto-mode apps))
11300 (dfile (downcase file))
11301 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11302 (link (cond ((and (eq line nil)
11303 (eq search nil))
11304 file)
11305 (line
11306 (concat file "::" (number-to-string line)))
11307 (search
11308 (concat file "::" search))))
11309 (dlink (downcase link))
11310 (old-buffer (current-buffer))
11311 (old-pos (point))
11312 (old-mode major-mode)
11313 ext cmd link-match-data)
11314 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11315 (setq ext (match-string 1 dfile))
11316 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11317 (setq ext (match-string 1 dfile))))
11318 (cond
11319 ((member in-emacs '((16) system))
11320 (setq cmd (cdr (assoc 'system apps))))
11321 (in-emacs (setq cmd 'emacs))
11323 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11324 (and dirp (cdr (assoc 'directory apps)))
11325 ; first, try matching against apps-dlink
11326 ; if we get a match here, store the match data for later
11327 (let ((match (assoc-default dlink apps-dlink
11328 'string-match)))
11329 (if match
11330 (progn (setq link-match-data (match-data))
11331 match)
11332 (progn (setq in-emacs (or in-emacs line search))
11333 nil))) ; if we have no match in apps-dlink,
11334 ; always open the file in emacs if line or search
11335 ; is given (for backwards compatibility)
11336 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11337 'string-match)
11338 (cdr (assoc ext apps))
11339 (cdr (assoc t apps))))))
11340 (when (eq cmd 'system)
11341 (setq cmd (cdr (assoc 'system apps))))
11342 (when (eq cmd 'default)
11343 (setq cmd (cdr (assoc t apps))))
11344 (when (eq cmd 'mailcap)
11345 (require 'mailcap)
11346 (mailcap-parse-mailcaps)
11347 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11348 (command (mailcap-mime-info mime-type)))
11349 (if (stringp command)
11350 (setq cmd command)
11351 (setq cmd 'emacs))))
11352 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11353 (not (file-exists-p file))
11354 (not org-open-non-existing-files))
11355 (user-error "No such file: %s" file))
11356 (cond
11357 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11358 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11359 (while (string-match "['\"]%s['\"]" cmd)
11360 (setq cmd (replace-match "%s" t t cmd)))
11361 (while (string-match "%s" cmd)
11362 (setq cmd (replace-match
11363 (save-match-data
11364 (shell-quote-argument
11365 (convert-standard-filename file)))
11366 t t cmd)))
11368 ;; Replace "%1", "%2" etc. in command with group matches from regex
11369 (save-match-data
11370 (let ((match-index 1)
11371 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11372 (set-match-data link-match-data)
11373 (while (<= match-index number-of-groups)
11374 (let ((regex (concat "%" (number-to-string match-index)))
11375 (replace-with (match-string match-index dlink)))
11376 (while (string-match regex cmd)
11377 (setq cmd (replace-match replace-with t t cmd))))
11378 (setq match-index (+ match-index 1)))))
11380 (save-window-excursion
11381 (message "Running %s...done" cmd)
11382 (start-process-shell-command cmd nil cmd)
11383 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11384 ((or (stringp cmd)
11385 (eq cmd 'emacs))
11386 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11387 (widen)
11388 (if line (progn (org-goto-line line)
11389 (if (derived-mode-p 'org-mode)
11390 (org-reveal)))
11391 (if search (org-link-search search))))
11392 ((consp cmd)
11393 (let ((file (convert-standard-filename file)))
11394 (save-match-data
11395 (set-match-data link-match-data)
11396 (eval cmd))))
11397 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11398 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11399 (or (not (equal old-buffer (current-buffer)))
11400 (not (equal old-pos (point))))
11401 (org-mark-ring-push old-pos old-buffer))))
11403 (defun org-file-apps-entry-match-against-dlink-p (entry)
11404 "This function returns non-nil if `entry' uses a regular
11405 expression which should be matched against the whole link by
11406 org-open-file.
11408 It assumes that is the case when the entry uses a regular
11409 expression which has at least one grouping construct and the
11410 action is either a lisp form or a command string containing
11411 '%1', i.e. using at least one subexpression match as a
11412 parameter."
11413 (let ((selector (car entry))
11414 (action (cdr entry)))
11415 (if (stringp selector)
11416 (and (> (regexp-opt-depth selector) 0)
11417 (or (and (stringp action)
11418 (string-match "%[0-9]" action))
11419 (consp action)))
11420 nil)))
11422 (defun org-default-apps ()
11423 "Return the default applications for this operating system."
11424 (cond
11425 ((eq system-type 'darwin)
11426 org-file-apps-defaults-macosx)
11427 ((eq system-type 'windows-nt)
11428 org-file-apps-defaults-windowsnt)
11429 (t org-file-apps-defaults-gnu)))
11431 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11432 "Convert extensions to regular expressions in the cars of LIST.
11433 Also, weed out any non-string entries, because the return value is used
11434 only for regexp matching.
11435 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11436 point to the symbol `emacs', indicating that the file should
11437 be opened in Emacs."
11438 (append
11439 (delq nil
11440 (mapcar (lambda (x)
11441 (if (not (stringp (car x)))
11443 (if (string-match "\\W" (car x))
11445 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11446 list))
11447 (if add-auto-mode
11448 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11450 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11451 (defun org-file-remote-p (file)
11452 "Test whether FILE specifies a location on a remote system.
11453 Return non-nil if the location is indeed remote.
11455 For example, the filename \"/user@host:/foo\" specifies a location
11456 on the system \"/user@host:\"."
11457 (cond ((fboundp 'file-remote-p)
11458 (file-remote-p file))
11459 ((fboundp 'tramp-handle-file-remote-p)
11460 (tramp-handle-file-remote-p file))
11461 ((and (boundp 'ange-ftp-name-format)
11462 (string-match (car ange-ftp-name-format) file))
11463 t)))
11466 ;;;; Refiling
11468 (defun org-get-org-file ()
11469 "Read a filename, with default directory `org-directory'."
11470 (let ((default (or org-default-notes-file remember-data-file)))
11471 (read-file-name (format "File name [%s]: " default)
11472 (file-name-as-directory org-directory)
11473 default)))
11475 (defun org-notes-order-reversed-p ()
11476 "Check if the current file should receive notes in reversed order."
11477 (cond
11478 ((not org-reverse-note-order) nil)
11479 ((eq t org-reverse-note-order) t)
11480 ((not (listp org-reverse-note-order)) nil)
11481 (t (catch 'exit
11482 (let ((all org-reverse-note-order)
11483 entry)
11484 (while (setq entry (pop all))
11485 (if (string-match (car entry) buffer-file-name)
11486 (throw 'exit (cdr entry))))
11487 nil)))))
11489 (defvar org-refile-target-table nil
11490 "The list of refile targets, created by `org-refile'.")
11492 (defvar org-agenda-new-buffers nil
11493 "Buffers created to visit agenda files.")
11495 (defvar org-refile-cache nil
11496 "Cache for refile targets.")
11498 (defvar org-refile-markers nil
11499 "All the markers used for caching refile locations.")
11501 (defun org-refile-marker (pos)
11502 "Get a new refile marker, but only if caching is in use."
11503 (if (not org-refile-use-cache)
11505 (let ((m (make-marker)))
11506 (move-marker m pos)
11507 (push m org-refile-markers)
11508 m)))
11510 (defun org-refile-cache-clear ()
11511 "Clear the refile cache and disable all the markers."
11512 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11513 (setq org-refile-markers nil)
11514 (setq org-refile-cache nil)
11515 (message "Refile cache has been cleared"))
11517 (defun org-refile-cache-check-set (set)
11518 "Check if all the markers in the cache still have live buffers."
11519 (let (marker)
11520 (catch 'exit
11521 (while (and set (setq marker (nth 3 (pop set))))
11522 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11523 (when (and marker (null (marker-buffer marker)))
11524 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11525 (sit-for 3)
11526 (throw 'exit nil)))
11527 t)))
11529 (defun org-refile-cache-put (set &rest identifiers)
11530 "Push the refile targets SET into the cache, under IDENTIFIERS."
11531 (let* ((key (sha1 (prin1-to-string identifiers)))
11532 (entry (assoc key org-refile-cache)))
11533 (if entry
11534 (setcdr entry set)
11535 (push (cons key set) org-refile-cache))))
11537 (defun org-refile-cache-get (&rest identifiers)
11538 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11539 (cond
11540 ((not org-refile-cache) nil)
11541 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11543 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11544 org-refile-cache))))
11545 (and set (org-refile-cache-check-set set) set)))))
11547 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11548 "Produce a table with refile targets."
11549 (let ((case-fold-search nil)
11550 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11551 (entries (or org-refile-targets '((nil . (:level . 1)))))
11552 targets tgs txt re files f desc descre fast-path-p level pos0)
11553 (message "Getting targets...")
11554 (with-current-buffer (or default-buffer (current-buffer))
11555 (while (setq entry (pop entries))
11556 (setq files (car entry) desc (cdr entry))
11557 (setq fast-path-p nil)
11558 (cond
11559 ((null files) (setq files (list (current-buffer))))
11560 ((eq files 'org-agenda-files)
11561 (setq files (org-agenda-files 'unrestricted)))
11562 ((and (symbolp files) (fboundp files))
11563 (setq files (funcall files)))
11564 ((and (symbolp files) (boundp files))
11565 (setq files (symbol-value files))))
11566 (if (stringp files) (setq files (list files)))
11567 (cond
11568 ((eq (car desc) :tag)
11569 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11570 ((eq (car desc) :todo)
11571 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11572 ((eq (car desc) :regexp)
11573 (setq descre (cdr desc)))
11574 ((eq (car desc) :level)
11575 (setq descre (concat "^\\*\\{" (number-to-string
11576 (if org-odd-levels-only
11577 (1- (* 2 (cdr desc)))
11578 (cdr desc)))
11579 "\\}[ \t]")))
11580 ((eq (car desc) :maxlevel)
11581 (setq fast-path-p t)
11582 (setq descre (concat "^\\*\\{1," (number-to-string
11583 (if org-odd-levels-only
11584 (1- (* 2 (cdr desc)))
11585 (cdr desc)))
11586 "\\}[ \t]")))
11587 (t (error "Bad refiling target description %s" desc)))
11588 (while (setq f (pop files))
11589 (with-current-buffer
11590 (if (bufferp f) f (org-get-agenda-file-buffer f))
11592 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11593 (progn
11594 (if (bufferp f) (setq f (buffer-file-name
11595 (buffer-base-buffer f))))
11596 (setq f (and f (expand-file-name f)))
11597 (if (eq org-refile-use-outline-path 'file)
11598 (push (list (file-name-nondirectory f) f nil nil) tgs))
11599 (save-excursion
11600 (save-restriction
11601 (widen)
11602 (goto-char (point-min))
11603 (while (re-search-forward descre nil t)
11604 (goto-char (setq pos0 (point-at-bol)))
11605 (catch 'next
11606 (when org-refile-target-verify-function
11607 (save-match-data
11608 (or (funcall org-refile-target-verify-function)
11609 (throw 'next t))))
11610 (when (and (looking-at org-complex-heading-regexp)
11611 (not (member (match-string 4) excluded-entries))
11612 (match-string 4))
11613 (setq level (org-reduced-level
11614 (- (match-end 1) (match-beginning 1)))
11615 txt (org-link-display-format (match-string 4))
11616 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11617 re (format org-complex-heading-regexp-format
11618 (regexp-quote (match-string 4))))
11619 (when org-refile-use-outline-path
11620 (setq txt (mapconcat
11621 'org-protect-slash
11622 (append
11623 (if (eq org-refile-use-outline-path
11624 'file)
11625 (list (file-name-nondirectory
11626 (buffer-file-name
11627 (buffer-base-buffer))))
11628 (if (eq org-refile-use-outline-path
11629 'full-file-path)
11630 (list (buffer-file-name
11631 (buffer-base-buffer)))))
11632 (org-get-outline-path fast-path-p
11633 level txt)
11634 (list txt))
11635 "/")))
11636 (push (list txt f re (org-refile-marker (point)))
11637 tgs)))
11638 (when (= (point) pos0)
11639 ;; verification function has not moved point
11640 (goto-char (point-at-eol))))))))
11641 (when org-refile-use-cache
11642 (org-refile-cache-put tgs (buffer-file-name) descre))
11643 (setq targets (append tgs targets))))))
11644 (message "Getting targets...done")
11645 (nreverse targets)))
11647 (defun org-protect-slash (s)
11648 (while (string-match "/" s)
11649 (setq s (replace-match "\\" t t s)))
11652 (defvar org-olpa (make-vector 20 nil))
11654 (defun org-get-outline-path (&optional fastp level heading)
11655 "Return the outline path to the current entry, as a list.
11657 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11658 routine which makes outline path derivations for an entire file,
11659 avoiding backtracing. Refile target collection makes use of that."
11660 (if fastp
11661 (progn
11662 (if (> level 19)
11663 (error "Outline path failure, more than 19 levels"))
11664 (loop for i from level upto 19 do
11665 (aset org-olpa i nil))
11666 (prog1
11667 (delq nil (append org-olpa nil))
11668 (aset org-olpa level heading)))
11669 (let (rtn case-fold-search)
11670 (save-excursion
11671 (save-restriction
11672 (widen)
11673 (while (org-up-heading-safe)
11674 (when (looking-at org-complex-heading-regexp)
11675 (push (org-trim
11676 (replace-regexp-in-string
11677 ;; Remove statistical/checkboxes cookies
11678 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11679 (org-match-string-no-properties 4)))
11680 rtn)))
11681 rtn)))))
11683 (defun org-format-outline-path (path &optional width prefix separator)
11684 "Format the outline path PATH for display.
11685 WIDTH is the maximum number of characters that is available.
11686 PREFIX is a prefix to be included in the returned string,
11687 such as the file name.
11688 SEPARATOR is inserted between the different parts of the path,
11689 the default is \"/\"."
11690 (setq width (or width 79))
11691 (if prefix (setq width (- width (length prefix))))
11692 (if (not path)
11693 (or prefix "")
11694 (let* ((nsteps (length path))
11695 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11696 (maxwidth (if (<= total-width width)
11697 10000 ;; everything fits
11698 ;; we need to shorten the level headings
11699 (/ (- width nsteps) nsteps)))
11700 (org-odd-levels-only nil)
11701 (n 0)
11702 (total (1+ (length prefix))))
11703 (setq maxwidth (max maxwidth 10))
11704 (concat prefix
11705 (if prefix (or separator "/"))
11706 (mapconcat
11707 (lambda (h)
11708 (setq n (1+ n))
11709 (if (and (= n nsteps) (< maxwidth 10000))
11710 (setq maxwidth (- total-width total)))
11711 (if (< (length h) maxwidth)
11712 (progn (setq total (+ total (length h) 1)) h)
11713 (setq h (substring h 0 (- maxwidth 2))
11714 total (+ total maxwidth 1))
11715 (if (string-match "[ \t]+\\'" h)
11716 (setq h (substring h 0 (match-beginning 0))))
11717 (setq h (concat h "..")))
11718 (org-add-props h nil 'face
11719 (nth (% (1- n) org-n-level-faces)
11720 org-level-faces))
11722 path (or separator "/"))))))
11724 (defun org-display-outline-path (&optional file current separator just-return-string)
11725 "Display the current outline path in the echo area.
11727 If FILE is non-nil, prepend the output with the file name.
11728 If CURRENT is non-nil, append the current heading to the output.
11729 SEPARATOR is passed through to `org-format-outline-path'. It separates
11730 the different parts of the path and defaults to \"/\".
11731 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11732 (interactive "P")
11733 (let* (case-fold-search
11734 (bfn (buffer-file-name (buffer-base-buffer)))
11735 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11736 res)
11737 (if current (setq path (append path
11738 (save-excursion
11739 (org-back-to-heading t)
11740 (if (looking-at org-complex-heading-regexp)
11741 (list (match-string 4)))))))
11742 (setq res
11743 (org-format-outline-path
11744 path
11745 (1- (frame-width))
11746 (and file bfn (concat (file-name-nondirectory bfn) separator))
11747 separator))
11748 (if just-return-string
11749 (org-no-properties res)
11750 (org-unlogged-message "%s" res))))
11752 (defvar org-refile-history nil
11753 "History for refiling operations.")
11755 (defvar org-after-refile-insert-hook nil
11756 "Hook run after `org-refile' has inserted its stuff at the new location.
11757 Note that this is still *before* the stuff will be removed from
11758 the *old* location.")
11760 (defvar org-capture-last-stored-marker)
11761 (defvar org-refile-keep nil
11762 "Non-nil means `org-refile' will copy instead of refile.")
11764 (defun org-copy ()
11765 "Like `org-refile', but copy."
11766 (interactive)
11767 (let ((org-refile-keep t))
11768 (funcall 'org-refile nil nil nil "Copy")))
11770 (defun org-refile (&optional arg default-buffer rfloc msg)
11771 "Move the entry or entries at point to another heading.
11772 The list of target headings is compiled using the information in
11773 `org-refile-targets', which see.
11775 At the target location, the entry is filed as a subitem of the
11776 target heading. Depending on `org-reverse-note-order', the new
11777 subitem will either be the first or the last subitem.
11779 If there is an active region, all entries in that region will be
11780 refiled. However, the region must fulfill the requirement that
11781 the first heading sets the top-level of the moved text.
11783 With prefix arg ARG, the command will only visit the target
11784 location and not actually move anything.
11786 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11787 refiling operation has put the subtree.
11789 With a numeric prefix argument of `2', refile to the running clock.
11791 With a numeric prefix argument of `3', emulate `org-refile-keep'
11792 being set to `t' and copy to the target location, don't move it.
11793 Beware that keeping refiled entries may result in duplicated ID
11794 properties.
11796 RFLOC can be a refile location obtained in a different way.
11798 MSG is a string to replace \"Refile\" in the default prompt with
11799 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11801 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11803 If you are using target caching (see `org-refile-use-cache'), you
11804 have to clear the target cache in order to find new targets.
11805 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11806 prefix argument (`C-u C-u C-u C-c C-w')."
11807 (interactive "P")
11808 (if (member arg '(0 (64)))
11809 (org-refile-cache-clear)
11810 (let* ((actionmsg (cond (msg msg)
11811 ((equal arg 3) "Refile (and keep)")
11812 (t "Refile")))
11813 (cbuf (current-buffer))
11814 (regionp (org-region-active-p))
11815 (region-start (and regionp (region-beginning)))
11816 (region-end (and regionp (region-end)))
11817 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11818 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11819 pos it nbuf file re level reversed)
11820 (setq last-command nil)
11821 (when regionp
11822 (goto-char region-start)
11823 (or (bolp) (goto-char (point-at-bol)))
11824 (setq region-start (point))
11825 (unless (or (org-kill-is-subtree-p
11826 (buffer-substring region-start region-end))
11827 (prog1 org-refile-active-region-within-subtree
11828 (let ((s (point-at-eol)))
11829 (org-toggle-heading)
11830 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11831 (user-error "The region is not a (sequence of) subtree(s)")))
11832 (if (equal arg '(16))
11833 (org-refile-goto-last-stored)
11834 (when (or
11835 (and (equal arg 2)
11836 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11837 (prog1
11838 (setq it (list (or org-clock-heading "running clock")
11839 (buffer-file-name
11840 (marker-buffer org-clock-hd-marker))
11842 (marker-position org-clock-hd-marker)))
11843 (setq arg nil)))
11844 (setq it (or rfloc
11845 (let (heading-text)
11846 (save-excursion
11847 (unless (and arg (listp arg))
11848 (org-back-to-heading t)
11849 (setq heading-text
11850 (replace-regexp-in-string
11851 org-bracket-link-regexp
11852 "\\3"
11853 (nth 4 (org-heading-components)))))
11854 (org-refile-get-location
11855 (cond ((and arg (listp arg)) "Goto")
11856 (regionp (concat actionmsg " region to"))
11857 (t (concat actionmsg " subtree \""
11858 heading-text "\" to")))
11859 default-buffer
11860 (and (not (equal '(4) arg))
11861 org-refile-allow-creating-parent-nodes)
11862 arg))))))
11863 (setq file (nth 1 it)
11864 re (nth 2 it)
11865 pos (nth 3 it))
11866 (if (and (not arg)
11868 (equal (buffer-file-name) file)
11869 (if regionp
11870 (and (>= pos region-start)
11871 (<= pos region-end))
11872 (and (>= pos (point))
11873 (< pos (save-excursion
11874 (org-end-of-subtree t t))))))
11875 (error "Cannot refile to position inside the tree or region"))
11876 (setq nbuf (or (find-buffer-visiting file)
11877 (find-file-noselect file)))
11878 (if (and arg (not (equal arg 3)))
11879 (progn
11880 (org-pop-to-buffer-same-window nbuf)
11881 (goto-char pos)
11882 (org-show-context 'org-goto))
11883 (if regionp
11884 (progn
11885 (org-kill-new (buffer-substring region-start region-end))
11886 (org-save-markers-in-region region-start region-end))
11887 (org-copy-subtree 1 nil t))
11888 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11889 (find-file-noselect file)))
11890 (setq reversed (org-notes-order-reversed-p))
11891 (save-excursion
11892 (save-restriction
11893 (widen)
11894 (if pos
11895 (progn
11896 (goto-char pos)
11897 (looking-at org-outline-regexp)
11898 (setq level (org-get-valid-level (funcall outline-level) 1))
11899 (goto-char
11900 (if reversed
11901 (or (outline-next-heading) (point-max))
11902 (or (save-excursion (org-get-next-sibling))
11903 (org-end-of-subtree t t)
11904 (point-max)))))
11905 (setq level 1)
11906 (if (not reversed)
11907 (goto-char (point-max))
11908 (goto-char (point-min))
11909 (or (outline-next-heading) (goto-char (point-max)))))
11910 (if (not (bolp)) (newline))
11911 (org-paste-subtree level nil nil t)
11912 (when org-log-refile
11913 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11914 (unless (eq org-log-refile 'note)
11915 (save-excursion (org-add-log-note))))
11916 (and org-auto-align-tags
11917 (let ((org-loop-over-headlines-in-active-region nil))
11918 (org-set-tags nil t)))
11919 (let ((bookmark-name (plist-get org-bookmark-names-plist
11920 :last-refile)))
11921 (when bookmark-name
11922 (with-demoted-errors
11923 (bookmark-set bookmark-name))))
11924 ;; If we are refiling for capture, make sure that the
11925 ;; last-capture pointers point here
11926 (when (org-bound-and-true-p org-refile-for-capture)
11927 (let ((bookmark-name (plist-get org-bookmark-names-plist
11928 :last-capture-marker)))
11929 (when bookmark-name
11930 (with-demoted-errors
11931 (bookmark-set bookmark-name))))
11932 (move-marker org-capture-last-stored-marker (point)))
11933 (if (fboundp 'deactivate-mark) (deactivate-mark))
11934 (run-hooks 'org-after-refile-insert-hook))))
11935 (unless org-refile-keep
11936 (if regionp
11937 (delete-region (point) (+ (point) (- region-end region-start)))
11938 (delete-region
11939 (and (org-back-to-heading t) (point))
11940 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11941 (when (featurep 'org-inlinetask)
11942 (org-inlinetask-remove-END-maybe))
11943 (setq org-markers-to-move nil)
11944 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11946 (defun org-refile-goto-last-stored ()
11947 "Go to the location where the last refile was stored."
11948 (interactive)
11949 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11950 (message "This is the location of the last refile"))
11952 (defun org-refile--get-location (refloc tbl)
11953 "When user refile to REFLOC, find the associated target in TBL.
11954 Also check `org-refile-target-table'."
11955 (car (delq
11957 (mapcar
11958 (lambda (r) (or (assoc r tbl)
11959 (assoc r org-refile-target-table)))
11960 (list (replace-regexp-in-string "/$" "" refloc)
11961 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11963 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11964 no-exclude)
11965 "Prompt the user for a refile location, using PROMPT.
11966 PROMPT should not be suffixed with a colon and a space, because
11967 this function appends the default value from
11968 `org-refile-history' automatically, if that is not empty.
11969 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11970 this is used for the GOTO interface."
11971 (let ((org-refile-targets org-refile-targets)
11972 (org-refile-use-outline-path org-refile-use-outline-path)
11973 excluded-entries)
11974 (when (and (derived-mode-p 'org-mode)
11975 (not org-refile-use-cache)
11976 (not no-exclude))
11977 (org-map-tree
11978 (lambda()
11979 (setq excluded-entries
11980 (append excluded-entries (list (org-get-heading t t)))))))
11981 (setq org-refile-target-table
11982 (org-refile-get-targets default-buffer excluded-entries)))
11983 (unless org-refile-target-table
11984 (user-error "No refile targets"))
11985 (let* ((cbuf (current-buffer))
11986 (partial-completion-mode nil)
11987 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11988 (cfunc (if (and org-refile-use-outline-path
11989 org-outline-path-complete-in-steps)
11990 'org-olpath-completing-read
11991 'org-icompleting-read))
11992 (extra (if org-refile-use-outline-path "/" ""))
11993 (cbnex (concat (buffer-name) extra))
11994 (filename (and cfn (expand-file-name cfn)))
11995 (tbl (mapcar
11996 (lambda (x)
11997 (if (and (not (member org-refile-use-outline-path
11998 '(file full-file-path)))
11999 (not (equal filename (nth 1 x))))
12000 (cons (concat (car x) extra " ("
12001 (file-name-nondirectory (nth 1 x)) ")")
12002 (cdr x))
12003 (cons (concat (car x) extra) (cdr x))))
12004 org-refile-target-table))
12005 (completion-ignore-case t)
12006 cdef
12007 (prompt (concat prompt
12008 (or (and (car org-refile-history)
12009 (concat " (default " (car org-refile-history) ")"))
12010 (and (assoc cbnex tbl) (setq cdef cbnex)
12011 (concat " (default " cbnex ")"))) ": "))
12012 pa answ parent-target child parent old-hist)
12013 (setq old-hist org-refile-history)
12014 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12015 nil 'org-refile-history (or cdef (car org-refile-history))))
12016 (if (setq pa (org-refile--get-location answ tbl))
12017 (progn
12018 (org-refile-check-position pa)
12019 (when (or (not org-refile-history)
12020 (not (eq old-hist org-refile-history))
12021 (not (equal (car pa) (car org-refile-history))))
12022 (setq org-refile-history
12023 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12024 org-refile-history
12025 (cdr org-refile-history))))
12026 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12027 (pop org-refile-history)))
12029 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12030 (progn
12031 (setq parent (match-string 1 answ)
12032 child (match-string 2 answ))
12033 (setq parent-target (org-refile--get-location parent tbl))
12034 (when (and parent-target
12035 (or (eq new-nodes t)
12036 (and (eq new-nodes 'confirm)
12037 (y-or-n-p (format "Create new node \"%s\"? "
12038 child)))))
12039 (org-refile-new-child parent-target child)))
12040 (user-error "Invalid target location")))))
12042 (declare-function org-string-nw-p "org-macs" (s))
12043 (defun org-refile-check-position (refile-pointer)
12044 "Check if the refile pointer matches the headline to which it points."
12045 (let* ((file (nth 1 refile-pointer))
12046 (re (nth 2 refile-pointer))
12047 (pos (nth 3 refile-pointer))
12048 buffer)
12049 (if (and (not (markerp pos)) (not file))
12050 (user-error "Please indicate a target file in the refile path")
12051 (when (org-string-nw-p re)
12052 (setq buffer (if (markerp pos)
12053 (marker-buffer pos)
12054 (or (find-buffer-visiting file)
12055 (find-file-noselect file))))
12056 (with-current-buffer buffer
12057 (save-excursion
12058 (save-restriction
12059 (widen)
12060 (goto-char pos)
12061 (beginning-of-line 1)
12062 (unless (org-looking-at-p re)
12063 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12065 (defun org-refile-new-child (parent-target child)
12066 "Use refile target PARENT-TARGET to add new CHILD below it."
12067 (unless parent-target
12068 (error "Cannot find parent for new node"))
12069 (let ((file (nth 1 parent-target))
12070 (pos (nth 3 parent-target))
12071 level)
12072 (with-current-buffer (or (find-buffer-visiting file)
12073 (find-file-noselect file))
12074 (save-excursion
12075 (save-restriction
12076 (widen)
12077 (if pos
12078 (goto-char pos)
12079 (goto-char (point-max))
12080 (if (not (bolp)) (newline)))
12081 (when (looking-at org-outline-regexp)
12082 (setq level (funcall outline-level))
12083 (org-end-of-subtree t t))
12084 (org-back-over-empty-lines)
12085 (insert "\n" (make-string
12086 (if pos (org-get-valid-level level 1) 1) ?*)
12087 " " child "\n")
12088 (beginning-of-line 0)
12089 (list (concat (car parent-target) "/" child) file "" (point)))))))
12091 (defun org-olpath-completing-read (prompt collection &rest args)
12092 "Read an outline path like a file name."
12093 (let ((thetable collection)
12094 (org-completion-use-ido nil) ; does not work with ido.
12095 (org-completion-use-iswitchb nil)) ; or iswitchb
12096 (apply #'org-icompleting-read
12097 prompt
12098 (lambda (string predicate &optional flag)
12099 (cond
12100 ((eq flag nil) (try-completion string thetable))
12101 ((eq flag t)
12102 (let ((l (length string)))
12103 (mapcar (lambda (x)
12104 (let ((r (substring x l))
12105 (f (if (string-match " ([^)]*)$" x)
12106 (match-string 0 x)
12107 "")))
12108 (if (string-match "/" r)
12109 (concat string (substring r 0 (match-end 0)) f)
12110 x)))
12111 (all-completions string thetable predicate))))
12112 ;; Exact match?
12113 ((eq flag 'lambda) (assoc string thetable))))
12114 args)))
12116 ;;;; Dynamic blocks
12118 (defun org-find-dblock (name)
12119 "Find the first dynamic block with name NAME in the buffer.
12120 If not found, stay at current position and return nil."
12121 (let ((case-fold-search t) pos)
12122 (save-excursion
12123 (goto-char (point-min))
12124 (setq pos (and (re-search-forward
12125 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12126 (match-beginning 0))))
12127 (if pos (goto-char pos))
12128 pos))
12130 (defun org-create-dblock (plist)
12131 "Create a dynamic block section, with parameters taken from PLIST.
12132 PLIST must contain a :name entry which is used as the name of the block."
12133 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12134 (end-of-line 1)
12135 (newline))
12136 (let ((col (current-column))
12137 (name (plist-get plist :name)))
12138 (insert "#+BEGIN: " name)
12139 (while plist
12140 (if (eq (car plist) :name)
12141 (setq plist (cddr plist))
12142 (insert " " (prin1-to-string (pop plist)))))
12143 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12144 (beginning-of-line -2)))
12146 (defun org-prepare-dblock ()
12147 "Prepare dynamic block for refresh.
12148 This empties the block, puts the cursor at the insert position and returns
12149 the property list including an extra property :name with the block name."
12150 (unless (looking-at org-dblock-start-re)
12151 (user-error "Not at a dynamic block"))
12152 (let* ((begdel (1+ (match-end 0)))
12153 (name (org-no-properties (match-string 1)))
12154 (params (append (list :name name)
12155 (read (concat "(" (match-string 3) ")")))))
12156 (save-excursion
12157 (beginning-of-line 1)
12158 (skip-chars-forward " \t")
12159 (setq params (plist-put params :indentation-column (current-column))))
12160 (unless (re-search-forward org-dblock-end-re nil t)
12161 (error "Dynamic block not terminated"))
12162 (setq params
12163 (append params
12164 (list :content (buffer-substring
12165 begdel (match-beginning 0)))))
12166 (delete-region begdel (match-beginning 0))
12167 (goto-char begdel)
12168 (open-line 1)
12169 params))
12171 (defun org-map-dblocks (&optional command)
12172 "Apply COMMAND to all dynamic blocks in the current buffer.
12173 If COMMAND is not given, use `org-update-dblock'."
12174 (let ((cmd (or command 'org-update-dblock)))
12175 (save-excursion
12176 (goto-char (point-min))
12177 (while (re-search-forward org-dblock-start-re nil t)
12178 (goto-char (match-beginning 0))
12179 (save-excursion
12180 (condition-case nil
12181 (funcall cmd)
12182 (error (message "Error during update of dynamic block"))))
12183 (unless (re-search-forward org-dblock-end-re nil t)
12184 (error "Dynamic block not terminated"))))))
12186 (defun org-dblock-update (&optional arg)
12187 "User command for updating dynamic blocks.
12188 Update the dynamic block at point. With prefix ARG, update all dynamic
12189 blocks in the buffer."
12190 (interactive "P")
12191 (if arg
12192 (org-update-all-dblocks)
12193 (or (looking-at org-dblock-start-re)
12194 (org-beginning-of-dblock))
12195 (org-update-dblock)))
12197 (defun org-update-dblock ()
12198 "Update the dynamic block at point.
12199 This means to empty the block, parse for parameters and then call
12200 the correct writing function."
12201 (interactive)
12202 (save-excursion
12203 (let* ((win (selected-window))
12204 (pos (point))
12205 (line (org-current-line))
12206 (params (org-prepare-dblock))
12207 (name (plist-get params :name))
12208 (indent (plist-get params :indentation-column))
12209 (cmd (intern (concat "org-dblock-write:" name))))
12210 (message "Updating dynamic block `%s' at line %d..." name line)
12211 (funcall cmd params)
12212 (message "Updating dynamic block `%s' at line %d...done" name line)
12213 (goto-char pos)
12214 (when (and indent (> indent 0))
12215 (setq indent (make-string indent ?\ ))
12216 (save-excursion
12217 (select-window win)
12218 (org-beginning-of-dblock)
12219 (forward-line 1)
12220 (while (not (looking-at org-dblock-end-re))
12221 (insert indent)
12222 (beginning-of-line 2))
12223 (when (looking-at org-dblock-end-re)
12224 (and (looking-at "[ \t]+")
12225 (replace-match ""))
12226 (insert indent)))))))
12228 (defun org-beginning-of-dblock ()
12229 "Find the beginning of the dynamic block at point.
12230 Error if there is no such block at point."
12231 (let ((pos (point))
12232 beg)
12233 (end-of-line 1)
12234 (if (and (re-search-backward org-dblock-start-re nil t)
12235 (setq beg (match-beginning 0))
12236 (re-search-forward org-dblock-end-re nil t)
12237 (> (match-end 0) pos))
12238 (goto-char beg)
12239 (goto-char pos)
12240 (error "Not in a dynamic block"))))
12242 (defun org-update-all-dblocks ()
12243 "Update all dynamic blocks in the buffer.
12244 This function can be used in a hook."
12245 (interactive)
12246 (when (derived-mode-p 'org-mode)
12247 (org-map-dblocks 'org-update-dblock)))
12250 ;;;; Completion
12252 (declare-function org-export-backend-name "org-export" (cl-x))
12253 (declare-function org-export-backend-options "org-export" (cl-x))
12254 (defun org-get-export-keywords ()
12255 "Return a list of all currently understood export keywords.
12256 Export keywords include options, block names, attributes and
12257 keywords relative to each registered export back-end."
12258 (let (keywords)
12259 (dolist (backend
12260 (org-bound-and-true-p org-export-registered-backends)
12261 (delq nil keywords))
12262 ;; Back-end name (for keywords, like #+LATEX:)
12263 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12264 (dolist (option-entry (org-export-backend-options backend))
12265 ;; Back-end options.
12266 (push (nth 1 option-entry) keywords)))))
12268 (defconst org-options-keywords
12269 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12270 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12271 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12272 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12273 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12275 (defcustom org-structure-template-alist
12276 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12277 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12278 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12279 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12280 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12281 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12282 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12283 ("L" "#+LaTeX: ")
12284 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12285 ("H" "#+HTML: ")
12286 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12287 ("A" "#+ASCII: ")
12288 ("i" "#+INDEX: ?")
12289 ("I" "#+INCLUDE: %file ?"))
12290 "Structure completion elements.
12291 This is a list of abbreviation keys and values. The value gets inserted
12292 if you type `<' followed by the key and then press the completion key,
12293 usually `TAB'. %file will be replaced by a file name after prompting
12294 for the file using completion. The cursor will be placed at the position
12295 of the `?` in the template.
12296 There are two templates for each key, the first uses the original Org syntax,
12297 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12298 the default when the /org-mtags.el/ module has been loaded. See also the
12299 variable `org-mtags-prefer-muse-templates'."
12300 :group 'org-completion
12301 :type '(repeat
12302 (list
12303 (string :tag "Key")
12304 (string :tag "Template")))
12305 :version "25.1"
12306 :package-version '(Org . "8.3"))
12308 (defun org-try-structure-completion ()
12309 "Try to complete a structure template before point.
12310 This looks for strings like \"<e\" on an otherwise empty line and
12311 expands them."
12312 (let ((l (buffer-substring (point-at-bol) (point)))
12314 (when (and (looking-at "[ \t]*$")
12315 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12316 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12317 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12318 (match-beginning 1)) a)
12319 t)))
12321 (defun org-complete-expand-structure-template (start cell)
12322 "Expand a structure template."
12323 (let ((rpl (nth 1 cell))
12324 (ind ""))
12325 (delete-region start (point))
12326 (when (string-match "\\`[ \t]*#\\+" rpl)
12327 (cond
12328 ((bolp))
12329 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12330 (setq ind (buffer-substring (point-at-bol) (point))))
12331 (t (newline))))
12332 (setq start (point))
12333 (if (string-match "%file" rpl)
12334 (setq rpl (replace-match
12335 (concat
12336 "\""
12337 (save-match-data
12338 (abbreviate-file-name (read-file-name "Include file: ")))
12339 "\"")
12340 t t rpl)))
12341 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12342 (concat "\n" ind)))
12343 (insert rpl)
12344 (if (re-search-backward "\\?" start t) (delete-char 1))))
12346 ;;;; TODO, DEADLINE, Comments
12348 (defun org-toggle-comment ()
12349 "Change the COMMENT state of an entry."
12350 (interactive)
12351 (save-excursion
12352 (org-back-to-heading)
12353 (looking-at org-complex-heading-regexp)
12354 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12355 (skip-chars-forward " \t")
12356 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12357 (if (org-in-commented-heading-p t)
12358 (delete-region (point)
12359 (progn (search-forward " " (line-end-position) 'move)
12360 (skip-chars-forward " \t")
12361 (point)))
12362 (insert org-comment-string)
12363 (unless (eolp) (insert " ")))))
12365 (defvar org-last-todo-state-is-todo nil
12366 "This is non-nil when the last TODO state change led to a TODO state.
12367 If the last change removed the TODO tag or switched to DONE, then
12368 this is nil.")
12370 (defvar org-setting-tags nil) ; dynamically skipped
12372 (defvar org-todo-setup-filter-hook nil
12373 "Hook for functions that pre-filter todo specs.
12374 Each function takes a todo spec and returns either nil or the spec
12375 transformed into canonical form." )
12377 (defvar org-todo-get-default-hook nil
12378 "Hook for functions that get a default item for todo.
12379 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12380 nil or a string to be used for the todo mark." )
12382 (defvar org-agenda-headline-snapshot-before-repeat)
12384 (defun org-current-effective-time ()
12385 "Return current time adjusted for `org-extend-today-until' variable."
12386 (let* ((ct (org-current-time))
12387 (dct (decode-time ct))
12388 (ct1
12389 (cond
12390 (org-use-last-clock-out-time-as-effective-time
12391 (or (org-clock-get-last-clock-out-time) ct))
12392 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12393 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12394 (t ct))))
12395 ct1))
12397 (defun org-todo-yesterday (&optional arg)
12398 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12399 (interactive "P")
12400 (if (eq major-mode 'org-agenda-mode)
12401 (apply 'org-agenda-todo-yesterday arg)
12402 (let* ((org-use-effective-time t)
12403 (hour (third (decode-time
12404 (org-current-time))))
12405 (org-extend-today-until (1+ hour)))
12406 (org-todo arg))))
12408 (defvar org-block-entry-blocking ""
12409 "First entry preventing the TODO state change.")
12411 (defun org-cancel-repeater ()
12412 "Cancel a repeater by setting its numeric value to zero."
12413 (interactive)
12414 (save-excursion
12415 (org-back-to-heading t)
12416 (let ((bound1 (point))
12417 (bound0 (save-excursion (outline-next-heading) (point))))
12418 (when (re-search-forward
12419 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12420 org-deadline-time-regexp "\\)\\|\\("
12421 org-ts-regexp "\\)")
12422 bound0 t)
12423 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12424 (replace-match "0" t nil nil 1))))))
12426 (defun org-todo (&optional arg)
12427 "Change the TODO state of an item.
12428 The state of an item is given by a keyword at the start of the heading,
12429 like
12430 *** TODO Write paper
12431 *** DONE Call mom
12433 The different keywords are specified in the variable `org-todo-keywords'.
12434 By default the available states are \"TODO\" and \"DONE\".
12435 So for this example: when the item starts with TODO, it is changed to DONE.
12436 When it starts with DONE, the DONE is removed. And when neither TODO nor
12437 DONE are present, add TODO at the beginning of the heading.
12439 With \\[universal-argument] prefix arg, use completion to determine the new \
12440 state.
12441 With numeric prefix arg, switch to that state.
12442 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12443 keywords (nextset).
12444 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12445 With a numeric prefix arg of 0, inhibit note taking for the change.
12446 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12448 When called through ELisp, arg is also interpreted in the following way:
12449 'none -> empty state
12450 \"\"(empty string) -> switch to empty state
12451 'done -> switch to DONE
12452 'nextset -> switch to the next set of keywords
12453 'previousset -> switch to the previous set of keywords
12454 \"WAITING\" -> switch to the specified keyword, but only if it
12455 really is a member of `org-todo-keywords'."
12456 (interactive "P")
12457 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12458 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12459 'region-start-level 'region))
12460 org-loop-over-headlines-in-active-region)
12461 (org-map-entries
12462 `(org-todo ,arg)
12463 org-loop-over-headlines-in-active-region
12464 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12465 (if (equal arg '(16)) (setq arg 'nextset))
12466 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12467 (let ((org-blocker-hook org-blocker-hook)
12468 commentp
12469 case-fold-search)
12470 (when (equal arg '(64))
12471 (setq arg nil org-blocker-hook nil))
12472 (when (and org-blocker-hook
12473 (or org-inhibit-blocking
12474 (org-entry-get nil "NOBLOCKING")))
12475 (setq org-blocker-hook nil))
12476 (save-excursion
12477 (catch 'exit
12478 (org-back-to-heading t)
12479 (when (org-in-commented-heading-p t)
12480 (org-toggle-comment)
12481 (setq commentp t))
12482 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12483 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12484 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12485 (let* ((match-data (match-data))
12486 (startpos (point-at-bol))
12487 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12488 (org-log-done org-log-done)
12489 (org-log-repeat org-log-repeat)
12490 (org-todo-log-states org-todo-log-states)
12491 (org-inhibit-logging
12492 (if (equal arg 0)
12493 (progn (setq arg nil) 'note) org-inhibit-logging))
12494 (this (match-string 1))
12495 (hl-pos (match-beginning 0))
12496 (head (org-get-todo-sequence-head this))
12497 (ass (assoc head org-todo-kwd-alist))
12498 (interpret (nth 1 ass))
12499 (done-word (nth 3 ass))
12500 (final-done-word (nth 4 ass))
12501 (org-last-state (or this ""))
12502 (completion-ignore-case t)
12503 (member (member this org-todo-keywords-1))
12504 (tail (cdr member))
12505 (org-state (cond
12506 ((and org-todo-key-trigger
12507 (or (and (equal arg '(4))
12508 (eq org-use-fast-todo-selection 'prefix))
12509 (and (not arg) org-use-fast-todo-selection
12510 (not (eq org-use-fast-todo-selection
12511 'prefix)))))
12512 ;; Use fast selection
12513 (org-fast-todo-selection))
12514 ((and (equal arg '(4))
12515 (or (not org-use-fast-todo-selection)
12516 (not org-todo-key-trigger)))
12517 ;; Read a state with completion
12518 (org-icompleting-read
12519 "State: " (mapcar 'list org-todo-keywords-1)
12520 nil t))
12521 ((eq arg 'right)
12522 (if this
12523 (if tail (car tail) nil)
12524 (car org-todo-keywords-1)))
12525 ((eq arg 'left)
12526 (if (equal member org-todo-keywords-1)
12528 (if this
12529 (nth (- (length org-todo-keywords-1)
12530 (length tail) 2)
12531 org-todo-keywords-1)
12532 (org-last org-todo-keywords-1))))
12533 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12534 (setq arg nil))) ; hack to fall back to cycling
12535 (arg
12536 ;; user or caller requests a specific state
12537 (cond
12538 ((equal arg "") nil)
12539 ((eq arg 'none) nil)
12540 ((eq arg 'done) (or done-word (car org-done-keywords)))
12541 ((eq arg 'nextset)
12542 (or (car (cdr (member head org-todo-heads)))
12543 (car org-todo-heads)))
12544 ((eq arg 'previousset)
12545 (let ((org-todo-heads (reverse org-todo-heads)))
12546 (or (car (cdr (member head org-todo-heads)))
12547 (car org-todo-heads))))
12548 ((car (member arg org-todo-keywords-1)))
12549 ((stringp arg)
12550 (user-error "State `%s' not valid in this file" arg))
12551 ((nth (1- (prefix-numeric-value arg))
12552 org-todo-keywords-1))))
12553 ((null member) (or head (car org-todo-keywords-1)))
12554 ((equal this final-done-word) nil) ;; -> make empty
12555 ((null tail) nil) ;; -> first entry
12556 ((memq interpret '(type priority))
12557 (if (eq this-command last-command)
12558 (car tail)
12559 (if (> (length tail) 0)
12560 (or done-word (car org-done-keywords))
12561 nil)))
12563 (car tail))))
12564 (org-state (or
12565 (run-hook-with-args-until-success
12566 'org-todo-get-default-hook org-state org-last-state)
12567 org-state))
12568 (next (if org-state (concat " " org-state " ") " "))
12569 (change-plist (list :type 'todo-state-change :from this :to org-state
12570 :position startpos))
12571 dolog now-done-p)
12572 (when org-blocker-hook
12573 (setq org-last-todo-state-is-todo
12574 (not (member this org-done-keywords)))
12575 (unless (save-excursion
12576 (save-match-data
12577 (org-with-wide-buffer
12578 (run-hook-with-args-until-failure
12579 'org-blocker-hook change-plist))))
12580 (if (org-called-interactively-p 'interactive)
12581 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12582 this org-state org-block-entry-blocking)
12583 ;; fail silently
12584 (message "TODO state change from %s to %s blocked (by \"%s\")"
12585 this org-state org-block-entry-blocking)
12586 (throw 'exit nil))))
12587 (store-match-data match-data)
12588 (replace-match next t t)
12589 (cond ((equal this org-state)
12590 (message "TODO state was already %s" (org-trim next)))
12591 ((pos-visible-in-window-p hl-pos)
12592 (message "TODO state changed to %s" (org-trim next))))
12593 (unless head
12594 (setq head (org-get-todo-sequence-head org-state)
12595 ass (assoc head org-todo-kwd-alist)
12596 interpret (nth 1 ass)
12597 done-word (nth 3 ass)
12598 final-done-word (nth 4 ass)))
12599 (when (memq arg '(nextset previousset))
12600 (message "Keyword-Set %d/%d: %s"
12601 (- (length org-todo-sets) -1
12602 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12603 (length org-todo-sets)
12604 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12605 (setq org-last-todo-state-is-todo
12606 (not (member org-state org-done-keywords)))
12607 (setq now-done-p (and (member org-state org-done-keywords)
12608 (not (member this org-done-keywords))))
12609 (and logging (org-local-logging logging))
12610 (when (and (or org-todo-log-states org-log-done)
12611 (not (eq org-inhibit-logging t))
12612 (not (memq arg '(nextset previousset))))
12613 ;; we need to look at recording a time and note
12614 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12615 (nth 2 (assoc this org-todo-log-states))))
12616 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12617 (setq dolog 'time))
12618 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12619 (and org-state
12620 (member org-state org-not-done-keywords)
12621 (not (member this org-not-done-keywords))))
12622 ;; This is now a todo state and was not one before
12623 ;; If there was a CLOSED time stamp, get rid of it.
12624 (org-add-planning-info nil nil 'closed))
12625 (when (and now-done-p org-log-done)
12626 ;; It is now done, and it was not done before
12627 (org-add-planning-info 'closed (org-current-effective-time))
12628 (if (and (not dolog) (eq 'note org-log-done))
12629 (org-add-log-setup 'done org-state this 'findpos 'note)))
12630 (when (and org-state dolog)
12631 ;; This is a non-nil state, and we need to log it
12632 (org-add-log-setup 'state org-state this 'findpos dolog)))
12633 ;; Fixup tag positioning
12634 (org-todo-trigger-tag-changes org-state)
12635 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12636 (when org-provide-todo-statistics
12637 (org-update-parent-todo-statistics))
12638 (run-hooks 'org-after-todo-state-change-hook)
12639 (if (and arg (not (member org-state org-done-keywords)))
12640 (setq head (org-get-todo-sequence-head org-state)))
12641 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12642 ;; Do we need to trigger a repeat?
12643 (when now-done-p
12644 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12645 ;; This is for the agenda, take a snapshot of the headline.
12646 (save-match-data
12647 (setq org-agenda-headline-snapshot-before-repeat
12648 (org-get-heading))))
12649 (org-auto-repeat-maybe org-state))
12650 ;; Fixup cursor location if close to the keyword
12651 (if (and (outline-on-heading-p)
12652 (not (bolp))
12653 (save-excursion (beginning-of-line 1)
12654 (looking-at org-todo-line-regexp))
12655 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12656 (progn
12657 (goto-char (or (match-end 2) (match-end 1)))
12658 (and (looking-at " ") (just-one-space))))
12659 (when org-trigger-hook
12660 (save-excursion
12661 (run-hook-with-args 'org-trigger-hook change-plist)))
12662 (when commentp (org-toggle-comment))))))))
12664 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12665 "Block turning an entry into a TODO, using the hierarchy.
12666 This checks whether the current task should be blocked from state
12667 changes. Such blocking occurs when:
12669 1. The task has children which are not all in a completed state.
12671 2. A task has a parent with the property :ORDERED:, and there
12672 are siblings prior to the current task with incomplete
12673 status.
12675 3. The parent of the task is blocked because it has siblings that should
12676 be done first, or is child of a block grandparent TODO entry."
12678 (if (not org-enforce-todo-dependencies)
12679 t ; if locally turned off don't block
12680 (catch 'dont-block
12681 ;; If this is not a todo state change, or if this entry is already DONE,
12682 ;; do not block
12683 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12684 (member (plist-get change-plist :from)
12685 (cons 'done org-done-keywords))
12686 (member (plist-get change-plist :to)
12687 (cons 'todo org-not-done-keywords))
12688 (not (plist-get change-plist :to)))
12689 (throw 'dont-block t))
12690 ;; If this task has children, and any are undone, it's blocked
12691 (save-excursion
12692 (org-back-to-heading t)
12693 (let ((this-level (funcall outline-level)))
12694 (outline-next-heading)
12695 (let ((child-level (funcall outline-level)))
12696 (while (and (not (eobp))
12697 (> child-level this-level))
12698 ;; this todo has children, check whether they are all
12699 ;; completed
12700 (if (and (not (org-entry-is-done-p))
12701 (org-entry-is-todo-p))
12702 (progn (setq org-block-entry-blocking (org-get-heading))
12703 (throw 'dont-block nil)))
12704 (outline-next-heading)
12705 (setq child-level (funcall outline-level))))))
12706 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12707 ;; any previous siblings are undone, it's blocked
12708 (save-excursion
12709 (org-back-to-heading t)
12710 (let* ((pos (point))
12711 (parent-pos (and (org-up-heading-safe) (point))))
12712 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12713 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12714 (forward-line 1)
12715 (re-search-forward org-not-done-heading-regexp pos t))
12716 (setq org-block-entry-blocking (match-string 0))
12717 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12718 ;; Search further up the hierarchy, to see if an ancestor is blocked
12719 (while t
12720 (goto-char parent-pos)
12721 (if (not (looking-at org-not-done-heading-regexp))
12722 (throw 'dont-block t)) ; do not block, parent is not a TODO
12723 (setq pos (point))
12724 (setq parent-pos (and (org-up-heading-safe) (point)))
12725 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12726 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12727 (forward-line 1)
12728 (re-search-forward org-not-done-heading-regexp pos t)
12729 (setq org-block-entry-blocking (org-get-heading)))
12730 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12732 (defcustom org-track-ordered-property-with-tag nil
12733 "Should the ORDERED property also be shown as a tag?
12734 The ORDERED property decides if an entry should require subtasks to be
12735 completed in sequence. Since a property is not very visible, setting
12736 this option means that toggling the ORDERED property with the command
12737 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12738 not relevant for the behavior, but it makes things more visible.
12740 Note that toggling the tag with tags commands will not change the property
12741 and therefore not influence behavior!
12743 This can be t, meaning the tag ORDERED should be used, It can also be a
12744 string to select a different tag for this task."
12745 :group 'org-todo
12746 :type '(choice
12747 (const :tag "No tracking" nil)
12748 (const :tag "Track with ORDERED tag" t)
12749 (string :tag "Use other tag")))
12751 (defun org-toggle-ordered-property ()
12752 "Toggle the ORDERED property of the current entry.
12753 For better visibility, you can track the value of this property with a tag.
12754 See variable `org-track-ordered-property-with-tag'."
12755 (interactive)
12756 (let* ((t1 org-track-ordered-property-with-tag)
12757 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12758 (save-excursion
12759 (org-back-to-heading)
12760 (if (org-entry-get nil "ORDERED")
12761 (progn
12762 (org-delete-property "ORDERED")
12763 (and tag (org-toggle-tag tag 'off))
12764 (message "Subtasks can be completed in arbitrary order"))
12765 (org-entry-put nil "ORDERED" "t")
12766 (and tag (org-toggle-tag tag 'on))
12767 (message "Subtasks must be completed in sequence")))))
12769 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12770 (defun org-block-todo-from-checkboxes (change-plist)
12771 "Block turning an entry into a TODO, using checkboxes.
12772 This checks whether the current task should be blocked from state
12773 changes because there are unchecked boxes in this entry."
12774 (if (not org-enforce-todo-checkbox-dependencies)
12775 t ; if locally turned off don't block
12776 (catch 'dont-block
12777 ;; If this is not a todo state change, or if this entry is already DONE,
12778 ;; do not block
12779 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12780 (member (plist-get change-plist :from)
12781 (cons 'done org-done-keywords))
12782 (member (plist-get change-plist :to)
12783 (cons 'todo org-not-done-keywords))
12784 (not (plist-get change-plist :to)))
12785 (throw 'dont-block t))
12786 ;; If this task has checkboxes that are not checked, it's blocked
12787 (save-excursion
12788 (org-back-to-heading t)
12789 (let ((beg (point)) end)
12790 (outline-next-heading)
12791 (setq end (point))
12792 (goto-char beg)
12793 (if (org-list-search-forward
12794 (concat (org-item-beginning-re)
12795 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12796 "\\[[- ]\\]")
12797 end t)
12798 (progn
12799 (if (boundp 'org-blocked-by-checkboxes)
12800 (setq org-blocked-by-checkboxes t))
12801 (throw 'dont-block nil)))))
12802 t))) ; do not block
12804 (defun org-entry-blocked-p ()
12805 "Is the current entry blocked?"
12806 (org-with-silent-modifications
12807 (if (org-entry-get nil "NOBLOCKING")
12808 nil ;; Never block this entry
12809 (not (run-hook-with-args-until-failure
12810 'org-blocker-hook
12811 (list :type 'todo-state-change
12812 :position (point)
12813 :from 'todo
12814 :to 'done))))))
12816 (defun org-update-statistics-cookies (all)
12817 "Update the statistics cookie, either from TODO or from checkboxes.
12818 This should be called with the cursor in a line with a statistics cookie."
12819 (interactive "P")
12820 (if all
12821 (progn
12822 (org-update-checkbox-count 'all)
12823 (org-map-entries 'org-update-parent-todo-statistics))
12824 (if (not (org-at-heading-p))
12825 (org-update-checkbox-count)
12826 (let ((pos (point-marker))
12827 end l1 l2)
12828 (ignore-errors (org-back-to-heading t))
12829 (if (not (org-at-heading-p))
12830 (org-update-checkbox-count)
12831 (setq l1 (org-outline-level))
12832 (setq end (save-excursion
12833 (outline-next-heading)
12834 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12835 (point)))
12836 (if (and (save-excursion
12837 (re-search-forward
12838 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12839 (not (save-excursion (re-search-forward
12840 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12841 (org-update-checkbox-count)
12842 (if (and l2 (> l2 l1))
12843 (progn
12844 (goto-char end)
12845 (org-update-parent-todo-statistics))
12846 (goto-char pos)
12847 (beginning-of-line 1)
12848 (while (re-search-forward
12849 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12850 (point-at-eol) t)
12851 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12852 (goto-char pos)
12853 (move-marker pos nil)))))
12855 (defvar org-entry-property-inherited-from) ;; defined below
12856 (defun org-update-parent-todo-statistics ()
12857 "Update any statistics cookie in the parent of the current headline.
12858 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12859 the entire subtree and this will travel up the hierarchy and update
12860 statistics everywhere."
12861 (let* ((prop (save-excursion (org-up-heading-safe)
12862 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12863 (recursive (or (not org-hierarchical-todo-statistics)
12864 (and prop (string-match "\\<recursive\\>" prop))))
12865 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12867 (first t)
12868 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12869 level ltoggle l1 new ndel
12870 (cnt-all 0) (cnt-done 0) is-percent kwd
12871 checkbox-beg ov ovs ove cookie-present)
12872 (catch 'exit
12873 (save-excursion
12874 (beginning-of-line 1)
12875 (setq ltoggle (funcall outline-level))
12876 ;; Three situations are to consider:
12878 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12879 ;; to the top-level ancestor on the headline;
12881 ;; 2. If parent has "recursive" property, repeat up to the
12882 ;; headline setting that property, taking inheritance into
12883 ;; account;
12885 ;; 3. Else, move up to direct parent and proceed only once.
12886 (while (and (setq level (org-up-heading-safe))
12887 (or recursive first)
12888 (>= (point) lim))
12889 (setq first nil cookie-present nil)
12890 (unless (and level
12891 (not (string-match
12892 "\\<checkbox\\>"
12893 (downcase (or (org-entry-get nil "COOKIE_DATA")
12894 "")))))
12895 (throw 'exit nil))
12896 (while (re-search-forward box-re (point-at-eol) t)
12897 (setq cnt-all 0 cnt-done 0 cookie-present t)
12898 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12899 (save-match-data
12900 (unless (outline-next-heading) (throw 'exit nil))
12901 (while (and (looking-at org-complex-heading-regexp)
12902 (> (setq l1 (length (match-string 1))) level))
12903 (setq kwd (and (or recursive (= l1 ltoggle))
12904 (match-string 2)))
12905 (if (or (eq org-provide-todo-statistics 'all-headlines)
12906 (and (eq org-provide-todo-statistics t)
12907 (or (member kwd org-done-keywords)))
12908 (and (listp org-provide-todo-statistics)
12909 (stringp (car org-provide-todo-statistics))
12910 (or (member kwd org-provide-todo-statistics)
12911 (member kwd org-done-keywords)))
12912 (and (listp org-provide-todo-statistics)
12913 (listp (car org-provide-todo-statistics))
12914 (or (member kwd (car org-provide-todo-statistics))
12915 (and (member kwd org-done-keywords)
12916 (member kwd (cadr org-provide-todo-statistics))))))
12917 (setq cnt-all (1+ cnt-all))
12918 (if (eq org-provide-todo-statistics t)
12919 (and kwd (setq cnt-all (1+ cnt-all)))))
12920 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12921 (member kwd org-done-keywords))
12922 (and (listp org-provide-todo-statistics)
12923 (listp (car org-provide-todo-statistics))
12924 (member kwd org-done-keywords)
12925 (member kwd (cadr org-provide-todo-statistics)))
12926 (and (listp org-provide-todo-statistics)
12927 (stringp (car org-provide-todo-statistics))
12928 (member kwd org-done-keywords)))
12929 (setq cnt-done (1+ cnt-done)))
12930 (outline-next-heading)))
12931 (setq new
12932 (if is-percent
12933 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12934 (format "[%d/%d]" cnt-done cnt-all))
12935 ndel (- (match-end 0) checkbox-beg))
12936 ;; handle overlays when updating cookie from column view
12937 (when (setq ov (car (overlays-at checkbox-beg)))
12938 (setq ovs (overlay-start ov) ove (overlay-end ov))
12939 (delete-overlay ov))
12940 (goto-char checkbox-beg)
12941 (insert new)
12942 (delete-region (point) (+ (point) ndel))
12943 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12944 (when ov (move-overlay ov ovs ove)))
12945 (when cookie-present
12946 (run-hook-with-args 'org-after-todo-statistics-hook
12947 cnt-done (- cnt-all cnt-done))))))
12948 (run-hooks 'org-todo-statistics-hook)))
12950 (defvar org-after-todo-statistics-hook nil
12951 "Hook that is called after a TODO statistics cookie has been updated.
12952 Each function is called with two arguments: the number of not-done entries
12953 and the number of done entries.
12955 For example, the following function, when added to this hook, will switch
12956 an entry to DONE when all children are done, and back to TODO when new
12957 entries are set to a TODO status. Note that this hook is only called
12958 when there is a statistics cookie in the headline!
12960 (defun org-summary-todo (n-done n-not-done)
12961 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12962 (let (org-log-done org-log-states) ; turn off logging
12963 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12966 (defvar org-todo-statistics-hook nil
12967 "Hook that is run whenever Org thinks TODO statistics should be updated.
12968 This hook runs even if there is no statistics cookie present, in which case
12969 `org-after-todo-statistics-hook' would not run.")
12971 (defun org-todo-trigger-tag-changes (state)
12972 "Apply the changes defined in `org-todo-state-tags-triggers'."
12973 (let ((l org-todo-state-tags-triggers)
12974 changes)
12975 (when (or (not state) (equal state ""))
12976 (setq changes (append changes (cdr (assoc "" l)))))
12977 (when (and (stringp state) (> (length state) 0))
12978 (setq changes (append changes (cdr (assoc state l)))))
12979 (when (member state org-not-done-keywords)
12980 (setq changes (append changes (cdr (assoc 'todo l)))))
12981 (when (member state org-done-keywords)
12982 (setq changes (append changes (cdr (assoc 'done l)))))
12983 (dolist (c changes)
12984 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12986 (defun org-local-logging (value)
12987 "Get logging settings from a property VALUE."
12988 (let* (words w a)
12989 ;; directly set the variables, they are already local.
12990 (setq org-log-done nil
12991 org-log-repeat nil
12992 org-todo-log-states nil)
12993 (setq words (org-split-string value))
12994 (while (setq w (pop words))
12995 (cond
12996 ((setq a (assoc w org-startup-options))
12997 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12998 (set (nth 1 a) (nth 2 a))))
12999 ((setq a (org-extract-log-state-settings w))
13000 (and (member (car a) org-todo-keywords-1)
13001 (push a org-todo-log-states)))))))
13003 (defun org-get-todo-sequence-head (kwd)
13004 "Return the head of the TODO sequence to which KWD belongs.
13005 If KWD is not set, check if there is a text property remembering the
13006 right sequence."
13007 (let (p)
13008 (cond
13009 ((not kwd)
13010 (or (get-text-property (point-at-bol) 'org-todo-head)
13011 (progn
13012 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13013 nil (point-at-eol)))
13014 (get-text-property p 'org-todo-head))))
13015 ((not (member kwd org-todo-keywords-1))
13016 (car org-todo-keywords-1))
13017 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13019 (defun org-fast-todo-selection ()
13020 "Fast TODO keyword selection with single keys.
13021 Returns the new TODO keyword, or nil if no state change should occur."
13022 (let* ((fulltable org-todo-key-alist)
13023 (done-keywords org-done-keywords) ;; needed for the faces.
13024 (maxlen (apply 'max (mapcar
13025 (lambda (x)
13026 (if (stringp (car x)) (string-width (car x)) 0))
13027 fulltable)))
13028 (expert nil)
13029 (fwidth (+ maxlen 3 1 3))
13030 (ncol (/ (- (window-width) 4) fwidth))
13031 tg cnt e c tbl
13032 groups ingroup)
13033 (save-excursion
13034 (save-window-excursion
13035 (if expert
13036 (set-buffer (get-buffer-create " *Org todo*"))
13037 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13038 (erase-buffer)
13039 (org-set-local 'org-done-keywords done-keywords)
13040 (setq tbl fulltable cnt 0)
13041 (while (setq e (pop tbl))
13042 (cond
13043 ((equal e '(:startgroup))
13044 (push '() groups) (setq ingroup t)
13045 (when (not (= cnt 0))
13046 (setq cnt 0)
13047 (insert "\n"))
13048 (insert "{ "))
13049 ((equal e '(:endgroup))
13050 (setq ingroup nil cnt 0)
13051 (insert "}\n"))
13052 ((equal e '(:newline))
13053 (when (not (= cnt 0))
13054 (setq cnt 0)
13055 (insert "\n")
13056 (setq e (car tbl))
13057 (while (equal (car tbl) '(:newline))
13058 (insert "\n")
13059 (setq tbl (cdr tbl)))))
13061 (setq tg (car e) c (cdr e))
13062 (if ingroup (push tg (car groups)))
13063 (setq tg (org-add-props tg nil 'face
13064 (org-get-todo-face tg)))
13065 (if (and (= cnt 0) (not ingroup)) (insert " "))
13066 (insert "[" c "] " tg (make-string
13067 (- fwidth 4 (length tg)) ?\ ))
13068 (when (= (setq cnt (1+ cnt)) ncol)
13069 (insert "\n")
13070 (if ingroup (insert " "))
13071 (setq cnt 0)))))
13072 (insert "\n")
13073 (goto-char (point-min))
13074 (if (not expert) (org-fit-window-to-buffer))
13075 (message "[a-z..]:Set [SPC]:clear")
13076 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13077 (cond
13078 ((or (= c ?\C-g)
13079 (and (= c ?q) (not (rassoc c fulltable))))
13080 (setq quit-flag t))
13081 ((= c ?\ ) nil)
13082 ((setq e (rassoc c fulltable) tg (car e))
13084 (t (setq quit-flag t)))))))
13086 (defun org-entry-is-todo-p ()
13087 (member (org-get-todo-state) org-not-done-keywords))
13089 (defun org-entry-is-done-p ()
13090 (member (org-get-todo-state) org-done-keywords))
13092 (defun org-get-todo-state ()
13093 "Return the TODO keyword of the current subtree."
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (and (looking-at org-todo-line-regexp)
13097 (match-end 2)
13098 (match-string 2))))
13100 (defun org-at-date-range-p (&optional inactive-ok)
13101 "Is the cursor inside a date range?"
13102 (interactive)
13103 (save-excursion
13104 (catch 'exit
13105 (let ((pos (point)))
13106 (skip-chars-backward "^[<\r\n")
13107 (skip-chars-backward "<[")
13108 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13109 (>= (match-end 0) pos)
13110 (throw 'exit t))
13111 (skip-chars-backward "^<[\r\n")
13112 (skip-chars-backward "<[")
13113 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13114 (>= (match-end 0) pos)
13115 (throw 'exit t)))
13116 nil)))
13118 (defun org-get-repeat (&optional tagline)
13119 "Check if there is a deadline/schedule with repeater in this entry."
13120 (save-match-data
13121 (save-excursion
13122 (org-back-to-heading t)
13123 (and (re-search-forward (if tagline
13124 (concat tagline "\\s-*" org-repeat-re)
13125 org-repeat-re)
13126 (org-entry-end-position) t)
13127 (match-string-no-properties 1)))))
13129 (defvar org-last-changed-timestamp)
13130 (defvar org-last-inserted-timestamp)
13131 (defvar org-log-post-message)
13132 (defvar org-log-note-purpose)
13133 (defvar org-log-note-how nil)
13134 (defvar org-log-note-extra)
13135 (defun org-auto-repeat-maybe (done-word)
13136 "Check if the current headline contains a repeated deadline/schedule.
13137 If yes, set TODO state back to what it was and change the base date
13138 of repeating deadline/scheduled time stamps to new date.
13139 This function is run automatically after each state change to a DONE state."
13140 ;; last-state is dynamically scoped into this function
13141 (let* ((repeat (org-get-repeat))
13142 (aa (assoc org-last-state org-todo-kwd-alist))
13143 (interpret (nth 1 aa))
13144 (head (nth 2 aa))
13145 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13146 (msg "Entry repeats: ")
13147 (org-log-done nil)
13148 (org-todo-log-states nil)
13149 re type n what ts time to-state)
13150 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13151 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13152 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13153 org-todo-repeat-to-state))
13154 (unless (and to-state (member to-state org-todo-keywords-1))
13155 (setq to-state (if (eq interpret 'type) org-last-state head)))
13156 (org-todo to-state)
13157 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13158 (org-entry-put nil "LAST_REPEAT" (format-time-string
13159 (org-time-stamp-format t t))))
13160 (when org-log-repeat
13161 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13162 (memq 'org-add-log-note post-command-hook))
13163 ;; OK, we are already setup for some record
13164 (if (eq org-log-repeat 'note)
13165 ;; make sure we take a note, not only a time stamp
13166 (setq org-log-note-how 'note))
13167 ;; Set up for taking a record
13168 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13169 org-last-state
13170 'findpos org-log-repeat)))
13171 (org-back-to-heading t)
13172 (org-add-planning-info nil nil 'closed)
13173 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13174 org-deadline-time-regexp "\\)\\|\\("
13175 org-ts-regexp "\\)"))
13176 (while (re-search-forward
13177 re (save-excursion (outline-next-heading) (point)) t)
13178 (setq type (if (match-end 1) org-scheduled-string
13179 (if (match-end 3) org-deadline-string "Plain:"))
13180 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13181 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13182 (setq n (string-to-number (match-string 2 ts))
13183 what (match-string 3 ts))
13184 (if (equal what "w") (setq n (* n 7) what "d"))
13185 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13186 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13187 ;; Preparation, see if we need to modify the start date for the change
13188 (when (match-end 1)
13189 (setq time (save-match-data (org-time-string-to-time ts)))
13190 (cond
13191 ((equal (match-string 1 ts) ".")
13192 ;; Shift starting date to today
13193 (org-timestamp-change
13194 (- (org-today) (time-to-days time))
13195 'day))
13196 ((equal (match-string 1 ts) "+")
13197 (let ((nshiftmax 10) (nshift 0))
13198 (while (or (= nshift 0)
13199 (<= (time-to-days time)
13200 (time-to-days (current-time))))
13201 (when (= (incf nshift) nshiftmax)
13202 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13203 (user-error "Abort")))
13204 (org-timestamp-change n (cdr (assoc what whata)))
13205 (org-at-timestamp-p t)
13206 (setq ts (match-string 1))
13207 (setq time (save-match-data (org-time-string-to-time ts)))))
13208 (org-timestamp-change (- n) (cdr (assoc what whata)))
13209 ;; rematch, so that we have everything in place for the real shift
13210 (org-at-timestamp-p t)
13211 (setq ts (match-string 1))
13212 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13213 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13214 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13215 (setq org-log-post-message msg)
13216 (message "%s" msg))))
13218 (defun org-show-todo-tree (arg)
13219 "Make a compact tree which shows all headlines marked with TODO.
13220 The tree will show the lines where the regexp matches, and all higher
13221 headlines above the match.
13222 With a \\[universal-argument] prefix, prompt for a regexp to match.
13223 With a numeric prefix N, construct a sparse tree for the Nth element
13224 of `org-todo-keywords-1'."
13225 (interactive "P")
13226 (let ((case-fold-search nil)
13227 (kwd-re
13228 (cond ((null arg) org-not-done-regexp)
13229 ((equal arg '(4))
13230 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13231 (mapcar 'list org-todo-keywords-1))))
13232 (concat "\\("
13233 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13234 "\\)\\>")))
13235 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13236 (regexp-quote (nth (1- (prefix-numeric-value arg))
13237 org-todo-keywords-1)))
13238 (t (user-error "Invalid prefix argument: %s" arg)))))
13239 (message "%d TODO entries found"
13240 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13242 (defun org-deadline (arg &optional time)
13243 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13244 With one universal prefix argument, remove any deadline from the item.
13245 With two universal prefix arguments, prompt for a warning delay.
13246 With argument TIME, set the deadline at the corresponding date. TIME
13247 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13248 (interactive "P")
13249 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13250 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13251 'region-start-level 'region))
13252 org-loop-over-headlines-in-active-region)
13253 (org-map-entries
13254 `(org-deadline ',arg ,time)
13255 org-loop-over-headlines-in-active-region
13256 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13257 (let* ((old-date (org-entry-get nil "DEADLINE"))
13258 (old-date-time (if old-date (org-time-string-to-time old-date)))
13259 (repeater (and old-date
13260 (string-match
13261 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13262 old-date)
13263 (match-string 1 old-date))))
13264 (cond
13265 ((equal arg '(4))
13266 (when (and old-date org-log-redeadline)
13267 (org-add-log-setup 'deldeadline nil old-date 'findpos
13268 org-log-redeadline))
13269 (org-remove-timestamp-with-keyword org-deadline-string)
13270 (message "Item no longer has a deadline."))
13271 ((equal arg '(16))
13272 (save-excursion
13273 (org-back-to-heading t)
13274 (if (re-search-forward
13275 org-deadline-time-regexp
13276 (save-excursion (outline-next-heading) (point)) t)
13277 (let* ((rpl0 (match-string 1))
13278 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13279 (replace-match
13280 (concat org-deadline-string
13281 " <" rpl
13282 (format " -%dd"
13283 (abs
13284 (- (time-to-days
13285 (save-match-data
13286 (org-read-date nil t nil "Warn starting from" old-date-time)))
13287 (time-to-days old-date-time))))
13288 ">") t t))
13289 (user-error "No deadline information to update"))))
13291 (org-add-planning-info 'deadline time 'closed)
13292 (when (and old-date org-log-redeadline
13293 (not (equal old-date
13294 (substring org-last-inserted-timestamp 1 -1))))
13295 (org-add-log-setup 'redeadline nil old-date 'findpos
13296 org-log-redeadline))
13297 (when repeater
13298 (save-excursion
13299 (org-back-to-heading t)
13300 (when (re-search-forward (concat org-deadline-string " "
13301 org-last-inserted-timestamp)
13302 (save-excursion
13303 (outline-next-heading) (point)) t)
13304 (goto-char (1- (match-end 0)))
13305 (insert " " repeater)
13306 (setq org-last-inserted-timestamp
13307 (concat (substring org-last-inserted-timestamp 0 -1)
13308 " " repeater
13309 (substring org-last-inserted-timestamp -1))))))
13310 (message "Deadline on %s" org-last-inserted-timestamp))))))
13312 (defun org-schedule (arg &optional time)
13313 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13314 With one universal prefix argument, remove any scheduling date from the item.
13315 With two universal prefix arguments, prompt for a delay cookie.
13316 With argument TIME, scheduled at the corresponding date. TIME can
13317 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13318 (interactive "P")
13319 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13320 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13321 'region-start-level 'region))
13322 org-loop-over-headlines-in-active-region)
13323 (org-map-entries
13324 `(org-schedule ',arg ,time)
13325 org-loop-over-headlines-in-active-region
13326 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13327 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13328 (old-date-time (if old-date (org-time-string-to-time old-date)))
13329 (repeater (and old-date
13330 (string-match
13331 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13332 old-date)
13333 (match-string 1 old-date))))
13334 (cond
13335 ((equal arg '(4))
13336 (progn
13337 (when (and old-date org-log-reschedule)
13338 (org-add-log-setup 'delschedule nil old-date 'findpos
13339 org-log-reschedule))
13340 (org-remove-timestamp-with-keyword org-scheduled-string)
13341 (message "Item is no longer scheduled.")))
13342 ((equal arg '(16))
13343 (save-excursion
13344 (org-back-to-heading t)
13345 (if (re-search-forward
13346 org-scheduled-time-regexp
13347 (save-excursion (outline-next-heading) (point)) t)
13348 (let* ((rpl0 (match-string 1))
13349 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13350 (replace-match
13351 (concat org-scheduled-string
13352 " <" rpl
13353 (format " -%dd"
13354 (abs
13355 (- (time-to-days
13356 (save-match-data
13357 (org-read-date nil t nil "Delay until" old-date-time)))
13358 (time-to-days old-date-time))))
13359 ">") t t))
13360 (user-error "No scheduled information to update"))))
13362 (org-add-planning-info 'scheduled time 'closed)
13363 (when (and old-date org-log-reschedule
13364 (not (equal old-date
13365 (substring org-last-inserted-timestamp 1 -1))))
13366 (org-add-log-setup 'reschedule nil old-date 'findpos
13367 org-log-reschedule))
13368 (when repeater
13369 (save-excursion
13370 (org-back-to-heading t)
13371 (when (re-search-forward (concat org-scheduled-string " "
13372 org-last-inserted-timestamp)
13373 (save-excursion
13374 (outline-next-heading) (point)) t)
13375 (goto-char (1- (match-end 0)))
13376 (insert " " repeater)
13377 (setq org-last-inserted-timestamp
13378 (concat (substring org-last-inserted-timestamp 0 -1)
13379 " " repeater
13380 (substring org-last-inserted-timestamp -1))))))
13381 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13383 (defun org-get-scheduled-time (pom &optional inherit)
13384 "Get the scheduled time as a time tuple, of a format suitable
13385 for calling org-schedule with, or if there is no scheduling,
13386 returns nil."
13387 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13388 (when time
13389 (apply 'encode-time (org-parse-time-string time)))))
13391 (defun org-get-deadline-time (pom &optional inherit)
13392 "Get the deadline as a time tuple, of a format suitable for
13393 calling org-deadline with, or if there is no scheduling, returns
13394 nil."
13395 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13396 (when time
13397 (apply 'encode-time (org-parse-time-string time)))))
13399 (defun org-remove-timestamp-with-keyword (keyword)
13400 "Remove all time stamps with KEYWORD in the current entry."
13401 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13402 beg)
13403 (save-excursion
13404 (org-back-to-heading t)
13405 (setq beg (point))
13406 (outline-next-heading)
13407 (while (re-search-backward re beg t)
13408 (replace-match "")
13409 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13410 (equal (char-before) ?\ ))
13411 (backward-delete-char 1)
13412 (if (string-match "^[ \t]*$" (buffer-substring
13413 (point-at-bol) (point-at-eol)))
13414 (delete-region (point-at-bol)
13415 (min (point-max) (1+ (point-at-eol))))))))))
13417 (defvar org-time-was-given) ; dynamically scoped parameter
13418 (defvar org-end-time-was-given) ; dynamically scoped parameter
13420 (defun org-at-planning-p ()
13421 "Non-nil when point is on a planning info line."
13422 ;; This is as accurate and faster than `org-element-at-point' since
13423 ;; planning info location is fixed in the section.
13424 (org-with-wide-buffer
13425 (beginning-of-line)
13426 (and (org-looking-at-p org-planning-line-re)
13427 (eq (point)
13428 (ignore-errors
13429 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13430 (org-back-to-heading t)
13431 (org-with-limited-levels (org-back-to-heading t)))
13432 (line-beginning-position 2))))))
13434 (defun org-add-planning-info (what &optional time &rest remove)
13435 "Insert new timestamp with keyword in the planning line.
13436 WHAT indicates what kind of time stamp to add. It is a symbol
13437 among `closed', `deadline', `scheduled' and nil. TIME indicates
13438 the time to use. If none is given, the user is prompted for
13439 a date. REMOVE indicates what kind of entries to remove. An old
13440 WHAT entry will also be removed."
13441 (let (org-time-was-given org-end-time-was-given default-time default-input)
13442 (catch 'exit
13443 (when (and (memq what '(scheduled deadline))
13444 (or (not time)
13445 (and (stringp time)
13446 (string-match "^[-+]+[0-9]" time))))
13447 ;; Try to get a default date/time from existing timestamp
13448 (save-excursion
13449 (org-back-to-heading t)
13450 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13451 (when (re-search-forward (if (eq what 'scheduled)
13452 org-scheduled-time-regexp
13453 org-deadline-time-regexp)
13454 end t)
13455 (setq ts (match-string 1)
13456 default-time (apply 'encode-time (org-parse-time-string ts))
13457 default-input (and ts (org-get-compact-tod ts)))))))
13458 (when what
13459 (setq time
13460 (if (stringp time)
13461 ;; This is a string (relative or absolute), set
13462 ;; proper date.
13463 (apply #'encode-time
13464 (org-read-date-analyze
13465 time default-time (decode-time default-time)))
13466 ;; If necessary, get the time from the user
13467 (or time (org-read-date nil 'to-time nil nil
13468 default-time default-input)))))
13470 (org-with-wide-buffer
13471 (org-back-to-heading t)
13472 (forward-line)
13473 (unless (bolp) (insert "\n"))
13474 (cond ((org-looking-at-p org-planning-line-re)
13475 ;; Move to current indentation.
13476 (skip-chars-forward " \t")
13477 ;; Check if we have to remove something.
13478 (dolist (type (if what (cons what remove) remove))
13479 (save-excursion
13480 (when (re-search-forward
13481 (concat
13482 " *"
13483 (case type
13484 (closed org-closed-time-regexp)
13485 (deadline org-deadline-time-regexp)
13486 (scheduled org-scheduled-time-regexp)
13487 (otherwise
13488 (error "Invalid planning type: %s" type))))
13489 (line-end-position) t)
13490 (replace-match "")
13491 (when (looking-at "--+<[^>]+>") (replace-match ""))
13492 (when (and (not what) (eq type 'closed))
13493 (save-excursion
13494 (beginning-of-line)
13495 (when (looking-at "[ \t]*$")
13496 (delete-region (point)
13497 (line-beginning-position 2)))))))
13498 ;; Remove leading white spaces.
13499 (when (looking-at "[ \t]+") (replace-match ""))))
13500 ((not what) (throw 'exit nil)) ; Nothing to do.
13501 (t (insert-before-markers "\n")
13502 (backward-char 1)
13503 (when org-adapt-indentation
13504 (org-indent-to-column (1+ (org-outline-level))))))
13505 (when what
13506 ;; Insert planning keyword.
13507 (insert (case what
13508 (closed org-closed-string)
13509 (deadline org-deadline-string)
13510 (scheduled org-scheduled-string)
13511 (otherwise (error "Invalid planning type: %s" what)))
13512 " ")
13513 ;; Insert associated timestamp.
13514 (let ((ts (org-insert-time-stamp
13515 time
13516 (or org-time-was-given
13517 (and (eq what 'closed) org-log-done-with-time))
13518 (eq what 'closed)
13519 nil nil (list org-end-time-was-given))))
13520 (unless (eolp) (insert " "))
13521 ts))))))
13523 (defvar org-log-note-marker (make-marker))
13524 (defvar org-log-note-purpose nil)
13525 (defvar org-log-note-state nil)
13526 (defvar org-log-note-previous-state nil)
13527 (defvar org-log-note-extra nil)
13528 (defvar org-log-note-window-configuration nil)
13529 (defvar org-log-note-return-to (make-marker))
13530 (defvar org-log-note-effective-time nil
13531 "Remembered current time so that dynamically scoped
13532 `org-extend-today-until' affects tha timestamps in state change
13533 log")
13535 (defvar org-log-post-message nil
13536 "Message to be displayed after a log note has been stored.
13537 The auto-repeater uses this.")
13539 (defun org-add-note ()
13540 "Add a note to the current entry.
13541 This is done in the same way as adding a state change note."
13542 (interactive)
13543 (org-add-log-setup 'note nil nil 'findpos nil))
13545 (defun org-log-beginning (&optional create)
13546 "Return expected start of log notes in current entry.
13547 When optional argument CREATE is non-nil, the function creates
13548 a drawer to store notes, if necessary. Returned position ignores
13549 narrowing."
13550 (org-with-wide-buffer
13551 (org-end-of-meta-data)
13552 (let ((end (if (org-at-heading-p) (point)
13553 (save-excursion (outline-next-heading) (point))))
13554 (drawer (org-log-into-drawer)))
13555 (cond
13556 (drawer
13557 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13558 (case-fold-search t))
13559 (catch 'exit
13560 ;; Try to find existing drawer.
13561 (while (re-search-forward regexp end t)
13562 (let ((element (org-element-at-point)))
13563 (when (eq (org-element-type element) 'drawer)
13564 (let ((cend (org-element-property :contents-end element)))
13565 (when (and (not org-log-states-order-reversed) cend)
13566 (goto-char cend)))
13567 (throw 'exit nil))))
13568 ;; No drawer found. Create one, if permitted.
13569 (when create
13570 (unless (bolp) (insert "\n"))
13571 (let ((beg (point)))
13572 (insert ":" drawer ":\n:END:\n")
13573 (org-indent-region beg (point)))
13574 (end-of-line -1)))))
13575 (org-log-state-notes-insert-after-drawers
13576 (while (and (looking-at org-drawer-regexp)
13577 (progn (goto-char (match-end 0))
13578 (re-search-forward org-property-end-re end t)))
13579 (forward-line)))))
13580 (if (bolp) (point) (line-beginning-position 2))))
13582 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13583 "Set up the post command hook to take a note.
13584 If this is about to TODO state change, the new state is expected in STATE.
13585 When FINDPOS is non-nil, find the correct position for the note in
13586 the current entry. If not, assume that it can be inserted at point.
13587 HOW is an indicator what kind of note should be created.
13588 EXTRA is additional text that will be inserted into the notes buffer."
13589 (org-with-wide-buffer
13590 (when findpos
13591 (goto-char (org-log-beginning t))
13592 (unless org-log-states-order-reversed
13593 (org-skip-over-state-notes)
13594 (skip-chars-backward " \t\n\r")
13595 (forward-line)))
13596 (move-marker org-log-note-marker (point))
13597 ;; Preserve position even if a property drawer is inserted in the
13598 ;; process.
13599 (set-marker-insertion-type org-log-note-marker t)
13600 (setq org-log-note-purpose purpose
13601 org-log-note-state state
13602 org-log-note-previous-state prev-state
13603 org-log-note-how how
13604 org-log-note-extra extra
13605 org-log-note-effective-time (org-current-effective-time))
13606 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13608 (defun org-skip-over-state-notes ()
13609 "Skip past the list of State notes in an entry."
13610 (when (ignore-errors (goto-char (org-in-item-p)))
13611 (let* ((struct (org-list-struct))
13612 (prevs (org-list-prevs-alist struct))
13613 (regexp
13614 (concat "[ \t]*- +"
13615 (replace-regexp-in-string
13616 " +" " +"
13617 (org-replace-escapes
13618 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13619 `(("%d" . ,org-ts-regexp-inactive)
13620 ("%D" . ,org-ts-regexp)
13621 ("%s" . "\"\\S-+\"")
13622 ("%S" . "\"\\S-+\"")
13623 ("%t" . ,org-ts-regexp-inactive)
13624 ("%T" . ,org-ts-regexp)
13625 ("%u" . ".*?")
13626 ("%U" . ".*?")))))))
13627 (while (org-looking-at-p regexp)
13628 (goto-char (or (org-list-get-next-item (point) struct prevs)
13629 (org-list-get-item-end (point) struct)))))))
13631 (defun org-add-log-note (&optional purpose)
13632 "Pop up a window for taking a note, and add this note later at point."
13633 (remove-hook 'post-command-hook 'org-add-log-note)
13634 (setq org-log-note-window-configuration (current-window-configuration))
13635 (delete-other-windows)
13636 (move-marker org-log-note-return-to (point))
13637 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13638 (goto-char org-log-note-marker)
13639 (org-switch-to-buffer-other-window "*Org Note*")
13640 (erase-buffer)
13641 (if (memq org-log-note-how '(time state))
13642 (let (current-prefix-arg) (org-store-log-note))
13643 (let ((org-inhibit-startup t)) (org-mode))
13644 (insert (format "# Insert note for %s.
13645 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13646 (cond
13647 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13648 ((eq org-log-note-purpose 'done) "closed todo item")
13649 ((eq org-log-note-purpose 'state)
13650 (format "state change from \"%s\" to \"%s\""
13651 (or org-log-note-previous-state "")
13652 (or org-log-note-state "")))
13653 ((eq org-log-note-purpose 'reschedule)
13654 "rescheduling")
13655 ((eq org-log-note-purpose 'delschedule)
13656 "no longer scheduled")
13657 ((eq org-log-note-purpose 'redeadline)
13658 "changing deadline")
13659 ((eq org-log-note-purpose 'deldeadline)
13660 "removing deadline")
13661 ((eq org-log-note-purpose 'refile)
13662 "refiling")
13663 ((eq org-log-note-purpose 'note)
13664 "this entry")
13665 (t (error "This should not happen")))))
13666 (if org-log-note-extra (insert org-log-note-extra))
13667 (org-set-local 'org-finish-function 'org-store-log-note)
13668 (run-hooks 'org-log-buffer-setup-hook)))
13670 (defvar org-note-abort nil) ; dynamically scoped
13671 (defun org-store-log-note ()
13672 "Finish taking a log note, and insert it to where it belongs."
13673 (let ((txt (buffer-string)))
13674 (kill-buffer (current-buffer))
13675 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13676 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13677 (setq txt (replace-match "" t t txt)))
13678 (if (string-match "\\s-+\\'" txt)
13679 (setq txt (replace-match "" t t txt)))
13680 (setq lines (org-split-string txt "\n"))
13681 (when (and note (string-match "\\S-" note))
13682 (setq note
13683 (org-replace-escapes
13684 note
13685 (list (cons "%u" (user-login-name))
13686 (cons "%U" user-full-name)
13687 (cons "%t" (format-time-string
13688 (org-time-stamp-format 'long 'inactive)
13689 org-log-note-effective-time))
13690 (cons "%T" (format-time-string
13691 (org-time-stamp-format 'long nil)
13692 org-log-note-effective-time))
13693 (cons "%d" (format-time-string
13694 (org-time-stamp-format nil 'inactive)
13695 org-log-note-effective-time))
13696 (cons "%D" (format-time-string
13697 (org-time-stamp-format nil nil)
13698 org-log-note-effective-time))
13699 (cons "%s" (cond
13700 ((not org-log-note-state) "")
13701 ((org-string-match-p org-ts-regexp
13702 org-log-note-state)
13703 (format "\"[%s]\""
13704 (substring org-log-note-state 1 -1)))
13705 (t (format "\"%s\"" org-log-note-state))))
13706 (cons "%S"
13707 (cond
13708 ((not org-log-note-previous-state) "")
13709 ((org-string-match-p org-ts-regexp
13710 org-log-note-previous-state)
13711 (format "\"[%s]\""
13712 (substring
13713 org-log-note-previous-state 1 -1)))
13714 (t (format "\"%s\""
13715 org-log-note-previous-state)))))))
13716 (when lines (setq note (concat note " \\\\")))
13717 (push note lines))
13718 (when (or current-prefix-arg org-note-abort)
13719 (when (org-log-into-drawer)
13720 (org-remove-empty-drawer-at org-log-note-marker))
13721 (setq lines nil))
13722 (when lines
13723 (with-current-buffer (marker-buffer org-log-note-marker)
13724 (org-with-wide-buffer
13725 (goto-char org-log-note-marker)
13726 (move-marker org-log-note-marker nil)
13727 ;; Make sure point is at the beginning of an empty line.
13728 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13729 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13730 ;; In an existing list, add a new item at the top level.
13731 ;; Otherwise, indent line like a regular one.
13732 (let ((itemp (org-in-item-p)))
13733 (if itemp
13734 (org-indent-line-to
13735 (let ((struct (save-excursion
13736 (goto-char itemp) (org-list-struct))))
13737 (org-list-get-ind (org-list-get-top-point struct) struct)))
13738 (org-indent-line)))
13739 (insert (org-list-bullet-string "-") (pop lines))
13740 (let ((ind (org-list-item-body-column (line-beginning-position))))
13741 (dolist (line lines)
13742 (insert "\n")
13743 (org-indent-line-to ind)
13744 (insert line)))
13745 (message "Note stored")
13746 (org-back-to-heading t)
13747 (org-cycle-hide-drawers 'children))
13748 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13749 ;; from within `org-add-log-note' because `buffer-undo-list'
13750 ;; is then modified outside of `org-with-remote-undo'.
13751 (when (eq this-command 'org-agenda-todo)
13752 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13753 ;; Don't add undo information when called from `org-agenda-todo'
13754 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13755 (set-window-configuration org-log-note-window-configuration)
13756 (with-current-buffer (marker-buffer org-log-note-return-to)
13757 (goto-char org-log-note-return-to))
13758 (move-marker org-log-note-return-to nil)
13759 (and org-log-post-message (message "%s" org-log-post-message))))
13761 (defun org-remove-empty-drawer-at (pos)
13762 "Remove an empty drawer at position POS.
13763 POS may also be a marker."
13764 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13765 (org-with-wide-buffer
13766 (goto-char pos)
13767 (let ((drawer (org-element-at-point)))
13768 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13769 (not (org-element-property :contents-begin drawer)))
13770 (delete-region (org-element-property :begin drawer)
13771 (progn (goto-char (org-element-property :end drawer))
13772 (skip-chars-backward " \r\t\n")
13773 (forward-line)
13774 (point))))))))
13776 (defvar org-ts-type nil)
13777 (defun org-sparse-tree (&optional arg type)
13778 "Create a sparse tree, prompt for the details.
13779 This command can create sparse trees. You first need to select the type
13780 of match used to create the tree:
13782 t Show all TODO entries.
13783 T Show entries with a specific TODO keyword.
13784 m Show entries selected by a tags/property match.
13785 p Enter a property name and its value (both with completion on existing
13786 names/values) and show entries with that property.
13787 r Show entries matching a regular expression (`/' can be used as well).
13788 b Show deadlines and scheduled items before a date.
13789 a Show deadlines and scheduled items after a date.
13790 d Show deadlines due within `org-deadline-warning-days'.
13791 D Show deadlines and scheduled items between a date range."
13792 (interactive "P")
13793 (setq type (or type org-sparse-tree-default-date-type))
13794 (setq org-ts-type type)
13795 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13796 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13797 [c]ycle through date types: %s"
13798 (case type
13799 (all "all timestamps")
13800 (scheduled "only scheduled")
13801 (deadline "only deadline")
13802 (active "only active timestamps")
13803 (inactive "only inactive timestamps")
13804 (closed "with a closed time-stamp")
13805 (otherwise "scheduled/deadline")))
13806 (let ((answer (read-char-exclusive)))
13807 (case answer
13809 (org-sparse-tree
13811 (cadr
13812 (memq type '(nil all scheduled deadline active inactive closed)))))
13813 (?d (call-interactively 'org-check-deadlines))
13814 (?b (call-interactively 'org-check-before-date))
13815 (?a (call-interactively 'org-check-after-date))
13816 (?D (call-interactively 'org-check-dates-range))
13817 (?t (call-interactively 'org-show-todo-tree))
13818 (?T (org-show-todo-tree '(4)))
13819 (?m (call-interactively 'org-match-sparse-tree))
13820 ((?p ?P)
13821 (let* ((kwd (org-icompleting-read
13822 "Property: " (mapcar 'list (org-buffer-property-keys))))
13823 (value (org-icompleting-read
13824 "Value: " (mapcar 'list (org-property-values kwd)))))
13825 (unless (string-match "\\`{.*}\\'" value)
13826 (setq value (concat "\"" value "\"")))
13827 (org-match-sparse-tree arg (concat kwd "=" value))))
13828 ((?r ?R ?/) (call-interactively 'org-occur))
13829 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13831 (defvar org-occur-highlights nil
13832 "List of overlays used for occur matches.")
13833 (make-variable-buffer-local 'org-occur-highlights)
13834 (defvar org-occur-parameters nil
13835 "Parameters of the active org-occur calls.
13836 This is a list, each call to org-occur pushes as cons cell,
13837 containing the regular expression and the callback, onto the list.
13838 The list can contain several entries if `org-occur' has been called
13839 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13840 will only contain one set of parameters. When the highlights are
13841 removed (for example with `C-c C-c', or with the next edit (depending
13842 on `org-remove-highlights-with-change'), this variable is emptied
13843 as well.")
13844 (make-variable-buffer-local 'org-occur-parameters)
13846 (defun org-occur (regexp &optional keep-previous callback)
13847 "Make a compact tree which shows all matches of REGEXP.
13848 The tree will show the lines where the regexp matches, and all higher
13849 headlines above the match. It will also show the heading after the match,
13850 to make sure editing the matching entry is easy.
13851 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13852 call to `org-occur' will be kept, to allow stacking of calls to this
13853 command.
13854 If CALLBACK is non-nil, it is a function which is called to confirm
13855 that the match should indeed be shown."
13856 (interactive "sRegexp: \nP")
13857 (when (equal regexp "")
13858 (user-error "Regexp cannot be empty"))
13859 (unless keep-previous
13860 (org-remove-occur-highlights nil nil t))
13861 (push (cons regexp callback) org-occur-parameters)
13862 (let ((cnt 0))
13863 (save-excursion
13864 (goto-char (point-min))
13865 (if (or (not keep-previous) ; do not want to keep
13866 (not org-occur-highlights)) ; no previous matches
13867 ;; hide everything
13868 (org-overview))
13869 (while (re-search-forward regexp nil t)
13870 (when (or (not callback)
13871 (save-match-data (funcall callback)))
13872 (setq cnt (1+ cnt))
13873 (when org-highlight-sparse-tree-matches
13874 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13875 (org-show-context 'occur-tree))))
13876 (when org-remove-highlights-with-change
13877 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13878 nil 'local))
13879 (unless org-sparse-tree-open-archived-trees
13880 (org-hide-archived-subtrees (point-min) (point-max)))
13881 (run-hooks 'org-occur-hook)
13882 (if (org-called-interactively-p 'interactive)
13883 (message "%d match(es) for regexp %s" cnt regexp))
13884 cnt))
13886 (defun org-occur-next-match (&optional n reset)
13887 "Function for `next-error-function' to find sparse tree matches.
13888 N is the number of matches to move, when negative move backwards.
13889 RESET is entirely ignored - this function always goes back to the
13890 starting point when no match is found."
13891 (let* ((limit (if (< n 0) (point-min) (point-max)))
13892 (search-func (if (< n 0)
13893 'previous-single-char-property-change
13894 'next-single-char-property-change))
13895 (n (abs n))
13896 (pos (point))
13898 (catch 'exit
13899 (while (setq p1 (funcall search-func (point) 'org-type))
13900 (when (equal p1 limit)
13901 (goto-char pos)
13902 (user-error "No more matches"))
13903 (when (equal (get-char-property p1 'org-type) 'org-occur)
13904 (setq n (1- n))
13905 (when (= n 0)
13906 (goto-char p1)
13907 (throw 'exit (point))))
13908 (goto-char p1))
13909 (goto-char p1)
13910 (user-error "No more matches"))))
13912 (defun org-show-context (&optional key)
13913 "Make sure point and context are visible.
13914 Optional argument KEY, when non-nil, is a symbol. See
13915 `org-show-context-detail' for allowed values and how much is to
13916 be shown."
13917 (org-show-set-visibility
13918 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13919 ((cdr (assq key org-show-context-detail)))
13920 (t (cdr (assq 'default org-show-context-detail))))))
13922 (defun org-show-set-visibility (detail)
13923 "Set visibility around point according to DETAIL.
13924 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13925 `tree', `canonical' or t. See `org-show-context-detail' for more
13926 information."
13927 (unless (org-before-first-heading-p)
13928 ;; Show current heading and possibly its entry, following headline
13929 ;; or all children.
13930 (if (and (org-at-heading-p) (not (eq detail 'local)))
13931 (org-flag-heading nil)
13932 (org-show-entry)
13933 (org-with-limited-levels
13934 (case detail
13935 ((tree canonical t) (show-children))
13936 ((nil minimal ancestors))
13937 (t (save-excursion
13938 (outline-next-heading)
13939 (org-flag-heading nil))))))
13940 ;; Show all siblings.
13941 (when (eq detail 'lineage) (org-show-siblings))
13942 ;; Show ancestors, possibly with their children.
13943 (when (memq detail '(ancestors lineage tree canonical t))
13944 (save-excursion
13945 (while (org-up-heading-safe)
13946 (org-flag-heading nil)
13947 (when (memq detail '(canonical t)) (org-show-entry))
13948 (when (memq detail '(tree canonical t)) (show-children)))))))
13950 (defvar org-reveal-start-hook nil
13951 "Hook run before revealing a location.")
13953 (defun org-reveal (&optional siblings)
13954 "Show current entry, hierarchy above it, and the following headline.
13956 This can be used to show a consistent set of context around
13957 locations exposed with `org-show-context'.
13959 With optional argument SIBLINGS, on each level of the hierarchy all
13960 siblings are shown. This repairs the tree structure to what it would
13961 look like when opened with hierarchical calls to `org-cycle'.
13963 With double optional argument \\[universal-argument] \\[universal-argument], \
13964 go to the parent and show the
13965 entire tree."
13966 (interactive "P")
13967 (run-hooks 'org-reveal-start-hook)
13968 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13969 ((equal siblings '(16))
13970 (save-excursion
13971 (when (org-up-heading-safe)
13972 (org-show-subtree)
13973 (run-hook-with-args 'org-cycle-hook 'subtree))))
13974 (t (org-show-set-visibility 'lineage))))
13976 (defun org-highlight-new-match (beg end)
13977 "Highlight from BEG to END and mark the highlight is an occur headline."
13978 (let ((ov (make-overlay beg end)))
13979 (overlay-put ov 'face 'secondary-selection)
13980 (overlay-put ov 'org-type 'org-occur)
13981 (push ov org-occur-highlights)))
13983 (defun org-remove-occur-highlights (&optional beg end noremove)
13984 "Remove the occur highlights from the buffer.
13985 BEG and END are ignored. If NOREMOVE is nil, remove this function
13986 from the `before-change-functions' in the current buffer."
13987 (interactive)
13988 (unless org-inhibit-highlight-removal
13989 (mapc 'delete-overlay org-occur-highlights)
13990 (setq org-occur-highlights nil)
13991 (setq org-occur-parameters nil)
13992 (unless noremove
13993 (remove-hook 'before-change-functions
13994 'org-remove-occur-highlights 'local))))
13996 ;;;; Priorities
13998 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13999 "Regular expression matching the priority indicator.")
14001 (defvar org-remove-priority-next-time nil)
14003 (defun org-priority-up ()
14004 "Increase the priority of the current item."
14005 (interactive)
14006 (org-priority 'up))
14008 (defun org-priority-down ()
14009 "Decrease the priority of the current item."
14010 (interactive)
14011 (org-priority 'down))
14013 (defun org-priority (&optional action show)
14014 "Change the priority of an item.
14015 ACTION can be `set', `up', `down', or a character."
14016 (interactive "P")
14017 (if (equal action '(4))
14018 (org-show-priority)
14019 (unless org-enable-priority-commands
14020 (user-error "Priority commands are disabled"))
14021 (setq action (or action 'set))
14022 (let (current new news have remove)
14023 (save-excursion
14024 (org-back-to-heading t)
14025 (if (looking-at org-priority-regexp)
14026 (setq current (string-to-char (match-string 2))
14027 have t))
14028 (cond
14029 ((eq action 'remove)
14030 (setq remove t new ?\ ))
14031 ((or (eq action 'set)
14032 (if (featurep 'xemacs) (characterp action) (integerp action)))
14033 (if (not (eq action 'set))
14034 (setq new action)
14035 (message "Priority %c-%c, SPC to remove: "
14036 org-highest-priority org-lowest-priority)
14037 (save-match-data
14038 (setq new (read-char-exclusive))))
14039 (if (and (= (upcase org-highest-priority) org-highest-priority)
14040 (= (upcase org-lowest-priority) org-lowest-priority))
14041 (setq new (upcase new)))
14042 (cond ((equal new ?\ ) (setq remove t))
14043 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14044 (user-error "Priority must be between `%c' and `%c'"
14045 org-highest-priority org-lowest-priority))))
14046 ((eq action 'up)
14047 (setq new (if have
14048 (1- current) ; normal cycling
14049 ;; last priority was empty
14050 (if (eq last-command this-command)
14051 org-lowest-priority ; wrap around empty to lowest
14052 ;; default
14053 (if org-priority-start-cycle-with-default
14054 org-default-priority
14055 (1- org-default-priority))))))
14056 ((eq action 'down)
14057 (setq new (if have
14058 (1+ current) ; normal cycling
14059 ;; last priority was empty
14060 (if (eq last-command this-command)
14061 org-highest-priority ; wrap around empty to highest
14062 ;; default
14063 (if org-priority-start-cycle-with-default
14064 org-default-priority
14065 (1+ org-default-priority))))))
14066 (t (user-error "Invalid action")))
14067 (if (or (< (upcase new) org-highest-priority)
14068 (> (upcase new) org-lowest-priority))
14069 (if (and (memq action '(up down))
14070 (not have) (not (eq last-command this-command)))
14071 ;; `new' is from default priority
14072 (error
14073 "The default can not be set, see `org-default-priority' why")
14074 ;; normal cycling: `new' is beyond highest/lowest priority
14075 ;; and is wrapped around to the empty priority
14076 (setq remove t)))
14077 (setq news (format "%c" new))
14078 (if have
14079 (if remove
14080 (replace-match "" t t nil 1)
14081 (replace-match news t t nil 2))
14082 (if remove
14083 (user-error "No priority cookie found in line")
14084 (let ((case-fold-search nil))
14085 (looking-at org-todo-line-regexp))
14086 (if (match-end 2)
14087 (progn
14088 (goto-char (match-end 2))
14089 (insert " [#" news "]"))
14090 (goto-char (match-beginning 3))
14091 (insert "[#" news "] "))))
14092 (org-set-tags nil 'align))
14093 (if remove
14094 (message "Priority removed")
14095 (message "Priority of current item set to %s" news)))))
14097 (defun org-show-priority ()
14098 "Show the priority of the current item.
14099 This priority is composed of the main priority given with the [#A] cookies,
14100 and by additional input from the age of a schedules or deadline entry."
14101 (interactive)
14102 (let ((pri (if (eq major-mode 'org-agenda-mode)
14103 (org-get-at-bol 'priority)
14104 (save-excursion
14105 (save-match-data
14106 (beginning-of-line)
14107 (and (looking-at org-heading-regexp)
14108 (org-get-priority (match-string 0))))))))
14109 (message "Priority is %d" (if pri pri -1000))))
14111 (defun org-get-priority (s)
14112 "Find priority cookie and return priority."
14113 (save-match-data
14114 (if (functionp org-get-priority-function)
14115 (funcall org-get-priority-function)
14116 (if (not (string-match org-priority-regexp s))
14117 (* 1000 (- org-lowest-priority org-default-priority))
14118 (* 1000 (- org-lowest-priority
14119 (string-to-char (match-string 2 s))))))))
14121 ;;;; Tags
14123 (defvar org-agenda-archives-mode)
14124 (defvar org-map-continue-from nil
14125 "Position from where mapping should continue.
14126 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14128 (defvar org-scanner-tags nil
14129 "The current tag list while the tags scanner is running.")
14130 (defvar org-trust-scanner-tags nil
14131 "Should `org-get-tags-at' use the tags for the scanner.
14132 This is for internal dynamical scoping only.
14133 When this is non-nil, the function `org-get-tags-at' will return the value
14134 of `org-scanner-tags' instead of building the list by itself. This
14135 can lead to large speed-ups when the tags scanner is used in a file with
14136 many entries, and when the list of tags is retrieved, for example to
14137 obtain a list of properties. Building the tags list for each entry in such
14138 a file becomes an N^2 operation - but with this variable set, it scales
14139 as N.")
14141 (defun org-scan-tags (action matcher todo-only &optional start-level)
14142 "Scan headline tags with inheritance and produce output ACTION.
14144 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14145 or `agenda' to produce an entry list for an agenda view. It can also be
14146 a Lisp form or a function that should be called at each matched headline, in
14147 this case the return value is a list of all return values from these calls.
14149 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14150 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14151 only lines with a not-done TODO keyword are included in the output.
14152 This should be the same variable that was scoped into
14153 and set by `org-make-tags-matcher' when it constructed MATCHER.
14155 START-LEVEL can be a string with asterisks, reducing the scope to
14156 headlines matching this string."
14157 (require 'org-agenda)
14158 (let* ((re (concat "^"
14159 (if start-level
14160 ;; Get the correct level to match
14161 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14162 org-outline-regexp)
14163 " *\\(\\<\\("
14164 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14165 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14166 (props (list 'face 'default
14167 'done-face 'org-agenda-done
14168 'undone-face 'default
14169 'mouse-face 'highlight
14170 'org-not-done-regexp org-not-done-regexp
14171 'org-todo-regexp org-todo-regexp
14172 'org-complex-heading-regexp org-complex-heading-regexp
14173 'help-echo
14174 (format "mouse-2 or RET jump to org file %s"
14175 (abbreviate-file-name
14176 (or (buffer-file-name (buffer-base-buffer))
14177 (buffer-name (buffer-base-buffer)))))))
14178 (org-map-continue-from nil)
14179 lspos tags tags-list
14180 (tags-alist (list (cons 0 org-file-tags)))
14181 (llast 0) rtn rtn1 level category i txt
14182 todo marker entry priority
14183 ts-date ts-date-type ts-date-pair)
14184 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14185 (setq action (list 'lambda nil action)))
14186 (save-excursion
14187 (goto-char (point-min))
14188 (when (eq action 'sparse-tree)
14189 (org-overview)
14190 (org-remove-occur-highlights))
14191 (while (let (case-fold-search)
14192 (re-search-forward re nil t))
14193 (setq org-map-continue-from nil)
14194 (catch :skip
14195 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14196 tags (if (match-end 4) (org-match-string-no-properties 4)))
14197 (goto-char (setq lspos (match-beginning 0)))
14198 (setq level (org-reduced-level (org-outline-level))
14199 category (org-get-category))
14200 (when (eq action 'agenda)
14201 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14202 ts-date (car ts-date-pair)
14203 ts-date-type (cdr ts-date-pair)))
14204 (setq i llast llast level)
14205 ;; remove tag lists from same and sublevels
14206 (while (>= i level)
14207 (when (setq entry (assoc i tags-alist))
14208 (setq tags-alist (delete entry tags-alist)))
14209 (setq i (1- i)))
14210 ;; add the next tags
14211 (when tags
14212 (setq tags (org-split-string tags ":")
14213 tags-alist
14214 (cons (cons level tags) tags-alist)))
14215 ;; compile tags for current headline
14216 (setq tags-list
14217 (if org-use-tag-inheritance
14218 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14219 tags)
14220 org-scanner-tags tags-list)
14221 (when org-use-tag-inheritance
14222 (setcdr (car tags-alist)
14223 (mapcar (lambda (x)
14224 (setq x (copy-sequence x))
14225 (org-add-prop-inherited x))
14226 (cdar tags-alist))))
14227 (when (and tags org-use-tag-inheritance
14228 (or (not (eq t org-use-tag-inheritance))
14229 org-tags-exclude-from-inheritance))
14230 ;; selective inheritance, remove uninherited ones
14231 (setcdr (car tags-alist)
14232 (org-remove-uninherited-tags (cdar tags-alist))))
14233 (when (and
14235 ;; eval matcher only when the todo condition is OK
14236 (and (or (not todo-only) (member todo org-not-done-keywords))
14237 (let ((case-fold-search t) (org-trust-scanner-tags t))
14238 (eval matcher)))
14240 ;; Call the skipper, but return t if it does not skip,
14241 ;; so that the `and' form continues evaluating
14242 (progn
14243 (unless (eq action 'sparse-tree) (org-agenda-skip))
14246 ;; Check if timestamps are deselecting this entry
14247 (or (not todo-only)
14248 (and (member todo org-not-done-keywords)
14249 (or (not org-agenda-tags-todo-honor-ignore-options)
14250 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14252 ;; select this headline
14253 (cond
14254 ((eq action 'sparse-tree)
14255 (and org-highlight-sparse-tree-matches
14256 (org-get-heading) (match-end 0)
14257 (org-highlight-new-match
14258 (match-beginning 1) (match-end 1)))
14259 (org-show-context 'tags-tree))
14260 ((eq action 'agenda)
14261 (setq txt (org-agenda-format-item
14263 (concat
14264 (if (eq org-tags-match-list-sublevels 'indented)
14265 (make-string (1- level) ?.) "")
14266 (org-get-heading))
14267 (make-string level ?\s)
14268 category
14269 tags-list)
14270 priority (org-get-priority txt))
14271 (goto-char lspos)
14272 (setq marker (org-agenda-new-marker))
14273 (org-add-props txt props
14274 'org-marker marker 'org-hd-marker marker 'org-category category
14275 'todo-state todo
14276 'ts-date ts-date
14277 'priority priority
14278 'type (concat "tagsmatch" ts-date-type))
14279 (push txt rtn))
14280 ((functionp action)
14281 (setq org-map-continue-from nil)
14282 (save-excursion
14283 (setq rtn1 (funcall action))
14284 (push rtn1 rtn)))
14285 (t (user-error "Invalid action")))
14287 ;; if we are to skip sublevels, jump to end of subtree
14288 (unless org-tags-match-list-sublevels
14289 (org-end-of-subtree t)
14290 (backward-char 1))))
14291 ;; Get the correct position from where to continue
14292 (if org-map-continue-from
14293 (goto-char org-map-continue-from)
14294 (and (= (point) lspos) (end-of-line 1)))))
14295 (when (and (eq action 'sparse-tree)
14296 (not org-sparse-tree-open-archived-trees))
14297 (org-hide-archived-subtrees (point-min) (point-max)))
14298 (nreverse rtn)))
14300 (defun org-remove-uninherited-tags (tags)
14301 "Remove all tags that are not inherited from the list TAGS."
14302 (cond
14303 ((eq org-use-tag-inheritance t)
14304 (if org-tags-exclude-from-inheritance
14305 (org-delete-all org-tags-exclude-from-inheritance tags)
14306 tags))
14307 ((not org-use-tag-inheritance) nil)
14308 ((stringp org-use-tag-inheritance)
14309 (delq nil (mapcar
14310 (lambda (x)
14311 (if (and (string-match org-use-tag-inheritance x)
14312 (not (member x org-tags-exclude-from-inheritance)))
14313 x nil))
14314 tags)))
14315 ((listp org-use-tag-inheritance)
14316 (delq nil (mapcar
14317 (lambda (x)
14318 (if (member x org-use-tag-inheritance) x nil))
14319 tags)))))
14321 (defun org-match-sparse-tree (&optional todo-only match)
14322 "Create a sparse tree according to tags string MATCH.
14323 MATCH can contain positive and negative selection of tags, like
14324 \"+WORK+URGENT-WITHBOSS\".
14325 If optional argument TODO-ONLY is non-nil, only select lines that are
14326 also TODO lines."
14327 (interactive "P")
14328 (org-agenda-prepare-buffers (list (current-buffer)))
14329 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14331 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14333 (defvar org-cached-props nil)
14334 (defun org-cached-entry-get (pom property)
14335 (if (or (eq t org-use-property-inheritance)
14336 (and (stringp org-use-property-inheritance)
14337 (let ((case-fold-search t))
14338 (org-string-match-p org-use-property-inheritance property)))
14339 (and (listp org-use-property-inheritance)
14340 (member-ignore-case property org-use-property-inheritance)))
14341 ;; Caching is not possible, check it directly.
14342 (org-entry-get pom property 'inherit)
14343 ;; Get all properties, so we can do complicated checks easily.
14344 (cdr (assoc-string property
14345 (or org-cached-props
14346 (setq org-cached-props (org-entry-properties pom)))
14347 t))))
14349 (defun org-global-tags-completion-table (&optional files)
14350 "Return the list of all tags in all agenda buffer/files.
14351 Optional FILES argument is a list of files which can be used
14352 instead of the agenda files."
14353 (save-excursion
14354 (org-uniquify
14355 (delq nil
14356 (apply 'append
14357 (mapcar
14358 (lambda (file)
14359 (set-buffer (find-file-noselect file))
14360 (append (org-get-buffer-tags)
14361 (mapcar (lambda (x) (if (stringp (car-safe x))
14362 (list (car-safe x)) nil))
14363 org-tag-alist)))
14364 (if (and files (car files))
14365 files
14366 (org-agenda-files))))))))
14368 (defun org-make-tags-matcher (match)
14369 "Create the TAGS/TODO matcher form for the selection string MATCH.
14371 The variable `todo-only' is scoped dynamically into this function.
14372 It will be set to t if the matcher restricts matching to TODO entries,
14373 otherwise will not be touched.
14375 Returns a cons of the selection string MATCH and the constructed
14376 lisp form implementing the matcher. The matcher is to be evaluated
14377 at an Org entry, with point on the headline, and returns t if the
14378 entry matches the selection string MATCH. The returned lisp form
14379 references two variables with information about the entry, which
14380 must be bound around the form's evaluation: todo, the TODO keyword
14381 at the entry (or nil of none); and tags-list, the list of all tags
14382 at the entry including inherited ones. Additionally, the category
14383 of the entry (if any) must be specified as the text property
14384 'org-category on the headline.
14386 See also `org-scan-tags'.
14388 (declare (special todo-only))
14389 (unless (boundp 'todo-only)
14390 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14391 (unless match
14392 ;; Get a new match request, with completion against the global
14393 ;; tags table and the local tags in current buffer
14394 (let ((org-last-tags-completion-table
14395 (org-uniquify
14396 (delq nil (append (org-get-buffer-tags)
14397 (org-global-tags-completion-table))))))
14398 (setq match (org-completing-read-no-i
14399 "Match: " 'org-tags-completion-function nil nil nil
14400 'org-tags-history))))
14402 ;; Parse the string and create a lisp form
14403 (let ((match0 match)
14404 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14405 minus tag mm
14406 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14407 orterms term orlist re-p str-p level-p level-op time-p
14408 prop-p pn pv po gv rest (start 0) (ss 0))
14409 ;; Expand group tags
14410 (setq match (org-tags-expand match))
14412 ;; Check if there is a TODO part of this match, which would be the
14413 ;; part after a "/". TO make sure that this slash is not part of
14414 ;; a property value to be matched against, we also check that there
14415 ;; is no " after that slash.
14416 ;; First, find the last slash
14417 (while (string-match "/+" match ss)
14418 (setq start (match-beginning 0) ss (match-end 0)))
14419 (if (and (string-match "/+" match start)
14420 (not (save-match-data (string-match "\"" match start))))
14421 ;; match contains also a todo-matching request
14422 (progn
14423 (setq tagsmatch (substring match 0 (match-beginning 0))
14424 todomatch (substring match (match-end 0)))
14425 (if (string-match "^!" todomatch)
14426 (setq todo-only t todomatch (substring todomatch 1)))
14427 (if (string-match "^\\s-*$" todomatch)
14428 (setq todomatch nil)))
14429 ;; only matching tags
14430 (setq tagsmatch match todomatch nil))
14432 ;; Make the tags matcher
14433 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14434 (setq tagsmatcher t)
14435 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14436 (while (setq term (pop orterms))
14437 (while (and (equal (substring term -1) "\\") orterms)
14438 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14439 (while (string-match re term)
14440 (setq rest (substring term (match-end 0))
14441 minus (and (match-end 1)
14442 (equal (match-string 1 term) "-"))
14443 tag (save-match-data (replace-regexp-in-string
14444 "\\\\-" "-"
14445 (match-string 2 term)))
14446 re-p (equal (string-to-char tag) ?{)
14447 level-p (match-end 4)
14448 prop-p (match-end 5)
14449 mm (cond
14450 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14451 (level-p
14452 (setq level-op (org-op-to-function (match-string 3 term)))
14453 `(,level-op level ,(string-to-number
14454 (match-string 4 term))))
14455 (prop-p
14456 (setq pn (match-string 5 term)
14457 po (match-string 6 term)
14458 pv (match-string 7 term)
14459 re-p (equal (string-to-char pv) ?{)
14460 str-p (equal (string-to-char pv) ?\")
14461 time-p (save-match-data
14462 (string-match "^\"[[<].*[]>]\"$" pv))
14463 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14464 (if time-p (setq pv (org-matcher-time pv)))
14465 (setq po (org-op-to-function po (if time-p 'time str-p)))
14466 (cond
14467 ((equal pn "CATEGORY")
14468 (setq gv '(get-text-property (point) 'org-category)))
14469 ((equal pn "TODO")
14470 (setq gv 'todo))
14472 (setq gv `(org-cached-entry-get nil ,pn))))
14473 (if re-p
14474 (if (eq po 'org<>)
14475 `(not (string-match ,pv (or ,gv "")))
14476 `(string-match ,pv (or ,gv "")))
14477 (if str-p
14478 `(,po (or ,gv "") ,pv)
14479 `(,po (string-to-number (or ,gv ""))
14480 ,(string-to-number pv) ))))
14481 (t `(member ,tag tags-list)))
14482 mm (if minus (list 'not mm) mm)
14483 term rest)
14484 (push mm tagsmatcher))
14485 (push (if (> (length tagsmatcher) 1)
14486 (cons 'and tagsmatcher)
14487 (car tagsmatcher))
14488 orlist)
14489 (setq tagsmatcher nil))
14490 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14491 (setq tagsmatcher
14492 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14493 ;; Make the todo matcher
14494 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14495 (setq todomatcher t)
14496 (setq orterms (org-split-string todomatch "|") orlist nil)
14497 (while (setq term (pop orterms))
14498 (while (string-match re term)
14499 (setq minus (and (match-end 1)
14500 (equal (match-string 1 term) "-"))
14501 kwd (match-string 2 term)
14502 re-p (equal (string-to-char kwd) ?{)
14503 term (substring term (match-end 0))
14504 mm (if re-p
14505 `(string-match ,(substring kwd 1 -1) todo)
14506 (list 'equal 'todo kwd))
14507 mm (if minus (list 'not mm) mm))
14508 (push mm todomatcher))
14509 (push (if (> (length todomatcher) 1)
14510 (cons 'and todomatcher)
14511 (car todomatcher))
14512 orlist)
14513 (setq todomatcher nil))
14514 (setq todomatcher (if (> (length orlist) 1)
14515 (cons 'or orlist) (car orlist))))
14517 ;; Return the string and lisp forms of the matcher
14518 (setq matcher (if todomatcher
14519 (list 'and tagsmatcher todomatcher)
14520 tagsmatcher))
14521 (when todo-only
14522 (setq matcher (list 'and '(member todo org-not-done-keywords)
14523 matcher)))
14524 (cons match0 matcher)))
14526 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14527 "Expand group tags in MATCH.
14529 This replaces every group tag in MATCH with a regexp tag search.
14530 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14531 will be replaced like this:
14533 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14534 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14535 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14537 Replacing by a regexp preserves the structure of the match.
14538 E.g., this expansion
14540 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14542 will match anything tagged with \"Lab\" and \"Home\", or tagged
14543 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14545 A group tag in MATCH can contain regular expressions of its own.
14546 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14547 will be replaced like this:
14549 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14551 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14552 assumed to be a single group tag, and the function will return
14553 the list of tags in this group.
14555 When DOWNCASE is non-nil, expand downcased TAGS."
14556 (if org-group-tags
14557 (let* ((case-fold-search t)
14558 (stable org-mode-syntax-table)
14559 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14560 (taggroups (if downcased
14561 (mapcar (lambda (tg) (mapcar #'downcase tg))
14562 taggroups)
14563 taggroups))
14564 (taggroups-keys (mapcar #'car taggroups))
14565 (return-match (if downcased (downcase match) match))
14566 (count 0)
14567 (work-already-expanded tags-already-expanded)
14568 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14569 ;; @ and _ are allowed as word-components in tags.
14570 (modify-syntax-entry ?@ "w" stable)
14571 (modify-syntax-entry ?_ "w" stable)
14572 ;; Temporarily replace regexp-expressions in the match-expression.
14573 (while (string-match "{.+?}" return-match)
14574 (incf count)
14575 (push (match-string 0 return-match) regexps-in-match)
14576 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14577 (while (and taggroups-keys
14578 (with-syntax-table stable
14579 (string-match
14580 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14581 (regexp-opt taggroups-keys) "\\>\\)") return-match)))
14582 (let* ((dir (match-string 1 return-match))
14583 (tag (match-string 2 return-match))
14584 (tag (if downcased (downcase tag) tag)))
14585 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14586 (member tag work-already-expanded))
14587 (setq tags-in-group (assoc tag taggroups))
14588 (push tag work-already-expanded)
14589 ;; Recursively expand each tag in the group, if the tag hasn't
14590 ;; already been expanded. Restore the match-data after all recursive calls.
14591 (save-match-data
14592 (let (tags-expanded)
14593 (dolist (x (cdr tags-in-group))
14594 (if (and (member x taggroups-keys)
14595 (not (member x work-already-expanded)))
14596 (setq tags-expanded
14597 (delete-dups
14598 (append
14599 (org-tags-expand x t downcased
14600 work-already-expanded)
14601 tags-expanded)))
14602 (setq tags-expanded
14603 (append (list x) tags-expanded)))
14604 (setq work-already-expanded
14605 (delete-dups
14606 (append tags-expanded
14607 work-already-expanded))))
14608 (setq tags-in-group
14609 (delete-dups (cons (car tags-in-group)
14610 tags-expanded)))))
14611 ;; Filter tag-regexps from tags.
14612 (setq regexp-in-group-escaped
14613 (delq nil (mapcar (lambda (x)
14614 (if (stringp x)
14615 (and (equal "{" (substring x 0 1))
14616 (equal "}" (substring x -1))
14619 tags-in-group))
14620 regexp-in-group
14621 (mapcar (lambda (x)
14622 (substring x 1 -1))
14623 regexp-in-group-escaped)
14624 tags-in-group
14625 (delq nil (mapcar (lambda (x)
14626 (if (stringp x)
14627 (and (not (equal "{" (substring x 0 1)))
14628 (not (equal "}" (substring x -1)))
14631 tags-in-group)))
14632 ;; If single-as-list, do no more in the while-loop.
14633 (if (not single-as-list)
14634 (progn
14635 (when regexp-in-group
14636 (setq regexp-in-group
14637 (concat "\\|"
14638 (mapconcat 'identity regexp-in-group
14639 "\\|"))))
14640 (setq tags-in-group
14641 (concat dir
14642 "{\\<"
14643 (regexp-opt tags-in-group)
14644 "\\>"
14645 regexp-in-group
14646 "}"))
14647 (when (stringp tags-in-group)
14648 (org-add-props tags-in-group '(grouptag t)))
14649 (setq return-match
14650 (replace-match tags-in-group t t return-match)))
14651 (setq tags-in-group
14652 (append regexp-in-group-escaped tags-in-group))))
14653 (setq taggroups-keys (delete tag taggroups-keys))))
14654 ;; Add the regular expressions back into the match-expression again.
14655 (while regexps-in-match
14656 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14657 (pop regexps-in-match)
14658 return-match t t))
14659 (decf count))
14660 (if single-as-list
14661 (if tags-in-group tags-in-group (list return-match))
14662 return-match))
14663 (if single-as-list
14664 (list (if downcased (downcase match) match))
14665 match)))
14667 (defun org-op-to-function (op &optional stringp)
14668 "Turn an operator into the appropriate function."
14669 (setq op
14670 (cond
14671 ((equal op "<" ) '(< string< org-time<))
14672 ((equal op ">" ) '(> org-string> org-time>))
14673 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14674 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14675 ((member op '("=" "==")) '(= string= org-time=))
14676 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14677 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14679 (defun org<> (a b) (not (= a b)))
14680 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14681 (defun org-string>= (a b) (not (string< a b)))
14682 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14683 (defun org-string<> (a b) (not (string= a b)))
14684 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14685 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14686 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14687 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14688 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14689 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14690 (defun org-2ft (s)
14691 "Convert S to a floating point time.
14692 If S is already a number, just return it. If it is a string, parse
14693 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14694 (cond
14695 ((numberp s) s)
14696 ((stringp s)
14697 (condition-case nil
14698 (float-time (apply 'encode-time (org-parse-time-string s)))
14699 (error 0.)))
14700 (t 0.)))
14702 (defun org-time-today ()
14703 "Time in seconds today at 0:00.
14704 Returns the float number of seconds since the beginning of the
14705 epoch to the beginning of today (00:00)."
14706 (float-time (apply 'encode-time
14707 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14709 (defun org-matcher-time (s)
14710 "Interpret a time comparison value."
14711 (save-match-data
14712 (cond
14713 ((string= s "<now>") (float-time))
14714 ((string= s "<today>") (org-time-today))
14715 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14716 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14717 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14718 (+ (org-time-today)
14719 (* (string-to-number (match-string 1 s))
14720 (cdr (assoc (match-string 2 s)
14721 '(("d" . 86400.0) ("w" . 604800.0)
14722 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14723 (t (org-2ft s)))))
14725 (defun org-match-any-p (re list)
14726 "Does re match any element of list?"
14727 (setq list (mapcar (lambda (x) (string-match re x)) list))
14728 (delq nil list))
14730 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14731 (defvar org-tags-overlay (make-overlay 1 1))
14732 (org-detach-overlay org-tags-overlay)
14734 (defun org-get-local-tags-at (&optional pos)
14735 "Get a list of tags defined in the current headline."
14736 (org-get-tags-at pos 'local))
14738 (defun org-get-local-tags ()
14739 "Get a list of tags defined in the current headline."
14740 (org-get-tags-at nil 'local))
14742 (defun org-get-tags-at (&optional pos local)
14743 "Get a list of all headline tags applicable at POS.
14744 POS defaults to point. If tags are inherited, the list contains
14745 the targets in the same sequence as the headlines appear, i.e.
14746 the tags of the current headline come last.
14747 When LOCAL is non-nil, only return tags from the current headline,
14748 ignore inherited ones."
14749 (interactive)
14750 (if (and org-trust-scanner-tags
14751 (or (not pos) (equal pos (point)))
14752 (not local))
14753 org-scanner-tags
14754 (let (tags ltags lastpos parent)
14755 (save-excursion
14756 (save-restriction
14757 (widen)
14758 (goto-char (or pos (point)))
14759 (save-match-data
14760 (catch 'done
14761 (condition-case nil
14762 (progn
14763 (org-back-to-heading t)
14764 (while (not (equal lastpos (point)))
14765 (setq lastpos (point))
14766 (when (looking-at
14767 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14768 (setq ltags (org-split-string
14769 (org-match-string-no-properties 1) ":"))
14770 (when parent
14771 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14772 (setq tags (append
14773 (if parent
14774 (org-remove-uninherited-tags ltags)
14775 ltags)
14776 tags)))
14777 (or org-use-tag-inheritance (throw 'done t))
14778 (if local (throw 'done t))
14779 (or (org-up-heading-safe) (error nil))
14780 (setq parent t)))
14781 (error nil)))))
14782 (if local
14783 tags
14784 (reverse (delete-dups
14785 (reverse (append
14786 (org-remove-uninherited-tags
14787 org-file-tags) tags)))))))))
14789 (defun org-add-prop-inherited (s)
14790 (add-text-properties 0 (length s) '(inherited t) s)
14793 (defun org-toggle-tag (tag &optional onoff)
14794 "Toggle the tag TAG for the current line.
14795 If ONOFF is `on' or `off', don't toggle but set to this state."
14796 (let (res current)
14797 (save-excursion
14798 (org-back-to-heading t)
14799 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14800 (point-at-eol) t)
14801 (progn
14802 (setq current (match-string 1))
14803 (replace-match ""))
14804 (setq current ""))
14805 (setq current (nreverse (org-split-string current ":")))
14806 (cond
14807 ((eq onoff 'on)
14808 (setq res t)
14809 (or (member tag current) (push tag current)))
14810 ((eq onoff 'off)
14811 (or (not (member tag current)) (setq current (delete tag current))))
14812 (t (if (member tag current)
14813 (setq current (delete tag current))
14814 (setq res t)
14815 (push tag current))))
14816 (end-of-line 1)
14817 (if current
14818 (progn
14819 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14820 (org-set-tags nil t))
14821 (delete-horizontal-space))
14822 (run-hooks 'org-after-tags-change-hook))
14823 res))
14825 (defun org-align-tags-here (to-col)
14826 ;; Assumes that this is a headline
14827 "Align tags on the current headline to TO-COL."
14828 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14829 (beginning-of-line 1)
14830 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14831 (< pos (match-beginning 2)))
14832 (progn
14833 (setq tags-l (- (match-end 2) (match-beginning 2)))
14834 (goto-char (match-beginning 1))
14835 (insert " ")
14836 (delete-region (point) (1+ (match-beginning 2)))
14837 (setq ncol (max (current-column)
14838 (1+ col)
14839 (if (> to-col 0)
14840 to-col
14841 (- (abs to-col) tags-l))))
14842 (setq p (point))
14843 (insert (make-string (- ncol (current-column)) ?\ ))
14844 (setq ncol (current-column))
14845 (when indent-tabs-mode (tabify p (point-at-eol)))
14846 (org-move-to-column (min ncol col)))
14847 (goto-char pos))))
14849 (defun org-set-tags-command (&optional arg just-align)
14850 "Call the set-tags command for the current entry."
14851 (interactive "P")
14852 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14853 (org-set-tags arg just-align)
14854 (save-excursion
14855 (unless (and (org-region-active-p)
14856 org-loop-over-headlines-in-active-region)
14857 (org-back-to-heading t))
14858 (org-set-tags arg just-align))))
14860 (defun org-set-tags-to (data)
14861 "Set the tags of the current entry to DATA, replacing the current tags.
14862 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14863 If DATA is nil or the empty string, any tags will be removed."
14864 (interactive "sTags: ")
14865 (setq data
14866 (cond
14867 ((eq data nil) "")
14868 ((equal data "") "")
14869 ((stringp data)
14870 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14871 ":"))
14872 ((listp data)
14873 (concat ":" (mapconcat 'identity data ":") ":"))))
14874 (when data
14875 (save-excursion
14876 (org-back-to-heading t)
14877 (when (looking-at org-complex-heading-regexp)
14878 (if (match-end 5)
14879 (progn
14880 (goto-char (match-beginning 5))
14881 (insert data)
14882 (delete-region (point) (point-at-eol))
14883 (org-set-tags nil 'align))
14884 (goto-char (point-at-eol))
14885 (insert " " data)
14886 (org-set-tags nil 'align)))
14887 (beginning-of-line 1)
14888 (if (looking-at ".*?\\([ \t]+\\)$")
14889 (delete-region (match-beginning 1) (match-end 1))))))
14891 (defun org-align-all-tags ()
14892 "Align the tags i all headings."
14893 (interactive)
14894 (save-excursion
14895 (or (ignore-errors (org-back-to-heading t))
14896 (outline-next-heading))
14897 (if (org-at-heading-p)
14898 (org-set-tags t)
14899 (message "No headings"))))
14901 (defvar org-indent-indentation-per-level)
14902 (defun org-set-tags (&optional arg just-align)
14903 "Set the tags for the current headline.
14904 With prefix ARG, realign all tags in headings in the current buffer.
14905 When JUST-ALIGN is non-nil, only align tags."
14906 (interactive "P")
14907 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14908 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14909 'region-start-level 'region))
14910 org-loop-over-headlines-in-active-region)
14911 (org-map-entries
14912 ;; We don't use ARG and JUST-ALIGN here because these args
14913 ;; are not useful when looping over headlines.
14914 `(org-set-tags)
14915 org-loop-over-headlines-in-active-region
14916 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14917 (let* ((re org-outline-regexp-bol)
14918 (current (unless arg (org-get-tags-string)))
14919 (col (current-column))
14920 (org-setting-tags t)
14921 table current-tags inherited-tags ; computed below when needed
14922 tags p0 c0 c1 rpl di tc level)
14923 (if arg
14924 (save-excursion
14925 (goto-char (point-min))
14926 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14927 (while (re-search-forward re nil t)
14928 (org-set-tags nil t)
14929 (end-of-line 1)))
14930 (message "All tags realigned to column %d" org-tags-column))
14931 (if just-align
14932 (setq tags current)
14933 ;; Get a new set of tags from the user
14934 (save-excursion
14935 (setq table (append org-tag-persistent-alist
14936 (or org-tag-alist (org-get-buffer-tags))
14937 (and
14938 org-complete-tags-always-offer-all-agenda-tags
14939 (org-global-tags-completion-table
14940 (org-agenda-files))))
14941 org-last-tags-completion-table table
14942 current-tags (org-split-string current ":")
14943 inherited-tags (nreverse
14944 (nthcdr (length current-tags)
14945 (nreverse (org-get-tags-at))))
14946 tags
14947 (if (or (eq t org-use-fast-tag-selection)
14948 (and org-use-fast-tag-selection
14949 (delq nil (mapcar 'cdr table))))
14950 (org-fast-tag-selection
14951 current-tags inherited-tags table
14952 (if org-fast-tag-selection-include-todo
14953 org-todo-key-alist))
14954 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14955 (org-trim
14956 (org-icompleting-read "Tags: "
14957 'org-tags-completion-function
14958 nil nil current 'org-tags-history))))))
14959 (while (string-match "[-+&]+" tags)
14960 ;; No boolean logic, just a list
14961 (setq tags (replace-match ":" t t tags))))
14963 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14965 (if org-tags-sort-function
14966 (setq tags (mapconcat 'identity
14967 (sort (org-split-string
14968 tags (org-re "[^[:alnum:]_@#%]+"))
14969 org-tags-sort-function) ":")))
14971 (if (string-match "\\`[\t ]*\\'" tags)
14972 (setq tags "")
14973 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14974 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14976 ;; Insert new tags at the correct column
14977 (beginning-of-line 1)
14978 (setq level (or (and (looking-at org-outline-regexp)
14979 (- (match-end 0) (point) 1))
14981 (cond
14982 ((and (equal current "") (equal tags "")))
14983 ((re-search-forward
14984 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14985 (point-at-eol) t)
14986 (if (equal tags "")
14987 (setq rpl "")
14988 (goto-char (match-beginning 0))
14989 (setq c0 (current-column)
14990 ;; compute offset for the case of org-indent-mode active
14991 di (if (org-bound-and-true-p org-indent-mode)
14992 (* (1- org-indent-indentation-per-level) (1- level))
14994 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14995 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14996 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14997 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14998 (replace-match rpl t t)
14999 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15000 tags)
15001 (t (error "Tags alignment failed")))
15002 (org-move-to-column col)
15003 (unless just-align
15004 (run-hooks 'org-after-tags-change-hook))))))
15006 (defun org-change-tag-in-region (beg end tag off)
15007 "Add or remove TAG for each entry in the region.
15008 This works in the agenda, and also in an org-mode buffer."
15009 (interactive
15010 (list (region-beginning) (region-end)
15011 (let ((org-last-tags-completion-table
15012 (if (derived-mode-p 'org-mode)
15013 (org-uniquify
15014 (delq nil (append (org-get-buffer-tags)
15015 (org-global-tags-completion-table))))
15016 (org-global-tags-completion-table))))
15017 (org-icompleting-read
15018 "Tag: " 'org-tags-completion-function nil nil nil
15019 'org-tags-history))
15020 (progn
15021 (message "[s]et or [r]emove? ")
15022 (equal (read-char-exclusive) ?r))))
15023 (if (fboundp 'deactivate-mark) (deactivate-mark))
15024 (let ((agendap (equal major-mode 'org-agenda-mode))
15025 l1 l2 m buf pos newhead (cnt 0))
15026 (goto-char end)
15027 (setq l2 (1- (org-current-line)))
15028 (goto-char beg)
15029 (setq l1 (org-current-line))
15030 (loop for l from l1 to l2 do
15031 (org-goto-line l)
15032 (setq m (get-text-property (point) 'org-hd-marker))
15033 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15034 (and agendap m))
15035 (setq buf (if agendap (marker-buffer m) (current-buffer))
15036 pos (if agendap m (point)))
15037 (with-current-buffer buf
15038 (save-excursion
15039 (save-restriction
15040 (goto-char pos)
15041 (setq cnt (1+ cnt))
15042 (org-toggle-tag tag (if off 'off 'on))
15043 (setq newhead (org-get-heading)))))
15044 (and agendap (org-agenda-change-all-lines newhead m))))
15045 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15047 (defun org-tags-completion-function (string predicate &optional flag)
15048 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15049 (confirm (lambda (x) (stringp (car x)))))
15050 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15051 (setq s1 (match-string 1 string)
15052 s2 (match-string 2 string))
15053 (setq s1 "" s2 string))
15054 (cond
15055 ((eq flag nil)
15056 ;; try completion
15057 (setq rtn (try-completion s2 ctable confirm))
15058 (if (stringp rtn)
15059 (setq rtn
15060 (concat s1 s2 (substring rtn (length s2))
15061 (if (and org-add-colon-after-tag-completion
15062 (assoc rtn ctable))
15063 ":" ""))))
15064 rtn)
15065 ((eq flag t)
15066 ;; all-completions
15067 (all-completions s2 ctable confirm))
15068 ((eq flag 'lambda)
15069 ;; exact match?
15070 (assoc s2 ctable)))))
15072 (defun org-fast-tag-insert (kwd tags face &optional end)
15073 "Insert KDW, and the TAGS, the latter with face FACE.
15074 Also insert END."
15075 (insert (format "%-12s" (concat kwd ":"))
15076 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15077 (or end "")))
15079 (defun org-fast-tag-show-exit (flag)
15080 (save-excursion
15081 (org-goto-line 3)
15082 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15083 (replace-match ""))
15084 (when flag
15085 (end-of-line 1)
15086 (org-move-to-column (- (window-width) 19) t)
15087 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15089 (defun org-set-current-tags-overlay (current prefix)
15090 "Add an overlay to CURRENT tag with PREFIX."
15091 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15092 (if (featurep 'xemacs)
15093 (org-overlay-display org-tags-overlay (concat prefix s)
15094 'secondary-selection)
15095 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15096 (org-overlay-display org-tags-overlay (concat prefix s)))))
15098 (defvar org-last-tag-selection-key nil)
15099 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15100 "Fast tag selection with single keys.
15101 CURRENT is the current list of tags in the headline, INHERITED is the
15102 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15103 possibly with grouping information. TODO-TABLE is a similar table with
15104 TODO keywords, should these have keys assigned to them.
15105 If the keys are nil, a-z are automatically assigned.
15106 Returns the new tags string, or nil to not change the current settings."
15107 (let* ((fulltable (append table todo-table))
15108 (maxlen (apply 'max (mapcar
15109 (lambda (x)
15110 (if (stringp (car x)) (string-width (car x)) 0))
15111 fulltable)))
15112 (buf (current-buffer))
15113 (expert (eq org-fast-tag-selection-single-key 'expert))
15114 (buffer-tags nil)
15115 (fwidth (+ maxlen 3 1 3))
15116 (ncol (/ (- (window-width) 4) fwidth))
15117 (i-face 'org-done)
15118 (c-face 'org-todo)
15119 tg cnt e c char c1 c2 ntable tbl rtn
15120 ov-start ov-end ov-prefix
15121 (exit-after-next org-fast-tag-selection-single-key)
15122 (done-keywords org-done-keywords)
15123 groups ingroup intaggroup)
15124 (save-excursion
15125 (beginning-of-line 1)
15126 (if (looking-at
15127 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15128 (setq ov-start (match-beginning 1)
15129 ov-end (match-end 1)
15130 ov-prefix "")
15131 (setq ov-start (1- (point-at-eol))
15132 ov-end (1+ ov-start))
15133 (skip-chars-forward "^\n\r")
15134 (setq ov-prefix
15135 (concat
15136 (buffer-substring (1- (point)) (point))
15137 (if (> (current-column) org-tags-column)
15139 (make-string (- org-tags-column (current-column)) ?\ ))))))
15140 (move-overlay org-tags-overlay ov-start ov-end)
15141 (save-window-excursion
15142 (if expert
15143 (set-buffer (get-buffer-create " *Org tags*"))
15144 (delete-other-windows)
15145 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15146 (org-switch-to-buffer-other-window " *Org tags*"))
15147 (erase-buffer)
15148 (org-set-local 'org-done-keywords done-keywords)
15149 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15150 (org-fast-tag-insert "Current" current c-face "\n\n")
15151 (org-fast-tag-show-exit exit-after-next)
15152 (org-set-current-tags-overlay current ov-prefix)
15153 (setq tbl fulltable char ?a cnt 0)
15154 (while (setq e (pop tbl))
15155 (cond
15156 ((eq (car e) :startgroup)
15157 (push '() groups) (setq ingroup t)
15158 (unless (zerop cnt)
15159 (setq cnt 0)
15160 (insert "\n"))
15161 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15162 ((eq (car e) :endgroup)
15163 (setq ingroup nil cnt 0)
15164 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15165 ((eq (car e) :startgrouptag)
15166 (setq intaggroup t)
15167 (unless (zerop cnt)
15168 (setq cnt 0)
15169 (insert "\n"))
15170 (insert "[ "))
15171 ((eq (car e) :endgrouptag)
15172 (setq intaggroup nil cnt 0)
15173 (insert "]\n"))
15174 ((equal e '(:newline))
15175 (unless (zerop cnt)
15176 (setq cnt 0)
15177 (insert "\n")
15178 (setq e (car tbl))
15179 (while (equal (car tbl) '(:newline))
15180 (insert "\n")
15181 (setq tbl (cdr tbl)))))
15182 ((equal e '(:grouptags)) (insert " : "))
15184 (setq tg (copy-sequence (car e)) c2 nil)
15185 (if (cdr e)
15186 (setq c (cdr e))
15187 ;; automatically assign a character.
15188 (setq c1 (string-to-char
15189 (downcase (substring
15190 tg (if (= (string-to-char tg) ?@) 1 0)))))
15191 (if (or (rassoc c1 ntable) (rassoc c1 table))
15192 (while (or (rassoc char ntable) (rassoc char table))
15193 (setq char (1+ char)))
15194 (setq c2 c1))
15195 (setq c (or c2 char)))
15196 (when ingroup (push tg (car groups)))
15197 (setq tg (org-add-props tg nil 'face
15198 (cond
15199 ((not (assoc tg table))
15200 (org-get-todo-face tg))
15201 ((member tg current) c-face)
15202 ((member tg inherited) i-face))))
15203 (when (equal (caar tbl) :grouptags)
15204 (org-add-props tg nil 'face 'org-tag-group))
15205 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15206 (insert "[" c "] " tg (make-string
15207 (- fwidth 4 (length tg)) ?\ ))
15208 (push (cons tg c) ntable)
15209 (when (= (incf cnt) ncol)
15210 (insert "\n")
15211 (when (or ingroup intaggroup) (insert " "))
15212 (setq cnt 0)))))
15213 (setq ntable (nreverse ntable))
15214 (insert "\n")
15215 (goto-char (point-min))
15216 (unless expert (org-fit-window-to-buffer))
15217 (setq rtn
15218 (catch 'exit
15219 (while t
15220 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15221 (if (not groups) "no " "")
15222 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15223 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15224 (setq org-last-tag-selection-key c)
15225 (cond
15226 ((= c ?\r) (throw 'exit t))
15227 ((= c ?!)
15228 (setq groups (not groups))
15229 (goto-char (point-min))
15230 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15231 ((= c ?\C-c)
15232 (if (not expert)
15233 (org-fast-tag-show-exit
15234 (setq exit-after-next (not exit-after-next)))
15235 (setq expert nil)
15236 (delete-other-windows)
15237 (set-window-buffer (split-window-vertically) " *Org tags*")
15238 (org-switch-to-buffer-other-window " *Org tags*")
15239 (org-fit-window-to-buffer)))
15240 ((or (= c ?\C-g)
15241 (and (= c ?q) (not (rassoc c ntable))))
15242 (org-detach-overlay org-tags-overlay)
15243 (setq quit-flag t))
15244 ((= c ?\ )
15245 (setq current nil)
15246 (when exit-after-next (setq exit-after-next 'now)))
15247 ((= c ?\t)
15248 (condition-case nil
15249 (setq tg (org-icompleting-read
15250 "Tag: "
15251 (or buffer-tags
15252 (with-current-buffer buf
15253 (org-get-buffer-tags)))))
15254 (quit (setq tg "")))
15255 (when (string-match "\\S-" tg)
15256 (add-to-list 'buffer-tags (list tg))
15257 (if (member tg current)
15258 (setq current (delete tg current))
15259 (push tg current)))
15260 (when exit-after-next (setq exit-after-next 'now)))
15261 ((setq e (rassoc c todo-table) tg (car e))
15262 (with-current-buffer buf
15263 (save-excursion (org-todo tg)))
15264 (when exit-after-next (setq exit-after-next 'now)))
15265 ((setq e (rassoc c ntable) tg (car e))
15266 (if (member tg current)
15267 (setq current (delete tg current))
15268 (loop for g in groups do
15269 (when (member tg g)
15270 (dolist (x g) (setq current (delete x current)))))
15271 (push tg current))
15272 (when exit-after-next (setq exit-after-next 'now))))
15274 ;; Create a sorted list
15275 (setq current
15276 (sort current
15277 (lambda (a b)
15278 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15279 (when (eq exit-after-next 'now) (throw 'exit t))
15280 (goto-char (point-min))
15281 (beginning-of-line 2)
15282 (delete-region (point) (point-at-eol))
15283 (org-fast-tag-insert "Current" current c-face)
15284 (org-set-current-tags-overlay current ov-prefix)
15285 (while (re-search-forward
15286 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15287 (setq tg (match-string 1))
15288 (add-text-properties
15289 (match-beginning 1) (match-end 1)
15290 (list 'face
15291 (cond
15292 ((member tg current) c-face)
15293 ((member tg inherited) i-face)
15294 (t (get-text-property (match-beginning 1) 'face))))))
15295 (goto-char (point-min)))))
15296 (org-detach-overlay org-tags-overlay)
15297 (if rtn
15298 (mapconcat 'identity current ":")
15299 nil))))
15301 (defun org-get-tags-string ()
15302 "Get the TAGS string in the current headline."
15303 (unless (org-at-heading-p t)
15304 (user-error "Not on a heading"))
15305 (save-excursion
15306 (beginning-of-line 1)
15307 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15308 (org-match-string-no-properties 1)
15309 "")))
15311 (defun org-get-tags ()
15312 "Get the list of tags specified in the current headline."
15313 (org-split-string (org-get-tags-string) ":"))
15315 (defun org-get-buffer-tags ()
15316 "Get a table of all tags used in the buffer, for completion."
15317 (org-with-wide-buffer
15318 (goto-char (point-min))
15319 (let ((tag-re (concat org-outline-regexp-bol
15320 "\\(?:.*?[ \t]\\)?"
15321 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15322 tags)
15323 (while (re-search-forward tag-re nil t)
15324 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15325 (push tag tags)))
15326 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15328 ;;;; The mapping API
15330 (defun org-map-entries (func &optional match scope &rest skip)
15331 "Call FUNC at each headline selected by MATCH in SCOPE.
15333 FUNC is a function or a lisp form. The function will be called without
15334 arguments, with the cursor positioned at the beginning of the headline.
15335 The return values of all calls to the function will be collected and
15336 returned as a list.
15338 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15339 does not need to preserve point. After evaluation, the cursor will be
15340 moved to the end of the line (presumably of the headline of the
15341 processed entry) and search continues from there. Under some
15342 circumstances, this may not produce the wanted results. For example,
15343 if you have removed (e.g. archived) the current (sub)tree it could
15344 mean that the next entry will be skipped entirely. In such cases, you
15345 can specify the position from where search should continue by making
15346 FUNC set the variable `org-map-continue-from' to the desired buffer
15347 position.
15349 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15350 Only headlines that are matched by this query will be considered during
15351 the iteration. When MATCH is nil or t, all headlines will be
15352 visited by the iteration.
15354 SCOPE determines the scope of this command. It can be any of:
15356 nil The current buffer, respecting the restriction if any
15357 tree The subtree started with the entry at point
15358 region The entries within the active region, if any
15359 region-start-level
15360 The entries within the active region, but only those at
15361 the same level than the first one.
15362 file The current buffer, without restriction
15363 file-with-archives
15364 The current buffer, and any archives associated with it
15365 agenda All agenda files
15366 agenda-with-archives
15367 All agenda files with any archive files associated with them
15368 \(file1 file2 ...)
15369 If this is a list, all files in the list will be scanned
15371 The remaining args are treated as settings for the skipping facilities of
15372 the scanner. The following items can be given here:
15374 archive skip trees with the archive tag
15375 comment skip trees with the COMMENT keyword
15376 function or Emacs Lisp form:
15377 will be used as value for `org-agenda-skip-function', so
15378 whenever the function returns a position, FUNC will not be
15379 called for that entry and search will continue from the
15380 position returned
15382 If your function needs to retrieve the tags including inherited tags
15383 at the *current* entry, you can use the value of the variable
15384 `org-scanner-tags' which will be much faster than getting the value
15385 with `org-get-tags-at'. If your function gets properties with
15386 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15387 to t around the call to `org-entry-properties' to get the same speedup.
15388 Note that if your function moves around to retrieve tags and properties at
15389 a *different* entry, you cannot use these techniques."
15390 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15391 (not (org-region-active-p)))
15392 (let* ((org-agenda-archives-mode nil) ; just to make sure
15393 (org-agenda-skip-archived-trees (memq 'archive skip))
15394 (org-agenda-skip-comment-trees (memq 'comment skip))
15395 (org-agenda-skip-function
15396 (car (org-delete-all '(comment archive) skip)))
15397 (org-tags-match-list-sublevels t)
15398 (start-level (eq scope 'region-start-level))
15399 matcher file res
15400 org-todo-keywords-for-agenda
15401 org-done-keywords-for-agenda
15402 org-todo-keyword-alist-for-agenda
15403 org-tag-alist-for-agenda
15404 todo-only)
15406 (cond
15407 ((eq match t) (setq matcher t))
15408 ((eq match nil) (setq matcher t))
15409 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15411 (save-excursion
15412 (save-restriction
15413 (cond ((eq scope 'tree)
15414 (org-back-to-heading t)
15415 (org-narrow-to-subtree)
15416 (setq scope nil))
15417 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15418 (org-region-active-p))
15419 ;; If needed, set start-level to a string like "2"
15420 (when start-level
15421 (save-excursion
15422 (goto-char (region-beginning))
15423 (unless (org-at-heading-p) (outline-next-heading))
15424 (setq start-level (org-current-level))))
15425 (narrow-to-region (region-beginning)
15426 (save-excursion
15427 (goto-char (region-end))
15428 (unless (and (bolp) (org-at-heading-p))
15429 (outline-next-heading))
15430 (point)))
15431 (setq scope nil)))
15433 (if (not scope)
15434 (progn
15435 (org-agenda-prepare-buffers
15436 (list (buffer-file-name (current-buffer))))
15437 (setq res (org-scan-tags func matcher todo-only start-level)))
15438 ;; Get the right scope
15439 (cond
15440 ((and scope (listp scope) (symbolp (car scope)))
15441 (setq scope (eval scope)))
15442 ((eq scope 'agenda)
15443 (setq scope (org-agenda-files t)))
15444 ((eq scope 'agenda-with-archives)
15445 (setq scope (org-agenda-files t))
15446 (setq scope (org-add-archive-files scope)))
15447 ((eq scope 'file)
15448 (setq scope (list (buffer-file-name))))
15449 ((eq scope 'file-with-archives)
15450 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15451 (org-agenda-prepare-buffers scope)
15452 (while (setq file (pop scope))
15453 (with-current-buffer (org-find-base-buffer-visiting file)
15454 (save-excursion
15455 (save-restriction
15456 (widen)
15457 (goto-char (point-min))
15458 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15459 res)))
15461 ;;; Properties API
15463 (defconst org-special-properties
15464 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15465 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15466 "The special properties valid in Org mode.
15467 These are properties that are not defined in the property drawer,
15468 but in some other way.")
15470 (defconst org-default-properties
15471 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15472 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15473 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15474 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15475 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15476 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15477 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15478 "Some properties that are used by Org mode for various purposes.
15479 Being in this list makes sure that they are offered for completion.")
15481 (defun org--update-property-plist (key val props)
15482 "Associate KEY to VAL in alist PROPS.
15483 Modifications are made by side-effect. Return new alist."
15484 (let* ((appending (string= (substring key -1) "+"))
15485 (key (if appending (substring key 0 -1) key))
15486 (old (assoc-string key props t)))
15487 (if (not old) (cons (cons key val) props)
15488 (setcdr old (if appending (concat (cdr old) " " val) val))
15489 props)))
15491 (defun org-get-property-block (&optional beg force)
15492 "Return the (beg . end) range of the body of the property drawer.
15493 BEG is the beginning of the current subtree, or of the part
15494 before the first headline. If it is not given, it will be found.
15495 If the drawer does not exist, create it if FORCE is non-nil, or
15496 return nil."
15497 (org-with-wide-buffer
15498 (when beg (goto-char beg))
15499 (unless (org-before-first-heading-p)
15500 (let ((beg (cond (beg)
15501 ((or (not (featurep 'org-inlinetask))
15502 (org-inlinetask-in-task-p))
15503 (org-back-to-heading t))
15504 (t (org-with-limited-levels (org-back-to-heading t))))))
15505 (forward-line)
15506 (when (org-looking-at-p org-planning-line-re) (forward-line))
15507 (cond ((looking-at org-property-drawer-re)
15508 (forward-line)
15509 (cons (point) (progn (goto-char (match-end 0))
15510 (line-beginning-position))))
15511 (force
15512 (goto-char beg)
15513 (org-insert-property-drawer)
15514 (let ((pos (save-excursion (search-forward ":END:")
15515 (line-beginning-position))))
15516 (cons pos pos))))))))
15518 (defun org-at-property-p ()
15519 "Non-nil when point is inside a property drawer.
15520 See `org-property-re' for match data, if applicable."
15521 (save-excursion
15522 (beginning-of-line)
15523 (and (looking-at org-property-re)
15524 (let ((property-drawer (save-match-data (org-get-property-block))))
15525 (and property-drawer
15526 (>= (point) (car property-drawer))
15527 (< (point) (cdr property-drawer)))))))
15529 (defun org-property-action ()
15530 "Do an action on properties."
15531 (interactive)
15532 (unless (org-at-property-p) (user-error "Not at a property"))
15533 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15534 (let ((c (read-char-exclusive)))
15535 (case c
15536 (?s (call-interactively #'org-set-property))
15537 (?d (call-interactively #'org-delete-property))
15538 (?D (call-interactively #'org-delete-property-globally))
15539 (?c (call-interactively #'org-compute-property-at-point))
15540 (otherwise (user-error "No such property action %c" c)))))
15542 (defun org-inc-effort ()
15543 "Increment the value of the effort property in the current entry."
15544 (interactive)
15545 (org-set-effort nil t))
15547 (defvar org-clock-effort) ; Defined in org-clock.el.
15548 (defvar org-clock-current-task) ; Defined in org-clock.el.
15549 (defun org-set-effort (&optional value increment)
15550 "Set the effort property of the current entry.
15551 With numerical prefix arg, use the nth allowed value, 0 stands for the
15552 10th allowed value.
15554 When INCREMENT is non-nil, set the property to the next allowed value."
15555 (interactive "P")
15556 (if (equal value 0) (setq value 10))
15557 (let* ((completion-ignore-case t)
15558 (prop org-effort-property)
15559 (cur (org-entry-get nil prop))
15560 (allowed (org-property-get-allowed-values nil prop 'table))
15561 (existing (mapcar 'list (org-property-values prop)))
15562 (heading (nth 4 (org-heading-components)))
15564 (val (cond
15565 ((stringp value) value)
15566 ((and allowed (integerp value))
15567 (or (car (nth (1- value) allowed))
15568 (car (org-last allowed))))
15569 ((and allowed increment)
15570 (or (caadr (member (list cur) allowed))
15571 (user-error "Allowed effort values are not set")))
15572 (allowed
15573 (message "Select 1-9,0, [RET%s]: %s"
15574 (if cur (concat "=" cur) "")
15575 (mapconcat 'car allowed " "))
15576 (setq rpl (read-char-exclusive))
15577 (if (equal rpl ?\r)
15579 (setq rpl (- rpl ?0))
15580 (if (equal rpl 0) (setq rpl 10))
15581 (if (and (> rpl 0) (<= rpl (length allowed)))
15582 (car (nth (1- rpl) allowed))
15583 (org-completing-read "Effort: " allowed nil))))
15585 (let (org-completion-use-ido org-completion-use-iswitchb)
15586 (org-completing-read
15587 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15588 (concat "[" cur "]") "")
15589 ": ")
15590 existing nil nil "" nil cur))))))
15591 (unless (equal (org-entry-get nil prop) val)
15592 (org-entry-put nil prop val))
15593 (org-refresh-property
15594 '((effort . identity)
15595 (effort-minutes . org-duration-string-to-minutes))
15596 val)
15597 (when (string= heading org-clock-current-task)
15598 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15599 (org-clock-update-mode-line))
15600 (message "%s is now %s" prop val)))
15602 (defun org-entry-properties (&optional pom which)
15603 "Get all properties of the current entry.
15605 When POM is a buffer position, get all properties from the entry
15606 there instead.
15608 This includes the TODO keyword, the tags, time strings for
15609 deadline, scheduled, and clocking, and any additional properties
15610 defined in the entry.
15612 If WHICH is nil or `all', get all properties. If WHICH is
15613 `special' or `standard', only get that subclass. If WHICH is
15614 a string, only get that property.
15616 Return value is an alist. Keys are properties, as upcased
15617 strings."
15618 (org-with-point-at pom
15619 (when (and (derived-mode-p 'org-mode)
15620 (ignore-errors (org-back-to-heading t)))
15621 (catch 'exit
15622 (let* ((beg (point))
15623 (specific (and (stringp which) (upcase which)))
15624 (which (cond ((not specific) which)
15625 ((member specific org-special-properties) 'special)
15626 (t 'standard)))
15627 props)
15628 ;; Get the special properties, like TODO and TAGS.
15629 (when (memq which '(nil all special))
15630 (when (or (not specific) (string= specific "CLOCKSUM"))
15631 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15632 (when clocksum
15633 (push (cons "CLOCKSUM"
15634 (org-columns-number-to-string
15635 (/ (float clocksum) 60.) 'add_times))
15636 props)))
15637 (when specific (throw 'exit props)))
15638 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15639 (let ((clocksumt (get-text-property (point)
15640 :org-clock-minutes-today)))
15641 (when clocksumt
15642 (push (cons "CLOCKSUM_T"
15643 (org-columns-number-to-string
15644 (/ (float clocksumt) 60.) 'add_times))
15645 props)))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "ITEM"))
15648 (when (looking-at org-complex-heading-regexp)
15649 (push (cons "ITEM"
15650 (concat
15651 (org-match-string-no-properties 1)
15652 (let ((title (org-match-string-no-properties 4)))
15653 (when (org-string-nw-p title)
15654 (concat " " (org-remove-tabs title))))))
15655 props))
15656 (when specific (throw 'exit props)))
15657 (when (or (not specific) (string= specific "TODO"))
15658 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15659 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15660 (when specific (throw 'exit props)))
15661 (when (or (not specific) (string= specific "PRIORITY"))
15662 (when (looking-at org-priority-regexp)
15663 (push (cons "PRIORITY" (org-match-string-no-properties 2))
15664 props))
15665 (when specific (throw 'exit props)))
15666 (when (or (not specific) (string= specific "FILE"))
15667 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15668 props)
15669 (when specific (throw 'exit props)))
15670 (when (or (not specific) (string= specific "TAGS"))
15671 (let ((value (org-string-nw-p (org-get-tags-string))))
15672 (when value (push (cons "TAGS" value) props)))
15673 (when specific (throw 'exit props)))
15674 (when (or (not specific) (string= specific "ALLTAGS"))
15675 (let ((value (org-get-tags-at)))
15676 (when value
15677 (push (cons "ALLTAGS"
15678 (format ":%s:" (mapconcat #'identity value ":")))
15679 props)))
15680 (when specific (throw 'exit props)))
15681 (when (or (not specific) (string= specific "BLOCKED"))
15682 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15683 (when specific (throw 'exit props)))
15684 (when (or (not specific)
15685 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15686 (forward-line)
15687 (when (org-looking-at-p org-planning-line-re)
15688 (end-of-line)
15689 (let ((bol (line-beginning-position))
15690 ;; Backward compatibility: time keywords used to
15691 ;; be configurable (before 8.3). Make sure we
15692 ;; get the correct keyword.
15693 (key-assoc `(("CLOSED" . ,org-closed-string)
15694 ("DEADLINE" . ,org-deadline-string)
15695 ("SCHEDULED" . ,org-scheduled-string))))
15696 (dolist (pair (if specific (list (assoc specific key-assoc))
15697 key-assoc))
15698 (save-excursion
15699 (when (search-backward (cdr pair) bol t)
15700 (goto-char (match-end 0))
15701 (skip-chars-forward " \t")
15702 (and (looking-at org-ts-regexp-both)
15703 (push (cons (car pair)
15704 (org-match-string-no-properties 0))
15705 props)))))))
15706 (when specific (throw 'exit props)))
15707 (when (or (not specific)
15708 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15709 (let ((find-ts
15710 (lambda (end ts)
15711 (let ((regexp (cond
15712 ((string= specific "TIMESTAMP")
15713 org-ts-regexp)
15714 ((string= specific "TIMESTAMP_IA")
15715 org-ts-regexp-inactive)
15716 ((assoc "TIMESTAMP_IA" ts)
15717 org-ts-regexp)
15718 ((assoc "TIMESTAMP" ts)
15719 org-ts-regexp-inactive)
15720 (t org-ts-regexp-both))))
15721 (catch 'next
15722 (while (re-search-forward regexp end t)
15723 (backward-char)
15724 (let ((object (org-element-context)))
15725 ;; Accept to match timestamps in node
15726 ;; properties, too.
15727 (when (memq (org-element-type object)
15728 '(node-property timestamp))
15729 (let ((type
15730 (org-element-property :type object)))
15731 (cond
15732 ((and (memq type '(active active-range))
15733 (not (equal specific "TIMESTAMP_IA")))
15734 (unless (assoc "TIMESTAMP" ts)
15735 (push (cons "TIMESTAMP"
15736 (org-element-property
15737 :raw-value object))
15739 (when specific (throw 'exit ts))))
15740 ((and (memq type '(inactive inactive-range))
15741 (not (string= specific "TIMESTAMP")))
15742 (unless (assoc "TIMESTAMP_IA" ts)
15743 (push (cons "TIMESTAMP_IA"
15744 (org-element-property
15745 :raw-value object))
15747 (when specific (throw 'exit ts))))))
15748 ;; Both timestamp types are found,
15749 ;; move to next part.
15750 (when (= (length ts) 2) (throw 'next ts)))))
15751 ts)))))
15752 (goto-char beg)
15753 ;; First look for timestamps within headline.
15754 (let ((ts (funcall find-ts (line-end-position) nil)))
15755 (if (= (length ts) 2) (setq props (nconc ts props))
15756 (forward-line)
15757 ;; Then find timestamps in the section, skipping
15758 ;; planning line.
15759 (when (org-looking-at-p org-planning-line-re)
15760 (forward-line))
15761 (let ((end (save-excursion (outline-next-heading))))
15762 (setq props (nconc (funcall find-ts end ts) props))))))))
15763 ;; Get the standard properties, like :PROP:.
15764 (when (memq which '(nil all standard))
15765 ;; If we are looking after a specific property, delegate
15766 ;; to `org-entry-get', which is faster. However, make an
15767 ;; exception for "CATEGORY", since it can be also set
15768 ;; through keywords (i.e. #+CATEGORY).
15769 (if (and specific (not (equal specific "CATEGORY")))
15770 (let ((value (org-entry-get beg specific nil t)))
15771 (throw 'exit (and value (list (cons specific value)))))
15772 (let ((range (org-get-property-block beg)))
15773 (when range
15774 (let ((end (cdr range)) seen-base)
15775 (goto-char (car range))
15776 ;; Unlike to `org--update-property-plist', we
15777 ;; handle the case where base values is found
15778 ;; after its extension. We also forbid standard
15779 ;; properties to be named as special properties.
15780 (while (re-search-forward org-property-re end t)
15781 (let* ((key (upcase (org-match-string-no-properties 2)))
15782 (extendp (org-string-match-p "\\+\\'" key))
15783 (key-base (if extendp (substring key 0 -1) key))
15784 (value (org-match-string-no-properties 3)))
15785 (cond
15786 ((member-ignore-case key-base org-special-properties))
15787 (extendp
15788 (setq props
15789 (org--update-property-plist key value props)))
15790 ((member key seen-base))
15791 (t (push key seen-base)
15792 (let ((p (assoc-string key props t)))
15793 (if p (setcdr p (concat value " " (cdr p)))
15794 (push (cons key value) props))))))))))))
15795 (unless (assoc "CATEGORY" props)
15796 (push (cons "CATEGORY" (org-get-category beg)) props)
15797 (when (string= specific "CATEGORY") (throw 'exit props)))
15798 ;; Return value.
15799 (append (get-text-property beg 'org-summaries) props))))))
15801 (defun org-property--local-values (property literal-nil)
15802 "Return value for PROPERTY in current entry.
15803 Value is a list whose care is the base value for PROPERTY and cdr
15804 a list of accumulated values. Return nil if neither is found in
15805 the entry. Also return nil when PROPERTY is set to \"nil\",
15806 unless LITERAL-NIL is non-nil."
15807 (let ((range (org-get-property-block)))
15808 (when range
15809 (goto-char (car range))
15810 (let* ((case-fold-search t)
15811 (end (cdr range))
15812 (value
15813 ;; Base value.
15814 (save-excursion
15815 (let ((v (and (re-search-forward
15816 (org-re-property property nil t) end t)
15817 (org-match-string-no-properties 3))))
15818 (list (if literal-nil v (org-not-nil v)))))))
15819 ;; Find additional values.
15820 (let* ((property+ (org-re-property (concat property "+") nil t)))
15821 (while (re-search-forward property+ end t)
15822 (push (org-match-string-no-properties 3) value)))
15823 ;; Return final values.
15824 (and (not (equal value '(nil))) (nreverse value))))))
15826 (defun org-entry-get (pom property &optional inherit literal-nil)
15827 "Get value of PROPERTY for entry or content at point-or-marker POM.
15829 If INHERIT is non-nil and the entry does not have the property,
15830 then also check higher levels of the hierarchy. If INHERIT is
15831 the symbol `selective', use inheritance only if the setting in
15832 `org-use-property-inheritance' selects PROPERTY for inheritance.
15834 If the property is present but empty, the return value is the
15835 empty string. If the property is not present at all, nil is
15836 returned. In any other case, return the value as a string.
15837 Search is case-insensitive.
15839 If LITERAL-NIL is set, return the string value \"nil\" as
15840 a string, do not interpret it as the list atom nil. This is used
15841 for inheritance when a \"nil\" value can supersede a non-nil
15842 value higher up the hierarchy."
15843 (org-with-point-at pom
15844 (cond
15845 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15846 ;; We need a special property. Use `org-entry-properties' to
15847 ;; retrieve it, but specify the wanted property.
15848 (cdr (assoc-string property (org-entry-properties nil property))))
15849 ((and inherit
15850 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15851 (org-entry-get-with-inheritance property literal-nil))
15853 (let* ((local (org-property--local-values property literal-nil))
15854 (value (and local (mapconcat #'identity (delq nil local) " "))))
15855 (if literal-nil value (org-not-nil value)))))))
15857 (defun org-property-or-variable-value (var &optional inherit)
15858 "Check if there is a property fixing the value of VAR.
15859 If yes, return this value. If not, return the current value of the variable."
15860 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15861 (if (and prop (stringp prop) (string-match "\\S-" prop))
15862 (read prop)
15863 (symbol-value var))))
15865 (defun org-entry-delete (pom property)
15866 "Delete PROPERTY from entry at point-or-marker POM.
15867 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15868 non-nil when a property was removed."
15869 (unless (member property org-special-properties)
15870 (org-with-point-at pom
15871 (let ((range (org-get-property-block)))
15872 (when range
15873 (let* ((begin (car range))
15874 (origin (cdr range))
15875 (end (copy-marker origin))
15876 (re (org-re-property
15877 (concat (regexp-quote property) "\\+?") t t)))
15878 (goto-char begin)
15879 (while (re-search-forward re end t)
15880 (delete-region (match-beginning 0) (line-beginning-position 2)))
15881 ;; If drawer is empty, remove it altogether.
15882 (when (= begin end)
15883 (delete-region (line-beginning-position 0)
15884 (line-beginning-position 2)))
15885 ;; Return non-nil if some property was removed.
15886 (prog1 (/= end origin) (set-marker end nil))))))))
15888 ;; Multi-values properties are properties that contain multiple values
15889 ;; These values are assumed to be single words, separated by whitespace.
15890 (defun org-entry-add-to-multivalued-property (pom property value)
15891 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15892 (let* ((old (org-entry-get pom property))
15893 (values (and old (org-split-string old "[ \t]"))))
15894 (setq value (org-entry-protect-space value))
15895 (unless (member value values)
15896 (setq values (append values (list value)))
15897 (org-entry-put pom property
15898 (mapconcat 'identity values " ")))))
15900 (defun org-entry-remove-from-multivalued-property (pom property value)
15901 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15902 (let* ((old (org-entry-get pom property))
15903 (values (and old (org-split-string old "[ \t]"))))
15904 (setq value (org-entry-protect-space value))
15905 (when (member value values)
15906 (setq values (delete value values))
15907 (org-entry-put pom property
15908 (mapconcat 'identity values " ")))))
15910 (defun org-entry-member-in-multivalued-property (pom property value)
15911 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15912 (let* ((old (org-entry-get pom property))
15913 (values (and old (org-split-string old "[ \t]"))))
15914 (setq value (org-entry-protect-space value))
15915 (member value values)))
15917 (defun org-entry-get-multivalued-property (pom property)
15918 "Return a list of values in a multivalued property."
15919 (let* ((value (org-entry-get pom property))
15920 (values (and value (org-split-string value "[ \t]"))))
15921 (mapcar 'org-entry-restore-space values)))
15923 (defun org-entry-put-multivalued-property (pom property &rest values)
15924 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15925 VALUES should be a list of strings. Spaces will be protected."
15926 (org-entry-put pom property
15927 (mapconcat 'org-entry-protect-space values " "))
15928 (let* ((value (org-entry-get pom property))
15929 (values (and value (org-split-string value "[ \t]"))))
15930 (mapcar 'org-entry-restore-space values)))
15932 (defun org-entry-protect-space (s)
15933 "Protect spaces and newline in string S."
15934 (while (string-match " " s)
15935 (setq s (replace-match "%20" t t s)))
15936 (while (string-match "\n" s)
15937 (setq s (replace-match "%0A" t t s)))
15940 (defun org-entry-restore-space (s)
15941 "Restore spaces and newline in string S."
15942 (while (string-match "%20" s)
15943 (setq s (replace-match " " t t s)))
15944 (while (string-match "%0A" s)
15945 (setq s (replace-match "\n" t t s)))
15948 (defvar org-entry-property-inherited-from (make-marker)
15949 "Marker pointing to the entry from where a property was inherited.
15950 Each call to `org-entry-get-with-inheritance' will set this marker to the
15951 location of the entry where the inheritance search matched. If there was
15952 no match, the marker will point nowhere.
15953 Note that also `org-entry-get' calls this function, if the INHERIT flag
15954 is set.")
15956 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15957 "Get PROPERTY of entry or content at point, search higher levels if needed.
15958 The search will stop at the first ancestor which has the property defined.
15959 If the value found is \"nil\", return nil to show that the property
15960 should be considered as undefined (this is the meaning of nil here).
15961 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15962 (move-marker org-entry-property-inherited-from nil)
15963 (org-with-wide-buffer
15964 (let (value)
15965 (catch 'exit
15966 (while t
15967 (let ((v (org-property--local-values property literal-nil)))
15968 (when v
15969 (setq value
15970 (concat (mapconcat #'identity (delq nil v) " ")
15971 (and value " ")
15972 value)))
15973 (cond
15974 ((car v)
15975 (org-back-to-heading t)
15976 (move-marker org-entry-property-inherited-from (point))
15977 (throw 'exit nil))
15978 ((org-up-heading-safe))
15980 (let ((global
15981 (cdr (or (assoc-string property org-file-properties t)
15982 (assoc-string property org-global-properties t)
15983 (assoc-string property org-global-properties-fixed t)))))
15984 (cond ((not global))
15985 (value (setq value (concat global " " value)))
15986 (t (setq value global))))
15987 (throw 'exit nil))))))
15988 (if literal-nil value (org-not-nil value)))))
15990 (defvar org-property-changed-functions nil
15991 "Hook called when the value of a property has changed.
15992 Each hook function should accept two arguments, the name of the property
15993 and the new value.")
15995 (defun org-entry-put (pom property value)
15996 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15998 If the value is `nil', it is converted to the empty string. If
15999 it is not a string, an error is raised.
16001 PROPERTY can be any regular property (see
16002 `org-special-properties'). It can also be \"TODO\",
16003 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16005 For the last two properties, VALUE may have any of the special
16006 values \"earlier\" and \"later\". The function then increases or
16007 decreases scheduled or deadline date by one day."
16008 (cond ((null value) (setq value ""))
16009 ((not (stringp value)) (error "Properties values should be strings")))
16010 (org-with-point-at pom
16011 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16012 (org-back-to-heading t)
16013 (org-with-limited-levels (org-back-to-heading t)))
16014 (let ((beg (point)))
16015 (cond
16016 ((equal property "TODO")
16017 (cond ((not (org-string-nw-p value)) (setq value 'none))
16018 ((not (member value org-todo-keywords-1))
16019 (user-error "\"%s\" is not a valid TODO state" value)))
16020 (org-todo value)
16021 (org-set-tags nil 'align))
16022 ((equal property "PRIORITY")
16023 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16024 (org-set-tags nil 'align))
16025 ((equal property "SCHEDULED")
16026 (forward-line)
16027 (if (and (org-looking-at-p org-planning-line-re)
16028 (re-search-forward
16029 org-scheduled-time-regexp (line-end-position) t))
16030 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16031 ((string= value "later") (org-timestamp-change 1 'day))
16032 ((string= value "") (org-schedule '(4)))
16033 (t (org-schedule nil value)))
16034 (if (member value '("earlier" "later" ""))
16035 (call-interactively #'org-schedule)
16036 (org-schedule nil value))))
16037 ((equal property "DEADLINE")
16038 (forward-line)
16039 (if (and (org-looking-at-p org-planning-line-re)
16040 (re-search-forward
16041 org-deadline-time-regexp (line-end-position) t))
16042 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16043 ((string= value "later") (org-timestamp-change 1 'day))
16044 ((string= value "") (org-deadline '(4)))
16045 (t (org-deadline nil value)))
16046 (if (member value '("earlier" "later" ""))
16047 (call-interactively #'org-deadline)
16048 (org-deadline nil value))))
16049 ((member property org-special-properties)
16050 (error "The %s property cannot be set with `org-entry-put'" property))
16052 (let* ((range (org-get-property-block beg 'force))
16053 (end (cdr range))
16054 (case-fold-search t))
16055 (goto-char (car range))
16056 (if (re-search-forward (org-re-property property nil t) end t)
16057 (progn (delete-region (match-beginning 0) (match-end 0))
16058 (goto-char (match-beginning 0)))
16059 (goto-char end)
16060 (insert "\n")
16061 (backward-char))
16062 (insert ":" property ":")
16063 (when value (insert " " value))
16064 (org-indent-line)))))
16065 (run-hook-with-args 'org-property-changed-functions property value)))
16067 (defun org-buffer-property-keys (&optional specials defaults columns)
16068 "Get all property keys in the current buffer.
16070 When SPECIALS is non-nil, also list the special properties that
16071 reflect things like tags and TODO state.
16073 When DEFAULTS is non-nil, also include properties that has
16074 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16075 DESCRIPTION, LOCATION, and LOGGING and others.
16077 When COLUMNS in non-nil, also include property names given in
16078 COLUMN formats in the current buffer."
16079 (let ((case-fold-search t)
16080 (props (append
16081 (and specials org-special-properties)
16082 (and defaults (cons org-effort-property org-default-properties))
16083 nil)))
16084 (org-with-wide-buffer
16085 (goto-char (point-min))
16086 (while (re-search-forward org-property-start-re nil t)
16087 (let ((range (org-get-property-block)))
16088 (catch 'skip
16089 (unless range
16090 (when (and (not (org-before-first-heading-p))
16091 (y-or-n-p (format "Malformed drawer at %d, repair?"
16092 (line-beginning-position))))
16093 (org-get-property-block nil t))
16094 (throw 'skip nil))
16095 (goto-char (car range))
16096 (let ((begin (car range))
16097 (end (cdr range)))
16098 ;; Make sure that found property block is not located
16099 ;; before current point, as it would generate an infloop.
16100 ;; It can happen, for example, in the following
16101 ;; situation:
16103 ;; * Headline
16104 ;; :PROPERTIES:
16105 ;; ...
16106 ;; :END:
16107 ;; *************** Inlinetask
16108 ;; #+BEGIN_EXAMPLE
16109 ;; :PROPERTIES:
16110 ;; #+END_EXAMPLE
16112 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16113 (while (< (point) end)
16114 (let ((p (progn (looking-at org-property-re)
16115 (org-match-string-no-properties 2))))
16116 ;; Only add true property name, not extension symbol.
16117 (add-to-list 'props
16118 (if (not (org-string-match-p "\\+\\'" p)) p
16119 (substring p 0 -1))))
16120 (forward-line))))
16121 (outline-next-heading)))
16122 (when columns
16123 (goto-char (point-min))
16124 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16125 (let ((element (org-element-at-point)))
16126 (when (memq (org-element-type element) '(keyword node-property))
16127 (let ((value (org-element-property :value element))
16128 (start 0))
16129 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16130 (setq start (match-end 0))
16131 (let ((p (org-match-string-no-properties 1 value)))
16132 (unless (member-ignore-case p org-special-properties)
16133 (add-to-list 'props p))))))))))
16134 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16136 (defun org-property-values (key)
16137 "List all non-nil values of property KEY in current buffer."
16138 (org-with-wide-buffer
16139 (goto-char (point-min))
16140 (let ((case-fold-search t)
16141 (re (org-re-property key))
16142 values)
16143 (while (re-search-forward re nil t)
16144 (add-to-list 'values (org-entry-get (point) key)))
16145 values)))
16147 (defun org-insert-property-drawer ()
16148 "Insert a property drawer into the current entry."
16149 (org-with-wide-buffer
16150 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16151 (org-back-to-heading t)
16152 (org-with-limited-levels (org-back-to-heading t)))
16153 (forward-line)
16154 (when (org-looking-at-p org-planning-line-re) (forward-line))
16155 (unless (org-looking-at-p org-property-drawer-re)
16156 (let ((inhibit-read-only t))
16157 (unless (bolp) (insert "\n"))
16158 (let ((begin (point)))
16159 (insert ":PROPERTIES:\n:END:\n")
16160 (org-indent-region begin (point)))))))
16162 (defun org-insert-drawer (&optional arg drawer)
16163 "Insert a drawer at point.
16165 When optional argument ARG is non-nil, insert a property drawer.
16167 Optional argument DRAWER, when non-nil, is a string representing
16168 drawer's name. Otherwise, the user is prompted for a name.
16170 If a region is active, insert the drawer around that region
16171 instead.
16173 Point is left between drawer's boundaries."
16174 (interactive "P")
16175 (let* ((drawer (if arg "PROPERTIES"
16176 (or drawer (read-from-minibuffer "Drawer: ")))))
16177 (cond
16178 ;; With C-u, fall back on `org-insert-property-drawer'
16179 (arg (org-insert-property-drawer))
16180 ;; Check validity of suggested drawer's name.
16181 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16182 (user-error "Invalid drawer name"))
16183 ;; With an active region, insert a drawer at point.
16184 ((not (org-region-active-p))
16185 (progn
16186 (unless (bolp) (insert "\n"))
16187 (insert (format ":%s:\n\n:END:\n" drawer))
16188 (forward-line -2)))
16189 ;; Otherwise, insert the drawer at point
16191 (let ((rbeg (region-beginning))
16192 (rend (copy-marker (region-end))))
16193 (unwind-protect
16194 (progn
16195 (goto-char rbeg)
16196 (beginning-of-line)
16197 (when (save-excursion
16198 (re-search-forward org-outline-regexp-bol rend t))
16199 (user-error "Drawers cannot contain headlines"))
16200 ;; Position point at the beginning of the first
16201 ;; non-blank line in region. Insert drawer's opening
16202 ;; there, then indent it.
16203 (org-skip-whitespace)
16204 (beginning-of-line)
16205 (insert ":" drawer ":\n")
16206 (forward-line -1)
16207 (indent-for-tab-command)
16208 ;; Move point to the beginning of the first blank line
16209 ;; after the last non-blank line in region. Insert
16210 ;; drawer's closing, then indent it.
16211 (goto-char rend)
16212 (skip-chars-backward " \r\t\n")
16213 (insert "\n:END:")
16214 (deactivate-mark t)
16215 (indent-for-tab-command)
16216 (unless (eolp) (insert "\n")))
16217 ;; Clear marker, whatever the outcome of insertion is.
16218 (set-marker rend nil)))))))
16220 (defvar org-property-set-functions-alist nil
16221 "Property set function alist.
16222 Each entry should have the following format:
16224 (PROPERTY . READ-FUNCTION)
16226 The read function will be called with the same argument as
16227 `org-completing-read'.")
16229 (defun org-set-property-function (property)
16230 "Get the function that should be used to set PROPERTY.
16231 This is computed according to `org-property-set-functions-alist'."
16232 (or (cdr (assoc property org-property-set-functions-alist))
16233 'org-completing-read))
16235 (defun org-read-property-value (property)
16236 "Read PROPERTY value from user."
16237 (let* ((completion-ignore-case t)
16238 (allowed (org-property-get-allowed-values nil property 'table))
16239 (cur (org-entry-get nil property))
16240 (prompt (concat property " value"
16241 (if (and cur (string-match "\\S-" cur))
16242 (concat " [" cur "]") "") ": "))
16243 (set-function (org-set-property-function property))
16244 (val (if allowed
16245 (funcall set-function prompt allowed nil
16246 (not (get-text-property 0 'org-unrestricted
16247 (caar allowed))))
16248 (let (org-completion-use-ido org-completion-use-iswitchb)
16249 (funcall set-function prompt
16250 (mapcar 'list (org-property-values property))
16251 nil nil "" nil cur)))))
16252 (org-trim val)))
16254 (defvar org-last-set-property nil)
16255 (defvar org-last-set-property-value nil)
16256 (defun org-read-property-name ()
16257 "Read a property name."
16258 (let ((completion-ignore-case t)
16259 (default-prop (or (and (org-at-property-p)
16260 (org-match-string-no-properties 2))
16261 org-last-set-property)))
16262 (org-completing-read
16263 (concat "Property"
16264 (if default-prop (concat " [" default-prop "]") "")
16265 ": ")
16266 (mapcar #'list (org-buffer-property-keys nil t t))
16267 nil nil nil nil default-prop)))
16269 (defun org-set-property-and-value (use-last)
16270 "Allow to set [PROPERTY]: [value] direction from prompt.
16271 When use-default, don't even ask, just use the last
16272 \"[PROPERTY]: [value]\" string from the history."
16273 (interactive "P")
16274 (let* ((completion-ignore-case t)
16275 (pv (or (and use-last org-last-set-property-value)
16276 (org-completing-read
16277 "Enter a \"[Property]: [value]\" pair: "
16278 nil nil nil nil nil
16279 org-last-set-property-value)))
16280 prop val)
16281 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16282 (setq prop (match-string 1 pv)
16283 val (match-string 2 pv))
16284 (org-set-property prop val))))
16286 (defun org-set-property (property value)
16287 "In the current entry, set PROPERTY to VALUE.
16288 When called interactively, this will prompt for a property name, offering
16289 completion on existing and default properties. And then it will prompt
16290 for a value, offering completion either on allowed values (via an inherited
16291 xxx_ALL property) or on existing values in other instances of this property
16292 in the current file."
16293 (interactive (list nil nil))
16294 (let* ((property (or property (org-read-property-name)))
16295 (value (or value (org-read-property-value property)))
16296 (fn (cdr (assoc property org-properties-postprocess-alist))))
16297 (setq org-last-set-property property)
16298 (setq org-last-set-property-value (concat property ": " value))
16299 ;; Possibly postprocess the inserted value:
16300 (when fn (setq value (funcall fn value)))
16301 (unless (equal (org-entry-get nil property) value)
16302 (org-entry-put nil property value))))
16304 (defun org-find-property (property &optional value)
16305 "Find first entry in buffer that sets PROPERTY.
16307 When optional argument VALUE is non-nil, only consider an entry
16308 if it contains PROPERTY set to this value. If PROPERTY should be
16309 explicitly set to nil, use string \"nil\" for VALUE.
16311 Return position where the entry begins, or nil if there is no
16312 such entry. If narrowing is in effect, only search the visible
16313 part of the buffer."
16314 (save-excursion
16315 (goto-char (point-min))
16316 (let ((case-fold-search t)
16317 (re (org-re-property property nil (not value) value)))
16318 (catch 'exit
16319 (while (re-search-forward re nil t)
16320 (when (if value (org-at-property-p)
16321 (org-entry-get (point) property nil t))
16322 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16324 (defun org-delete-property (property)
16325 "In the current entry, delete PROPERTY."
16326 (interactive
16327 (let* ((completion-ignore-case t)
16328 (cat (org-entry-get (point) "CATEGORY"))
16329 (props0 (org-entry-properties nil 'standard))
16330 (props (if cat props0
16331 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16332 (prop (if (< 1 (length props))
16333 (org-icompleting-read "Property: " props nil t)
16334 (caar props))))
16335 (list prop)))
16336 (if (not property)
16337 (message "No property to delete in this entry")
16338 (org-entry-delete nil property)
16339 (message "Property \"%s\" deleted" property)))
16341 (defun org-delete-property-globally (property)
16342 "Remove PROPERTY globally, from all entries.
16343 This function ignores narrowing, if any."
16344 (interactive
16345 (let* ((completion-ignore-case t)
16346 (prop (org-icompleting-read
16347 "Globally remove property: "
16348 (mapcar #'list (org-buffer-property-keys)))))
16349 (list prop)))
16350 (org-with-wide-buffer
16351 (goto-char (point-min))
16352 (let ((count 0)
16353 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16354 (while (re-search-forward re nil t)
16355 (when (org-entry-delete (point) property) (incf count)))
16356 (message "Property \"%s\" removed from %d entries" property count))))
16358 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16360 (defun org-compute-property-at-point ()
16361 "Compute the property at point.
16362 This looks for an enclosing column format, extracts the operator and
16363 then applies it to the property in the column format's scope."
16364 (interactive)
16365 (unless (org-at-property-p)
16366 (user-error "Not at a property"))
16367 (let ((prop (org-match-string-no-properties 2)))
16368 (org-columns-get-format-and-top-level)
16369 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16370 (user-error "No operator defined for property %s" prop))
16371 (org-columns-compute prop)))
16373 (defvar org-property-allowed-value-functions nil
16374 "Hook for functions supplying allowed values for a specific property.
16375 The functions must take a single argument, the name of the property, and
16376 return a flat list of allowed values. If \":ETC\" is one of
16377 the values, this means that these values are intended as defaults for
16378 completion, but that other values should be allowed too.
16379 The functions must return nil if they are not responsible for this
16380 property.")
16382 (defun org-property-get-allowed-values (pom property &optional table)
16383 "Get allowed values for the property PROPERTY.
16384 When TABLE is non-nil, return an alist that can directly be used for
16385 completion."
16386 (let (vals)
16387 (cond
16388 ((equal property "TODO")
16389 (setq vals (org-with-point-at pom
16390 (append org-todo-keywords-1 '("")))))
16391 ((equal property "PRIORITY")
16392 (let ((n org-lowest-priority))
16393 (while (>= n org-highest-priority)
16394 (push (char-to-string n) vals)
16395 (setq n (1- n)))))
16396 ((equal property "CATEGORY"))
16397 ((member property org-special-properties))
16398 ((setq vals (run-hook-with-args-until-success
16399 'org-property-allowed-value-functions property)))
16401 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16402 (when (and vals (string-match "\\S-" vals))
16403 (setq vals (car (read-from-string (concat "(" vals ")"))))
16404 (setq vals (mapcar (lambda (x)
16405 (cond ((stringp x) x)
16406 ((numberp x) (number-to-string x))
16407 ((symbolp x) (symbol-name x))
16408 (t "???")))
16409 vals)))))
16410 (when (member ":ETC" vals)
16411 (setq vals (remove ":ETC" vals))
16412 (org-add-props (car vals) '(org-unrestricted t)))
16413 (if table (mapcar 'list vals) vals)))
16415 (defun org-property-previous-allowed-value (&optional previous)
16416 "Switch to the next allowed value for this property."
16417 (interactive)
16418 (org-property-next-allowed-value t))
16420 (defun org-property-next-allowed-value (&optional previous)
16421 "Switch to the next allowed value for this property."
16422 (interactive)
16423 (unless (org-at-property-p)
16424 (user-error "Not at a property"))
16425 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16426 (key (match-string 2))
16427 (value (match-string 3))
16428 (allowed (or (org-property-get-allowed-values (point) key)
16429 (and (member value '("[ ]" "[-]" "[X]"))
16430 '("[ ]" "[X]"))))
16431 (heading (save-match-data (nth 4 (org-heading-components))))
16432 nval)
16433 (unless allowed
16434 (user-error "Allowed values for this property have not been defined"))
16435 (if previous (setq allowed (reverse allowed)))
16436 (if (member value allowed)
16437 (setq nval (car (cdr (member value allowed)))))
16438 (setq nval (or nval (car allowed)))
16439 (if (equal nval value)
16440 (user-error "Only one allowed value for this property"))
16441 (org-at-property-p)
16442 (replace-match (concat " :" key ": " nval) t t)
16443 (org-indent-line)
16444 (beginning-of-line 1)
16445 (skip-chars-forward " \t")
16446 (when (equal prop org-effort-property)
16447 (org-refresh-property
16448 '((effort . identity)
16449 (effort-minutes . org-duration-string-to-minutes))
16450 nval)
16451 (when (string= org-clock-current-task heading)
16452 (setq org-clock-effort nval)
16453 (org-clock-update-mode-line)))
16454 (run-hook-with-args 'org-property-changed-functions key nval)))
16456 (defun org-find-olp (path &optional this-buffer)
16457 "Return a marker pointing to the entry at outline path OLP.
16458 If anything goes wrong, throw an error.
16459 You can wrap this call to catch the error like this:
16461 (condition-case msg
16462 (org-mobile-locate-entry (match-string 4))
16463 (error (nth 1 msg)))
16465 The return value will then be either a string with the error message,
16466 or a marker if everything is OK.
16468 If THIS-BUFFER is set, the outline path does not contain a file,
16469 only headings."
16470 (let* ((file (if this-buffer buffer-file-name (pop path)))
16471 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16472 (level 1)
16473 (lmin 1)
16474 (lmax 1)
16475 limit re end found pos heading cnt flevel)
16476 (unless buffer (error "File not found :%s" file))
16477 (with-current-buffer buffer
16478 (save-excursion
16479 (save-restriction
16480 (widen)
16481 (setq limit (point-max))
16482 (goto-char (point-min))
16483 (while (setq heading (pop path))
16484 (setq re (format org-complex-heading-regexp-format
16485 (regexp-quote heading)))
16486 (setq cnt 0 pos (point))
16487 (while (re-search-forward re end t)
16488 (setq level (- (match-end 1) (match-beginning 1)))
16489 (if (and (>= level lmin) (<= level lmax))
16490 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16491 (when (= cnt 0) (error "Heading not found on level %d: %s"
16492 lmax heading))
16493 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16494 lmax heading))
16495 (goto-char found)
16496 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16497 (setq end (save-excursion (org-end-of-subtree t t))))
16498 (when (org-at-heading-p)
16499 (point-marker)))))))
16501 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16502 "Find node HEADING in BUFFER.
16503 Return a marker to the heading if it was found, or nil if not.
16504 If POS-ONLY is set, return just the position instead of a marker.
16506 The heading text must match exact, but it may have a TODO keyword,
16507 a priority cookie and tags in the standard locations."
16508 (with-current-buffer (or buffer (current-buffer))
16509 (save-excursion
16510 (save-restriction
16511 (widen)
16512 (goto-char (point-min))
16513 (let (case-fold-search)
16514 (if (re-search-forward
16515 (format org-complex-heading-regexp-format
16516 (regexp-quote heading)) nil t)
16517 (if pos-only
16518 (match-beginning 0)
16519 (move-marker (make-marker) (match-beginning 0)))))))))
16521 (defun org-find-exact-heading-in-directory (heading &optional dir)
16522 "Find Org node headline HEADING in all .org files in directory DIR.
16523 When the target headline is found, return a marker to this location."
16524 (let ((files (directory-files (or dir default-directory)
16525 t "\\`[^.#].*\\.org\\'"))
16526 file visiting m buffer)
16527 (catch 'found
16528 (while (setq file (pop files))
16529 (message "trying %s" file)
16530 (setq visiting (org-find-base-buffer-visiting file))
16531 (setq buffer (or visiting (find-file-noselect file)))
16532 (setq m (org-find-exact-headline-in-buffer
16533 heading buffer))
16534 (when (and (not m) (not visiting)) (kill-buffer buffer))
16535 (and m (throw 'found m))))))
16537 (defun org-find-entry-with-id (ident)
16538 "Locate the entry that contains the ID property with exact value IDENT.
16539 IDENT can be a string, a symbol or a number, this function will search for
16540 the string representation of it.
16541 Return the position where this entry starts, or nil if there is no such entry."
16542 (interactive "sID: ")
16543 (let ((id (cond
16544 ((stringp ident) ident)
16545 ((symbolp ident) (symbol-name ident))
16546 ((numberp ident) (number-to-string ident))
16547 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16548 (org-with-wide-buffer (org-find-property "ID" id))))
16550 ;;;; Timestamps
16552 (defvar org-last-changed-timestamp nil)
16553 (defvar org-last-inserted-timestamp nil
16554 "The last time stamp inserted with `org-insert-time-stamp'.")
16555 (defvar org-ts-what) ; dynamically scoped parameter
16557 (defun org-time-stamp (arg &optional inactive)
16558 "Prompt for a date/time and insert a time stamp.
16560 If the user specifies a time like HH:MM or if this command is
16561 called with at least one prefix argument, the time stamp contains
16562 the date and the time. Otherwise, only the date is included.
16564 All parts of a date not specified by the user are filled in from
16565 the timestamp at point, if any, or the current date/time
16566 otherwise.
16568 If there is already a timestamp at the cursor, it is replaced.
16570 With two universal prefix arguments, insert an active timestamp
16571 with the current time without prompting the user.
16573 When called from lisp, the timestamp is inactive if INACTIVE is
16574 non-nil."
16575 (interactive "P")
16576 (let* ((ts
16577 (cond ((org-at-date-range-p t)
16578 (save-excursion
16579 (goto-char (match-beginning 0))
16580 (looking-at (if inactive org-ts-regexp-both org-ts-regexp)))
16581 (match-string 0))
16582 ((org-at-timestamp-p t) (match-string 0))))
16583 ;; Default time is either the timestamp at point or today.
16584 ;; When entering a range, only the range start is considered.
16585 (default-time (if (not ts) (current-time)
16586 (apply #'encode-time (org-parse-time-string ts))))
16587 (default-input (and ts (org-get-compact-tod ts)))
16588 (repeater (and ts
16589 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16590 (match-string 0 ts)))
16591 org-time-was-given
16592 org-end-time-was-given
16593 (time
16594 (and (if (equal arg '(16)) (current-time)
16595 ;; Preserve `this-command' and `last-command'.
16596 (let ((this-command this-command)
16597 (last-command last-command))
16598 (org-read-date
16599 arg 'totime nil nil default-time default-input
16600 inactive))))))
16601 (cond
16602 ((and ts
16603 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16604 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16605 (insert "--")
16606 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16608 ;; Make sure we're on a timestamp. When in the middle of a date
16609 ;; range, move arbitrarily to range end.
16610 (unless (org-at-timestamp-p t)
16611 (skip-chars-forward "-")
16612 (org-at-timestamp-p t))
16613 (replace-match "")
16614 (setq org-last-changed-timestamp
16615 (org-insert-time-stamp
16616 time (or org-time-was-given arg)
16617 inactive nil nil (list org-end-time-was-given)))
16618 (when repeater
16619 (backward-char)
16620 (insert " " repeater)
16621 (setq org-last-changed-timestamp
16622 (concat (substring org-last-inserted-timestamp 0 -1)
16623 " " repeater ">")))
16624 (message "Timestamp updated"))
16625 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16626 (t (org-insert-time-stamp
16627 time (or org-time-was-given arg) inactive nil nil
16628 (list org-end-time-was-given))))))
16630 ;; FIXME: can we use this for something else, like computing time differences?
16631 (defun org-get-compact-tod (s)
16632 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16633 (let* ((t1 (match-string 1 s))
16634 (h1 (string-to-number (match-string 2 s)))
16635 (m1 (string-to-number (match-string 3 s)))
16636 (t2 (and (match-end 4) (match-string 5 s)))
16637 (h2 (and t2 (string-to-number (match-string 6 s))))
16638 (m2 (and t2 (string-to-number (match-string 7 s))))
16639 dh dm)
16640 (if (not t2)
16642 (setq dh (- h2 h1) dm (- m2 m1))
16643 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16644 (concat t1 "+" (number-to-string dh)
16645 (and (/= 0 dm) (format ":%02d" dm)))))))
16647 (defun org-time-stamp-inactive (&optional arg)
16648 "Insert an inactive time stamp.
16649 An inactive time stamp is enclosed in square brackets instead of angle
16650 brackets. It is inactive in the sense that it does not trigger agenda entries,
16651 does not link to the calendar and cannot be changed with the S-cursor keys.
16652 So these are more for recording a certain time/date."
16653 (interactive "P")
16654 (org-time-stamp arg 'inactive))
16656 (defvar org-date-ovl (make-overlay 1 1))
16657 (overlay-put org-date-ovl 'face 'org-date-selected)
16658 (org-detach-overlay org-date-ovl)
16660 (defvar org-ans1) ; dynamically scoped parameter
16661 (defvar org-ans2) ; dynamically scoped parameter
16663 (defvar org-plain-time-of-day-regexp) ; defined below
16665 (defvar org-overriding-default-time nil) ; dynamically scoped
16666 (defvar org-read-date-overlay nil)
16667 (defvar org-dcst nil) ; dynamically scoped
16668 (defvar org-read-date-history nil)
16669 (defvar org-read-date-final-answer nil)
16670 (defvar org-read-date-analyze-futurep nil)
16671 (defvar org-read-date-analyze-forced-year nil)
16672 (defvar org-read-date-inactive)
16674 (defvar org-read-date-minibuffer-local-map
16675 (let* ((map (make-sparse-keymap)))
16676 (set-keymap-parent map minibuffer-local-map)
16677 (org-defkey map (kbd ".")
16678 (lambda () (interactive)
16679 ;; Are we at the beginning of the prompt?
16680 (if (looking-back "^[^:]+: ")
16681 (org-eval-in-calendar '(calendar-goto-today))
16682 (insert "."))))
16683 (org-defkey map (kbd "C-.")
16684 (lambda () (interactive)
16685 (org-eval-in-calendar '(calendar-goto-today))))
16686 (org-defkey map [(meta shift left)]
16687 (lambda () (interactive)
16688 (org-eval-in-calendar '(calendar-backward-month 1))))
16689 (org-defkey map [(meta shift right)]
16690 (lambda () (interactive)
16691 (org-eval-in-calendar '(calendar-forward-month 1))))
16692 (org-defkey map [(meta shift up)]
16693 (lambda () (interactive)
16694 (org-eval-in-calendar '(calendar-backward-year 1))))
16695 (org-defkey map [(meta shift down)]
16696 (lambda () (interactive)
16697 (org-eval-in-calendar '(calendar-forward-year 1))))
16698 (org-defkey map [?\e (shift left)]
16699 (lambda () (interactive)
16700 (org-eval-in-calendar '(calendar-backward-month 1))))
16701 (org-defkey map [?\e (shift right)]
16702 (lambda () (interactive)
16703 (org-eval-in-calendar '(calendar-forward-month 1))))
16704 (org-defkey map [?\e (shift up)]
16705 (lambda () (interactive)
16706 (org-eval-in-calendar '(calendar-backward-year 1))))
16707 (org-defkey map [?\e (shift down)]
16708 (lambda () (interactive)
16709 (org-eval-in-calendar '(calendar-forward-year 1))))
16710 (org-defkey map [(shift up)]
16711 (lambda () (interactive)
16712 (org-eval-in-calendar '(calendar-backward-week 1))))
16713 (org-defkey map [(shift down)]
16714 (lambda () (interactive)
16715 (org-eval-in-calendar '(calendar-forward-week 1))))
16716 (org-defkey map [(shift left)]
16717 (lambda () (interactive)
16718 (org-eval-in-calendar '(calendar-backward-day 1))))
16719 (org-defkey map [(shift right)]
16720 (lambda () (interactive)
16721 (org-eval-in-calendar '(calendar-forward-day 1))))
16722 (org-defkey map "!"
16723 (lambda () (interactive)
16724 (org-eval-in-calendar '(diary-view-entries))
16725 (message "")))
16726 (org-defkey map ">"
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-scroll-left 1))))
16729 (org-defkey map "<"
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(calendar-scroll-right 1))))
16732 (org-defkey map "\C-v"
16733 (lambda () (interactive)
16734 (org-eval-in-calendar
16735 '(calendar-scroll-left-three-months 1))))
16736 (org-defkey map "\M-v"
16737 (lambda () (interactive)
16738 (org-eval-in-calendar
16739 '(calendar-scroll-right-three-months 1))))
16740 map)
16741 "Keymap for minibuffer commands when using `org-read-date'.")
16743 (defvar org-def)
16744 (defvar org-defdecode)
16745 (defvar org-with-time)
16747 (defun org-read-date (&optional org-with-time to-time from-string prompt
16748 default-time default-input inactive)
16749 "Read a date, possibly a time, and make things smooth for the user.
16750 The prompt will suggest to enter an ISO date, but you can also enter anything
16751 which will at least partially be understood by `parse-time-string'.
16752 Unrecognized parts of the date will default to the current day, month, year,
16753 hour and minute. If this command is called to replace a timestamp at point,
16754 or to enter the second timestamp of a range, the default time is taken
16755 from the existing stamp. Furthermore, the command prefers the future,
16756 so if you are giving a date where the year is not given, and the day-month
16757 combination is already past in the current year, it will assume you
16758 mean next year. For details, see the manual. A few examples:
16760 3-2-5 --> 2003-02-05
16761 feb 15 --> currentyear-02-15
16762 2/15 --> currentyear-02-15
16763 sep 12 9 --> 2009-09-12
16764 12:45 --> today 12:45
16765 22 sept 0:34 --> currentyear-09-22 0:34
16766 12 --> currentyear-currentmonth-12
16767 Fri --> nearest Friday after today
16768 -Tue --> last Tuesday
16769 etc.
16771 Furthermore you can specify a relative date by giving, as the *first* thing
16772 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16773 change in days weeks, months, years.
16774 With a single plus or minus, the date is relative to today. With a double
16775 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16776 +4d --> four days from today
16777 +4 --> same as above
16778 +2w --> two weeks from today
16779 ++5 --> five days from default date
16781 The function understands only English month and weekday abbreviations.
16783 While prompting, a calendar is popped up - you can also select the
16784 date with the mouse (button 1). The calendar shows a period of three
16785 months. To scroll it to other months, use the keys `>' and `<'.
16786 If you don't like the calendar, turn it off with
16787 \(setq org-read-date-popup-calendar nil)
16789 With optional argument TO-TIME, the date will immediately be converted
16790 to an internal time.
16791 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16792 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16793 still enter a time, and this function will inform the calling routine
16794 about this change. The calling routine may then choose to change the
16795 format used to insert the time stamp into the buffer to include the time.
16796 With optional argument FROM-STRING, read from this string instead from
16797 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16798 the time/date that is used for everything that is not specified by the
16799 user."
16800 (require 'parse-time)
16801 (let* ((org-time-stamp-rounding-minutes
16802 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16803 (org-dcst org-display-custom-times)
16804 (ct (org-current-time))
16805 (org-def (or org-overriding-default-time default-time ct))
16806 (org-defdecode (decode-time org-def))
16807 (dummy (progn
16808 (when (< (nth 2 org-defdecode) org-extend-today-until)
16809 (setcar (nthcdr 2 org-defdecode) -1)
16810 (setcar (nthcdr 1 org-defdecode) 59)
16811 (setq org-def (apply 'encode-time org-defdecode)
16812 org-defdecode (decode-time org-def)))))
16813 (cur-frame (selected-frame))
16814 (mouse-autoselect-window nil) ; Don't let the mouse jump
16815 (calendar-frame-setup nil)
16816 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16817 (calendar-move-hook nil)
16818 (calendar-view-diary-initially-flag nil)
16819 (calendar-view-holidays-initially-flag nil)
16820 (timestr (format-time-string
16821 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16822 (prompt (concat (if prompt (concat prompt " ") "")
16823 (format "Date+time [%s]: " timestr)))
16824 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16826 (cond
16827 (from-string (setq ans from-string))
16828 (org-read-date-popup-calendar
16829 (save-excursion
16830 (save-window-excursion
16831 (calendar)
16832 (when (eq calendar-setup 'calendar-only)
16833 (setq cal-frame
16834 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16835 (select-frame cal-frame))
16836 (org-eval-in-calendar '(setq cursor-type nil) t)
16837 (unwind-protect
16838 (progn
16839 (calendar-forward-day (- (time-to-days org-def)
16840 (calendar-absolute-from-gregorian
16841 (calendar-current-date))))
16842 (org-eval-in-calendar nil t)
16843 (let* ((old-map (current-local-map))
16844 (map (copy-keymap calendar-mode-map))
16845 (minibuffer-local-map
16846 (copy-keymap org-read-date-minibuffer-local-map)))
16847 (org-defkey map (kbd "RET") 'org-calendar-select)
16848 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16849 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16850 (unwind-protect
16851 (progn
16852 (use-local-map map)
16853 (setq org-read-date-inactive inactive)
16854 (add-hook 'post-command-hook 'org-read-date-display)
16855 (setq org-ans0 (read-string prompt default-input
16856 'org-read-date-history nil))
16857 ;; org-ans0: from prompt
16858 ;; org-ans1: from mouse click
16859 ;; org-ans2: from calendar motion
16860 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16861 (remove-hook 'post-command-hook 'org-read-date-display)
16862 (use-local-map old-map)
16863 (when org-read-date-overlay
16864 (delete-overlay org-read-date-overlay)
16865 (setq org-read-date-overlay nil)))))
16866 (bury-buffer "*Calendar*")
16867 (when cal-frame
16868 (delete-frame cal-frame)
16869 (select-frame-set-input-focus cur-frame))))))
16871 (t ; Naked prompt only
16872 (unwind-protect
16873 (setq ans (read-string prompt default-input
16874 'org-read-date-history timestr))
16875 (when org-read-date-overlay
16876 (delete-overlay org-read-date-overlay)
16877 (setq org-read-date-overlay nil)))))
16879 (setq final (org-read-date-analyze ans org-def org-defdecode))
16881 (when org-read-date-analyze-forced-year
16882 (message "Year was forced into %s"
16883 (if org-read-date-force-compatible-dates
16884 "compatible range (1970-2037)"
16885 "range representable on this machine"))
16886 (ding))
16888 ;; One round trip to get rid of 34th of August and stuff like that....
16889 (setq final (decode-time (apply 'encode-time final)))
16891 (setq org-read-date-final-answer ans)
16893 (if to-time
16894 (apply 'encode-time final)
16895 (if (and (boundp 'org-time-was-given) org-time-was-given)
16896 (format "%04d-%02d-%02d %02d:%02d"
16897 (nth 5 final) (nth 4 final) (nth 3 final)
16898 (nth 2 final) (nth 1 final))
16899 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16901 (defun org-read-date-display ()
16902 "Display the current date prompt interpretation in the minibuffer."
16903 (when org-read-date-display-live
16904 (when org-read-date-overlay
16905 (delete-overlay org-read-date-overlay))
16906 (when (minibufferp (current-buffer))
16907 (save-excursion
16908 (end-of-line 1)
16909 (while (not (equal (buffer-substring
16910 (max (point-min) (- (point) 4)) (point))
16911 " "))
16912 (insert " ")))
16913 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16914 " " (or org-ans1 org-ans2)))
16915 (org-end-time-was-given nil)
16916 (f (org-read-date-analyze ans org-def org-defdecode))
16917 (fmts (if org-dcst
16918 org-time-stamp-custom-formats
16919 org-time-stamp-formats))
16920 (fmt (if (or org-with-time
16921 (and (boundp 'org-time-was-given) org-time-was-given))
16922 (cdr fmts)
16923 (car fmts)))
16924 (txt (format-time-string fmt (apply 'encode-time f)))
16925 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16926 (txt (concat "=> " txt)))
16927 (when (and org-end-time-was-given
16928 (string-match org-plain-time-of-day-regexp txt))
16929 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16930 org-end-time-was-given
16931 (substring txt (match-end 0)))))
16932 (when org-read-date-analyze-futurep
16933 (setq txt (concat txt " (=>F)")))
16934 (setq org-read-date-overlay
16935 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16936 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16938 (defun org-read-date-analyze (ans org-def org-defdecode)
16939 "Analyze the combined answer of the date prompt."
16940 ;; FIXME: cleanup and comment
16941 (let ((nowdecode (decode-time (current-time)))
16942 delta deltan deltaw deltadef year month day
16943 hour minute second wday pm h2 m2 tl wday1
16944 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16945 (setq org-read-date-analyze-futurep nil
16946 org-read-date-analyze-forced-year nil)
16947 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16948 (setq ans "+0"))
16950 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16951 (setq ans (replace-match "" t t ans)
16952 deltan (car delta)
16953 deltaw (nth 1 delta)
16954 deltadef (nth 2 delta)))
16956 ;; Check if there is an iso week date in there. If yes, store the
16957 ;; info and postpone interpreting it until the rest of the parsing
16958 ;; is done.
16959 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16960 (setq iso-year (if (match-end 1)
16961 (org-small-year-to-year
16962 (string-to-number (match-string 1 ans))))
16963 iso-weekday (if (match-end 3)
16964 (string-to-number (match-string 3 ans)))
16965 iso-week (string-to-number (match-string 2 ans)))
16966 (setq ans (replace-match "" t t ans)))
16968 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16969 (when (string-match
16970 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16971 (setq year (if (match-end 2)
16972 (string-to-number (match-string 2 ans))
16973 (progn (setq kill-year t)
16974 (string-to-number (format-time-string "%Y"))))
16975 month (string-to-number (match-string 3 ans))
16976 day (string-to-number (match-string 4 ans)))
16977 (if (< year 100) (setq year (+ 2000 year)))
16978 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16979 t nil ans)))
16981 ;; Help matching dotted european dates
16982 (when (string-match
16983 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16984 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16985 (setq kill-year t)
16986 (string-to-number (format-time-string "%Y")))
16987 day (string-to-number (match-string 1 ans))
16988 month (string-to-number (match-string 2 ans))
16989 ans (replace-match (format "%04d-%02d-%02d" year month day)
16990 t nil ans)))
16992 ;; Help matching american dates, like 5/30 or 5/30/7
16993 (when (string-match
16994 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16995 (setq year (if (match-end 4)
16996 (string-to-number (match-string 4 ans))
16997 (progn (setq kill-year t)
16998 (string-to-number (format-time-string "%Y"))))
16999 month (string-to-number (match-string 1 ans))
17000 day (string-to-number (match-string 2 ans)))
17001 (if (< year 100) (setq year (+ 2000 year)))
17002 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17003 t nil ans)))
17004 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17005 ;; If there is a time with am/pm, and *no* time without it, we convert
17006 ;; so that matching will be successful.
17007 (loop for i from 1 to 2 do ; twice, for end time as well
17008 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17009 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17010 (setq hour (string-to-number (match-string 1 ans))
17011 minute (if (match-end 3)
17012 (string-to-number (match-string 3 ans))
17014 pm (equal ?p
17015 (string-to-char (downcase (match-string 4 ans)))))
17016 (if (and (= hour 12) (not pm))
17017 (setq hour 0)
17018 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17019 (setq ans (replace-match (format "%02d:%02d" hour minute)
17020 t t ans))))
17022 ;; Check if a time range is given as a duration
17023 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17024 (setq hour (string-to-number (match-string 1 ans))
17025 h2 (+ hour (string-to-number (match-string 3 ans)))
17026 minute (string-to-number (match-string 2 ans))
17027 m2 (+ minute (if (match-end 5) (string-to-number
17028 (match-string 5 ans))0)))
17029 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17030 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17031 t t ans)))
17033 ;; Check if there is a time range
17034 (when (boundp 'org-end-time-was-given)
17035 (setq org-time-was-given nil)
17036 (when (and (string-match org-plain-time-of-day-regexp ans)
17037 (match-end 8))
17038 (setq org-end-time-was-given (match-string 8 ans))
17039 (setq ans (concat (substring ans 0 (match-beginning 7))
17040 (substring ans (match-end 7))))))
17042 (setq tl (parse-time-string ans)
17043 day (or (nth 3 tl) (nth 3 org-defdecode))
17044 month
17045 (cond ((nth 4 tl))
17046 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17047 ;; Day was specified. Make sure DAY+MONTH
17048 ;; combination happens in the future.
17049 ((nth 3 tl)
17050 (setq futurep t)
17051 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17052 (nth 4 nowdecode)))
17053 (t (nth 4 org-defdecode)))
17054 year
17055 (cond ((and (not kill-year) (nth 5 tl)))
17056 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17057 ;; Month was guessed in the future and is at least
17058 ;; equal to NOWDECODE's. Fix year accordingly.
17059 (futurep
17060 (if (or (> month (nth 4 nowdecode))
17061 (>= day (nth 3 nowdecode)))
17062 (nth 5 nowdecode)
17063 (1+ (nth 5 nowdecode))))
17064 ;; Month was specified. Make sure MONTH+YEAR
17065 ;; combination happens in the future.
17066 ((nth 4 tl)
17067 (setq futurep t)
17068 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17069 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17070 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17071 (t (nth 5 nowdecode))))
17072 (t (nth 5 org-defdecode)))
17073 hour (or (nth 2 tl) (nth 2 org-defdecode))
17074 minute (or (nth 1 tl) (nth 1 org-defdecode))
17075 second (or (nth 0 tl) 0)
17076 wday (nth 6 tl))
17078 (when (and (eq org-read-date-prefer-future 'time)
17079 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17080 (equal day (nth 3 nowdecode))
17081 (equal month (nth 4 nowdecode))
17082 (equal year (nth 5 nowdecode))
17083 (nth 2 tl)
17084 (or (< (nth 2 tl) (nth 2 nowdecode))
17085 (and (= (nth 2 tl) (nth 2 nowdecode))
17086 (nth 1 tl)
17087 (< (nth 1 tl) (nth 1 nowdecode)))))
17088 (setq day (1+ day)
17089 futurep t))
17091 ;; Special date definitions below
17092 (cond
17093 (iso-week
17094 ;; There was an iso week
17095 (require 'cal-iso)
17096 (setq futurep nil)
17097 (setq year (or iso-year year)
17098 day (or iso-weekday wday 1)
17099 wday nil ; to make sure that the trigger below does not match
17100 iso-date (calendar-gregorian-from-absolute
17101 (calendar-iso-to-absolute
17102 (list iso-week day year))))
17103 ; FIXME: Should we also push ISO weeks into the future?
17104 ; (when (and org-read-date-prefer-future
17105 ; (not iso-year)
17106 ; (< (calendar-absolute-from-gregorian iso-date)
17107 ; (time-to-days (current-time))))
17108 ; (setq year (1+ year)
17109 ; iso-date (calendar-gregorian-from-absolute
17110 ; (calendar-iso-to-absolute
17111 ; (list iso-week day year)))))
17112 (setq month (car iso-date)
17113 year (nth 2 iso-date)
17114 day (nth 1 iso-date)))
17115 (deltan
17116 (setq futurep nil)
17117 (unless deltadef
17118 (let ((now (decode-time (current-time))))
17119 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17120 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17121 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17122 ((equal deltaw "m") (setq month (+ month deltan)))
17123 ((equal deltaw "y") (setq year (+ year deltan)))))
17124 ((and wday (not (nth 3 tl)))
17125 ;; Weekday was given, but no day, so pick that day in the week
17126 ;; on or after the derived date.
17127 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17128 (unless (equal wday wday1)
17129 (setq day (+ day (% (- wday wday1 -7) 7))))))
17130 (if (and (boundp 'org-time-was-given)
17131 (nth 2 tl))
17132 (setq org-time-was-given t))
17133 (if (< year 100) (setq year (+ 2000 year)))
17134 ;; Check of the date is representable
17135 (if org-read-date-force-compatible-dates
17136 (progn
17137 (if (< year 1970)
17138 (setq year 1970 org-read-date-analyze-forced-year t))
17139 (if (> year 2037)
17140 (setq year 2037 org-read-date-analyze-forced-year t)))
17141 (condition-case nil
17142 (ignore (encode-time second minute hour day month year))
17143 (error
17144 (setq year (nth 5 org-defdecode))
17145 (setq org-read-date-analyze-forced-year t))))
17146 (setq org-read-date-analyze-futurep futurep)
17147 (list second minute hour day month year)))
17149 (defvar parse-time-weekdays)
17150 (defun org-read-date-get-relative (s today default)
17151 "Check string S for special relative date string.
17152 TODAY and DEFAULT are internal times, for today and for a default.
17153 Return shift list (N what def-flag)
17154 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17155 N is the number of WHATs to shift.
17156 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17157 the DEFAULT date rather than TODAY."
17158 (require 'parse-time)
17159 (when (and
17160 (string-match
17161 (concat
17162 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17163 "\\([0-9]+\\)?"
17164 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17165 "\\([ \t]\\|$\\)") s)
17166 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17167 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17168 (string-to-char (substring (match-string 1 s) -1))
17169 ?+))
17170 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17171 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17172 (what (if (match-end 3) (match-string 3 s) "d"))
17173 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17174 (date (if rel default today))
17175 (wday (nth 6 (decode-time date)))
17176 delta)
17177 (if wday1
17178 (progn
17179 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17180 (if (= delta 0) (setq delta 7))
17181 (if (= dir ?-)
17182 (progn
17183 (setq delta (- delta 7))
17184 (if (= delta 0) (setq delta -7))))
17185 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17186 (list delta "d" rel))
17187 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17189 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17190 "Turn a user-specified date into the internal representation.
17191 The internal representation needed by the calendar is (month day year).
17192 This is a wrapper to handle the brain-dead convention in calendar that
17193 user function argument order change dependent on argument order."
17194 (if (boundp 'calendar-date-style)
17195 (cond
17196 ((eq calendar-date-style 'american)
17197 (list arg1 arg2 arg3))
17198 ((eq calendar-date-style 'european)
17199 (list arg2 arg1 arg3))
17200 ((eq calendar-date-style 'iso)
17201 (list arg2 arg3 arg1)))
17202 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17203 (if (org-bound-and-true-p european-calendar-style)
17204 (list arg2 arg1 arg3)
17205 (list arg1 arg2 arg3)))))
17207 (defun org-eval-in-calendar (form &optional keepdate)
17208 "Eval FORM in the calendar window and return to current window.
17209 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17210 otherwise stick to the current value of `org-ans2'."
17211 (let ((sf (selected-frame))
17212 (sw (selected-window)))
17213 (select-window (get-buffer-window "*Calendar*" t))
17214 (eval form)
17215 (when (and (not keepdate) (calendar-cursor-to-date))
17216 (let* ((date (calendar-cursor-to-date))
17217 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17218 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17219 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17220 (select-window sw)
17221 (org-select-frame-set-input-focus sf)))
17223 (defun org-calendar-select ()
17224 "Return to `org-read-date' with the date currently selected.
17225 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17226 (interactive)
17227 (when (calendar-cursor-to-date)
17228 (let* ((date (calendar-cursor-to-date))
17229 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17230 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17231 (if (active-minibuffer-window) (exit-minibuffer))))
17233 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17234 "Insert a date stamp for the date given by the internal TIME.
17235 See `format-time-string' for the format of TIME.
17236 WITH-HM means use the stamp format that includes the time of the day.
17237 INACTIVE means use square brackets instead of angular ones, so that the
17238 stamp will not contribute to the agenda.
17239 PRE and POST are optional strings to be inserted before and after the
17240 stamp.
17241 The command returns the inserted time stamp."
17242 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17243 stamp)
17244 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17245 (insert-before-markers (or pre ""))
17246 (when (listp extra)
17247 (setq extra (car extra))
17248 (if (and (stringp extra)
17249 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17250 (setq extra (format "-%02d:%02d"
17251 (string-to-number (match-string 1 extra))
17252 (string-to-number (match-string 2 extra))))
17253 (setq extra nil)))
17254 (when extra
17255 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17256 (insert-before-markers (setq stamp (format-time-string fmt time)))
17257 (insert-before-markers (or post ""))
17258 (setq org-last-inserted-timestamp stamp)))
17260 (defun org-toggle-time-stamp-overlays ()
17261 "Toggle the use of custom time stamp formats."
17262 (interactive)
17263 (setq org-display-custom-times (not org-display-custom-times))
17264 (unless org-display-custom-times
17265 (let ((p (point-min)) (bmp (buffer-modified-p)))
17266 (while (setq p (next-single-property-change p 'display))
17267 (if (and (get-text-property p 'display)
17268 (eq (get-text-property p 'face) 'org-date))
17269 (remove-text-properties
17270 p (setq p (next-single-property-change p 'display))
17271 '(display t))))
17272 (set-buffer-modified-p bmp)))
17273 (if (featurep 'xemacs)
17274 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17275 (org-restart-font-lock)
17276 (setq org-table-may-need-update t)
17277 (if org-display-custom-times
17278 (message "Time stamps are overlaid with custom format")
17279 (message "Time stamp overlays removed")))
17281 (defun org-display-custom-time (beg end)
17282 "Overlay modified time stamp format over timestamp between BEG and END."
17283 (let* ((ts (buffer-substring beg end))
17284 t1 w1 with-hm tf time str w2 (off 0))
17285 (save-match-data
17286 (setq t1 (org-parse-time-string ts t))
17287 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17288 (setq off (- (match-end 0) (match-beginning 0)))))
17289 (setq end (- end off))
17290 (setq w1 (- end beg)
17291 with-hm (and (nth 1 t1) (nth 2 t1))
17292 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17293 time (org-fix-decoded-time t1)
17294 str (org-add-props
17295 (format-time-string
17296 (substring tf 1 -1) (apply 'encode-time time))
17297 nil 'mouse-face 'highlight)
17298 w2 (length str))
17299 (if (not (= w2 w1))
17300 (add-text-properties (1+ beg) (+ 2 beg)
17301 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17302 (if (featurep 'xemacs)
17303 (progn
17304 (put-text-property beg end 'invisible t)
17305 (put-text-property beg end 'end-glyph (make-glyph str)))
17306 (put-text-property beg end 'display str))))
17308 (defun org-fix-decoded-time (time)
17309 "Set 0 instead of nil for the first 6 elements of time.
17310 Don't touch the rest."
17311 (let ((n 0))
17312 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17314 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17316 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17317 "Difference between TIMESTAMP-STRING and now in days.
17318 If SECONDS is non-nil, return the difference in seconds."
17319 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17320 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17321 (funcall fdiff (current-time)))))
17323 (defun org-deadline-close (timestamp-string &optional ndays)
17324 "Is the time in TIMESTAMP-STRING close to the current date?"
17325 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17326 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17327 (not (org-entry-is-done-p))))
17329 (defun org-get-wdays (ts &optional delay zero-delay)
17330 "Get the deadline lead time appropriate for timestring TS.
17331 When DELAY is non-nil, get the delay time for scheduled items
17332 instead of the deadline lead time. When ZERO-DELAY is non-nil
17333 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17334 don't try to find the delay cookie in the scheduled timestamp."
17335 (let ((tv (if delay org-scheduled-delay-days
17336 org-deadline-warning-days)))
17337 (cond
17338 ((or (and delay (< tv 0))
17339 (and delay zero-delay (<= tv 0))
17340 (and (not delay) (<= tv 0)))
17341 ;; Enforce this value no matter what
17342 (- tv))
17343 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17344 ;; lead time is specified.
17345 (floor (* (string-to-number (match-string 1 ts))
17346 (cdr (assoc (match-string 2 ts)
17347 '(("d" . 1) ("w" . 7)
17348 ("m" . 30.4) ("y" . 365.25)
17349 ("h" . 0.041667)))))))
17350 ;; go for the default.
17351 (t tv))))
17353 (defun org-calendar-select-mouse (ev)
17354 "Return to `org-read-date' with the date currently selected.
17355 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17356 (interactive "e")
17357 (mouse-set-point ev)
17358 (when (calendar-cursor-to-date)
17359 (let* ((date (calendar-cursor-to-date))
17360 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17361 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17362 (if (active-minibuffer-window) (exit-minibuffer))))
17364 (defun org-check-deadlines (ndays)
17365 "Check if there are any deadlines due or past due.
17366 A deadline is considered due if it happens within `org-deadline-warning-days'
17367 days from today's date. If the deadline appears in an entry marked DONE,
17368 it is not shown. The prefix arg NDAYS can be used to test that many
17369 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17370 (interactive "P")
17371 (let* ((org-warn-days
17372 (cond
17373 ((equal ndays '(4)) 100000)
17374 (ndays (prefix-numeric-value ndays))
17375 (t (abs org-deadline-warning-days))))
17376 (case-fold-search nil)
17377 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17378 (callback
17379 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17381 (message "%d deadlines past-due or due within %d days"
17382 (org-occur regexp nil callback)
17383 org-warn-days)))
17385 (defsubst org-re-timestamp (type)
17386 "Return a regexp for timestamp TYPE.
17387 Allowed values for TYPE are:
17389 all: all timestamps
17390 active: only active timestamps (<...>)
17391 inactive: only inactive timestamps ([...])
17392 scheduled: only scheduled timestamps
17393 deadline: only deadline timestamps
17394 closed: only closed time-stamps
17396 When TYPE is nil, fall back on returning a regexp that matches
17397 both scheduled and deadline timestamps."
17398 (case type
17399 (all org-ts-regexp-both)
17400 (active org-ts-regexp)
17401 (inactive org-ts-regexp-inactive)
17402 (scheduled org-scheduled-time-regexp)
17403 (deadline org-deadline-time-regexp)
17404 (closed org-closed-time-regexp)
17405 (otherwise
17406 (concat "\\<"
17407 (regexp-opt (list org-deadline-string org-scheduled-string))
17408 " *<\\([^>]+\\)>"))))
17410 (defun org-check-before-date (date)
17411 "Check if there are deadlines or scheduled entries before DATE."
17412 (interactive (list (org-read-date)))
17413 (let ((case-fold-search nil)
17414 (regexp (org-re-timestamp org-ts-type))
17415 (callback
17416 `(lambda ()
17417 (and ,(if (memq org-ts-type '(active inactive all))
17418 '(eq (org-element-type (org-element-context)) 'timestamp)
17419 '(org-at-planning-p))
17420 (time-less-p
17421 (org-time-string-to-time (match-string 1))
17422 (org-time-string-to-time date))))))
17423 (message "%d entries before %s"
17424 (org-occur regexp nil callback) date)))
17426 (defun org-check-after-date (date)
17427 "Check if there are deadlines or scheduled entries after DATE."
17428 (interactive (list (org-read-date)))
17429 (let ((case-fold-search nil)
17430 (regexp (org-re-timestamp org-ts-type))
17431 (callback
17432 `(lambda ()
17433 (and ,(if (memq org-ts-type '(active inactive all))
17434 '(eq (org-element-type (org-element-context)) 'timestamp)
17435 '(org-at-planning-p))
17436 (not (time-less-p
17437 (org-time-string-to-time (match-string 1))
17438 (org-time-string-to-time date)))))))
17439 (message "%d entries after %s"
17440 (org-occur regexp nil callback) date)))
17442 (defun org-check-dates-range (start-date end-date)
17443 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17444 (interactive (list (org-read-date nil nil nil "Range starts")
17445 (org-read-date nil nil nil "Range end")))
17446 (let ((case-fold-search nil)
17447 (regexp (org-re-timestamp org-ts-type))
17448 (callback
17449 `(lambda ()
17450 (let ((match (match-string 1)))
17451 (and
17452 ,(if (memq org-ts-type '(active inactive all))
17453 '(eq (org-element-type (org-element-context)) 'timestamp)
17454 '(org-at-planning-p))
17455 (not (time-less-p
17456 (org-time-string-to-time match)
17457 (org-time-string-to-time start-date)))
17458 (time-less-p
17459 (org-time-string-to-time match)
17460 (org-time-string-to-time end-date)))))))
17461 (message "%d entries between %s and %s"
17462 (org-occur regexp nil callback) start-date end-date)))
17464 (defun org-evaluate-time-range (&optional to-buffer)
17465 "Evaluate a time range by computing the difference between start and end.
17466 Normally the result is just printed in the echo area, but with prefix arg
17467 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17468 If the time range is actually in a table, the result is inserted into the
17469 next column.
17470 For time difference computation, a year is assumed to be exactly 365
17471 days in order to avoid rounding problems."
17472 (interactive "P")
17474 (org-clock-update-time-maybe)
17475 (save-excursion
17476 (unless (org-at-date-range-p t)
17477 (goto-char (point-at-bol))
17478 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17479 (if (not (org-at-date-range-p t))
17480 (user-error "Not at a time-stamp range, and none found in current line")))
17481 (let* ((ts1 (match-string 1))
17482 (ts2 (match-string 2))
17483 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17484 (match-end (match-end 0))
17485 (time1 (org-time-string-to-time ts1))
17486 (time2 (org-time-string-to-time ts2))
17487 (t1 (org-float-time time1))
17488 (t2 (org-float-time time2))
17489 (diff (abs (- t2 t1)))
17490 (negative (< (- t2 t1) 0))
17491 ;; (ys (floor (* 365 24 60 60)))
17492 (ds (* 24 60 60))
17493 (hs (* 60 60))
17494 (fy "%dy %dd %02d:%02d")
17495 (fy1 "%dy %dd")
17496 (fd "%dd %02d:%02d")
17497 (fd1 "%dd")
17498 (fh "%02d:%02d")
17499 y d h m align)
17500 (if havetime
17501 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17503 d (floor (/ diff ds)) diff (mod diff ds)
17504 h (floor (/ diff hs)) diff (mod diff hs)
17505 m (floor (/ diff 60)))
17506 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17508 d (floor (+ (/ diff ds) 0.5))
17509 h 0 m 0))
17510 (if (not to-buffer)
17511 (message "%s" (org-make-tdiff-string y d h m))
17512 (if (org-at-table-p)
17513 (progn
17514 (goto-char match-end)
17515 (setq align t)
17516 (and (looking-at " *|") (goto-char (match-end 0))))
17517 (goto-char match-end))
17518 (if (looking-at
17519 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17520 (replace-match ""))
17521 (if negative (insert " -"))
17522 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17523 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17524 (insert " " (format fh h m))))
17525 (if align (org-table-align))
17526 (message "Time difference inserted")))))
17528 (defun org-make-tdiff-string (y d h m)
17529 (let ((fmt "")
17530 (l nil))
17531 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17532 l (push y l)))
17533 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17534 l (push d l)))
17535 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17536 l (push h l)))
17537 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17538 l (push m l)))
17539 (apply 'format fmt (nreverse l))))
17541 (defun org-time-string-to-time (s &optional buffer pos)
17542 "Convert a timestamp string into internal time."
17543 (condition-case errdata
17544 (apply 'encode-time (org-parse-time-string s))
17545 (error (error "Bad timestamp `%s'%s\nError was: %s"
17546 s (if (not (and buffer pos))
17548 (format " at %d in buffer `%s'" pos buffer))
17549 (cdr errdata)))))
17551 (defun org-time-string-to-seconds (s)
17552 "Convert a timestamp string to a number of seconds."
17553 (org-float-time (org-time-string-to-time s)))
17555 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17556 "Convert a time stamp to an absolute day number.
17557 If there is a specifier for a cyclic time stamp, get the closest
17558 date to DAYNR.
17559 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17560 The variable `date' is bound by the calendar when this is called."
17561 (cond
17562 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17563 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17564 daynr
17565 (+ daynr 1000)))
17566 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17567 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17568 (time-to-days (current-time))) (match-string 0 s)
17569 prefer show-all))
17570 (t (time-to-days
17571 (condition-case errdata
17572 (apply 'encode-time (org-parse-time-string s))
17573 (error (error "Bad timestamp `%s'%s\nError was: %s"
17574 s (if (not (and buffer pos))
17576 (format " at %d in buffer `%s'" pos buffer))
17577 (cdr errdata))))))))
17579 (defun org-days-to-iso-week (days)
17580 "Return the iso week number."
17581 (require 'cal-iso)
17582 (car (calendar-iso-from-absolute days)))
17584 (defun org-small-year-to-year (year)
17585 "Convert 2-digit years into 4-digit years.
17586 YEAR is expanded into one of the 30 next years, if possible, or
17587 into a past one. Any year larger than 99 is returned unchanged."
17588 (if (>= year 100) year
17589 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17590 (century (/ current 100))
17591 (offset (- year (% current 100))))
17592 (cond ((> offset 30) (+ (* (1- century) 100) year))
17593 ((> offset -70) (+ (* century 100) year))
17594 (t (+ (* (1+ century) 100) year))))))
17596 (defun org-time-from-absolute (d)
17597 "Return the time corresponding to date D.
17598 D may be an absolute day number, or a calendar-type list (month day year)."
17599 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17600 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17602 (defun org-calendar-holiday ()
17603 "List of holidays, for Diary display in Org-mode."
17604 (require 'holidays)
17605 (let ((hl (funcall
17606 (if (fboundp 'calendar-check-holidays)
17607 'calendar-check-holidays 'check-calendar-holidays) date)))
17608 (if hl (mapconcat 'identity hl "; "))))
17610 (defun org-diary-sexp-entry (sexp entry date)
17611 "Process a SEXP diary ENTRY for DATE."
17612 (require 'diary-lib)
17613 (let ((result (if calendar-debug-sexp
17614 (let ((stack-trace-on-error t))
17615 (eval (car (read-from-string sexp))))
17616 (condition-case nil
17617 (eval (car (read-from-string sexp)))
17618 (error
17619 (beep)
17620 (message "Bad sexp at line %d in %s: %s"
17621 (org-current-line)
17622 (buffer-file-name) sexp)
17623 (sleep-for 2))))))
17624 (cond ((stringp result) (split-string result "; "))
17625 ((and (consp result)
17626 (not (consp (cdr result)))
17627 (stringp (cdr result))) (cdr result))
17628 ((and (consp result)
17629 (stringp (car result))) result)
17630 (result entry))))
17632 (defun org-diary-to-ical-string (frombuf)
17633 "Get iCalendar entries from diary entries in buffer FROMBUF.
17634 This uses the icalendar.el library."
17635 (let* ((tmpdir (if (featurep 'xemacs)
17636 (temp-directory)
17637 temporary-file-directory))
17638 (tmpfile (make-temp-name
17639 (expand-file-name "orgics" tmpdir)))
17640 buf rtn b e)
17641 (with-current-buffer frombuf
17642 (icalendar-export-region (point-min) (point-max) tmpfile)
17643 (setq buf (find-buffer-visiting tmpfile))
17644 (set-buffer buf)
17645 (goto-char (point-min))
17646 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17647 (setq b (match-beginning 0)))
17648 (goto-char (point-max))
17649 (if (re-search-backward "^END:VEVENT" nil t)
17650 (setq e (match-end 0)))
17651 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17652 (kill-buffer buf)
17653 (delete-file tmpfile)
17654 rtn))
17656 (defun org-closest-date (start current change prefer show-all)
17657 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17658 When PREFER is `past', return a date that is either CURRENT or past.
17659 When PREFER is `future', return a date that is either CURRENT or future.
17660 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17661 ;; Make the proper lists from the dates
17662 (catch 'exit
17663 (let ((a1 '(("h" . hour)
17664 ("d" . day)
17665 ("w" . week)
17666 ("m" . month)
17667 ("y" . year)))
17668 (shour (nth 2 (org-parse-time-string start)))
17669 dn dw sday cday n1 n2 n0
17670 d m y y1 y2 date1 date2 nmonths nm ny m2)
17672 (setq start (org-date-to-gregorian start)
17673 current (org-date-to-gregorian
17674 (if show-all
17675 current
17676 (time-to-days (current-time))))
17677 sday (calendar-absolute-from-gregorian start)
17678 cday (calendar-absolute-from-gregorian current))
17680 (if (<= cday sday) (throw 'exit sday))
17682 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17683 (setq dn (string-to-number (match-string 1 change))
17684 dw (cdr (assoc (match-string 2 change) a1)))
17685 (user-error "Invalid change specifier: %s" change))
17686 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17687 (cond
17688 ((eq dw 'hour)
17689 (let ((missing-hours
17690 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17691 dn)))
17692 (setq n1 (if (zerop missing-hours) cday
17693 (- cday (1+ (floor (/ missing-hours 24)))))
17694 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17695 ((eq dw 'day)
17696 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17697 n2 (+ n1 dn)))
17698 ((eq dw 'year)
17699 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17700 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17701 (setq date1 (list m d y1)
17702 n1 (calendar-absolute-from-gregorian date1)
17703 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17704 n2 (calendar-absolute-from-gregorian date2)))
17705 ((eq dw 'month)
17706 ;; approx number of month between the two dates
17707 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17708 ;; How often does dn fit in there?
17709 (setq d (nth 1 start) m (car start) y (nth 2 start)
17710 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17711 m (+ m nm)
17712 ny (floor (/ m 12))
17713 y (+ y ny)
17714 m (- m (* ny 12)))
17715 (while (> m 12) (setq m (- m 12) y (1+ y)))
17716 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17717 (setq m2 (+ m dn) y2 y)
17718 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17719 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17720 (while (<= n2 cday)
17721 (setq n1 n2 m m2 y y2)
17722 (setq m2 (+ m dn) y2 y)
17723 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17724 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17725 ;; Make sure n1 is the earlier date
17726 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17727 (if show-all
17728 (cond
17729 ((eq prefer 'past) (if (= cday n2) n2 n1))
17730 ((eq prefer 'future) (if (= cday n1) n1 n2))
17731 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17732 (cond
17733 ((eq prefer 'past) (if (= cday n2) n2 n1))
17734 ((eq prefer 'future) (if (= cday n1) n1 n2))
17735 (t (if (= cday n1) n1 n2)))))))
17737 (defun org-date-to-gregorian (date)
17738 "Turn any specification of DATE into a Gregorian date for the calendar."
17739 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17740 ((and (listp date) (= (length date) 3)) date)
17741 ((stringp date)
17742 (setq date (org-parse-time-string date))
17743 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17744 ((listp date)
17745 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17747 (defun org-parse-time-string (s &optional nodefault)
17748 "Parse the standard Org-mode time string.
17749 This should be a lot faster than the normal `parse-time-string'.
17750 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17751 hour and minute fields will be nil if not given."
17752 (cond ((string-match org-ts-regexp0 s)
17753 (list 0
17754 (if (or (match-beginning 8) (not nodefault))
17755 (string-to-number (or (match-string 8 s) "0")))
17756 (if (or (match-beginning 7) (not nodefault))
17757 (string-to-number (or (match-string 7 s) "0")))
17758 (string-to-number (match-string 4 s))
17759 (string-to-number (match-string 3 s))
17760 (string-to-number (match-string 2 s))
17761 nil nil nil))
17762 ((string-match "^<[^>]+>$" s)
17763 (decode-time (seconds-to-time (org-matcher-time s))))
17764 (t (error "Not a standard Org-mode time string: %s" s))))
17766 (defun org-timestamp-up (&optional arg)
17767 "Increase the date item at the cursor by one.
17768 If the cursor is on the year, change the year. If it is on the month,
17769 the day or the time, change that.
17770 With prefix ARG, change by that many units."
17771 (interactive "p")
17772 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17774 (defun org-timestamp-down (&optional arg)
17775 "Decrease the date item at the cursor by one.
17776 If the cursor is on the year, change the year. If it is on the month,
17777 the day or the time, change that.
17778 With prefix ARG, change by that many units."
17779 (interactive "p")
17780 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17782 (defun org-timestamp-up-day (&optional arg)
17783 "Increase the date in the time stamp by one day.
17784 With prefix ARG, change that many days."
17785 (interactive "p")
17786 (if (and (not (org-at-timestamp-p t))
17787 (org-at-heading-p))
17788 (org-todo 'up)
17789 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17791 (defun org-timestamp-down-day (&optional arg)
17792 "Decrease the date in the time stamp by one day.
17793 With prefix ARG, change that many days."
17794 (interactive "p")
17795 (if (and (not (org-at-timestamp-p t))
17796 (org-at-heading-p))
17797 (org-todo 'down)
17798 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17800 (defun org-at-timestamp-p (&optional inactive-ok)
17801 "Determine if the cursor is in or at a timestamp."
17802 (interactive)
17803 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17804 (pos (point))
17805 (ans (or (looking-at tsr)
17806 (save-excursion
17807 (skip-chars-backward "^[<\n\r\t")
17808 (if (> (point) (point-min)) (backward-char 1))
17809 (and (looking-at tsr)
17810 (> (- (match-end 0) pos) -1))))))
17811 (and ans
17812 (boundp 'org-ts-what)
17813 (setq org-ts-what
17814 (cond
17815 ((= pos (match-beginning 0)) 'bracket)
17816 ;; Point is considered to be "on the bracket" whether
17817 ;; it's really on it or right after it.
17818 ((= pos (1- (match-end 0))) 'bracket)
17819 ((= pos (match-end 0)) 'after)
17820 ((org-pos-in-match-range pos 2) 'year)
17821 ((org-pos-in-match-range pos 3) 'month)
17822 ((org-pos-in-match-range pos 7) 'hour)
17823 ((org-pos-in-match-range pos 8) 'minute)
17824 ((or (org-pos-in-match-range pos 4)
17825 (org-pos-in-match-range pos 5)) 'day)
17826 ((and (> pos (or (match-end 8) (match-end 5)))
17827 (< pos (match-end 0)))
17828 (- pos (or (match-end 8) (match-end 5))))
17829 (t 'day))))
17830 ans))
17832 (defun org-toggle-timestamp-type ()
17833 "Toggle the type (<active> or [inactive]) of a time stamp."
17834 (interactive)
17835 (when (org-at-timestamp-p t)
17836 (let ((beg (match-beginning 0)) (end (match-end 0))
17837 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17838 (save-excursion
17839 (goto-char beg)
17840 (while (re-search-forward "[][<>]" end t)
17841 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17842 t t)))
17843 (message "Timestamp is now %sactive"
17844 (if (equal (char-after beg) ?<) "" "in")))))
17846 (defun org-at-clock-log-p nil
17847 "Is the cursor on the clock log line?"
17848 (save-excursion
17849 (move-beginning-of-line 1)
17850 (looking-at org-clock-line-re)))
17852 (defvar org-clock-history) ; defined in org-clock.el
17853 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17854 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17855 "Change the date in the time stamp at point.
17856 The date will be changed by N times WHAT. WHAT can be `day', `month',
17857 `year', `minute', `second'. If WHAT is not given, the cursor position
17858 in the timestamp determines what will be changed.
17859 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17860 (let ((origin (point)) origin-cat
17861 with-hm inactive
17862 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17863 org-ts-what
17864 extra rem
17865 ts time time0 fixnext clrgx)
17866 (if (not (org-at-timestamp-p t))
17867 (user-error "Not at a timestamp"))
17868 (if (and (not what) (eq org-ts-what 'bracket))
17869 (org-toggle-timestamp-type)
17870 ;; Point isn't on brackets. Remember the part of the time-stamp
17871 ;; the point was in. Indeed, size of time-stamps may change,
17872 ;; but point must be kept in the same category nonetheless.
17873 (setq origin-cat org-ts-what)
17874 (if (and (not what) (not (eq org-ts-what 'day))
17875 org-display-custom-times
17876 (get-text-property (point) 'display)
17877 (not (get-text-property (1- (point)) 'display)))
17878 (setq org-ts-what 'day))
17879 (setq org-ts-what (or what org-ts-what)
17880 inactive (= (char-after (match-beginning 0)) ?\[)
17881 ts (match-string 0))
17882 (replace-match "")
17883 (when (string-match
17884 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17886 (setq extra (match-string 1 ts))
17887 (if suppress-tmp-delay
17888 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17889 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17890 (setq with-hm t))
17891 (setq time0 (org-parse-time-string ts))
17892 (when (and updown
17893 (eq org-ts-what 'minute)
17894 (not current-prefix-arg))
17895 ;; This looks like s-up and s-down. Change by one rounding step.
17896 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17897 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17898 (setcar (cdr time0) (+ (nth 1 time0)
17899 (if (> n 0) (- rem) (- dm rem))))))
17900 (setq time
17901 (encode-time (or (car time0) 0)
17902 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17903 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17904 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17905 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17906 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17907 (nthcdr 6 time0)))
17908 (when (and (member org-ts-what '(hour minute))
17909 extra
17910 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17911 (setq extra (org-modify-ts-extra
17912 extra
17913 (if (eq org-ts-what 'hour) 2 5)
17914 n dm)))
17915 (when (integerp org-ts-what)
17916 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17917 (if (eq what 'calendar)
17918 (let ((cal-date (org-get-date-from-calendar)))
17919 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17920 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17921 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17922 (setcar time0 (or (car time0) 0))
17923 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17924 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17925 (setq time (apply 'encode-time time0))))
17926 ;; Insert the new time-stamp, and ensure point stays in the same
17927 ;; category as before (i.e. not after the last position in that
17928 ;; category).
17929 (let ((pos (point)))
17930 ;; Stay before inserted string. `save-excursion' is of no use.
17931 (setq org-last-changed-timestamp
17932 (org-insert-time-stamp time with-hm inactive nil nil extra))
17933 (goto-char pos))
17934 (save-match-data
17935 (looking-at org-ts-regexp3)
17936 (goto-char (cond
17937 ;; `day' category ends before `hour' if any, or at
17938 ;; the end of the day name.
17939 ((eq origin-cat 'day)
17940 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17941 ((eq origin-cat 'hour) (min (match-end 7) origin))
17942 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17943 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17944 ;; `year' and `month' have both fixed size: point
17945 ;; couldn't have moved into another part.
17946 (t origin))))
17947 ;; Update clock if on a CLOCK line.
17948 (org-clock-update-time-maybe)
17949 ;; Maybe adjust the closest clock in `org-clock-history'
17950 (when org-clock-adjust-closest
17951 (if (not (and (org-at-clock-log-p)
17952 (< 1 (length (delq nil (mapcar 'marker-position
17953 org-clock-history))))))
17954 (message "No clock to adjust")
17955 (cond ((save-excursion ; fix previous clock?
17956 (re-search-backward org-ts-regexp0 nil t)
17957 (org-looking-back (concat org-clock-string " \\[")))
17958 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17959 ((save-excursion ; fix next clock?
17960 (re-search-backward org-ts-regexp0 nil t)
17961 (looking-at (concat org-ts-regexp0 "\\] =>")))
17962 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17963 (save-window-excursion
17964 ;; Find closest clock to point, adjust the previous/next one in history
17965 (let* ((p (save-excursion (org-back-to-heading t)))
17966 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17967 (clfixnth
17968 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17969 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17970 (if (not clfixpos)
17971 (message "No clock to adjust")
17972 (save-excursion
17973 (org-goto-marker-or-bmk clfixpos)
17974 (org-show-subtree)
17975 (when (re-search-forward clrgx nil t)
17976 (goto-char (match-beginning 1))
17977 (let (org-clock-adjust-closest)
17978 (org-timestamp-change n org-ts-what updown))
17979 (message "Clock adjusted in %s for heading: %s"
17980 (file-name-nondirectory (buffer-file-name))
17981 (org-get-heading t t)))))))))
17982 ;; Try to recenter the calendar window, if any.
17983 (if (and org-calendar-follow-timestamp-change
17984 (get-buffer-window "*Calendar*" t)
17985 (memq org-ts-what '(day month year)))
17986 (org-recenter-calendar (time-to-days time))))))
17988 (defun org-modify-ts-extra (s pos n dm)
17989 "Change the different parts of the lead-time and repeat fields in timestamp."
17990 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17991 ng h m new rem)
17992 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17993 (cond
17994 ((or (org-pos-in-match-range pos 2)
17995 (org-pos-in-match-range pos 3))
17996 (setq m (string-to-number (match-string 3 s))
17997 h (string-to-number (match-string 2 s)))
17998 (if (org-pos-in-match-range pos 2)
17999 (setq h (+ h n))
18000 (setq n (* dm (org-no-warnings (signum n))))
18001 (when (not (= 0 (setq rem (% m dm))))
18002 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18003 (setq m (+ m n)))
18004 (if (< m 0) (setq m (+ m 60) h (1- h)))
18005 (if (> m 59) (setq m (- m 60) h (1+ h)))
18006 (setq h (min 24 (max 0 h)))
18007 (setq ng 1 new (format "-%02d:%02d" h m)))
18008 ((org-pos-in-match-range pos 6)
18009 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18010 ((org-pos-in-match-range pos 5)
18011 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18013 ((org-pos-in-match-range pos 9)
18014 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18015 ((org-pos-in-match-range pos 8)
18016 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18018 (when ng
18019 (setq s (concat
18020 (substring s 0 (match-beginning ng))
18022 (substring s (match-end ng))))))
18025 (defun org-recenter-calendar (date)
18026 "If the calendar is visible, recenter it to DATE."
18027 (let ((cwin (get-buffer-window "*Calendar*" t)))
18028 (when cwin
18029 (let ((calendar-move-hook nil))
18030 (with-selected-window cwin
18031 (calendar-goto-date (if (listp date) date
18032 (calendar-gregorian-from-absolute date))))))))
18034 (defun org-goto-calendar (&optional arg)
18035 "Go to the Emacs calendar at the current date.
18036 If there is a time stamp in the current line, go to that date.
18037 A prefix ARG can be used to force the current date."
18038 (interactive "P")
18039 (let ((tsr org-ts-regexp) diff
18040 (calendar-move-hook nil)
18041 (calendar-view-holidays-initially-flag nil)
18042 (calendar-view-diary-initially-flag nil))
18043 (if (or (org-at-timestamp-p)
18044 (save-excursion
18045 (beginning-of-line 1)
18046 (looking-at (concat ".*" tsr))))
18047 (let ((d1 (time-to-days (current-time)))
18048 (d2 (time-to-days
18049 (org-time-string-to-time (match-string 1)))))
18050 (setq diff (- d2 d1))))
18051 (calendar)
18052 (calendar-goto-today)
18053 (if (and diff (not arg)) (calendar-forward-day diff))))
18055 (defun org-get-date-from-calendar ()
18056 "Return a list (month day year) of date at point in calendar."
18057 (with-current-buffer "*Calendar*"
18058 (save-match-data
18059 (calendar-cursor-to-date))))
18061 (defun org-date-from-calendar ()
18062 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18063 If there is already a time stamp at the cursor position, update it."
18064 (interactive)
18065 (if (org-at-timestamp-p t)
18066 (org-timestamp-change 0 'calendar)
18067 (let ((cal-date (org-get-date-from-calendar)))
18068 (org-insert-time-stamp
18069 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18071 (defcustom org-effort-durations
18072 `(("min" . 1)
18073 ("h" . 60)
18074 ("d" . ,(* 60 8))
18075 ("w" . ,(* 60 8 5))
18076 ("m" . ,(* 60 8 5 4))
18077 ("y" . ,(* 60 8 5 40)))
18078 "Conversion factor to minutes for an effort modifier.
18080 Each entry has the form (MODIFIER . MINUTES).
18082 In an effort string, a number followed by MODIFIER is multiplied
18083 by the specified number of MINUTES to obtain an effort in
18084 minutes.
18086 For example, if the value of this variable is ((\"hours\" . 60)), then an
18087 effort string \"2hours\" is equivalent to 120 minutes."
18088 :group 'org-agenda
18089 :version "25.1"
18090 :package-version '(Org . "8.3")
18091 :type '(alist :key-type (string :tag "Modifier")
18092 :value-type (number :tag "Minutes")))
18094 (defun org-minutes-to-clocksum-string (m)
18095 "Format number of minutes as a clocksum string.
18096 The format is determined by `org-time-clocksum-format',
18097 `org-time-clocksum-use-fractional' and
18098 `org-time-clocksum-fractional-format' and
18099 `org-time-clocksum-use-effort-durations'."
18100 (let ((clocksum "")
18101 (m (round m)) ; Don't allow fractions of minutes
18102 h d w mo y fmt n)
18103 (setq h (if org-time-clocksum-use-effort-durations
18104 (cdr (assoc "h" org-effort-durations)) 60)
18105 d (if org-time-clocksum-use-effort-durations
18106 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18107 w (if org-time-clocksum-use-effort-durations
18108 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18109 mo (if org-time-clocksum-use-effort-durations
18110 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18111 y (if org-time-clocksum-use-effort-durations
18112 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18113 ;; fractional format
18114 (if org-time-clocksum-use-fractional
18115 (cond
18116 ;; single format string
18117 ((stringp org-time-clocksum-fractional-format)
18118 (format org-time-clocksum-fractional-format (/ m (float h))))
18119 ;; choice of fractional formats for different time units
18120 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18121 (> (/ (truncate m) (* y d h)) 0))
18122 (format fmt (/ m (* y d (float h)))))
18123 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18124 (> (/ (truncate m) (* mo d h)) 0))
18125 (format fmt (/ m (* mo d (float h)))))
18126 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18127 (> (/ (truncate m) (* w d h)) 0))
18128 (format fmt (/ m (* w d (float h)))))
18129 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18130 (> (/ (truncate m) (* d h)) 0))
18131 (format fmt (/ m (* d (float h)))))
18132 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18133 (> (/ (truncate m) h) 0))
18134 (format fmt (/ m (float h))))
18135 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18136 (format fmt m))
18137 ;; fall back to smallest time unit with a format
18138 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18139 (format fmt (/ m (float h))))
18140 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18141 (format fmt (/ m (* d (float h)))))
18142 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18143 (format fmt (/ m (* w d (float h)))))
18144 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18145 (format fmt (/ m (* mo d (float h)))))
18146 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18147 (format fmt (/ m (* y d (float h))))))
18148 ;; standard (non-fractional) format, with single format string
18149 (if (stringp org-time-clocksum-format)
18150 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18151 ;; separate formats components
18152 (and (setq fmt (plist-get org-time-clocksum-format :years))
18153 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18154 (plist-get org-time-clocksum-format :require-years))
18155 (setq clocksum (concat clocksum (format fmt n))
18156 m (- m (* n y d h))))
18157 (and (setq fmt (plist-get org-time-clocksum-format :months))
18158 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18159 (plist-get org-time-clocksum-format :require-months))
18160 (setq clocksum (concat clocksum (format fmt n))
18161 m (- m (* n mo d h))))
18162 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18163 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18164 (plist-get org-time-clocksum-format :require-weeks))
18165 (setq clocksum (concat clocksum (format fmt n))
18166 m (- m (* n w d h))))
18167 (and (setq fmt (plist-get org-time-clocksum-format :days))
18168 (or (> (setq n (/ (truncate m) (* d h))) 0)
18169 (plist-get org-time-clocksum-format :require-days))
18170 (setq clocksum (concat clocksum (format fmt n))
18171 m (- m (* n d h))))
18172 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18173 (or (> (setq n (/ (truncate m) h)) 0)
18174 (plist-get org-time-clocksum-format :require-hours))
18175 (setq clocksum (concat clocksum (format fmt n))
18176 m (- m (* n h))))
18177 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18178 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18179 (setq clocksum (concat clocksum (format fmt m))))
18180 ;; return formatted time duration
18181 clocksum))))
18183 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18184 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18185 "Org mode version 8.0")
18187 (defun org-hours-to-clocksum-string (n)
18188 (org-minutes-to-clocksum-string (* n 60)))
18190 (defun org-hh:mm-string-to-minutes (s)
18191 "Convert a string H:MM to a number of minutes.
18192 If the string is just a number, interpret it as minutes.
18193 In fact, the first hh:mm or number in the string will be taken,
18194 there can be extra stuff in the string.
18195 If no number is found, the return value is 0."
18196 (cond
18197 ((integerp s) s)
18198 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18199 (+ (* (string-to-number (match-string 1 s)) 60)
18200 (string-to-number (match-string 2 s))))
18201 ((string-match "\\([0-9]+\\)" s)
18202 (string-to-number (match-string 1 s)))
18203 (t 0)))
18205 (defcustom org-image-actual-width t
18206 "Should we use the actual width of images when inlining them?
18208 When set to `t', always use the image width.
18210 When set to a number, use imagemagick (when available) to set
18211 the image's width to this value.
18213 When set to a number in a list, try to get the width from any
18214 #+ATTR.* keyword if it matches a width specification like
18216 #+ATTR_HTML: :width 300px
18218 and fall back on that number if none is found.
18220 When set to nil, try to get the width from an #+ATTR.* keyword
18221 and fall back on the original width if none is found.
18223 This requires Emacs >= 24.1, build with imagemagick support."
18224 :group 'org-appearance
18225 :version "24.4"
18226 :package-version '(Org . "8.0")
18227 :type '(choice
18228 (const :tag "Use the image width" t)
18229 (integer :tag "Use a number of pixels")
18230 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18231 (const :tag "Use #+ATTR* or don't resize" nil)))
18233 (defcustom org-agenda-inhibit-startup nil
18234 "Inhibit startup when preparing agenda buffers.
18235 When this variable is `t', the initialization of the Org agenda
18236 buffers is inhibited: e.g. the visibility state is not set, the
18237 tables are not re-aligned, etc."
18238 :type 'boolean
18239 :version "24.3"
18240 :group 'org-agenda)
18242 (define-obsolete-variable-alias
18243 'org-agenda-ignore-drawer-properties
18244 'org-agenda-ignore-properties "25.1")
18246 (defcustom org-agenda-ignore-properties nil
18247 "Avoid updating text properties when building the agenda.
18248 Properties are used to prepare buffers for effort estimates,
18249 appointments, statistics and subtree-local categories.
18250 If you don't use these in the agenda, you can add them to this
18251 list and agenda building will be a bit faster.
18252 The value is a list, with zero or more of the symbols `effort', `appt',
18253 `stats' or `category'."
18254 :type '(set :greedy t
18255 (const effort)
18256 (const appt)
18257 (const stats)
18258 (const category))
18259 :version "25.1"
18260 :package-version '(Org . "8.3")
18261 :group 'org-agenda)
18263 (defun org-duration-string-to-minutes (s &optional output-to-string)
18264 "Convert a duration string S to minutes.
18266 A bare number is interpreted as minutes, modifiers can be set by
18267 customizing `org-effort-durations' (which see).
18269 Entries containing a colon are interpreted as H:MM by
18270 `org-hh:mm-string-to-minutes'."
18271 (let ((result 0)
18272 (re (concat "\\([0-9.]+\\) *\\("
18273 (regexp-opt (mapcar 'car org-effort-durations))
18274 "\\)")))
18275 (while (string-match re s)
18276 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18277 (string-to-number (match-string 1 s))))
18278 (setq s (replace-match "" nil t s)))
18279 (setq result (floor result))
18280 (incf result (org-hh:mm-string-to-minutes s))
18281 (if output-to-string (number-to-string result) result)))
18283 ;;;; Files
18285 (defun org-save-all-org-buffers ()
18286 "Save all Org-mode buffers without user confirmation."
18287 (interactive)
18288 (message "Saving all Org-mode buffers...")
18289 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18290 (when (featurep 'org-id) (org-id-locations-save))
18291 (message "Saving all Org-mode buffers... done"))
18293 (defun org-revert-all-org-buffers ()
18294 "Revert all Org-mode buffers.
18295 Prompt for confirmation when there are unsaved changes.
18296 Be sure you know what you are doing before letting this function
18297 overwrite your changes.
18299 This function is useful in a setup where one tracks org files
18300 with a version control system, to revert on one machine after pulling
18301 changes from another. I believe the procedure must be like this:
18303 1. M-x org-save-all-org-buffers
18304 2. Pull changes from the other machine, resolve conflicts
18305 3. M-x org-revert-all-org-buffers"
18306 (interactive)
18307 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18308 (user-error "Abort"))
18309 (save-excursion
18310 (save-window-excursion
18311 (mapc
18312 (lambda (b)
18313 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18314 (with-current-buffer b buffer-file-name))
18315 (org-pop-to-buffer-same-window b)
18316 (revert-buffer t 'no-confirm)))
18317 (buffer-list))
18318 (when (and (featurep 'org-id) org-id-track-globally)
18319 (org-id-locations-load)))))
18321 ;;;; Agenda files
18323 ;;;###autoload
18324 (defun org-switchb (&optional arg)
18325 "Switch between Org buffers.
18326 With one prefix argument, restrict available buffers to files.
18327 With two prefix arguments, restrict available buffers to agenda files.
18329 Defaults to `iswitchb' for buffer name completion.
18330 Set `org-completion-use-ido' to make it use ido instead."
18331 (interactive "P")
18332 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18333 ((equal arg '(16)) (org-buffer-list 'agenda))
18334 (t (org-buffer-list))))
18335 (org-completion-use-iswitchb org-completion-use-iswitchb)
18336 (org-completion-use-ido org-completion-use-ido))
18337 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18338 (setq org-completion-use-iswitchb t))
18339 (org-pop-to-buffer-same-window
18340 (org-icompleting-read "Org buffer: "
18341 (mapcar 'list (mapcar 'buffer-name blist))
18342 nil t))))
18344 ;;; Define some older names previously used for this functionality
18345 ;;;###autoload
18346 (defalias 'org-ido-switchb 'org-switchb)
18347 ;;;###autoload
18348 (defalias 'org-iswitchb 'org-switchb)
18350 (defun org-buffer-list (&optional predicate exclude-tmp)
18351 "Return a list of Org buffers.
18352 PREDICATE can be `export', `files' or `agenda'.
18354 export restrict the list to Export buffers.
18355 files restrict the list to buffers visiting Org files.
18356 agenda restrict the list to buffers visiting agenda files.
18358 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18359 (let* ((bfn nil)
18360 (agenda-files (and (eq predicate 'agenda)
18361 (mapcar 'file-truename (org-agenda-files t))))
18362 (filter
18363 (cond
18364 ((eq predicate 'files)
18365 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18366 ((eq predicate 'export)
18367 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18368 ((eq predicate 'agenda)
18369 (lambda (b)
18370 (with-current-buffer b
18371 (and (derived-mode-p 'org-mode)
18372 (setq bfn (buffer-file-name b))
18373 (member (file-truename bfn) agenda-files)))))
18374 (t (lambda (b) (with-current-buffer b
18375 (or (derived-mode-p 'org-mode)
18376 (string-match "\*Org .*Export"
18377 (buffer-name b)))))))))
18378 (delq nil
18379 (mapcar
18380 (lambda(b)
18381 (if (and (funcall filter b)
18382 (or (not exclude-tmp)
18383 (not (string-match "tmp" (buffer-name b)))))
18385 nil))
18386 (buffer-list)))))
18388 (defun org-agenda-files (&optional unrestricted archives)
18389 "Get the list of agenda files.
18390 Optional UNRESTRICTED means return the full list even if a restriction
18391 is currently in place.
18392 When ARCHIVES is t, include all archive files that are really being
18393 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18394 `org-agenda-archives-mode' is t."
18395 (let ((files
18396 (cond
18397 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18398 ((stringp org-agenda-files) (org-read-agenda-file-list))
18399 ((listp org-agenda-files) org-agenda-files)
18400 (t (error "Invalid value of `org-agenda-files'")))))
18401 (setq files (apply 'append
18402 (mapcar (lambda (f)
18403 (if (file-directory-p f)
18404 (directory-files
18405 f t org-agenda-file-regexp)
18406 (list f)))
18407 files)))
18408 (when org-agenda-skip-unavailable-files
18409 (setq files (delq nil
18410 (mapcar (function
18411 (lambda (file)
18412 (and (file-readable-p file) file)))
18413 files))))
18414 (when (or (eq archives t)
18415 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18416 (setq files (org-add-archive-files files)))
18417 files))
18419 (defun org-agenda-file-p (&optional file)
18420 "Return non-nil, if FILE is an agenda file.
18421 If FILE is omitted, use the file associated with the current
18422 buffer."
18423 (let ((fname (or file (buffer-file-name))))
18424 (and fname
18425 (member (file-truename fname)
18426 (mapcar #'file-truename (org-agenda-files t))))))
18428 (defun org-edit-agenda-file-list ()
18429 "Edit the list of agenda files.
18430 Depending on setup, this either uses customize to edit the variable
18431 `org-agenda-files', or it visits the file that is holding the list. In the
18432 latter case, the buffer is set up in a way that saving it automatically kills
18433 the buffer and restores the previous window configuration."
18434 (interactive)
18435 (if (stringp org-agenda-files)
18436 (let ((cw (current-window-configuration)))
18437 (find-file org-agenda-files)
18438 (org-set-local 'org-window-configuration cw)
18439 (org-add-hook 'after-save-hook
18440 (lambda ()
18441 (set-window-configuration
18442 (prog1 org-window-configuration
18443 (kill-buffer (current-buffer))))
18444 (org-install-agenda-files-menu)
18445 (message "New agenda file list installed"))
18446 nil 'local)
18447 (message "%s" (substitute-command-keys
18448 "Edit list and finish with \\[save-buffer]")))
18449 (customize-variable 'org-agenda-files)))
18451 (defun org-store-new-agenda-file-list (list)
18452 "Set new value for the agenda file list and save it correctly."
18453 (if (stringp org-agenda-files)
18454 (let ((fe (org-read-agenda-file-list t)) b u)
18455 (while (setq b (find-buffer-visiting org-agenda-files))
18456 (kill-buffer b))
18457 (with-temp-file org-agenda-files
18458 (insert
18459 (mapconcat
18460 (lambda (f) ;; Keep un-expanded entries.
18461 (if (setq u (assoc f fe))
18462 (cdr u)
18464 list "\n")
18465 "\n")))
18466 (let ((org-mode-hook nil) (org-inhibit-startup t)
18467 (org-insert-mode-line-in-empty-file nil))
18468 (setq org-agenda-files list)
18469 (customize-save-variable 'org-agenda-files org-agenda-files))))
18471 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18472 "Read the list of agenda files from a file.
18473 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18474 filenames, used by `org-store-new-agenda-file-list' to write back
18475 un-expanded file names."
18476 (when (file-directory-p org-agenda-files)
18477 (error "`org-agenda-files' cannot be a single directory"))
18478 (when (stringp org-agenda-files)
18479 (with-temp-buffer
18480 (insert-file-contents org-agenda-files)
18481 (mapcar
18482 (lambda (f)
18483 (let ((e (expand-file-name (substitute-in-file-name f)
18484 org-directory)))
18485 (if pair-with-expansion
18486 (cons e f)
18487 e)))
18488 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18490 ;;;###autoload
18491 (defun org-cycle-agenda-files ()
18492 "Cycle through the files in `org-agenda-files'.
18493 If the current buffer visits an agenda file, find the next one in the list.
18494 If the current buffer does not, find the first agenda file."
18495 (interactive)
18496 (let* ((fs (org-agenda-files t))
18497 (files (append fs (list (car fs))))
18498 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18499 file)
18500 (unless files (user-error "No agenda files"))
18501 (catch 'exit
18502 (while (setq file (pop files))
18503 (if (equal (file-truename file) tcf)
18504 (when (car files)
18505 (find-file (car files))
18506 (throw 'exit t))))
18507 (find-file (car fs)))
18508 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18510 (defun org-agenda-file-to-front (&optional to-end)
18511 "Move/add the current file to the top of the agenda file list.
18512 If the file is not present in the list, it is added to the front. If it is
18513 present, it is moved there. With optional argument TO-END, add/move to the
18514 end of the list."
18515 (interactive "P")
18516 (let ((org-agenda-skip-unavailable-files nil)
18517 (file-alist (mapcar (lambda (x)
18518 (cons (file-truename x) x))
18519 (org-agenda-files t)))
18520 (ctf (file-truename
18521 (or buffer-file-name
18522 (user-error "Please save the current buffer to a file"))))
18523 x had)
18524 (setq x (assoc ctf file-alist) had x)
18526 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18527 (if to-end
18528 (setq file-alist (append (delq x file-alist) (list x)))
18529 (setq file-alist (cons x (delq x file-alist))))
18530 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18531 (org-install-agenda-files-menu)
18532 (message "File %s to %s of agenda file list"
18533 (if had "moved" "added") (if to-end "end" "front"))))
18535 (defun org-remove-file (&optional file)
18536 "Remove current file from the list of files in variable `org-agenda-files'.
18537 These are the files which are being checked for agenda entries.
18538 Optional argument FILE means use this file instead of the current."
18539 (interactive)
18540 (let* ((org-agenda-skip-unavailable-files nil)
18541 (file (or file buffer-file-name
18542 (user-error "Current buffer does not visit a file")))
18543 (true-file (file-truename file))
18544 (afile (abbreviate-file-name file))
18545 (files (delq nil (mapcar
18546 (lambda (x)
18547 (if (equal true-file
18548 (file-truename x))
18549 nil x))
18550 (org-agenda-files t)))))
18551 (if (not (= (length files) (length (org-agenda-files t))))
18552 (progn
18553 (org-store-new-agenda-file-list files)
18554 (org-install-agenda-files-menu)
18555 (message "Removed from Org Agenda list: %s" afile))
18556 (message "File was not in list: %s (not removed)" afile))))
18558 (defun org-file-menu-entry (file)
18559 (vector file (list 'find-file file) t))
18561 (defun org-check-agenda-file (file)
18562 "Make sure FILE exists. If not, ask user what to do."
18563 (when (not (file-exists-p file))
18564 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18565 (abbreviate-file-name file))
18566 (let ((r (downcase (read-char-exclusive))))
18567 (cond
18568 ((equal r ?r)
18569 (org-remove-file file)
18570 (throw 'nextfile t))
18571 (t (user-error "Abort"))))))
18573 (defun org-get-agenda-file-buffer (file)
18574 "Get an agenda buffer visiting FILE.
18575 If the buffer needs to be created, add it to the list of buffers
18576 which might be released later."
18577 (let ((buf (org-find-base-buffer-visiting file)))
18578 (if buf
18579 buf ; just return it
18580 ;; Make a new buffer and remember it
18581 (setq buf (find-file-noselect file))
18582 (if buf (push buf org-agenda-new-buffers))
18583 buf)))
18585 (defun org-release-buffers (blist)
18586 "Release all buffers in list, asking the user for confirmation when needed.
18587 When a buffer is unmodified, it is just killed. When modified, it is saved
18588 \(if the user agrees) and then killed."
18589 (let (buf file)
18590 (while (setq buf (pop blist))
18591 (setq file (buffer-file-name buf))
18592 (when (and (buffer-modified-p buf)
18593 file
18594 (y-or-n-p (format "Save file %s? " file)))
18595 (with-current-buffer buf (save-buffer)))
18596 (kill-buffer buf))))
18598 (defun org-agenda-prepare-buffers (files)
18599 "Create buffers for all agenda files, protect archived trees and comments."
18600 (interactive)
18601 (let ((pa '(:org-archived t))
18602 (pc '(:org-comment t))
18603 (pall '(:org-archived t :org-comment t))
18604 (inhibit-read-only t)
18605 (org-inhibit-startup org-agenda-inhibit-startup)
18606 (rea (concat ":" org-archive-tag ":"))
18607 file re pos)
18608 (setq org-tag-alist-for-agenda nil
18609 org-tag-groups-alist-for-agenda nil)
18610 (save-excursion
18611 (save-restriction
18612 (while (setq file (pop files))
18613 (catch 'nextfile
18614 (if (bufferp file)
18615 (set-buffer file)
18616 (org-check-agenda-file file)
18617 (set-buffer (org-get-agenda-file-buffer file)))
18618 (widen)
18619 (org-set-regexps-and-options 'tags-only)
18620 (setq pos (point))
18621 (or (memq 'category org-agenda-ignore-properties)
18622 (org-refresh-category-properties))
18623 (or (memq 'stats org-agenda-ignore-properties)
18624 (org-refresh-stats-properties))
18625 (or (memq 'effort org-agenda-ignore-properties)
18626 (org-refresh-effort-properties))
18627 (or (memq 'appt org-agenda-ignore-properties)
18628 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18629 (setq org-todo-keywords-for-agenda
18630 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18631 (setq org-done-keywords-for-agenda
18632 (append org-done-keywords-for-agenda org-done-keywords))
18633 (setq org-todo-keyword-alist-for-agenda
18634 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18635 (setq org-tag-alist-for-agenda
18636 (org-uniquify
18637 (append org-tag-alist-for-agenda
18638 org-tag-alist
18639 org-tag-persistent-alist)))
18640 (if org-group-tags
18641 (setq org-tag-groups-alist-for-agenda
18642 (org-uniquify-alist
18643 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18644 (org-with-silent-modifications
18645 (save-excursion
18646 (remove-text-properties (point-min) (point-max) pall)
18647 (when org-agenda-skip-archived-trees
18648 (goto-char (point-min))
18649 (while (re-search-forward rea nil t)
18650 (if (org-at-heading-p t)
18651 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18652 (goto-char (point-min))
18653 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18654 (while (re-search-forward re nil t)
18655 (when (save-match-data (org-in-commented-heading-p t))
18656 (add-text-properties
18657 (match-beginning 0) (org-end-of-subtree t) pc)))))
18658 (goto-char pos)))))
18659 (setq org-todo-keywords-for-agenda
18660 (org-uniquify org-todo-keywords-for-agenda))
18661 (setq org-todo-keyword-alist-for-agenda
18662 (org-uniquify org-todo-keyword-alist-for-agenda))))
18665 ;;;; CDLaTeX minor mode
18667 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18668 "Keymap for the minor `org-cdlatex-mode'.")
18670 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18671 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18672 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18673 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18674 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18676 (defvar org-cdlatex-texmathp-advice-is-done nil
18677 "Flag remembering if we have applied the advice to texmathp already.")
18679 (define-minor-mode org-cdlatex-mode
18680 "Toggle the minor `org-cdlatex-mode'.
18681 This mode supports entering LaTeX environment and math in LaTeX fragments
18682 in Org-mode.
18683 \\{org-cdlatex-mode-map}"
18684 nil " OCDL" nil
18685 (when org-cdlatex-mode
18686 (require 'cdlatex)
18687 (run-hooks 'cdlatex-mode-hook)
18688 (cdlatex-compute-tables))
18689 (unless org-cdlatex-texmathp-advice-is-done
18690 (setq org-cdlatex-texmathp-advice-is-done t)
18691 (defadvice texmathp (around org-math-always-on activate)
18692 "Always return t in org-mode buffers.
18693 This is because we want to insert math symbols without dollars even outside
18694 the LaTeX math segments. If Orgmode thinks that point is actually inside
18695 an embedded LaTeX fragment, let texmathp do its job.
18696 \\[org-cdlatex-mode-map]"
18697 (interactive)
18698 (let (p)
18699 (cond
18700 ((not (derived-mode-p 'org-mode)) ad-do-it)
18701 ((eq this-command 'cdlatex-math-symbol)
18702 (setq ad-return-value t
18703 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18705 (let ((p (org-inside-LaTeX-fragment-p)))
18706 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18707 (setq ad-return-value t
18708 texmathp-why '("Org-mode embedded math" . 0))
18709 (if p ad-do-it)))))))))
18711 (defun turn-on-org-cdlatex ()
18712 "Unconditionally turn on `org-cdlatex-mode'."
18713 (org-cdlatex-mode 1))
18715 (defun org-try-cdlatex-tab ()
18716 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18717 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18718 - inside a LaTeX fragment, or
18719 - after the first word in a line, where an abbreviation expansion could
18720 insert a LaTeX environment."
18721 (when org-cdlatex-mode
18722 (cond
18723 ;; Before any word on the line: No expansion possible.
18724 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18725 ;; Just after first word on the line: Expand it. Make sure it
18726 ;; cannot happen on headlines, though.
18727 ((save-excursion
18728 (skip-chars-backward "a-zA-Z0-9*")
18729 (skip-chars-backward " \t")
18730 (and (bolp) (not (org-at-heading-p))))
18731 (cdlatex-tab) t)
18732 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18734 (defun org-cdlatex-underscore-caret (&optional arg)
18735 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18736 Revert to the normal definition outside of these fragments."
18737 (interactive "P")
18738 (if (org-inside-LaTeX-fragment-p)
18739 (call-interactively 'cdlatex-sub-superscript)
18740 (let (org-cdlatex-mode)
18741 (call-interactively (key-binding (vector last-input-event))))))
18743 (defun org-cdlatex-math-modify (&optional arg)
18744 "Execute `cdlatex-math-modify' in LaTeX fragments.
18745 Revert to the normal definition outside of these fragments."
18746 (interactive "P")
18747 (if (org-inside-LaTeX-fragment-p)
18748 (call-interactively 'cdlatex-math-modify)
18749 (let (org-cdlatex-mode)
18750 (call-interactively (key-binding (vector last-input-event))))))
18752 (defun org-cdlatex-environment-indent (&optional environment item)
18753 "Execute `cdlatex-environment' and indent the inserted environment.
18755 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18757 The inserted environment is indented to current indentation
18758 unless point is at the beginning of the line, in which the
18759 environment remains unintended."
18760 (interactive)
18761 ;; cdlatex-environment always return nil. Therefore, capture output
18762 ;; first and determine if an environment was selected.
18763 (let* ((beg (point-marker))
18764 (end (copy-marker (point) t))
18765 (inserted (progn
18766 (ignore-errors (cdlatex-environment environment item))
18767 (< beg end)))
18768 ;; Figure out how many lines to move forward after the
18769 ;; environment has been inserted.
18770 (lines (when inserted
18771 (save-excursion
18772 (- (loop while (< beg (point))
18773 with x = 0
18774 do (forward-line -1)
18775 (incf x)
18776 finally return x)
18777 (if (progn (goto-char beg)
18778 (and (progn (skip-chars-forward " \t") (eolp))
18779 (progn (skip-chars-backward " \t") (bolp))))
18780 1 0)))))
18781 (env (org-trim (delete-and-extract-region beg end))))
18782 (when inserted
18783 ;; Get indentation of next line unless at column 0.
18784 (let ((ind (if (bolp) 0
18785 (save-excursion
18786 (org-return-indent)
18787 (prog1 (org-get-indentation)
18788 (when (progn (skip-chars-forward " \t") (eolp))
18789 (delete-region beg (point)))))))
18790 (bol (progn (skip-chars-backward " \t") (bolp))))
18791 ;; Insert a newline before environment unless at column zero
18792 ;; to "escape" the current line. Insert a newline if
18793 ;; something is one the same line as \end{ENVIRONMENT}.
18794 (insert
18795 (concat (unless bol "\n") env
18796 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18797 (unless (zerop ind)
18798 (save-excursion
18799 (goto-char beg)
18800 (while (< (point) end)
18801 (unless (eolp) (org-indent-line-to ind))
18802 (forward-line))))
18803 (goto-char beg)
18804 (forward-line lines)
18805 (org-indent-line-to ind)))
18806 (set-marker beg nil)
18807 (set-marker end nil)))
18810 ;;;; LaTeX fragments
18812 (defun org-inside-LaTeX-fragment-p ()
18813 "Test if point is inside a LaTeX fragment.
18814 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18815 sequence appearing also before point.
18816 Even though the matchers for math are configurable, this function assumes
18817 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18818 delimiters are skipped when they have been removed by customization.
18819 The return value is nil, or a cons cell with the delimiter and the
18820 position of this delimiter.
18822 This function does a reasonably good job, but can locally be fooled by
18823 for example currency specifications. For example it will assume being in
18824 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18825 fragments that are properly closed, but during editing, we have to live
18826 with the uncertainty caused by missing closing delimiters. This function
18827 looks only before point, not after."
18828 (catch 'exit
18829 (let ((pos (point))
18830 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18831 (lim (progn
18832 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18833 (point)))
18834 dd-on str (start 0) m re)
18835 (goto-char pos)
18836 (when dodollar
18837 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18838 re (nth 1 (assoc "$" org-latex-regexps)))
18839 (while (string-match re str start)
18840 (cond
18841 ((= (match-end 0) (length str))
18842 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18843 ((= (match-end 0) (- (length str) 5))
18844 (throw 'exit nil))
18845 (t (setq start (match-end 0))))))
18846 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18847 (goto-char pos)
18848 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18849 (and (match-beginning 2) (throw 'exit nil))
18850 ;; count $$
18851 (while (re-search-backward "\\$\\$" lim t)
18852 (setq dd-on (not dd-on)))
18853 (goto-char pos)
18854 (if dd-on (cons "$$" m))))))
18856 (defun org-inside-latex-macro-p ()
18857 "Is point inside a LaTeX macro or its arguments?"
18858 (save-match-data
18859 (org-in-regexp
18860 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18862 (defvar org-latex-fragment-image-overlays nil
18863 "List of overlays carrying the images of latex fragments.")
18864 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18866 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18867 "Remove all overlays with LaTeX fragment images in current buffer.
18868 When optional arguments BEG and END are non-nil, remove all
18869 overlays between them instead. Return t when some overlays were
18870 removed, nil otherwise."
18871 (let (removedp)
18872 (setq org-latex-fragment-image-overlays
18873 (let ((beg (or beg (point-min)))
18874 (end (or end (point-max))))
18875 (org-remove-if
18876 (lambda (o)
18877 (and (>= (overlay-start o) beg)
18878 (<= (overlay-end o) end)
18879 (progn (delete-overlay o)
18880 (or removedp (setq removedp t)))))
18881 org-latex-fragment-image-overlays)))
18882 removedp))
18884 (define-obsolete-function-alias
18885 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18886 (defun org-toggle-latex-fragment (&optional arg)
18887 "Preview the LaTeX fragment at point, or all locally or globally.
18889 If the cursor is on a LaTeX fragment, create the image and overlay
18890 it over the source code, if there is none. Remove it otherwise.
18891 If there is no fragment at point, display all fragments in the
18892 current section.
18894 With prefix ARG, preview or clear image for all fragments in the
18895 current subtree or in the whole buffer when used before the first
18896 headline. With a double prefix ARG \\[universal-argument] \
18897 \\[universal-argument] preview or clear images
18898 for all fragments in the buffer."
18899 (interactive "P")
18900 (unless (buffer-file-name (buffer-base-buffer))
18901 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18902 (when (display-graphic-p)
18903 (catch 'exit
18904 (save-excursion
18905 (let ((window-start (window-start)) msg)
18906 (save-restriction
18907 (cond
18908 ((or (equal arg '(16))
18909 (and (equal arg '(4))
18910 (org-with-limited-levels (org-before-first-heading-p))))
18911 (if (org-remove-latex-fragment-image-overlays)
18912 (progn (message "LaTeX fragments images removed from buffer")
18913 (throw 'exit nil))
18914 (setq msg "Creating images for buffer...")))
18915 ((equal arg '(4))
18916 (org-with-limited-levels (org-back-to-heading t))
18917 (let ((beg (point))
18918 (end (progn (org-end-of-subtree t) (point))))
18919 (if (org-remove-latex-fragment-image-overlays beg end)
18920 (progn
18921 (message "LaTeX fragment images removed from subtree")
18922 (throw 'exit nil))
18923 (setq msg "Creating images for subtree...")
18924 (narrow-to-region beg end))))
18925 ((let ((datum (org-element-context)))
18926 (when (memq (org-element-type datum)
18927 '(latex-environment latex-fragment))
18928 (let* ((beg (org-element-property :begin datum))
18929 (end (org-element-property :end datum)))
18930 (if (org-remove-latex-fragment-image-overlays beg end)
18931 (progn (message "LaTeX fragment image removed")
18932 (throw 'exit nil))
18933 (narrow-to-region beg end)
18934 (setq msg "Creating image..."))))))
18936 (org-with-limited-levels
18937 (let ((beg (if (org-at-heading-p) (line-beginning-position)
18938 (outline-previous-heading)
18939 (point)))
18940 (end (progn (outline-next-heading) (point))))
18941 (if (org-remove-latex-fragment-image-overlays beg end)
18942 (progn
18943 (message "LaTeX fragment images removed from section")
18944 (throw 'exit nil))
18945 (setq msg "Creating images for section...")
18946 (narrow-to-region beg end))))))
18947 (let ((file (buffer-file-name (buffer-base-buffer))))
18948 (org-format-latex
18949 (concat org-latex-preview-ltxpng-directory
18950 (file-name-sans-extension (file-name-nondirectory file)))
18951 ;; Emacs cannot overlay images from remote hosts.
18952 ;; Create it in `temporary-file-directory' instead.
18953 (if (file-remote-p file) temporary-file-directory
18954 default-directory)
18955 'overlays msg 'forbuffer
18956 org-latex-create-formula-image-program)))
18957 ;; Work around a bug that doesn't restore window's start
18958 ;; when widening back the buffer.
18959 (set-window-start nil window-start)
18960 (message (concat msg "done")))))))
18962 (defun org-format-latex
18963 (prefix &optional dir overlays msg forbuffer processing-type)
18964 "Replace LaTeX fragments with links to an image, and produce images.
18966 When optional argument OVERLAYS is non-nil, display the image on
18967 top of the fragment instead of replacing it.
18969 PROCESSING-TYPE is the conversion method to use, as a symbol.
18971 Some of the options can be changed using the variable
18972 `org-format-latex-options', which see."
18973 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18974 (unless (eq processing-type 'verbatim)
18975 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18976 (cnt 0)
18977 checkdir-flag)
18978 (goto-char (point-min))
18979 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18980 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18981 (overlay-recenter (point-max)))
18982 (while (re-search-forward math-regexp nil t)
18983 (unless (and overlays
18984 (eq (get-char-property (point) 'org-overlay-type)
18985 'org-latex-overlay))
18986 (let* ((context (org-element-context))
18987 (type (org-element-type context)))
18988 (when (memq type '(latex-environment latex-fragment))
18989 (let ((block-type (eq type 'latex-environment))
18990 (value (org-element-property :value context))
18991 (beg (org-element-property :begin context))
18992 (end (save-excursion
18993 (goto-char (org-element-property :end context))
18994 (skip-chars-backward " \r\t\n")
18995 (point))))
18996 (case processing-type
18997 (mathjax
18998 ;; Prepare for MathJax processing.
18999 (if (eq (char-after beg) ?$)
19000 (save-excursion
19001 (delete-region beg end)
19002 (insert "\\(" (substring value 1 -1) "\\)"))
19003 (goto-char end)))
19004 ((dvipng imagemagick)
19005 ;; Process to an image.
19006 (incf cnt)
19007 (goto-char beg)
19008 (let* ((face (face-at-point))
19009 ;; Get the colors from the face at point.
19011 (let ((color (plist-get org-format-latex-options
19012 :foreground)))
19013 (if (and forbuffer (eq color 'auto))
19014 (face-attribute face :foreground nil 'default)
19015 color)))
19017 (let ((color (plist-get org-format-latex-options
19018 :background)))
19019 (if (and forbuffer (eq color 'auto))
19020 (face-attribute face :background nil 'default)
19021 color)))
19022 (hash (sha1 (prin1-to-string
19023 (list org-format-latex-header
19024 org-latex-default-packages-alist
19025 org-latex-packages-alist
19026 org-format-latex-options
19027 forbuffer value fg bg))))
19028 (absprefix (expand-file-name prefix dir))
19029 (linkfile (format "%s_%s.png" prefix hash))
19030 (movefile (format "%s_%s.png" absprefix hash))
19031 (sep (and block-type "\n\n"))
19032 (link (concat sep "[[file:" linkfile "]]" sep))
19033 (options
19034 (org-combine-plists
19035 org-format-latex-options
19036 `(:foreground ,fg :background ,bg))))
19037 (when msg (message msg cnt))
19038 (unless checkdir-flag ; Ensure the directory exists.
19039 (setq checkdir-flag t)
19040 (let ((todir (file-name-directory absprefix)))
19041 (unless (file-directory-p todir)
19042 (make-directory todir t))))
19043 (unless (file-exists-p movefile)
19044 (org-create-formula-image
19045 value movefile options forbuffer processing-type))
19046 (if overlays
19047 (progn
19048 (dolist (o (overlays-in beg end))
19049 (when (eq (overlay-get o 'org-overlay-type)
19050 'org-latex-overlay)
19051 (delete-overlay o)))
19052 (let ((ov (make-overlay beg end)))
19053 (overlay-put ov
19054 'org-overlay-type
19055 'org-latex-overlay)
19056 (overlay-put ov 'evaporate t)
19057 (if (featurep 'xemacs)
19058 (progn
19059 (overlay-put ov 'invisible t)
19060 (overlay-put
19061 ov 'end-glyph
19062 (make-glyph
19063 (vector 'png :file movefile))))
19064 (overlay-put
19065 ov 'display
19066 (list 'image
19067 :type 'png
19068 :file movefile
19069 :ascent 'center)))
19070 (push ov org-latex-fragment-image-overlays))
19071 (goto-char end))
19072 (delete-region beg end)
19073 (insert
19074 (org-add-props link
19075 (list 'org-latex-src
19076 (replace-regexp-in-string "\"" "" value)
19077 'org-latex-src-embed-type
19078 (if block-type 'paragraph 'character)))))))
19079 (mathml
19080 ;; Process to MathML.
19081 (unless (org-format-latex-mathml-available-p)
19082 (user-error "LaTeX to MathML converter not configured"))
19083 (incf cnt)
19084 (when msg (message msg cnt))
19085 (goto-char beg)
19086 (delete-region beg end)
19087 (insert (org-format-latex-as-mathml
19088 value block-type prefix dir)))
19089 (otherwise
19090 (error "Unknown conversion type %s for LaTeX fragments"
19091 processing-type)))))))))))
19093 (defun org-create-math-formula (latex-frag &optional mathml-file)
19094 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19095 Use `org-latex-to-mathml-convert-command'. If the conversion is
19096 sucessful, return the portion between \"<math...> </math>\"
19097 elements otherwise return nil. When MATHML-FILE is specified,
19098 write the results in to that file. When invoked as an
19099 interactive command, prompt for LATEX-FRAG, with initial value
19100 set to the current active region and echo the results for user
19101 inspection."
19102 (interactive (list (let ((frag (when (org-region-active-p)
19103 (buffer-substring-no-properties
19104 (region-beginning) (region-end)))))
19105 (read-string "LaTeX Fragment: " frag nil frag))))
19106 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19107 (let* ((tmp-in-file (file-relative-name
19108 (make-temp-name (expand-file-name "ltxmathml-in"))))
19109 (ignore (write-region latex-frag nil tmp-in-file))
19110 (tmp-out-file (file-relative-name
19111 (make-temp-name (expand-file-name "ltxmathml-out"))))
19112 (cmd (format-spec
19113 org-latex-to-mathml-convert-command
19114 `((?j . ,(and org-latex-to-mathml-jar-file
19115 (shell-quote-argument
19116 (expand-file-name
19117 org-latex-to-mathml-jar-file))))
19118 (?I . ,(shell-quote-argument tmp-in-file))
19119 (?i . ,latex-frag)
19120 (?o . ,(shell-quote-argument tmp-out-file)))))
19121 mathml shell-command-output)
19122 (when (org-called-interactively-p 'any)
19123 (unless (org-format-latex-mathml-available-p)
19124 (user-error "LaTeX to MathML converter not configured")))
19125 (message "Running %s" cmd)
19126 (setq shell-command-output (shell-command-to-string cmd))
19127 (setq mathml
19128 (when (file-readable-p tmp-out-file)
19129 (with-current-buffer (find-file-noselect tmp-out-file t)
19130 (goto-char (point-min))
19131 (when (re-search-forward
19132 (concat
19133 (regexp-quote
19134 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19135 "[^>]*?>"
19136 "\\(.\\|\n\\)*"
19137 "</math>")
19138 nil t)
19139 (prog1 (match-string 0) (kill-buffer))))))
19140 (cond
19141 (mathml
19142 (setq mathml
19143 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19144 (when mathml-file
19145 (write-region mathml nil mathml-file))
19146 (when (org-called-interactively-p 'any)
19147 (message mathml)))
19148 ((message "LaTeX to MathML conversion failed")
19149 (message shell-command-output)))
19150 (delete-file tmp-in-file)
19151 (when (file-exists-p tmp-out-file)
19152 (delete-file tmp-out-file))
19153 mathml))
19155 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19156 prefix &optional dir)
19157 "Use `org-create-math-formula' but check local cache first."
19158 (let* ((absprefix (expand-file-name prefix dir))
19159 (print-length nil) (print-level nil)
19160 (formula-id (concat
19161 "formula-"
19162 (sha1
19163 (prin1-to-string
19164 (list latex-frag
19165 org-latex-to-mathml-convert-command)))))
19166 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19167 (formula-cache-dir (file-name-directory formula-cache)))
19169 (unless (file-directory-p formula-cache-dir)
19170 (make-directory formula-cache-dir t))
19172 (unless (file-exists-p formula-cache)
19173 (org-create-math-formula latex-frag formula-cache))
19175 (if (file-exists-p formula-cache)
19176 ;; Successful conversion. Return the link to MathML file.
19177 (org-add-props
19178 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19179 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19180 'org-latex-src-embed-type (if latex-frag-type
19181 'paragraph 'character)))
19182 ;; Failed conversion. Return the LaTeX fragment verbatim
19183 latex-frag)))
19185 (defun org-create-formula-image (string tofile options buffer &optional type)
19186 "Create an image from LaTeX source using dvipng or convert.
19187 This function calls either `org-create-formula-image-with-dvipng'
19188 or `org-create-formula-image-with-imagemagick' depending on the
19189 value of `org-latex-create-formula-image-program' or on the value
19190 of the optional TYPE variable.
19192 Note: ultimately these two function should be combined as they
19193 share a good deal of logic."
19194 (org-check-external-command
19195 "latex" "needed to convert LaTeX fragments to images")
19196 (funcall
19197 (case (or type org-latex-create-formula-image-program)
19198 (dvipng
19199 (org-check-external-command
19200 "dvipng" "needed to convert LaTeX fragments to images")
19201 #'org-create-formula-image-with-dvipng)
19202 (imagemagick
19203 (org-check-external-command
19204 "convert" "you need to install imagemagick")
19205 #'org-create-formula-image-with-imagemagick)
19206 (t (error
19207 "Invalid value of `org-latex-create-formula-image-program'")))
19208 string tofile options buffer))
19210 (declare-function org-export-get-backend "ox" (name))
19211 (declare-function org-export--get-global-options "ox" (&optional backend))
19212 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19213 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19214 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19215 (defun org-create-formula--latex-header ()
19216 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19217 (let ((info (org-combine-plists (org-export--get-global-options
19218 (org-export-get-backend 'latex))
19219 (org-export--get-inbuffer-options
19220 (org-export-get-backend 'latex)))))
19221 (org-latex-guess-babel-language
19222 (org-latex-guess-inputenc
19223 (org-splice-latex-header
19224 org-format-latex-header
19225 org-latex-default-packages-alist
19226 org-latex-packages-alist t
19227 (plist-get info :latex-header)))
19228 info)))
19230 (defun org--get-display-dpi ()
19231 "Get the DPI of the display.
19233 Assumes that the display has the same pixel width in the
19234 horizontal and vertical directions."
19235 (if (display-graphic-p)
19236 (round (/ (display-pixel-height)
19237 (/ (display-mm-height) 25.4)))
19238 (error "Attempt to calculate the dpi of a non-graphic display")))
19240 ;; This function borrows from Ganesh Swami's latex2png.el
19241 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19242 "This calls dvipng."
19243 (require 'ox-latex)
19244 (let* ((tmpdir (if (featurep 'xemacs)
19245 (temp-directory)
19246 temporary-file-directory))
19247 (texfilebase (make-temp-name
19248 (expand-file-name "orgtex" tmpdir)))
19249 (texfile (concat texfilebase ".tex"))
19250 (dvifile (concat texfilebase ".dvi"))
19251 (pngfile (concat texfilebase ".png"))
19252 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19253 ;; This assumes that the display has the same pixel width in
19254 ;; the horizontal and vertical directions
19255 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19256 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19257 "Black"))
19258 (bg (or (plist-get options (if buffer :background :html-background))
19259 "Transparent")))
19260 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19261 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19262 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19263 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19264 (let ((latex-header (org-create-formula--latex-header)))
19265 (with-temp-file texfile
19266 (insert latex-header)
19267 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19268 (let ((dir default-directory))
19269 (ignore-errors
19270 (cd tmpdir)
19271 (call-process "latex" nil nil nil texfile))
19272 (cd dir))
19273 (if (not (file-exists-p dvifile))
19274 (progn (message "Failed to create dvi file from %s" texfile) nil)
19275 (ignore-errors
19276 (if (featurep 'xemacs)
19277 (call-process "dvipng" nil nil nil
19278 "-fg" fg "-bg" bg
19279 "-T" "tight"
19280 "-o" pngfile
19281 dvifile)
19282 (call-process "dvipng" nil nil nil
19283 "-fg" fg "-bg" bg
19284 "-D" dpi
19285 ;;"-x" scale "-y" scale
19286 "-T" "tight"
19287 "-o" pngfile
19288 dvifile)))
19289 (if (not (file-exists-p pngfile))
19290 (if org-format-latex-signal-error
19291 (error "Failed to create png file from %s" texfile)
19292 (message "Failed to create png file from %s" texfile)
19293 nil)
19294 ;; Use the requested file name and clean up
19295 (copy-file pngfile tofile 'replace)
19296 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19297 (if (file-exists-p (concat texfilebase e))
19298 (delete-file (concat texfilebase e))))
19299 pngfile))))
19301 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19302 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19303 "This calls convert, which is included into imagemagick."
19304 (require 'ox-latex)
19305 (let* ((tmpdir (if (featurep 'xemacs)
19306 (temp-directory)
19307 temporary-file-directory))
19308 (texfilebase (make-temp-name
19309 (expand-file-name "orgtex" tmpdir)))
19310 (texfile (concat texfilebase ".tex"))
19311 (pdffile (concat texfilebase ".pdf"))
19312 (pngfile (concat texfilebase ".png"))
19313 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19314 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19315 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19316 "black"))
19317 (bg (or (plist-get options (if buffer :background :html-background))
19318 "white")))
19319 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19320 (setq fg (org-latex-color-format fg)))
19321 (if (eq bg 'default) (setq bg (org-latex-color :background))
19322 (setq bg (org-latex-color-format
19323 (if (string= bg "Transparent") "white" bg))))
19324 (let ((latex-header (org-create-formula--latex-header)))
19325 (with-temp-file texfile
19326 (insert latex-header)
19327 (insert "\n\\begin{document}\n"
19328 "\\definecolor{fg}{rgb}{" fg "}\n"
19329 "\\definecolor{bg}{rgb}{" bg "}\n"
19330 "\n\\pagecolor{bg}\n"
19331 "\n{\\color{fg}\n"
19332 string
19333 "\n}\n"
19334 "\n\\end{document}\n")))
19335 (org-latex-compile texfile t)
19336 (if (not (file-exists-p pdffile))
19337 (progn (message "Failed to create pdf file from %s" texfile) nil)
19338 (ignore-errors
19339 (if (featurep 'xemacs)
19340 (call-process "convert" nil nil nil
19341 "-density" "96"
19342 "-trim"
19343 "-antialias"
19344 pdffile
19345 "-quality" "100"
19346 ;; "-sharpen" "0x1.0"
19347 pngfile)
19348 (call-process "convert" nil nil nil
19349 "-density" dpi
19350 "-trim"
19351 "-antialias"
19352 pdffile
19353 "-quality" "100"
19354 ;; "-sharpen" "0x1.0"
19355 pngfile)))
19356 (if (not (file-exists-p pngfile))
19357 (if org-format-latex-signal-error
19358 (error "Failed to create png file from %s" texfile)
19359 (message "Failed to create png file from %s" texfile)
19360 nil)
19361 ;; Use the requested file name and clean up
19362 (copy-file pngfile tofile 'replace)
19363 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19364 (if (file-exists-p (concat texfilebase e))
19365 (delete-file (concat texfilebase e))))
19366 pngfile))))
19368 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19369 "Fill a LaTeX header template TPL.
19370 In the template, the following place holders will be recognized:
19372 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19373 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19374 [PACKAGES] \\usepackage statements for PKG
19375 [NO-PACKAGES] do not include PKG
19376 [EXTRA] the string EXTRA
19377 [NO-EXTRA] do not include EXTRA
19379 For backward compatibility, if both the positive and the negative place
19380 holder is missing, the positive one (without the \"NO-\") will be
19381 assumed to be present at the end of the template.
19382 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19383 EXTRA is a string.
19384 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19385 (let (rpl (end ""))
19386 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19387 (setq rpl (if (or (match-end 1) (not def-pkg))
19388 "" (org-latex-packages-to-string def-pkg snippets-p t))
19389 tpl (replace-match rpl t t tpl))
19390 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19392 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19393 (setq rpl (if (or (match-end 1) (not pkg))
19394 "" (org-latex-packages-to-string pkg snippets-p t))
19395 tpl (replace-match rpl t t tpl))
19396 (if pkg (setq end
19397 (concat end "\n"
19398 (org-latex-packages-to-string pkg snippets-p)))))
19400 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19401 (setq rpl (if (or (match-end 1) (not extra))
19402 "" (concat extra "\n"))
19403 tpl (replace-match rpl t t tpl))
19404 (if (and extra (string-match "\\S-" extra))
19405 (setq end (concat end "\n" extra))))
19407 (if (string-match "\\S-" end)
19408 (concat tpl "\n" end)
19409 tpl)))
19411 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19412 "Turn an alist of packages into a string with the \\usepackage macros."
19413 (setq pkg (mapconcat (lambda(p)
19414 (cond
19415 ((stringp p) p)
19416 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19417 (format "%% Package %s omitted" (cadr p)))
19418 ((equal "" (car p))
19419 (format "\\usepackage{%s}" (cadr p)))
19421 (format "\\usepackage[%s]{%s}"
19422 (car p) (cadr p)))))
19424 "\n"))
19425 (if newline (concat pkg "\n") pkg))
19427 (defun org-dvipng-color (attr)
19428 "Return a RGB color specification for dvipng."
19429 (apply 'format "rgb %s %s %s"
19430 (mapcar 'org-normalize-color
19431 (if (featurep 'xemacs)
19432 (color-rgb-components
19433 (face-property 'default
19434 (cond ((eq attr :foreground) 'foreground)
19435 ((eq attr :background) 'background))))
19436 (color-values (face-attribute 'default attr nil))))))
19438 (defun org-dvipng-color-format (color-name)
19439 "Convert COLOR-NAME to a RGB color value for dvipng."
19440 (apply 'format "rgb %s %s %s"
19441 (mapcar 'org-normalize-color
19442 (color-values color-name))))
19444 (defun org-latex-color (attr)
19445 "Return a RGB color for the LaTeX color package."
19446 (apply 'format "%s,%s,%s"
19447 (mapcar 'org-normalize-color
19448 (if (featurep 'xemacs)
19449 (color-rgb-components
19450 (face-property 'default
19451 (cond ((eq attr :foreground) 'foreground)
19452 ((eq attr :background) 'background))))
19453 (color-values (face-attribute 'default attr nil))))))
19455 (defun org-latex-color-format (color-name)
19456 "Convert COLOR-NAME to a RGB color value."
19457 (apply 'format "%s,%s,%s"
19458 (mapcar 'org-normalize-color
19459 (color-values color-name))))
19461 (defun org-normalize-color (value)
19462 "Return string to be used as color value for an RGB component."
19463 (format "%g" (/ value 65535.0)))
19467 ;; Image display
19469 (defvar org-inline-image-overlays nil)
19470 (make-variable-buffer-local 'org-inline-image-overlays)
19472 (defun org-toggle-inline-images (&optional include-linked)
19473 "Toggle the display of inline images.
19474 INCLUDE-LINKED is passed to `org-display-inline-images'."
19475 (interactive "P")
19476 (if org-inline-image-overlays
19477 (progn
19478 (org-remove-inline-images)
19479 (when (org-called-interactively-p 'interactive)
19480 (message "Inline image display turned off")))
19481 (org-display-inline-images include-linked)
19482 (when (org-called-interactively-p 'interactive)
19483 (message (if org-inline-image-overlays
19484 (format "%d images displayed inline"
19485 (length org-inline-image-overlays))
19486 "No images to display inline")))))
19488 (defun org-redisplay-inline-images ()
19489 "Refresh the display of inline images."
19490 (interactive)
19491 (if (not org-inline-image-overlays)
19492 (org-toggle-inline-images)
19493 (org-toggle-inline-images)
19494 (org-toggle-inline-images)))
19496 (defun org-display-inline-images (&optional include-linked refresh beg end)
19497 "Display inline images.
19499 An inline image is a link which follows either of these
19500 conventions:
19502 1. Its path is a file with an extension matching return value
19503 from `image-file-name-regexp' and it has no contents.
19505 2. Its description consists in a single link of the previous
19506 type.
19508 When optional argument INCLUDE-LINKED is non-nil, also links with
19509 a text description part will be inlined. This can be nice for
19510 a quick look at those images, but it does not reflect what
19511 exported files will look like.
19513 When optional argument REFRESH is non-nil, refresh existing
19514 images between BEG and END. This will create new image displays
19515 only if necessary. BEG and END default to the buffer
19516 boundaries."
19517 (interactive "P")
19518 (when (display-graphic-p)
19519 (unless refresh
19520 (org-remove-inline-images)
19521 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19522 (org-with-wide-buffer
19523 (goto-char (or beg (point-min)))
19524 (let ((case-fold-search t)
19525 (file-extension-re (org-image-file-name-regexp)))
19526 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19527 (let ((link (save-match-data (org-element-context))))
19528 ;; Check if we're at an inline image.
19529 (when (and (equal (org-element-property :type link) "file")
19530 (or include-linked
19531 (not (org-element-property :contents-begin link)))
19532 (let ((parent (org-element-property :parent link)))
19533 (or (not (eq (org-element-type parent) 'link))
19534 (not (cdr (org-element-contents parent)))))
19535 (org-string-match-p file-extension-re
19536 (org-element-property :path link)))
19537 (let ((file (expand-file-name
19538 (org-link-unescape
19539 (org-element-property :path link)))))
19540 (when (file-exists-p file)
19541 (let ((width
19542 ;; Apply `org-image-actual-width' specifications.
19543 (cond
19544 ((not (image-type-available-p 'imagemagick)) nil)
19545 ((eq org-image-actual-width t) nil)
19546 ((listp org-image-actual-width)
19548 ;; First try to find a width among
19549 ;; attributes associated to the paragraph
19550 ;; containing link.
19551 (let ((paragraph
19552 (let ((e link))
19553 (while (and (setq e (org-element-property
19554 :parent e))
19555 (not (eq (org-element-type e)
19556 'paragraph))))
19557 e)))
19558 (when paragraph
19559 (save-excursion
19560 (goto-char (org-element-property :begin paragraph))
19561 (when
19562 (re-search-forward
19563 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19564 (org-element-property
19565 :post-affiliated paragraph)
19567 (string-to-number (match-string 1))))))
19568 ;; Otherwise, fall-back to provided number.
19569 (car org-image-actual-width)))
19570 ((numberp org-image-actual-width)
19571 org-image-actual-width)))
19572 (old (get-char-property-and-overlay
19573 (org-element-property :begin link)
19574 'org-image-overlay)))
19575 (if (and (car-safe old) refresh)
19576 (image-refresh (overlay-get (cdr old) 'display))
19577 (let ((image (create-image file
19578 (and width 'imagemagick)
19580 :width width)))
19581 (when image
19582 (let* ((link
19583 ;; If inline image is the description
19584 ;; of another link, be sure to
19585 ;; consider the latter as the one to
19586 ;; apply the overlay on.
19587 (let ((parent
19588 (org-element-property :parent link)))
19589 (if (eq (org-element-type parent) 'link)
19590 parent
19591 link)))
19592 (ov (make-overlay
19593 (org-element-property :begin link)
19594 (progn
19595 (goto-char
19596 (org-element-property :end link))
19597 (skip-chars-backward " \t")
19598 (point)))))
19599 (overlay-put ov 'display image)
19600 (overlay-put ov 'face 'default)
19601 (overlay-put ov 'org-image-overlay t)
19602 (overlay-put
19603 ov 'modification-hooks
19604 (list 'org-display-inline-remove-overlay))
19605 (push ov org-inline-image-overlays)))))))))))))))
19607 (define-obsolete-function-alias
19608 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19610 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19611 "Remove inline-display overlay if a corresponding region is modified."
19612 (let ((inhibit-modification-hooks t))
19613 (when (and ov after)
19614 (delete ov org-inline-image-overlays)
19615 (delete-overlay ov))))
19617 (defun org-remove-inline-images ()
19618 "Remove inline display of images."
19619 (interactive)
19620 (mapc 'delete-overlay org-inline-image-overlays)
19621 (setq org-inline-image-overlays nil))
19623 ;;;; Key bindings
19625 ;; Outline functions from `outline-mode-prefix-map'
19626 ;; that can be remapped in Org:
19627 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19628 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19629 (define-key org-mode-map [remap outline-forward-same-level]
19630 'org-forward-heading-same-level)
19631 (define-key org-mode-map [remap outline-backward-same-level]
19632 'org-backward-heading-same-level)
19633 (define-key org-mode-map [remap show-branches]
19634 'org-kill-note-or-show-branches)
19635 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19636 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19637 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19638 (define-key org-mode-map [remap outline-next-visible-heading]
19639 'org-next-visible-heading)
19640 (define-key org-mode-map [remap outline-previous-visible-heading]
19641 'org-previous-visible-heading)
19643 ;; Outline functions from `outline-mode-prefix-map' that can not
19644 ;; be remapped in Org:
19646 ;; - the column "key binding" shows whether the Outline function is still
19647 ;; available in Org mode on the same key that it has been bound to in
19648 ;; Outline mode:
19649 ;; - "overridden": key used for a different functionality in Org mode
19650 ;; - else: key still bound to the same Outline function in Org mode
19652 ;; | Outline function | key binding | Org replacement |
19653 ;; |------------------------------------+-------------+--------------------------|
19654 ;; | `outline-next-visible-heading' | `C-c C-n' | better: skip inlinetasks |
19655 ;; | `outline-previous-visible-heading' | `C-c C-p' | better: skip inlinetasks |
19656 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19657 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19658 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19659 ;; | `show-entry' | overridden | no replacement |
19660 ;; | `show-children' | `C-c C-i' | visibility cycling |
19661 ;; | `show-branches' | `C-c C-k' | still same function |
19662 ;; | `show-subtree' | overridden | visibility cycling |
19663 ;; | `show-all' | overridden | no replacement |
19664 ;; | `hide-subtree' | overridden | visibility cycling |
19665 ;; | `hide-body' | overridden | no replacement |
19666 ;; | `hide-entry' | overridden | visibility cycling |
19667 ;; | `hide-leaves' | overridden | no replacement |
19668 ;; | `hide-sublevels' | overridden | no replacement |
19669 ;; | `hide-other' | overridden | no replacement |
19671 ;; Make `C-c C-x' a prefix key
19672 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19674 ;; TAB key with modifiers
19675 (org-defkey org-mode-map "\C-i" 'org-cycle)
19676 (org-defkey org-mode-map [(tab)] 'org-cycle)
19677 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19678 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19679 ;; The following line is necessary under Suse GNU/Linux
19680 (unless (featurep 'xemacs)
19681 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19682 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19683 (define-key org-mode-map [backtab] 'org-shifttab)
19685 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19686 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19687 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19689 ;; Cursor keys with modifiers
19690 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19691 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19692 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19693 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19695 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19696 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19697 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19698 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19699 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19700 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19702 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19703 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19704 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19705 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19707 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19708 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19709 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19710 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19712 ;; Babel keys
19713 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19714 (mapc (lambda (pair)
19715 (define-key org-babel-map (car pair) (cdr pair)))
19716 org-babel-key-bindings)
19718 ;;; Extra keys for tty access.
19719 ;; We only set them when really needed because otherwise the
19720 ;; menus don't show the simple keys
19722 (when (or org-use-extra-keys
19723 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19724 (not window-system))
19725 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19726 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19727 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19728 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19729 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19730 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19731 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19732 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19733 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19734 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19735 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19736 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19737 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19738 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19739 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19740 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19741 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19742 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19743 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19744 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19745 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19746 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19747 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19748 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19749 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19750 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19751 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19752 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19754 ;; All the other keys
19756 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19757 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19758 (if (boundp 'narrow-map)
19759 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19760 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19761 (if (boundp 'narrow-map)
19762 (org-defkey narrow-map "b" 'org-narrow-to-block)
19763 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19764 (if (boundp 'narrow-map)
19765 (org-defkey narrow-map "e" 'org-narrow-to-element)
19766 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19767 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19768 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19769 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19770 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19771 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19772 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19773 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19774 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19775 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19776 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19777 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19778 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19779 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19780 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19781 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19782 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19783 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19784 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19785 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19786 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19787 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19788 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19789 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19790 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19791 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19792 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19793 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19794 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19795 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19796 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19797 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19798 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19799 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19800 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19801 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19802 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19803 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19804 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19805 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19806 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19807 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19808 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19809 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19810 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19811 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19812 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19813 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19814 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19815 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19816 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19817 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19818 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19819 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19820 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19821 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19822 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19823 (org-defkey org-mode-map "\C-c^" 'org-sort)
19824 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19825 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19826 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19827 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19828 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19829 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19830 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19831 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19832 (org-defkey org-mode-map "\C-m" 'org-return)
19833 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19834 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19835 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19836 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19837 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19838 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19839 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19840 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19841 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19842 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19843 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19844 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19845 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19846 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19847 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19848 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19849 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19850 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19851 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19852 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19853 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19854 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19855 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19856 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19857 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19859 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19860 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19861 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19863 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19864 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19865 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19866 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19867 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19868 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19869 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19870 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19871 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19872 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19873 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19874 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19875 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19876 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19877 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19878 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19879 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19880 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19881 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19882 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19883 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19884 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19886 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19887 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19888 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19889 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19890 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19892 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19894 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19896 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19897 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19899 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19902 (when (featurep 'xemacs)
19903 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19906 (defconst org-speed-commands-default
19908 ("Outline Navigation")
19909 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19910 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19911 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19912 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19913 ("F" . org-next-block)
19914 ("B" . org-previous-block)
19915 ("u" . (org-speed-move-safe 'outline-up-heading))
19916 ("j" . org-goto)
19917 ("g" . (org-refile t))
19918 ("Outline Visibility")
19919 ("c" . org-cycle)
19920 ("C" . org-shifttab)
19921 (" " . org-display-outline-path)
19922 ("s" . org-narrow-to-subtree)
19923 ("=" . org-columns)
19924 ("Outline Structure Editing")
19925 ("U" . org-metaup)
19926 ("D" . org-metadown)
19927 ("r" . org-metaright)
19928 ("l" . org-metaleft)
19929 ("R" . org-shiftmetaright)
19930 ("L" . org-shiftmetaleft)
19931 ("i" . (progn (forward-char 1) (call-interactively
19932 'org-insert-heading-respect-content)))
19933 ("^" . org-sort)
19934 ("w" . org-refile)
19935 ("a" . org-archive-subtree-default-with-confirmation)
19936 ("@" . org-mark-subtree)
19937 ("#" . org-toggle-comment)
19938 ("Clock Commands")
19939 ("I" . org-clock-in)
19940 ("O" . org-clock-out)
19941 ("Meta Data Editing")
19942 ("t" . org-todo)
19943 ("," . (org-priority))
19944 ("0" . (org-priority ?\ ))
19945 ("1" . (org-priority ?A))
19946 ("2" . (org-priority ?B))
19947 ("3" . (org-priority ?C))
19948 (":" . org-set-tags-command)
19949 ("e" . org-set-effort)
19950 ("E" . org-inc-effort)
19951 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19952 (org-entry-put (point) "APPT_WARNTIME" m)))
19953 ("Agenda Views etc")
19954 ("v" . org-agenda)
19955 ("/" . org-sparse-tree)
19956 ("Misc")
19957 ("o" . org-open-at-point)
19958 ("?" . org-speed-command-help)
19959 ("<" . (org-agenda-set-restriction-lock 'subtree))
19960 (">" . (org-agenda-remove-restriction-lock))
19962 "The default speed commands.")
19964 (defun org-print-speed-command (e)
19965 (if (> (length (car e)) 1)
19966 (progn
19967 (princ "\n")
19968 (princ (car e))
19969 (princ "\n")
19970 (princ (make-string (length (car e)) ?-))
19971 (princ "\n"))
19972 (princ (car e))
19973 (princ " ")
19974 (if (symbolp (cdr e))
19975 (princ (symbol-name (cdr e)))
19976 (prin1 (cdr e)))
19977 (princ "\n")))
19979 (defun org-speed-command-help ()
19980 "Show the available speed commands."
19981 (interactive)
19982 (if (not org-use-speed-commands)
19983 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19984 (with-output-to-temp-buffer "*Help*"
19985 (princ "User-defined Speed commands\n===========================\n")
19986 (mapc 'org-print-speed-command org-speed-commands-user)
19987 (princ "\n")
19988 (princ "Built-in Speed commands\n=======================\n")
19989 (mapc 'org-print-speed-command org-speed-commands-default))
19990 (with-current-buffer "*Help*"
19991 (setq truncate-lines t))))
19993 (defun org-speed-move-safe (cmd)
19994 "Execute CMD, but make sure that the cursor always ends up in a headline.
19995 If not, return to the original position and throw an error."
19996 (interactive)
19997 (let ((pos (point)))
19998 (call-interactively cmd)
19999 (unless (and (bolp) (org-at-heading-p))
20000 (goto-char pos)
20001 (error "Boundary reached while executing %s" cmd))))
20003 (defvar org-self-insert-command-undo-counter 0)
20005 (defvar org-table-auto-blank-field) ; defined in org-table.el
20006 (defvar org-speed-command nil)
20008 (define-obsolete-function-alias
20009 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20011 (defun org-speed-command-activate (keys)
20012 "Hook for activating single-letter speed commands.
20013 `org-speed-commands-default' specifies a minimal command set.
20014 Use `org-speed-commands-user' for further customization."
20015 (when (or (and (bolp) (looking-at org-outline-regexp))
20016 (and (functionp org-use-speed-commands)
20017 (funcall org-use-speed-commands)))
20018 (cdr (assoc keys (append org-speed-commands-user
20019 org-speed-commands-default)))))
20021 (define-obsolete-function-alias
20022 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20024 (defun org-babel-speed-command-activate (keys)
20025 "Hook for activating single-letter code block commands."
20026 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20027 (cdr (assoc keys org-babel-key-bindings))))
20029 (defcustom org-speed-command-hook
20030 '(org-speed-command-default-hook org-babel-speed-command-hook)
20031 "Hook for activating speed commands at strategic locations.
20032 Hook functions are called in sequence until a valid handler is
20033 found.
20035 Each hook takes a single argument, a user-pressed command key
20036 which is also a `self-insert-command' from the global map.
20038 Within the hook, examine the cursor position and the command key
20039 and return nil or a valid handler as appropriate. Handler could
20040 be one of an interactive command, a function, or a form.
20042 Set `org-use-speed-commands' to non-nil value to enable this
20043 hook. The default setting is `org-speed-command-activate'."
20044 :group 'org-structure
20045 :version "24.1"
20046 :type 'hook)
20048 (defun org-self-insert-command (N)
20049 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20050 If the cursor is in a table looking at whitespace, the whitespace is
20051 overwritten, and the table is not marked as requiring realignment."
20052 (interactive "p")
20053 (org-check-before-invisible-edit 'insert)
20054 (cond
20055 ((and org-use-speed-commands
20056 (let ((kv (this-command-keys-vector)))
20057 (setq org-speed-command
20058 (run-hook-with-args-until-success
20059 'org-speed-command-hook
20060 (make-string 1 (aref kv (1- (length kv))))))))
20061 (cond
20062 ((commandp org-speed-command)
20063 (setq this-command org-speed-command)
20064 (call-interactively org-speed-command))
20065 ((functionp org-speed-command)
20066 (funcall org-speed-command))
20067 ((and org-speed-command (listp org-speed-command))
20068 (eval org-speed-command))
20069 (t (let (org-use-speed-commands)
20070 (call-interactively 'org-self-insert-command)))))
20071 ((and
20072 (org-table-p)
20073 (progn
20074 ;; check if we blank the field, and if that triggers align
20075 (and (featurep 'org-table) org-table-auto-blank-field
20076 (memq last-command
20077 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20078 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
20079 ;; got extra space, this field does not determine column width
20080 (let (org-table-may-need-update) (org-table-blank-field))
20081 ;; no extra space, this field may determine column width
20082 (org-table-blank-field)))
20084 (eq N 1)
20085 (looking-at "[^|\n]* |"))
20086 (let (org-table-may-need-update)
20087 (goto-char (1- (match-end 0)))
20088 (backward-delete-char 1)
20089 (goto-char (match-beginning 0))
20090 (self-insert-command N)))
20092 (setq org-table-may-need-update t)
20093 (self-insert-command N)
20094 (org-fix-tags-on-the-fly)
20095 (if org-self-insert-cluster-for-undo
20096 (if (not (eq last-command 'org-self-insert-command))
20097 (setq org-self-insert-command-undo-counter 1)
20098 (if (>= org-self-insert-command-undo-counter 20)
20099 (setq org-self-insert-command-undo-counter 1)
20100 (and (> org-self-insert-command-undo-counter 0)
20101 buffer-undo-list (listp buffer-undo-list)
20102 (not (cadr buffer-undo-list)) ; remove nil entry
20103 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20104 (setq org-self-insert-command-undo-counter
20105 (1+ org-self-insert-command-undo-counter))))))))
20107 (defun org-check-before-invisible-edit (kind)
20108 "Check is editing if kind KIND would be dangerous with invisible text around.
20109 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20110 ;; First, try to get out of here as quickly as possible, to reduce overhead
20111 (if (and org-catch-invisible-edits
20112 (or (not (boundp 'visible-mode)) (not visible-mode))
20113 (or (get-char-property (point) 'invisible)
20114 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20115 ;; OK, we need to take a closer look
20116 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20117 (invisible-before-point (if (bobp) nil (get-char-property
20118 (1- (point)) 'invisible)))
20119 (border-and-ok-direction
20121 ;; Check if we are acting predictably before invisible text
20122 (and invisible-at-point (not invisible-before-point)
20123 (memq kind '(insert delete-backward)))
20124 ;; Check if we are acting predictably after invisible text
20125 ;; This works not well, and I have turned it off. It seems
20126 ;; better to always show and stop after invisible text.
20127 ;; (and (not invisible-at-point) invisible-before-point
20128 ;; (memq kind '(insert delete)))
20130 (when (or (memq invisible-at-point '(outline org-hide-block t))
20131 (memq invisible-before-point '(outline org-hide-block t)))
20132 (if (eq org-catch-invisible-edits 'error)
20133 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20134 (if (and org-custom-properties-overlays
20135 (y-or-n-p "Display invisible properties in this buffer? "))
20136 (org-toggle-custom-properties-visibility)
20137 ;; Make the area visible
20138 (save-excursion
20139 (if invisible-before-point
20140 (goto-char (previous-single-char-property-change
20141 (point) 'invisible)))
20142 (show-subtree))
20143 (cond
20144 ((eq org-catch-invisible-edits 'show)
20145 ;; That's it, we do the edit after showing
20146 (message
20147 "Unfolding invisible region around point before editing")
20148 (sit-for 1))
20149 ((and (eq org-catch-invisible-edits 'smart)
20150 border-and-ok-direction)
20151 (message "Unfolding invisible region around point before editing"))
20153 ;; Don't do the edit, make the user repeat it in full visibility
20154 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20156 (defun org-fix-tags-on-the-fly ()
20157 (when (and (equal (char-after (point-at-bol)) ?*)
20158 (org-at-heading-p))
20159 (org-align-tags-here org-tags-column)))
20161 (defun org-delete-backward-char (N)
20162 "Like `delete-backward-char', insert whitespace at field end in tables.
20163 When deleting backwards, in tables this function will insert whitespace in
20164 front of the next \"|\" separator, to keep the table aligned. The table will
20165 still be marked for re-alignment if the field did fill the entire column,
20166 because, in this case the deletion might narrow the column."
20167 (interactive "p")
20168 (save-match-data
20169 (org-check-before-invisible-edit 'delete-backward)
20170 (if (and (org-table-p)
20171 (eq N 1)
20172 (string-match "|" (buffer-substring (point-at-bol) (point)))
20173 (looking-at ".*?|"))
20174 (let ((pos (point))
20175 (noalign (looking-at "[^|\n\r]* |"))
20176 (c org-table-may-need-update))
20177 (backward-delete-char N)
20178 (if (not overwrite-mode)
20179 (progn
20180 (skip-chars-forward "^|")
20181 (insert " ")
20182 (goto-char (1- pos))))
20183 ;; noalign: if there were two spaces at the end, this field
20184 ;; does not determine the width of the column.
20185 (if noalign (setq org-table-may-need-update c)))
20186 (backward-delete-char N)
20187 (org-fix-tags-on-the-fly))))
20189 (defun org-delete-char (N)
20190 "Like `delete-char', but insert whitespace at field end in tables.
20191 When deleting characters, in tables this function will insert whitespace in
20192 front of the next \"|\" separator, to keep the table aligned. The table will
20193 still be marked for re-alignment if the field did fill the entire column,
20194 because, in this case the deletion might narrow the column."
20195 (interactive "p")
20196 (save-match-data
20197 (org-check-before-invisible-edit 'delete)
20198 (if (and (org-table-p)
20199 (not (bolp))
20200 (not (= (char-after) ?|))
20201 (eq N 1))
20202 (if (looking-at ".*?|")
20203 (let ((pos (point))
20204 (noalign (looking-at "[^|\n\r]* |"))
20205 (c org-table-may-need-update))
20206 (replace-match
20207 (concat (substring (match-string 0) 1 -1) " |") nil t)
20208 (goto-char pos)
20209 ;; noalign: if there were two spaces at the end, this field
20210 ;; does not determine the width of the column.
20211 (if noalign (setq org-table-may-need-update c)))
20212 (delete-char N))
20213 (delete-char N)
20214 (org-fix-tags-on-the-fly))))
20216 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20217 (put 'org-self-insert-command 'delete-selection
20218 (lambda ()
20219 (not (run-hook-with-args-until-success
20220 'self-insert-uses-region-functions))))
20221 (put 'orgtbl-self-insert-command 'delete-selection
20222 (lambda ()
20223 (not (run-hook-with-args-until-success
20224 'self-insert-uses-region-functions))))
20225 (put 'org-delete-char 'delete-selection 'supersede)
20226 (put 'org-delete-backward-char 'delete-selection 'supersede)
20227 (put 'org-yank 'delete-selection 'yank)
20229 ;; Make `flyspell-mode' delay after some commands
20230 (put 'org-self-insert-command 'flyspell-delayed t)
20231 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20232 (put 'org-delete-char 'flyspell-delayed t)
20233 (put 'org-delete-backward-char 'flyspell-delayed t)
20235 ;; Make pabbrev-mode expand after org-mode commands
20236 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20237 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20239 (defun org-remap (map &rest commands)
20240 "In MAP, remap the functions given in COMMANDS.
20241 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20242 (let (new old)
20243 (while commands
20244 (setq old (pop commands) new (pop commands))
20245 (if (fboundp 'command-remapping)
20246 (org-defkey map (vector 'remap old) new)
20247 (substitute-key-definition old new map global-map)))))
20249 (defun org-transpose-words ()
20250 "Transpose words for Org.
20251 This uses the `org-mode-transpose-word-syntax-table' syntax
20252 table, which interprets characters in `org-emphasis-alist' as
20253 word constituents."
20254 (interactive)
20255 (with-syntax-table org-mode-transpose-word-syntax-table
20256 (call-interactively 'transpose-words)))
20257 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20259 (when (eq org-enable-table-editor 'optimized)
20260 ;; If the user wants maximum table support, we need to hijack
20261 ;; some standard editing functions
20262 (org-remap org-mode-map
20263 'self-insert-command 'org-self-insert-command
20264 'delete-char 'org-delete-char
20265 'delete-backward-char 'org-delete-backward-char)
20266 (org-defkey org-mode-map "|" 'org-force-self-insert))
20268 (defvar org-ctrl-c-ctrl-c-hook nil
20269 "Hook for functions attaching themselves to `C-c C-c'.
20271 This can be used to add additional functionality to the C-c C-c
20272 key which executes context-dependent commands. This hook is run
20273 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20274 run after the last test.
20276 Each function will be called with no arguments. The function
20277 must check if the context is appropriate for it to act. If yes,
20278 it should do its thing and then return a non-nil value. If the
20279 context is wrong, just do nothing and return nil.")
20281 (defvar org-ctrl-c-ctrl-c-final-hook nil
20282 "Hook for functions attaching themselves to `C-c C-c'.
20284 This can be used to add additional functionality to the C-c C-c
20285 key which executes context-dependent commands. This hook is run
20286 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20287 before the first test.
20289 Each function will be called with no arguments. The function
20290 must check if the context is appropriate for it to act. If yes,
20291 it should do its thing and then return a non-nil value. If the
20292 context is wrong, just do nothing and return nil.")
20294 (defvar org-tab-first-hook nil
20295 "Hook for functions to attach themselves to TAB.
20296 See `org-ctrl-c-ctrl-c-hook' for more information.
20297 This hook runs as the first action when TAB is pressed, even before
20298 `org-cycle' messes around with the `outline-regexp' to cater for
20299 inline tasks and plain list item folding.
20300 If any function in this hook returns t, any other actions that
20301 would have been caused by TAB (such as table field motion or visibility
20302 cycling) will not occur.")
20304 (defvar org-tab-after-check-for-table-hook nil
20305 "Hook for functions to attach themselves to TAB.
20306 See `org-ctrl-c-ctrl-c-hook' for more information.
20307 This hook runs after it has been established that the cursor is not in a
20308 table, but before checking if the cursor is in a headline or if global cycling
20309 should be done.
20310 If any function in this hook returns t, not other actions like visibility
20311 cycling will be done.")
20313 (defvar org-tab-after-check-for-cycling-hook nil
20314 "Hook for functions to attach themselves to TAB.
20315 See `org-ctrl-c-ctrl-c-hook' for more information.
20316 This hook runs after it has been established that not table field motion and
20317 not visibility should be done because of current context. This is probably
20318 the place where a package like yasnippets can hook in.")
20320 (defvar org-tab-before-tab-emulation-hook nil
20321 "Hook for functions to attach themselves to TAB.
20322 See `org-ctrl-c-ctrl-c-hook' for more information.
20323 This hook runs after every other options for TAB have been exhausted, but
20324 before indentation and \t insertion takes place.")
20326 (defvar org-metaleft-hook nil
20327 "Hook for functions attaching themselves to `M-left'.
20328 See `org-ctrl-c-ctrl-c-hook' for more information.")
20329 (defvar org-metaright-hook nil
20330 "Hook for functions attaching themselves to `M-right'.
20331 See `org-ctrl-c-ctrl-c-hook' for more information.")
20332 (defvar org-metaup-hook nil
20333 "Hook for functions attaching themselves to `M-up'.
20334 See `org-ctrl-c-ctrl-c-hook' for more information.")
20335 (defvar org-metadown-hook nil
20336 "Hook for functions attaching themselves to `M-down'.
20337 See `org-ctrl-c-ctrl-c-hook' for more information.")
20338 (defvar org-shiftmetaleft-hook nil
20339 "Hook for functions attaching themselves to `M-S-left'.
20340 See `org-ctrl-c-ctrl-c-hook' for more information.")
20341 (defvar org-shiftmetaright-hook nil
20342 "Hook for functions attaching themselves to `M-S-right'.
20343 See `org-ctrl-c-ctrl-c-hook' for more information.")
20344 (defvar org-shiftmetaup-hook nil
20345 "Hook for functions attaching themselves to `M-S-up'.
20346 See `org-ctrl-c-ctrl-c-hook' for more information.")
20347 (defvar org-shiftmetadown-hook nil
20348 "Hook for functions attaching themselves to `M-S-down'.
20349 See `org-ctrl-c-ctrl-c-hook' for more information.")
20350 (defvar org-metareturn-hook nil
20351 "Hook for functions attaching themselves to `M-RET'.
20352 See `org-ctrl-c-ctrl-c-hook' for more information.")
20353 (defvar org-shiftup-hook nil
20354 "Hook for functions attaching themselves to `S-up'.
20355 See `org-ctrl-c-ctrl-c-hook' for more information.")
20356 (defvar org-shiftup-final-hook nil
20357 "Hook for functions attaching themselves to `S-up'.
20358 This one runs after all other options except shift-select have been excluded.
20359 See `org-ctrl-c-ctrl-c-hook' for more information.")
20360 (defvar org-shiftdown-hook nil
20361 "Hook for functions attaching themselves to `S-down'.
20362 See `org-ctrl-c-ctrl-c-hook' for more information.")
20363 (defvar org-shiftdown-final-hook nil
20364 "Hook for functions attaching themselves to `S-down'.
20365 This one runs after all other options except shift-select have been excluded.
20366 See `org-ctrl-c-ctrl-c-hook' for more information.")
20367 (defvar org-shiftleft-hook nil
20368 "Hook for functions attaching themselves to `S-left'.
20369 See `org-ctrl-c-ctrl-c-hook' for more information.")
20370 (defvar org-shiftleft-final-hook nil
20371 "Hook for functions attaching themselves to `S-left'.
20372 This one runs after all other options except shift-select have been excluded.
20373 See `org-ctrl-c-ctrl-c-hook' for more information.")
20374 (defvar org-shiftright-hook nil
20375 "Hook for functions attaching themselves to `S-right'.
20376 See `org-ctrl-c-ctrl-c-hook' for more information.")
20377 (defvar org-shiftright-final-hook nil
20378 "Hook for functions attaching themselves to `S-right'.
20379 This one runs after all other options except shift-select have been excluded.
20380 See `org-ctrl-c-ctrl-c-hook' for more information.")
20382 (defun org-modifier-cursor-error ()
20383 "Throw an error, a modified cursor command was applied in wrong context."
20384 (user-error "This command is active in special context like tables, headlines or items"))
20386 (defun org-shiftselect-error ()
20387 "Throw an error because Shift-Cursor command was applied in wrong context."
20388 (if (and (boundp 'shift-select-mode) shift-select-mode)
20389 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20390 (user-error "This command works only in special context like headlines or timestamps")))
20392 (defun org-call-for-shift-select (cmd)
20393 (let ((this-command-keys-shift-translated t))
20394 (call-interactively cmd)))
20396 (defun org-shifttab (&optional arg)
20397 "Global visibility cycling or move to previous table field.
20398 Call `org-table-previous-field' within a table.
20399 When ARG is nil, cycle globally through visibility states.
20400 When ARG is a numeric prefix, show contents of this level."
20401 (interactive "P")
20402 (cond
20403 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20404 ((integerp arg)
20405 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20406 (message "Content view to level: %d" arg)
20407 (org-content (prefix-numeric-value arg2))
20408 (org-cycle-show-empty-lines t)
20409 (setq org-cycle-global-status 'overview)))
20410 (t (call-interactively 'org-global-cycle))))
20412 (defun org-shiftmetaleft ()
20413 "Promote subtree or delete table column.
20414 Calls `org-promote-subtree', `org-outdent-item-tree', or
20415 `org-table-delete-column', depending on context. See the
20416 individual commands for more information."
20417 (interactive)
20418 (cond
20419 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20420 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20421 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20422 ((if (not (org-region-active-p)) (org-at-item-p)
20423 (save-excursion (goto-char (region-beginning))
20424 (org-at-item-p)))
20425 (call-interactively 'org-outdent-item-tree))
20426 (t (org-modifier-cursor-error))))
20428 (defun org-shiftmetaright ()
20429 "Demote subtree or insert table column.
20430 Calls `org-demote-subtree', `org-indent-item-tree', or
20431 `org-table-insert-column', depending on context. See the
20432 individual commands for more information."
20433 (interactive)
20434 (cond
20435 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20436 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20437 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20438 ((if (not (org-region-active-p)) (org-at-item-p)
20439 (save-excursion (goto-char (region-beginning))
20440 (org-at-item-p)))
20441 (call-interactively 'org-indent-item-tree))
20442 (t (org-modifier-cursor-error))))
20444 (defun org-shiftmetaup (&optional arg)
20445 "Drag the line at point up.
20446 In a table, kill the current row.
20447 On a clock timestamp, update the value of the timestamp like `S-<up>'
20448 but also adjust the previous clocked item in the clock history.
20449 Everywhere else, drag the line at point up."
20450 (interactive "P")
20451 (cond
20452 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20453 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20454 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20455 (call-interactively 'org-timestamp-up)))
20456 (t (call-interactively 'org-drag-line-backward))))
20458 (defun org-shiftmetadown (&optional arg)
20459 "Drag the line at point down.
20460 In a table, insert an empty row at the current line.
20461 On a clock timestamp, update the value of the timestamp like `S-<down>'
20462 but also adjust the previous clocked item in the clock history.
20463 Everywhere else, drag the line at point down."
20464 (interactive "P")
20465 (cond
20466 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20467 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20468 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20469 (call-interactively 'org-timestamp-down)))
20470 (t (call-interactively 'org-drag-line-forward))))
20472 (defsubst org-hidden-tree-error ()
20473 (user-error
20474 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20476 (defun org-metaleft (&optional arg)
20477 "Promote heading, list item at point or move table column left.
20479 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20480 depending on context. With no specific context, calls the Emacs
20481 default `backward-word'. See the individual commands for more
20482 information.
20484 This function runs the hook `org-metaleft-hook' as a first step,
20485 and returns at first non-nil value."
20486 (interactive "P")
20487 (cond
20488 ((run-hook-with-args-until-success 'org-metaleft-hook))
20489 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20490 ((org-with-limited-levels
20491 (or (org-at-heading-p)
20492 (and (org-region-active-p)
20493 (save-excursion
20494 (goto-char (region-beginning))
20495 (org-at-heading-p)))))
20496 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20497 (call-interactively 'org-do-promote))
20498 ;; At an inline task.
20499 ((org-at-heading-p)
20500 (call-interactively 'org-inlinetask-promote))
20501 ((or (org-at-item-p)
20502 (and (org-region-active-p)
20503 (save-excursion
20504 (goto-char (region-beginning))
20505 (org-at-item-p))))
20506 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20507 (call-interactively 'org-outdent-item))
20508 (t (call-interactively 'backward-word))))
20510 (defun org-metaright (&optional arg)
20511 "Demote heading, list item at point or move table column right.
20513 In front of a drawer or a block keyword, indent it correctly.
20515 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20516 `org-indnet-drawer' or `org-indent-block' depending on context.
20517 With no specific context, calls the Emacs default `forward-word'.
20518 See the individual commands for more information.
20520 This function runs the hook `org-metaright-hook' as a first step,
20521 and returns at first non-nil value."
20522 (interactive "P")
20523 (cond
20524 ((run-hook-with-args-until-success 'org-metaright-hook))
20525 ((org-at-table-p) (call-interactively 'org-table-move-column))
20526 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20527 ((org-at-block-p) (call-interactively 'org-indent-block))
20528 ((org-with-limited-levels
20529 (or (org-at-heading-p)
20530 (and (org-region-active-p)
20531 (save-excursion
20532 (goto-char (region-beginning))
20533 (org-at-heading-p)))))
20534 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20535 (call-interactively 'org-do-demote))
20536 ;; At an inline task.
20537 ((org-at-heading-p)
20538 (call-interactively 'org-inlinetask-demote))
20539 ((or (org-at-item-p)
20540 (and (org-region-active-p)
20541 (save-excursion
20542 (goto-char (region-beginning))
20543 (org-at-item-p))))
20544 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20545 (call-interactively 'org-indent-item))
20546 (t (call-interactively 'forward-word))))
20548 (defun org-check-for-hidden (what)
20549 "Check if there are hidden headlines/items in the current visual line.
20550 WHAT can be either `headlines' or `items'. If the current line is
20551 an outline or item heading and it has a folded subtree below it,
20552 this function returns t, nil otherwise."
20553 (let ((re (cond
20554 ((eq what 'headlines) org-outline-regexp-bol)
20555 ((eq what 'items) (org-item-beginning-re))
20556 (t (error "This should not happen"))))
20557 beg end)
20558 (save-excursion
20559 (catch 'exit
20560 (unless (org-region-active-p)
20561 (setq beg (point-at-bol))
20562 (beginning-of-line 2)
20563 (while (and (not (eobp)) ;; this is like `next-line'
20564 (get-char-property (1- (point)) 'invisible))
20565 (beginning-of-line 2))
20566 (setq end (point))
20567 (goto-char beg)
20568 (goto-char (point-at-eol))
20569 (setq end (max end (point)))
20570 (while (re-search-forward re end t)
20571 (if (get-char-property (match-beginning 0) 'invisible)
20572 (throw 'exit t))))
20573 nil))))
20575 (defun org-metaup (&optional arg)
20576 "Move subtree up or move table row up.
20577 Calls `org-move-subtree-up' or `org-table-move-row' or
20578 `org-move-item-up', depending on context. See the individual commands
20579 for more information."
20580 (interactive "P")
20581 (cond
20582 ((run-hook-with-args-until-success 'org-metaup-hook))
20583 ((org-region-active-p)
20584 (let* ((a (min (region-beginning) (region-end)))
20585 (b (1- (max (region-beginning) (region-end))))
20586 (c (save-excursion (goto-char a)
20587 (move-beginning-of-line 0)))
20588 (d (save-excursion (goto-char a)
20589 (move-end-of-line 0) (point))))
20590 (transpose-regions a b c d)
20591 (goto-char c)))
20592 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20593 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20594 ((org-at-item-p) (call-interactively 'org-move-item-up))
20595 (t (org-drag-element-backward))))
20597 (defun org-metadown (&optional arg)
20598 "Move subtree down or move table row down.
20599 Calls `org-move-subtree-down' or `org-table-move-row' or
20600 `org-move-item-down', depending on context. See the individual
20601 commands for more information."
20602 (interactive "P")
20603 (cond
20604 ((run-hook-with-args-until-success 'org-metadown-hook))
20605 ((org-region-active-p)
20606 (let* ((a (min (region-beginning) (region-end)))
20607 (b (max (region-beginning) (region-end)))
20608 (c (save-excursion (goto-char b)
20609 (move-beginning-of-line 1)))
20610 (d (save-excursion (goto-char b)
20611 (move-end-of-line 1) (1+ (point)))))
20612 (transpose-regions a b c d)
20613 (goto-char d)))
20614 ((org-at-table-p) (call-interactively 'org-table-move-row))
20615 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20616 ((org-at-item-p) (call-interactively 'org-move-item-down))
20617 (t (org-drag-element-forward))))
20619 (defun org-shiftup (&optional arg)
20620 "Increase item in timestamp or increase priority of current headline.
20621 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20622 depending on context. See the individual commands for more information."
20623 (interactive "P")
20624 (cond
20625 ((run-hook-with-args-until-success 'org-shiftup-hook))
20626 ((and org-support-shift-select (org-region-active-p))
20627 (org-call-for-shift-select 'previous-line))
20628 ((org-at-timestamp-p t)
20629 (call-interactively (if org-edit-timestamp-down-means-later
20630 'org-timestamp-down 'org-timestamp-up)))
20631 ((and (not (eq org-support-shift-select 'always))
20632 org-enable-priority-commands
20633 (org-at-heading-p))
20634 (call-interactively 'org-priority-up))
20635 ((and (not org-support-shift-select) (org-at-item-p))
20636 (call-interactively 'org-previous-item))
20637 ((org-clocktable-try-shift 'up arg))
20638 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20639 (org-support-shift-select
20640 (org-call-for-shift-select 'previous-line))
20641 (t (org-shiftselect-error))))
20643 (defun org-shiftdown (&optional arg)
20644 "Decrease item in timestamp or decrease priority of current headline.
20645 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20646 depending on context. See the individual commands for more information."
20647 (interactive "P")
20648 (cond
20649 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20650 ((and org-support-shift-select (org-region-active-p))
20651 (org-call-for-shift-select 'next-line))
20652 ((org-at-timestamp-p t)
20653 (call-interactively (if org-edit-timestamp-down-means-later
20654 'org-timestamp-up 'org-timestamp-down)))
20655 ((and (not (eq org-support-shift-select 'always))
20656 org-enable-priority-commands
20657 (org-at-heading-p))
20658 (call-interactively 'org-priority-down))
20659 ((and (not org-support-shift-select) (org-at-item-p))
20660 (call-interactively 'org-next-item))
20661 ((org-clocktable-try-shift 'down arg))
20662 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20663 (org-support-shift-select
20664 (org-call-for-shift-select 'next-line))
20665 (t (org-shiftselect-error))))
20667 (defun org-shiftright (&optional arg)
20668 "Cycle the thing at point or in the current line, depending on context.
20669 Depending on context, this does one of the following:
20671 - switch a timestamp at point one day into the future
20672 - on a headline, switch to the next TODO keyword.
20673 - on an item, switch entire list to the next bullet type
20674 - on a property line, switch to the next allowed value
20675 - on a clocktable definition line, move time block into the future"
20676 (interactive "P")
20677 (cond
20678 ((run-hook-with-args-until-success 'org-shiftright-hook))
20679 ((and org-support-shift-select (org-region-active-p))
20680 (org-call-for-shift-select 'forward-char))
20681 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20682 ((and (not (eq org-support-shift-select 'always))
20683 (org-at-heading-p))
20684 (let ((org-inhibit-logging
20685 (not org-treat-S-cursor-todo-selection-as-state-change))
20686 (org-inhibit-blocking
20687 (not org-treat-S-cursor-todo-selection-as-state-change)))
20688 (org-call-with-arg 'org-todo 'right)))
20689 ((or (and org-support-shift-select
20690 (not (eq org-support-shift-select 'always))
20691 (org-at-item-bullet-p))
20692 (and (not org-support-shift-select) (org-at-item-p)))
20693 (org-call-with-arg 'org-cycle-list-bullet nil))
20694 ((and (not (eq org-support-shift-select 'always))
20695 (org-at-property-p))
20696 (call-interactively 'org-property-next-allowed-value))
20697 ((org-clocktable-try-shift 'right arg))
20698 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20699 (org-support-shift-select
20700 (org-call-for-shift-select 'forward-char))
20701 (t (org-shiftselect-error))))
20703 (defun org-shiftleft (&optional arg)
20704 "Cycle the thing at point or in the current line, depending on context.
20705 Depending on context, this does one of the following:
20707 - switch a timestamp at point one day into the past
20708 - on a headline, switch to the previous TODO keyword.
20709 - on an item, switch entire list to the previous bullet type
20710 - on a property line, switch to the previous allowed value
20711 - on a clocktable definition line, move time block into the past"
20712 (interactive "P")
20713 (cond
20714 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20715 ((and org-support-shift-select (org-region-active-p))
20716 (org-call-for-shift-select 'backward-char))
20717 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20718 ((and (not (eq org-support-shift-select 'always))
20719 (org-at-heading-p))
20720 (let ((org-inhibit-logging
20721 (not org-treat-S-cursor-todo-selection-as-state-change))
20722 (org-inhibit-blocking
20723 (not org-treat-S-cursor-todo-selection-as-state-change)))
20724 (org-call-with-arg 'org-todo 'left)))
20725 ((or (and org-support-shift-select
20726 (not (eq org-support-shift-select 'always))
20727 (org-at-item-bullet-p))
20728 (and (not org-support-shift-select) (org-at-item-p)))
20729 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20730 ((and (not (eq org-support-shift-select 'always))
20731 (org-at-property-p))
20732 (call-interactively 'org-property-previous-allowed-value))
20733 ((org-clocktable-try-shift 'left arg))
20734 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20735 (org-support-shift-select
20736 (org-call-for-shift-select 'backward-char))
20737 (t (org-shiftselect-error))))
20739 (defun org-shiftcontrolright ()
20740 "Switch to next TODO set."
20741 (interactive)
20742 (cond
20743 ((and org-support-shift-select (org-region-active-p))
20744 (org-call-for-shift-select 'forward-word))
20745 ((and (not (eq org-support-shift-select 'always))
20746 (org-at-heading-p))
20747 (org-call-with-arg 'org-todo 'nextset))
20748 (org-support-shift-select
20749 (org-call-for-shift-select 'forward-word))
20750 (t (org-shiftselect-error))))
20752 (defun org-shiftcontrolleft ()
20753 "Switch to previous TODO set."
20754 (interactive)
20755 (cond
20756 ((and org-support-shift-select (org-region-active-p))
20757 (org-call-for-shift-select 'backward-word))
20758 ((and (not (eq org-support-shift-select 'always))
20759 (org-at-heading-p))
20760 (org-call-with-arg 'org-todo 'previousset))
20761 (org-support-shift-select
20762 (org-call-for-shift-select 'backward-word))
20763 (t (org-shiftselect-error))))
20765 (defun org-shiftcontrolup (&optional n)
20766 "Change timestamps synchronously up in CLOCK log lines.
20767 Optional argument N tells to change by that many units."
20768 (interactive "P")
20769 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20770 (let (org-support-shift-select)
20771 (org-clock-timestamps-up n))
20772 (user-error "Not at a clock log")))
20774 (defun org-shiftcontroldown (&optional n)
20775 "Change timestamps synchronously down in CLOCK log lines.
20776 Optional argument N tells to change by that many units."
20777 (interactive "P")
20778 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20779 (let (org-support-shift-select)
20780 (org-clock-timestamps-down n))
20781 (user-error "Not at a clock log")))
20783 (defun org-increase-number-at-point (&optional inc)
20784 "Increment the number at point.
20785 With an optional prefix numeric argument INC, increment using
20786 this numeric value."
20787 (interactive "p")
20788 (if (not (number-at-point))
20789 (user-error "Not on a number")
20790 (unless inc (setq inc 1))
20791 (let ((pos (point))
20792 (beg (skip-chars-backward "-+^/*0-9eE."))
20793 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20794 (setq nap (buffer-substring-no-properties
20795 (+ pos beg) (+ pos beg end)))
20796 (delete-region (+ pos beg) (+ pos beg end))
20797 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20798 (when (org-at-table-p)
20799 (org-table-align)
20800 (org-table-end-of-field 1))))
20802 (defun org-decrease-number-at-point (&optional inc)
20803 "Decrement the number at point.
20804 With an optional prefix numeric argument INC, decrement using
20805 this numeric value."
20806 (interactive "p")
20807 (org-increase-number-at-point (- (or inc 1))))
20809 (defun org-ctrl-c-ret ()
20810 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20811 (interactive)
20812 (cond
20813 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20814 (t (call-interactively 'org-insert-heading))))
20816 (defun org-find-visible ()
20817 (let ((s (point)))
20818 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20819 (get-char-property s 'invisible)))
20821 (defun org-find-invisible ()
20822 (let ((s (point)))
20823 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20824 (not (get-char-property s 'invisible))))
20827 (defun org-copy-visible (beg end)
20828 "Copy the visible parts of the region."
20829 (interactive "r")
20830 (let (snippets s)
20831 (save-excursion
20832 (save-restriction
20833 (narrow-to-region beg end)
20834 (setq s (goto-char (point-min)))
20835 (while (not (= (point) (point-max)))
20836 (goto-char (org-find-invisible))
20837 (push (buffer-substring s (point)) snippets)
20838 (setq s (goto-char (org-find-visible))))))
20839 (kill-new (apply 'concat (nreverse snippets)))))
20841 (defun org-copy-special ()
20842 "Copy region in table or copy current subtree.
20843 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20844 See the individual commands for more information."
20845 (interactive)
20846 (call-interactively
20847 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20849 (defun org-cut-special ()
20850 "Cut region in table or cut current subtree.
20851 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20852 See the individual commands for more information."
20853 (interactive)
20854 (call-interactively
20855 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20857 (defun org-paste-special (arg)
20858 "Paste rectangular region into table, or past subtree relative to level.
20859 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20860 See the individual commands for more information."
20861 (interactive "P")
20862 (if (org-at-table-p)
20863 (org-table-paste-rectangle)
20864 (org-paste-subtree arg)))
20866 (defsubst org-in-fixed-width-region-p ()
20867 "Is point in a fixed-width region?"
20868 (save-match-data
20869 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20871 (defun org-edit-special (&optional arg)
20872 "Call a special editor for the element at point.
20873 When at a table, call the formula editor with `org-table-edit-formulas'.
20874 When in a source code block, call `org-edit-src-code'.
20875 When in a fixed-width region, call `org-edit-fixed-width-region'.
20876 When in an export block, call `org-edit-export-block'.
20877 When at an #+INCLUDE keyword, visit the included file.
20878 When at a footnote reference, call `org-edit-footnote-reference'
20879 On a link, call `ffap' to visit the link at point.
20880 Otherwise, return a user error."
20881 (interactive "P")
20882 (let ((element (org-element-at-point)))
20883 (assert (not buffer-read-only) nil
20884 "Buffer is read-only: %s" (buffer-name))
20885 (case (org-element-type element)
20886 (src-block
20887 (if (not arg) (org-edit-src-code)
20888 (let* ((info (org-babel-get-src-block-info))
20889 (lang (nth 0 info))
20890 (params (nth 2 info))
20891 (session (cdr (assq :session params))))
20892 (if (not session) (org-edit-src-code)
20893 ;; At a src-block with a session and function called with
20894 ;; an ARG: switch to the buffer related to the inferior
20895 ;; process.
20896 (switch-to-buffer
20897 (funcall (intern (concat "org-babel-prep-session:" lang))
20898 session params))))))
20899 (keyword
20900 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20901 (org-open-link-from-string
20902 (format "[[%s]]"
20903 (expand-file-name
20904 (let ((value (org-element-property :value element)))
20905 (cond ((not (org-string-nw-p value))
20906 (user-error "No file to edit"))
20907 ((string-match "\\`\"\\(.*?\\)\"" value)
20908 (match-string 1 value))
20909 ((string-match "\\`[^ \t\"]\\S-*" value)
20910 (match-string 0 value))
20911 (t (user-error "No valid file specified")))))))
20912 (user-error "No special environment to edit here")))
20913 (table
20914 (if (eq (org-element-property :type element) 'table.el)
20915 (org-edit-table.el)
20916 (call-interactively 'org-table-edit-formulas)))
20917 ;; Only Org tables contain `table-row' type elements.
20918 (table-row (call-interactively 'org-table-edit-formulas))
20919 (example-block (org-edit-src-code))
20920 (export-block (org-edit-export-block))
20921 (fixed-width (org-edit-fixed-width-region))
20922 (otherwise
20923 ;; No notable element at point. Though, we may be at a link or
20924 ;; a footnote reference, which are objects. Thus, scan deeper.
20925 (let ((context (org-element-context element)))
20926 (case (org-element-type context)
20927 (link (call-interactively #'ffap))
20928 (footnote-reference (org-edit-footnote-reference))
20929 (t (user-error "No special environment to edit here"))))))))
20931 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20932 (defun org-ctrl-c-ctrl-c (&optional arg)
20933 "Set tags in headline, or update according to changed information at point.
20935 This command does many different things, depending on context:
20937 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20938 this is what we do.
20940 - If the cursor is on a statistics cookie, update it.
20942 - If the cursor is in a headline, prompt for tags and insert them
20943 into the current line, aligned to `org-tags-column'. When called
20944 with prefix arg, realign all tags in the current buffer.
20946 - If the cursor is in one of the special #+KEYWORD lines, this
20947 triggers scanning the buffer for these lines and updating the
20948 information.
20950 - If the cursor is inside a table, realign the table. This command
20951 works even if the automatic table editor has been turned off.
20953 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20954 the entire table.
20956 - If the cursor is at a footnote reference or definition, jump to
20957 the corresponding definition or references, respectively.
20959 - If the cursor is a the beginning of a dynamic block, update it.
20961 - If the current buffer is a capture buffer, close note and file it.
20963 - If the cursor is on a <<<target>>>, update radio targets and
20964 corresponding links in this buffer.
20966 - If the cursor is on a numbered item in a plain list, renumber the
20967 ordered list.
20969 - If the cursor is on a checkbox, toggle it.
20971 - If the cursor is on a code block, evaluate it. The variable
20972 `org-confirm-babel-evaluate' can be used to control prompting
20973 before code block evaluation, by default every code block
20974 evaluation requires confirmation. Code block evaluation can be
20975 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20976 (interactive "P")
20977 (cond
20978 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20979 org-occur-highlights)
20980 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20981 (org-remove-occur-highlights)
20982 (message "Temporary highlights/overlays removed from current buffer"))
20983 ((and (local-variable-p 'org-finish-function (current-buffer))
20984 (fboundp org-finish-function))
20985 (funcall org-finish-function))
20986 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20988 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20989 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20990 (user-error "C-c C-c can do nothing useful at this location"))
20991 (let* ((context (org-element-context))
20992 (type (org-element-type context)))
20993 (case type
20994 ;; When at a link, act according to the parent instead.
20995 (link (setq context (org-element-property :parent context))
20996 (setq type (org-element-type context)))
20997 ;; Unsupported object types: refer to the first supported
20998 ;; element or object containing it.
20999 ((bold code entity export-snippet inline-babel-call inline-src-block
21000 italic latex-fragment line-break macro strike-through subscript
21001 superscript underline verbatim)
21002 (setq context
21003 (org-element-lineage
21004 context '(radio-target paragraph verse-block table-cell)))))
21005 ;; For convenience: at the first line of a paragraph on the
21006 ;; same line as an item, apply function on that item instead.
21007 (when (eq type 'paragraph)
21008 (let ((parent (org-element-property :parent context)))
21009 (when (and (eq (org-element-type parent) 'item)
21010 (= (line-beginning-position)
21011 (org-element-property :begin parent)))
21012 (setq context parent type 'item))))
21013 ;; Act according to type of element or object at point.
21014 (case type
21015 (clock (org-clock-update-time-maybe))
21016 (dynamic-block
21017 (save-excursion
21018 (goto-char (org-element-property :post-affiliated context))
21019 (org-update-dblock)))
21020 (footnote-definition
21021 (goto-char (org-element-property :post-affiliated context))
21022 (call-interactively 'org-footnote-action))
21023 (footnote-reference (call-interactively 'org-footnote-action))
21024 ((headline inlinetask)
21025 (save-excursion (goto-char (org-element-property :begin context))
21026 (call-interactively 'org-set-tags)))
21027 (item
21028 ;; At an item: a double C-u set checkbox to "[-]"
21029 ;; unconditionally, whereas a single one will toggle its
21030 ;; presence. Without an universal argument, if the item
21031 ;; has a checkbox, toggle it. Otherwise repair the list.
21032 (let* ((box (org-element-property :checkbox context))
21033 (struct (org-element-property :structure context))
21034 (old-struct (copy-tree struct))
21035 (parents (org-list-parents-alist struct))
21036 (prevs (org-list-prevs-alist struct))
21037 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21038 (org-list-set-checkbox
21039 (org-element-property :begin context) struct
21040 (cond ((equal arg '(16)) "[-]")
21041 ((and (not box) (equal arg '(4))) "[ ]")
21042 ((or (not box) (equal arg '(4))) nil)
21043 ((eq box 'on) "[ ]")
21044 (t "[X]")))
21045 ;; Mimic `org-list-write-struct' but with grabbing
21046 ;; a return value from `org-list-struct-fix-box'.
21047 (org-list-struct-fix-ind struct parents 2)
21048 (org-list-struct-fix-item-end struct)
21049 (org-list-struct-fix-bul struct prevs)
21050 (org-list-struct-fix-ind struct parents)
21051 (let ((block-item
21052 (org-list-struct-fix-box struct parents prevs orderedp)))
21053 (if (and box (equal struct old-struct))
21054 (if (equal arg '(16))
21055 (message "Checkboxes already reset")
21056 (user-error "Cannot toggle this checkbox: %s"
21057 (if (eq box 'on)
21058 "all subitems checked"
21059 "unchecked subitems")))
21060 (org-list-struct-apply-struct struct old-struct)
21061 (org-update-checkbox-count-maybe))
21062 (when block-item
21063 (message "Checkboxes were removed due to empty box at line %d"
21064 (org-current-line block-item))))))
21065 (keyword
21066 (let ((org-inhibit-startup-visibility-stuff t)
21067 (org-startup-align-all-tables nil))
21068 (when (boundp 'org-table-coordinate-overlays)
21069 (mapc 'delete-overlay org-table-coordinate-overlays)
21070 (setq org-table-coordinate-overlays nil))
21071 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21072 (message "Local setup has been refreshed"))
21073 (plain-list
21074 ;; At a plain list, with a double C-u argument, set
21075 ;; checkboxes of each item to "[-]", whereas a single one
21076 ;; will toggle their presence according to the state of the
21077 ;; first item in the list. Without an argument, repair the
21078 ;; list.
21079 (let* ((begin (org-element-property :contents-begin context))
21080 (beginm (move-marker (make-marker) begin))
21081 (struct (org-element-property :structure context))
21082 (old-struct (copy-tree struct))
21083 (first-box (save-excursion
21084 (goto-char begin)
21085 (looking-at org-list-full-item-re)
21086 (match-string-no-properties 3)))
21087 (new-box (cond ((equal arg '(16)) "[-]")
21088 ((equal arg '(4)) (unless first-box "[ ]"))
21089 ((equal first-box "[X]") "[ ]")
21090 (t "[X]"))))
21091 (cond
21092 (arg
21093 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
21094 (org-list-get-all-items
21095 begin struct (org-list-prevs-alist struct))))
21096 ((and first-box (eq (point) begin))
21097 ;; For convenience, when point is at bol on the first
21098 ;; item of the list and no argument is provided, simply
21099 ;; toggle checkbox of that item, if any.
21100 (org-list-set-checkbox begin struct new-box)))
21101 (org-list-write-struct
21102 struct (org-list-parents-alist struct) old-struct)
21103 (org-update-checkbox-count-maybe)
21104 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21105 ((property-drawer node-property)
21106 (call-interactively 'org-property-action))
21107 ((radio-target target)
21108 (call-interactively 'org-update-radio-target-regexp))
21109 (statistics-cookie
21110 (call-interactively 'org-update-statistics-cookies))
21111 ((table table-cell table-row)
21112 ;; At a table, recalculate every field and align it. Also
21113 ;; send the table if necessary. If the table has
21114 ;; a `table.el' type, just give up. At a table row or
21115 ;; cell, maybe recalculate line but always align table.
21116 (if (eq (org-element-property :type context) 'table.el)
21117 (message "Use C-c ' to edit table.el tables")
21118 (let ((org-enable-table-editor t))
21119 (if (or (eq type 'table)
21120 ;; Check if point is at a TBLFM line.
21121 (and (eq type 'table-row)
21122 (= (point) (org-element-property :end context))))
21123 (save-excursion
21124 (if (org-at-TBLFM-p)
21125 (progn (require 'org-table)
21126 (org-table-calc-current-TBLFM))
21127 (goto-char (org-element-property :contents-begin context))
21128 (org-call-with-arg 'org-table-recalculate (or arg t))
21129 (orgtbl-send-table 'maybe)))
21130 (org-table-maybe-eval-formula)
21131 (cond (arg (call-interactively 'org-table-recalculate))
21132 ((org-table-maybe-recalculate-line))
21133 (t (org-table-align)))))))
21134 (timestamp (org-timestamp-change 0 'day))
21135 (otherwise
21136 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21137 (user-error
21138 "C-c C-c can do nothing useful at this location")))))))))
21140 (defun org-mode-restart ()
21141 (interactive)
21142 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21143 (funcall major-mode)
21144 (hack-local-variables)
21145 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21146 (org-indent-mode -1)))
21147 (message "%s restarted" major-mode))
21149 (defun org-kill-note-or-show-branches ()
21150 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21151 (interactive)
21152 (if (not org-finish-function)
21153 (progn
21154 (hide-subtree)
21155 (call-interactively 'show-branches))
21156 (let ((org-note-abort t))
21157 (funcall org-finish-function))))
21159 (defun org-delete-indentation (&optional ARG)
21160 "Join current line to previous and fix whitespace at join.
21162 If previous line is a headline add to headline title. Otherwise
21163 the function calls `delete-indentation'.
21165 With argument, join this line to following line."
21166 (interactive "*P")
21167 (if (save-excursion
21168 (if ARG (beginning-of-line)
21169 (forward-line -1))
21170 (looking-at org-complex-heading-regexp))
21171 ;; At headline.
21172 (let ((tags-column (when (match-beginning 5)
21173 (save-excursion (goto-char (match-beginning 5))
21174 (current-column))))
21175 (string (concat " " (progn (when ARG (forward-line 1))
21176 (org-trim (delete-and-extract-region
21177 (line-beginning-position)
21178 (line-end-position)))))))
21179 (unless (bobp) (delete-region (point) (1- (point))))
21180 (goto-char (or (match-end 4)
21181 (match-beginning 5)
21182 (match-end 0)))
21183 (skip-chars-backward " \t")
21184 (save-excursion (insert string))
21185 ;; Adjust alignment of tags.
21186 (when tags-column
21187 (org-align-tags-here (if org-auto-align-tags
21188 org-tags-column
21189 tags-column))))
21190 (delete-indentation ARG)))
21192 (defun org-open-line (n)
21193 "Insert a new row in tables, call `open-line' elsewhere.
21194 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21195 (interactive "*p")
21196 (cond
21197 ((not org-special-ctrl-o)
21198 (open-line n))
21199 ((org-at-table-p)
21200 (org-table-insert-row))
21202 (open-line n))))
21204 (defun org-return (&optional indent)
21205 "Goto next table row or insert a newline.
21207 Calls `org-table-next-row' or `newline', depending on context.
21209 When optional INDENT argument is non-nil, call
21210 `newline-and-indent' instead of `newline'.
21212 When `org-return-follows-link' is non-nil and point is on
21213 a timestamp or a link, call `org-open-at-point'. However, it
21214 will not happen if point is in a table or on a \"dead\"
21215 object (e.g., within a comment). In these case, you need to use
21216 `org-open-at-point' directly."
21217 (interactive)
21218 (if (and (not (bolp))
21219 (save-excursion (beginning-of-line)
21220 (looking-at org-complex-heading-regexp)))
21221 ;; At headline.
21222 (let ((tags-column (when (match-beginning 5)
21223 (save-excursion (goto-char (match-beginning 5))
21224 (current-column))))
21225 ;; Test if before or after headline title.
21226 (string (when (and (match-end 4)
21227 (not (or (< (point)
21228 (or (match-end 3)
21229 (match-end 2)
21230 (save-excursion
21231 (goto-char (match-beginning 4))
21232 (skip-chars-backward " \t")
21233 (point))))
21234 (and (match-beginning 5)
21235 (>= (point) (match-beginning 5))))))
21236 ;; Point is on headline keywords, tags or cookies. Do not break
21237 ;; them: add a newline after the headline instead.
21238 (org-string-nw-p
21239 (delete-and-extract-region (point) (match-end 4))))))
21240 ;; Adjust alignment of tags.
21241 (when (and tags-column string)
21242 (org-align-tags-here (if org-auto-align-tags
21243 org-tags-column
21244 tags-column)))
21245 (end-of-line)
21246 (org-show-entry)
21247 (if indent (newline-and-indent) (newline))
21248 (and string (save-excursion (insert (org-trim string)))))
21249 (let* ((context (if org-return-follows-link (org-element-context)
21250 (org-element-at-point)))
21251 (type (org-element-type context)))
21252 (cond
21253 ;; In a table, call `org-table-next-row'.
21254 ((or (and (eq type 'table)
21255 (>= (point) (org-element-property :contents-begin context))
21256 (< (point) (org-element-property :contents-end context)))
21257 (org-element-lineage context '(table-row table-cell) t))
21258 (org-table-justify-field-maybe)
21259 (call-interactively #'org-table-next-row))
21260 ;; On a link or a timestamp but not on white spaces after it,
21261 ;; call `org-open-line' if `org-return-follows-link' allows it.
21262 ((and org-return-follows-link
21263 (memq type '(link timestamp))
21264 (< (point)
21265 (save-excursion (goto-char (org-element-property :end context))
21266 (skip-chars-backward " \t")
21267 (point))))
21268 (call-interactively #'org-open-at-point))
21269 ;; In a list, make sure indenting keeps trailing text within.
21270 ((and indent
21271 (not (eolp))
21272 (org-element-lineage context '(item)))
21273 (let ((trailing-data
21274 (delete-and-extract-region (point) (line-end-position))))
21275 (newline-and-indent)
21276 (save-excursion (insert trailing-data))))
21277 (t (if indent (newline-and-indent) (newline)))))))
21279 (defun org-return-indent ()
21280 "Goto next table row or insert a newline and indent.
21281 Calls `org-table-next-row' or `newline-and-indent', depending on
21282 context. See the individual commands for more information."
21283 (interactive)
21284 (org-return t))
21286 (defun org-ctrl-c-star ()
21287 "Compute table, or change heading status of lines.
21288 Calls `org-table-recalculate' or `org-toggle-heading',
21289 depending on context."
21290 (interactive)
21291 (cond
21292 ((org-at-table-p)
21293 (call-interactively 'org-table-recalculate))
21295 ;; Convert all lines in region to list items
21296 (call-interactively 'org-toggle-heading))))
21298 (defun org-ctrl-c-minus ()
21299 "Insert separator line in table or modify bullet status of line.
21300 Also turns a plain line or a region of lines into list items.
21301 Calls `org-table-insert-hline', `org-toggle-item', or
21302 `org-cycle-list-bullet', depending on context."
21303 (interactive)
21304 (cond
21305 ((org-at-table-p)
21306 (call-interactively 'org-table-insert-hline))
21307 ((org-region-active-p)
21308 (call-interactively 'org-toggle-item))
21309 ((org-in-item-p)
21310 (call-interactively 'org-cycle-list-bullet))
21312 (call-interactively 'org-toggle-item))))
21314 (defun org-toggle-item (arg)
21315 "Convert headings or normal lines to items, items to normal lines.
21316 If there is no active region, only the current line is considered.
21318 If the first non blank line in the region is a headline, convert
21319 all headlines to items, shifting text accordingly.
21321 If it is an item, convert all items to normal lines.
21323 If it is normal text, change region into a list of items.
21324 With a prefix argument ARG, change the region in a single item."
21325 (interactive "P")
21326 (let ((shift-text
21327 (function
21328 ;; Shift text in current section to IND, from point to END.
21329 ;; The function leaves point to END line.
21330 (lambda (ind end)
21331 (let ((min-i 1000) (end (copy-marker end)))
21332 ;; First determine the minimum indentation (MIN-I) of
21333 ;; the text.
21334 (save-excursion
21335 (catch 'exit
21336 (while (< (point) end)
21337 (let ((i (org-get-indentation)))
21338 (cond
21339 ;; Skip blank lines and inline tasks.
21340 ((looking-at "^[ \t]*$"))
21341 ((looking-at org-outline-regexp-bol))
21342 ;; We can't find less than 0 indentation.
21343 ((zerop i) (throw 'exit (setq min-i 0)))
21344 ((< i min-i) (setq min-i i))))
21345 (forward-line))))
21346 ;; Then indent each line so that a line indented to
21347 ;; MIN-I becomes indented to IND. Ignore blank lines
21348 ;; and inline tasks in the process.
21349 (let ((delta (- ind min-i)))
21350 (while (< (point) end)
21351 (unless (or (looking-at "^[ \t]*$")
21352 (looking-at org-outline-regexp-bol))
21353 (org-indent-line-to (+ (org-get-indentation) delta)))
21354 (forward-line)))))))
21355 (skip-blanks
21356 (function
21357 ;; Return beginning of first non-blank line, starting from
21358 ;; line at POS.
21359 (lambda (pos)
21360 (save-excursion
21361 (goto-char pos)
21362 (skip-chars-forward " \r\t\n")
21363 (point-at-bol)))))
21364 beg end)
21365 ;; Determine boundaries of changes.
21366 (if (org-region-active-p)
21367 (setq beg (funcall skip-blanks (region-beginning))
21368 end (copy-marker (region-end)))
21369 (setq beg (funcall skip-blanks (point-at-bol))
21370 end (copy-marker (point-at-eol))))
21371 ;; Depending on the starting line, choose an action on the text
21372 ;; between BEG and END.
21373 (org-with-limited-levels
21374 (save-excursion
21375 (goto-char beg)
21376 (cond
21377 ;; Case 1. Start at an item: de-itemize. Note that it only
21378 ;; happens when a region is active: `org-ctrl-c-minus'
21379 ;; would call `org-cycle-list-bullet' otherwise.
21380 ((org-at-item-p)
21381 (while (< (point) end)
21382 (when (org-at-item-p)
21383 (skip-chars-forward " \t")
21384 (delete-region (point) (match-end 0)))
21385 (forward-line)))
21386 ;; Case 2. Start at an heading: convert to items.
21387 ((org-at-heading-p)
21388 (let* ((bul (org-list-bullet-string "-"))
21389 (bul-len (length bul))
21390 (done (org-entry-is-done-p))
21391 (todo (org-entry-is-todo-p))
21392 ;; Indentation of the first heading. It should be
21393 ;; relative to the indentation of its parent, if any.
21394 (start-ind (save-excursion
21395 (cond
21396 ((not org-adapt-indentation) 0)
21397 ((not (outline-previous-heading)) 0)
21398 (t (length (match-string 0))))))
21399 ;; Level of first heading. Further headings will be
21400 ;; compared to it to determine hierarchy in the list.
21401 (ref-level (org-reduced-level (org-outline-level))))
21402 (when (or done todo) (org-todo ""))
21403 (while (< (point) end)
21404 (let* ((level (org-reduced-level (org-outline-level)))
21405 (delta (max 0 (- level ref-level))))
21406 ;; If current headline is less indented than the first
21407 ;; one, set it as reference, in order to preserve
21408 ;; subtrees.
21409 (when (< level ref-level) (setq ref-level level))
21410 (replace-match bul t t)
21411 (org-indent-line-to (+ start-ind (* delta bul-len)))
21412 (when (or done todo)
21413 (let* ((struct (org-list-struct))
21414 (old (copy-tree struct)))
21415 (org-list-set-checkbox (line-beginning-position)
21416 struct
21417 (if done "[X]" "[ ]"))
21418 (org-list-write-struct struct
21419 (org-list-parents-alist struct)
21420 old)))
21421 ;; Ensure all text down to END (or SECTION-END) belongs
21422 ;; to the newly created item.
21423 (let ((section-end (save-excursion
21424 (or (outline-next-heading) (point)))))
21425 (forward-line)
21426 (funcall shift-text
21427 (+ start-ind (* (1+ delta) bul-len))
21428 (min end section-end)))))))
21429 ;; Case 3. Normal line with ARG: make the first line of region
21430 ;; an item, and shift indentation of others lines to
21431 ;; set them as item's body.
21432 (arg (let* ((bul (org-list-bullet-string "-"))
21433 (bul-len (length bul))
21434 (ref-ind (org-get-indentation)))
21435 (skip-chars-forward " \t")
21436 (insert bul)
21437 (forward-line)
21438 (while (< (point) end)
21439 ;; Ensure that lines less indented than first one
21440 ;; still get included in item body.
21441 (funcall shift-text
21442 (+ ref-ind bul-len)
21443 (min end (save-excursion (or (outline-next-heading)
21444 (point)))))
21445 (forward-line))))
21446 ;; Case 4. Normal line without ARG: turn each non-item line
21447 ;; into an item.
21449 (while (< (point) end)
21450 (unless (or (org-at-heading-p) (org-at-item-p))
21451 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21452 (replace-match
21453 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21454 (forward-line))))))))
21456 (defun org-toggle-heading (&optional nstars)
21457 "Convert headings to normal text, or items or text to headings.
21458 If there is no active region, only convert the current line.
21460 With a \\[universal-argument] prefix, convert the whole list at
21461 point into heading.
21463 In a region:
21465 - If the first non blank line is a headline, remove the stars
21466 from all headlines in the region.
21468 - If it is a normal line, turn each and every normal line (i.e.,
21469 not an heading or an item) in the region into headings. If you
21470 want to convert only the first line of this region, use one
21471 universal prefix argument.
21473 - If it is a plain list item, turn all plain list items into headings.
21475 When converting a line into a heading, the number of stars is chosen
21476 such that the lines become children of the current entry. However,
21477 when a numeric prefix argument is given, its value determines the
21478 number of stars to add."
21479 (interactive "P")
21480 (let ((skip-blanks
21481 (function
21482 ;; Return beginning of first non-blank line, starting from
21483 ;; line at POS.
21484 (lambda (pos)
21485 (save-excursion
21486 (goto-char pos)
21487 (while (org-at-comment-p) (forward-line))
21488 (skip-chars-forward " \r\t\n")
21489 (point-at-bol)))))
21490 beg end toggled)
21491 ;; Determine boundaries of changes. If a universal prefix has
21492 ;; been given, put the list in a region. If region ends at a bol,
21493 ;; do not consider the last line to be in the region.
21495 (when (and current-prefix-arg (org-at-item-p))
21496 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21497 (org-mark-element))
21499 (if (org-region-active-p)
21500 (setq beg (funcall skip-blanks (region-beginning))
21501 end (copy-marker (save-excursion
21502 (goto-char (region-end))
21503 (if (bolp) (point) (point-at-eol)))))
21504 (setq beg (funcall skip-blanks (point-at-bol))
21505 end (copy-marker (point-at-eol))))
21506 ;; Ensure inline tasks don't count as headings.
21507 (org-with-limited-levels
21508 (save-excursion
21509 (goto-char beg)
21510 (cond
21511 ;; Case 1. Started at an heading: de-star headings.
21512 ((org-at-heading-p)
21513 (while (< (point) end)
21514 (when (org-at-heading-p t)
21515 (looking-at org-outline-regexp) (replace-match "")
21516 (setq toggled t))
21517 (forward-line)))
21518 ;; Case 2. Started at an item: change items into headlines.
21519 ;; One star will be added by `org-list-to-subtree'.
21520 ((org-at-item-p)
21521 (while (< (point) end)
21522 (when (org-at-item-p)
21523 ;; Pay attention to cases when region ends before list.
21524 (let* ((struct (org-list-struct))
21525 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21526 (save-restriction
21527 (narrow-to-region (point) list-end)
21528 (insert (org-list-to-subtree (org-list-parse-list t)))))
21529 (setq toggled t))
21530 (forward-line)))
21531 ;; Case 3. Started at normal text: make every line an heading,
21532 ;; skipping headlines and items.
21533 (t (let* ((stars
21534 (make-string
21535 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21536 (add-stars
21537 (cond (nstars "") ; stars from prefix only
21538 ((equal stars "") "*") ; before first heading
21539 (org-odd-levels-only "**") ; inside heading, odd
21540 (t "*"))) ; inside heading, oddeven
21541 (rpl (concat stars add-stars " "))
21542 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21543 (while (< (point) (if (equal nstars '(4)) lend end))
21544 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21545 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21546 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21547 (forward-line)))))))
21548 (unless toggled (message "Cannot toggle heading from here"))))
21550 (defun org-meta-return (&optional arg)
21551 "Insert a new heading or wrap a region in a table.
21552 Calls `org-insert-heading' or `org-table-wrap-region', depending
21553 on context. See the individual commands for more information."
21554 (interactive "P")
21555 (org-check-before-invisible-edit 'insert)
21556 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21557 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21558 #'org-insert-heading))))
21560 ;;; Menu entries
21562 (defsubst org-in-subtree-not-table-p ()
21563 "Are we in a subtree and not in a table?"
21564 (and (not (org-before-first-heading-p))
21565 (not (org-at-table-p))))
21567 ;; Define the Org-mode menus
21568 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21569 '("Tbl"
21570 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21571 ["Next Field" org-cycle (org-at-table-p)]
21572 ["Previous Field" org-shifttab (org-at-table-p)]
21573 ["Next Row" org-return (org-at-table-p)]
21574 "--"
21575 ["Blank Field" org-table-blank-field (org-at-table-p)]
21576 ["Edit Field" org-table-edit-field (org-at-table-p)]
21577 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21578 "--"
21579 ("Column"
21580 ["Move Column Left" org-metaleft (org-at-table-p)]
21581 ["Move Column Right" org-metaright (org-at-table-p)]
21582 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21583 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21584 ("Row"
21585 ["Move Row Up" org-metaup (org-at-table-p)]
21586 ["Move Row Down" org-metadown (org-at-table-p)]
21587 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21588 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21589 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21590 "--"
21591 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21592 ("Rectangle"
21593 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21594 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21595 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21596 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21597 "--"
21598 ("Calculate"
21599 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21600 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21601 ["Edit Formulas" org-edit-special (org-at-table-p)]
21602 "--"
21603 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21604 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21605 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21606 "--"
21607 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21608 "--"
21609 ["Sum Column/Rectangle" org-table-sum
21610 (or (org-at-table-p) (org-region-active-p))]
21611 ["Which Column?" org-table-current-column (org-at-table-p)])
21612 ["Debug Formulas"
21613 org-table-toggle-formula-debugger
21614 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21615 ["Show Col/Row Numbers"
21616 org-table-toggle-coordinate-overlays
21617 :style toggle
21618 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21619 "--"
21620 ["Create" org-table-create (and (not (org-at-table-p))
21621 org-enable-table-editor)]
21622 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21623 ["Import from File" org-table-import (not (org-at-table-p))]
21624 ["Export to File" org-table-export (org-at-table-p)]
21625 "--"
21626 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21627 "--"
21628 ("Plot"
21629 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21630 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21632 (easy-menu-define org-org-menu org-mode-map "Org menu"
21633 '("Org"
21634 ("Show/Hide"
21635 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21636 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21637 ["Sparse Tree..." org-sparse-tree t]
21638 ["Reveal Context" org-reveal t]
21639 ["Show All" show-all t]
21640 "--"
21641 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21642 "--"
21643 ["New Heading" org-insert-heading t]
21644 ("Navigate Headings"
21645 ["Up" outline-up-heading t]
21646 ["Next" outline-next-visible-heading t]
21647 ["Previous" outline-previous-visible-heading t]
21648 ["Next Same Level" outline-forward-same-level t]
21649 ["Previous Same Level" outline-backward-same-level t]
21650 "--"
21651 ["Jump" org-goto t])
21652 ("Edit Structure"
21653 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21654 "--"
21655 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21656 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21657 "--"
21658 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21659 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21660 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21661 "--"
21662 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21663 "--"
21664 ["Copy visible text" org-copy-visible t]
21665 "--"
21666 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21667 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21668 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21669 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21670 "--"
21671 ["Sort Region/Children" org-sort t]
21672 "--"
21673 ["Convert to odd levels" org-convert-to-odd-levels t]
21674 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21675 ("Editing"
21676 ["Emphasis..." org-emphasize t]
21677 ["Edit Source Example" org-edit-special t]
21678 "--"
21679 ["Footnote new/jump" org-footnote-action t]
21680 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21681 ("Archive"
21682 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21683 "--"
21684 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21685 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21686 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21688 "--"
21689 ("Hyperlinks"
21690 ["Store Link (Global)" org-store-link t]
21691 ["Find existing link to here" org-occur-link-in-agenda-files t]
21692 ["Insert Link" org-insert-link t]
21693 ["Follow Link" org-open-at-point t]
21694 "--"
21695 ["Next link" org-next-link t]
21696 ["Previous link" org-previous-link t]
21697 "--"
21698 ["Descriptive Links"
21699 org-toggle-link-display
21700 :style radio
21701 :selected org-descriptive-links
21703 ["Literal Links"
21704 org-toggle-link-display
21705 :style radio
21706 :selected (not org-descriptive-links)])
21707 "--"
21708 ("TODO Lists"
21709 ["TODO/DONE/-" org-todo t]
21710 ("Select keyword"
21711 ["Next keyword" org-shiftright (org-at-heading-p)]
21712 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21713 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21714 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21715 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21716 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21717 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21718 "--"
21719 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21720 :selected org-enforce-todo-dependencies :style toggle :active t]
21721 "Settings for tree at point"
21722 ["Do Children sequentially" org-toggle-ordered-property :style radio
21723 :selected (org-entry-get nil "ORDERED")
21724 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21725 ["Do Children parallel" org-toggle-ordered-property :style radio
21726 :selected (not (org-entry-get nil "ORDERED"))
21727 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21728 "--"
21729 ["Set Priority" org-priority t]
21730 ["Priority Up" org-shiftup t]
21731 ["Priority Down" org-shiftdown t]
21732 "--"
21733 ["Get news from all feeds" org-feed-update-all t]
21734 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21735 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21736 ("TAGS and Properties"
21737 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21738 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21739 "--"
21740 ["Set property" org-set-property (not (org-before-first-heading-p))]
21741 ["Column view of properties" org-columns t]
21742 ["Insert Column View DBlock" org-insert-columns-dblock t])
21743 ("Dates and Scheduling"
21744 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21745 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21746 ("Change Date"
21747 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21748 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21749 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21750 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21751 ["Compute Time Range" org-evaluate-time-range t]
21752 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21753 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21754 "--"
21755 ["Custom time format" org-toggle-time-stamp-overlays
21756 :style radio :selected org-display-custom-times]
21757 "--"
21758 ["Goto Calendar" org-goto-calendar t]
21759 ["Date from Calendar" org-date-from-calendar t]
21760 "--"
21761 ["Start/Restart Timer" org-timer-start t]
21762 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21763 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21764 ["Insert Timer String" org-timer t]
21765 ["Insert Timer Item" org-timer-item t])
21766 ("Logging work"
21767 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21768 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21769 ["Clock out" org-clock-out t]
21770 ["Clock cancel" org-clock-cancel t]
21771 "--"
21772 ["Mark as default task" org-clock-mark-default-task t]
21773 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21774 ["Goto running clock" org-clock-goto t]
21775 "--"
21776 ["Display times" org-clock-display t]
21777 ["Create clock table" org-clock-report t]
21778 "--"
21779 ["Record DONE time"
21780 (progn (setq org-log-done (not org-log-done))
21781 (message "Switching to %s will %s record a timestamp"
21782 (car org-done-keywords)
21783 (if org-log-done "automatically" "not")))
21784 :style toggle :selected org-log-done])
21785 "--"
21786 ["Agenda Command..." org-agenda t]
21787 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21788 ("File List for Agenda")
21789 ("Special views current file"
21790 ["TODO Tree" org-show-todo-tree t]
21791 ["Check Deadlines" org-check-deadlines t]
21792 ["Timeline" org-timeline t]
21793 ["Tags/Property tree" org-match-sparse-tree t])
21794 "--"
21795 ["Export/Publish..." org-export-dispatch t]
21796 ("LaTeX"
21797 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21798 :selected org-cdlatex-mode]
21799 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21800 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21801 ["Modify math symbol" org-cdlatex-math-modify
21802 (org-inside-LaTeX-fragment-p)]
21803 ["Insert citation" org-reftex-citation t]
21804 "--"
21805 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21806 "--"
21807 ("MobileOrg"
21808 ["Push Files and Views" org-mobile-push t]
21809 ["Get Captured and Flagged" org-mobile-pull t]
21810 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21811 "--"
21812 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21813 "--"
21814 ("Documentation"
21815 ["Show Version" org-version t]
21816 ["Info Documentation" org-info t])
21817 ("Customize"
21818 ["Browse Org Group" org-customize t]
21819 "--"
21820 ["Expand This Menu" org-create-customize-menu
21821 (fboundp 'customize-menu-create)])
21822 ["Send bug report" org-submit-bug-report t]
21823 "--"
21824 ("Refresh/Reload"
21825 ["Refresh setup current buffer" org-mode-restart t]
21826 ["Reload Org (after update)" org-reload t]
21827 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21830 (defun org-info (&optional node)
21831 "Read documentation for Org-mode in the info system.
21832 With optional NODE, go directly to that node."
21833 (interactive)
21834 (info (format "(org)%s" (or node ""))))
21836 ;;;###autoload
21837 (defun org-submit-bug-report ()
21838 "Submit a bug report on Org-mode via mail.
21840 Don't hesitate to report any problems or inaccurate documentation.
21842 If you don't have setup sending mail from (X)Emacs, please copy the
21843 output buffer into your mail program, as it gives us important
21844 information about your Org-mode version and configuration."
21845 (interactive)
21846 (require 'reporter)
21847 (org-load-modules-maybe)
21848 (org-require-autoloaded-modules)
21849 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21850 (reporter-submit-bug-report
21851 "emacs-orgmode@gnu.org"
21852 (org-version nil 'full)
21853 (let (list)
21854 (save-window-excursion
21855 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21856 (delete-other-windows)
21857 (erase-buffer)
21858 (insert "You are about to submit a bug report to the Org-mode mailing list.
21860 We would like to add your full Org-mode and Outline configuration to the
21861 bug report. This greatly simplifies the work of the maintainer and
21862 other experts on the mailing list.
21864 HOWEVER, some variables you have customized may contain private
21865 information. The names of customers, colleagues, or friends, might
21866 appear in the form of file names, tags, todo states, or search strings.
21867 If you answer yes to the prompt, you might want to check and remove
21868 such private information before sending the email.")
21869 (add-text-properties (point-min) (point-max) '(face org-warning))
21870 (when (yes-or-no-p "Include your Org-mode configuration ")
21871 (mapatoms
21872 (lambda (v)
21873 (and (boundp v)
21874 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21875 (or (and (symbol-value v)
21876 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21877 (and
21878 (get v 'custom-type) (get v 'standard-value)
21879 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21880 (push v list)))))
21881 (kill-buffer (get-buffer "*Warn about privacy*"))
21882 list))
21883 nil nil
21884 "Remember to cover the basics, that is, what you expected to happen and
21885 what in fact did happen. You don't know how to make a good report? See
21887 http://orgmode.org/manual/Feedback.html#Feedback
21889 Your bug report will be posted to the Org-mode mailing list.
21890 ------------------------------------------------------------------------")
21891 (save-excursion
21892 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21893 (replace-match "\\1Bug: \\3 [\\2]")))))
21896 (defun org-install-agenda-files-menu ()
21897 (let ((bl (buffer-list)))
21898 (save-excursion
21899 (while bl
21900 (set-buffer (pop bl))
21901 (if (derived-mode-p 'org-mode) (setq bl nil)))
21902 (when (derived-mode-p 'org-mode)
21903 (easy-menu-change
21904 '("Org") "File List for Agenda"
21905 (append
21906 (list
21907 ["Edit File List" (org-edit-agenda-file-list) t]
21908 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21909 ["Remove Current File from List" org-remove-file t]
21910 ["Cycle through agenda files" org-cycle-agenda-files t]
21911 ["Occur in all agenda files" org-occur-in-agenda-files t]
21912 "--")
21913 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21915 ;;;; Documentation
21917 (defun org-require-autoloaded-modules ()
21918 (interactive)
21919 (mapc 'require
21920 '(org-agenda org-archive org-attach org-clock org-colview org-id
21921 org-table org-timer)))
21923 ;;;###autoload
21924 (defun org-reload (&optional uncompiled)
21925 "Reload all org lisp files.
21926 With prefix arg UNCOMPILED, load the uncompiled versions."
21927 (interactive "P")
21928 (require 'loadhist)
21929 (let* ((org-dir (org-find-library-dir "org"))
21930 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21931 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21932 (remove-re (mapconcat 'identity
21933 (mapcar (lambda (f) (concat "^" f "$"))
21934 (list (if (featurep 'xemacs)
21935 "org-colview"
21936 "org-colview-xemacs")
21937 "org" "org-loaddefs" "org-version"))
21938 "\\|"))
21939 (feats (delete-dups
21940 (mapcar 'file-name-sans-extension
21941 (mapcar 'file-name-nondirectory
21942 (delq nil
21943 (mapcar 'feature-file
21944 features))))))
21945 (lfeat (append
21946 (sort
21947 (setq feats
21948 (delq nil (mapcar
21949 (lambda (f)
21950 (if (and (string-match feature-re f)
21951 (not (string-match remove-re f)))
21952 f nil))
21953 feats)))
21954 'string-lessp)
21955 (list "org-version" "org")))
21956 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21957 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21958 load-uncore load-misses)
21959 (setq load-misses
21960 (delq 't
21961 (mapcar (lambda (f)
21962 (or (org-load-noerror-mustsuffix (concat org-dir f))
21963 (and (string= org-dir contrib-dir)
21964 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21965 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21966 (add-to-list 'load-uncore f 'append)
21969 lfeat)))
21970 (if load-uncore
21971 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21972 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21973 (if load-misses
21974 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21975 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21976 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21978 ;;;###autoload
21979 (defun org-customize ()
21980 "Call the customize function with org as argument."
21981 (interactive)
21982 (org-load-modules-maybe)
21983 (org-require-autoloaded-modules)
21984 (customize-browse 'org))
21986 (defun org-create-customize-menu ()
21987 "Create a full customization menu for Org-mode, insert it into the menu."
21988 (interactive)
21989 (org-load-modules-maybe)
21990 (org-require-autoloaded-modules)
21991 (if (fboundp 'customize-menu-create)
21992 (progn
21993 (easy-menu-change
21994 '("Org") "Customize"
21995 `(["Browse Org group" org-customize t]
21996 "--"
21997 ,(customize-menu-create 'org)
21998 ["Set" Custom-set t]
21999 ["Save" Custom-save t]
22000 ["Reset to Current" Custom-reset-current t]
22001 ["Reset to Saved" Custom-reset-saved t]
22002 ["Reset to Standard Settings" Custom-reset-standard t]))
22003 (message "\"Org\"-menu now contains full customization menu"))
22004 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22006 ;;;; Miscellaneous stuff
22008 ;;; Generally useful functions
22010 (defsubst org-get-at-eol (property n)
22011 "Get text property PROPERTY at the end of line less N characters."
22012 (get-text-property (- (point-at-eol) n) property))
22014 (defun org-find-text-property-in-string (prop s)
22015 "Return the first non-nil value of property PROP in string S."
22016 (or (get-text-property 0 prop s)
22017 (get-text-property (or (next-single-property-change 0 prop s) 0)
22018 prop s)))
22020 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22021 "Display the given MESSAGE as a warning."
22022 (if (fboundp 'display-warning)
22023 (display-warning 'org message
22024 (if (featurep 'xemacs) 'warning :warning))
22025 (let ((buf (get-buffer-create "*Org warnings*")))
22026 (with-current-buffer buf
22027 (goto-char (point-max))
22028 (insert "Warning (Org): " message)
22029 (unless (bolp)
22030 (newline)))
22031 (display-buffer buf)
22032 (sit-for 0))))
22034 (defun org-eval (form)
22035 "Eval FORM and return result."
22036 (condition-case error
22037 (eval form)
22038 (error (format "%%![Error: %s]" error))))
22040 (defun org-in-clocktable-p ()
22041 "Check if the cursor is in a clocktable."
22042 (let ((pos (point)) start)
22043 (save-excursion
22044 (end-of-line 1)
22045 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22046 (setq start (match-beginning 0))
22047 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22048 (>= (match-end 0) pos)
22049 start))))
22051 (defun org-in-verbatim-emphasis ()
22052 (save-match-data
22053 (and (org-in-regexp org-emph-re 2)
22054 (>= (point) (match-beginning 3))
22055 (<= (point) (match-end 4))
22056 (member (match-string 3) '("=" "~")))))
22058 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22059 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22060 (if (and marker (marker-buffer marker)
22061 (buffer-live-p (marker-buffer marker)))
22062 (progn
22063 (org-pop-to-buffer-same-window (marker-buffer marker))
22064 (if (or (> marker (point-max)) (< marker (point-min)))
22065 (widen))
22066 (goto-char marker)
22067 (org-show-context 'org-goto))
22068 (if bookmark
22069 (bookmark-jump bookmark)
22070 (error "Cannot find location"))))
22072 (defun org-quote-csv-field (s)
22073 "Quote field for inclusion in CSV material."
22074 (if (string-match "[\",]" s)
22075 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22078 (defun org-force-self-insert (N)
22079 "Needed to enforce self-insert under remapping."
22080 (interactive "p")
22081 (self-insert-command N))
22083 (defun org-string-width (s)
22084 "Compute width of string, ignoring invisible characters.
22085 This ignores character with invisibility property `org-link', and also
22086 characters with property `org-cwidth', because these will become invisible
22087 upon the next fontification round."
22088 (let (b l)
22089 (when (or (eq t buffer-invisibility-spec)
22090 (assq 'org-link buffer-invisibility-spec))
22091 (while (setq b (text-property-any 0 (length s)
22092 'invisible 'org-link s))
22093 (setq s (concat (substring s 0 b)
22094 (substring s (or (next-single-property-change
22095 b 'invisible s) (length s)))))))
22096 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22097 (setq s (concat (substring s 0 b)
22098 (substring s (or (next-single-property-change
22099 b 'org-cwidth s) (length s))))))
22100 (setq l (string-width s) b -1)
22101 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22102 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22105 (defun org-shorten-string (s maxlength)
22106 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22107 If the string is shorter or has length MAXLENGTH, just return the
22108 original string. If it is longer, the functions finds a space in the
22109 string, breaks this string off at that locations and adds three dots
22110 as ellipsis. Including the ellipsis, the string will not be longer
22111 than MAXLENGTH. If finding a good breaking point in the string does
22112 not work, the string is just chopped off in the middle of a word
22113 if necessary."
22114 (if (<= (length s) maxlength)
22116 (let* ((n (max (- maxlength 4) 1))
22117 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22118 (if (string-match re s)
22119 (concat (match-string 1 s) "...")
22120 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22122 (defun org-get-indentation (&optional line)
22123 "Get the indentation of the current line, interpreting tabs.
22124 When LINE is given, assume it represents a line and compute its indentation."
22125 (if line
22126 (if (string-match "^ *" (org-remove-tabs line))
22127 (match-end 0))
22128 (save-excursion
22129 (beginning-of-line 1)
22130 (skip-chars-forward " \t")
22131 (current-column))))
22133 (defun org-get-string-indentation (s)
22134 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22135 (let ((n -1) (i 0) (w tab-width) c)
22136 (catch 'exit
22137 (while (< (setq n (1+ n)) (length s))
22138 (setq c (aref s n))
22139 (cond ((= c ?\ ) (setq i (1+ i)))
22140 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22141 (t (throw 'exit t)))))
22144 (defun org-remove-tabs (s &optional width)
22145 "Replace tabulators in S with spaces.
22146 Assumes that s is a single line, starting in column 0."
22147 (setq width (or width tab-width))
22148 (while (string-match "\t" s)
22149 (setq s (replace-match
22150 (make-string
22151 (- (* width (/ (+ (match-beginning 0) width) width))
22152 (match-beginning 0)) ?\ )
22153 t t s)))
22156 (defun org-fix-indentation (line ind)
22157 "Fix indentation in LINE.
22158 IND is a cons cell with target and minimum indentation.
22159 If the current indentation in LINE is smaller than the minimum,
22160 leave it alone. If it is larger than ind, set it to the target."
22161 (let* ((l (org-remove-tabs line))
22162 (i (org-get-indentation l))
22163 (i1 (car ind)) (i2 (cdr ind)))
22164 (if (>= i i2) (setq l (substring line i2)))
22165 (if (> i1 0)
22166 (concat (make-string i1 ?\ ) l)
22167 l)))
22169 (defun org-remove-indentation (code &optional n)
22170 "Remove the maximum common indentation from the lines in CODE.
22171 N may optionally be the number of spaces to remove."
22172 (with-temp-buffer
22173 (insert code)
22174 (org-do-remove-indentation n)
22175 (buffer-string)))
22177 (defun org-do-remove-indentation (&optional n)
22178 "Remove the maximum common indentation from the buffer."
22179 (untabify (point-min) (point-max))
22180 (let ((min 10000) re)
22181 (if n
22182 (setq min n)
22183 (goto-char (point-min))
22184 (while (re-search-forward "^ *[^ \n]" nil t)
22185 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
22186 (unless (or (= min 0) (= min 10000))
22187 (setq re (format "^ \\{%d\\}" min))
22188 (goto-char (point-min))
22189 (while (re-search-forward re nil t)
22190 (replace-match "")
22191 (end-of-line 1))
22192 min)))
22194 (defun org-fill-template (template alist)
22195 "Find each %key of ALIST in TEMPLATE and replace it."
22196 (let ((case-fold-search nil)
22197 entry key value)
22198 (setq alist (sort (copy-sequence alist)
22199 (lambda (a b) (< (length (car a)) (length (car b))))))
22200 (while (setq entry (pop alist))
22201 (setq template
22202 (replace-regexp-in-string
22203 (concat "%" (regexp-quote (car entry)))
22204 (or (cdr entry) "") template t t)))
22205 template))
22207 (defun org-base-buffer (buffer)
22208 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22209 (if (not buffer)
22210 buffer
22211 (or (buffer-base-buffer buffer)
22212 buffer)))
22214 (defun org-wrap (string &optional width lines)
22215 "Wrap string to either a number of lines, or a width in characters.
22216 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22217 that costs. If there is a word longer than WIDTH, the text is actually
22218 wrapped to the length of that word.
22219 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22220 many lines, whatever width that takes.
22221 The return value is a list of lines, without newlines at the end."
22222 (let* ((words (org-split-string string "[ \t\n]+"))
22223 (maxword (apply 'max (mapcar 'org-string-width words)))
22224 w ll)
22225 (cond (width
22226 (org-do-wrap words (max maxword width)))
22227 (lines
22228 (setq w maxword)
22229 (setq ll (org-do-wrap words maxword))
22230 (if (<= (length ll) lines)
22232 (setq ll words)
22233 (while (> (length ll) lines)
22234 (setq w (1+ w))
22235 (setq ll (org-do-wrap words w)))
22236 ll))
22237 (t (error "Cannot wrap this")))))
22239 (defun org-do-wrap (words width)
22240 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22241 (let (lines line)
22242 (while words
22243 (setq line (pop words))
22244 (while (and words (< (+ (length line) (length (car words))) width))
22245 (setq line (concat line " " (pop words))))
22246 (setq lines (push line lines)))
22247 (nreverse lines)))
22249 (defun org-split-string (string &optional separators)
22250 "Splits STRING into substrings at SEPARATORS.
22251 No empty strings are returned if there are matches at the beginning
22252 and end of string."
22253 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
22254 (start 0)
22255 notfirst
22256 (list nil))
22257 (while (and (string-match rexp string
22258 (if (and notfirst
22259 (= start (match-beginning 0))
22260 (< start (length string)))
22261 (1+ start) start))
22262 (< (match-beginning 0) (length string)))
22263 (setq notfirst t)
22264 (or (eq (match-beginning 0) 0)
22265 (and (eq (match-beginning 0) (match-end 0))
22266 (eq (match-beginning 0) start))
22267 (setq list
22268 (cons (substring string start (match-beginning 0))
22269 list)))
22270 (setq start (match-end 0)))
22271 (or (eq start (length string))
22272 (setq list
22273 (cons (substring string start)
22274 list)))
22275 (nreverse list)))
22277 (defun org-quote-vert (s)
22278 "Replace \"|\" with \"\\vert\"."
22279 (while (string-match "|" s)
22280 (setq s (replace-match "\\vert" t t s)))
22283 (defun org-uuidgen-p (s)
22284 "Is S an ID created by UUIDGEN?"
22285 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22287 (defun org-in-src-block-p (&optional inside)
22288 "Whether point is in a code source block.
22289 When INSIDE is non-nil, don't consider we are within a src block
22290 when point is at #+BEGIN_SRC or #+END_SRC."
22291 (let ((case-fold-search t) ov)
22292 (or (and (eq (get-char-property (point) 'src-block) t))
22293 (and (not inside)
22294 (save-match-data
22295 (save-excursion
22296 (beginning-of-line)
22297 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22299 (defun org-context ()
22300 "Return a list of contexts of the current cursor position.
22301 If several contexts apply, all are returned.
22302 Each context entry is a list with a symbol naming the context, and
22303 two positions indicating start and end of the context. Possible
22304 contexts are:
22306 :headline anywhere in a headline
22307 :headline-stars on the leading stars in a headline
22308 :todo-keyword on a TODO keyword (including DONE) in a headline
22309 :tags on the TAGS in a headline
22310 :priority on the priority cookie in a headline
22311 :item on the first line of a plain list item
22312 :item-bullet on the bullet/number of a plain list item
22313 :checkbox on the checkbox in a plain list item
22314 :table in an org-mode table
22315 :table-special on a special filed in a table
22316 :table-table in a table.el table
22317 :clocktable in a clocktable
22318 :src-block in a source block
22319 :link on a hyperlink
22320 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22321 :target on a <<target>>
22322 :radio-target on a <<<radio-target>>>
22323 :latex-fragment on a LaTeX fragment
22324 :latex-preview on a LaTeX fragment with overlaid preview image
22326 This function expects the position to be visible because it uses font-lock
22327 faces as a help to recognize the following contexts: :table-special, :link,
22328 and :keyword."
22329 (let* ((f (get-text-property (point) 'face))
22330 (faces (if (listp f) f (list f)))
22331 (case-fold-search t)
22332 (p (point)) clist o)
22333 ;; First the large context
22334 (cond
22335 ((org-at-heading-p t)
22336 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22337 (when (progn
22338 (beginning-of-line 1)
22339 (looking-at org-todo-line-tags-regexp))
22340 (push (org-point-in-group p 1 :headline-stars) clist)
22341 (push (org-point-in-group p 2 :todo-keyword) clist)
22342 (push (org-point-in-group p 4 :tags) clist))
22343 (goto-char p)
22344 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22345 (if (looking-at "\\[#[A-Z0-9]\\]")
22346 (push (org-point-in-group p 0 :priority) clist)))
22348 ((org-at-item-p)
22349 (push (org-point-in-group p 2 :item-bullet) clist)
22350 (push (list :item (point-at-bol)
22351 (save-excursion (org-end-of-item) (point)))
22352 clist)
22353 (and (org-at-item-checkbox-p)
22354 (push (org-point-in-group p 0 :checkbox) clist)))
22356 ((org-at-table-p)
22357 (push (list :table (org-table-begin) (org-table-end)) clist)
22358 (if (memq 'org-formula faces)
22359 (push (list :table-special
22360 (previous-single-property-change p 'face)
22361 (next-single-property-change p 'face)) clist)))
22362 ((org-at-table-p 'any)
22363 (push (list :table-table) clist)))
22364 (goto-char p)
22366 (let ((case-fold-search t))
22367 ;; New the "medium" contexts: clocktables, source blocks
22368 (cond ((org-in-clocktable-p)
22369 (push (list :clocktable
22370 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22371 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22372 (match-beginning 1))
22373 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22374 (match-end 0))) clist))
22375 ((org-in-src-block-p)
22376 (push (list :src-block
22377 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22378 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22379 (match-beginning 1))
22380 (and (search-forward "#+END_SRC" nil t)
22381 (match-beginning 0))) clist))))
22382 (goto-char p)
22384 ;; Now the small context
22385 (cond
22386 ((org-at-timestamp-p)
22387 (push (org-point-in-group p 0 :timestamp) clist))
22388 ((memq 'org-link faces)
22389 (push (list :link
22390 (previous-single-property-change p 'face)
22391 (next-single-property-change p 'face)) clist))
22392 ((memq 'org-special-keyword faces)
22393 (push (list :keyword
22394 (previous-single-property-change p 'face)
22395 (next-single-property-change p 'face)) clist))
22396 ((org-at-target-p)
22397 (push (org-point-in-group p 0 :target) clist)
22398 (goto-char (1- (match-beginning 0)))
22399 (if (looking-at org-radio-target-regexp)
22400 (push (org-point-in-group p 0 :radio-target) clist))
22401 (goto-char p))
22402 ((setq o (car (delq nil
22403 (mapcar
22404 (lambda (x)
22405 (if (memq x org-latex-fragment-image-overlays) x))
22406 (overlays-at (point))))))
22407 (push (list :latex-fragment
22408 (overlay-start o) (overlay-end o)) clist)
22409 (push (list :latex-preview
22410 (overlay-start o) (overlay-end o)) clist))
22411 ((org-inside-LaTeX-fragment-p)
22412 ;; FIXME: positions wrong.
22413 (push (list :latex-fragment (point) (point)) clist)))
22415 (setq clist (nreverse (delq nil clist)))
22416 clist))
22418 (defun org-in-regexp (re &optional nlines visually)
22419 "Check if point is inside a match of RE.
22421 Normally only the current line is checked, but you can include
22422 NLINES extra lines after point into the search. If VISUALLY is
22423 set, require that the cursor is not after the match but really
22424 on, so that the block visually is on the match."
22425 (catch 'exit
22426 (let ((pos (point))
22427 (eol (point-at-eol (+ 1 (or nlines 0))))
22428 (inc (if visually 1 0)))
22429 (save-excursion
22430 (beginning-of-line (- 1 (or nlines 0)))
22431 (while (re-search-forward re eol t)
22432 (if (and (<= (match-beginning 0) pos)
22433 (>= (+ inc (match-end 0)) pos))
22434 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22435 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22436 "Org mode 8.3")
22438 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22439 "Non-nil when point is between matches of START-RE and END-RE.
22441 Also return a non-nil value when point is on one of the matches.
22443 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22444 buffer positions. Default values are the positions of headlines
22445 surrounding the point.
22447 The functions returns a cons cell whose car (resp. cdr) is the
22448 position before START-RE (resp. after END-RE)."
22449 (save-match-data
22450 (let ((pos (point))
22451 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22452 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22453 beg end)
22454 (save-excursion
22455 ;; Point is on a block when on START-RE or if START-RE can be
22456 ;; found before it...
22457 (and (or (org-in-regexp start-re)
22458 (re-search-backward start-re limit-up t))
22459 (setq beg (match-beginning 0))
22460 ;; ... and END-RE after it...
22461 (goto-char (match-end 0))
22462 (re-search-forward end-re limit-down t)
22463 (> (setq end (match-end 0)) pos)
22464 ;; ... without another START-RE in-between.
22465 (goto-char (match-beginning 0))
22466 (not (re-search-backward start-re (1+ beg) t))
22467 ;; Return value.
22468 (cons beg end))))))
22470 (defun org-in-block-p (names)
22471 "Non-nil when point belongs to a block whose name belongs to NAMES.
22473 NAMES is a list of strings containing names of blocks.
22475 Return first block name matched, or nil. Beware that in case of
22476 nested blocks, the returned name may not belong to the closest
22477 block from point."
22478 (save-match-data
22479 (catch 'exit
22480 (let ((case-fold-search t)
22481 (lim-up (save-excursion (outline-previous-heading)))
22482 (lim-down (save-excursion (outline-next-heading))))
22483 (mapc (lambda (name)
22484 (let ((n (regexp-quote name)))
22485 (when (org-between-regexps-p
22486 (concat "^[ \t]*#\\+begin_" n)
22487 (concat "^[ \t]*#\\+end_" n)
22488 lim-up lim-down)
22489 (throw 'exit n))))
22490 names))
22491 nil)))
22493 (defun org-occur-in-agenda-files (regexp &optional nlines)
22494 "Call `multi-occur' with buffers for all agenda files."
22495 (interactive "sOrg-files matching: \np")
22496 (let* ((files (org-agenda-files))
22497 (tnames (mapcar 'file-truename files))
22498 (extra org-agenda-text-search-extra-files)
22500 (when (eq (car extra) 'agenda-archives)
22501 (setq extra (cdr extra))
22502 (setq files (org-add-archive-files files)))
22503 (while (setq f (pop extra))
22504 (unless (member (file-truename f) tnames)
22505 (add-to-list 'files f 'append)
22506 (add-to-list 'tnames (file-truename f) 'append)))
22507 (multi-occur
22508 (mapcar (lambda (x)
22509 (with-current-buffer
22510 (or (get-file-buffer x) (find-file-noselect x))
22511 (widen)
22512 (current-buffer)))
22513 files)
22514 regexp)))
22516 (if (boundp 'occur-mode-find-occurrence-hook)
22517 ;; Emacs 23
22518 (add-hook 'occur-mode-find-occurrence-hook
22519 (lambda ()
22520 (when (derived-mode-p 'org-mode)
22521 (org-reveal))))
22522 ;; Emacs 22
22523 (defadvice occur-mode-goto-occurrence
22524 (after org-occur-reveal activate)
22525 (and (derived-mode-p 'org-mode) (org-reveal)))
22526 (defadvice occur-mode-goto-occurrence-other-window
22527 (after org-occur-reveal activate)
22528 (and (derived-mode-p 'org-mode) (org-reveal)))
22529 (defadvice occur-mode-display-occurrence
22530 (after org-occur-reveal activate)
22531 (when (derived-mode-p 'org-mode)
22532 (let ((pos (occur-mode-find-occurrence)))
22533 (with-current-buffer (marker-buffer pos)
22534 (save-excursion
22535 (goto-char pos)
22536 (org-reveal)))))))
22538 (defun org-occur-link-in-agenda-files ()
22539 "Create a link and search for it in the agendas.
22540 The link is not stored in `org-stored-links', it is just created
22541 for the search purpose."
22542 (interactive)
22543 (let ((link (condition-case nil
22544 (org-store-link nil)
22545 (error "Unable to create a link to here"))))
22546 (org-occur-in-agenda-files (regexp-quote link))))
22548 (defun org-reverse-string (string)
22549 "Return the reverse of STRING."
22550 (apply 'string (reverse (string-to-list string))))
22552 ;; defsubst org-uniquify must be defined before first use
22554 (defun org-uniquify-alist (alist)
22555 "Merge elements of ALIST with the same key.
22557 For example, in this alist:
22559 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22560 => '((a 1 3) (b 2))
22562 merge (a 1) and (a 3) into (a 1 3).
22564 The function returns the new ALIST."
22565 (let (rtn)
22566 (mapc
22567 (lambda (e)
22568 (let (n)
22569 (if (not (assoc (car e) rtn))
22570 (push e rtn)
22571 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22572 (setq rtn (assq-delete-all (car e) rtn))
22573 (push n rtn))))
22574 alist)
22575 rtn))
22577 (defun org-delete-all (elts list)
22578 "Remove all elements in ELTS from LIST."
22579 (while elts
22580 (setq list (delete (pop elts) list)))
22581 list)
22583 (defun org-count (cl-item cl-seq)
22584 "Count the number of occurrences of ITEM in SEQ.
22585 Taken from `count' in cl-seq.el with all keyword arguments removed."
22586 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22587 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22588 (while (< cl-start cl-end)
22589 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22590 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22591 (setq cl-start (1+ cl-start)))
22592 cl-count))
22594 (defun org-remove-if (predicate seq)
22595 "Remove everything from SEQ that fulfills PREDICATE."
22596 (let (res e)
22597 (while seq
22598 (setq e (pop seq))
22599 (if (not (funcall predicate e)) (push e res)))
22600 (nreverse res)))
22602 (defun org-remove-if-not (predicate seq)
22603 "Remove everything from SEQ that does not fulfill PREDICATE."
22604 (let (res e)
22605 (while seq
22606 (setq e (pop seq))
22607 (if (funcall predicate e) (push e res)))
22608 (nreverse res)))
22610 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22611 "Reduce two-argument FUNCTION across SEQ.
22612 Taken from `reduce' in cl-seq.el with all keyword arguments but
22613 \":initial-value\" removed."
22614 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22615 (cadr (memq :initial-value cl-keys)))
22616 (cl-seq (pop cl-seq))
22617 (t (funcall cl-func)))))
22618 (while cl-seq
22619 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22620 cl-accum))
22622 (defun org-every (pred seq)
22623 "Return true if PREDICATE is true of every element of SEQ.
22624 Adapted from `every' in cl.el."
22625 (catch 'org-every
22626 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22629 (defun org-some (pred seq)
22630 "Return true if PREDICATE is true of any element of SEQ.
22631 Adapted from `some' in cl.el."
22632 (catch 'org-some
22633 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22634 nil))
22636 (defun org-back-over-empty-lines ()
22637 "Move backwards over whitespace, to the beginning of the first empty line.
22638 Returns the number of empty lines passed."
22639 (let ((pos (point)))
22640 (if (cdr (assoc 'heading org-blank-before-new-entry))
22641 (skip-chars-backward " \t\n\r")
22642 (unless (eobp)
22643 (forward-line -1)))
22644 (beginning-of-line 2)
22645 (goto-char (min (point) pos))
22646 (count-lines (point) pos)))
22648 (defun org-skip-whitespace ()
22649 (skip-chars-forward " \t\n\r"))
22651 (defun org-point-in-group (point group &optional context)
22652 "Check if POINT is in match-group GROUP.
22653 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22654 match. If the match group does not exist or point is not inside it,
22655 return nil."
22656 (and (match-beginning group)
22657 (>= point (match-beginning group))
22658 (<= point (match-end group))
22659 (if context
22660 (list context (match-beginning group) (match-end group))
22661 t)))
22663 (defun org-switch-to-buffer-other-window (&rest args)
22664 "Switch to buffer in a second window on the current frame.
22665 In particular, do not allow pop-up frames.
22666 Returns the newly created buffer."
22667 (org-no-popups
22668 (apply 'switch-to-buffer-other-window args)))
22670 (defun org-combine-plists (&rest plists)
22671 "Create a single property list from all plists in PLISTS.
22672 The process starts by copying the first list, and then setting properties
22673 from the other lists. Settings in the last list are the most significant
22674 ones and overrule settings in the other lists."
22675 (let ((rtn (copy-sequence (pop plists)))
22676 p v ls)
22677 (while plists
22678 (setq ls (pop plists))
22679 (while ls
22680 (setq p (pop ls) v (pop ls))
22681 (setq rtn (plist-put rtn p v))))
22682 rtn))
22684 (defun org-replace-escapes (string table)
22685 "Replace %-escapes in STRING with values in TABLE.
22686 TABLE is an association list with keys like \"%a\" and string values.
22687 The sequences in STRING may contain normal field width and padding information,
22688 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22689 so values can contain further %-escapes if they are define later in TABLE."
22690 (let ((tbl (copy-alist table))
22691 (case-fold-search nil)
22692 (pchg 0)
22693 e re rpl)
22694 (while (setq e (pop tbl))
22695 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22696 (when (and (cdr e) (string-match re (cdr e)))
22697 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22698 (safe "SREF"))
22699 (add-text-properties 0 3 (list 'sref sref) safe)
22700 (setcdr e (replace-match safe t t (cdr e)))))
22701 (while (string-match re string)
22702 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22703 (cdr e)))
22704 (setq string (replace-match rpl t t string))))
22705 (while (setq pchg (next-property-change pchg string))
22706 (let ((sref (get-text-property pchg 'sref string)))
22707 (when (and sref (string-match "SREF" string pchg))
22708 (setq string (replace-match sref t t string)))))
22709 string))
22711 (defun org-sublist (list start end)
22712 "Return a section of LIST, from START to END.
22713 Counting starts at 1."
22714 (let (rtn (c start))
22715 (setq list (nthcdr (1- start) list))
22716 (while (and list (<= c end))
22717 (push (pop list) rtn)
22718 (setq c (1+ c)))
22719 (nreverse rtn)))
22721 (defun org-find-base-buffer-visiting (file)
22722 "Like `find-buffer-visiting' but always return the base buffer and
22723 not an indirect buffer."
22724 (let ((buf (or (get-file-buffer file)
22725 (find-buffer-visiting file))))
22726 (if buf
22727 (or (buffer-base-buffer buf) buf)
22728 nil)))
22730 (defun org-image-file-name-regexp (&optional extensions)
22731 "Return regexp matching the file names of images.
22732 If EXTENSIONS is given, only match these."
22733 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22734 (image-file-name-regexp)
22735 (let ((image-file-name-extensions
22736 (or extensions
22737 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22738 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22739 (concat "\\."
22740 (regexp-opt (nconc (mapcar 'upcase
22741 image-file-name-extensions)
22742 image-file-name-extensions)
22744 "\\'"))))
22746 (defun org-file-image-p (file &optional extensions)
22747 "Return non-nil if FILE is an image."
22748 (save-match-data
22749 (string-match (org-image-file-name-regexp extensions) file)))
22751 (defun org-get-cursor-date (&optional with-time)
22752 "Return the date at cursor in as a time.
22753 This works in the calendar and in the agenda, anywhere else it just
22754 returns the current time.
22755 If WITH-TIME is non-nil, returns the time of the event at point (in
22756 the agenda) or the current time of the day."
22757 (let (date day defd tp tm hod mod)
22758 (when with-time
22759 (setq tp (get-text-property (point) 'time))
22760 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22761 (setq hod (string-to-number (match-string 1 tp))
22762 mod (string-to-number (match-string 2 tp))))
22763 (or tp (setq hod (nth 2 (decode-time (current-time)))
22764 mod (nth 1 (decode-time (current-time))))))
22765 (cond
22766 ((eq major-mode 'calendar-mode)
22767 (setq date (calendar-cursor-to-date)
22768 defd (encode-time 0 (or mod 0) (or hod 0)
22769 (nth 1 date) (nth 0 date) (nth 2 date))))
22770 ((eq major-mode 'org-agenda-mode)
22771 (setq day (get-text-property (point) 'day))
22772 (if day
22773 (setq date (calendar-gregorian-from-absolute day)
22774 defd (encode-time 0 (or mod 0) (or hod 0)
22775 (nth 1 date) (nth 0 date) (nth 2 date))))))
22776 (or defd (current-time))))
22778 (defun org-mark-subtree (&optional up)
22779 "Mark the current subtree.
22780 This puts point at the start of the current subtree, and mark at
22781 the end. If a numeric prefix UP is given, move up into the
22782 hierarchy of headlines by UP levels before marking the subtree."
22783 (interactive "P")
22784 (org-with-limited-levels
22785 (cond ((org-at-heading-p) (beginning-of-line))
22786 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22787 (t (outline-previous-visible-heading 1))))
22788 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22789 (if (org-called-interactively-p 'any)
22790 (call-interactively 'org-mark-element)
22791 (org-mark-element)))
22794 ;;; Indentation
22796 (defun org--get-expected-indentation (element contentsp)
22797 "Expected indentation column for current line, according to ELEMENT.
22798 ELEMENT is an element containing point. CONTENTSP is non-nil
22799 when indentation is to be computed according to contents of
22800 ELEMENT."
22801 (let ((type (org-element-type element))
22802 (start (org-element-property :begin element))
22803 (post-affiliated (org-element-property :post-affiliated element)))
22804 (org-with-wide-buffer
22805 (cond
22806 (contentsp
22807 (case type
22808 ((diary-sexp footnote-definition) 0)
22809 ((headline inlinetask nil)
22810 (if (not org-adapt-indentation) 0
22811 (let ((level (org-current-level)))
22812 (if level (1+ level) 0))))
22813 ((item plain-list) (org-list-item-body-column post-affiliated))
22815 (goto-char start)
22816 (org-get-indentation))))
22817 ((memq type '(headline inlinetask nil))
22818 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22819 (org--get-expected-indentation element t)
22821 ((memq type '(diary-sexp footnote-definition)) 0)
22822 ;; First paragraph of a footnote definition or an item.
22823 ;; Indent like parent.
22824 ((< (line-beginning-position) start)
22825 (org--get-expected-indentation
22826 (org-element-property :parent element) t))
22827 ;; At first line: indent according to previous sibling, if any,
22828 ;; ignoring footnote definitions and inline tasks, or parent's
22829 ;; contents.
22830 ((= (line-beginning-position) start)
22831 (catch 'exit
22832 (while t
22833 (if (= (point-min) start) (throw 'exit 0)
22834 (goto-char (1- start))
22835 (let* ((previous (org-element-at-point))
22836 (parent previous))
22837 (while (and parent (<= (org-element-property :end parent) start))
22838 (setq previous parent
22839 parent (org-element-property :parent parent)))
22840 (cond
22841 ((not previous) (throw 'exit 0))
22842 ((> (org-element-property :end previous) start)
22843 (throw 'exit (org--get-expected-indentation previous t)))
22844 ((memq (org-element-type previous)
22845 '(footnote-definition inlinetask))
22846 (setq start (org-element-property :begin previous)))
22847 (t (goto-char (org-element-property :begin previous))
22848 (throw 'exit
22849 (if (bolp) (org-get-indentation)
22850 ;; At first paragraph in an item or
22851 ;; a footnote definition.
22852 (org--get-expected-indentation
22853 (org-element-property :parent previous) t))))))))))
22854 ;; Otherwise, move to the first non-blank line above.
22856 (beginning-of-line)
22857 (let ((pos (point)))
22858 (skip-chars-backward " \r\t\n")
22859 (cond
22860 ;; Two blank lines end a footnote definition or a plain
22861 ;; list. When we indent an empty line after them, the
22862 ;; containing list or footnote definition is over, so it
22863 ;; qualifies as a previous sibling. Therefore, we indent
22864 ;; like its first line.
22865 ((and (memq type '(footnote-definition plain-list))
22866 (> (count-lines (point) pos) 2))
22867 (goto-char start)
22868 (org-get-indentation))
22869 ;; Line above is the first one of a paragraph at the
22870 ;; beginning of an item or a footnote definition. Indent
22871 ;; like parent.
22872 ((< (line-beginning-position) start)
22873 (org--get-expected-indentation
22874 (org-element-property :parent element) t))
22875 ;; Line above is the beginning of an element, i.e., point
22876 ;; was originally on the blank lines between element's start
22877 ;; and contents.
22878 ((= (line-beginning-position) post-affiliated)
22879 (org--get-expected-indentation element t))
22880 ;; POS is after contents in a greater element. Indent like
22881 ;; the beginning of the element.
22883 ;; As a special case, if point is at the end of a footnote
22884 ;; definition or an item, indent like the very last element
22885 ;; within.
22886 ((and (not (eq type 'paragraph))
22887 (let ((cend (org-element-property :contents-end element)))
22888 (and cend (<= cend pos))))
22889 (if (memq type '(footnote-definition item plain-list))
22890 (let ((last (org-element-at-point)))
22891 (org--get-expected-indentation
22892 last
22893 (memq (org-element-type last)
22894 '(footnote-definition item plain-list))))
22895 (goto-char start)
22896 (org-get-indentation)))
22897 ;; In any other case, indent like the current line.
22898 (t (org-get-indentation)))))))))
22900 (defun org--align-node-property ()
22901 "Align node property at point.
22902 Alignment is done according to `org-property-format', which see."
22903 (when (save-excursion
22904 (beginning-of-line)
22905 (looking-at org-property-re))
22906 (replace-match
22907 (concat (match-string 4)
22908 (org-trim
22909 (format org-property-format (match-string 1) (match-string 3))))
22910 t t)))
22912 (defun org-indent-line ()
22913 "Indent line depending on context.
22915 Indentation is done according to the following rules:
22917 - Footnote definitions, diary sexps, headlines and inline tasks
22918 have to start at column 0.
22920 - On the very first line of an element, consider, in order, the
22921 next rules until one matches:
22923 1. If there's a sibling element before, ignoring footnote
22924 definitions and inline tasks, indent like its first line.
22926 2. If element has a parent, indent like its contents. More
22927 precisely, if parent is an item, indent after the
22928 description part, if any, or the bullet (see
22929 `org-list-description-max-indent'). Else, indent like
22930 parent's first line.
22932 3. Otherwise, indent relatively to current level, if
22933 `org-adapt-indentation' is non-nil, or to left margin.
22935 - On a blank line at the end of an element, indent according to
22936 the type of the element. More precisely
22938 1. If element is a plain list, an item, or a footnote
22939 definition, indent like the very last element within.
22941 2. If element is a paragraph, indent like its last non blank
22942 line.
22944 3. Otherwise, indent like its very first line.
22946 - In the code part of a source block, use language major mode
22947 to indent current line if `org-src-tab-acts-natively' is
22948 non-nil. If it is nil, do nothing.
22950 - Otherwise, indent like the first non-blank line above.
22952 The function doesn't indent an item as it could break the whole
22953 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22954 \\[org-shiftmetaright].
22956 Also align node properties according to `org-property-format'."
22957 (interactive)
22958 (cond
22959 (orgstruct-is-++
22960 (let ((indent-line-function
22961 (cadadr (assq 'indent-line-function org-fb-vars))))
22962 (indent-according-to-mode)))
22963 ((org-at-heading-p) 'noindent)
22965 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22966 (type (org-element-type element)))
22967 (cond ((and (memq type '(plain-list item))
22968 (= (line-beginning-position)
22969 (org-element-property :post-affiliated element)))
22970 'noindent)
22971 ((and (eq type 'src-block)
22972 org-src-tab-acts-natively
22973 (> (line-beginning-position)
22974 (org-element-property :post-affiliated element))
22975 (< (line-beginning-position)
22976 (org-with-wide-buffer
22977 (goto-char (org-element-property :end element))
22978 (skip-chars-backward " \r\t\n")
22979 (line-beginning-position))))
22980 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22982 (let ((column (org--get-expected-indentation element nil)))
22983 ;; Preserve current column.
22984 (if (<= (current-column) (current-indentation))
22985 (org-indent-line-to column)
22986 (save-excursion (org-indent-line-to column))))
22987 ;; Align node property. Also preserve current column.
22988 (when (eq type 'node-property)
22989 (let ((column (current-column)))
22990 (org--align-node-property)
22991 (org-move-to-column column)))))))))
22993 (defun org-indent-region (start end)
22994 "Indent each non-blank line in the region.
22995 Called from a program, START and END specify the region to
22996 indent. The function will not indent contents of example blocks,
22997 verse blocks and export blocks as leading white spaces are
22998 assumed to be significant there."
22999 (interactive "r")
23000 (save-excursion
23001 (goto-char start)
23002 (skip-chars-forward " \r\t\n")
23003 (unless (eobp) (beginning-of-line))
23004 (let ((indent-to
23005 (lambda (ind pos)
23006 ;; Set IND as indentation for all lines between point and
23007 ;; POS or END, whichever comes first. Blank lines are
23008 ;; ignored. Leave point after POS once done.
23009 (let ((limit (copy-marker (min end pos))))
23010 (while (< (point) limit)
23011 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23012 (forward-line))
23013 (set-marker limit nil))))
23014 (end (copy-marker end)))
23015 (while (< (point) end)
23016 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23017 (let* ((element (org-element-at-point))
23018 (type (org-element-type element))
23019 (element-end (copy-marker (org-element-property :end element)))
23020 (ind (org--get-expected-indentation element nil)))
23021 (cond
23022 ((or (memq type '(paragraph table table-row))
23023 (not (or (org-element-property :contents-begin element)
23024 (memq type
23025 '(example-block export-block src-block)))))
23026 ;; Elements here are indented as a single block. Also
23027 ;; align node properties.
23028 (when (eq type 'node-property)
23029 (org--align-node-property)
23030 (beginning-of-line))
23031 (funcall indent-to ind element-end))
23033 ;; Elements in this category consist of three parts:
23034 ;; before the contents, the contents, and after the
23035 ;; contents. The contents are treated specially,
23036 ;; according to the element type, or not indented at
23037 ;; all. Other parts are indented as a single block.
23038 (let* ((post (copy-marker
23039 (org-element-property :post-affiliated element)))
23040 (cbeg
23041 (copy-marker
23042 (cond
23043 ((not (org-element-property :contents-begin element))
23044 ;; Fake contents for source blocks.
23045 (org-with-wide-buffer
23046 (goto-char post)
23047 (forward-line)
23048 (point)))
23049 ((memq type '(footnote-definition item plain-list))
23050 ;; Contents in these elements could start on
23051 ;; the same line as the beginning of the
23052 ;; element. Make sure we start indenting
23053 ;; from the second line.
23054 (org-with-wide-buffer
23055 (goto-char post)
23056 (end-of-line)
23057 (skip-chars-forward " \r\t\n")
23058 (if (eobp) (point) (line-beginning-position))))
23059 (t (org-element-property :contents-begin element)))))
23060 (cend (copy-marker
23061 (or (org-element-property :contents-end element)
23062 ;; Fake contents for source blocks.
23063 (org-with-wide-buffer
23064 (goto-char element-end)
23065 (skip-chars-backward " \r\t\n")
23066 (line-beginning-position)))
23067 t)))
23068 ;; Do not change items indentation individually as it
23069 ;; might break the list as a whole. On the other
23070 ;; hand, when at a plain list, indent it as a whole.
23071 (cond ((eq type 'plain-list)
23072 (let ((offset (- ind (org-get-indentation))))
23073 (unless (zerop offset)
23074 (indent-rigidly (org-element-property :begin element)
23075 (org-element-property :end element)
23076 offset))
23077 (goto-char cbeg)))
23078 ((eq type 'item) (goto-char cbeg))
23079 (t (funcall indent-to ind cbeg)))
23080 (when (< (point) end)
23081 (case type
23082 ((example-block export-block verse-block))
23083 (src-block
23084 ;; In a source block, indent source code
23085 ;; according to language major mode, but only if
23086 ;; `org-src-tab-acts-natively' is non-nil.
23087 (when (and (< (point) end) org-src-tab-acts-natively)
23088 (ignore-errors
23089 (org-babel-do-in-edit-buffer
23090 (indent-region (point-min) (point-max))))))
23091 (t (org-indent-region (point) (min cend end))))
23092 (goto-char (min cend end))
23093 (when (< (point) end) (funcall indent-to ind element-end)))
23094 (set-marker post nil)
23095 (set-marker cbeg nil)
23096 (set-marker cend nil))))
23097 (set-marker element-end nil))))
23098 (set-marker end nil))))
23100 (defun org-indent-drawer ()
23101 "Indent the drawer at point."
23102 (interactive)
23103 (unless (save-excursion
23104 (beginning-of-line)
23105 (org-looking-at-p org-drawer-regexp))
23106 (user-error "Not at a drawer"))
23107 (let ((element (org-element-at-point)))
23108 (unless (memq (org-element-type element) '(drawer property-drawer))
23109 (user-error "Not at a drawer"))
23110 (org-with-wide-buffer
23111 (org-indent-region (org-element-property :begin element)
23112 (org-element-property :end element))))
23113 (message "Drawer at point indented"))
23115 (defun org-indent-block ()
23116 "Indent the block at point."
23117 (interactive)
23118 (unless (save-excursion
23119 (beginning-of-line)
23120 (let ((case-fold-search t))
23121 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23122 (user-error "Not at a block"))
23123 (let ((element (org-element-at-point)))
23124 (unless (memq (org-element-type element)
23125 '(comment-block center-block dynamic-block example-block
23126 export-block quote-block special-block
23127 src-block verse-block))
23128 (user-error "Not at a block"))
23129 (org-with-wide-buffer
23130 (org-indent-region (org-element-property :begin element)
23131 (org-element-property :end element))))
23132 (message "Block at point indented"))
23135 ;;; Filling
23137 ;; We use our own fill-paragraph and auto-fill functions.
23139 ;; `org-fill-paragraph' relies on adaptive filling and context
23140 ;; checking. Appropriate `fill-prefix' is computed with
23141 ;; `org-adaptive-fill-function'.
23143 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23144 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23145 ;; `org-adaptive-fill-function' value. Internally,
23146 ;; `org-comment-line-break-function' breaks the line.
23148 ;; `org-setup-filling' installs filling and auto-filling related
23149 ;; variables during `org-mode' initialization.
23151 (defvar org-element-paragraph-separate) ; org-element.el
23152 (defun org-setup-filling ()
23153 (require 'org-element)
23154 ;; Prevent auto-fill from inserting unwanted new items.
23155 (when (boundp 'fill-nobreak-predicate)
23156 (org-set-local
23157 'fill-nobreak-predicate
23158 (org-uniquify
23159 (append fill-nobreak-predicate
23160 '(org-fill-line-break-nobreak-p
23161 org-fill-paragraph-with-timestamp-nobreak-p)))))
23162 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23163 (org-set-local 'paragraph-start paragraph-ending)
23164 (org-set-local 'paragraph-separate paragraph-ending))
23165 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
23166 (org-set-local 'auto-fill-inhibit-regexp nil)
23167 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
23168 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
23169 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
23171 (defun org-fill-line-break-nobreak-p ()
23172 "Non-nil when a new line at point would create an Org line break."
23173 (save-excursion
23174 (skip-chars-backward "[ \t]")
23175 (skip-chars-backward "\\\\")
23176 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23178 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23179 "Non-nil when a new line at point would split a timestamp."
23180 (and (org-at-timestamp-p t)
23181 (not (looking-at org-ts-regexp-both))))
23183 (declare-function message-in-body-p "message" ())
23184 (defvar orgtbl-line-start-regexp) ; From org-table.el
23185 (defun org-adaptive-fill-function ()
23186 "Compute a fill prefix for the current line.
23187 Return fill prefix, as a string, or nil if current line isn't
23188 meant to be filled. For convenience, if `adaptive-fill-regexp'
23189 matches in paragraphs or comments, use it."
23190 (catch 'exit
23191 (when (derived-mode-p 'message-mode)
23192 (save-excursion
23193 (beginning-of-line)
23194 (cond ((not (message-in-body-p)) (throw 'exit nil))
23195 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23196 ((looking-at message-cite-prefix-regexp)
23197 (throw 'exit (match-string-no-properties 0)))
23198 ((looking-at org-outline-regexp)
23199 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23200 (org-with-wide-buffer
23201 (unless (org-at-heading-p)
23202 (let* ((p (line-beginning-position))
23203 (element (save-excursion
23204 (beginning-of-line)
23205 (org-element-at-point)))
23206 (type (org-element-type element))
23207 (post-affiliated (org-element-property :post-affiliated element)))
23208 (unless (< p post-affiliated)
23209 (case type
23210 (comment
23211 (save-excursion
23212 (beginning-of-line)
23213 (looking-at "[ \t]*")
23214 (concat (match-string 0) "# ")))
23215 (footnote-definition "")
23216 ((item plain-list)
23217 (make-string (org-list-item-body-column post-affiliated) ?\s))
23218 (paragraph
23219 ;; Fill prefix is usually the same as the current line,
23220 ;; unless the paragraph is at the beginning of an item.
23221 (let ((parent (org-element-property :parent element)))
23222 (save-excursion
23223 (beginning-of-line)
23224 (cond ((eq (org-element-type parent) 'item)
23225 (make-string (org-list-item-body-column
23226 (org-element-property :begin parent))
23227 ?\s))
23228 ((and adaptive-fill-regexp
23229 ;; Locally disable
23230 ;; `adaptive-fill-function' to let
23231 ;; `fill-context-prefix' handle
23232 ;; `adaptive-fill-regexp' variable.
23233 (let (adaptive-fill-function)
23234 (fill-context-prefix
23235 post-affiliated
23236 (org-element-property :end element)))))
23237 ((looking-at "[ \t]+") (match-string 0))
23238 (t "")))))
23239 (comment-block
23240 ;; Only fill contents if P is within block boundaries.
23241 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23242 (forward-line)
23243 (point)))
23244 (cend (save-excursion
23245 (goto-char (org-element-property :end element))
23246 (skip-chars-backward " \r\t\n")
23247 (line-beginning-position))))
23248 (when (and (>= p cbeg) (< p cend))
23249 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23250 (match-string 0)
23251 "")))))))))))
23253 (declare-function message-goto-body "message" ())
23254 (defvar message-cite-prefix-regexp) ; From message.el
23255 (defun org-fill-paragraph (&optional justify)
23256 "Fill element at point, when applicable.
23258 This function only applies to comment blocks, comments, example
23259 blocks and paragraphs. Also, as a special case, re-align table
23260 when point is at one.
23262 If JUSTIFY is non-nil (interactively, with prefix argument),
23263 justify as well. If `sentence-end-double-space' is non-nil, then
23264 period followed by one space does not end a sentence, so don't
23265 break a line there. The variable `fill-column' controls the
23266 width for filling.
23268 For convenience, when point is at a plain list, an item or
23269 a footnote definition, try to fill the first paragraph within."
23270 (interactive)
23271 (if (and (derived-mode-p 'message-mode)
23272 (or (not (message-in-body-p))
23273 (save-excursion (move-beginning-of-line 1)
23274 (looking-at message-cite-prefix-regexp))))
23275 ;; First ensure filling is correct in message-mode.
23276 (let ((fill-paragraph-function
23277 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23278 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23279 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23280 (paragraph-separate
23281 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23282 (fill-paragraph nil))
23283 (with-syntax-table org-mode-transpose-word-syntax-table
23284 ;; Move to end of line in order to get the first paragraph
23285 ;; within a plain list or a footnote definition.
23286 (let ((element (save-excursion
23287 (end-of-line)
23288 (or (ignore-errors (org-element-at-point))
23289 (user-error "An element cannot be parsed line %d"
23290 (line-number-at-pos (point)))))))
23291 ;; First check if point is in a blank line at the beginning of
23292 ;; the buffer. In that case, ignore filling.
23293 (case (org-element-type element)
23294 ;; Use major mode filling function is src blocks.
23295 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23296 ;; Align Org tables, leave table.el tables as-is.
23297 (table-row (org-table-align) t)
23298 (table
23299 (when (eq (org-element-property :type element) 'org)
23300 (save-excursion
23301 (goto-char (org-element-property :post-affiliated element))
23302 (org-table-align)))
23304 (paragraph
23305 ;; Paragraphs may contain `line-break' type objects.
23306 (let ((beg (max (point-min)
23307 (org-element-property :contents-begin element)))
23308 (end (min (point-max)
23309 (org-element-property :contents-end element))))
23310 ;; Do nothing if point is at an affiliated keyword.
23311 (if (< (line-end-position) beg) t
23312 (when (derived-mode-p 'message-mode)
23313 ;; In `message-mode', do not fill following citation
23314 ;; in current paragraph nor text before message body.
23315 (let ((body-start (save-excursion (message-goto-body))))
23316 (when body-start (setq beg (max body-start beg))))
23317 (when (save-excursion
23318 (re-search-forward
23319 (concat "^" message-cite-prefix-regexp) end t))
23320 (setq end (match-beginning 0))))
23321 ;; Fill paragraph, taking line breaks into account.
23322 (save-excursion
23323 (goto-char beg)
23324 (let ((cuts (list beg)))
23325 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23326 (when (eq 'line-break
23327 (org-element-type
23328 (save-excursion (backward-char)
23329 (org-element-context))))
23330 (push (point) cuts)))
23331 (dolist (c (delq end cuts))
23332 (fill-region-as-paragraph c end justify)
23333 (setq end c))))
23334 t)))
23335 ;; Contents of `comment-block' type elements should be
23336 ;; filled as plain text, but only if point is within block
23337 ;; markers.
23338 (comment-block
23339 (let* ((case-fold-search t)
23340 (beg (save-excursion
23341 (goto-char (org-element-property :begin element))
23342 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23343 (forward-line)
23344 (point)))
23345 (end (save-excursion
23346 (goto-char (org-element-property :end element))
23347 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23348 (line-beginning-position))))
23349 (if (or (< (point) beg) (> (point) end)) t
23350 (fill-region-as-paragraph
23351 (save-excursion (end-of-line)
23352 (re-search-backward "^[ \t]*$" beg 'move)
23353 (line-beginning-position))
23354 (save-excursion (beginning-of-line)
23355 (re-search-forward "^[ \t]*$" end 'move)
23356 (line-beginning-position))
23357 justify))))
23358 ;; Fill comments.
23359 (comment
23360 (let ((begin (org-element-property :post-affiliated element))
23361 (end (org-element-property :end element)))
23362 (when (and (>= (point) begin) (<= (point) end))
23363 (let ((begin (save-excursion
23364 (end-of-line)
23365 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23366 (progn (forward-line) (point))
23367 begin)))
23368 (end (save-excursion
23369 (end-of-line)
23370 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23371 (1- (line-beginning-position))
23372 (skip-chars-backward " \r\t\n")
23373 (line-end-position)))))
23374 ;; Do not fill comments when at a blank line.
23375 (when (> end begin)
23376 (let ((fill-prefix
23377 (save-excursion
23378 (beginning-of-line)
23379 (looking-at "[ \t]*#")
23380 (let ((comment-prefix (match-string 0)))
23381 (goto-char (match-end 0))
23382 (if (looking-at adaptive-fill-regexp)
23383 (concat comment-prefix (match-string 0))
23384 (concat comment-prefix " "))))))
23385 (save-excursion
23386 (fill-region-as-paragraph begin end justify))))))
23388 ;; Ignore every other element.
23389 (otherwise t))))))
23391 (defun org-auto-fill-function ()
23392 "Auto-fill function."
23393 ;; Check if auto-filling is meaningful.
23394 (let ((fc (current-fill-column)))
23395 (when (and fc (> (current-column) fc))
23396 (let* ((fill-prefix (org-adaptive-fill-function))
23397 ;; Enforce empty fill prefix, if required. Otherwise, it
23398 ;; will be computed again.
23399 (adaptive-fill-mode (not (equal fill-prefix ""))))
23400 (when fill-prefix (do-auto-fill))))))
23402 (defun org-comment-line-break-function (&optional soft)
23403 "Break line at point and indent, continuing comment if within one.
23404 The inserted newline is marked hard if variable
23405 `use-hard-newlines' is true, unless optional argument SOFT is
23406 non-nil."
23407 (if soft (insert-and-inherit ?\n) (newline 1))
23408 (save-excursion (forward-char -1) (delete-horizontal-space))
23409 (delete-horizontal-space)
23410 (indent-to-left-margin)
23411 (insert-before-markers-and-inherit fill-prefix))
23414 ;;; Fixed Width Areas
23416 (defun org-toggle-fixed-width ()
23417 "Toggle fixed-width markup.
23419 Add or remove fixed-width markup on current line, whenever it
23420 makes sense. Return an error otherwise.
23422 If a region is active and if it contains only fixed-width areas
23423 or blank lines, remove all fixed-width markup in it. If the
23424 region contains anything else, convert all non-fixed-width lines
23425 to fixed-width ones.
23427 Blank lines at the end of the region are ignored unless the
23428 region only contains such lines."
23429 (interactive)
23430 (if (not (org-region-active-p))
23431 ;; No region:
23433 ;; Remove fixed width marker only in a fixed-with element.
23435 ;; Add fixed width maker in paragraphs, in blank lines after
23436 ;; elements or at the beginning of a headline or an inlinetask,
23437 ;; and before any one-line elements (e.g., a clock).
23438 (progn
23439 (beginning-of-line)
23440 (let* ((element (org-element-at-point))
23441 (type (org-element-type element)))
23442 (cond
23443 ((and (eq type 'fixed-width)
23444 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23445 (replace-match
23446 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23447 ((and (memq type '(babel-call clock comment diary-sexp headline
23448 horizontal-rule keyword paragraph
23449 planning))
23450 (<= (org-element-property :post-affiliated element) (point)))
23451 (skip-chars-forward " \t")
23452 (insert ": "))
23453 ((and (org-looking-at-p "[ \t]*$")
23454 (or (eq type 'inlinetask)
23455 (save-excursion
23456 (skip-chars-forward " \r\t\n")
23457 (<= (org-element-property :end element) (point)))))
23458 (delete-region (point) (line-end-position))
23459 (org-indent-line)
23460 (insert ": "))
23461 (t (user-error "Cannot insert a fixed-width line here")))))
23462 ;; Region active.
23463 (let* ((begin (save-excursion
23464 (goto-char (region-beginning))
23465 (line-beginning-position)))
23466 (end (copy-marker
23467 (save-excursion
23468 (goto-char (region-end))
23469 (unless (eolp) (beginning-of-line))
23470 (if (save-excursion (re-search-backward "\\S-" begin t))
23471 (progn (skip-chars-backward " \r\t\n") (point))
23472 (point)))))
23473 (all-fixed-width-p
23474 (catch 'not-all-p
23475 (save-excursion
23476 (goto-char begin)
23477 (skip-chars-forward " \r\t\n")
23478 (when (eobp) (throw 'not-all-p nil))
23479 (while (< (point) end)
23480 (let ((element (org-element-at-point)))
23481 (if (eq (org-element-type element) 'fixed-width)
23482 (goto-char (org-element-property :end element))
23483 (throw 'not-all-p nil))))
23484 t))))
23485 (if all-fixed-width-p
23486 (save-excursion
23487 (goto-char begin)
23488 (while (< (point) end)
23489 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23490 (replace-match
23491 "" nil nil nil
23492 (if (= (line-end-position) (match-end 0)) 0 1)))
23493 (forward-line)))
23494 (let ((min-ind (point-max)))
23495 ;; Find minimum indentation across all lines.
23496 (save-excursion
23497 (goto-char begin)
23498 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23499 (setq min-ind 0)
23500 (catch 'zerop
23501 (while (< (point) end)
23502 (unless (org-looking-at-p "[ \t]*$")
23503 (let ((ind (org-get-indentation)))
23504 (setq min-ind (min min-ind ind))
23505 (when (zerop ind) (throw 'zerop t))))
23506 (forward-line)))))
23507 ;; Loop over all lines and add fixed-width markup everywhere
23508 ;; but in fixed-width lines.
23509 (save-excursion
23510 (goto-char begin)
23511 (while (< (point) end)
23512 (cond
23513 ((org-at-heading-p)
23514 (insert ": ")
23515 (forward-line)
23516 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23517 (insert ":")
23518 (forward-line)))
23519 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23520 (let* ((element (org-element-at-point))
23521 (element-end (org-element-property :end element)))
23522 (if (eq (org-element-type element) 'fixed-width)
23523 (progn (goto-char element-end)
23524 (skip-chars-backward " \r\t\n")
23525 (forward-line))
23526 (let ((limit (min end element-end)))
23527 (while (< (point) limit)
23528 (org-move-to-column min-ind t)
23529 (insert ": ")
23530 (forward-line))))))
23532 (org-move-to-column min-ind t)
23533 (insert ": ")
23534 (forward-line)))))))
23535 (set-marker end nil))))
23538 ;;; Comments
23540 ;; Org comments syntax is quite complex. It requires the entire line
23541 ;; to be just a comment. Also, even with the right syntax at the
23542 ;; beginning of line, some some elements (i.e. verse-block or
23543 ;; example-block) don't accept comments. Usual Emacs comment commands
23544 ;; cannot cope with those requirements. Therefore, Org replaces them.
23546 ;; Org still relies on `comment-dwim', but cannot trust
23547 ;; `comment-only-p'. So, `comment-region-function' and
23548 ;; `uncomment-region-function' both point
23549 ;; to`org-comment-or-uncomment-region'. Eventually,
23550 ;; `org-insert-comment' takes care of insertion of comments at the
23551 ;; beginning of line.
23553 ;; `org-setup-comments-handling' install comments related variables
23554 ;; during `org-mode' initialization.
23556 (defun org-setup-comments-handling ()
23557 (interactive)
23558 (org-set-local 'comment-use-syntax nil)
23559 (org-set-local 'comment-start "# ")
23560 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23561 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23562 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23563 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23565 (defun org-insert-comment ()
23566 "Insert an empty comment above current line.
23567 If the line is empty, insert comment at its beginning. When
23568 point is within a source block, comment according to the related
23569 major mode."
23570 (if (let ((element (org-element-at-point)))
23571 (and (eq (org-element-type element) 'src-block)
23572 (< (save-excursion
23573 (goto-char (org-element-property :post-affiliated element))
23574 (line-end-position))
23575 (point))
23576 (> (save-excursion
23577 (goto-char (org-element-property :end element))
23578 (skip-chars-backward " \r\t\n")
23579 (line-beginning-position))
23580 (point))))
23581 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23582 (beginning-of-line)
23583 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23584 (open-line 1))
23585 (org-indent-line)
23586 (insert "# ")))
23588 (defvar comment-empty-lines) ; From newcomment.el.
23589 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23590 "Comment or uncomment each non-blank line in the region.
23591 Uncomment each non-blank line between BEG and END if it only
23592 contains commented lines. Otherwise, comment them. If region is
23593 strictly within a source block, use appropriate comment syntax."
23594 (if (let ((element (org-element-at-point)))
23595 (and (eq (org-element-type element) 'src-block)
23596 (< (save-excursion
23597 (goto-char (org-element-property :post-affiliated element))
23598 (line-end-position))
23599 beg)
23600 (>= (save-excursion
23601 (goto-char (org-element-property :end element))
23602 (skip-chars-backward " \r\t\n")
23603 (line-beginning-position))
23604 end)))
23605 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23606 (save-restriction
23607 ;; Restrict region
23608 (narrow-to-region (save-excursion (goto-char beg)
23609 (skip-chars-forward " \r\t\n" end)
23610 (line-beginning-position))
23611 (save-excursion (goto-char end)
23612 (skip-chars-backward " \r\t\n" beg)
23613 (line-end-position)))
23614 (let ((uncommentp
23615 ;; UNCOMMENTP is non-nil when every non blank line between
23616 ;; BEG and END is a comment.
23617 (save-excursion
23618 (goto-char (point-min))
23619 (while (and (not (eobp))
23620 (let ((element (org-element-at-point)))
23621 (and (eq (org-element-type element) 'comment)
23622 (goto-char (min (point-max)
23623 (org-element-property
23624 :end element)))))))
23625 (eobp))))
23626 (if uncommentp
23627 ;; Only blank lines and comments in region: uncomment it.
23628 (save-excursion
23629 (goto-char (point-min))
23630 (while (not (eobp))
23631 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23632 (replace-match "" nil nil nil 1))
23633 (forward-line)))
23634 ;; Comment each line in region.
23635 (let ((min-indent (point-max)))
23636 ;; First find the minimum indentation across all lines.
23637 (save-excursion
23638 (goto-char (point-min))
23639 (while (and (not (eobp)) (not (zerop min-indent)))
23640 (unless (looking-at "[ \t]*$")
23641 (setq min-indent (min min-indent (current-indentation))))
23642 (forward-line)))
23643 ;; Then loop over all lines.
23644 (save-excursion
23645 (goto-char (point-min))
23646 (while (not (eobp))
23647 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23648 ;; Don't get fooled by invisible text (e.g. link path)
23649 ;; when moving to column MIN-INDENT.
23650 (let ((buffer-invisibility-spec nil))
23651 (org-move-to-column min-indent t))
23652 (insert comment-start))
23653 (forward-line)))))))))
23655 (defun org-comment-dwim (arg)
23656 "Call `comment-dwim' within a source edit buffer if needed."
23657 (interactive "*P")
23658 (if (org-in-src-block-p)
23659 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23660 (call-interactively 'comment-dwim)))
23663 ;;; Timestamps API
23665 ;; This section contains tools to operate on timestamp objects, as
23666 ;; returned by, e.g. `org-element-context'.
23668 (defun org-timestamp--to-internal-time (timestamp &optional end)
23669 "Encode TIMESTAMP object into Emacs internal time.
23670 Use end of date range or time range when END is non-nil."
23671 (apply #'encode-time
23672 (cons 0
23673 (mapcar
23674 (lambda (prop) (or (org-element-property prop timestamp) 0))
23675 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23676 '(:minute-start :hour-start :day-start :month-start
23677 :year-start))))))
23679 (defun org-timestamp-has-time-p (timestamp)
23680 "Non-nil when TIMESTAMP has a time specified."
23681 (org-element-property :hour-start timestamp))
23683 (defun org-timestamp-format (timestamp format &optional end utc)
23684 "Format a TIMESTAMP object into a string.
23686 FORMAT is a format specifier to be passed to
23687 `format-time-string'.
23689 When optional argument END is non-nil, use end of date-range or
23690 time-range, if possible.
23692 When optional argument UTC is non-nil, time will be expressed as
23693 Universal Time."
23694 (format-time-string
23695 format (org-timestamp--to-internal-time timestamp end) utc))
23697 (defun org-timestamp-split-range (timestamp &optional end)
23698 "Extract a TIMESTAMP object from a date or time range.
23700 END, when non-nil, means extract the end of the range.
23701 Otherwise, extract its start.
23703 Return a new timestamp object."
23704 (let ((type (org-element-property :type timestamp)))
23705 (if (memq type '(active inactive diary)) timestamp
23706 (let ((split-ts (org-element-copy timestamp)))
23707 ;; Set new type.
23708 (org-element-put-property
23709 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23710 ;; Copy start properties over end properties if END is
23711 ;; non-nil. Otherwise, copy end properties over `start' ones.
23712 (let ((p-alist '((:minute-start . :minute-end)
23713 (:hour-start . :hour-end)
23714 (:day-start . :day-end)
23715 (:month-start . :month-end)
23716 (:year-start . :year-end))))
23717 (dolist (p-cell p-alist)
23718 (org-element-put-property
23719 split-ts
23720 (funcall (if end #'car #'cdr) p-cell)
23721 (org-element-property
23722 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23723 ;; Eventually refresh `:raw-value'.
23724 (org-element-put-property split-ts :raw-value nil)
23725 (org-element-put-property
23726 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23728 (defun org-timestamp-translate (timestamp &optional boundary)
23729 "Translate TIMESTAMP object to custom format.
23731 Format string is defined in `org-time-stamp-custom-formats',
23732 which see.
23734 When optional argument BOUNDARY is non-nil, it is either the
23735 symbol `start' or `end'. In this case, only translate the
23736 starting or ending part of TIMESTAMP if it is a date or time
23737 range. Otherwise, translate both parts.
23739 Return timestamp as-is if `org-display-custom-times' is nil or if
23740 it has a `diary' type."
23741 (let ((type (org-element-property :type timestamp)))
23742 (if (or (not org-display-custom-times) (eq type 'diary))
23743 (org-element-interpret-data timestamp)
23744 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23745 org-time-stamp-custom-formats)))
23746 (if (and (not boundary) (memq type '(active-range inactive-range)))
23747 (concat (org-timestamp-format timestamp fmt)
23748 "--"
23749 (org-timestamp-format timestamp fmt t))
23750 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23754 ;;; Other stuff.
23756 (defun org-reftex-citation ()
23757 "Use reftex-citation to insert a citation into the buffer.
23758 This looks for a line like
23760 #+BIBLIOGRAPHY: foo plain option:-d
23762 and derives from it that foo.bib is the bibliography file relevant
23763 for this document. It then installs the necessary environment for RefTeX
23764 to work in this buffer and calls `reftex-citation' to insert a citation
23765 into the buffer.
23767 Export of such citations to both LaTeX and HTML is handled by the contributed
23768 package ox-bibtex by Taru Karttunen."
23769 (interactive)
23770 (let ((reftex-docstruct-symbol 'rds)
23771 (reftex-cite-format "\\cite{%l}")
23772 rds bib)
23773 (save-excursion
23774 (save-restriction
23775 (widen)
23776 (let ((case-fold-search t)
23777 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23778 (if (not (save-excursion
23779 (or (re-search-forward re nil t)
23780 (re-search-backward re nil t))))
23781 (user-error "No bibliography defined in file")
23782 (setq bib (concat (match-string 1) ".bib")
23783 rds (list (list 'bib bib)))))))
23784 (call-interactively 'reftex-citation)))
23786 ;;;; Functions extending outline functionality
23788 (defun org-beginning-of-line (&optional arg)
23789 "Go to the beginning of the current line. If that is invisible, continue
23790 to a visible line beginning. This makes the function of C-a more intuitive.
23791 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23792 first attempt, and only move to after the tags when the cursor is already
23793 beyond the end of the headline."
23794 (interactive "P")
23795 (let ((pos (point))
23796 (special (if (consp org-special-ctrl-a/e)
23797 (car org-special-ctrl-a/e)
23798 org-special-ctrl-a/e))
23799 deactivate-mark refpos)
23800 (if (org-bound-and-true-p visual-line-mode)
23801 (beginning-of-visual-line 1)
23802 (beginning-of-line 1))
23803 (if (and arg (fboundp 'move-beginning-of-line))
23804 (call-interactively 'move-beginning-of-line)
23805 (if (bobp)
23807 (backward-char 1)
23808 (if (org-truely-invisible-p)
23809 (while (and (not (bobp)) (org-truely-invisible-p))
23810 (backward-char 1)
23811 (beginning-of-line 1))
23812 (forward-char 1))))
23813 (when special
23814 (cond
23815 ((and (looking-at org-complex-heading-regexp)
23816 (= (char-after (match-end 1)) ?\ ))
23817 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23818 (point-at-eol)))
23819 (goto-char
23820 (if (eq special t)
23821 (cond ((> pos refpos) refpos)
23822 ((= pos (point)) refpos)
23823 (t (point)))
23824 (cond ((> pos (point)) (point))
23825 ((not (eq last-command this-command)) (point))
23826 (t refpos)))))
23827 ((org-at-item-p)
23828 ;; Being at an item and not looking at an the item means point
23829 ;; was previously moved to beginning of a visual line, which
23830 ;; doesn't contain the item. Therefore, do nothing special,
23831 ;; just stay here.
23832 (when (looking-at org-list-full-item-re)
23833 ;; Set special position at first white space character after
23834 ;; bullet, and check-box, if any.
23835 (let ((after-bullet
23836 (let ((box (match-end 3)))
23837 (if (not box) (match-end 1)
23838 (let ((after (char-after box)))
23839 (if (and after (= after ? )) (1+ box) box))))))
23840 ;; Special case: Move point to special position when
23841 ;; currently after it or at beginning of line.
23842 (if (eq special t)
23843 (when (or (> pos after-bullet) (= (point) pos))
23844 (goto-char after-bullet))
23845 ;; Reversed case: Move point to special position when
23846 ;; point was already at beginning of line and command is
23847 ;; repeated.
23848 (when (and (= (point) pos) (eq last-command this-command))
23849 (goto-char after-bullet))))))))
23850 (org-no-warnings
23851 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23852 (setq disable-point-adjustment
23853 (or (not (invisible-p (point)))
23854 (not (invisible-p (max (point-min) (1- (point))))))))
23856 (defun org-end-of-line (&optional arg)
23857 "Go to the end of the line.
23858 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23859 tags on the first attempt, and only move to after the tags when
23860 the cursor is already beyond the end of the headline."
23861 (interactive "P")
23862 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23863 org-special-ctrl-a/e))
23864 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23865 'end-of-visual-line)
23866 ((fboundp 'move-end-of-line) 'move-end-of-line)
23867 (t 'end-of-line)))
23868 deactivate-mark)
23869 (if (or (not special) arg) (call-interactively move-fun)
23870 (let* ((element (save-excursion (beginning-of-line)
23871 (org-element-at-point)))
23872 (type (org-element-type element)))
23873 (cond
23874 ((memq type '(headline inlinetask))
23875 (let ((pos (point)))
23876 (beginning-of-line 1)
23877 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23878 (if (eq special t)
23879 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23880 (goto-char (match-beginning 1))
23881 (goto-char (match-end 0)))
23882 (if (or (< pos (match-end 0))
23883 (not (eq this-command last-command)))
23884 (goto-char (match-end 0))
23885 (goto-char (match-beginning 1))))
23886 (call-interactively move-fun))))
23887 ((outline-invisible-p (line-end-position))
23888 ;; If element is hidden, `move-end-of-line' would put point
23889 ;; after it. Use `end-of-line' to stay on current line.
23890 (call-interactively 'end-of-line))
23891 (t (call-interactively move-fun)))))
23892 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23893 (setq disable-point-adjustment
23894 (or (not (invisible-p (point)))
23895 (not (invisible-p (max (point-min) (1- (point))))))))
23897 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23898 (define-key org-mode-map "\C-e" 'org-end-of-line)
23900 (defun org-backward-sentence (&optional arg)
23901 "Go to beginning of sentence, or beginning of table field.
23902 This will call `backward-sentence' or `org-table-beginning-of-field',
23903 depending on context."
23904 (interactive "P")
23905 (let* ((element (org-element-at-point))
23906 (contents-begin (org-element-property :contents-begin element))
23907 (table (org-element-lineage element '(table) t)))
23908 (if (and table
23909 (> (point) contents-begin)
23910 (<= (point) (org-element-property :contents-end table)))
23911 (call-interactively #'org-table-beginning-of-field)
23912 (save-restriction
23913 (when (and contents-begin
23914 (< (point-min) contents-begin)
23915 (> (point) contents-begin))
23916 (narrow-to-region contents-begin
23917 (org-element-property :contents-end element)))
23918 (call-interactively #'backward-sentence)))))
23920 (defun org-forward-sentence (&optional arg)
23921 "Go to end of sentence, or end of table field.
23922 This will call `forward-sentence' or `org-table-end-of-field',
23923 depending on context."
23924 (interactive "P")
23925 (let* ((element (org-element-at-point))
23926 (contents-end (org-element-property :contents-end element))
23927 (table (org-element-lineage element '(table) t)))
23928 (if (and table
23929 (>= (point) (org-element-property :contents-begin table))
23930 (< (point) contents-end))
23931 (call-interactively #'org-table-end-of-field)
23932 (save-restriction
23933 (when (and contents-end
23934 (> (point-max) contents-end)
23935 ;; Skip blank lines between elements.
23936 (< (org-element-property :end element)
23937 (save-excursion (goto-char contents-end)
23938 (skip-chars-forward " \r\t\n"))))
23939 (narrow-to-region (org-element-property :contents-begin element)
23940 contents-end))
23941 (call-interactively #'forward-sentence)))))
23943 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23944 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23946 (defun org-kill-line (&optional arg)
23947 "Kill line, to tags or end of line."
23948 (interactive "P")
23949 (cond
23950 ((or (not org-special-ctrl-k)
23951 (bolp)
23952 (not (org-at-heading-p)))
23953 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23954 org-ctrl-k-protect-subtree)
23955 (if (or (eq org-ctrl-k-protect-subtree 'error)
23956 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23957 (user-error "C-k aborted as it would kill a hidden subtree")))
23958 (call-interactively
23959 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23960 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23961 (kill-region (point) (match-beginning 1))
23962 (org-set-tags nil t))
23963 (t (kill-region (point) (point-at-eol)))))
23965 (define-key org-mode-map "\C-k" 'org-kill-line)
23967 (defun org-yank (&optional arg)
23968 "Yank. If the kill is a subtree, treat it specially.
23969 This command will look at the current kill and check if is a single
23970 subtree, or a series of subtrees[1]. If it passes the test, and if the
23971 cursor is at the beginning of a line or after the stars of a currently
23972 empty headline, then the yank is handled specially. How exactly depends
23973 on the value of the following variables, both set by default.
23975 `org-yank-folded-subtrees'
23976 When set, the subtree(s) will be folded after insertion, but only
23977 if doing so would now swallow text after the yanked text.
23979 `org-yank-adjusted-subtrees'
23980 When set, the subtree will be promoted or demoted in order to
23981 fit into the local outline tree structure, which means that the
23982 level will be adjusted so that it becomes the smaller one of the
23983 two *visible* surrounding headings.
23985 Any prefix to this command will cause `yank' to be called directly with
23986 no special treatment. In particular, a simple \\[universal-argument] prefix \
23987 will just
23988 plainly yank the text as it is.
23990 \[1] The test checks if the first non-white line is a heading
23991 and if there are no other headings with fewer stars."
23992 (interactive "P")
23993 (org-yank-generic 'yank arg))
23995 (defun org-yank-generic (command arg)
23996 "Perform some yank-like command.
23998 This function implements the behavior described in the `org-yank'
23999 documentation. However, it has been generalized to work for any
24000 interactive command with similar behavior."
24002 ;; pretend to be command COMMAND
24003 (setq this-command command)
24005 (if arg
24006 (call-interactively command)
24008 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24009 (and (org-kill-is-subtree-p)
24010 (or (bolp)
24011 (and (looking-at "[ \t]*$")
24012 (string-match
24013 "\\`\\*+\\'"
24014 (buffer-substring (point-at-bol) (point)))))))
24015 swallowp)
24016 (cond
24017 ((and subtreep org-yank-folded-subtrees)
24018 (let ((beg (point))
24019 end)
24020 (if (and subtreep org-yank-adjusted-subtrees)
24021 (org-paste-subtree nil nil 'for-yank)
24022 (call-interactively command))
24024 (setq end (point))
24025 (goto-char beg)
24026 (when (and (bolp) subtreep
24027 (not (setq swallowp
24028 (org-yank-folding-would-swallow-text beg end))))
24029 (org-with-limited-levels
24030 (or (looking-at org-outline-regexp)
24031 (re-search-forward org-outline-regexp-bol end t))
24032 (while (and (< (point) end) (looking-at org-outline-regexp))
24033 (hide-subtree)
24034 (org-cycle-show-empty-lines 'folded)
24035 (condition-case nil
24036 (outline-forward-same-level 1)
24037 (error (goto-char end))))))
24038 (when swallowp
24039 (message
24040 "Inserted text not folded because that would swallow text"))
24042 (goto-char end)
24043 (skip-chars-forward " \t\n\r")
24044 (beginning-of-line 1)
24045 (push-mark beg 'nomsg)))
24046 ((and subtreep org-yank-adjusted-subtrees)
24047 (let ((beg (point-at-bol)))
24048 (org-paste-subtree nil nil 'for-yank)
24049 (push-mark beg 'nomsg)))
24051 (call-interactively command))))))
24053 (defun org-yank-folding-would-swallow-text (beg end)
24054 "Would hide-subtree at BEG swallow any text after END?"
24055 (let (level)
24056 (org-with-limited-levels
24057 (save-excursion
24058 (goto-char beg)
24059 (when (or (looking-at org-outline-regexp)
24060 (re-search-forward org-outline-regexp-bol end t))
24061 (setq level (org-outline-level)))
24062 (goto-char end)
24063 (skip-chars-forward " \t\r\n\v\f")
24064 (if (or (eobp)
24065 (and (bolp) (looking-at org-outline-regexp)
24066 (<= (org-outline-level) level)))
24067 nil ; Nothing would be swallowed
24068 t))))) ; something would swallow
24070 (define-key org-mode-map "\C-y" 'org-yank)
24072 (defun org-truely-invisible-p ()
24073 "Check if point is at a character currently not visible.
24074 This version does not only check the character property, but also
24075 `visible-mode'."
24076 ;; Early versions of noutline don't have `outline-invisible-p'.
24077 (if (org-bound-and-true-p visible-mode)
24079 (outline-invisible-p)))
24081 (defun org-invisible-p2 ()
24082 "Check if point is at a character currently not visible."
24083 (save-excursion
24084 (if (and (eolp) (not (bobp))) (backward-char 1))
24085 ;; Early versions of noutline don't have `outline-invisible-p'.
24086 (outline-invisible-p)))
24088 (defun org-back-to-heading (&optional invisible-ok)
24089 "Call `outline-back-to-heading', but provide a better error message."
24090 (condition-case nil
24091 (outline-back-to-heading invisible-ok)
24092 (error (error "Before first headline at position %d in buffer %s"
24093 (point) (current-buffer)))))
24095 (defun org-before-first-heading-p ()
24096 "Before first heading?"
24097 (save-excursion
24098 (end-of-line)
24099 (null (re-search-backward org-outline-regexp-bol nil t))))
24101 (defun org-at-heading-p (&optional ignored)
24102 (outline-on-heading-p t))
24103 ;; Compatibility alias with Org versions < 7.8.03
24104 (defalias 'org-on-heading-p 'org-at-heading-p)
24106 (defun org-in-commented-heading-p (&optional no-inheritance)
24107 "Non-nil if point is under a commented heading.
24108 This function also checks ancestors of the current headline,
24109 unless optional argument NO-INHERITANCE is non-nil."
24110 (cond
24111 ((org-before-first-heading-p) nil)
24112 ((let ((headline (nth 4 (org-heading-components))))
24113 (and headline
24114 (let ((case-fold-search nil))
24115 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24116 headline)))))
24117 (no-inheritance nil)
24119 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24121 (defun org-at-comment-p nil
24122 "Is cursor in a commented line?"
24123 (save-excursion
24124 (save-match-data
24125 (beginning-of-line)
24126 (looking-at "^[ \t]*# "))))
24128 (defun org-at-drawer-p nil
24129 "Is cursor at a drawer keyword?"
24130 (save-excursion
24131 (move-beginning-of-line 1)
24132 (looking-at org-drawer-regexp)))
24134 (defun org-at-block-p nil
24135 "Is cursor at a block keyword?"
24136 (save-excursion
24137 (move-beginning-of-line 1)
24138 (looking-at org-block-regexp)))
24140 (defun org-point-at-end-of-empty-headline ()
24141 "If point is at the end of an empty headline, return t, else nil.
24142 If the heading only contains a TODO keyword, it is still still considered
24143 empty."
24144 (and (looking-at "[ \t]*$")
24145 (when org-todo-line-regexp
24146 (save-excursion
24147 (beginning-of-line 1)
24148 (let ((case-fold-search nil))
24149 (looking-at org-todo-line-regexp)
24150 (string= (match-string 3) ""))))))
24152 (defun org-at-heading-or-item-p ()
24153 (or (org-at-heading-p) (org-at-item-p)))
24155 (defun org-at-target-p ()
24156 (or (org-in-regexp org-radio-target-regexp)
24157 (org-in-regexp org-target-regexp)))
24158 ;; Compatibility alias with Org versions < 7.8.03
24159 (defalias 'org-on-target-p 'org-at-target-p)
24161 (defun org-up-heading-all (arg)
24162 "Move to the heading line of which the present line is a subheading.
24163 This function considers both visible and invisible heading lines.
24164 With argument, move up ARG levels."
24165 (if (fboundp 'outline-up-heading-all)
24166 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24167 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24169 (defun org-up-heading-safe ()
24170 "Move to the heading line of which the present line is a subheading.
24171 This version will not throw an error. It will return the level of the
24172 headline found, or nil if no higher level is found.
24174 Also, this function will be a lot faster than `outline-up-heading',
24175 because it relies on stars being the outline starters. This can really
24176 make a significant difference in outlines with very many siblings."
24177 (when (ignore-errors (org-back-to-heading t))
24178 (let ((level-up (1- (funcall outline-level))))
24179 (and (> level-up 0)
24180 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24181 (funcall outline-level)))))
24183 (defun org-first-sibling-p ()
24184 "Is this heading the first child of its parents?"
24185 (interactive)
24186 (let ((re org-outline-regexp-bol)
24187 level l)
24188 (unless (org-at-heading-p t)
24189 (user-error "Not at a heading"))
24190 (setq level (funcall outline-level))
24191 (save-excursion
24192 (if (not (re-search-backward re nil t))
24194 (setq l (funcall outline-level))
24195 (< l level)))))
24197 (defun org-goto-sibling (&optional previous)
24198 "Goto the next sibling, even if it is invisible.
24199 When PREVIOUS is set, go to the previous sibling instead. Returns t
24200 when a sibling was found. When none is found, return nil and don't
24201 move point."
24202 (let ((fun (if previous 're-search-backward 're-search-forward))
24203 (pos (point))
24204 (re org-outline-regexp-bol)
24205 level l)
24206 (when (ignore-errors (org-back-to-heading t))
24207 (setq level (funcall outline-level))
24208 (catch 'exit
24209 (or previous (forward-char 1))
24210 (while (funcall fun re nil t)
24211 (setq l (funcall outline-level))
24212 (when (< l level) (goto-char pos) (throw 'exit nil))
24213 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24214 (goto-char pos)
24215 nil))))
24217 (defun org-show-siblings ()
24218 "Show all siblings of the current headline."
24219 (save-excursion
24220 (while (org-goto-sibling) (org-flag-heading nil)))
24221 (save-excursion
24222 (while (org-goto-sibling 'previous)
24223 (org-flag-heading nil))))
24225 (defun org-goto-first-child ()
24226 "Goto the first child, even if it is invisible.
24227 Return t when a child was found. Otherwise don't move point and
24228 return nil."
24229 (let (level (pos (point)) (re org-outline-regexp-bol))
24230 (when (ignore-errors (org-back-to-heading t))
24231 (setq level (outline-level))
24232 (forward-char 1)
24233 (if (and (re-search-forward re nil t) (> (outline-level) level))
24234 (progn (goto-char (match-beginning 0)) t)
24235 (goto-char pos) nil))))
24237 (defun org-show-hidden-entry ()
24238 "Show an entry where even the heading is hidden."
24239 (save-excursion
24240 (org-show-entry)))
24242 (defun org-flag-heading (flag &optional entry)
24243 "Flag the current heading. FLAG non-nil means make invisible.
24244 When ENTRY is non-nil, show the entire entry."
24245 (save-excursion
24246 (org-back-to-heading t)
24247 ;; Check if we should show the entire entry
24248 (if entry
24249 (progn
24250 (org-show-entry)
24251 (save-excursion
24252 (and (outline-next-heading)
24253 (org-flag-heading nil))))
24254 (outline-flag-region (max (point-min) (1- (point)))
24255 (save-excursion (outline-end-of-heading) (point))
24256 flag))))
24258 (defun org-get-next-sibling ()
24259 "Move to next heading of the same level, and return point.
24260 If there is no such heading, return nil.
24261 This is like outline-next-sibling, but invisible headings are ok."
24262 (let ((level (funcall outline-level)))
24263 (outline-next-heading)
24264 (while (and (not (eobp)) (> (funcall outline-level) level))
24265 (outline-next-heading))
24266 (if (or (eobp) (< (funcall outline-level) level))
24268 (point))))
24270 (defun org-get-last-sibling ()
24271 "Move to previous heading of the same level, and return point.
24272 If there is no such heading, return nil."
24273 (let ((opoint (point))
24274 (level (funcall outline-level)))
24275 (outline-previous-heading)
24276 (when (and (/= (point) opoint) (outline-on-heading-p t))
24277 (while (and (> (funcall outline-level) level)
24278 (not (bobp)))
24279 (outline-previous-heading))
24280 (if (< (funcall outline-level) level)
24282 (point)))))
24284 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24285 "Goto to the end of a subtree."
24286 ;; This contains an exact copy of the original function, but it uses
24287 ;; `org-back-to-heading', to make it work also in invisible
24288 ;; trees. And is uses an invisible-ok argument.
24289 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24290 ;; Furthermore, when used inside Org, finding the end of a large subtree
24291 ;; with many children and grandchildren etc, this can be much faster
24292 ;; than the outline version.
24293 (org-back-to-heading invisible-ok)
24294 (let ((first t)
24295 (level (funcall outline-level)))
24296 (if (and (derived-mode-p 'org-mode) (< level 1000))
24297 ;; A true heading (not a plain list item), in Org-mode
24298 ;; This means we can easily find the end by looking
24299 ;; only for the right number of stars. Using a regexp to do
24300 ;; this is so much faster than using a Lisp loop.
24301 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24302 (forward-char 1)
24303 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24304 ;; something else, do it the slow way
24305 (while (and (not (eobp))
24306 (or first (> (funcall outline-level) level)))
24307 (setq first nil)
24308 (outline-next-heading)))
24309 (unless to-heading
24310 (if (memq (preceding-char) '(?\n ?\^M))
24311 (progn
24312 ;; Go to end of line before heading
24313 (forward-char -1)
24314 (if (memq (preceding-char) '(?\n ?\^M))
24315 ;; leave blank line before heading
24316 (forward-char -1))))))
24317 (point))
24319 (defun org-end-of-meta-data (&optional full)
24320 "Skip planning line and properties drawer in current entry.
24321 When optional argument FULL is non-nil, also skip empty lines,
24322 clocking lines and regular drawers at the beginning of the
24323 entry."
24324 (org-back-to-heading t)
24325 (forward-line)
24326 (when (org-looking-at-p org-planning-line-re) (forward-line))
24327 (when (looking-at org-property-drawer-re)
24328 (goto-char (match-end 0))
24329 (forward-line))
24330 (when (and full (not (org-at-heading-p)))
24331 (catch 'exit
24332 (let ((end (save-excursion (outline-next-heading) (point)))
24333 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24334 (while (not (eobp))
24335 (cond ((org-looking-at-p org-drawer-regexp)
24336 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24337 (forward-line)
24338 (throw 'exit t)))
24339 ((org-looking-at-p re) (forward-line))
24340 (t (throw 'exit t))))))))
24342 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24343 "Move forward to the ARG'th subheading at same level as this one.
24344 Stop at the first and last subheadings of a superior heading.
24345 Normally this only looks at visible headings, but when INVISIBLE-OK is
24346 non-nil it will also look at invisible ones."
24347 (interactive "p")
24348 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24349 (if (and arg (< arg 0))
24350 (goto-char (point-min))
24351 (outline-next-heading))
24352 (org-at-heading-p)
24353 (let ((level (- (match-end 0) (match-beginning 0) 1))
24354 (f (if (and arg (< arg 0))
24355 're-search-backward
24356 're-search-forward))
24357 (count (if arg (abs arg) 1))
24358 (result (point)))
24359 (while (and (prog1 (> count 0)
24360 (forward-char (if (and arg (< arg 0)) -1 1)))
24361 (funcall f org-outline-regexp-bol nil 'move))
24362 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24363 (cond ((< l level) (setq count 0))
24364 ((and (= l level)
24365 (or invisible-ok
24366 (progn
24367 (goto-char (line-beginning-position))
24368 (not (outline-invisible-p)))))
24369 (setq count (1- count))
24370 (when (eq l level)
24371 (setq result (point)))))))
24372 (goto-char result))
24373 (beginning-of-line 1)))
24375 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24376 "Move backward to the ARG'th subheading at same level as this one.
24377 Stop at the first and last subheadings of a superior heading."
24378 (interactive "p")
24379 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24381 (defun org-next-visible-heading (arg)
24382 "Move to the next visible heading.
24384 This function wraps `outline-next-visible-heading' with
24385 `org-with-limited-levels' in order to skip over inline tasks and
24386 respect customization of `org-odd-levels-only'."
24387 (interactive "p")
24388 (org-with-limited-levels
24389 (outline-next-visible-heading arg)))
24391 (defun org-previous-visible-heading (arg)
24392 "Move to the next visible heading.
24394 This function wraps `outline-previous-visible-heading' with
24395 `org-with-limited-levels' in order to skip over inline tasks and
24396 respect customization of `org-odd-levels-only'."
24397 (interactive "p")
24398 (org-with-limited-levels
24399 (outline-previous-visible-heading arg)))
24401 (defun org-next-block (arg &optional backward block-regexp)
24402 "Jump to the next block.
24404 With a prefix argument ARG, jump forward ARG many blocks.
24406 When BACKWARD is non-nil, jump to the previous block.
24408 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24409 Match data is set according to this regexp when the function
24410 returns.
24412 Return point at beginning of the opening line of found block.
24413 Throw an error if no block is found."
24414 (interactive "p")
24415 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24416 (case-fold-search t)
24417 (search-fn (if backward #'re-search-backward #'re-search-forward))
24418 (count (or arg 1))
24419 (origin (point))
24420 last-element)
24421 (if backward (beginning-of-line) (end-of-line))
24422 (while (and (> count 0) (funcall search-fn re nil t))
24423 (let ((element (save-excursion
24424 (goto-char (match-beginning 0))
24425 (save-match-data (org-element-at-point)))))
24426 (when (and (memq (org-element-type element)
24427 '(center-block comment-block dynamic-block
24428 example-block export-block quote-block
24429 special-block src-block verse-block))
24430 (<= (match-beginning 0)
24431 (org-element-property :post-affiliated element)))
24432 (setq last-element element)
24433 (decf count))))
24434 (if (= count 0)
24435 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24436 (save-match-data (org-show-context)))
24437 (goto-char origin)
24438 (user-error "No %s code blocks" (if backward "previous" "further")))))
24440 (defun org-previous-block (arg &optional block-regexp)
24441 "Jump to the previous block.
24442 With a prefix argument ARG, jump backward ARG many source blocks.
24443 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24444 (interactive "p")
24445 (org-next-block arg t block-regexp))
24447 (defun org-forward-paragraph ()
24448 "Move forward to beginning of next paragraph or equivalent.
24450 The function moves point to the beginning of the next visible
24451 structural element, which can be a paragraph, a table, a list
24452 item, etc. It also provides some special moves for convenience:
24454 - On an affiliated keyword, jump to the beginning of the
24455 relative element.
24456 - On an item or a footnote definition, move to the second
24457 element inside, if any.
24458 - On a table or a property drawer, jump after it.
24459 - On a verse or source block, stop after blank lines."
24460 (interactive)
24461 (when (eobp) (user-error "Cannot move further down"))
24462 (let* ((deactivate-mark nil)
24463 (element (org-element-at-point))
24464 (type (org-element-type element))
24465 (post-affiliated (org-element-property :post-affiliated element))
24466 (contents-begin (org-element-property :contents-begin element))
24467 (contents-end (org-element-property :contents-end element))
24468 (end (let ((end (org-element-property :end element)) (parent element))
24469 (while (and (setq parent (org-element-property :parent parent))
24470 (= (org-element-property :contents-end parent) end))
24471 (setq end (org-element-property :end parent)))
24472 end)))
24473 (cond ((not element)
24474 (skip-chars-forward " \r\t\n")
24475 (or (eobp) (beginning-of-line)))
24476 ;; On affiliated keywords, move to element's beginning.
24477 ((< (point) post-affiliated)
24478 (goto-char post-affiliated))
24479 ;; At a table row, move to the end of the table. Similarly,
24480 ;; at a node property, move to the end of the property
24481 ;; drawer.
24482 ((memq type '(node-property table-row))
24483 (goto-char (org-element-property
24484 :end (org-element-property :parent element))))
24485 ((memq type '(property-drawer table)) (goto-char end))
24486 ;; Consider blank lines as separators in verse and source
24487 ;; blocks to ease editing.
24488 ((memq type '(src-block verse-block))
24489 (when (eq type 'src-block)
24490 (setq contents-end
24491 (save-excursion (goto-char end)
24492 (skip-chars-backward " \r\t\n")
24493 (line-beginning-position))))
24494 (beginning-of-line)
24495 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24496 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24497 (goto-char end)
24498 (skip-chars-forward " \r\t\n")
24499 (if (= (point) contents-end) (goto-char end)
24500 (beginning-of-line))))
24501 ;; With no contents, just skip element.
24502 ((not contents-begin) (goto-char end))
24503 ;; If contents are invisible, skip the element altogether.
24504 ((outline-invisible-p (line-end-position))
24505 (case type
24506 (headline
24507 (org-with-limited-levels (outline-next-visible-heading 1)))
24508 ;; At a plain list, make sure we move to the next item
24509 ;; instead of skipping the whole list.
24510 (plain-list (forward-char)
24511 (org-forward-paragraph))
24512 (otherwise (goto-char end))))
24513 ((>= (point) contents-end) (goto-char end))
24514 ((>= (point) contents-begin)
24515 ;; This can only happen on paragraphs and plain lists.
24516 (case type
24517 (paragraph (goto-char end))
24518 ;; At a plain list, try to move to second element in
24519 ;; first item, if possible.
24520 (plain-list (end-of-line)
24521 (org-forward-paragraph))))
24522 ;; When contents start on the middle of a line (e.g. in
24523 ;; items and footnote definitions), try to reach first
24524 ;; element starting after current line.
24525 ((> (line-end-position) contents-begin)
24526 (end-of-line)
24527 (org-forward-paragraph))
24528 (t (goto-char contents-begin)))))
24530 (defun org-backward-paragraph ()
24531 "Move backward to start of previous paragraph or equivalent.
24533 The function moves point to the beginning of the current
24534 structural element, which can be a paragraph, a table, a list
24535 item, etc., or to the beginning of the previous visible one if
24536 point is already there. It also provides some special moves for
24537 convenience:
24539 - On an affiliated keyword, jump to the first one.
24540 - On a table or a property drawer, move to its beginning.
24541 - On a verse or source block, stop before blank lines."
24542 (interactive)
24543 (when (bobp) (user-error "Cannot move further up"))
24544 (let* ((deactivate-mark nil)
24545 (element (org-element-at-point))
24546 (type (org-element-type element))
24547 (contents-begin (org-element-property :contents-begin element))
24548 (contents-end (org-element-property :contents-end element))
24549 (post-affiliated (org-element-property :post-affiliated element))
24550 (begin (org-element-property :begin element)))
24551 (cond
24552 ((not element) (goto-char (point-min)))
24553 ((= (point) begin)
24554 (backward-char)
24555 (org-backward-paragraph))
24556 ((<= (point) post-affiliated) (goto-char begin))
24557 ((memq type '(node-property table-row))
24558 (goto-char (org-element-property
24559 :post-affiliated (org-element-property :parent element))))
24560 ((memq type '(property-drawer table)) (goto-char begin))
24561 ((memq type '(src-block verse-block))
24562 (when (eq type 'src-block)
24563 (setq contents-begin
24564 (save-excursion (goto-char begin) (forward-line) (point))))
24565 (if (= (point) contents-begin) (goto-char post-affiliated)
24566 ;; Inside a verse block, see blank lines as paragraph
24567 ;; separators.
24568 (let ((origin (point)))
24569 (skip-chars-backward " \r\t\n" contents-begin)
24570 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24571 (skip-chars-forward " \r\t\n" origin)
24572 (if (= (point) origin) (goto-char contents-begin)
24573 (beginning-of-line))))))
24574 ((not contents-begin) (goto-char (or post-affiliated begin)))
24575 ((eq type 'paragraph)
24576 (goto-char contents-begin)
24577 ;; When at first paragraph in an item or a footnote definition,
24578 ;; move directly to beginning of line.
24579 (let ((parent-contents
24580 (org-element-property
24581 :contents-begin (org-element-property :parent element))))
24582 (when (and parent-contents (= parent-contents contents-begin))
24583 (beginning-of-line))))
24584 ;; At the end of a greater element, move to the beginning of the
24585 ;; last element within.
24586 ((>= (point) contents-end)
24587 (goto-char (1- contents-end))
24588 (org-backward-paragraph))
24589 (t (goto-char (or post-affiliated begin))))
24590 ;; Ensure we never leave point invisible.
24591 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24593 (defun org-forward-element ()
24594 "Move forward by one element.
24595 Move to the next element at the same level, when possible."
24596 (interactive)
24597 (cond ((eobp) (user-error "Cannot move further down"))
24598 ((org-with-limited-levels (org-at-heading-p))
24599 (let ((origin (point)))
24600 (goto-char (org-end-of-subtree nil t))
24601 (unless (org-with-limited-levels (org-at-heading-p))
24602 (goto-char origin)
24603 (user-error "Cannot move further down"))))
24605 (let* ((elem (org-element-at-point))
24606 (end (org-element-property :end elem))
24607 (parent (org-element-property :parent elem)))
24608 (cond ((and parent (= (org-element-property :contents-end parent) end))
24609 (goto-char (org-element-property :end parent)))
24610 ((integer-or-marker-p end) (goto-char end))
24611 (t (message "No element at point")))))))
24613 (defun org-backward-element ()
24614 "Move backward by one element.
24615 Move to the previous element at the same level, when possible."
24616 (interactive)
24617 (cond ((bobp) (user-error "Cannot move further up"))
24618 ((org-with-limited-levels (org-at-heading-p))
24619 ;; At a headline, move to the previous one, if any, or stay
24620 ;; here.
24621 (let ((origin (point)))
24622 (org-with-limited-levels (org-backward-heading-same-level 1))
24623 ;; When current headline has no sibling above, move to its
24624 ;; parent.
24625 (when (= (point) origin)
24626 (or (org-with-limited-levels (org-up-heading-safe))
24627 (progn (goto-char origin)
24628 (user-error "Cannot move further up"))))))
24630 (let* ((elem (org-element-at-point))
24631 (beg (org-element-property :begin elem)))
24632 (cond
24633 ;; Move to beginning of current element if point isn't
24634 ;; there already.
24635 ((null beg) (message "No element at point"))
24636 ((/= (point) beg) (goto-char beg))
24637 (t (goto-char beg)
24638 (skip-chars-backward " \r\t\n")
24639 (unless (bobp)
24640 (let ((prev (org-element-at-point)))
24641 (goto-char (org-element-property :begin prev))
24642 (while (and (setq prev (org-element-property :parent prev))
24643 (<= (org-element-property :end prev) beg))
24644 (goto-char (org-element-property :begin prev)))))))))))
24646 (defun org-up-element ()
24647 "Move to upper element."
24648 (interactive)
24649 (if (org-with-limited-levels (org-at-heading-p))
24650 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24651 (let* ((elem (org-element-at-point))
24652 (parent (org-element-property :parent elem)))
24653 (if parent (goto-char (org-element-property :begin parent))
24654 (if (org-with-limited-levels (org-before-first-heading-p))
24655 (user-error "No surrounding element")
24656 (org-with-limited-levels (org-back-to-heading)))))))
24658 (defvar org-element-greater-elements)
24659 (defun org-down-element ()
24660 "Move to inner element."
24661 (interactive)
24662 (let ((element (org-element-at-point)))
24663 (cond
24664 ((memq (org-element-type element) '(plain-list table))
24665 (goto-char (org-element-property :contents-begin element))
24666 (forward-char))
24667 ((memq (org-element-type element) org-element-greater-elements)
24668 ;; If contents are hidden, first disclose them.
24669 (when (outline-invisible-p (line-end-position)) (org-cycle))
24670 (goto-char (or (org-element-property :contents-begin element)
24671 (user-error "No content for this element"))))
24672 (t (user-error "No inner element")))))
24674 (defun org-drag-element-backward ()
24675 "Move backward element at point."
24676 (interactive)
24677 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24678 (let* ((elem (org-element-at-point))
24679 (prev-elem
24680 (save-excursion
24681 (goto-char (org-element-property :begin elem))
24682 (skip-chars-backward " \r\t\n")
24683 (unless (bobp)
24684 (let* ((beg (org-element-property :begin elem))
24685 (prev (org-element-at-point))
24686 (up prev))
24687 (while (and (setq up (org-element-property :parent up))
24688 (<= (org-element-property :end up) beg))
24689 (setq prev up))
24690 prev)))))
24691 ;; Error out if no previous element or previous element is
24692 ;; a parent of the current one.
24693 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24694 (user-error "Cannot drag element backward")
24695 (let ((pos (point)))
24696 (org-element-swap-A-B prev-elem elem)
24697 (goto-char (+ (org-element-property :begin prev-elem)
24698 (- pos (org-element-property :begin elem)))))))))
24700 (defun org-drag-element-forward ()
24701 "Move forward element at point."
24702 (interactive)
24703 (let* ((pos (point))
24704 (elem (org-element-at-point)))
24705 (when (= (point-max) (org-element-property :end elem))
24706 (user-error "Cannot drag element forward"))
24707 (goto-char (org-element-property :end elem))
24708 (let ((next-elem (org-element-at-point)))
24709 (when (or (org-element-nested-p elem next-elem)
24710 (and (eq (org-element-type next-elem) 'headline)
24711 (not (eq (org-element-type elem) 'headline))))
24712 (goto-char pos)
24713 (user-error "Cannot drag element forward"))
24714 ;; Compute new position of point: it's shifted by NEXT-ELEM
24715 ;; body's length (without final blanks) and by the length of
24716 ;; blanks between ELEM and NEXT-ELEM.
24717 (let ((size-next (- (save-excursion
24718 (goto-char (org-element-property :end next-elem))
24719 (skip-chars-backward " \r\t\n")
24720 (forward-line)
24721 ;; Small correction if buffer doesn't end
24722 ;; with a newline character.
24723 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24724 (org-element-property :begin next-elem)))
24725 (size-blank (- (org-element-property :end elem)
24726 (save-excursion
24727 (goto-char (org-element-property :end elem))
24728 (skip-chars-backward " \r\t\n")
24729 (forward-line)
24730 (point)))))
24731 (org-element-swap-A-B elem next-elem)
24732 (goto-char (+ pos size-next size-blank))))))
24734 (defun org-drag-line-forward (arg)
24735 "Drag the line at point ARG lines forward."
24736 (interactive "p")
24737 (dotimes (n (abs arg))
24738 (let ((c (current-column)))
24739 (if (< 0 arg)
24740 (progn
24741 (beginning-of-line 2)
24742 (transpose-lines 1)
24743 (beginning-of-line 0))
24744 (transpose-lines 1)
24745 (beginning-of-line -1))
24746 (org-move-to-column c))))
24748 (defun org-drag-line-backward (arg)
24749 "Drag the line at point ARG lines backward."
24750 (interactive "p")
24751 (org-drag-line-forward (- arg)))
24753 (defun org-mark-element ()
24754 "Put point at beginning of this element, mark at end.
24756 Interactively, if this command is repeated or (in Transient Mark
24757 mode) if the mark is active, it marks the next element after the
24758 ones already marked."
24759 (interactive)
24760 (let (deactivate-mark)
24761 (if (and (org-called-interactively-p 'any)
24762 (or (and (eq last-command this-command) (mark t))
24763 (and transient-mark-mode mark-active)))
24764 (set-mark
24765 (save-excursion
24766 (goto-char (mark))
24767 (goto-char (org-element-property :end (org-element-at-point)))))
24768 (let ((element (org-element-at-point)))
24769 (end-of-line)
24770 (push-mark (org-element-property :end element) t t)
24771 (goto-char (org-element-property :begin element))))))
24773 (defun org-narrow-to-element ()
24774 "Narrow buffer to current element."
24775 (interactive)
24776 (let ((elem (org-element-at-point)))
24777 (cond
24778 ((eq (car elem) 'headline)
24779 (narrow-to-region
24780 (org-element-property :begin elem)
24781 (org-element-property :end elem)))
24782 ((memq (car elem) org-element-greater-elements)
24783 (narrow-to-region
24784 (org-element-property :contents-begin elem)
24785 (org-element-property :contents-end elem)))
24787 (narrow-to-region
24788 (org-element-property :begin elem)
24789 (org-element-property :end elem))))))
24791 (defun org-transpose-element ()
24792 "Transpose current and previous elements, keeping blank lines between.
24793 Point is moved after both elements."
24794 (interactive)
24795 (org-skip-whitespace)
24796 (let ((end (org-element-property :end (org-element-at-point))))
24797 (org-drag-element-backward)
24798 (goto-char end)))
24800 (defun org-unindent-buffer ()
24801 "Un-indent the visible part of the buffer.
24802 Relative indentation (between items, inside blocks, etc.) isn't
24803 modified."
24804 (interactive)
24805 (unless (eq major-mode 'org-mode)
24806 (user-error "Cannot un-indent a buffer not in Org mode"))
24807 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24808 unindent-tree ; For byte-compiler.
24809 (unindent-tree
24810 (function
24811 (lambda (contents)
24812 (mapc
24813 (lambda (element)
24814 (if (memq (org-element-type element) '(headline section))
24815 (funcall unindent-tree (org-element-contents element))
24816 (save-excursion
24817 (save-restriction
24818 (narrow-to-region
24819 (org-element-property :begin element)
24820 (org-element-property :end element))
24821 (org-do-remove-indentation)))))
24822 (reverse contents))))))
24823 (funcall unindent-tree (org-element-contents parse-tree))))
24825 (defun org-show-subtree ()
24826 "Show everything after this heading at deeper levels."
24827 (interactive)
24828 (outline-flag-region
24829 (point)
24830 (save-excursion
24831 (org-end-of-subtree t t))
24832 nil))
24834 (defun org-show-entry ()
24835 "Show the body directly following this heading.
24836 Show the heading too, if it is currently invisible."
24837 (interactive)
24838 (save-excursion
24839 (ignore-errors
24840 (org-back-to-heading t)
24841 (outline-flag-region
24842 (max (point-min) (1- (point)))
24843 (save-excursion
24844 (if (re-search-forward
24845 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24846 (match-beginning 1)
24847 (point-max)))
24848 nil)
24849 (org-cycle-hide-drawers 'children))))
24851 (defun org-make-options-regexp (kwds &optional extra)
24852 "Make a regular expression for keyword lines.
24853 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24854 when non-nil, is a regexp matching keywords names."
24855 (concat "^[ \t]*#\\+\\("
24856 (regexp-opt kwds)
24857 (and extra (concat (and kwds "\\|") extra))
24858 "\\):[ \t]*\\(.*\\)"))
24860 ;; Make isearch reveal the necessary context
24861 (defun org-isearch-end ()
24862 "Reveal context after isearch exits."
24863 (when isearch-success ; only if search was successful
24864 (if (featurep 'xemacs)
24865 ;; Under XEmacs, the hook is run in the correct place,
24866 ;; we directly show the context.
24867 (org-show-context 'isearch)
24868 ;; In Emacs the hook runs *before* restoring the overlays.
24869 ;; So we have to use a one-time post-command-hook to do this.
24870 ;; (Emacs 22 has a special variable, see function `org-mode')
24871 (unless (and (boundp 'isearch-mode-end-hook-quit)
24872 isearch-mode-end-hook-quit)
24873 ;; Only when the isearch was not quitted.
24874 (org-add-hook 'post-command-hook 'org-isearch-post-command
24875 'append 'local)))))
24877 (defun org-isearch-post-command ()
24878 "Remove self from hook, and show context."
24879 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24880 (org-show-context 'isearch))
24883 ;;;; Integration with and fixes for other packages
24885 ;;; Imenu support
24887 (defvar org-imenu-markers nil
24888 "All markers currently used by Imenu.")
24889 (make-variable-buffer-local 'org-imenu-markers)
24891 (defun org-imenu-new-marker (&optional pos)
24892 "Return a new marker for use by Imenu, and remember the marker."
24893 (let ((m (make-marker)))
24894 (move-marker m (or pos (point)))
24895 (push m org-imenu-markers)
24898 (defun org-imenu-get-tree ()
24899 "Produce the index for Imenu."
24900 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24901 (setq org-imenu-markers nil)
24902 (let* ((n org-imenu-depth)
24903 (re (concat "^" (org-get-limited-outline-regexp)))
24904 (subs (make-vector (1+ n) nil))
24905 (last-level 0)
24906 m level head0 head)
24907 (save-excursion
24908 (save-restriction
24909 (widen)
24910 (goto-char (point-max))
24911 (while (re-search-backward re nil t)
24912 (setq level (org-reduced-level (funcall outline-level)))
24913 (when (and (<= level n)
24914 (looking-at org-complex-heading-regexp)
24915 (setq head0 (org-match-string-no-properties 4)))
24916 (setq head (org-link-display-format head0)
24917 m (org-imenu-new-marker))
24918 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24919 (if (>= level last-level)
24920 (push (cons head m) (aref subs level))
24921 (push (cons head (aref subs (1+ level))) (aref subs level))
24922 (loop for i from (1+ level) to n do (aset subs i nil)))
24923 (setq last-level level)))))
24924 (aref subs 1)))
24926 (eval-after-load "imenu"
24927 '(progn
24928 (add-hook 'imenu-after-jump-hook
24929 (lambda ()
24930 (if (derived-mode-p 'org-mode)
24931 (org-show-context 'org-goto))))))
24933 (defun org-link-display-format (link)
24934 "Replace a link with its the description.
24935 If there is no description, use the link target."
24936 (save-match-data
24937 (if (string-match org-bracket-link-analytic-regexp link)
24938 (replace-match (if (match-end 5)
24939 (match-string 5 link)
24940 (concat (match-string 1 link)
24941 (match-string 3 link)))
24942 nil t link)
24943 link)))
24945 (defun org-toggle-link-display ()
24946 "Toggle the literal or descriptive display of links."
24947 (interactive)
24948 (if org-descriptive-links
24949 (progn (org-remove-from-invisibility-spec '(org-link))
24950 (org-restart-font-lock)
24951 (setq org-descriptive-links nil))
24952 (progn (add-to-invisibility-spec '(org-link))
24953 (org-restart-font-lock)
24954 (setq org-descriptive-links t))))
24956 ;; Speedbar support
24958 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24959 "Overlay marking the agenda restriction line in speedbar.")
24960 (overlay-put org-speedbar-restriction-lock-overlay
24961 'face 'org-agenda-restriction-lock)
24962 (overlay-put org-speedbar-restriction-lock-overlay
24963 'help-echo "Agendas are currently limited to this item.")
24964 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24966 (defun org-speedbar-set-agenda-restriction ()
24967 "Restrict future agenda commands to the location at point in speedbar.
24968 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24969 (interactive)
24970 (require 'org-agenda)
24971 (let (p m tp np dir txt)
24972 (cond
24973 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24974 'org-imenu t))
24975 (setq m (get-text-property p 'org-imenu-marker))
24976 (with-current-buffer (marker-buffer m)
24977 (goto-char m)
24978 (org-agenda-set-restriction-lock 'subtree)))
24979 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24980 'speedbar-function 'speedbar-find-file))
24981 (setq tp (previous-single-property-change
24982 (1+ p) 'speedbar-function)
24983 np (next-single-property-change
24984 tp 'speedbar-function)
24985 dir (speedbar-line-directory)
24986 txt (buffer-substring-no-properties (or tp (point-min))
24987 (or np (point-max))))
24988 (with-current-buffer (find-file-noselect
24989 (let ((default-directory dir))
24990 (expand-file-name txt)))
24991 (unless (derived-mode-p 'org-mode)
24992 (user-error "Cannot restrict to non-Org-mode file"))
24993 (org-agenda-set-restriction-lock 'file)))
24994 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24995 (move-overlay org-speedbar-restriction-lock-overlay
24996 (point-at-bol) (point-at-eol))
24997 (setq current-prefix-arg nil)
24998 (org-agenda-maybe-redo)))
25000 (defvar speedbar-file-key-map)
25001 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25002 (eval-after-load "speedbar"
25003 '(progn
25004 (speedbar-add-supported-extension ".org")
25005 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25006 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25007 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25008 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25009 (add-hook 'speedbar-visiting-tag-hook
25010 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25012 ;;; Fixes and Hacks for problems with other packages
25014 (defun org--flyspell-object-check-p (element)
25015 "Non-nil when Flyspell can check object at point.
25016 ELEMENT is the element at point."
25017 (let ((object (save-excursion
25018 (when (org-looking-at-p "\\>") (backward-char))
25019 (org-element-context element))))
25020 (case (org-element-type object)
25021 ;; Prevent checks in links due to keybinding conflict with
25022 ;; Flyspell.
25023 ((code entity export-snippet inline-babel-call
25024 inline-src-block line-break latex-fragment link macro
25025 statistics-cookie target timestamp verbatim)
25026 nil)
25027 (footnote-reference
25028 ;; Only in inline footnotes, within the definition.
25029 (and (eq (org-element-property :type object) 'inline)
25030 (< (save-excursion
25031 (goto-char (org-element-property :begin object))
25032 (search-forward ":" nil t 2))
25033 (point))))
25034 (otherwise t))))
25036 (defun org-mode-flyspell-verify ()
25037 "Function used for `flyspell-generic-check-word-predicate'."
25038 (if (org-at-heading-p)
25039 ;; At a headline or an inlinetask, check title only. This is
25040 ;; faster than relying on `org-element-at-point'.
25041 (and (save-excursion (beginning-of-line)
25042 (and (let ((case-fold-search t))
25043 (not (looking-at "\\*+ END[ \t]*$")))
25044 (looking-at org-complex-heading-regexp)))
25045 (match-beginning 4)
25046 (>= (point) (match-beginning 4))
25047 (or (not (match-beginning 5))
25048 (< (point) (match-beginning 5))))
25049 (let* ((element (org-element-at-point))
25050 (post-affiliated (org-element-property :post-affiliated element)))
25051 (cond
25052 ;; Ignore checks in all affiliated keywords but captions.
25053 ((< (point) post-affiliated)
25054 (and (save-excursion
25055 (beginning-of-line)
25056 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25057 (> (point) (match-end 0))
25058 (org--flyspell-object-check-p element)))
25059 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25060 ((let ((log (org-log-into-drawer)))
25061 (and log
25062 (let ((drawer (org-element-lineage element '(drawer))))
25063 (and drawer
25064 (eq (compare-strings
25065 log nil nil
25066 (org-element-property :drawer-name drawer) nil nil t)
25067 t)))))
25068 nil)
25070 (case (org-element-type element)
25071 ((comment quote-section) t)
25072 (comment-block
25073 ;; Allow checks between block markers, not on them.
25074 (and (> (line-beginning-position) post-affiliated)
25075 (save-excursion
25076 (end-of-line)
25077 (skip-chars-forward " \r\t\n")
25078 (< (point) (org-element-property :end element)))))
25079 ;; Arbitrary list of keywords where checks are meaningful.
25080 ;; Make sure point is on the value part of the element.
25081 (keyword
25082 (and (member (org-element-property :key element)
25083 '("DESCRIPTION" "TITLE"))
25084 (save-excursion
25085 (search-backward ":" (line-beginning-position) t))))
25086 ;; Check is globally allowed in paragraphs verse blocks and
25087 ;; table rows (after affiliated keywords) but some objects
25088 ;; must not be affected.
25089 ((paragraph table-row verse-block)
25090 (let ((cbeg (org-element-property :contents-begin element))
25091 (cend (org-element-property :contents-end element)))
25092 (and cbeg (>= (point) cbeg) (< (point) cend)
25093 (org--flyspell-object-check-p element))))))))))
25094 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25096 (defun org-remove-flyspell-overlays-in (beg end)
25097 "Remove flyspell overlays in region."
25098 (and (org-bound-and-true-p flyspell-mode)
25099 (fboundp 'flyspell-delete-region-overlays)
25100 (flyspell-delete-region-overlays beg end)))
25102 (defvar flyspell-delayed-commands)
25103 (eval-after-load "flyspell"
25104 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25106 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25107 (eval-after-load "bookmark"
25108 '(if (boundp 'bookmark-after-jump-hook)
25109 ;; We can use the hook
25110 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25111 ;; Hook not available, use advice
25112 (defadvice bookmark-jump (after org-make-visible activate)
25113 "Make the position visible."
25114 (org-bookmark-jump-unhide))))
25116 ;; Make sure saveplace shows the location if it was hidden
25117 (eval-after-load "saveplace"
25118 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25119 "Make the position visible."
25120 (org-bookmark-jump-unhide)))
25122 ;; Make sure ecb shows the location if it was hidden
25123 (eval-after-load "ecb"
25124 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25125 "Make hierarchy visible when jumping into location from ECB tree buffer."
25126 (if (derived-mode-p 'org-mode)
25127 (org-show-context))))
25129 (defun org-bookmark-jump-unhide ()
25130 "Unhide the current position, to show the bookmark location."
25131 (and (derived-mode-p 'org-mode)
25132 (or (outline-invisible-p)
25133 (save-excursion (goto-char (max (point-min) (1- (point))))
25134 (outline-invisible-p)))
25135 (org-show-context 'bookmark-jump)))
25137 (defun org-mark-jump-unhide ()
25138 "Make the point visible with `org-show-context' after jumping to the mark."
25139 (when (and (derived-mode-p 'org-mode)
25140 (outline-invisible-p))
25141 (org-show-context 'mark-goto)))
25143 (eval-after-load "simple"
25144 '(defadvice pop-to-mark-command (after org-make-visible activate)
25145 "Make the point visible with `org-show-context'."
25146 (org-mark-jump-unhide)))
25148 (eval-after-load "simple"
25149 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25150 "Make the point visible with `org-show-context'."
25151 (org-mark-jump-unhide)))
25153 (eval-after-load "simple"
25154 '(defadvice pop-global-mark (after org-make-visible activate)
25155 "Make the point visible with `org-show-context'."
25156 (org-mark-jump-unhide)))
25158 ;; Make session.el ignore our circular variable
25159 (defvar session-globals-exclude)
25160 (eval-after-load "session"
25161 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25163 ;;;; Finish up
25165 (provide 'org)
25167 (run-hooks 'org-load-hook)
25169 ;;; org.el ends here