Turn buffer local syntax variables into constants
[org-mode/org-tableheadings.git] / lisp / org.el
blobfaa73e48311de1ab803268fe89cfdfae1db1a1a8
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 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 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 ;; In Org buffers, the value of `outline-regexp' is that of
100 ;; `org-outline-regexp'. The only function still directly relying on
101 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
102 ;; job when `orgstruct-mode' is active.
103 (defvar org-outline-regexp "\\*+ "
104 "Regexp to match Org headlines.")
106 (defvar org-outline-regexp-bol "^\\*+ "
107 "Regexp to match Org headlines.
108 This is similar to `org-outline-regexp' but additionally makes
109 sure that we are at the beginning of the line.")
111 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
112 "Matches a headline, putting stars and text into groups.
113 Stars are put in group 1 and the trimmed body in group 2.")
115 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
116 (unless (boundp 'calendar-view-holidays-initially-flag)
117 (org-defvaralias 'calendar-view-holidays-initially-flag
118 'view-calendar-holidays-initially))
119 (unless (boundp 'calendar-view-diary-initially-flag)
120 (org-defvaralias 'calendar-view-diary-initially-flag
121 'view-diary-entries-initially))
122 (unless (boundp 'diary-fancy-buffer)
123 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
125 (declare-function org-add-archive-files "org-archive" (files))
127 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
128 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
129 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
130 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
133 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
134 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
135 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
136 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
137 (declare-function org-clock-update-time-maybe "org-clock" ())
138 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
141 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
142 (declare-function orgtbl-mode "org-table" (&optional arg))
143 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
144 (declare-function org-beamer-mode "ox-beamer" ())
145 (declare-function org-table-blank-field "org-table" ())
146 (declare-function org-table-edit-field "org-table" (arg))
147 (declare-function org-table-insert-row "org-table" (&optional arg))
148 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
149 (declare-function org-table-set-constants "org-table" ())
150 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-add-archive-files "org-archive" (files))
153 (declare-function org-id-find-id-file "org-id" (id))
154 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
155 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
156 (declare-function org-agenda-redo "org-agenda" (&optional all))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-paste-rectangle "org-table" ())
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
167 (declare-function org-plot/gnuplot "org-plot" (&optional params))
169 (declare-function org-element-at-point "org-element" ())
170 (declare-function org-element-cache-reset "org-element" (&optional all))
171 (declare-function org-element-cache-refresh "org-element" (pos))
172 (declare-function org-element-contents "org-element" (element))
173 (declare-function org-element-context "org-element" (&optional element))
174 (declare-function org-element-interpret-data "org-element"
175 (data &optional parent))
176 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
177 (declare-function org-element-parse-buffer "org-element"
178 (&optional granularity visible-only))
179 (declare-function org-element-property "org-element" (property element))
180 (declare-function org-element-put-property "org-element"
181 (element property value))
182 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
183 (declare-function org-element-parse-buffer "org-element"
184 (&optional granularity visible-only))
185 (declare-function org-element-type "org-element" (element))
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s)
196 "Remove whitespace at the beginning and the end of string S."
197 (replace-regexp-in-string
198 "\\`[ \t\n\r]+" ""
199 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
201 ;; load languages based on value of `org-babel-load-languages'
202 (defvar org-babel-load-languages)
204 ;;;###autoload
205 (defun org-babel-do-load-languages (sym value)
206 "Load the languages defined in `org-babel-load-languages'."
207 (set-default sym value)
208 (mapc (lambda (pair)
209 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
210 (if active
211 (progn
212 (require (intern (concat "ob-" lang))))
213 (progn
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
218 org-babel-load-languages))
220 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
221 ;;;###autoload
222 (defun org-babel-load-file (file &optional compile)
223 "Load Emacs Lisp source code blocks in the Org-mode FILE.
224 This function exports the source code using `org-babel-tangle'
225 and then loads the resulting file using `load-file'. With prefix
226 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
227 file to byte-code before it is loaded."
228 (interactive "fFile to load: \nP")
229 (let* ((age (lambda (file)
230 (float-time
231 (time-subtract (current-time)
232 (nth 5 (or (file-attributes (file-truename file))
233 (file-attributes file)))))))
234 (base-name (file-name-sans-extension file))
235 (exported-file (concat base-name ".el")))
236 ;; tangle if the org-mode file is newer than the elisp file
237 (unless (and (file-exists-p exported-file)
238 (> (funcall age file) (funcall age exported-file)))
239 (setq exported-file
240 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org-mode buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "IO" io)
280 (const :tag "J" J)
281 (const :tag "Java" java)
282 (const :tag "Javascript" js)
283 (const :tag "LaTeX" latex)
284 (const :tag "Ledger" ledger)
285 (const :tag "Lilypond" lilypond)
286 (const :tag "Lisp" lisp)
287 (const :tag "Makefile" makefile)
288 (const :tag "Maxima" maxima)
289 (const :tag "Matlab" matlab)
290 (const :tag "Mscgen" mscgen)
291 (const :tag "Ocaml" ocaml)
292 (const :tag "Octave" octave)
293 (const :tag "Org" org)
294 (const :tag "Perl" perl)
295 (const :tag "Pico Lisp" picolisp)
296 (const :tag "PlantUML" plantuml)
297 (const :tag "Python" python)
298 (const :tag "Ruby" ruby)
299 (const :tag "Sass" sass)
300 (const :tag "Scala" scala)
301 (const :tag "Scheme" scheme)
302 (const :tag "Screen" screen)
303 (const :tag "Shell Script" shell)
304 (const :tag "Shen" shen)
305 (const :tag "Sql" sql)
306 (const :tag "Sqlite" sqlite)
307 (const :tag "ebnf2ps" ebnf2ps))
308 :value-type (boolean :tag "Activate" :value t)))
310 ;;;; Customization variables
311 (defcustom org-clone-delete-id nil
312 "Remove ID property of clones of a subtree.
313 When non-nil, clones of a subtree don't inherit the ID property.
314 Otherwise they inherit the ID property with a new unique
315 identifier."
316 :type 'boolean
317 :version "24.1"
318 :group 'org-id)
320 ;;; Version
321 (org-check-version)
323 ;;;###autoload
324 (defun org-version (&optional here full message)
325 "Show the org-mode version.
326 Interactively, or when MESSAGE is non-nil, show it in echo area.
327 With prefix argument, or when HERE is non-nil, insert it at point.
328 In non-interactive uses, a reduced version string is output unless
329 FULL is given."
330 (interactive (list current-prefix-arg t (not current-prefix-arg)))
331 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
332 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
333 (load-suffixes (list ".el"))
334 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
335 (org-trash (or
336 (and (fboundp 'org-release) (fboundp 'org-git-version))
337 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
338 (load-suffixes save-load-suffixes)
339 (org-version (org-release))
340 (git-version (org-git-version))
341 (version (format "Org-mode version %s (%s @ %s)"
342 org-version
343 git-version
344 (if org-install-dir
345 (if (string= org-dir org-install-dir)
346 org-install-dir
347 (concat "mixed installation! " org-install-dir " and " org-dir))
348 "org-loaddefs.el can not be found!")))
349 (version1 (if full version org-version)))
350 (when here (insert version1))
351 (when message (message "%s" version1))
352 version1))
354 (defconst org-version (org-version))
357 ;;; Syntax Constants
359 ;;;; Block
361 (defconst org-block-regexp
362 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
363 "Regular expression for hiding blocks.")
365 (defconst org-dblock-start-re
366 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
367 "Matches the start line of a dynamic block, with parameters.")
369 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
370 "Matches the end of a dynamic block.")
372 ;;;; Clock and Planning
374 (defconst org-clock-string "CLOCK:"
375 "String used as prefix for timestamps clocking work hours on an item.")
377 (defconst org-closed-string "CLOSED:"
378 "String used as the prefix for timestamps logging closing a TODO entry.")
380 (defconst org-deadline-string "DEADLINE:"
381 "String to mark deadline entries.
382 A deadline is this string, followed by a time stamp. Should be a word,
383 terminated by a colon. You can insert a schedule keyword and
384 a timestamp with \\[org-deadline].")
386 (defconst org-scheduled-string "SCHEDULED:"
387 "String to mark scheduled TODO entries.
388 A schedule is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-schedule].")
392 (defconst org-ds-keyword-length
393 (+ 2
394 (apply #'max
395 (mapcar #'length
396 (list org-deadline-string org-scheduled-string
397 org-clock-string org-closed-string))))
398 "Maximum length of the DEADLINE and SCHEDULED keywords.")
400 (defconst org-planning-line-re
401 (concat "^[ \t]*"
402 (regexp-opt
403 (list org-closed-string org-deadline-string org-scheduled-string)
405 "Matches a line with planning info.
406 Matched keyword is in group 1.")
408 (defconst org-clock-line-re
409 (concat "^[ \t]*" org-clock-string)
410 "Matches a line with clock info.")
412 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
413 "Matches the DEADLINE keyword.")
415 (defconst org-deadline-time-regexp
416 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
417 "Matches the DEADLINE keyword together with a time stamp.")
419 (defconst org-deadline-time-hour-regexp
420 (concat "\\<" org-deadline-string
421 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
422 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
424 (defconst org-deadline-line-regexp
425 (concat "\\<\\(" org-deadline-string "\\).*")
426 "Matches the DEADLINE keyword and the rest of the line.")
428 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
429 "Matches the SCHEDULED keyword.")
431 (defconst org-scheduled-time-regexp
432 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
433 "Matches the SCHEDULED keyword together with a time stamp.")
435 (defconst org-scheduled-time-hour-regexp
436 (concat "\\<" org-scheduled-string
437 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
438 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
440 (defconst org-closed-time-regexp
441 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
442 "Matches the CLOSED keyword together with a time stamp.")
444 (defconst org-keyword-time-regexp
445 (concat "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string
448 org-clock-string)
450 " *[[<]\\([^]>]+\\)[]>]")
451 "Matches any of the 4 keywords, together with the time stamp.")
453 (defconst org-keyword-time-not-clock-regexp
454 (concat
455 "\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string) t)
458 " *[[<]\\([^]>]+\\)[]>]")
459 "Matches any of the 3 keywords, together with the time stamp.")
461 (defconst org-maybe-keyword-time-regexp
462 (concat "\\(\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string
465 org-clock-string)
467 "\\)?"
468 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
469 "\\|"
470 "<%%([^\r\n>]*>\\)")
471 "Matches a timestamp, possibly preceded by a keyword.")
473 (defconst org-all-time-keywords
474 (mapcar (lambda (w) (substring w 0 -1))
475 (list org-scheduled-string org-deadline-string
476 org-clock-string org-closed-string))
477 "List of time keywords.")
479 ;;;; Drawer
481 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
482 "Matches first or last line of a hidden block.
483 Group 1 contains drawer's name or \"END\".")
485 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
486 "Regular expression matching the first line of a property drawer.")
488 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a property drawer.")
491 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
492 "Regular expression matching the first line of a clock drawer.")
494 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
495 "Regular expression matching the last line of a clock drawer.")
497 (defconst org-property-drawer-re
498 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
499 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
500 "[ \t]*:END:[ \t]*$")
501 "Matches an entire property drawer.")
503 (defconst org-clock-drawer-re
504 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
505 org-clock-drawer-end-re "\\)\n?")
506 "Matches an entire clock drawer.")
508 ;;;; Headline
510 (defconst org-heading-keyword-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline with some keyword.
513 This regexp will match the headline of any node which has the
514 exact keyword that is put into the format. The keyword isn't in
515 any group by default, but the stars and the body are.")
517 (defconst org-heading-keyword-maybe-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline, possibly with some keyword.
520 This regexp can match any headline with the specified keyword, or
521 without a keyword. The keyword isn't in any group by default,
522 but the stars and the body are.")
524 (defconst org-archive-tag "ARCHIVE"
525 "The tag that marks a subtree as archived.
526 An archived subtree does not open during visibility cycling, and does
527 not contribute to the agenda listings.")
529 (defconst org-comment-string "COMMENT"
530 "Entries starting with this keyword will never be exported.
531 An entry can be toggled between COMMENT and normal with
532 \\[org-toggle-comment].")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast 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 (defconst org-context-choice
1164 '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const agenda)
1171 (const org-goto)
1172 (const occur-tree)
1173 (const tags-tree)
1174 (const link-search)
1175 (const mark-goto)
1176 (const bookmark-jump)
1177 (const isearch)
1178 (const default))
1179 (boolean))))
1180 "Contexts for the reveal options.")
1182 (defcustom org-show-hierarchy-above '((default . t))
1183 "Non-nil means show full hierarchy when revealing a location.
1184 Org-mode often shows locations in an org-mode file which might have
1185 been invisible before. When this is set, the hierarchy of headings
1186 above the exposed location is shown.
1187 Turning this off for example for sparse trees makes them very compact.
1188 Instead of t, this can also be an alist specifying this option for different
1189 contexts. Valid contexts are
1190 agenda when exposing an entry from the agenda
1191 org-goto when using the command `org-goto' on key C-c C-j
1192 occur-tree when using the command `org-occur' on key C-c /
1193 tags-tree when constructing a sparse tree based on tags matches
1194 link-search when exposing search matches associated with a link
1195 mark-goto when exposing the jump goal of a mark
1196 bookmark-jump when exposing a bookmark location
1197 isearch when exiting from an incremental search
1198 default default for all contexts not set explicitly"
1199 :group 'org-reveal-location
1200 :type org-context-choice)
1202 (defcustom org-show-following-heading '((default . nil))
1203 "Non-nil means show following heading when revealing a location.
1204 Org-mode often shows locations in an org-mode file which might have
1205 been invisible before. When this is set, the heading following the
1206 match is shown.
1207 Turning this off for example for sparse trees makes them very compact,
1208 but makes it harder to edit the location of the match. In such a case,
1209 use the command \\[org-reveal] to show more context.
1210 Instead of t, this can also be an alist specifying this option for different
1211 contexts. See `org-show-hierarchy-above' for valid contexts."
1212 :group 'org-reveal-location
1213 :type org-context-choice)
1215 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1216 "Non-nil means show all sibling heading when revealing a location.
1217 Org-mode often shows locations in an org-mode file which might have
1218 been invisible before. When this is set, the sibling of the current entry
1219 heading are all made visible. If `org-show-hierarchy-above' is t,
1220 the same happens on each level of the hierarchy above the current entry.
1222 By default this is on for the isearch context, off for all other contexts.
1223 Turning this off for example for sparse trees makes them very compact,
1224 but makes it harder to edit the location of the match. In such a case,
1225 use the command \\[org-reveal] to show more context.
1226 Instead of t, this can also be an alist specifying this option for different
1227 contexts. See `org-show-hierarchy-above' for valid contexts."
1228 :group 'org-reveal-location
1229 :type org-context-choice
1230 :version "24.4"
1231 :package-version '(Org . "8.0"))
1233 (defcustom org-show-entry-below '((default . nil))
1234 "Non-nil means show the entry below a headline when revealing a location.
1235 Org-mode often shows locations in an org-mode file which might have
1236 been invisible before. When this is set, the text below the headline that is
1237 exposed is also shown.
1239 By default this is off for all contexts.
1240 Instead of t, this can also be an alist specifying this option for different
1241 contexts. See `org-show-hierarchy-above' for valid contexts."
1242 :group 'org-reveal-location
1243 :type org-context-choice)
1245 (defcustom org-indirect-buffer-display 'other-window
1246 "How should indirect tree buffers be displayed?
1247 This applies to indirect buffers created with the commands
1248 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1249 Valid values are:
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group 'org-structure
1257 :group 'org-agenda-windows
1258 :type '(choice
1259 (const :tag "In current window" current-window)
1260 (const :tag "In current frame, other window" other-window)
1261 (const :tag "Each time a new frame" new-frame)
1262 (const :tag "One dedicated frame" dedicated-frame)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group 'org-structure
1275 :type '(choice
1276 (const :tag "Never" nil)
1277 (const :tag "At beginning of headline stars" t)
1278 (function)))
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group 'org-structure
1293 :type '(repeat :value ("k" . ignore)
1294 (choice :value ("k" . ignore)
1295 (list :tag "Descriptive Headline" (string :tag "Headline"))
1296 (cons :tag "Letter and Command"
1297 (string :tag "Command letter")
1298 (choice
1299 (function)
1300 (sexp))))))
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture "org-capture-last-stored"
1304 :last-refile "org-refile-last-stored"
1305 :last-capture-marker "org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1309 :last-capture
1310 :last-capture-marker
1311 :last-refile
1312 When a key does not show up in the property list, the corresponding bookmark
1313 is not set."
1314 :group 'org-structure
1315 :type 'plist)
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org-mode."
1319 :tag "Org Cycle"
1320 :group 'org-structure)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1324 :group 'org-cycle
1325 :type 'boolean)
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1336 than its value."
1337 :group 'org-cycle
1338 :type '(choice
1339 (const :tag "No limit" nil)
1340 (integer :tag "Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org-mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1348 :group 'org-startup
1349 :group 'org-cycle
1350 :type 'boolean)
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1354 This makes it possible to do global cycling without having to use S-TAB or
1355 \\[universal-argument] TAB. For this special case to work, the first line
1356 of the buffer must not be a headline -- it may be empty or some other text.
1357 When used in this way, `org-cycle-hook' is disabled temporarily to make
1358 sure the cursor stays at the beginning of the buffer. When this option is
1359 nil, don't do anything special at the beginning of the buffer."
1360 :group 'org-cycle
1361 :type 'boolean)
1363 (defcustom org-cycle-level-after-item/entry-creation t
1364 "Non-nil means cycle entry level or item indentation in new empty entries.
1366 When the cursor is at the end of an empty headline, i.e., with only stars
1367 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1368 and then all possible ancestor states, before returning to the original state.
1369 This makes data entry extremely fast: M-RET to create a new headline,
1370 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1372 When the cursor is at the end of an empty plain list item, one TAB will
1373 make it a subitem, two or more tabs will back up to make this an item
1374 higher up in the item hierarchy."
1375 :group 'org-cycle
1376 :type 'boolean)
1378 (defcustom org-cycle-emulate-tab t
1379 "Where should `org-cycle' emulate TAB.
1380 nil Never
1381 white Only in completely white lines
1382 whitestart Only at the beginning of lines, before the first non-white char
1383 t Everywhere except in headlines
1384 exc-hl-bol Everywhere except at the start of a headline
1385 If TAB is used in a place where it does not emulate TAB, the current subtree
1386 visibility is cycled."
1387 :group 'org-cycle
1388 :type '(choice (const :tag "Never" nil)
1389 (const :tag "Only in completely white lines" white)
1390 (const :tag "Before first char in a line" whitestart)
1391 (const :tag "Everywhere except in headlines" t)
1392 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1394 (defcustom org-cycle-separator-lines 2
1395 "Number of empty lines needed to keep an empty line between collapsed trees.
1396 If you leave an empty line between the end of a subtree and the following
1397 headline, this empty line is hidden when the subtree is folded.
1398 Org-mode will leave (exactly) one empty line visible if the number of
1399 empty lines is equal or larger to the number given in this variable.
1400 So the default 2 means at least 2 empty lines after the end of a subtree
1401 are needed to produce free space between a collapsed subtree and the
1402 following headline.
1404 If the number is negative, and the number of empty lines is at least -N,
1405 all empty lines are shown.
1407 Special case: when 0, never leave empty lines in collapsed view."
1408 :group 'org-cycle
1409 :type 'integer)
1410 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1412 (defcustom org-pre-cycle-hook nil
1413 "Hook that is run before visibility cycling is happening.
1414 The function(s) in this hook must accept a single argument which indicates
1415 the new state that will be set right after running this hook. The
1416 argument is a symbol. Before a global state change, it can have the values
1417 `overview', `content', or `all'. Before a local state change, it can have
1418 the values `folded', `children', or `subtree'."
1419 :group 'org-cycle
1420 :type 'hook)
1422 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1423 org-cycle-hide-drawers
1424 org-cycle-hide-inline-tasks
1425 org-cycle-show-empty-lines
1426 org-optimize-window-after-visibility-change)
1427 "Hook that is run after `org-cycle' has changed the buffer visibility.
1428 The function(s) in this hook must accept a single argument which indicates
1429 the new state that was set by the most recent `org-cycle' command. The
1430 argument is a symbol. After a global state change, it can have the values
1431 `overview', `contents', or `all'. After a local state change, it can have
1432 the values `folded', `children', or `subtree'."
1433 :group 'org-cycle
1434 :type 'hook)
1436 (defgroup org-edit-structure nil
1437 "Options concerning structure editing in Org-mode."
1438 :tag "Org Edit Structure"
1439 :group 'org-structure)
1441 (defcustom org-odd-levels-only nil
1442 "Non-nil means skip even levels and only use odd levels for the outline.
1443 This has the effect that two stars are being added/taken away in
1444 promotion/demotion commands. It also influences how levels are
1445 handled by the exporters.
1446 Changing it requires restart of `font-lock-mode' to become effective
1447 for fontification also in regions already fontified.
1448 You may also set this on a per-file basis by adding one of the following
1449 lines to the buffer:
1451 #+STARTUP: odd
1452 #+STARTUP: oddeven"
1453 :group 'org-edit-structure
1454 :group 'org-appearance
1455 :type 'boolean)
1457 (defcustom org-adapt-indentation t
1458 "Non-nil means adapt indentation to outline node level.
1460 When this variable is set, Org assumes that you write outlines by
1461 indenting text in each node to align with the headline (after the stars).
1462 The following issues are influenced by this variable:
1464 - When this is set and the *entire* text in an entry is indented, the
1465 indentation is increased by one space in a demotion command, and
1466 decreased by one in a promotion command. If any line in the entry
1467 body starts with text at column 0, indentation is not changed at all.
1469 - Property drawers and planning information is inserted indented when
1470 this variable s set. When nil, they will not be indented.
1472 - TAB indents a line relative to context. The lines below a headline
1473 will be indented when this variable is set.
1475 Note that this is all about true indentation, by adding and removing
1476 space characters. See also `org-indent.el' which does level-dependent
1477 indentation in a virtual way, i.e. at display time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 When nil, the new heading is created directly after the current line.
1619 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1620 this variable on for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not.
1632 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1633 the setting here is ignored and no empty line is inserted to avoid breaking
1634 the list structure."
1635 :group 'org-edit-structure
1636 :type '(list
1637 (cons (const heading)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))
1641 (cons (const plain-list-item)
1642 (choice (const :tag "Never" nil)
1643 (const :tag "Always" t)
1644 (const :tag "Auto" auto)))))
1646 (defcustom org-insert-heading-hook nil
1647 "Hook being run after inserting a new heading."
1648 :group 'org-edit-structure
1649 :type 'hook)
1651 (defcustom org-enable-fixed-width-editor t
1652 "Non-nil means lines starting with \":\" are treated as fixed-width.
1653 This currently only means they are never auto-wrapped.
1654 When nil, such lines will be treated like ordinary lines."
1655 :group 'org-edit-structure
1656 :type 'boolean)
1658 (defcustom org-goto-auto-isearch t
1659 "Non-nil means typing characters in `org-goto' starts incremental search.
1660 When nil, you can use these keybindings to navigate the buffer:
1662 q Quit the org-goto interface
1663 n Go to the next visible heading
1664 p Go to the previous visible heading
1665 f Go one heading forward on same level
1666 b Go one heading backward on same level
1667 u Go one heading up"
1668 :group 'org-edit-structure
1669 :type 'boolean)
1671 (defgroup org-sparse-trees nil
1672 "Options concerning sparse trees in Org-mode."
1673 :tag "Org Sparse Trees"
1674 :group 'org-structure)
1676 (defcustom org-highlight-sparse-tree-matches t
1677 "Non-nil means highlight all matches that define a sparse tree.
1678 The highlights will automatically disappear the next time the buffer is
1679 changed by an edit command."
1680 :group 'org-sparse-trees
1681 :type 'boolean)
1683 (defcustom org-remove-highlights-with-change t
1684 "Non-nil means any change to the buffer will remove temporary highlights.
1685 Such highlights are created by `org-occur' and `org-clock-display'.
1686 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1687 The highlights created by `org-toggle-latex-fragment' always need
1688 `C-c C-x C-l' to be removed."
1689 :group 'org-sparse-trees
1690 :group 'org-time
1691 :type 'boolean)
1694 (defcustom org-occur-hook '(org-first-headline-recenter)
1695 "Hook that is run after `org-occur' has constructed a sparse tree.
1696 This can be used to recenter the window to show as much of the structure
1697 as possible."
1698 :group 'org-sparse-trees
1699 :type 'hook)
1701 (defgroup org-imenu-and-speedbar nil
1702 "Options concerning imenu and speedbar in Org-mode."
1703 :tag "Org Imenu and Speedbar"
1704 :group 'org-structure)
1706 (defcustom org-imenu-depth 2
1707 "The maximum level for Imenu access to Org-mode headlines.
1708 This also applied for speedbar access."
1709 :group 'org-imenu-and-speedbar
1710 :type 'integer)
1712 (defgroup org-table nil
1713 "Options concerning tables in Org-mode."
1714 :tag "Org Table"
1715 :group 'org)
1717 (defcustom org-enable-table-editor 'optimized
1718 "Non-nil means lines starting with \"|\" are handled by the table editor.
1719 When nil, such lines will be treated like ordinary lines.
1721 When equal to the symbol `optimized', the table editor will be optimized to
1722 do the following:
1723 - Automatic overwrite mode in front of whitespace in table fields.
1724 This makes the structure of the table stay in tact as long as the edited
1725 field does not exceed the column width.
1726 - Minimize the number of realigns. Normally, the table is aligned each time
1727 TAB or RET are pressed to move to another field. With optimization this
1728 happens only if changes to a field might have changed the column width.
1729 Optimization requires replacing the functions `self-insert-command',
1730 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1731 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1732 very good at guessing when a re-align will be necessary, but you can always
1733 force one with \\[org-ctrl-c-ctrl-c].
1735 If you would like to use the optimized version in Org-mode, but the
1736 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1738 This variable can be used to turn on and off the table editor during a session,
1739 but in order to toggle optimization, a restart is required.
1741 See also the variable `org-table-auto-blank-field'."
1742 :group 'org-table
1743 :type '(choice
1744 (const :tag "off" nil)
1745 (const :tag "on" t)
1746 (const :tag "on, optimized" optimized)))
1748 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1749 (version<= emacs-version "24.1"))
1750 "Non-nil means cluster self-insert commands for undo when possible.
1751 If this is set, then, like in the Emacs command loop, 20 consecutive
1752 characters will be undone together.
1753 This is configurable, because there is some impact on typing performance."
1754 :group 'org-table
1755 :type 'boolean)
1757 (defcustom org-table-tab-recognizes-table.el t
1758 "Non-nil means TAB will automatically notice a table.el table.
1759 When it sees such a table, it moves point into it and - if necessary -
1760 calls `table-recognize-table'."
1761 :group 'org-table-editing
1762 :type 'boolean)
1764 (defgroup org-link nil
1765 "Options concerning links in Org-mode."
1766 :tag "Org Link"
1767 :group 'org)
1769 (defvar org-link-abbrev-alist-local nil
1770 "Buffer-local version of `org-link-abbrev-alist', which see.
1771 The value of this is taken from the #+LINK lines.")
1772 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1774 (defcustom org-link-abbrev-alist nil
1775 "Alist of link abbreviations.
1776 The car of each element is a string, to be replaced at the start of a link.
1777 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1778 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1780 [[linkkey:tag][description]]
1782 The 'linkkey' must be a word word, starting with a letter, followed
1783 by letters, numbers, '-' or '_'.
1785 If REPLACE is a string, the tag will simply be appended to create the link.
1786 If the string contains \"%s\", the tag will be inserted there. If the string
1787 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1788 at that point (see the function `url-hexify-string'). If the string contains
1789 the specifier \"%(my-function)\", then the custom function `my-function' will
1790 be invoked: this function takes the tag as its only argument and must return
1791 a string.
1793 REPLACE may also be a function that will be called with the tag as the
1794 only argument to create the link, which should be returned as a string.
1796 See the manual for examples."
1797 :group 'org-link
1798 :type '(repeat
1799 (cons
1800 (string :tag "Protocol")
1801 (choice
1802 (string :tag "Format")
1803 (function)))))
1805 (defcustom org-descriptive-links t
1806 "Non-nil means Org will display descriptive links.
1807 E.g. [[http://orgmode.org][Org website]] will be displayed as
1808 \"Org Website\", hiding the link itself and just displaying its
1809 description. When set to `nil', Org will display the full links
1810 literally.
1812 You can interactively set the value of this variable by calling
1813 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1814 :group 'org-link
1815 :type 'boolean)
1817 (defcustom org-link-file-path-type 'adaptive
1818 "How the path name in file links should be stored.
1819 Valid values are:
1821 relative Relative to the current directory, i.e. the directory of the file
1822 into which the link is being inserted.
1823 absolute Absolute path, if possible with ~ for home directory.
1824 noabbrev Absolute path, no abbreviation of home directory.
1825 adaptive Use relative path for files in the current directory and sub-
1826 directories of it. For other files, use an absolute path."
1827 :group 'org-link
1828 :type '(choice
1829 (const relative)
1830 (const absolute)
1831 (const noabbrev)
1832 (const adaptive)))
1834 (defvaralias 'org-activate-links 'org-highlight-links)
1835 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1836 "Types of links that should be highlighted in Org-mode files.
1838 This is a list of symbols, each one of them leading to the
1839 highlighting of a certain link type.
1841 You can still open links that are not highlighted.
1843 In principle, it does not hurt to turn on highlighting for all
1844 link types. There may be a small gain when turning off unused
1845 link types. The types are:
1847 bracket The recommended [[link][description]] or [[link]] links with hiding.
1848 angle Links in angular brackets that may contain whitespace like
1849 <bbdb:Carsten Dominik>.
1850 plain Plain links in normal text, no whitespace, like http://google.com.
1851 radio Text that is matched by a radio target, see manual for details.
1852 tag Tag settings in a headline (link to tag search).
1853 date Time stamps (link to calendar).
1854 footnote Footnote labels.
1856 If you set this variable during an Emacs session, use `org-mode-restart'
1857 in the Org buffer so that the change takes effect."
1858 :group 'org-link
1859 :group 'org-appearance
1860 :type '(set :greedy t
1861 (const :tag "Double bracket links" bracket)
1862 (const :tag "Angular bracket links" angle)
1863 (const :tag "Plain text links" plain)
1864 (const :tag "Radio target matches" radio)
1865 (const :tag "Tags" tag)
1866 (const :tag "Timestamps" date)
1867 (const :tag "Footnotes" footnote)))
1869 (defcustom org-make-link-description-function nil
1870 "Function to use for generating link descriptions from links.
1871 When nil, the link location will be used. This function must take
1872 two parameters: the first one is the link, the second one is the
1873 description generated by `org-insert-link'. The function should
1874 return the description to use."
1875 :group 'org-link
1876 :type '(choice (const nil) (function)))
1878 (defgroup org-link-store nil
1879 "Options concerning storing links in Org-mode."
1880 :tag "Org Store Link"
1881 :group 'org-link)
1883 (defcustom org-url-hexify-p t
1884 "When non-nil, hexify URL when creating a link."
1885 :type 'boolean
1886 :version "24.3"
1887 :group 'org-link-store)
1889 (defcustom org-email-link-description-format "Email %c: %.30s"
1890 "Format of the description part of a link to an email or usenet message.
1891 The following %-escapes will be replaced by corresponding information:
1893 %F full \"From\" field
1894 %f name, taken from \"From\" field, address if no name
1895 %T full \"To\" field
1896 %t first name in \"To\" field, address if no name
1897 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1898 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1899 %s subject
1900 %d date
1901 %m message-id.
1903 You may use normal field width specification between the % and the letter.
1904 This is for example useful to limit the length of the subject.
1906 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1907 :group 'org-link-store
1908 :type 'string)
1910 (defcustom org-from-is-user-regexp
1911 (let (r1 r2)
1912 (when (and user-mail-address (not (string= user-mail-address "")))
1913 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1914 (when (and user-full-name (not (string= user-full-name "")))
1915 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1916 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1917 "Regexp matched against the \"From:\" header of an email or usenet message.
1918 It should match if the message is from the user him/herself."
1919 :group 'org-link-store
1920 :type 'regexp)
1922 (defcustom org-context-in-file-links t
1923 "Non-nil means file links from `org-store-link' contain context.
1924 A search string will be added to the file name with :: as separator and
1925 used to find the context when the link is activated by the command
1926 `org-open-at-point'. When this option is t, the entire active region
1927 will be placed in the search string of the file link. If set to a
1928 positive integer, only the first n lines of context will be stored.
1930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1931 negates this setting for the duration of the command."
1932 :group 'org-link-store
1933 :type '(choice boolean integer))
1935 (defcustom org-keep-stored-link-after-insertion nil
1936 "Non-nil means keep link in list for entire session.
1938 The command `org-store-link' adds a link pointing to the current
1939 location to an internal list. These links accumulate during a session.
1940 The command `org-insert-link' can be used to insert links into any
1941 Org-mode file (offering completion for all stored links). When this
1942 option is nil, every link which has been inserted once using \\[org-insert-link]
1943 will be removed from the list, to make completing the unused links
1944 more efficient."
1945 :group 'org-link-store
1946 :type 'boolean)
1948 (defgroup org-link-follow nil
1949 "Options concerning following links in Org-mode."
1950 :tag "Org Follow Link"
1951 :group 'org-link)
1953 (defcustom org-link-translation-function nil
1954 "Function to translate links with different syntax to Org syntax.
1955 This can be used to translate links created for example by the Planner
1956 or emacs-wiki packages to Org syntax.
1957 The function must accept two parameters, a TYPE containing the link
1958 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1959 which is everything after the link protocol. It should return a cons
1960 with possibly modified values of type and path.
1961 Org contains a function for this, so if you set this variable to
1962 `org-translate-link-from-planner', you should be able follow many
1963 links created by planner."
1964 :group 'org-link-follow
1965 :type '(choice (const nil) (function)))
1967 (defcustom org-follow-link-hook nil
1968 "Hook that is run after a link has been followed."
1969 :group 'org-link-follow
1970 :type 'hook)
1972 (defcustom org-tab-follows-link nil
1973 "Non-nil means on links TAB will follow the link.
1974 Needs to be set before org.el is loaded.
1975 This really should not be used, it does not make sense, and the
1976 implementation is bad."
1977 :group 'org-link-follow
1978 :type 'boolean)
1980 (defcustom org-return-follows-link nil
1981 "Non-nil means on links RET will follow the link.
1982 In tables, the special behavior of RET has precedence."
1983 :group 'org-link-follow
1984 :type 'boolean)
1986 (defcustom org-mouse-1-follows-link
1987 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1988 "Non-nil means mouse-1 on a link will follow the link.
1989 A longer mouse click will still set point. Does not work on XEmacs.
1990 Needs to be set before org.el is loaded."
1991 :group 'org-link-follow
1992 :version "24.4"
1993 :package-version '(Org . "8.3")
1994 :type '(choice
1995 (const :tag "A double click follows the link" double)
1996 (const :tag "Unconditionally follow the link with mouse-1" t)
1997 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1999 (defcustom org-mark-ring-length 4
2000 "Number of different positions to be recorded in the ring.
2001 Changing this requires a restart of Emacs to work correctly."
2002 :group 'org-link-follow
2003 :type 'integer)
2005 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2006 "Non-nil means internal links in Org files must exactly match a headline.
2007 When nil, the link search tries to match a phrase with all words
2008 in the search text."
2009 :group 'org-link-follow
2010 :version "24.1"
2011 :type '(choice
2012 (const :tag "Use fuzzy text search" nil)
2013 (const :tag "Match only exact headline" t)
2014 (const :tag "Match exact headline or query to create it"
2015 query-to-create)))
2017 (defcustom org-link-frame-setup
2018 '((vm . vm-visit-folder-other-frame)
2019 (vm-imap . vm-visit-imap-folder-other-frame)
2020 (gnus . org-gnus-no-new-news)
2021 (file . find-file-other-window)
2022 (wl . wl-other-frame))
2023 "Setup the frame configuration for following links.
2024 When following a link with Emacs, it may often be useful to display
2025 this link in another window or frame. This variable can be used to
2026 set this up for the different types of links.
2027 For VM, use any of
2028 `vm-visit-folder'
2029 `vm-visit-folder-other-window'
2030 `vm-visit-folder-other-frame'
2031 For Gnus, use any of
2032 `gnus'
2033 `gnus-other-frame'
2034 `org-gnus-no-new-news'
2035 For FILE, use any of
2036 `find-file'
2037 `find-file-other-window'
2038 `find-file-other-frame'
2039 For Wanderlust use any of
2040 `wl'
2041 `wl-other-frame'
2042 For the calendar, use the variable `calendar-setup'.
2043 For BBDB, it is currently only possible to display the matches in
2044 another window."
2045 :group 'org-link-follow
2046 :type '(list
2047 (cons (const vm)
2048 (choice
2049 (const vm-visit-folder)
2050 (const vm-visit-folder-other-window)
2051 (const vm-visit-folder-other-frame)))
2052 (cons (const vm-imap)
2053 (choice
2054 (const vm-visit-imap-folder)
2055 (const vm-visit-imap-folder-other-window)
2056 (const vm-visit-imap-folder-other-frame)))
2057 (cons (const gnus)
2058 (choice
2059 (const gnus)
2060 (const gnus-other-frame)
2061 (const org-gnus-no-new-news)))
2062 (cons (const file)
2063 (choice
2064 (const find-file)
2065 (const find-file-other-window)
2066 (const find-file-other-frame)))
2067 (cons (const wl)
2068 (choice
2069 (const wl)
2070 (const wl-other-frame)))))
2072 (defcustom org-display-internal-link-with-indirect-buffer nil
2073 "Non-nil means use indirect buffer to display infile links.
2074 Activating internal links (from one location in a file to another location
2075 in the same file) normally just jumps to the location. When the link is
2076 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2077 is displayed in
2078 another window. When this option is set, the other window actually displays
2079 an indirect buffer clone of the current buffer, to avoid any visibility
2080 changes to the current buffer."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-open-non-existing-files nil
2085 "Non-nil means `org-open-file' will open non-existing files.
2086 When nil, an error will be generated.
2087 This variable applies only to external applications because they
2088 might choke on non-existing files. If the link is to a file that
2089 will be opened in Emacs, the variable is ignored."
2090 :group 'org-link-follow
2091 :type 'boolean)
2093 (defcustom org-open-directory-means-index-dot-org nil
2094 "Non-nil means a link to a directory really means to index.org.
2095 When nil, following a directory link will run dired or open a finder/explorer
2096 window on that directory."
2097 :group 'org-link-follow
2098 :type 'boolean)
2100 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2101 "Non-nil means ask for confirmation before executing shell links.
2102 Shell links can be dangerous: just think about a link
2104 [[shell:rm -rf ~/*][Google Search]]
2106 This link would show up in your Org-mode document as \"Google Search\",
2107 but really it would remove your entire home directory.
2108 Therefore we advise against setting this variable to nil.
2109 Just change it to `y-or-n-p' if you want to confirm with a
2110 single keystroke rather than having to type \"yes\"."
2111 :group 'org-link-follow
2112 :type '(choice
2113 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2114 (const :tag "with y-or-n (faster)" y-or-n-p)
2115 (const :tag "no confirmation (dangerous)" nil)))
2116 (put 'org-confirm-shell-link-function
2117 'safe-local-variable
2118 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2120 (defcustom org-confirm-shell-link-not-regexp ""
2121 "A regexp to skip confirmation for shell links."
2122 :group 'org-link-follow
2123 :version "24.1"
2124 :type 'regexp)
2126 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2127 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2128 Elisp links can be dangerous: just think about a link
2130 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2132 This link would show up in your Org-mode document as \"Google Search\",
2133 but really it would remove your entire home directory.
2134 Therefore we advise against setting this variable to nil.
2135 Just change it to `y-or-n-p' if you want to confirm with a
2136 single keystroke rather than having to type \"yes\"."
2137 :group 'org-link-follow
2138 :type '(choice
2139 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2140 (const :tag "with y-or-n (faster)" y-or-n-p)
2141 (const :tag "no confirmation (dangerous)" nil)))
2142 (put 'org-confirm-shell-link-function
2143 'safe-local-variable
2144 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2146 (defcustom org-confirm-elisp-link-not-regexp ""
2147 "A regexp to skip confirmation for Elisp links."
2148 :group 'org-link-follow
2149 :version "24.1"
2150 :type 'regexp)
2152 (defconst org-file-apps-defaults-gnu
2153 '((remote . emacs)
2154 (system . mailcap)
2155 (t . mailcap))
2156 "Default file applications on a UNIX or GNU/Linux system.
2157 See `org-file-apps'.")
2159 (defconst org-file-apps-defaults-macosx
2160 '((remote . emacs)
2161 (t . "open %s")
2162 (system . "open %s")
2163 ("ps.gz" . "gv %s")
2164 ("eps.gz" . "gv %s")
2165 ("dvi" . "xdvi %s")
2166 ("fig" . "xfig %s"))
2167 "Default file applications on a MacOS X system.
2168 The system \"open\" is known as a default, but we use X11 applications
2169 for some files for which the OS does not have a good default.
2170 See `org-file-apps'.")
2172 (defconst org-file-apps-defaults-windowsnt
2173 (list
2174 '(remote . emacs)
2175 (cons t
2176 (list (if (featurep 'xemacs)
2177 'mswindows-shell-execute
2178 'w32-shell-execute)
2179 "open" 'file))
2180 (cons 'system
2181 (list (if (featurep 'xemacs)
2182 'mswindows-shell-execute
2183 'w32-shell-execute)
2184 "open" 'file)))
2185 "Default file applications on a Windows NT system.
2186 The system \"open\" is used for most files.
2187 See `org-file-apps'.")
2189 (defcustom org-file-apps
2190 '((auto-mode . emacs)
2191 ("\\.mm\\'" . default)
2192 ("\\.x?html?\\'" . default)
2193 ("\\.pdf\\'" . default))
2194 "External applications for opening `file:path' items in a document.
2195 Org-mode uses system defaults for different file types, but
2196 you can use this variable to set the application for a given file
2197 extension. The entries in this list are cons cells where the car identifies
2198 files and the cdr the corresponding command. Possible values for the
2199 file identifier are
2200 \"string\" A string as a file identifier can be interpreted in different
2201 ways, depending on its contents:
2203 - Alphanumeric characters only:
2204 Match links with this file extension.
2205 Example: (\"pdf\" . \"evince %s\")
2206 to open PDFs with evince.
2208 - Regular expression: Match links where the
2209 filename matches the regexp. If you want to
2210 use groups here, use shy groups.
2212 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2213 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2214 to open *.html and *.xhtml with firefox.
2216 - Regular expression which contains (non-shy) groups:
2217 Match links where the whole link, including \"::\", and
2218 anything after that, matches the regexp.
2219 In a custom command string, %1, %2, etc. are replaced with
2220 the parts of the link that were matched by the groups.
2221 For backwards compatibility, if a command string is given
2222 that does not use any of the group matches, this case is
2223 handled identically to the second one (i.e. match against
2224 file name only).
2225 In a custom lisp form, you can access the group matches with
2226 (match-string n link).
2228 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2229 to open [[file:document.pdf::5]] with evince at page 5.
2231 `directory' Matches a directory
2232 `remote' Matches a remote file, accessible through tramp or efs.
2233 Remote files most likely should be visited through Emacs
2234 because external applications cannot handle such paths.
2235 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2236 so all files Emacs knows how to handle. Using this with
2237 command `emacs' will open most files in Emacs. Beware that this
2238 will also open html files inside Emacs, unless you add
2239 (\"html\" . default) to the list as well.
2240 t Default for files not matched by any of the other options.
2241 `system' The system command to open files, like `open' on Windows
2242 and Mac OS X, and mailcap under GNU/Linux. This is the command
2243 that will be selected if you call `C-c C-o' with a double
2244 \\[universal-argument] \\[universal-argument] prefix.
2246 Possible values for the command are:
2247 `emacs' The file will be visited by the current Emacs process.
2248 `default' Use the default application for this file type, which is the
2249 association for t in the list, most likely in the system-specific
2250 part.
2251 This can be used to overrule an unwanted setting in the
2252 system-specific variable.
2253 `system' Use the system command for opening files, like \"open\".
2254 This command is specified by the entry whose car is `system'.
2255 Most likely, the system-specific version of this variable
2256 does define this command, but you can overrule/replace it
2257 here.
2258 string A command to be executed by a shell; %s will be replaced
2259 by the path to the file.
2260 sexp A Lisp form which will be evaluated. The file path will
2261 be available in the Lisp variable `file'.
2262 For more examples, see the system specific constants
2263 `org-file-apps-defaults-macosx'
2264 `org-file-apps-defaults-windowsnt'
2265 `org-file-apps-defaults-gnu'."
2266 :group 'org-link-follow
2267 :type '(repeat
2268 (cons (choice :value ""
2269 (string :tag "Extension")
2270 (const :tag "System command to open files" system)
2271 (const :tag "Default for unrecognized files" t)
2272 (const :tag "Remote file" remote)
2273 (const :tag "Links to a directory" directory)
2274 (const :tag "Any files that have Emacs modes"
2275 auto-mode))
2276 (choice :value ""
2277 (const :tag "Visit with Emacs" emacs)
2278 (const :tag "Use default" default)
2279 (const :tag "Use the system command" system)
2280 (string :tag "Command")
2281 (sexp :tag "Lisp form")))))
2283 (defcustom org-doi-server-url "http://dx.doi.org/"
2284 "The URL of the DOI server."
2285 :type 'string
2286 :version "24.3"
2287 :group 'org-link-follow)
2289 (defgroup org-refile nil
2290 "Options concerning refiling entries in Org-mode."
2291 :tag "Org Refile"
2292 :group 'org)
2294 (defcustom org-directory "~/org"
2295 "Directory with org files.
2296 This is just a default location to look for Org files. There is no need
2297 at all to put your files into this directory. It is only used in the
2298 following situations:
2300 1. When a capture template specifies a target file that is not an
2301 absolute path. The path will then be interpreted relative to
2302 `org-directory'
2303 2. When a capture note is filed away in an interactive way (when exiting the
2304 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2305 with `org-directory' as the default path."
2306 :group 'org-refile
2307 :group 'org-capture
2308 :type 'directory)
2310 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2311 "Default target for storing notes.
2312 Used as a fall back file for org-capture.el, for templates that
2313 do not specify a target file."
2314 :group 'org-refile
2315 :group 'org-capture
2316 :type '(choice
2317 (const :tag "Default from remember-data-file" nil)
2318 file))
2320 (defcustom org-goto-interface 'outline
2321 "The default interface to be used for `org-goto'.
2322 Allowed values are:
2323 outline The interface shows an outline of the relevant file
2324 and the correct heading is found by moving through
2325 the outline or by searching with incremental search.
2326 outline-path-completion Headlines in the current buffer are offered via
2327 completion. This is the interface also used by
2328 the refile command."
2329 :group 'org-refile
2330 :type '(choice
2331 (const :tag "Outline" outline)
2332 (const :tag "Outline-path-completion" outline-path-completion)))
2334 (defcustom org-goto-max-level 5
2335 "Maximum target level when running `org-goto' with refile interface."
2336 :group 'org-refile
2337 :type 'integer)
2339 (defcustom org-reverse-note-order nil
2340 "Non-nil means store new notes at the beginning of a file or entry.
2341 When nil, new notes will be filed to the end of a file or entry.
2342 This can also be a list with cons cells of regular expressions that
2343 are matched against file names, and values."
2344 :group 'org-capture
2345 :group 'org-refile
2346 :type '(choice
2347 (const :tag "Reverse always" t)
2348 (const :tag "Reverse never" nil)
2349 (repeat :tag "By file name regexp"
2350 (cons regexp boolean))))
2352 (defcustom org-log-refile nil
2353 "Information to record when a task is refiled.
2355 Possible values are:
2357 nil Don't add anything
2358 time Add a time stamp to the task
2359 note Prompt for a note and add it with template `org-log-note-headings'
2361 This option can also be set with on a per-file-basis with
2363 #+STARTUP: nologrefile
2364 #+STARTUP: logrefile
2365 #+STARTUP: lognoterefile
2367 You can have local logging settings for a subtree by setting the LOGGING
2368 property to one or more of these keywords.
2370 When bulk-refiling from the agenda, the value `note' is forbidden and
2371 will temporarily be changed to `time'."
2372 :group 'org-refile
2373 :group 'org-progress
2374 :version "24.1"
2375 :type '(choice
2376 (const :tag "No logging" nil)
2377 (const :tag "Record timestamp" time)
2378 (const :tag "Record timestamp with note." note)))
2380 (defcustom org-refile-targets nil
2381 "Targets for refiling entries with \\[org-refile].
2382 This is a list of cons cells. Each cell contains:
2383 - a specification of the files to be considered, either a list of files,
2384 or a symbol whose function or variable value will be used to retrieve
2385 a file name or a list of file names. If you use `org-agenda-files' for
2386 that, all agenda files will be scanned for targets. Nil means consider
2387 headings in the current buffer.
2388 - A specification of how to find candidate refile targets. This may be
2389 any of:
2390 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2391 This tag has to be present in all target headlines, inheritance will
2392 not be considered.
2393 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2394 todo keyword.
2395 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2396 headlines that are refiling targets.
2397 - a cons cell (:level . N). Any headline of level N is considered a target.
2398 Note that, when `org-odd-levels-only' is set, level corresponds to
2399 order in hierarchy, not to the number of stars.
2400 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2401 Note that, when `org-odd-levels-only' is set, level corresponds to
2402 order in hierarchy, not to the number of stars.
2404 Each element of this list generates a set of possible targets.
2405 The union of these sets is presented (with completion) to
2406 the user by `org-refile'.
2408 You can set the variable `org-refile-target-verify-function' to a function
2409 to verify each headline found by the simple criteria above.
2411 When this variable is nil, all top-level headlines in the current buffer
2412 are used, equivalent to the value `((nil . (:level . 1))'."
2413 :group 'org-refile
2414 :type '(repeat
2415 (cons
2416 (choice :value org-agenda-files
2417 (const :tag "All agenda files" org-agenda-files)
2418 (const :tag "Current buffer" nil)
2419 (function) (variable) (file))
2420 (choice :tag "Identify target headline by"
2421 (cons :tag "Specific tag" (const :value :tag) (string))
2422 (cons :tag "TODO keyword" (const :value :todo) (string))
2423 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2424 (cons :tag "Level number" (const :value :level) (integer))
2425 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2427 (defcustom org-refile-target-verify-function nil
2428 "Function to verify if the headline at point should be a refile target.
2429 The function will be called without arguments, with point at the
2430 beginning of the headline. It should return t and leave point
2431 where it is if the headline is a valid target for refiling.
2433 If the target should not be selected, the function must return nil.
2434 In addition to this, it may move point to a place from where the search
2435 should be continued. For example, the function may decide that the entire
2436 subtree of the current entry should be excluded and move point to the end
2437 of the subtree."
2438 :group 'org-refile
2439 :type '(choice
2440 (const nil)
2441 (function)))
2443 (defcustom org-refile-use-cache nil
2444 "Non-nil means cache refile targets to speed up the process.
2445 The cache for a particular file will be updated automatically when
2446 the buffer has been killed, or when any of the marker used for flagging
2447 refile targets no longer points at a live buffer.
2448 If you have added new entries to a buffer that might themselves be targets,
2449 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2450 find that easier, `C-u C-u C-u C-c C-w'."
2451 :group 'org-refile
2452 :version "24.1"
2453 :type 'boolean)
2455 (defcustom org-refile-use-outline-path nil
2456 "Non-nil means provide refile targets as paths.
2457 So a level 3 headline will be available as level1/level2/level3.
2459 When the value is `file', also include the file name (without directory)
2460 into the path. In this case, you can also stop the completion after
2461 the file name, to get entries inserted as top level in the file.
2463 When `full-file-path', include the full file path."
2464 :group 'org-refile
2465 :type '(choice
2466 (const :tag "Not" nil)
2467 (const :tag "Yes" t)
2468 (const :tag "Start with file name" file)
2469 (const :tag "Start with full file path" full-file-path)))
2471 (defcustom org-outline-path-complete-in-steps t
2472 "Non-nil means complete the outline path in hierarchical steps.
2473 When Org-mode uses the refile interface to select an outline path
2474 \(see variable `org-refile-use-outline-path'), the completion of
2475 the path can be done is a single go, or if can be done in steps down
2476 the headline hierarchy. Going in steps is probably the best if you
2477 do not use a special completion package like `ido' or `icicles'.
2478 However, when using these packages, going in one step can be very
2479 fast, while still showing the whole path to the entry."
2480 :group 'org-refile
2481 :type 'boolean)
2483 (defcustom org-refile-allow-creating-parent-nodes nil
2484 "Non-nil means allow to create new nodes as refile targets.
2485 New nodes are then created by adding \"/new node name\" to the completion
2486 of an existing node. When the value of this variable is `confirm',
2487 new node creation must be confirmed by the user (recommended).
2488 When nil, the completion must match an existing entry.
2490 Note that, if the new heading is not seen by the criteria
2491 listed in `org-refile-targets', multiple instances of the same
2492 heading would be created by trying again to file under the new
2493 heading."
2494 :group 'org-refile
2495 :type '(choice
2496 (const :tag "Never" nil)
2497 (const :tag "Always" t)
2498 (const :tag "Prompt for confirmation" confirm)))
2500 (defcustom org-refile-active-region-within-subtree nil
2501 "Non-nil means also refile active region within a subtree.
2503 By default `org-refile' doesn't allow refiling regions if they
2504 don't contain a set of subtrees, but it might be convenient to
2505 do so sometimes: in that case, the first line of the region is
2506 converted to a headline before refiling."
2507 :group 'org-refile
2508 :version "24.1"
2509 :type 'boolean)
2511 (defgroup org-todo nil
2512 "Options concerning TODO items in Org-mode."
2513 :tag "Org TODO"
2514 :group 'org)
2516 (defgroup org-progress nil
2517 "Options concerning Progress logging in Org-mode."
2518 :tag "Org Progress"
2519 :group 'org-time)
2521 (defvar org-todo-interpretation-widgets
2522 '((:tag "Sequence (cycling hits every state)" sequence)
2523 (:tag "Type (cycling directly to DONE)" type))
2524 "The available interpretation symbols for customizing `org-todo-keywords'.
2525 Interested libraries should add to this list.")
2527 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2528 "List of TODO entry keyword sequences and their interpretation.
2529 \\<org-mode-map>This is a list of sequences.
2531 Each sequence starts with a symbol, either `sequence' or `type',
2532 indicating if the keywords should be interpreted as a sequence of
2533 action steps, or as different types of TODO items. The first
2534 keywords are states requiring action - these states will select a headline
2535 for inclusion into the global TODO list Org-mode produces. If one of
2536 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2537 signify that no further action is necessary. If \"|\" is not found,
2538 the last keyword is treated as the only DONE state of the sequence.
2540 The command \\[org-todo] cycles an entry through these states, and one
2541 additional state where no keyword is present. For details about this
2542 cycling, see the manual.
2544 TODO keywords and interpretation can also be set on a per-file basis with
2545 the special #+SEQ_TODO and #+TYP_TODO lines.
2547 Each keyword can optionally specify a character for fast state selection
2548 \(in combination with the variable `org-use-fast-todo-selection')
2549 and specifiers for state change logging, using the same syntax that
2550 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2551 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2552 indicates to record a time stamp each time this state is selected.
2554 Each keyword may also specify if a timestamp or a note should be
2555 recorded when entering or leaving the state, by adding additional
2556 characters in the parenthesis after the keyword. This looks like this:
2557 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2558 record only the time of the state change. With X and Y being either
2559 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2560 Y when leaving the state if and only if the *target* state does not
2561 define X. You may omit any of the fast-selection key or X or /Y,
2562 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2564 For backward compatibility, this variable may also be just a list
2565 of keywords. In this case the interpretation (sequence or type) will be
2566 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2567 :group 'org-todo
2568 :group 'org-keywords
2569 :type '(choice
2570 (repeat :tag "Old syntax, just keywords"
2571 (string :tag "Keyword"))
2572 (repeat :tag "New syntax"
2573 (cons
2574 (choice
2575 :tag "Interpretation"
2576 ;;Quick and dirty way to see
2577 ;;`org-todo-interpretations'. This takes the
2578 ;;place of item arguments
2579 :convert-widget
2580 (lambda (widget)
2581 (widget-put widget
2582 :args (mapcar
2583 (lambda (x)
2584 (widget-convert
2585 (cons 'const x)))
2586 org-todo-interpretation-widgets))
2587 widget))
2588 (repeat
2589 (string :tag "Keyword"))))))
2591 (defvar org-todo-keywords-1 nil
2592 "All TODO and DONE keywords active in a buffer.")
2593 (make-variable-buffer-local 'org-todo-keywords-1)
2594 (defvar org-todo-keywords-for-agenda nil)
2595 (defvar org-done-keywords-for-agenda nil)
2596 (defvar org-todo-keyword-alist-for-agenda nil)
2597 (defvar org-tag-alist-for-agenda nil
2598 "Alist of all tags from all agenda files.")
2599 (defvar org-tag-groups-alist-for-agenda nil
2600 "Alist of all groups tags from all current agenda files.")
2601 (defvar org-tag-groups-alist nil)
2602 (make-variable-buffer-local 'org-tag-groups-alist)
2603 (defvar org-agenda-contributing-files nil)
2604 (defvar org-not-done-keywords nil)
2605 (make-variable-buffer-local 'org-not-done-keywords)
2606 (defvar org-done-keywords nil)
2607 (make-variable-buffer-local 'org-done-keywords)
2608 (defvar org-todo-heads nil)
2609 (make-variable-buffer-local 'org-todo-heads)
2610 (defvar org-todo-sets nil)
2611 (make-variable-buffer-local 'org-todo-sets)
2612 (defvar org-todo-log-states nil)
2613 (make-variable-buffer-local 'org-todo-log-states)
2614 (defvar org-todo-kwd-alist nil)
2615 (make-variable-buffer-local 'org-todo-kwd-alist)
2616 (defvar org-todo-key-alist nil)
2617 (make-variable-buffer-local 'org-todo-key-alist)
2618 (defvar org-todo-key-trigger nil)
2619 (make-variable-buffer-local 'org-todo-key-trigger)
2621 (defcustom org-todo-interpretation 'sequence
2622 "Controls how TODO keywords are interpreted.
2623 This variable is in principle obsolete and is only used for
2624 backward compatibility, if the interpretation of todo keywords is
2625 not given already in `org-todo-keywords'. See that variable for
2626 more information."
2627 :group 'org-todo
2628 :group 'org-keywords
2629 :type '(choice (const sequence)
2630 (const type)))
2632 (defcustom org-use-fast-todo-selection t
2633 "Non-nil means use the fast todo selection scheme with C-c C-t.
2634 This variable describes if and under what circumstances the cycling
2635 mechanism for TODO keywords will be replaced by a single-key, direct
2636 selection scheme.
2638 When nil, fast selection is never used.
2640 When the symbol `prefix', it will be used when `org-todo' is called
2641 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2642 `C-u t' in an agenda buffer.
2644 When t, fast selection is used by default. In this case, the prefix
2645 argument forces cycling instead.
2647 In all cases, the special interface is only used if access keys have
2648 actually been assigned by the user, i.e. if keywords in the configuration
2649 are followed by a letter in parenthesis, like TODO(t)."
2650 :group 'org-todo
2651 :type '(choice
2652 (const :tag "Never" nil)
2653 (const :tag "By default" t)
2654 (const :tag "Only with C-u C-c C-t" prefix)))
2656 (defcustom org-provide-todo-statistics t
2657 "Non-nil means update todo statistics after insert and toggle.
2658 ALL-HEADLINES means update todo statistics by including headlines
2659 with no TODO keyword as well, counting them as not done.
2660 A list of TODO keywords means the same, but skip keywords that are
2661 not in this list.
2662 When set to a list of two lists, the first list contains keywords
2663 to consider as TODO keywords, the second list contains keywords
2664 to consider as DONE keywords.
2666 When this is set, todo statistics is updated in the parent of the
2667 current entry each time a todo state is changed."
2668 :group 'org-todo
2669 :type '(choice
2670 (const :tag "Yes, only for TODO entries" t)
2671 (const :tag "Yes, including all entries" all-headlines)
2672 (repeat :tag "Yes, for TODOs in this list"
2673 (string :tag "TODO keyword"))
2674 (list :tag "Yes, for TODOs and DONEs in these lists"
2675 (repeat (string :tag "TODO keyword"))
2676 (repeat (string :tag "DONE keyword")))
2677 (other :tag "No TODO statistics" nil)))
2679 (defcustom org-hierarchical-todo-statistics t
2680 "Non-nil means TODO statistics covers just direct children.
2681 When nil, all entries in the subtree are considered.
2682 This has only an effect if `org-provide-todo-statistics' is set.
2683 To set this to nil for only a single subtree, use a COOKIE_DATA
2684 property and include the word \"recursive\" into the value."
2685 :group 'org-todo
2686 :type 'boolean)
2688 (defcustom org-after-todo-state-change-hook nil
2689 "Hook which is run after the state of a TODO item was changed.
2690 The new state (a string with a TODO keyword, or nil) is available in the
2691 Lisp variable `org-state'."
2692 :group 'org-todo
2693 :type 'hook)
2695 (defvar org-blocker-hook nil
2696 "Hook for functions that are allowed to block a state change.
2698 Functions in this hook should not modify the buffer.
2699 Each function gets as its single argument a property list,
2700 see `org-trigger-hook' for more information about this list.
2702 If any of the functions in this hook returns nil, the state change
2703 is blocked.")
2705 (defvar org-trigger-hook nil
2706 "Hook for functions that are triggered by a state change.
2708 Each function gets as its single argument a property list with at
2709 least the following elements:
2711 (:type type-of-change :position pos-at-entry-start
2712 :from old-state :to new-state)
2714 Depending on the type, more properties may be present.
2716 This mechanism is currently implemented for:
2718 TODO state changes
2719 ------------------
2720 :type todo-state-change
2721 :from previous state (keyword as a string), or nil, or a symbol
2722 'todo' or 'done', to indicate the general type of state.
2723 :to new state, like in :from")
2725 (defcustom org-enforce-todo-dependencies nil
2726 "Non-nil means undone TODO entries will block switching the parent to DONE.
2727 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2728 be blocked if any prior sibling is not yet done.
2729 Finally, if the parent is blocked because of ordered siblings of its own,
2730 the child will also be blocked."
2731 :set (lambda (var val)
2732 (set var val)
2733 (if val
2734 (add-hook 'org-blocker-hook
2735 'org-block-todo-from-children-or-siblings-or-parent)
2736 (remove-hook 'org-blocker-hook
2737 'org-block-todo-from-children-or-siblings-or-parent)))
2738 :group 'org-todo
2739 :type 'boolean)
2741 (defcustom org-enforce-todo-checkbox-dependencies nil
2742 "Non-nil means unchecked boxes will block switching the parent to DONE.
2743 When this is nil, checkboxes have no influence on switching TODO states.
2744 When non-nil, you first need to check off all check boxes before the TODO
2745 entry can be switched to DONE.
2746 This variable needs to be set before org.el is loaded, and you need to
2747 restart Emacs after a change to make the change effective. The only way
2748 to change is while Emacs is running is through the customize interface."
2749 :set (lambda (var val)
2750 (set var val)
2751 (if val
2752 (add-hook 'org-blocker-hook
2753 'org-block-todo-from-checkboxes)
2754 (remove-hook 'org-blocker-hook
2755 'org-block-todo-from-checkboxes)))
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-treat-insert-todo-heading-as-state-change nil
2760 "Non-nil means inserting a TODO heading is treated as state change.
2761 So when the command \\[org-insert-todo-heading] is used, state change
2762 logging will apply if appropriate. When nil, the new TODO item will
2763 be inserted directly, and no logging will take place."
2764 :group 'org-todo
2765 :type 'boolean)
2767 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2768 "Non-nil means switching TODO states with S-cursor counts as state change.
2769 This is the default behavior. However, setting this to nil allows a
2770 convenient way to select a TODO state and bypass any logging associated
2771 with that."
2772 :group 'org-todo
2773 :type 'boolean)
2775 (defcustom org-todo-state-tags-triggers nil
2776 "Tag changes that should be triggered by TODO state changes.
2777 This is a list. Each entry is
2779 (state-change (tag . flag) .......)
2781 State-change can be a string with a state, and empty string to indicate the
2782 state that has no TODO keyword, or it can be one of the symbols `todo'
2783 or `done', meaning any not-done or done state, respectively."
2784 :group 'org-todo
2785 :group 'org-tags
2786 :type '(repeat
2787 (cons (choice :tag "When changing to"
2788 (const :tag "Not-done state" todo)
2789 (const :tag "Done state" done)
2790 (string :tag "State"))
2791 (repeat
2792 (cons :tag "Tag action"
2793 (string :tag "Tag")
2794 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2796 (defcustom org-log-done nil
2797 "Information to record when a task moves to the DONE state.
2799 Possible values are:
2801 nil Don't add anything, just change the keyword
2802 time Add a time stamp to the task
2803 note Prompt for a note and add it with template `org-log-note-headings'
2805 This option can also be set with on a per-file-basis with
2807 #+STARTUP: nologdone
2808 #+STARTUP: logdone
2809 #+STARTUP: lognotedone
2811 You can have local logging settings for a subtree by setting the LOGGING
2812 property to one or more of these keywords."
2813 :group 'org-todo
2814 :group 'org-progress
2815 :type '(choice
2816 (const :tag "No logging" nil)
2817 (const :tag "Record CLOSED timestamp" time)
2818 (const :tag "Record CLOSED timestamp with note." note)))
2820 ;; Normalize old uses of org-log-done.
2821 (cond
2822 ((eq org-log-done t) (setq org-log-done 'time))
2823 ((and (listp org-log-done) (memq 'done org-log-done))
2824 (setq org-log-done 'note)))
2826 (defcustom org-log-reschedule nil
2827 "Information to record when the scheduling date of a tasks is modified.
2829 Possible values are:
2831 nil Don't add anything, just change the date
2832 time Add a time stamp to the task
2833 note Prompt for a note and add it with template `org-log-note-headings'
2835 This option can also be set with on a per-file-basis with
2837 #+STARTUP: nologreschedule
2838 #+STARTUP: logreschedule
2839 #+STARTUP: lognotereschedule"
2840 :group 'org-todo
2841 :group 'org-progress
2842 :type '(choice
2843 (const :tag "No logging" nil)
2844 (const :tag "Record timestamp" time)
2845 (const :tag "Record timestamp with note." note)))
2847 (defcustom org-log-redeadline nil
2848 "Information to record when the deadline date of a tasks is modified.
2850 Possible values are:
2852 nil Don't add anything, just change the date
2853 time Add a time stamp to the task
2854 note Prompt for a note and add it with template `org-log-note-headings'
2856 This option can also be set with on a per-file-basis with
2858 #+STARTUP: nologredeadline
2859 #+STARTUP: logredeadline
2860 #+STARTUP: lognoteredeadline
2862 You can have local logging settings for a subtree by setting the LOGGING
2863 property to one or more of these keywords."
2864 :group 'org-todo
2865 :group 'org-progress
2866 :type '(choice
2867 (const :tag "No logging" nil)
2868 (const :tag "Record timestamp" time)
2869 (const :tag "Record timestamp with note." note)))
2871 (defcustom org-log-note-clock-out nil
2872 "Non-nil means record a note when clocking out of an item.
2873 This can also be configured on a per-file basis by adding one of
2874 the following lines anywhere in the buffer:
2876 #+STARTUP: lognoteclock-out
2877 #+STARTUP: nolognoteclock-out"
2878 :group 'org-todo
2879 :group 'org-progress
2880 :type 'boolean)
2882 (defcustom org-log-done-with-time t
2883 "Non-nil means the CLOSED time stamp will contain date and time.
2884 When nil, only the date will be recorded."
2885 :group 'org-progress
2886 :type 'boolean)
2888 (defcustom org-log-note-headings
2889 '((done . "CLOSING NOTE %t")
2890 (state . "State %-12s from %-12S %t")
2891 (note . "Note taken on %t")
2892 (reschedule . "Rescheduled from %S on %t")
2893 (delschedule . "Not scheduled, was %S on %t")
2894 (redeadline . "New deadline from %S on %t")
2895 (deldeadline . "Removed deadline, was %S on %t")
2896 (refile . "Refiled on %t")
2897 (clock-out . ""))
2898 "Headings for notes added to entries.
2899 The value is an alist, with the car being a symbol indicating the note
2900 context, and the cdr is the heading to be used. The heading may also be the
2901 empty string.
2902 %t in the heading will be replaced by a time stamp.
2903 %T will be an active time stamp instead the default inactive one
2904 %d will be replaced by a short-format time stamp.
2905 %D will be replaced by an active short-format time stamp.
2906 %s will be replaced by the new TODO state, in double quotes.
2907 %S will be replaced by the old TODO state, in double quotes.
2908 %u will be replaced by the user name.
2909 %U will be replaced by the full user name.
2911 In fact, it is not a good idea to change the `state' entry, because
2912 agenda log mode depends on the format of these entries."
2913 :group 'org-todo
2914 :group 'org-progress
2915 :type '(list :greedy t
2916 (cons (const :tag "Heading when closing an item" done) string)
2917 (cons (const :tag
2918 "Heading when changing todo state (todo sequence only)"
2919 state) string)
2920 (cons (const :tag "Heading when just taking a note" note) string)
2921 (cons (const :tag "Heading when rescheduling" reschedule) string)
2922 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2923 (cons (const :tag "Heading when changing deadline" redeadline) string)
2924 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2925 (cons (const :tag "Heading when refiling" refile) string)
2926 (cons (const :tag "Heading when clocking out" clock-out) string)))
2928 (unless (assq 'note org-log-note-headings)
2929 (push '(note . "%t") org-log-note-headings))
2931 (defcustom org-log-into-drawer nil
2932 "Non-nil means insert state change notes and time stamps into a drawer.
2933 When nil, state changes notes will be inserted after the headline and
2934 any scheduling and clock lines, but not inside a drawer.
2936 The value of this variable should be the name of the drawer to use.
2937 LOGBOOK is proposed as the default drawer for this purpose, you can
2938 also set this to a string to define the drawer of your choice.
2940 A value of t is also allowed, representing \"LOGBOOK\".
2942 A value of t or nil can also be set with on a per-file-basis with
2944 #+STARTUP: logdrawer
2945 #+STARTUP: nologdrawer
2947 If this variable is set, `org-log-state-notes-insert-after-drawers'
2948 will be ignored.
2950 You can set the property LOG_INTO_DRAWER to overrule this setting for
2951 a subtree."
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 "Return the value of `org-log-into-drawer', but let properties overrule.
2963 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2964 used instead of the default value."
2965 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2966 (cond
2967 ((not p) org-log-into-drawer)
2968 ((equal p "nil") nil)
2969 ((equal p "t") "LOGBOOK")
2970 (t p))))
2972 (defcustom org-log-state-notes-insert-after-drawers nil
2973 "Non-nil means insert state change notes after any drawers in entry.
2974 Only the drawers that *immediately* follow the headline and the
2975 deadline/scheduled line are skipped.
2976 When nil, insert notes right after the heading and perhaps the line
2977 with deadline/scheduling if present.
2979 This variable will have no effect if `org-log-into-drawer' is
2980 set."
2981 :group 'org-todo
2982 :group 'org-progress
2983 :type 'boolean)
2985 (defcustom org-log-states-order-reversed t
2986 "Non-nil means the latest state note will be directly after heading.
2987 When nil, the state change notes will be ordered according to time.
2989 This option can also be set with on a per-file-basis with
2991 #+STARTUP: logstatesreversed
2992 #+STARTUP: nologstatesreversed"
2993 :group 'org-todo
2994 :group 'org-progress
2995 :type 'boolean)
2997 (defcustom org-todo-repeat-to-state nil
2998 "The TODO state to which a repeater should return the repeating task.
2999 By default this is the first task in a TODO sequence, or the previous state
3000 in a TODO_TYP set. But you can specify another task here.
3001 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3002 :group 'org-todo
3003 :version "24.1"
3004 :type '(choice (const :tag "Head of sequence" nil)
3005 (string :tag "Specific state")))
3007 (defcustom org-log-repeat 'time
3008 "Non-nil means record moving through the DONE state when triggering repeat.
3009 An auto-repeating task is immediately switched back to TODO when
3010 marked DONE. If you are not logging state changes (by adding \"@\"
3011 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3012 record a closing note, there will be no record of the task moving
3013 through DONE. This variable forces taking a note anyway.
3015 nil Don't force a record
3016 time Record a time stamp
3017 note Prompt for a note and add it with template `org-log-note-headings'
3019 This option can also be set with on a per-file-basis with
3021 #+STARTUP: nologrepeat
3022 #+STARTUP: logrepeat
3023 #+STARTUP: lognoterepeat
3025 You can have local logging settings for a subtree by setting the LOGGING
3026 property to one or more of these keywords."
3027 :group 'org-todo
3028 :group 'org-progress
3029 :type '(choice
3030 (const :tag "Don't force a record" nil)
3031 (const :tag "Force recording the DONE state" time)
3032 (const :tag "Force recording a note with the DONE state" note)))
3035 (defgroup org-priorities nil
3036 "Priorities in Org-mode."
3037 :tag "Org Priorities"
3038 :group 'org-todo)
3040 (defcustom org-enable-priority-commands t
3041 "Non-nil means priority commands are active.
3042 When nil, these commands will be disabled, so that you never accidentally
3043 set a priority."
3044 :group 'org-priorities
3045 :type 'boolean)
3047 (defcustom org-highest-priority ?A
3048 "The highest priority of TODO items. A character like ?A, ?B etc.
3049 Must have a smaller ASCII number than `org-lowest-priority'."
3050 :group 'org-priorities
3051 :type 'character)
3053 (defcustom org-lowest-priority ?C
3054 "The lowest priority of TODO items. A character like ?A, ?B etc.
3055 Must have a larger ASCII number than `org-highest-priority'."
3056 :group 'org-priorities
3057 :type 'character)
3059 (defcustom org-default-priority ?B
3060 "The default priority of TODO items.
3061 This is the priority an item gets if no explicit priority is given.
3062 When starting to cycle on an empty priority the first step in the cycle
3063 depends on `org-priority-start-cycle-with-default'. The resulting first
3064 step priority must not exceed the range from `org-highest-priority' to
3065 `org-lowest-priority' which means that `org-default-priority' has to be
3066 in this range exclusive or inclusive the range boundaries. Else the
3067 first step refuses to set the default and the second will fall back
3068 to (depending on the command used) the highest or lowest priority."
3069 :group 'org-priorities
3070 :type 'character)
3072 (defcustom org-priority-start-cycle-with-default t
3073 "Non-nil means start with default priority when starting to cycle.
3074 When this is nil, the first step in the cycle will be (depending on the
3075 command used) one higher or lower than the default priority.
3076 See also `org-default-priority'."
3077 :group 'org-priorities
3078 :type 'boolean)
3080 (defcustom org-get-priority-function nil
3081 "Function to extract the priority from a string.
3082 The string is normally the headline. If this is nil Org computes the
3083 priority from the priority cookie like [#A] in the headline. It returns
3084 an integer, increasing by 1000 for each priority level.
3085 The user can set a different function here, which should take a string
3086 as an argument and return the numeric priority."
3087 :group 'org-priorities
3088 :version "24.1"
3089 :type '(choice
3090 (const nil)
3091 (function)))
3093 (defgroup org-time nil
3094 "Options concerning time stamps and deadlines in Org-mode."
3095 :tag "Org Time"
3096 :group 'org)
3098 (defcustom org-insert-labeled-timestamps-at-point nil
3099 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3100 When nil, these labeled time stamps are forces into the second line of an
3101 entry, just after the headline. When scheduling from the global TODO list,
3102 the time stamp will always be forced into the second line."
3103 :group 'org-time
3104 :type 'boolean)
3106 (defcustom org-time-stamp-rounding-minutes '(0 5)
3107 "Number of minutes to round time stamps to.
3108 These are two values, the first applies when first creating a time stamp.
3109 The second applies when changing it with the commands `S-up' and `S-down'.
3110 When changing the time stamp, this means that it will change in steps
3111 of N minutes, as given by the second value.
3113 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3114 numbers should be factors of 60, so for example 5, 10, 15.
3116 When this is larger than 1, you can still force an exact time stamp by using
3117 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3118 and by using a prefix arg to `S-up/down' to specify the exact number
3119 of minutes to shift."
3120 :group 'org-time
3121 :get (lambda (var) ; Make sure both elements are there
3122 (if (integerp (default-value var))
3123 (list (default-value var) 5)
3124 (default-value var)))
3125 :type '(list
3126 (integer :tag "when inserting times")
3127 (integer :tag "when modifying times")))
3129 ;; Normalize old customizations of this variable.
3130 (when (integerp org-time-stamp-rounding-minutes)
3131 (setq org-time-stamp-rounding-minutes
3132 (list org-time-stamp-rounding-minutes
3133 org-time-stamp-rounding-minutes)))
3135 (defcustom org-display-custom-times nil
3136 "Non-nil means overlay custom formats over all time stamps.
3137 The formats are defined through the variable `org-time-stamp-custom-formats'.
3138 To turn this on on a per-file basis, insert anywhere in the file:
3139 #+STARTUP: customtime"
3140 :group 'org-time
3141 :set 'set-default
3142 :type 'sexp)
3143 (make-variable-buffer-local 'org-display-custom-times)
3145 (defcustom org-time-stamp-custom-formats
3146 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3147 "Custom formats for time stamps. See `format-time-string' for the syntax.
3148 These are overlaid over the default ISO format if the variable
3149 `org-display-custom-times' is set. Time like %H:%M should be at the
3150 end of the second format. The custom formats are also honored by export
3151 commands, if custom time display is turned on at the time of export."
3152 :group 'org-time
3153 :type 'sexp)
3155 (defun org-time-stamp-format (&optional long inactive)
3156 "Get the right format for a time string."
3157 (let ((f (if long (cdr org-time-stamp-formats)
3158 (car org-time-stamp-formats))))
3159 (if inactive
3160 (concat "[" (substring f 1 -1) "]")
3161 f)))
3163 (defcustom org-time-clocksum-format
3164 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3165 "The format string used when creating CLOCKSUM lines.
3166 This is also used when Org mode generates a time duration.
3168 The value can be a single format string containing two
3169 %-sequences, which will be filled with the number of hours and
3170 minutes in that order.
3172 Alternatively, the value can be a plist associating any of the
3173 keys :years, :months, :weeks, :days, :hours or :minutes with
3174 format strings. The time duration is formatted using only the
3175 time components that are needed and concatenating the results.
3176 If a time unit in absent, it falls back to the next smallest
3177 unit.
3179 The keys :require-years, :require-months, :require-days,
3180 :require-weeks, :require-hours, :require-minutes are also
3181 meaningful. A non-nil value for these keys indicates that the
3182 corresponding time component should always be included, even if
3183 its value is 0.
3186 For example,
3188 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3189 :require-minutes t)
3191 means durations longer than a day will be expressed in days,
3192 hours and minutes, and durations less than a day will always be
3193 expressed in hours and minutes (even for durations less than an
3194 hour).
3196 The value
3198 \(:days \"%dd\" :minutes \"%dm\")
3200 means durations longer than a day will be expressed in days and
3201 minutes, and durations less than a day will be expressed entirely
3202 in minutes (even for durations longer than an hour)."
3203 :group 'org-time
3204 :group 'org-clock
3205 :version "24.4"
3206 :package-version '(Org . "8.0")
3207 :type '(choice (string :tag "Format string")
3208 (set :tag "Plist"
3209 (group :inline t (const :tag "Years" :years)
3210 (string :tag "Format string"))
3211 (group :inline t
3212 (const :tag "Always show years" :require-years)
3213 (const t))
3214 (group :inline t (const :tag "Months" :months)
3215 (string :tag "Format string"))
3216 (group :inline t
3217 (const :tag "Always show months" :require-months)
3218 (const t))
3219 (group :inline t (const :tag "Weeks" :weeks)
3220 (string :tag "Format string"))
3221 (group :inline t
3222 (const :tag "Always show weeks" :require-weeks)
3223 (const t))
3224 (group :inline t (const :tag "Days" :days)
3225 (string :tag "Format string"))
3226 (group :inline t
3227 (const :tag "Always show days" :require-days)
3228 (const t))
3229 (group :inline t (const :tag "Hours" :hours)
3230 (string :tag "Format string"))
3231 (group :inline t
3232 (const :tag "Always show hours" :require-hours)
3233 (const t))
3234 (group :inline t (const :tag "Minutes" :minutes)
3235 (string :tag "Format string"))
3236 (group :inline t
3237 (const :tag "Always show minutes" :require-minutes)
3238 (const t)))))
3240 (defcustom org-time-clocksum-use-fractional nil
3241 "When non-nil, \\[org-clock-display] uses fractional times.
3242 See `org-time-clocksum-format' for more on time clock formats."
3243 :group 'org-time
3244 :group 'org-clock
3245 :version "24.3"
3246 :type 'boolean)
3248 (defcustom org-time-clocksum-use-effort-durations nil
3249 "When non-nil, \\[org-clock-display] uses effort durations.
3250 E.g. by default, one day is considered to be a 8 hours effort,
3251 so a task that has been clocked for 16 hours will be displayed
3252 as during 2 days in the clock display or in the clocktable.
3254 See `org-effort-durations' on how to set effort durations
3255 and `org-time-clocksum-format' for more on time clock formats."
3256 :group 'org-time
3257 :group 'org-clock
3258 :version "24.4"
3259 :package-version '(Org . "8.0")
3260 :type 'boolean)
3262 (defcustom org-time-clocksum-fractional-format "%.2f"
3263 "The format string used when creating CLOCKSUM lines,
3264 or when Org mode generates a time duration, if
3265 `org-time-clocksum-use-fractional' is enabled.
3267 The value can be a single format string containing one
3268 %-sequence, which will be filled with the number of hours as
3269 a float.
3271 Alternatively, the value can be a plist associating any of the
3272 keys :years, :months, :weeks, :days, :hours or :minutes with
3273 a format string. The time duration is formatted using the
3274 largest time unit which gives a non-zero integer part. If all
3275 specified formats have zero integer part, the smallest time unit
3276 is used."
3277 :group 'org-time
3278 :type '(choice (string :tag "Format string")
3279 (set (group :inline t (const :tag "Years" :years)
3280 (string :tag "Format string"))
3281 (group :inline t (const :tag "Months" :months)
3282 (string :tag "Format string"))
3283 (group :inline t (const :tag "Weeks" :weeks)
3284 (string :tag "Format string"))
3285 (group :inline t (const :tag "Days" :days)
3286 (string :tag "Format string"))
3287 (group :inline t (const :tag "Hours" :hours)
3288 (string :tag "Format string"))
3289 (group :inline t (const :tag "Minutes" :minutes)
3290 (string :tag "Format string")))))
3292 (defcustom org-deadline-warning-days 14
3293 "Number of days before expiration during which a deadline becomes active.
3294 This variable governs the display in sparse trees and in the agenda.
3295 When 0 or negative, it means use this number (the absolute value of it)
3296 even if a deadline has a different individual lead time specified.
3298 Custom commands can set this variable in the options section."
3299 :group 'org-time
3300 :group 'org-agenda-daily/weekly
3301 :type 'integer)
3303 (defcustom org-scheduled-delay-days 0
3304 "Number of days before a scheduled item becomes active.
3305 This variable governs the display in sparse trees and in the agenda.
3306 The default value (i.e. 0) means: don't delay scheduled item.
3307 When negative, it means use this number (the absolute value of it)
3308 even if a scheduled item has a different individual delay time
3309 specified.
3311 Custom commands can set this variable in the options section."
3312 :group 'org-time
3313 :group 'org-agenda-daily/weekly
3314 :version "24.4"
3315 :package-version '(Org . "8.0")
3316 :type 'integer)
3318 (defcustom org-read-date-prefer-future t
3319 "Non-nil means assume future for incomplete date input from user.
3320 This affects the following situations:
3321 1. The user gives a month but not a year.
3322 For example, if it is April and you enter \"feb 2\", this will be read
3323 as Feb 2, *next* year. \"May 5\", however, will be this year.
3324 2. The user gives a day, but no month.
3325 For example, if today is the 15th, and you enter \"3\", Org-mode will
3326 read this as the third of *next* month. However, if you enter \"17\",
3327 it will be considered as *this* month.
3329 If you set this variable to the symbol `time', then also the following
3330 will work:
3332 3. If the user gives a time.
3333 If the time is before now, it will be interpreted as tomorrow.
3335 Currently none of this works for ISO week specifications.
3337 When this option is nil, the current day, month and year will always be
3338 used as defaults.
3340 See also `org-agenda-jump-prefer-future'."
3341 :group 'org-time
3342 :type '(choice
3343 (const :tag "Never" nil)
3344 (const :tag "Check month and day" t)
3345 (const :tag "Check month, day, and time" time)))
3347 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3348 "Should the agenda jump command prefer the future for incomplete dates?
3349 The default is to do the same as configured in `org-read-date-prefer-future'.
3350 But you can also set a deviating value here.
3351 This may t or nil, or the symbol `org-read-date-prefer-future'."
3352 :group 'org-agenda
3353 :group 'org-time
3354 :version "24.1"
3355 :type '(choice
3356 (const :tag "Use org-read-date-prefer-future"
3357 org-read-date-prefer-future)
3358 (const :tag "Never" nil)
3359 (const :tag "Always" t)))
3361 (defcustom org-read-date-force-compatible-dates t
3362 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3364 Depending on the system Emacs is running on, certain dates cannot
3365 be represented with the type used internally to represent time.
3366 Dates between 1970-1-1 and 2038-1-1 can always be represented
3367 correctly. Some systems allow for earlier dates, some for later,
3368 some for both. One way to find out it to insert any date into an
3369 Org buffer, putting the cursor on the year and hitting S-up and
3370 S-down to test the range.
3372 When this variable is set to t, the date/time prompt will not let
3373 you specify dates outside the 1970-2037 range, so it is certain that
3374 these dates will work in whatever version of Emacs you are
3375 running, and also that you can move a file from one Emacs implementation
3376 to another. WHenever Org is forcing the year for you, it will display
3377 a message and beep.
3379 When this variable is nil, Org will check if the date is
3380 representable in the specific Emacs implementation you are using.
3381 If not, it will force a year, usually the current year, and beep
3382 to remind you. Currently this setting is not recommended because
3383 the likelihood that you will open your Org files in an Emacs that
3384 has limited date range is not negligible.
3386 A workaround for this problem is to use diary sexp dates for time
3387 stamps outside of this range."
3388 :group 'org-time
3389 :version "24.1"
3390 :type 'boolean)
3392 (defcustom org-read-date-display-live t
3393 "Non-nil means display current interpretation of date prompt live.
3394 This display will be in an overlay, in the minibuffer."
3395 :group 'org-time
3396 :type 'boolean)
3398 (defcustom org-read-date-popup-calendar t
3399 "Non-nil means pop up a calendar when prompting for a date.
3400 In the calendar, the date can be selected with mouse-1. However, the
3401 minibuffer will also be active, and you can simply enter the date as well.
3402 When nil, only the minibuffer will be available."
3403 :group 'org-time
3404 :type 'boolean)
3405 (org-defvaralias 'org-popup-calendar-for-date-prompt
3406 'org-read-date-popup-calendar)
3408 (make-obsolete-variable
3409 'org-read-date-minibuffer-setup-hook
3410 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3411 (defcustom org-read-date-minibuffer-setup-hook nil
3412 "Hook to be used to set up keys for the date/time interface.
3413 Add key definitions to `minibuffer-local-map', which will be a
3414 temporary copy.
3416 WARNING: This option is obsolete, you should use
3417 `org-read-date-minibuffer-local-map' to set up keys."
3418 :group 'org-time
3419 :type 'hook)
3421 (defcustom org-extend-today-until 0
3422 "The hour when your day really ends. Must be an integer.
3423 This has influence for the following applications:
3424 - When switching the agenda to \"today\". It it is still earlier than
3425 the time given here, the day recognized as TODAY is actually yesterday.
3426 - When a date is read from the user and it is still before the time given
3427 here, the current date and time will be assumed to be yesterday, 23:59.
3428 Also, timestamps inserted in capture templates follow this rule.
3430 IMPORTANT: This is a feature whose implementation is and likely will
3431 remain incomplete. Really, it is only here because past midnight seems to
3432 be the favorite working time of John Wiegley :-)"
3433 :group 'org-time
3434 :type 'integer)
3436 (defcustom org-use-effective-time nil
3437 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3438 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3439 \"effective time\" of any timestamps between midnight and 8am will be
3440 23:59 of the previous day."
3441 :group 'org-time
3442 :version "24.1"
3443 :type 'boolean)
3445 (defcustom org-use-last-clock-out-time-as-effective-time nil
3446 "When non-nil, use the last clock out time for `org-todo'.
3447 Note that this option has precedence over the combined use of
3448 `org-use-effective-time' and `org-extend-today-until'."
3449 :group 'org-time
3450 :version "24.4"
3451 :package-version '(Org . "8.0")
3452 :type 'boolean)
3454 (defcustom org-edit-timestamp-down-means-later nil
3455 "Non-nil means S-down will increase the time in a time stamp.
3456 When nil, S-up will increase."
3457 :group 'org-time
3458 :type 'boolean)
3460 (defcustom org-calendar-follow-timestamp-change t
3461 "Non-nil means make the calendar window follow timestamp changes.
3462 When a timestamp is modified and the calendar window is visible, it will be
3463 moved to the new date."
3464 :group 'org-time
3465 :type 'boolean)
3467 (defgroup org-tags nil
3468 "Options concerning tags in Org-mode."
3469 :tag "Org Tags"
3470 :group 'org)
3472 (defcustom org-tag-alist nil
3473 "List of tags allowed in Org-mode files.
3474 When this list is nil, Org-mode will base TAG input on what is already in the
3475 buffer.
3476 The value of this variable is an alist, the car of each entry must be a
3477 keyword as a string, the cdr may be a character that is used to select
3478 that tag through the fast-tag-selection interface.
3479 See the manual for details."
3480 :group 'org-tags
3481 :type '(repeat
3482 (choice
3483 (cons (string :tag "Tag name")
3484 (character :tag "Access char"))
3485 (list :tag "Start radio group"
3486 (const :startgroup)
3487 (option (string :tag "Group description")))
3488 (list :tag "Group tags delimiter"
3489 (const :grouptags))
3490 (list :tag "End radio group"
3491 (const :endgroup)
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 %o: Output MathML file
3978 This command is used by `org-create-math-formula'.
3980 When using MathToWeb as the converter, set this to
3981 \"java -jar %j -unicode -force -df %o %I\"."
3982 :group 'org-latex
3983 :version "24.1"
3984 :type '(choice
3985 (const :tag "None" nil)
3986 (string :tag "\nShell command")))
3988 (defcustom org-latex-create-formula-image-program 'dvipng
3989 "Program to convert LaTeX fragments with.
3991 dvipng Process the LaTeX fragments to dvi file, then convert
3992 dvi files to png files using dvipng.
3993 This will also include processing of non-math environments.
3994 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3995 to convert pdf files to png files"
3996 :group 'org-latex
3997 :version "24.1"
3998 :type '(choice
3999 (const :tag "dvipng" dvipng)
4000 (const :tag "imagemagick" imagemagick)))
4002 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4003 "Path to store latex preview images.
4004 A relative path here creates many directories relative to the
4005 processed org files paths. An absolute path puts all preview
4006 images at the same place."
4007 :group 'org-latex
4008 :version "24.3"
4009 :type 'string)
4011 (defun org-format-latex-mathml-available-p ()
4012 "Return t if `org-latex-to-mathml-convert-command' is usable."
4013 (save-match-data
4014 (when (and (boundp 'org-latex-to-mathml-convert-command)
4015 org-latex-to-mathml-convert-command)
4016 (let ((executable (car (split-string
4017 org-latex-to-mathml-convert-command))))
4018 (when (executable-find executable)
4019 (if (string-match
4020 "%j" org-latex-to-mathml-convert-command)
4021 (file-readable-p org-latex-to-mathml-jar-file)
4022 t))))))
4024 (defcustom org-format-latex-header "\\documentclass{article}
4025 \\usepackage[usenames]{color}
4026 \[PACKAGES]
4027 \[DEFAULT-PACKAGES]
4028 \\pagestyle{empty} % do not remove
4029 % The settings below are copied from fullpage.sty
4030 \\setlength{\\textwidth}{\\paperwidth}
4031 \\addtolength{\\textwidth}{-3cm}
4032 \\setlength{\\oddsidemargin}{1.5cm}
4033 \\addtolength{\\oddsidemargin}{-2.54cm}
4034 \\setlength{\\evensidemargin}{\\oddsidemargin}
4035 \\setlength{\\textheight}{\\paperheight}
4036 \\addtolength{\\textheight}{-\\headheight}
4037 \\addtolength{\\textheight}{-\\headsep}
4038 \\addtolength{\\textheight}{-\\footskip}
4039 \\addtolength{\\textheight}{-3cm}
4040 \\setlength{\\topmargin}{1.5cm}
4041 \\addtolength{\\topmargin}{-2.54cm}"
4042 "The document header used for processing LaTeX fragments.
4043 It is imperative that this header make sure that no page number
4044 appears on the page. The package defined in the variables
4045 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4046 will either replace the placeholder \"[PACKAGES]\" in this
4047 header, or they will be appended."
4048 :group 'org-latex
4049 :type 'string)
4051 (defun org-set-packages-alist (var val)
4052 "Set the packages alist and make sure it has 3 elements per entry."
4053 (set var (mapcar (lambda (x)
4054 (if (and (consp x) (= (length x) 2))
4055 (list (car x) (nth 1 x) t)
4057 val)))
4059 (defun org-get-packages-alist (var)
4060 "Get the packages alist and make sure it has 3 elements per entry."
4061 (mapcar (lambda (x)
4062 (if (and (consp x) (= (length x) 2))
4063 (list (car x) (nth 1 x) t)
4065 (default-value var)))
4067 (defcustom org-latex-default-packages-alist
4068 '(("AUTO" "inputenc" t)
4069 ("T1" "fontenc" t)
4070 ("" "fixltx2e" nil)
4071 ("" "graphicx" t)
4072 ("" "longtable" nil)
4073 ("" "float" nil)
4074 ("" "wrapfig" nil)
4075 ("" "rotating" nil)
4076 ("normalem" "ulem" t)
4077 ("" "amsmath" t)
4078 ("" "textcomp" t)
4079 ("" "marvosym" t)
4080 ("" "wasysym" t)
4081 ("" "amssymb" t)
4082 ("" "capt-of" nil)
4083 ("" "hyperref" nil)
4084 "\\tolerance=1000")
4085 "Alist of default packages to be inserted in the header.
4087 Change this only if one of the packages here causes an
4088 incompatibility with another package you are using.
4090 The packages in this list are needed by one part or another of
4091 Org mode to function properly:
4093 - inputenc, fontenc: for basic font and character selection
4094 - fixltx2e: Important patches of LaTeX itself
4095 - graphicx: for including images
4096 - longtable: For multipage tables
4097 - float, wrapfig: for figure placement
4098 - rotating: for sideways figures and tables
4099 - ulem: for underline and strike-through
4100 - amsmath: for subscript and superscript and math environments
4101 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4102 for interpreting the entities in `org-entities'. You can skip
4103 some of these packages if you don't use any of their symbols.
4104 - capt-of: for captions outside of floats
4105 - hyperref: for cross references
4107 Therefore you should not modify this variable unless you know
4108 what you are doing. The one reason to change it anyway is that
4109 you might be loading some other package that conflicts with one
4110 of the default packages. Each element is either a cell or
4111 a string.
4113 A cell is of the format:
4115 \( \"options\" \"package\" SNIPPET-FLAG).
4117 If SNIPPET-FLAG is non-nil, the package also needs to be included
4118 when compiling LaTeX snippets into images for inclusion into
4119 non-LaTeX output.
4121 A string will be inserted as-is in the header of the document."
4122 :group 'org-latex
4123 :group 'org-export-latex
4124 :set 'org-set-packages-alist
4125 :get 'org-get-packages-alist
4126 :version "24.1"
4127 :type '(repeat
4128 (choice
4129 (list :tag "options/package pair"
4130 (string :tag "options")
4131 (string :tag "package")
4132 (boolean :tag "Snippet"))
4133 (string :tag "A line of LaTeX"))))
4135 (defcustom org-latex-packages-alist nil
4136 "Alist of packages to be inserted in every LaTeX header.
4138 These will be inserted after `org-latex-default-packages-alist'.
4139 Each element is either a cell or a string.
4141 A cell is of the format:
4143 \(\"options\" \"package\" SNIPPET-FLAG)
4145 SNIPPET-FLAG, when non-nil, indicates that this package is also
4146 needed when turning LaTeX snippets into images for inclusion into
4147 non-LaTeX output.
4149 A string will be inserted as-is in the header of the document.
4151 Make sure that you only list packages here which:
4153 - you want in every file;
4154 - do not conflict with the setup in `org-format-latex-header';
4155 - do not conflict with the default packages in
4156 `org-latex-default-packages-alist'."
4157 :group 'org-latex
4158 :group 'org-export-latex
4159 :set 'org-set-packages-alist
4160 :get 'org-get-packages-alist
4161 :type '(repeat
4162 (choice
4163 (list :tag "options/package pair"
4164 (string :tag "options")
4165 (string :tag "package")
4166 (boolean :tag "Snippet"))
4167 (string :tag "A line of LaTeX"))))
4169 (defgroup org-appearance nil
4170 "Settings for Org-mode appearance."
4171 :tag "Org Appearance"
4172 :group 'org)
4174 (defcustom org-level-color-stars-only nil
4175 "Non-nil means fontify only the stars in each headline.
4176 When nil, the entire headline is fontified.
4177 Changing it requires restart of `font-lock-mode' to become effective
4178 also in regions already fontified."
4179 :group 'org-appearance
4180 :type 'boolean)
4182 (defcustom org-hide-leading-stars nil
4183 "Non-nil means hide the first N-1 stars in a headline.
4184 This works by using the face `org-hide' for these stars. This
4185 face is white for a light background, and black for a dark
4186 background. You may have to customize the face `org-hide' to
4187 make this work.
4188 Changing it requires restart of `font-lock-mode' to become effective
4189 also in regions already fontified.
4190 You may also set this on a per-file basis by adding one of the following
4191 lines to the buffer:
4193 #+STARTUP: hidestars
4194 #+STARTUP: showstars"
4195 :group 'org-appearance
4196 :type 'boolean)
4198 (defcustom org-hidden-keywords nil
4199 "List of symbols corresponding to keywords to be hidden the org buffer.
4200 For example, a value '(title) for this list will make the document's title
4201 appear in the buffer without the initial #+TITLE: keyword."
4202 :group 'org-appearance
4203 :version "24.1"
4204 :type '(set (const :tag "#+AUTHOR" author)
4205 (const :tag "#+DATE" date)
4206 (const :tag "#+EMAIL" email)
4207 (const :tag "#+TITLE" title)))
4209 (defcustom org-custom-properties nil
4210 "List of properties (as strings) with a special meaning.
4211 The default use of these custom properties is to let the user
4212 hide them with `org-toggle-custom-properties-visibility'."
4213 :group 'org-properties
4214 :group 'org-appearance
4215 :version "24.3"
4216 :type '(repeat (string :tag "Property Name")))
4218 (defcustom org-fontify-done-headline nil
4219 "Non-nil means change the face of a headline if it is marked DONE.
4220 Normally, only the TODO/DONE keyword indicates the state of a headline.
4221 When this is non-nil, the headline after the keyword is set to the
4222 `org-headline-done' as an additional indication."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-fontify-emphasized-text t
4227 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4228 Changing this variable requires a restart of Emacs to take effect."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-fontify-whole-heading-line nil
4233 "Non-nil means fontify the whole line for headings.
4234 This is useful when setting a background color for the
4235 org-level-* faces."
4236 :group 'org-appearance
4237 :type 'boolean)
4239 (defcustom org-highlight-latex-and-related nil
4240 "Non-nil means highlight LaTeX related syntax in the buffer.
4241 When non nil, the value should be a list containing any of the
4242 following symbols:
4243 `latex' Highlight LaTeX snippets and environments.
4244 `script' Highlight subscript and superscript.
4245 `entities' Highlight entities."
4246 :group 'org-appearance
4247 :version "24.4"
4248 :package-version '(Org . "8.0")
4249 :type '(choice
4250 (const :tag "No highlighting" nil)
4251 (set :greedy t :tag "Highlight"
4252 (const :tag "LaTeX snippets and environments" latex)
4253 (const :tag "Subscript and superscript" script)
4254 (const :tag "Entities" entities))))
4256 (defcustom org-hide-emphasis-markers nil
4257 "Non-nil mean font-lock should hide the emphasis marker characters."
4258 :group 'org-appearance
4259 :type 'boolean)
4261 (defcustom org-hide-macro-markers nil
4262 "Non-nil mean font-lock should hide the brackets marking macro calls."
4263 :group 'org-appearance
4264 :type 'boolean)
4266 (defcustom org-pretty-entities nil
4267 "Non-nil means show entities as UTF8 characters.
4268 When nil, the \\name form remains in the buffer."
4269 :group 'org-appearance
4270 :version "24.1"
4271 :type 'boolean)
4273 (defcustom org-pretty-entities-include-sub-superscripts t
4274 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4275 :group 'org-appearance
4276 :version "24.1"
4277 :type 'boolean)
4279 (defvar org-emph-re nil
4280 "Regular expression for matching emphasis.
4281 After a match, the match groups contain these elements:
4282 0 The match of the full regular expression, including the characters
4283 before and after the proper match
4284 1 The character before the proper match, or empty at beginning of line
4285 2 The proper match, including the leading and trailing markers
4286 3 The leading marker like * or /, indicating the type of highlighting
4287 4 The text between the emphasis markers, not including the markers
4288 5 The character after the match, empty at the end of a line")
4289 (defvar org-verbatim-re nil
4290 "Regular expression for matching verbatim text.")
4291 (defvar org-emphasis-regexp-components) ; defined just below
4292 (defvar org-emphasis-alist) ; defined just below
4293 (defun org-set-emph-re (var val)
4294 "Set variable and compute the emphasis regular expression."
4295 (set var val)
4296 (when (and (boundp 'org-emphasis-alist)
4297 (boundp 'org-emphasis-regexp-components)
4298 org-emphasis-alist org-emphasis-regexp-components)
4299 (let* ((e org-emphasis-regexp-components)
4300 (pre (car e))
4301 (post (nth 1 e))
4302 (border (nth 2 e))
4303 (body (nth 3 e))
4304 (nl (nth 4 e))
4305 (body1 (concat body "*?"))
4306 (markers (mapconcat 'car org-emphasis-alist ""))
4307 (vmarkers (mapconcat
4308 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4309 org-emphasis-alist "")))
4310 ;; make sure special characters appear at the right position in the class
4311 (if (string-match "\\^" markers)
4312 (setq markers (concat (replace-match "" t t markers) "^")))
4313 (if (string-match "-" markers)
4314 (setq markers (concat (replace-match "" t t markers) "-")))
4315 (if (string-match "\\^" vmarkers)
4316 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4317 (if (string-match "-" vmarkers)
4318 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4319 (if (> nl 0)
4320 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4321 (int-to-string nl) "\\}")))
4322 ;; Make the regexp
4323 (setq org-emph-re
4324 (concat "\\([" pre "]\\|^\\)"
4325 "\\("
4326 "\\([" markers "]\\)"
4327 "\\("
4328 "[^" border "]\\|"
4329 "[^" border "]"
4330 body1
4331 "[^" border "]"
4332 "\\)"
4333 "\\3\\)"
4334 "\\([" post "]\\|$\\)"))
4335 (setq org-verbatim-re
4336 (concat "\\([" pre "]\\|^\\)"
4337 "\\("
4338 "\\([" vmarkers "]\\)"
4339 "\\("
4340 "[^" border "]\\|"
4341 "[^" border "]"
4342 body1
4343 "[^" border "]"
4344 "\\)"
4345 "\\3\\)"
4346 "\\([" post "]\\|$\\)")))))
4348 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4349 ;; set this option proved cumbersome. See this message/thread:
4350 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4351 (defvar org-emphasis-regexp-components
4352 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4353 "Components used to build the regular expression for emphasis.
4354 This is a list with five entries. Terminology: In an emphasis string
4355 like \" *strong word* \", we call the initial space PREMATCH, the final
4356 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4357 and \"trong wor\" is the body. The different components in this variable
4358 specify what is allowed/forbidden in each part:
4360 pre Chars allowed as prematch. Beginning of line will be allowed too.
4361 post Chars allowed as postmatch. End of line will be allowed too.
4362 border The chars *forbidden* as border characters.
4363 body-regexp A regexp like \".\" to match a body character. Don't use
4364 non-shy groups here, and don't allow newline here.
4365 newline The maximum number of newlines allowed in an emphasis exp.
4367 You need to reload Org or to restart Emacs after customizing this.")
4369 (defcustom org-emphasis-alist
4370 `(("*" bold)
4371 ("/" italic)
4372 ("_" underline)
4373 ("=" org-verbatim verbatim)
4374 ("~" org-code verbatim)
4375 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4376 "Alist of characters and faces to emphasize text.
4377 Text starting and ending with a special character will be emphasized,
4378 for example *bold*, _underlined_ and /italic/. This variable sets the
4379 marker characters and the face to be used by font-lock for highlighting
4380 in Org-mode Emacs buffers.
4382 You need to reload Org or to restart Emacs after customizing this."
4383 :group 'org-appearance
4384 :set 'org-set-emph-re
4385 :version "24.4"
4386 :package-version '(Org . "8.0")
4387 :type '(repeat
4388 (list
4389 (string :tag "Marker character")
4390 (choice
4391 (face :tag "Font-lock-face")
4392 (plist :tag "Face property list"))
4393 (option (const verbatim)))))
4395 (defvar org-protecting-blocks
4396 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4397 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4398 This is needed for font-lock setup.")
4400 ;;; Miscellaneous options
4402 (defgroup org-completion nil
4403 "Completion in Org-mode."
4404 :tag "Org Completion"
4405 :group 'org)
4407 (defcustom org-completion-use-ido nil
4408 "Non-nil means use ido completion wherever possible.
4409 Note that `ido-mode' must be active for this variable to be relevant.
4410 If you decide to turn this variable on, you might well want to turn off
4411 `org-outline-path-complete-in-steps'.
4412 See also `org-completion-use-iswitchb'."
4413 :group 'org-completion
4414 :type 'boolean)
4416 (defcustom org-completion-use-iswitchb nil
4417 "Non-nil means use iswitchb completion wherever possible.
4418 Note that `iswitchb-mode' must be active for this variable to be relevant.
4419 If you decide to turn this variable on, you might well want to turn off
4420 `org-outline-path-complete-in-steps'.
4421 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4422 :group 'org-completion
4423 :type 'boolean)
4425 (defcustom org-completion-fallback-command 'hippie-expand
4426 "The expansion command called by \\[pcomplete] in normal context.
4427 Normal means, no org-mode-specific context."
4428 :group 'org-completion
4429 :type 'function)
4431 ;;; Functions and variables from their packages
4432 ;; Declared here to avoid compiler warnings
4434 ;; XEmacs only
4435 (defvar outline-mode-menu-heading)
4436 (defvar outline-mode-menu-show)
4437 (defvar outline-mode-menu-hide)
4438 (defvar zmacs-regions) ; XEmacs regions
4440 ;; Emacs only
4441 (defvar mark-active)
4443 ;; Various packages
4444 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4445 (declare-function calendar-forward-day "cal-move" (arg))
4446 (declare-function calendar-goto-date "cal-move" (date))
4447 (declare-function calendar-goto-today "cal-move" ())
4448 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4449 (defvar calc-embedded-close-formula)
4450 (defvar calc-embedded-open-formula)
4451 (declare-function cdlatex-tab "ext:cdlatex" ())
4452 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4453 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4454 (defvar font-lock-unfontify-region-function)
4455 (declare-function iswitchb-read-buffer "iswitchb"
4456 (prompt &optional default require-match start matches-set))
4457 (defvar iswitchb-temp-buflist)
4458 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4459 (defvar org-agenda-tags-todo-honor-ignore-options)
4460 (declare-function org-agenda-skip "org-agenda" ())
4461 (declare-function
4462 org-agenda-format-item "org-agenda"
4463 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4464 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4465 (declare-function org-agenda-change-all-lines "org-agenda"
4466 (newhead hdmarker &optional fixface just-this))
4467 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4468 (declare-function org-agenda-maybe-redo "org-agenda" ())
4469 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4470 (beg end))
4471 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4472 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4473 "org-agenda" (&optional end))
4474 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4475 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4476 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4477 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4478 (declare-function org-indent-mode "org-indent" (&optional arg))
4479 (declare-function parse-time-string "parse-time" (string))
4480 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4481 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4482 (defvar remember-data-file)
4483 (defvar texmathp-why)
4484 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4485 (declare-function table--at-cell-p "table" (position &optional object at-column))
4486 (declare-function calc-eval "calc" (str &optional separator &rest args))
4488 ;;;###autoload
4489 (defun turn-on-orgtbl ()
4490 "Unconditionally turn on `orgtbl-mode'."
4491 (require 'org-table)
4492 (orgtbl-mode 1))
4494 (defun org-at-table-p (&optional table-type)
4495 "Return t if the cursor is inside an org-type table.
4496 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4497 (if org-enable-table-editor
4498 (save-excursion
4499 (beginning-of-line 1)
4500 (looking-at (if table-type org-table-any-line-regexp
4501 org-table-line-regexp)))
4502 nil))
4503 (defsubst org-table-p () (org-at-table-p))
4505 (defun org-at-table.el-p ()
4506 "Return t if and only if we are at a table.el table."
4507 (and (org-at-table-p 'any)
4508 (save-excursion
4509 (goto-char (org-table-begin 'any))
4510 (looking-at org-table1-hline-regexp))))
4512 (defun org-table-recognize-table.el ()
4513 "If there is a table.el table nearby, recognize it and move into it."
4514 (if org-table-tab-recognizes-table.el
4515 (if (org-at-table.el-p)
4516 (progn
4517 (beginning-of-line 1)
4518 (if (looking-at org-table-dataline-regexp)
4520 (if (looking-at org-table1-hline-regexp)
4521 (progn
4522 (beginning-of-line 2)
4523 (if (looking-at org-table-any-border-regexp)
4524 (beginning-of-line -1)))))
4525 (if (re-search-forward "|" (org-table-end t) t)
4526 (progn
4527 (require 'table)
4528 (if (table--at-cell-p (point))
4530 (message "recognizing table.el table...")
4531 (table-recognize-table)
4532 (message "recognizing table.el table...done")))
4533 (error "This should not happen"))
4535 nil)
4536 nil))
4538 (defun org-at-table-hline-p ()
4539 "Return t if the cursor is inside a hline in a table."
4540 (if org-enable-table-editor
4541 (save-excursion
4542 (beginning-of-line 1)
4543 (looking-at org-table-hline-regexp))
4544 nil))
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 "Return t when point (or POS) is in #+TBLFM line."
4572 (save-excursion
4573 (let ((pos pos)))
4574 (goto-char (or pos (point)))
4575 (beginning-of-line 1)
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 'scheduled-or-deadline
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" scheduled-or-deadline)
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 "24.3"
4726 :group 'org-sparse-trees)
4728 (defun org-cycle-hide-archived-subtrees (state)
4729 "Re-hide all archived subtrees after a visibility state change."
4730 (when (and (not org-cycle-open-archived-trees)
4731 (not (memq state '(overview folded))))
4732 (save-excursion
4733 (let* ((globalp (memq state '(contents all)))
4734 (beg (if globalp (point-min) (point)))
4735 (end (if globalp (point-max) (org-end-of-subtree t))))
4736 (org-hide-archived-subtrees beg end)
4737 (goto-char beg)
4738 (if (looking-at (concat ".*:" org-archive-tag ":"))
4739 (message "%s" (substitute-command-keys
4740 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4742 (defun org-force-cycle-archived ()
4743 "Cycle subtree even if it is archived."
4744 (interactive)
4745 (setq this-command 'org-cycle)
4746 (let ((org-cycle-open-archived-trees t))
4747 (call-interactively 'org-cycle)))
4749 (defun org-hide-archived-subtrees (beg end)
4750 "Re-hide all archived subtrees after a visibility state change."
4751 (save-excursion
4752 (let* ((re (concat ":" org-archive-tag ":")))
4753 (goto-char beg)
4754 (while (re-search-forward re end t)
4755 (when (org-at-heading-p)
4756 (org-flag-subtree t)
4757 (org-end-of-subtree t))))))
4759 (declare-function outline-end-of-heading "outline" ())
4760 (declare-function outline-flag-region "outline" (from to flag))
4761 (defun org-flag-subtree (flag)
4762 (save-excursion
4763 (org-back-to-heading t)
4764 (outline-end-of-heading)
4765 (outline-flag-region (point)
4766 (progn (org-end-of-subtree t) (point))
4767 flag)))
4769 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4771 ;; Declare Column View Code
4773 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4774 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4775 (declare-function org-columns-compute "org-colview" (property))
4777 ;; Declare ID code
4779 (declare-function org-id-store-link "org-id")
4780 (declare-function org-id-locations-load "org-id")
4781 (declare-function org-id-locations-save "org-id")
4782 (defvar org-id-track-globally)
4784 ;;; Variables for pre-computed regular expressions, all buffer local
4786 (defvar org-todo-regexp nil
4787 "Matches any of the TODO state keywords.")
4788 (make-variable-buffer-local 'org-todo-regexp)
4789 (defvar org-not-done-regexp nil
4790 "Matches any of the TODO state keywords except the last one.")
4791 (make-variable-buffer-local 'org-not-done-regexp)
4792 (defvar org-not-done-heading-regexp nil
4793 "Matches a TODO headline that is not done.")
4794 (make-variable-buffer-local 'org-not-done-regexp)
4795 (defvar org-todo-line-regexp nil
4796 "Matches a headline and puts TODO state into group 2 if present.")
4797 (make-variable-buffer-local 'org-todo-line-regexp)
4798 (defvar org-complex-heading-regexp nil
4799 "Matches a headline and puts everything into groups:
4800 group 1: the stars
4801 group 2: The todo keyword, maybe
4802 group 3: Priority cookie
4803 group 4: True headline
4804 group 5: Tags")
4805 (make-variable-buffer-local 'org-complex-heading-regexp)
4806 (defvar org-complex-heading-regexp-format nil
4807 "Printf format to make regexp to match an exact headline.
4808 This regexp will match the headline of any node which has the
4809 exact headline text that is put into the format, but may have any
4810 TODO state, priority and tags.")
4811 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4812 (defvar org-todo-line-tags-regexp nil
4813 "Matches a headline and puts TODO state into group 2 if present.
4814 Also put tags into group 4 if tags are present.")
4815 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4817 (defconst org-plain-time-of-day-regexp
4818 (concat
4819 "\\(\\<[012]?[0-9]"
4820 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4821 "\\(--?"
4822 "\\(\\<[012]?[0-9]"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4824 "\\)?")
4825 "Regular expression to match a plain time or time range.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4828 0 the full match
4829 1 the first time, range or not
4830 8 the second time, if it is a range.")
4832 (defconst org-plain-time-extension-regexp
4833 (concat
4834 "\\(\\<[012]?[0-9]"
4835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4836 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4837 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4838 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4839 groups carry important information:
4840 0 the full match
4841 7 hours of duration
4842 9 minutes of duration")
4844 (defconst org-stamp-time-of-day-regexp
4845 (concat
4846 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4847 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4848 "\\(--?"
4849 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4850 "Regular expression to match a timestamp time or time range.
4851 After a match, the following groups carry important information:
4852 0 the full match
4853 1 date plus weekday, for back referencing to make sure both times are on the same day
4854 2 the first time, range or not
4855 4 the second time, if it is a range.")
4857 (defconst org-startup-options
4858 '(("fold" org-startup-folded t)
4859 ("overview" org-startup-folded t)
4860 ("nofold" org-startup-folded nil)
4861 ("showall" org-startup-folded nil)
4862 ("showeverything" org-startup-folded showeverything)
4863 ("content" org-startup-folded content)
4864 ("indent" org-startup-indented t)
4865 ("noindent" org-startup-indented nil)
4866 ("hidestars" org-hide-leading-stars t)
4867 ("showstars" org-hide-leading-stars nil)
4868 ("odd" org-odd-levels-only t)
4869 ("oddeven" org-odd-levels-only nil)
4870 ("align" org-startup-align-all-tables t)
4871 ("noalign" org-startup-align-all-tables nil)
4872 ("inlineimages" org-startup-with-inline-images t)
4873 ("noinlineimages" org-startup-with-inline-images nil)
4874 ("latexpreview" org-startup-with-latex-preview t)
4875 ("nolatexpreview" org-startup-with-latex-preview nil)
4876 ("customtime" org-display-custom-times t)
4877 ("logdone" org-log-done time)
4878 ("lognotedone" org-log-done note)
4879 ("nologdone" org-log-done nil)
4880 ("lognoteclock-out" org-log-note-clock-out t)
4881 ("nolognoteclock-out" org-log-note-clock-out nil)
4882 ("logrepeat" org-log-repeat state)
4883 ("lognoterepeat" org-log-repeat note)
4884 ("logdrawer" org-log-into-drawer t)
4885 ("nologdrawer" org-log-into-drawer nil)
4886 ("logstatesreversed" org-log-states-order-reversed t)
4887 ("nologstatesreversed" org-log-states-order-reversed nil)
4888 ("nologrepeat" org-log-repeat nil)
4889 ("logreschedule" org-log-reschedule time)
4890 ("lognotereschedule" org-log-reschedule note)
4891 ("nologreschedule" org-log-reschedule nil)
4892 ("logredeadline" org-log-redeadline time)
4893 ("lognoteredeadline" org-log-redeadline note)
4894 ("nologredeadline" org-log-redeadline nil)
4895 ("logrefile" org-log-refile time)
4896 ("lognoterefile" org-log-refile note)
4897 ("nologrefile" org-log-refile nil)
4898 ("fninline" org-footnote-define-inline t)
4899 ("nofninline" org-footnote-define-inline nil)
4900 ("fnlocal" org-footnote-section nil)
4901 ("fnauto" org-footnote-auto-label t)
4902 ("fnprompt" org-footnote-auto-label nil)
4903 ("fnconfirm" org-footnote-auto-label confirm)
4904 ("fnplain" org-footnote-auto-label plain)
4905 ("fnadjust" org-footnote-auto-adjust t)
4906 ("nofnadjust" org-footnote-auto-adjust nil)
4907 ("constcgs" constants-unit-system cgs)
4908 ("constSI" constants-unit-system SI)
4909 ("noptag" org-tag-persistent-alist nil)
4910 ("hideblocks" org-hide-block-startup t)
4911 ("nohideblocks" org-hide-block-startup nil)
4912 ("beamer" org-startup-with-beamer-mode t)
4913 ("entitiespretty" org-pretty-entities t)
4914 ("entitiesplain" org-pretty-entities nil))
4915 "Variable associated with STARTUP options for org-mode.
4916 Each element is a list of three items: the startup options (as written
4917 in the #+STARTUP line), the corresponding variable, and the value to set
4918 this variable to if the option is found. An optional forth element PUSH
4919 means to push this value onto the list in the variable.")
4921 (defcustom org-group-tags t
4922 "When non-nil (the default), use group tags.
4923 This can be turned on/off through `org-toggle-tags-groups'."
4924 :group 'org-tags
4925 :group 'org-startup
4926 :type 'boolean)
4928 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4930 (defun org-toggle-tags-groups ()
4931 "Toggle support for group tags.
4932 Support for group tags is controlled by the option
4933 `org-group-tags', which is non-nil by default."
4934 (interactive)
4935 (setq org-group-tags (not org-group-tags))
4936 (cond ((and (derived-mode-p 'org-agenda-mode)
4937 org-group-tags)
4938 (org-agenda-redo))
4939 ((derived-mode-p 'org-mode)
4940 (let ((org-inhibit-startup t)) (org-mode))))
4941 (message "Groups tags support has been turned %s"
4942 (if org-group-tags "on" "off")))
4944 (defun org-set-regexps-and-options-for-tags ()
4945 "Precompute variables used for tags."
4946 (when (derived-mode-p 'org-mode)
4947 (org-set-local 'org-file-tags nil)
4948 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4949 (splitre "[ \t]+")
4950 (start 0)
4951 tags ftags key value)
4952 (save-excursion
4953 (save-restriction
4954 (widen)
4955 (goto-char (point-min))
4956 (while (re-search-forward re nil t)
4957 (setq key (upcase (org-match-string-no-properties 1))
4958 value (org-match-string-no-properties 2))
4959 (if (stringp value) (setq value (org-trim value)))
4960 (cond
4961 ((equal key "TAGS")
4962 (setq tags (append tags (if tags '("\\n") nil)
4963 (org-split-string value splitre))))
4964 ((equal key "FILETAGS")
4965 (when (string-match "\\S-" value)
4966 (setq ftags
4967 (append
4968 ftags
4969 (apply 'append
4970 (mapcar (lambda (x) (org-split-string x ":"))
4971 (org-split-string value)))))))))))
4972 ;; Process the file tags.
4973 (and ftags (org-set-local 'org-file-tags
4974 (mapcar 'org-add-prop-inherited ftags)))
4975 (org-set-local 'org-tag-groups-alist nil)
4976 ;; Process the tags.
4977 (when (and (not tags) org-tag-alist)
4978 (setq tags
4979 (mapcar
4980 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4981 ((eq (car tg) :endgroup) "}")
4982 ((eq (car tg) :grouptags) ":")
4983 ((eq (car tg) :newline) "\n")
4984 (t (concat (car tg)
4985 (if (characterp (cdr tg))
4986 (format "(%s)" (char-to-string (cdr tg))) "")))))
4987 org-tag-alist)))
4988 (let (e tgs g)
4989 (while (setq e (pop tags))
4990 (cond
4991 ((equal e "{")
4992 (progn (push '(:startgroup) tgs)
4993 (when (equal (nth 1 tags) ":")
4994 (push (list (replace-regexp-in-string
4995 "(.+)$" "" (nth 0 tags)))
4996 org-tag-groups-alist)
4997 (setq g 0))))
4998 ((equal e ":") (push '(:grouptags) tgs))
4999 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
5000 ((equal e "\\n") (push '(:newline) tgs))
5001 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
5002 (push (cons (match-string 1 e)
5003 (string-to-char (match-string 2 e))) tgs)
5004 (if (and g (> g 0))
5005 (setcar org-tag-groups-alist
5006 (append (car org-tag-groups-alist)
5007 (list (match-string 1 e)))))
5008 (if g (setq g (1+ g))))
5009 (t (push (list e) tgs)
5010 (if (and g (> g 0))
5011 (setcar org-tag-groups-alist
5012 (append (car org-tag-groups-alist) (list e))))
5013 (if g (setq g (1+ g))))))
5014 (org-set-local 'org-tag-alist nil)
5015 (while (setq e (pop tgs))
5016 (or (and (stringp (car e))
5017 (assoc (car e) org-tag-alist))
5018 (push e org-tag-alist)))
5019 ;; Return a list with tag variables
5020 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
5022 (defvar org-ota nil)
5023 (defun org-set-regexps-and-options ()
5024 "Precompute regular expressions used in the current buffer."
5025 (when (derived-mode-p 'org-mode)
5026 (org-set-local 'org-todo-kwd-alist nil)
5027 (org-set-local 'org-todo-key-alist nil)
5028 (org-set-local 'org-todo-key-trigger nil)
5029 (org-set-local 'org-todo-keywords-1 nil)
5030 (org-set-local 'org-done-keywords nil)
5031 (org-set-local 'org-todo-heads nil)
5032 (org-set-local 'org-todo-sets nil)
5033 (org-set-local 'org-todo-log-states nil)
5034 (org-set-local 'org-file-properties nil)
5035 (let ((re (org-make-options-regexp
5036 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5037 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5038 "SETUPFILE" "OPTIONS")
5039 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5040 (splitre "[ \t]+")
5041 (scripts org-use-sub-superscripts)
5042 kwds kws0 kwsa key log value cat arch const links hw dws
5043 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5044 (start 0))
5045 (save-excursion
5046 (save-restriction
5047 (widen)
5048 (goto-char (point-min))
5049 (while
5050 (or (and
5051 ext-setup-or-nil
5052 (not org-ota)
5053 (let (ret)
5054 (with-temp-buffer
5055 (insert ext-setup-or-nil)
5056 (let ((major-mode 'org-mode) org-ota)
5057 (setq ret (save-match-data
5058 (org-set-regexps-and-options-for-tags)))))
5059 ;; Append setupfile tags to existing tags
5060 (setq org-ota t)
5061 (setq org-file-tags
5062 (delq nil (append org-file-tags (nth 0 ret)))
5063 org-tag-alist
5064 (delq nil (append org-tag-alist (nth 1 ret)))
5065 org-tag-groups-alist
5066 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5067 (and ext-setup-or-nil
5068 (string-match re ext-setup-or-nil start)
5069 (setq start (match-end 0)))
5070 (and (setq ext-setup-or-nil nil start 0)
5071 (re-search-forward re nil t)))
5072 (setq key (upcase (match-string 1 ext-setup-or-nil))
5073 value (org-match-string-no-properties 2 ext-setup-or-nil))
5074 (if (stringp value) (setq value (org-trim value)))
5075 (cond
5076 ((equal key "CATEGORY")
5077 (setq cat value))
5078 ((member key '("SEQ_TODO" "TODO"))
5079 (push (cons 'sequence (org-split-string value splitre)) kwds))
5080 ((equal key "TYP_TODO")
5081 (push (cons 'type (org-split-string value splitre)) kwds))
5082 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5083 ;; general TODO-like setup
5084 (push (cons (intern (downcase (match-string 1 key)))
5085 (org-split-string value splitre)) kwds))
5086 ((equal key "COLUMNS")
5087 (org-set-local 'org-columns-default-format value))
5088 ((equal key "LINK")
5089 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5090 (push (cons (match-string 1 value)
5091 (org-trim (match-string 2 value)))
5092 links)))
5093 ((equal key "PRIORITIES")
5094 (setq prio (org-split-string value " +")))
5095 ((equal key "PROPERTY")
5096 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5097 (setq props (org--update-property-plist (match-string 1 value)
5098 (match-string 2 value)
5099 props))))
5100 ((equal key "CONSTANTS")
5101 (org-table-set-constants))
5102 ((equal key "STARTUP")
5103 (let ((opts (org-split-string value splitre))
5104 l var val)
5105 (while (setq l (pop opts))
5106 (when (setq l (assoc l org-startup-options))
5107 (setq var (nth 1 l) val (nth 2 l))
5108 (if (not (nth 3 l))
5109 (set (make-local-variable var) val)
5110 (if (not (listp (symbol-value var)))
5111 (set (make-local-variable var) nil))
5112 (set (make-local-variable var) (symbol-value var))
5113 (add-to-list var val))))))
5114 ((equal key "ARCHIVE")
5115 (setq arch value)
5116 (remove-text-properties 0 (length arch)
5117 '(face t fontified t) arch))
5118 ((equal key "OPTIONS")
5119 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5120 (setq scripts (read (match-string 2 value)))))
5121 ((and (equal key "SETUPFILE")
5122 ;; Prevent checking in Gnus messages
5123 (not buffer-read-only))
5124 (setq setup-contents (org-file-contents
5125 (expand-file-name
5126 (org-remove-double-quotes value))
5127 'noerror))
5128 (if (not ext-setup-or-nil)
5129 (setq ext-setup-or-nil setup-contents start 0)
5130 (setq ext-setup-or-nil
5131 (concat (substring ext-setup-or-nil 0 start)
5132 "\n" setup-contents "\n"
5133 (substring ext-setup-or-nil start)))))))))
5134 (org-set-local 'org-use-sub-superscripts scripts)
5135 (when cat
5136 (org-set-local 'org-category (intern cat))
5137 (push (cons "CATEGORY" cat) props))
5138 (when prio
5139 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5140 (setq prio (mapcar 'string-to-char prio))
5141 (org-set-local 'org-highest-priority (nth 0 prio))
5142 (org-set-local 'org-lowest-priority (nth 1 prio))
5143 (org-set-local 'org-default-priority (nth 2 prio)))
5144 (and props (org-set-local 'org-file-properties props))
5145 (and arch (org-set-local 'org-archive-location arch))
5146 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5147 ;; Process the TODO keywords
5148 (unless kwds
5149 ;; Use the global values as if they had been given locally.
5150 (setq kwds (default-value 'org-todo-keywords))
5151 (if (stringp (car kwds))
5152 (setq kwds (list (cons org-todo-interpretation
5153 (default-value 'org-todo-keywords)))))
5154 (setq kwds (reverse kwds)))
5155 (setq kwds (nreverse kwds))
5156 (let (inter kws kw)
5157 (while (setq kws (pop kwds))
5158 (let ((kws (or
5159 (run-hook-with-args-until-success
5160 'org-todo-setup-filter-hook kws)
5161 kws)))
5162 (setq inter (pop kws) sep (member "|" kws)
5163 kws0 (delete "|" (copy-sequence kws))
5164 kwsa nil
5165 kws1 (mapcar
5166 (lambda (x)
5167 ;; 1 2
5168 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5169 (progn
5170 (setq kw (match-string 1 x)
5171 key (and (match-end 2) (match-string 2 x))
5172 log (org-extract-log-state-settings x))
5173 (push (cons kw (and key (string-to-char key))) kwsa)
5174 (and log (push log org-todo-log-states))
5176 (error "Invalid TODO keyword %s" x)))
5177 kws0)
5178 kwsa (if kwsa (append '((:startgroup))
5179 (nreverse kwsa)
5180 '((:endgroup))))
5181 hw (car kws1)
5182 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5183 tail (list inter hw (car dws) (org-last dws))))
5184 (add-to-list 'org-todo-heads hw 'append)
5185 (push kws1 org-todo-sets)
5186 (setq org-done-keywords (append org-done-keywords dws nil))
5187 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5188 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5189 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5190 (setq org-todo-sets (nreverse org-todo-sets)
5191 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5192 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5193 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5194 ;; Compute the regular expressions and other local variables.
5195 ;; Using `org-outline-regexp-bol' would complicate them much,
5196 ;; because of the fixed white space at the end of that string.
5197 (if (not org-done-keywords)
5198 (setq org-done-keywords (and org-todo-keywords-1
5199 (list (org-last org-todo-keywords-1)))))
5200 (setq org-not-done-keywords
5201 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5202 org-todo-regexp
5203 (concat "\\("
5204 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5205 "\\)")
5206 org-not-done-regexp
5207 (concat "\\("
5208 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5209 "\\)")
5210 org-not-done-heading-regexp
5211 (format org-heading-keyword-regexp-format org-not-done-regexp)
5212 org-todo-line-regexp
5213 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5214 org-complex-heading-regexp
5215 (concat "^\\(\\*+\\)"
5216 "\\(?: +" org-todo-regexp "\\)?"
5217 "\\(?: +\\(\\[#.\\]\\)\\)?"
5218 "\\(?: +\\(.*?\\)\\)??"
5219 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5220 "[ \t]*$")
5221 org-complex-heading-regexp-format
5222 (concat "^\\(\\*+\\)"
5223 "\\(?: +" org-todo-regexp "\\)?"
5224 "\\(?: +\\(\\[#.\\]\\)\\)?"
5225 "\\(?: +"
5226 ;; Stats cookies can be stuck to body.
5227 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5228 "\\(%s\\)"
5229 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5230 "\\)"
5231 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5232 "[ \t]*$")
5233 org-todo-line-tags-regexp
5234 (concat "^\\(\\*+\\)"
5235 "\\(?: +" org-todo-regexp "\\)?"
5236 "\\(?: +\\(.*?\\)\\)??"
5237 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5238 "[ \t]*$"))
5239 (setq org-ota nil)
5240 (org-compute-latex-and-related-regexp))))
5242 (defun org-file-contents (file &optional noerror)
5243 "Return the contents of FILE, as a string."
5244 (if (and file (file-readable-p file))
5245 (with-temp-buffer
5246 (insert-file-contents file)
5247 (buffer-string))
5248 (funcall (if noerror 'message 'error)
5249 "Cannot read file \"%s\"%s"
5250 file
5251 (let ((from (buffer-file-name (buffer-base-buffer))))
5252 (if from (concat " (referenced in file \"" from "\")") "")))))
5254 (defun org-extract-log-state-settings (x)
5255 "Extract the log state setting from a TODO keyword string.
5256 This will extract info from a string like \"WAIT(w@/!)\"."
5257 (let (kw key log1 log2)
5258 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5259 (setq kw (match-string 1 x)
5260 key (and (match-end 2) (match-string 2 x))
5261 log1 (and (match-end 3) (match-string 3 x))
5262 log2 (and (match-end 4) (match-string 4 x)))
5263 (and (or log1 log2)
5264 (list kw
5265 (and log1 (if (equal log1 "!") 'time 'note))
5266 (and log2 (if (equal log2 "!") 'time 'note)))))))
5268 (defun org-remove-keyword-keys (list)
5269 "Remove a pair of parenthesis at the end of each string in LIST."
5270 (mapcar (lambda (x)
5271 (if (string-match "(.*)$" x)
5272 (substring x 0 (match-beginning 0))
5274 list))
5276 (defun org-assign-fast-keys (alist)
5277 "Assign fast keys to a keyword-key alist.
5278 Respect keys that are already there."
5279 (let (new e (alt ?0))
5280 (while (setq e (pop alist))
5281 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5282 (cdr e)) ;; Key already assigned.
5283 (push e new)
5284 (let ((clist (string-to-list (downcase (car e))))
5285 (used (append new alist)))
5286 (when (= (car clist) ?@)
5287 (pop clist))
5288 (while (and clist (rassoc (car clist) used))
5289 (pop clist))
5290 (unless clist
5291 (while (rassoc alt used)
5292 (incf alt)))
5293 (push (cons (car e) (or (car clist) alt)) new))))
5294 (nreverse new)))
5296 ;;; Some variables used in various places
5298 (defvar org-window-configuration nil
5299 "Used in various places to store a window configuration.")
5300 (defvar org-selected-window nil
5301 "Used in various places to store a window configuration.")
5302 (defvar org-finish-function nil
5303 "Function to be called when `C-c C-c' is used.
5304 This is for getting out of special buffers like capture.")
5307 ;; FIXME: Occasionally check by commenting these, to make sure
5308 ;; no other functions uses these, forgetting to let-bind them.
5309 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5310 (defvar org-last-state)
5311 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5313 ;; Defined somewhere in this file, but used before definition.
5314 (defvar org-entities) ;; defined in org-entities.el
5315 (defvar org-struct-menu)
5316 (defvar org-org-menu)
5317 (defvar org-tbl-menu)
5319 ;;;; Define the Org-mode
5321 ;; We use a before-change function to check if a table might need
5322 ;; an update.
5323 (defvar org-table-may-need-update t
5324 "Indicates that a table might need an update.
5325 This variable is set by `org-before-change-function'.
5326 `org-table-align' sets it back to nil.")
5327 (defun org-before-change-function (beg end)
5328 "Every change indicates that a table might need an update."
5329 (setq org-table-may-need-update t))
5330 (defvar org-mode-map)
5331 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5332 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5333 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5334 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5335 (defvar org-table-buffer-is-an nil)
5337 (defvar bidi-paragraph-direction)
5338 (defvar buffer-face-mode-face)
5340 (require 'outline)
5341 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5342 (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"))
5343 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5345 ;; Other stuff we need.
5346 (require 'time-date)
5347 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5348 (require 'easymenu)
5349 (require 'overlay)
5351 ;; (require 'org-macs) moved higher up in the file before it is first used
5352 (require 'org-entities)
5353 ;; (require 'org-compat) moved higher up in the file before it is first used
5354 (require 'org-faces)
5355 (require 'org-list)
5356 (require 'org-pcomplete)
5357 (require 'org-src)
5358 (require 'org-footnote)
5359 (require 'org-macro)
5361 ;; babel
5362 (require 'ob)
5364 ;;;###autoload
5365 (define-derived-mode org-mode outline-mode "Org"
5366 "Outline-based notes management and organizer, alias
5367 \"Carsten's outline-mode for keeping track of everything.\"
5369 Org-mode develops organizational tasks around a NOTES file which
5370 contains information about projects as plain text. Org-mode is
5371 implemented on top of outline-mode, which is ideal to keep the content
5372 of large files well structured. It supports ToDo items, deadlines and
5373 time stamps, which magically appear in the diary listing of the Emacs
5374 calendar. Tables are easily created with a built-in table editor.
5375 Plain text URL-like links connect to websites, emails (VM), Usenet
5376 messages (Gnus), BBDB entries, and any files related to the project.
5377 For printing and sharing of notes, an Org-mode file (or a part of it)
5378 can be exported as a structured ASCII or HTML file.
5380 The following commands are available:
5382 \\{org-mode-map}"
5384 ;; Get rid of Outline menus, they are not needed
5385 ;; Need to do this here because define-derived-mode sets up
5386 ;; the keymap so late. Still, it is a waste to call this each time
5387 ;; we switch another buffer into org-mode.
5388 (if (featurep 'xemacs)
5389 (when (boundp 'outline-mode-menu-heading)
5390 ;; Assume this is Greg's port, it uses easymenu
5391 (easy-menu-remove outline-mode-menu-heading)
5392 (easy-menu-remove outline-mode-menu-show)
5393 (easy-menu-remove outline-mode-menu-hide))
5394 (define-key org-mode-map [menu-bar headings] 'undefined)
5395 (define-key org-mode-map [menu-bar hide] 'undefined)
5396 (define-key org-mode-map [menu-bar show] 'undefined))
5398 (org-load-modules-maybe)
5399 (easy-menu-add org-org-menu)
5400 (easy-menu-add org-tbl-menu)
5401 (org-install-agenda-files-menu)
5402 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5403 (add-to-invisibility-spec '(org-cwidth))
5404 (add-to-invisibility-spec '(org-hide-block . t))
5405 (when (featurep 'xemacs)
5406 (org-set-local 'line-move-ignore-invisible t))
5407 (org-set-local 'outline-regexp org-outline-regexp)
5408 (org-set-local 'outline-level 'org-outline-level)
5409 (setq bidi-paragraph-direction 'left-to-right)
5410 (when (and org-ellipsis
5411 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5412 (fboundp 'make-glyph-code))
5413 (unless org-display-table
5414 (setq org-display-table (make-display-table)))
5415 (set-display-table-slot
5416 org-display-table 4
5417 (vconcat (mapcar
5418 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5419 org-ellipsis)))
5420 (if (stringp org-ellipsis) org-ellipsis "..."))))
5421 (setq buffer-display-table org-display-table))
5422 (org-set-regexps-and-options-for-tags)
5423 (org-set-regexps-and-options)
5424 (org-set-font-lock-defaults)
5425 (when (and org-tag-faces (not org-tags-special-faces-re))
5426 ;; tag faces set outside customize.... force initialization.
5427 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5428 ;; Calc embedded
5429 (org-set-local 'calc-embedded-open-mode "# ")
5430 ;; Modify a few syntax entries
5431 (modify-syntax-entry ?@ "w")
5432 (modify-syntax-entry ?\" "\"")
5433 (modify-syntax-entry ?\\ "_")
5434 (modify-syntax-entry ?~ "_")
5435 (if org-startup-truncated (setq truncate-lines t))
5436 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5437 (org-set-local 'font-lock-unfontify-region-function
5438 'org-unfontify-region)
5439 ;; Activate before-change-function
5440 (org-set-local 'org-table-may-need-update t)
5441 (org-add-hook 'before-change-functions 'org-before-change-function nil
5442 'local)
5443 ;; Check for running clock before killing a buffer
5444 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5445 ;; Initialize macros templates.
5446 (org-macro-initialize-templates)
5447 ;; Initialize radio targets.
5448 (org-update-radio-target-regexp)
5449 ;; Indentation.
5450 (org-set-local 'indent-line-function 'org-indent-line)
5451 (org-set-local 'indent-region-function 'org-indent-region)
5452 ;; Filling and auto-filling.
5453 (org-setup-filling)
5454 ;; Comments.
5455 (org-setup-comments-handling)
5456 ;; Initialize cache.
5457 (org-element-cache-reset)
5458 ;; Beginning/end of defun
5459 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5460 (org-set-local 'end-of-defun-function
5461 (lambda ()
5462 (if (not (org-at-heading-p))
5463 (org-forward-element)
5464 (org-forward-element)
5465 (forward-char -1))))
5466 ;; Next error for sparse trees
5467 (org-set-local 'next-error-function 'org-occur-next-match)
5468 ;; Make sure dependence stuff works reliably, even for users who set it
5469 ;; too late :-(
5470 (if org-enforce-todo-dependencies
5471 (add-hook 'org-blocker-hook
5472 'org-block-todo-from-children-or-siblings-or-parent)
5473 (remove-hook 'org-blocker-hook
5474 'org-block-todo-from-children-or-siblings-or-parent))
5475 (if org-enforce-todo-checkbox-dependencies
5476 (add-hook 'org-blocker-hook
5477 'org-block-todo-from-checkboxes)
5478 (remove-hook 'org-blocker-hook
5479 'org-block-todo-from-checkboxes))
5481 ;; Align options lines
5482 (org-set-local
5483 'align-mode-rules-list
5484 '((org-in-buffer-settings
5485 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5486 (modes . '(org-mode)))))
5488 ;; Imenu
5489 (org-set-local 'imenu-create-index-function
5490 'org-imenu-get-tree)
5492 ;; Make isearch reveal context
5493 (if (or (featurep 'xemacs)
5494 (not (boundp 'outline-isearch-open-invisible-function)))
5495 ;; Emacs 21 and XEmacs make use of the hook
5496 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5497 ;; Emacs 22 deals with this through a special variable
5498 (org-set-local 'outline-isearch-open-invisible-function
5499 (lambda (&rest ignore) (org-show-context 'isearch))))
5501 ;; Setup the pcomplete hooks
5502 (set (make-local-variable 'pcomplete-command-completion-function)
5503 'org-pcomplete-initial)
5504 (set (make-local-variable 'pcomplete-command-name-function)
5505 'org-command-at-point)
5506 (set (make-local-variable 'pcomplete-default-completion-function)
5507 'ignore)
5508 (set (make-local-variable 'pcomplete-parse-arguments-function)
5509 'org-parse-arguments)
5510 (set (make-local-variable 'pcomplete-termination-string) "")
5511 (when (>= emacs-major-version 23)
5512 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5514 ;; If empty file that did not turn on org-mode automatically, make it to.
5515 (if (and org-insert-mode-line-in-empty-file
5516 (org-called-interactively-p 'any)
5517 (= (point-min) (point-max)))
5518 (insert "# -*- mode: org -*-\n\n"))
5519 (unless org-inhibit-startup
5520 (org-unmodified
5521 (and org-startup-with-beamer-mode (org-beamer-mode))
5522 (when org-startup-align-all-tables
5523 (org-table-map-tables 'org-table-align 'quietly))
5524 (when org-startup-with-inline-images
5525 (org-display-inline-images))
5526 (when org-startup-with-latex-preview
5527 (org-toggle-latex-fragment))
5528 (unless org-inhibit-startup-visibility-stuff
5529 (org-set-startup-visibility))
5530 (org-refresh-effort-properties)))
5531 ;; Try to set org-hide correctly
5532 (let ((foreground (org-find-invisible-foreground)))
5533 (if foreground
5534 (set-face-foreground 'org-hide foreground))))
5536 ;; Update `customize-package-emacs-version-alist'
5537 (add-to-list 'customize-package-emacs-version-alist
5538 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5539 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5540 ("8.2.6" . "24.4")))
5542 (defvar org-mode-transpose-word-syntax-table
5543 (let ((st (make-syntax-table)))
5544 (mapc (lambda(c) (modify-syntax-entry
5545 (string-to-char (car c)) "w p" st))
5546 org-emphasis-alist)
5547 st))
5549 (when (fboundp 'abbrev-table-put)
5550 (abbrev-table-put org-mode-abbrev-table
5551 :parents (list text-mode-abbrev-table)))
5553 (defun org-find-invisible-foreground ()
5554 (let ((candidates (remove
5555 "unspecified-bg"
5556 (nconc
5557 (list (face-background 'default)
5558 (face-background 'org-default))
5559 (mapcar
5560 (lambda (alist)
5561 (when (boundp alist)
5562 (cdr (assoc 'background-color (symbol-value alist)))))
5563 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5564 (list (face-foreground 'org-hide))))))
5565 (car (remove nil candidates))))
5567 (defun org-current-time (&optional rounding-minutes past)
5568 "Current time, possibly rounded to ROUNDING-MINUTES.
5569 When ROUNDING-MINUTES is not an integer, fall back on the car of
5570 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5571 the rounding returns a past time."
5572 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5573 (car org-time-stamp-rounding-minutes)))
5574 (time (decode-time)) res)
5575 (if (< r 1)
5576 (current-time)
5577 (setq res
5578 (apply 'encode-time
5579 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5580 (nthcdr 2 time))))
5581 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5582 (seconds-to-time (- (org-float-time res) (* r 60)))
5583 res))))
5585 (defun org-today ()
5586 "Return today date, considering `org-extend-today-until'."
5587 (time-to-days
5588 (time-subtract (current-time)
5589 (list 0 (* 3600 org-extend-today-until) 0))))
5591 ;;;; Font-Lock stuff, including the activators
5593 (defvar org-mouse-map (make-sparse-keymap))
5594 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5595 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5596 (when org-mouse-1-follows-link
5597 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5598 (when org-tab-follows-link
5599 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5600 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5602 (require 'font-lock)
5604 (defconst org-non-link-chars "]\t\n\r<>")
5605 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5606 "file+sys" "news" "shell" "elisp" "doi" "message"
5607 "help"))
5608 (defvar org-link-types-re nil
5609 "Matches a link that has a url-like prefix like \"http:\"")
5610 (defvar org-link-re-with-space nil
5611 "Matches a link with spaces, optional angular brackets around it.")
5612 (defvar org-link-re-with-space2 nil
5613 "Matches a link with spaces, optional angular brackets around it.")
5614 (defvar org-link-re-with-space3 nil
5615 "Matches a link with spaces, only for internal part in bracket links.")
5616 (defvar org-angle-link-re nil
5617 "Matches link with angular brackets, spaces are allowed.")
5618 (defvar org-plain-link-re nil
5619 "Matches plain link, without spaces.")
5620 (defvar org-bracket-link-regexp nil
5621 "Matches a link in double brackets.")
5622 (defvar org-bracket-link-analytic-regexp nil
5623 "Regular expression used to analyze links.
5624 Here is what the match groups contain after a match:
5625 1: http:
5626 2: http
5627 3: path
5628 4: [desc]
5629 5: desc")
5630 (defvar org-bracket-link-analytic-regexp++ nil
5631 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5632 (defvar org-any-link-re nil
5633 "Regular expression matching any link.")
5635 (defconst org-match-sexp-depth 3
5636 "Number of stacked braces for sub/superscript matching.")
5638 (defun org-create-multibrace-regexp (left right n)
5639 "Create a regular expression which will match a balanced sexp.
5640 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5641 as single character strings.
5642 The regexp returned will match the entire expression including the
5643 delimiters. It will also define a single group which contains the
5644 match except for the outermost delimiters. The maximum depth of
5645 stacked delimiters is N. Escaping delimiters is not possible."
5646 (let* ((nothing (concat "[^" left right "]*?"))
5647 (or "\\|")
5648 (re nothing)
5649 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5650 (while (> n 1)
5651 (setq n (1- n)
5652 re (concat re or next)
5653 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5654 (concat left "\\(" re "\\)" right)))
5656 (defconst org-match-substring-regexp
5657 (concat
5658 "\\(\\S-\\)\\([_^]\\)\\("
5659 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5660 "\\|"
5661 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5662 "\\|"
5663 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5664 "The regular expression matching a sub- or superscript.")
5666 (defconst org-match-substring-with-braces-regexp
5667 (concat
5668 "\\(\\S-\\)\\([_^]\\)"
5669 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5670 "The regular expression matching a sub- or superscript, forcing braces.")
5672 (defun org-make-link-regexps ()
5673 "Update the link regular expressions.
5674 This should be called after the variable `org-link-types' has changed."
5675 (let ((types-re (regexp-opt org-link-types t)))
5676 (setq org-link-types-re
5677 (concat "\\`" types-re ":")
5678 org-link-re-with-space
5679 (concat "<?" types-re ":"
5680 "\\([^" org-non-link-chars " ]"
5681 "[^" org-non-link-chars "]*"
5682 "[^" org-non-link-chars " ]\\)>?")
5683 org-link-re-with-space2
5684 (concat "<?" types-re ":"
5685 "\\([^" org-non-link-chars " ]"
5686 "[^\t\n\r]*"
5687 "[^" org-non-link-chars " ]\\)>?")
5688 org-link-re-with-space3
5689 (concat "<?" types-re ":"
5690 "\\([^" org-non-link-chars " ]"
5691 "[^\t\n\r]*\\)")
5692 org-angle-link-re
5693 (concat "<" types-re ":"
5694 "\\([^" org-non-link-chars " ]"
5695 "[^" org-non-link-chars "]*"
5696 "\\)>")
5697 org-plain-link-re
5698 (concat
5699 "\\<" types-re ":"
5700 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5701 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5702 org-bracket-link-regexp
5703 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5704 org-bracket-link-analytic-regexp
5705 (concat
5706 "\\[\\["
5707 "\\(" types-re ":\\)?"
5708 "\\([^]]+\\)"
5709 "\\]"
5710 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5711 "\\]")
5712 org-bracket-link-analytic-regexp++
5713 (concat
5714 "\\[\\["
5715 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5716 "\\([^]]+\\)"
5717 "\\]"
5718 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5719 "\\]")
5720 org-any-link-re
5721 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5722 org-angle-link-re "\\)\\|\\("
5723 org-plain-link-re "\\)"))))
5725 (org-make-link-regexps)
5727 (defvar org-emph-face nil)
5729 (defun org-do-emphasis-faces (limit)
5730 "Run through the buffer and emphasize strings."
5731 (let (rtn a)
5732 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5733 (let* ((border (char-after (match-beginning 3)))
5734 (bre (regexp-quote (char-to-string border))))
5735 (if (and (not (= border (char-after (match-beginning 4))))
5736 (not (save-match-data
5737 (string-match (concat bre ".*" bre)
5738 (replace-regexp-in-string
5739 "\n" " "
5740 (substring (match-string 2) 1 -1))))))
5741 (progn
5742 (setq rtn t)
5743 (setq a (assoc (match-string 3) org-emphasis-alist))
5744 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5745 'face
5746 (nth 1 a))
5747 (and (nth 2 a)
5748 (org-remove-flyspell-overlays-in
5749 (match-beginning 0) (match-end 0)))
5750 (add-text-properties (match-beginning 2) (match-end 2)
5751 '(font-lock-multiline t org-emphasis t))
5752 (when org-hide-emphasis-markers
5753 (add-text-properties (match-end 4) (match-beginning 5)
5754 '(invisible org-link))
5755 (add-text-properties (match-beginning 3) (match-end 3)
5756 '(invisible org-link))))))
5757 (goto-char (1+ (match-beginning 0))))
5758 rtn))
5760 (defun org-emphasize (&optional char)
5761 "Insert or change an emphasis, i.e. a font like bold or italic.
5762 If there is an active region, change that region to a new emphasis.
5763 If there is no region, just insert the marker characters and position
5764 the cursor between them.
5765 CHAR should be the marker character. If it is a space, it means to
5766 remove the emphasis of the selected region.
5767 If CHAR is not given (for example in an interactive call) it will be
5768 prompted for."
5769 (interactive)
5770 (let ((erc org-emphasis-regexp-components)
5771 (prompt "")
5772 (string "") beg end move c s)
5773 (if (org-region-active-p)
5774 (setq beg (region-beginning) end (region-end)
5775 string (buffer-substring beg end))
5776 (setq move t))
5778 (unless char
5779 (message "Emphasis marker or tag: [%s]"
5780 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5781 (setq char (read-char-exclusive)))
5782 (if (equal char ?\ )
5783 (setq s "" move nil)
5784 (unless (assoc (char-to-string char) org-emphasis-alist)
5785 (user-error "No such emphasis marker: \"%c\"" char))
5786 (setq s (char-to-string char)))
5787 (while (and (> (length string) 1)
5788 (equal (substring string 0 1) (substring string -1))
5789 (assoc (substring string 0 1) org-emphasis-alist))
5790 (setq string (substring string 1 -1)))
5791 (setq string (concat s string s))
5792 (if beg (delete-region beg end))
5793 (unless (or (bolp)
5794 (string-match (concat "[" (nth 0 erc) "\n]")
5795 (char-to-string (char-before (point)))))
5796 (insert " "))
5797 (unless (or (eobp)
5798 (string-match (concat "[" (nth 1 erc) "\n]")
5799 (char-to-string (char-after (point)))))
5800 (insert " ") (backward-char 1))
5801 (insert string)
5802 (and move (backward-char 1))))
5804 (defconst org-nonsticky-props
5805 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5807 (defsubst org-rear-nonsticky-at (pos)
5808 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5810 (defun org-activate-plain-links (limit)
5811 "Add link properties for plain links."
5812 (let (f hl)
5813 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5814 (not (member 'org-tag
5815 (get-text-property (1- (match-beginning 0)) 'face)))
5816 (not (org-in-src-block-p)))
5817 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5818 (setq f (get-text-property (match-beginning 0) 'face))
5819 (setq hl (org-match-string-no-properties 0))
5820 (if (or (eq f 'org-tag)
5821 (and (listp f) (memq 'org-tag f)))
5823 (add-text-properties (match-beginning 0) (match-end 0)
5824 (list 'mouse-face 'highlight
5825 'face 'org-link
5826 'htmlize-link `(:uri ,hl)
5827 'keymap org-mouse-map))
5828 (org-rear-nonsticky-at (match-end 0)))
5829 t)))
5831 (defun org-activate-code (limit)
5832 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5833 (progn
5834 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5835 (remove-text-properties (match-beginning 0) (match-end 0)
5836 '(display t invisible t intangible t))
5837 t)))
5839 (defcustom org-src-fontify-natively t
5840 "When non-nil, fontify code in code blocks."
5841 :type 'boolean
5842 :version "24.4"
5843 :package-version '(Org . "8.3")
5844 :group 'org-appearance
5845 :group 'org-babel)
5847 (defcustom org-allow-promoting-top-level-subtree nil
5848 "When non-nil, allow promoting a top level subtree.
5849 The leading star of the top level headline will be replaced
5850 by a #."
5851 :type 'boolean
5852 :version "24.1"
5853 :group 'org-appearance)
5855 (defun org-fontify-meta-lines-and-blocks (limit)
5856 (condition-case nil
5857 (org-fontify-meta-lines-and-blocks-1 limit)
5858 (error (message "org-mode fontification error"))))
5860 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5861 "Fontify #+ lines and blocks."
5862 (let ((case-fold-search t))
5863 (if (re-search-forward
5864 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5865 limit t)
5866 (let ((beg (match-beginning 0))
5867 (block-start (match-end 0))
5868 (block-end nil)
5869 (lang (match-string 7))
5870 (beg1 (line-beginning-position 2))
5871 (dc1 (downcase (match-string 2)))
5872 (dc3 (downcase (match-string 3)))
5873 end end1 quoting block-type ovl)
5874 (cond
5875 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5876 ;; a single line of backend-specific content
5877 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5878 (remove-text-properties (match-beginning 0) (match-end 0)
5879 '(display t invisible t intangible t))
5880 (add-text-properties (match-beginning 1) (match-end 3)
5881 '(font-lock-fontified t face org-meta-line))
5882 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5883 '(font-lock-fontified t face org-block))
5884 ; for backend-specific code
5886 ((and (match-end 4) (equal dc3 "+begin"))
5887 ;; Truly a block
5888 (setq block-type (downcase (match-string 5))
5889 quoting (member block-type org-protecting-blocks))
5890 (when (re-search-forward
5891 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5892 nil t) ;; on purpose, we look further than LIMIT
5893 (setq end (min (point-max) (match-end 0))
5894 end1 (min (point-max) (1- (match-beginning 0))))
5895 (setq block-end (match-beginning 0))
5896 (when quoting
5897 (org-remove-flyspell-overlays-in beg1 end1)
5898 (remove-text-properties beg end
5899 '(display t invisible t intangible t)))
5900 (add-text-properties
5901 beg end '(font-lock-fontified t font-lock-multiline t))
5902 (add-text-properties beg beg1 '(face org-meta-line))
5903 (org-remove-flyspell-overlays-in beg beg1)
5904 (add-text-properties ; For end_src
5905 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5906 (org-remove-flyspell-overlays-in end1 end)
5907 (cond
5908 ((and lang (not (string= lang "")) org-src-fontify-natively)
5909 (org-src-font-lock-fontify-block lang block-start block-end)
5910 (add-text-properties beg1 block-end '(src-block t)))
5911 (quoting
5912 (add-text-properties beg1 (min (point-max) (1+ end1))
5913 '(face org-block))) ; end of source block
5914 ((not org-fontify-quote-and-verse-blocks))
5915 ((string= block-type "quote")
5916 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5917 ((string= block-type "verse")
5918 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5919 (add-text-properties beg beg1 '(face org-block-begin-line))
5920 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5921 '(face org-block-end-line))
5923 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5924 (org-remove-flyspell-overlays-in
5925 (match-beginning 0)
5926 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5927 (add-text-properties
5928 beg (match-end 3)
5929 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5930 '(font-lock-fontified t invisible t)
5931 '(font-lock-fontified t face org-document-info-keyword)))
5932 (add-text-properties
5933 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5934 (if (string-equal dc1 "+title:")
5935 '(font-lock-fontified t face org-document-title)
5936 '(font-lock-fontified t face org-document-info))))
5937 ((or (equal dc1 "+results")
5938 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5939 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5940 "+call:" "+header:" "+headers:" "+name:"))
5941 (and (match-end 4) (equal dc3 "+attr")))
5942 (org-remove-flyspell-overlays-in
5943 (match-beginning 0)
5944 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5945 (add-text-properties
5946 beg (match-end 0)
5947 '(font-lock-fontified t face org-meta-line))
5949 ((member dc3 '(" " ""))
5950 (org-remove-flyspell-overlays-in beg (match-end 0))
5951 (add-text-properties
5952 beg (match-end 0)
5953 '(font-lock-fontified t face font-lock-comment-face)))
5954 (t ;; just any other in-buffer setting, but not indented
5955 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5956 (add-text-properties
5957 beg (match-end 0)
5958 '(font-lock-fontified t face org-meta-line))
5959 t))))))
5961 (defun org-fontify-drawers (limit)
5962 "Fontify drawers."
5963 (when (re-search-forward org-drawer-regexp limit t)
5964 (add-text-properties
5965 (match-beginning 0) (match-end 0)
5966 '(font-lock-fontified t face org-special-keyword))
5967 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (defun org-fontify-macros (limit)
5971 "Fontify macros."
5972 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5973 (add-text-properties
5974 (match-beginning 0) (match-end 0)
5975 '(font-lock-fontified t face org-macro))
5976 (when org-hide-macro-markers
5977 (add-text-properties (match-end 2) (match-beginning 2)
5978 '(invisible t))
5979 (add-text-properties (match-beginning 1) (match-end 1)
5980 '(invisible t)))
5981 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (defun org-activate-angle-links (limit)
5985 "Add text properties for angle links."
5986 (if (and (re-search-forward org-angle-link-re limit t)
5987 (not (org-in-src-block-p)))
5988 (progn
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5990 (add-text-properties (match-beginning 0) (match-end 0)
5991 (list 'mouse-face 'highlight
5992 'keymap org-mouse-map))
5993 (org-rear-nonsticky-at (match-end 0))
5994 t)))
5996 (defun org-activate-footnote-links (limit)
5997 "Add text properties for footnotes."
5998 (let ((fn (org-footnote-next-reference-or-definition limit)))
5999 (when fn
6000 (let* ((beg (nth 1 fn))
6001 (end (nth 2 fn))
6002 (label (car fn))
6003 (referencep (/= (line-beginning-position) beg)))
6004 (when (and referencep (nth 3 fn))
6005 (save-excursion
6006 (goto-char beg)
6007 (search-forward (or label "fn:"))
6008 (org-remove-flyspell-overlays-in beg (match-end 0))))
6009 (add-text-properties beg end
6010 (list 'mouse-face 'highlight
6011 'keymap org-mouse-map
6012 'help-echo
6013 (if referencep "Footnote reference"
6014 "Footnote definition")
6015 'font-lock-fontified t
6016 'font-lock-multiline t
6017 'face 'org-footnote))))))
6019 (defun org-activate-bracket-links (limit)
6020 "Add text properties for bracketed links."
6021 (if (and (re-search-forward org-bracket-link-regexp limit t)
6022 (not (org-in-src-block-p)))
6023 (let* ((hl (org-match-string-no-properties 1))
6024 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6025 (ip (org-maybe-intangible
6026 (list 'invisible 'org-link
6027 'keymap org-mouse-map 'mouse-face 'highlight
6028 'font-lock-multiline t 'help-echo help
6029 'htmlize-link `(:uri ,hl))))
6030 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6031 'font-lock-multiline t 'help-echo help
6032 'htmlize-link `(:uri ,hl))))
6033 ;; We need to remove the invisible property here. Table narrowing
6034 ;; may have made some of this invisible.
6035 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6036 (remove-text-properties (match-beginning 0) (match-end 0)
6037 '(invisible nil))
6038 (if (match-end 3)
6039 (progn
6040 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6041 (org-rear-nonsticky-at (match-beginning 3))
6042 (add-text-properties (match-beginning 3) (match-end 3) vp)
6043 (org-rear-nonsticky-at (match-end 3))
6044 (add-text-properties (match-end 3) (match-end 0) ip)
6045 (org-rear-nonsticky-at (match-end 0)))
6046 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6047 (org-rear-nonsticky-at (match-beginning 1))
6048 (add-text-properties (match-beginning 1) (match-end 1) vp)
6049 (org-rear-nonsticky-at (match-end 1))
6050 (add-text-properties (match-end 1) (match-end 0) ip)
6051 (org-rear-nonsticky-at (match-end 0)))
6052 t)))
6054 (defun org-activate-dates (limit)
6055 "Add text properties for dates."
6056 (if (and (re-search-forward org-tsr-regexp-both limit t)
6057 (not (equal (char-before (match-beginning 0)) 91)))
6058 (progn
6059 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6060 (add-text-properties (match-beginning 0) (match-end 0)
6061 (list 'mouse-face 'highlight
6062 'keymap org-mouse-map))
6063 (org-rear-nonsticky-at (match-end 0))
6064 (when org-display-custom-times
6065 (if (match-end 3)
6066 (org-display-custom-time (match-beginning 3) (match-end 3)))
6067 (org-display-custom-time (match-beginning 1) (match-end 1)))
6068 t)))
6070 (defvar org-target-link-regexp nil
6071 "Regular expression matching radio targets in plain text.")
6072 (make-variable-buffer-local 'org-target-link-regexp)
6074 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6075 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6076 border border border))
6077 "Regular expression matching a link target.")
6079 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6080 "Regular expression matching a radio target.")
6082 (defconst org-any-target-regexp
6083 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6084 "Regular expression matching any target.")
6086 (defun org-activate-target-links (limit)
6087 "Add text properties for target matches."
6088 (when org-target-link-regexp
6089 (let ((case-fold-search t))
6090 (if (re-search-forward org-target-link-regexp limit t)
6091 (progn
6092 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6093 (add-text-properties (match-beginning 1) (match-end 1)
6094 (list 'mouse-face 'highlight
6095 'keymap org-mouse-map
6096 'help-echo "Radio target link"
6097 'org-linked-text t))
6098 (org-rear-nonsticky-at (match-end 1))
6099 t)))))
6101 (defun org-update-radio-target-regexp ()
6102 "Find all radio targets in this file and update the regular expression.
6103 Also refresh fontification if needed."
6104 (interactive)
6105 (let ((old-regexp org-target-link-regexp)
6106 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6107 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6108 (targets
6109 (org-with-wide-buffer
6110 (goto-char (point-min))
6111 (let (rtn)
6112 (while (re-search-forward org-radio-target-regexp nil t)
6113 ;; Make sure point is really within the object.
6114 (backward-char)
6115 (let ((obj (org-element-context)))
6116 (when (eq (org-element-type obj) 'radio-target)
6117 (add-to-list 'rtn (org-element-property :value obj)))))
6118 rtn))))
6119 (setq org-target-link-regexp
6120 (and targets
6121 (concat before-re
6122 (mapconcat
6123 (lambda (x)
6124 (replace-regexp-in-string
6125 " +" "\\s-+" (regexp-quote x) t t))
6126 targets
6127 "\\|")
6128 after-re)))
6129 (unless (equal old-regexp org-target-link-regexp)
6130 ;; Clean-up cache.
6131 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6132 ((not org-target-link-regexp) old-regexp)
6134 (concat before-re
6135 (mapconcat
6136 (lambda (re)
6137 (substring re (length before-re)
6138 (- (length after-re))))
6139 (list old-regexp org-target-link-regexp)
6140 "\\|")
6141 after-re)))))
6142 (org-with-wide-buffer
6143 (goto-char (point-min))
6144 (while (re-search-forward regexp nil t)
6145 (org-element-cache-refresh (match-beginning 1)))))
6146 ;; Re fontify buffer.
6147 (when (memq 'radio org-highlight-links)
6148 (org-restart-font-lock)))))
6150 (defun org-hide-wide-columns (limit)
6151 (let (s e)
6152 (setq s (text-property-any (point) (or limit (point-max))
6153 'org-cwidth t))
6154 (when s
6155 (setq e (next-single-property-change s 'org-cwidth))
6156 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6157 (goto-char e)
6158 t)))
6160 (defvar org-latex-and-related-regexp nil
6161 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6163 (defun org-compute-latex-and-related-regexp ()
6164 "Compute regular expression for LaTeX, entities and sub/superscript.
6165 Result depends on variable `org-highlight-latex-and-related'."
6166 (org-set-local
6167 'org-latex-and-related-regexp
6168 (let* ((re-sub
6169 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6170 ((eq org-use-sub-superscripts '{})
6171 (list org-match-substring-with-braces-regexp))
6172 (org-use-sub-superscripts (list org-match-substring-regexp))))
6173 (re-latex
6174 (when (memq 'latex org-highlight-latex-and-related)
6175 (let ((matchers (plist-get org-format-latex-options :matchers)))
6176 (delq nil
6177 (mapcar (lambda (x)
6178 (and (member (car x) matchers) (nth 1 x)))
6179 org-latex-regexps)))))
6180 (re-entities
6181 (when (memq 'entities org-highlight-latex-and-related)
6182 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6183 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6185 (defun org-do-latex-and-related (limit)
6186 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6187 LIMIT bounds the search for syntax to highlight. Stop at first
6188 highlighted object, if any. Return t if some highlighting was
6189 done, nil otherwise."
6190 (when (org-string-nw-p org-latex-and-related-regexp)
6191 (catch 'found
6192 (while (re-search-forward org-latex-and-related-regexp limit t)
6193 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6194 'face))
6195 '(org-code org-verbatim underline))
6196 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6197 '(?_ ?^))
6199 0)))
6200 (font-lock-prepend-text-property
6201 (+ offset (match-beginning 0)) (match-end 0)
6202 'face 'org-latex-and-related)
6203 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6204 '(font-lock-multiline t)))
6205 (throw 'found t)))
6206 nil)))
6208 (defun org-restart-font-lock ()
6209 "Restart `font-lock-mode', to force refontification."
6210 (when (and (boundp 'font-lock-mode) font-lock-mode)
6211 (font-lock-mode -1)
6212 (font-lock-mode 1)))
6214 (defun org-activate-tags (limit)
6215 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6216 (progn
6217 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6218 (add-text-properties (match-beginning 1) (match-end 1)
6219 (list 'mouse-face 'highlight
6220 'keymap org-mouse-map))
6221 (org-rear-nonsticky-at (match-end 1))
6222 t)))
6224 (defun org-outline-level ()
6225 "Compute the outline level of the heading at point.
6226 If this is called at a normal headline, the level is the number of stars.
6227 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6228 (save-excursion
6229 (if (not (ignore-errors (org-back-to-heading t)))
6231 (looking-at org-outline-regexp)
6232 (1- (- (match-end 0) (match-beginning 0))))))
6234 (defvar org-font-lock-keywords nil)
6236 (defsubst org-re-property (property &optional literal allow-null)
6237 "Return a regexp matching a PROPERTY line.
6239 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6240 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6241 non-nil, match properties even without a value.
6243 Match group 3 is set to the value when it exists. If there is no
6244 value and ALLOW-NULL is non-nil, it is set to the empty string."
6245 (concat
6246 "^\\(?4:[ \t]*\\)"
6247 (format "\\(?1::\\(?2:%s\\):\\)"
6248 (if literal property (regexp-quote property)))
6249 (if allow-null
6250 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6251 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6253 (defconst org-property-re
6254 (org-re-property "\\S-+" 'literal t)
6255 "Regular expression matching a property line.
6256 There are four matching groups:
6257 1: :PROPKEY: including the leading and trailing colon,
6258 2: PROPKEY without the leading and trailing colon,
6259 3: PROPVAL without leading or trailing spaces,
6260 4: the indentation of the current line,
6261 5: trailing whitespace.")
6263 (defvar org-font-lock-hook nil
6264 "Functions to be called for special font lock stuff.")
6266 (defvar org-font-lock-set-keywords-hook nil
6267 "Functions that can manipulate `org-font-lock-extra-keywords'.
6268 This is called after `org-font-lock-extra-keywords' is defined, but before
6269 it is installed to be used by font lock. This can be useful if something
6270 needs to be inserted at a specific position in the font-lock sequence.")
6272 (defun org-font-lock-hook (limit)
6273 "Run `org-font-lock-hook' within LIMIT."
6274 (run-hook-with-args 'org-font-lock-hook limit))
6276 (defun org-set-font-lock-defaults ()
6277 "Set font lock defaults for the current buffer."
6278 (let* ((em org-fontify-emphasized-text)
6279 (lk org-highlight-links)
6280 (org-font-lock-extra-keywords
6281 (list
6282 ;; Call the hook
6283 '(org-font-lock-hook)
6284 ;; Headlines
6285 `(,(if org-fontify-whole-heading-line
6286 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6287 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6288 (1 (org-get-level-face 1))
6289 (2 (org-get-level-face 2))
6290 (3 (org-get-level-face 3)))
6291 ;; Table lines
6292 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6293 (1 'org-table t))
6294 ;; Table internals
6295 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6296 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6297 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6298 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6299 ;; Drawers
6300 '(org-fontify-drawers)
6301 ;; Properties
6302 (list org-property-re
6303 '(1 'org-special-keyword t)
6304 '(3 'org-property-value t))
6305 ;; Links
6306 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6307 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6308 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6309 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6310 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6311 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6312 (if (memq 'footnote lk) '(org-activate-footnote-links))
6313 ;; Targets.
6314 (list org-any-target-regexp '(0 'org-target t))
6315 ;; Diary sexps.
6316 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6317 ;; Macro
6318 '(org-fontify-macros)
6319 '(org-hide-wide-columns (0 nil append))
6320 ;; TODO keyword
6321 (list (format org-heading-keyword-regexp-format
6322 org-todo-regexp)
6323 '(2 (org-get-todo-face 2) t))
6324 ;; DONE
6325 (if org-fontify-done-headline
6326 (list (format org-heading-keyword-regexp-format
6327 (concat
6328 "\\(?:"
6329 (mapconcat 'regexp-quote org-done-keywords "\\|")
6330 "\\)"))
6331 '(2 'org-headline-done t))
6332 nil)
6333 ;; Priorities
6334 '(org-font-lock-add-priority-faces)
6335 ;; Tags
6336 '(org-font-lock-add-tag-faces)
6337 ;; Tags groups
6338 (if (and org-group-tags org-tag-groups-alist)
6339 (list (concat org-outline-regexp-bol ".+\\(:"
6340 (regexp-opt (mapcar 'car org-tag-groups-alist))
6341 ":\\).*$")
6342 '(1 'org-tag-group prepend)))
6343 ;; Special keywords
6344 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6345 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6346 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6347 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6348 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6349 ;; Emphasis
6350 (if em
6351 (if (featurep 'xemacs)
6352 '(org-do-emphasis-faces (0 nil append))
6353 '(org-do-emphasis-faces)))
6354 ;; Checkboxes
6355 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6356 1 'org-checkbox prepend)
6357 (if (cdr (assq 'checkbox org-list-automatic-rules))
6358 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6359 (0 (org-get-checkbox-statistics-face) t)))
6360 ;; Description list items
6361 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6362 1 'org-list-dt prepend)
6363 ;; ARCHIVEd headings
6364 (list (concat
6365 org-outline-regexp-bol
6366 "\\(.*:" org-archive-tag ":.*\\)")
6367 '(1 'org-archived prepend))
6368 ;; Specials
6369 '(org-do-latex-and-related)
6370 '(org-fontify-entities)
6371 '(org-raise-scripts)
6372 ;; Code
6373 '(org-activate-code (1 'org-code t))
6374 ;; COMMENT
6375 (list (format
6376 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6377 org-todo-regexp
6378 org-comment-string)
6379 '(9 'org-special-keyword t))
6380 ;; Blocks and meta lines
6381 '(org-fontify-meta-lines-and-blocks))))
6382 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6383 (run-hooks 'org-font-lock-set-keywords-hook)
6384 ;; Now set the full font-lock-keywords
6385 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6386 (org-set-local 'font-lock-defaults
6387 '(org-font-lock-keywords t nil nil backward-paragraph))
6388 (kill-local-variable 'font-lock-keywords) nil))
6390 (defun org-toggle-pretty-entities ()
6391 "Toggle the composition display of entities as UTF8 characters."
6392 (interactive)
6393 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6394 (org-restart-font-lock)
6395 (if org-pretty-entities
6396 (message "Entities are now displayed as UTF8 characters")
6397 (save-restriction
6398 (widen)
6399 (org-decompose-region (point-min) (point-max))
6400 (message "Entities are now displayed as plain text"))))
6402 (defvar org-custom-properties-overlays nil
6403 "List of overlays used for custom properties.")
6404 (make-variable-buffer-local 'org-custom-properties-overlays)
6406 (defun org-toggle-custom-properties-visibility ()
6407 "Display or hide properties in `org-custom-properties'."
6408 (interactive)
6409 (if org-custom-properties-overlays
6410 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6411 (setq org-custom-properties-overlays nil))
6412 (unless (not org-custom-properties)
6413 (save-excursion
6414 (save-restriction
6415 (widen)
6416 (goto-char (point-min))
6417 (while (re-search-forward org-property-re nil t)
6418 (mapc (lambda(p)
6419 (when (equal p (substring (match-string 1) 1 -1))
6420 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6421 (overlay-put o 'invisible t)
6422 (overlay-put o 'org-custom-property t)
6423 (push o org-custom-properties-overlays))))
6424 org-custom-properties)))))))
6426 (defun org-fontify-entities (limit)
6427 "Find an entity to fontify."
6428 (let (ee)
6429 (when org-pretty-entities
6430 (catch 'match
6431 (while (re-search-forward
6432 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6433 limit t)
6434 (if (and (not (org-at-comment-p))
6435 (setq ee (org-entity-get (match-string 1)))
6436 (= (length (nth 6 ee)) 1))
6437 (let*
6438 ((end (if (equal (match-string 2) "{}")
6439 (match-end 2)
6440 (match-end 1))))
6441 (add-text-properties
6442 (match-beginning 0) end
6443 (list 'font-lock-fontified t))
6444 (compose-region (match-beginning 0) end
6445 (nth 6 ee) nil)
6446 (backward-char 1)
6447 (throw 'match t))))
6448 nil))))
6450 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6451 "Fontify string S like in Org-mode."
6452 (with-temp-buffer
6453 (insert s)
6454 (let ((org-odd-levels-only odd-levels))
6455 (org-mode)
6456 (font-lock-ensure)
6457 (buffer-string))))
6459 (defvar org-m nil)
6460 (defvar org-l nil)
6461 (defvar org-f nil)
6462 (defun org-get-level-face (n)
6463 "Get the right face for match N in font-lock matching of headlines."
6464 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6465 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6466 (if org-cycle-level-faces
6467 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6468 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6469 (cond
6470 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6471 ((eq n 2) org-f)
6472 (t (if org-level-color-stars-only nil org-f))))
6475 (defun org-get-todo-face (kwd)
6476 "Get the right face for a TODO keyword KWD.
6477 If KWD is a number, get the corresponding match group."
6478 (if (numberp kwd) (setq kwd (match-string kwd)))
6479 (or (org-face-from-face-or-color
6480 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6481 (and (member kwd org-done-keywords) 'org-done)
6482 'org-todo))
6484 (defun org-face-from-face-or-color (context inherit face-or-color)
6485 "Create a face list that inherits INHERIT, but sets the foreground color.
6486 When FACE-OR-COLOR is not a string, just return it."
6487 (if (stringp face-or-color)
6488 (list :inherit inherit
6489 (cdr (assoc context org-faces-easy-properties))
6490 face-or-color)
6491 face-or-color))
6493 (defun org-font-lock-add-tag-faces (limit)
6494 "Add the special tag faces."
6495 (when (and org-tag-faces org-tags-special-faces-re)
6496 (while (re-search-forward org-tags-special-faces-re limit t)
6497 (add-text-properties (match-beginning 1) (match-end 1)
6498 (list 'face (org-get-tag-face 1)
6499 'font-lock-fontified t))
6500 (backward-char 1))))
6502 (defun org-font-lock-add-priority-faces (limit)
6503 "Add the special priority faces."
6504 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6505 (when (save-match-data (org-at-heading-p))
6506 (add-text-properties
6507 (match-beginning 0) (match-end 0)
6508 (list 'face (or (org-face-from-face-or-color
6509 'priority 'org-priority
6510 (cdr (assoc (char-after (match-beginning 1))
6511 org-priority-faces)))
6512 'org-priority)
6513 'font-lock-fontified t)))))
6515 (defun org-get-tag-face (kwd)
6516 "Get the right face for a TODO keyword KWD.
6517 If KWD is a number, get the corresponding match group."
6518 (if (numberp kwd) (setq kwd (match-string kwd)))
6519 (or (org-face-from-face-or-color
6520 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6521 'org-tag))
6523 (defun org-unfontify-region (beg end &optional maybe_loudly)
6524 "Remove fontification and activation overlays from links."
6525 (font-lock-default-unfontify-region beg end)
6526 (let* ((buffer-undo-list t)
6527 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6528 (inhibit-modification-hooks t)
6529 deactivate-mark buffer-file-name buffer-file-truename)
6530 (org-decompose-region beg end)
6531 (remove-text-properties beg end
6532 '(mouse-face t keymap t org-linked-text t
6533 invisible t intangible t
6534 org-emphasis t))
6535 (org-remove-font-lock-display-properties beg end)))
6537 (defconst org-script-display '(((raise -0.3) (height 0.7))
6538 ((raise 0.3) (height 0.7))
6539 ((raise -0.5))
6540 ((raise 0.5)))
6541 "Display properties for showing superscripts and subscripts.")
6543 (defun org-remove-font-lock-display-properties (beg end)
6544 "Remove specific display properties that have been added by font lock.
6545 The will remove the raise properties that are used to show superscripts
6546 and subscripts."
6547 (let (next prop)
6548 (while (< beg end)
6549 (setq next (next-single-property-change beg 'display nil end)
6550 prop (get-text-property beg 'display))
6551 (if (member prop org-script-display)
6552 (put-text-property beg next 'display nil))
6553 (setq beg next))))
6555 (defun org-raise-scripts (limit)
6556 "Add raise properties to sub/superscripts."
6557 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6558 (if (re-search-forward
6559 (if (eq org-use-sub-superscripts t)
6560 org-match-substring-regexp
6561 org-match-substring-with-braces-regexp)
6562 limit t)
6563 (let* ((pos (point)) table-p comment-p
6564 (mpos (match-beginning 3))
6565 (emph-p (get-text-property mpos 'org-emphasis))
6566 (link-p (get-text-property mpos 'mouse-face))
6567 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6568 (goto-char (point-at-bol))
6569 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6570 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6571 (goto-char pos)
6572 ;; Handle a_b^c
6573 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6574 (if (or comment-p emph-p link-p keyw-p)
6576 (put-text-property (match-beginning 3) (match-end 0)
6577 'display
6578 (if (equal (char-after (match-beginning 2)) ?^)
6579 (nth (if table-p 3 1) org-script-display)
6580 (nth (if table-p 2 0) org-script-display)))
6581 (add-text-properties (match-beginning 2) (match-end 2)
6582 (list 'invisible t
6583 'org-dwidth t 'org-dwidth-n 1))
6584 (if (and (eq (char-after (match-beginning 3)) ?{)
6585 (eq (char-before (match-end 3)) ?}))
6586 (progn
6587 (add-text-properties
6588 (match-beginning 3) (1+ (match-beginning 3))
6589 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6590 (add-text-properties
6591 (1- (match-end 3)) (match-end 3)
6592 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6593 t)))))
6595 ;;;; Visibility cycling, including org-goto and indirect buffer
6597 ;;; Cycling
6599 (defvar org-cycle-global-status nil)
6600 (make-variable-buffer-local 'org-cycle-global-status)
6601 (put 'org-cycle-global-status 'org-state t)
6602 (defvar org-cycle-subtree-status nil)
6603 (make-variable-buffer-local 'org-cycle-subtree-status)
6604 (put 'org-cycle-subtree-status 'org-state t)
6606 (defvar org-inlinetask-min-level)
6608 (defun org-unlogged-message (&rest args)
6609 "Display a message, but avoid logging it in the *Messages* buffer."
6610 (let ((message-log-max nil))
6611 (apply 'message args)))
6613 ;;;###autoload
6614 (defun org-cycle (&optional arg)
6615 "TAB-action and visibility cycling for Org-mode.
6617 This is the command invoked in Org-mode by the TAB key. Its main purpose
6618 is outline visibility cycling, but it also invokes other actions
6619 in special contexts.
6621 - When this function is called with a prefix argument, rotate the entire
6622 buffer through 3 states (global cycling)
6623 1. OVERVIEW: Show only top-level headlines.
6624 2. CONTENTS: Show all headlines of all levels, but no body text.
6625 3. SHOW ALL: Show everything.
6626 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6627 determined by the variable `org-startup-folded', and by any VISIBILITY
6628 properties in the buffer.
6629 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6630 including any drawers.
6632 - When inside a table, re-align the table and move to the next field.
6634 - When point is at the beginning of a headline, rotate the subtree started
6635 by this line through 3 different states (local cycling)
6636 1. FOLDED: Only the main headline is shown.
6637 2. CHILDREN: The main headline and the direct children are shown.
6638 From this state, you can move to one of the children
6639 and zoom in further.
6640 3. SUBTREE: Show the entire subtree, including body text.
6641 If there is no subtree, switch directly from CHILDREN to FOLDED.
6643 - When point is at the beginning of an empty headline and the variable
6644 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6645 of the headline by demoting and promoting it to likely levels. This
6646 speeds up creation document structure by pressing TAB once or several
6647 times right after creating a new headline.
6649 - When there is a numeric prefix, go up to a heading with level ARG, do
6650 a `show-subtree' and return to the previous cursor position. If ARG
6651 is negative, go up that many levels.
6653 - When point is not at the beginning of a headline, execute the global
6654 binding for TAB, which is re-indenting the line. See the option
6655 `org-cycle-emulate-tab' for details.
6657 - Special case: if point is at the beginning of the buffer and there is
6658 no headline in line 1, this function will act as if called with prefix arg
6659 (C-u TAB, same as S-TAB) also when called without prefix arg.
6660 But only if also the variable `org-cycle-global-at-bob' is t."
6661 (interactive "P")
6662 (org-load-modules-maybe)
6663 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6664 (and org-cycle-level-after-item/entry-creation
6665 (or (org-cycle-level)
6666 (org-cycle-item-indentation))))
6667 (let* ((limit-level
6668 (or org-cycle-max-level
6669 (and (boundp 'org-inlinetask-min-level)
6670 org-inlinetask-min-level
6671 (1- org-inlinetask-min-level))))
6672 (nstars (and limit-level
6673 (if org-odd-levels-only
6674 (and limit-level (1- (* limit-level 2)))
6675 limit-level)))
6676 (org-outline-regexp
6677 (if (not (derived-mode-p 'org-mode))
6678 outline-regexp
6679 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6680 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6681 (not (looking-at org-outline-regexp))))
6682 (org-cycle-hook
6683 (if bob-special
6684 (delq 'org-optimize-window-after-visibility-change
6685 (copy-sequence org-cycle-hook))
6686 org-cycle-hook))
6687 (pos (point)))
6689 (if (or bob-special (equal arg '(4)))
6690 ;; special case: use global cycling
6691 (setq arg t))
6693 (cond
6695 ((equal arg '(16))
6696 (setq last-command 'dummy)
6697 (org-set-startup-visibility)
6698 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6700 ((equal arg '(64))
6701 (show-all)
6702 (org-unlogged-message "Entire buffer visible, including drawers"))
6704 ;; Try cdlatex TAB completion
6705 ((org-try-cdlatex-tab))
6707 ;; Table: enter it or move to the next field.
6708 ((org-at-table-p 'any)
6709 (if (org-at-table.el-p)
6710 (message "Use C-c ' to edit table.el tables")
6711 (if arg (org-table-edit-field t)
6712 (org-table-justify-field-maybe)
6713 (call-interactively 'org-table-next-field))))
6715 ((run-hook-with-args-until-success
6716 'org-tab-after-check-for-table-hook))
6718 ;; Global cycling: delegate to `org-cycle-internal-global'.
6719 ((eq arg t) (org-cycle-internal-global))
6721 ;; Drawers: delegate to `org-flag-drawer'.
6722 ((save-excursion
6723 (beginning-of-line 1)
6724 (looking-at org-drawer-regexp))
6725 (org-flag-drawer ; toggle block visibility
6726 (not (get-char-property (match-end 0) 'invisible))))
6728 ;; Show-subtree, ARG levels up from here.
6729 ((integerp arg)
6730 (save-excursion
6731 (org-back-to-heading)
6732 (outline-up-heading (if (< arg 0) (- arg)
6733 (- (funcall outline-level) arg)))
6734 (org-show-subtree)))
6736 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6737 ((and (featurep 'org-inlinetask)
6738 (org-inlinetask-at-task-p)
6739 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6740 (org-inlinetask-toggle-visibility))
6742 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6743 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6744 (save-excursion (beginning-of-line 1)
6745 (looking-at org-outline-regexp)))
6746 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6747 (org-cycle-internal-local))
6749 ;; From there: TAB emulation and template completion.
6750 (buffer-read-only (org-back-to-heading))
6752 ((run-hook-with-args-until-success
6753 'org-tab-after-check-for-cycling-hook))
6755 ((org-try-structure-completion))
6757 ((run-hook-with-args-until-success
6758 'org-tab-before-tab-emulation-hook))
6760 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6761 (or (not (bolp))
6762 (not (looking-at org-outline-regexp))))
6763 (call-interactively (global-key-binding "\t")))
6765 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6766 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6767 (or (and (eq org-cycle-emulate-tab 'white)
6768 (= (match-end 0) (point-at-eol)))
6769 (and (eq org-cycle-emulate-tab 'whitestart)
6770 (>= (match-end 0) pos))))
6772 (eq org-cycle-emulate-tab t))
6773 (call-interactively (global-key-binding "\t")))
6775 (t (save-excursion
6776 (org-back-to-heading)
6777 (org-cycle)))))))
6779 (defun org-cycle-internal-global ()
6780 "Do the global cycling action."
6781 ;; Hack to avoid display of messages for .org attachments in Gnus
6782 (let ((ga (string-match "\\*fontification" (buffer-name))))
6783 (cond
6784 ((and (eq last-command this-command)
6785 (eq org-cycle-global-status 'overview))
6786 ;; We just created the overview - now do table of contents
6787 ;; This can be slow in very large buffers, so indicate action
6788 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6789 (unless ga (org-unlogged-message "CONTENTS..."))
6790 (org-content)
6791 (unless ga (org-unlogged-message "CONTENTS...done"))
6792 (setq org-cycle-global-status 'contents)
6793 (run-hook-with-args 'org-cycle-hook 'contents))
6795 ((and (eq last-command this-command)
6796 (eq org-cycle-global-status 'contents))
6797 ;; We just showed the table of contents - now show everything
6798 (run-hook-with-args 'org-pre-cycle-hook 'all)
6799 (show-all)
6800 (unless ga (org-unlogged-message "SHOW ALL"))
6801 (setq org-cycle-global-status 'all)
6802 (run-hook-with-args 'org-cycle-hook 'all))
6805 ;; Default action: go to overview
6806 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6807 (org-overview)
6808 (unless ga (org-unlogged-message "OVERVIEW"))
6809 (setq org-cycle-global-status 'overview)
6810 (run-hook-with-args 'org-cycle-hook 'overview)))))
6812 (defvar org-called-with-limited-levels nil
6813 "Non-nil when `org-with-limited-levels' is currently active.")
6815 (defun org-cycle-internal-local ()
6816 "Do the local cycling action."
6817 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6818 ;; First, determine end of headline (EOH), end of subtree or item
6819 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6820 (save-excursion
6821 (if (org-at-item-p)
6822 (progn
6823 (beginning-of-line)
6824 (setq struct (org-list-struct))
6825 (setq eoh (point-at-eol))
6826 (setq eos (org-list-get-item-end-before-blank (point) struct))
6827 (setq has-children (org-list-has-child-p (point) struct)))
6828 (org-back-to-heading)
6829 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6830 (setq eos (save-excursion (org-end-of-subtree t t)
6831 (when (bolp) (backward-char)) (point)))
6832 (setq has-children
6833 (or (save-excursion
6834 (let ((level (funcall outline-level)))
6835 (outline-next-heading)
6836 (and (org-at-heading-p t)
6837 (> (funcall outline-level) level))))
6838 (save-excursion
6839 (org-list-search-forward (org-item-beginning-re) eos t)))))
6840 ;; Determine end invisible part of buffer (EOL)
6841 (beginning-of-line 2)
6842 ;; XEmacs doesn't have `next-single-char-property-change'
6843 (if (featurep 'xemacs)
6844 (while (and (not (eobp)) ;; this is like `next-line'
6845 (get-char-property (1- (point)) 'invisible))
6846 (beginning-of-line 2))
6847 (while (and (not (eobp)) ;; this is like `next-line'
6848 (get-char-property (1- (point)) 'invisible))
6849 (goto-char (next-single-char-property-change (point) 'invisible))
6850 (and (eolp) (beginning-of-line 2))))
6851 (setq eol (point)))
6852 ;; Find out what to do next and set `this-command'
6853 (cond
6854 ((= eos eoh)
6855 ;; Nothing is hidden behind this heading
6856 (unless (org-before-first-heading-p)
6857 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6858 (org-unlogged-message "EMPTY ENTRY")
6859 (setq org-cycle-subtree-status nil)
6860 (save-excursion
6861 (goto-char eos)
6862 (outline-next-heading)
6863 (if (outline-invisible-p) (org-flag-heading nil))))
6864 ((and (or (>= eol eos)
6865 (not (string-match "\\S-" (buffer-substring eol eos))))
6866 (or has-children
6867 (not (setq children-skipped
6868 org-cycle-skip-children-state-if-no-children))))
6869 ;; Entire subtree is hidden in one line: children view
6870 (unless (org-before-first-heading-p)
6871 (run-hook-with-args 'org-pre-cycle-hook 'children))
6872 (if (org-at-item-p)
6873 (org-list-set-item-visibility (point-at-bol) struct 'children)
6874 (org-show-entry)
6875 (org-with-limited-levels (show-children))
6876 ;; FIXME: This slows down the func way too much.
6877 ;; How keep drawers hidden in subtree anyway?
6878 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6879 ;; (org-cycle-hide-drawers 'subtree))
6881 ;; Fold every list in subtree to top-level items.
6882 (when (eq org-cycle-include-plain-lists 'integrate)
6883 (save-excursion
6884 (org-back-to-heading)
6885 (while (org-list-search-forward (org-item-beginning-re) eos t)
6886 (beginning-of-line 1)
6887 (let* ((struct (org-list-struct))
6888 (prevs (org-list-prevs-alist struct))
6889 (end (org-list-get-bottom-point struct)))
6890 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6891 (org-list-get-all-items (point) struct prevs))
6892 (goto-char (if (< end eos) end eos)))))))
6893 (org-unlogged-message "CHILDREN")
6894 (save-excursion
6895 (goto-char eos)
6896 (outline-next-heading)
6897 (if (outline-invisible-p) (org-flag-heading nil)))
6898 (setq org-cycle-subtree-status 'children)
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-cycle-hook 'children)))
6901 ((or children-skipped
6902 (and (eq last-command this-command)
6903 (eq org-cycle-subtree-status 'children)))
6904 ;; We just showed the children, or no children are there,
6905 ;; now show everything.
6906 (unless (org-before-first-heading-p)
6907 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6908 (outline-flag-region eoh eos nil)
6909 (org-unlogged-message
6910 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6911 (setq org-cycle-subtree-status 'subtree)
6912 (unless (org-before-first-heading-p)
6913 (run-hook-with-args 'org-cycle-hook 'subtree)))
6915 ;; Default action: hide the subtree.
6916 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6917 (outline-flag-region eoh eos t)
6918 (org-unlogged-message "FOLDED")
6919 (setq org-cycle-subtree-status 'folded)
6920 (unless (org-before-first-heading-p)
6921 (run-hook-with-args 'org-cycle-hook 'folded))))))
6923 ;;;###autoload
6924 (defun org-global-cycle (&optional arg)
6925 "Cycle the global visibility. For details see `org-cycle'.
6926 With \\[universal-argument] prefix arg, switch to startup visibility.
6927 With a numeric prefix, show all headlines up to that level."
6928 (interactive "P")
6929 (let ((org-cycle-include-plain-lists
6930 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6931 (cond
6932 ((integerp arg)
6933 (show-all)
6934 (hide-sublevels arg)
6935 (setq org-cycle-global-status 'contents))
6936 ((equal arg '(4))
6937 (org-set-startup-visibility)
6938 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6940 (org-cycle '(4))))))
6942 (defun org-set-startup-visibility ()
6943 "Set the visibility required by startup options and properties."
6944 (cond
6945 ((eq org-startup-folded t)
6946 (org-overview))
6947 ((eq org-startup-folded 'content)
6948 (org-content))
6949 ((or (eq org-startup-folded 'showeverything)
6950 (eq org-startup-folded nil))
6951 (show-all)))
6952 (unless (eq org-startup-folded 'showeverything)
6953 (if org-hide-block-startup (org-hide-block-all))
6954 (org-set-visibility-according-to-property 'no-cleanup)
6955 (org-cycle-hide-archived-subtrees 'all)
6956 (org-cycle-hide-drawers 'all)
6957 (org-cycle-show-empty-lines t)))
6959 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6960 "Switch subtree visibilities according to :VISIBILITY: property."
6961 (interactive)
6962 (let (org-show-entry-below state)
6963 (save-excursion
6964 (goto-char (point-min))
6965 (while (re-search-forward
6966 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6967 nil t)
6968 (setq state (match-string 1))
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (hide-subtree)
6972 (org-reveal)
6973 (cond
6974 ((equal state '("fold" "folded"))
6975 (hide-subtree))
6976 ((equal state "children")
6977 (org-show-hidden-entry)
6978 (show-children))
6979 ((equal state "content")
6980 (save-excursion
6981 (save-restriction
6982 (org-narrow-to-subtree)
6983 (org-content))))
6984 ((member state '("all" "showall"))
6985 (show-subtree)))))
6986 (unless no-cleanup
6987 (org-cycle-hide-archived-subtrees 'all)
6988 (org-cycle-hide-drawers 'all)
6989 (org-cycle-show-empty-lines 'all)))))
6991 ;; This function uses outline-regexp instead of the more fundamental
6992 ;; org-outline-regexp so that org-cycle-global works outside of Org
6993 ;; buffers, where outline-regexp is needed.
6994 (defun org-overview ()
6995 "Switch to overview mode, showing only top-level headlines.
6996 This shows all headlines with a level equal or greater than the level
6997 of the first headline in the buffer. This is important, because if the
6998 first headline is not level one, then (hide-sublevels 1) gives confusing
6999 results."
7000 (interactive)
7001 (save-excursion
7002 (let ((level
7003 (save-excursion
7004 (goto-char (point-min))
7005 (if (re-search-forward (concat "^" outline-regexp) nil t)
7006 (progn
7007 (goto-char (match-beginning 0))
7008 (funcall outline-level))))))
7009 (and level (hide-sublevels level)))))
7011 (defun org-content (&optional arg)
7012 "Show all headlines in the buffer, like a table of contents.
7013 With numerical argument N, show content up to level N."
7014 (interactive "P")
7015 (org-overview)
7016 (save-excursion
7017 ;; Visit all headings and show their offspring
7018 (and (integerp arg) (org-overview))
7019 (goto-char (point-max))
7020 (catch 'exit
7021 (while (and (progn (condition-case nil
7022 (outline-previous-visible-heading 1)
7023 (error (goto-char (point-min))))
7025 (looking-at org-outline-regexp))
7026 (if (integerp arg)
7027 (show-children (1- arg))
7028 (show-branches))
7029 (if (bobp) (throw 'exit nil))))))
7031 (defun org-optimize-window-after-visibility-change (state)
7032 "Adjust the window after a change in outline visibility.
7033 This function is the default value of the hook `org-cycle-hook'."
7034 (when (get-buffer-window (current-buffer))
7035 (cond
7036 ((eq state 'content) nil)
7037 ((eq state 'all) nil)
7038 ((eq state 'folded) nil)
7039 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7040 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7042 (defun org-remove-empty-overlays-at (pos)
7043 "Remove outline overlays that do not contain non-white stuff."
7044 (mapc
7045 (lambda (o)
7046 (and (eq 'outline (overlay-get o 'invisible))
7047 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7048 (overlay-end o))))
7049 (delete-overlay o)))
7050 (overlays-at pos)))
7052 (defun org-clean-visibility-after-subtree-move ()
7053 "Fix visibility issues after moving a subtree."
7054 ;; First, find a reasonable region to look at:
7055 ;; Start two siblings above, end three below
7056 (let* ((beg (save-excursion
7057 (and (org-get-last-sibling)
7058 (org-get-last-sibling))
7059 (point)))
7060 (end (save-excursion
7061 (and (org-get-next-sibling)
7062 (org-get-next-sibling)
7063 (org-get-next-sibling))
7064 (if (org-at-heading-p)
7065 (point-at-eol)
7066 (point))))
7067 (level (looking-at "\\*+"))
7068 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7069 (save-excursion
7070 (save-restriction
7071 (narrow-to-region beg end)
7072 (when re
7073 ;; Properly fold already folded siblings
7074 (goto-char (point-min))
7075 (while (re-search-forward re nil t)
7076 (if (and (not (outline-invisible-p))
7077 (save-excursion
7078 (goto-char (point-at-eol)) (outline-invisible-p)))
7079 (hide-entry))))
7080 (org-cycle-show-empty-lines 'overview)
7081 (org-cycle-hide-drawers 'overview)))))
7083 (defun org-cycle-show-empty-lines (state)
7084 "Show empty lines above all visible headlines.
7085 The region to be covered depends on STATE when called through
7086 `org-cycle-hook'. Lisp program can use t for STATE to get the
7087 entire buffer covered. Note that an empty line is only shown if there
7088 are at least `org-cycle-separator-lines' empty lines before the headline."
7089 (when (not (= org-cycle-separator-lines 0))
7090 (save-excursion
7091 (let* ((n (abs org-cycle-separator-lines))
7092 (re (cond
7093 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7094 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7095 (t (let ((ns (number-to-string (- n 2))))
7096 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7097 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7098 beg end b e)
7099 (cond
7100 ((memq state '(overview contents t))
7101 (setq beg (point-min) end (point-max)))
7102 ((memq state '(children folded))
7103 (setq beg (point) end (progn (org-end-of-subtree t t)
7104 (beginning-of-line 2)
7105 (point)))))
7106 (when beg
7107 (goto-char beg)
7108 (while (re-search-forward re end t)
7109 (unless (get-char-property (match-end 1) 'invisible)
7110 (setq e (match-end 1))
7111 (if (< org-cycle-separator-lines 0)
7112 (setq b (save-excursion
7113 (goto-char (match-beginning 0))
7114 (org-back-over-empty-lines)
7115 (if (save-excursion
7116 (goto-char (max (point-min) (1- (point))))
7117 (org-at-heading-p))
7118 (1- (point))
7119 (point))))
7120 (setq b (match-beginning 1)))
7121 (outline-flag-region b e nil)))))))
7122 ;; Never hide empty lines at the end of the file.
7123 (save-excursion
7124 (goto-char (point-max))
7125 (outline-previous-heading)
7126 (outline-end-of-heading)
7127 (if (and (looking-at "[ \t\n]+")
7128 (= (match-end 0) (point-max)))
7129 (outline-flag-region (point) (match-end 0) nil))))
7131 (defun org-show-empty-lines-in-parent ()
7132 "Move to the parent and re-show empty lines before visible headlines."
7133 (save-excursion
7134 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7135 (org-cycle-show-empty-lines context))))
7137 (defun org-files-list ()
7138 "Return `org-agenda-files' list, plus all open org-mode files.
7139 This is useful for operations that need to scan all of a user's
7140 open and agenda-wise Org files."
7141 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7142 (dolist (buf (buffer-list))
7143 (with-current-buffer buf
7144 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7145 (let ((file (expand-file-name (buffer-file-name))))
7146 (unless (member file files)
7147 (push file files))))))
7148 files))
7150 (defsubst org-entry-beginning-position ()
7151 "Return the beginning position of the current entry."
7152 (save-excursion (outline-back-to-heading t) (point)))
7154 (defsubst org-entry-end-position ()
7155 "Return the end position of the current entry."
7156 (save-excursion (outline-next-heading) (point)))
7158 (defun org-cycle-hide-drawers (state &optional exceptions)
7159 "Re-hide all drawers after a visibility state change.
7160 When non-nil, optional argument EXCEPTIONS is a list of strings
7161 specifying which drawers should not be hidden."
7162 (when (and (derived-mode-p 'org-mode)
7163 (not (memq state '(overview folded contents))))
7164 (save-excursion
7165 (let* ((globalp (memq state '(contents all)))
7166 (beg (if globalp (point-min) (point)))
7167 (end (if globalp (point-max)
7168 (if (eq state 'children)
7169 (save-excursion (outline-next-heading) (point))
7170 (org-end-of-subtree t)))))
7171 (goto-char beg)
7172 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7173 (unless (member-ignore-case (match-string 1) exceptions)
7174 (let ((drawer (org-element-at-point)))
7175 (when (memq (org-element-type drawer) '(drawer property-drawer))
7176 (org-flag-drawer t drawer)
7177 ;; Make sure to skip drawer entirely or we might flag
7178 ;; it another time when matching its ending line with
7179 ;; `org-drawer-regexp'.
7180 (goto-char (org-element-property :end drawer))))))))))
7182 (defun org-cycle-hide-inline-tasks (state)
7183 "Re-hide inline tasks when switching to 'contents or 'children
7184 visibility state."
7185 (case state
7186 (contents
7187 (when (org-bound-and-true-p org-inlinetask-min-level)
7188 (hide-sublevels (1- org-inlinetask-min-level))))
7189 (children
7190 (when (featurep 'org-inlinetask)
7191 (save-excursion
7192 (while (and (outline-next-heading)
7193 (org-inlinetask-at-task-p))
7194 (org-inlinetask-toggle-visibility)
7195 (org-inlinetask-goto-end)))))))
7197 (defun org-flag-drawer (flag &optional element)
7198 "When FLAG is non-nil, hide the drawer we are at.
7199 Otherwise make it visible. When optional argument ELEMENT is
7200 a parsed drawer, as returned by `org-element-at-point', hide or
7201 show that drawer instead."
7202 (when (save-excursion
7203 (beginning-of-line)
7204 (org-looking-at-p org-drawer-regexp))
7205 (let ((drawer (or element (org-element-at-point))))
7206 (when (memq (org-element-type drawer) '(drawer property-drawer))
7207 (let ((post (org-element-property :post-affiliated drawer)))
7208 (save-excursion
7209 (outline-flag-region
7210 (progn (goto-char post) (line-end-position))
7211 (progn (goto-char (org-element-property :end drawer))
7212 (skip-chars-backward " \r\t\n")
7213 (line-end-position))
7214 flag))
7215 ;; When the drawer is hidden away, make sure point lies in
7216 ;; a visible part of the buffer.
7217 (when (and flag (> (line-beginning-position) post))
7218 (goto-char post)))))))
7220 (defun org-subtree-end-visible-p ()
7221 "Is the end of the current subtree visible?"
7222 (pos-visible-in-window-p
7223 (save-excursion (org-end-of-subtree t) (point))))
7225 (defun org-first-headline-recenter ()
7226 "Move cursor to the first headline and recenter the headline."
7227 (goto-char (point-min))
7228 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7229 (set-window-start (selected-window) (point-at-bol))))
7231 ;;; Saving and restoring visibility
7233 (defun org-outline-overlay-data (&optional use-markers)
7234 "Return a list of the locations of all outline overlays.
7235 These are overlays with the `invisible' property value `outline'.
7236 The return value is a list of cons cells, with start and stop
7237 positions for each overlay.
7238 If USE-MARKERS is set, return the positions as markers."
7239 (let (beg end)
7240 (save-excursion
7241 (save-restriction
7242 (widen)
7243 (delq nil
7244 (mapcar (lambda (o)
7245 (when (eq (overlay-get o 'invisible) 'outline)
7246 (setq beg (overlay-start o)
7247 end (overlay-end o))
7248 (and beg end (> end beg)
7249 (if use-markers
7250 (cons (copy-marker beg)
7251 (copy-marker end t))
7252 (cons beg end)))))
7253 (overlays-in (point-min) (point-max))))))))
7255 (defun org-set-outline-overlay-data (data)
7256 "Create visibility overlays for all positions in DATA.
7257 DATA should have been made by `org-outline-overlay-data'."
7258 (let (o)
7259 (save-excursion
7260 (save-restriction
7261 (widen)
7262 (show-all)
7263 (mapc (lambda (c)
7264 (outline-flag-region (car c) (cdr c) t))
7265 data)))))
7267 ;;; Folding of blocks
7269 (defvar org-hide-block-overlays nil
7270 "Overlays hiding blocks.")
7271 (make-variable-buffer-local 'org-hide-block-overlays)
7273 (defun org-block-map (function &optional start end)
7274 "Call FUNCTION at the head of all source blocks in the current buffer.
7275 Optional arguments START and END can be used to limit the range."
7276 (let ((start (or start (point-min)))
7277 (end (or end (point-max))))
7278 (save-excursion
7279 (goto-char start)
7280 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7281 (save-excursion
7282 (save-match-data
7283 (goto-char (match-beginning 0))
7284 (funcall function)))))))
7286 (defun org-hide-block-toggle-all ()
7287 "Toggle the visibility of all blocks in the current buffer."
7288 (org-block-map 'org-hide-block-toggle))
7290 (defun org-hide-block-all ()
7291 "Fold all blocks in the current buffer."
7292 (interactive)
7293 (org-show-block-all)
7294 (org-block-map 'org-hide-block-toggle-maybe))
7296 (defun org-show-block-all ()
7297 "Unfold all blocks in the current buffer."
7298 (interactive)
7299 (mapc 'delete-overlay org-hide-block-overlays)
7300 (setq org-hide-block-overlays nil))
7302 (defun org-hide-block-toggle-maybe ()
7303 "Toggle visibility of block at point.
7304 Unlike to `org-hide-block-toggle', this function does not throw
7305 an error. Return a non-nil value when toggling is successful."
7306 (interactive)
7307 (ignore-errors (org-hide-block-toggle)))
7309 (defun org-hide-block-toggle (&optional force)
7310 "Toggle the visibility of the current block.
7311 When optional argument FORCE is `off', make block visible. If it
7312 is non-nil, hide it unconditionally. Throw an error when not at
7313 a block. Return a non-nil value when toggling is successful."
7314 (interactive)
7315 (let ((element (org-element-at-point)))
7316 (unless (memq (org-element-type element)
7317 '(center-block comment-block dynamic-block example-block
7318 export-block quote-block special-block
7319 src-block verse-block))
7320 (user-error "Not at a block"))
7321 (let* ((start (save-excursion
7322 (goto-char (org-element-property :post-affiliated element))
7323 (line-end-position)))
7324 (end (save-excursion
7325 (goto-char (org-element-property :end element))
7326 (skip-chars-backward " \r\t\n")
7327 (line-end-position)))
7328 (overlays (overlays-at start)))
7329 (cond
7330 ;; Do nothing when not before or at the block opening line or
7331 ;; at the block closing line.
7332 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7333 ((and (not (eq force 'off))
7334 (not (memq t (mapcar
7335 (lambda (o)
7336 (eq (overlay-get o 'invisible) 'org-hide-block))
7337 overlays))))
7338 (let ((ov (make-overlay start end)))
7339 (overlay-put ov 'invisible 'org-hide-block)
7340 ;; Make the block accessible to `isearch'.
7341 (overlay-put
7342 ov 'isearch-open-invisible
7343 (lambda (ov)
7344 (when (memq ov org-hide-block-overlays)
7345 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7346 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7347 (delete-overlay ov))))
7348 (push ov org-hide-block-overlays)
7349 ;; When the block is hidden away, make sure point is left in
7350 ;; a visible part of the buffer.
7351 (when (> (line-beginning-position) start)
7352 (goto-char start)
7353 (beginning-of-line))
7354 ;; Signal successful toggling.
7356 ((or (not force) (eq force 'off))
7357 (dolist (ov overlays t)
7358 (when (memq ov org-hide-block-overlays)
7359 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7360 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7361 (delete-overlay ov))))))))
7363 ;; org-tab-after-check-for-cycling-hook
7364 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7365 ;; Remove overlays when changing major mode
7366 (add-hook 'org-mode-hook
7367 (lambda () (org-add-hook 'change-major-mode-hook
7368 'org-show-block-all 'append 'local)))
7370 ;;; Org-goto
7372 (defvar org-goto-window-configuration nil)
7373 (defvar org-goto-marker nil)
7374 (defvar org-goto-map)
7375 (defun org-goto-map ()
7376 "Set the keymap `org-goto'."
7377 (setq org-goto-map
7378 (let ((map (make-sparse-keymap)))
7379 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7380 mouse-drag-region universal-argument org-occur))
7381 cmd)
7382 (while (setq cmd (pop cmds))
7383 (substitute-key-definition cmd cmd map global-map)))
7384 (suppress-keymap map)
7385 (org-defkey map "\C-m" 'org-goto-ret)
7386 (org-defkey map [(return)] 'org-goto-ret)
7387 (org-defkey map [(left)] 'org-goto-left)
7388 (org-defkey map [(right)] 'org-goto-right)
7389 (org-defkey map [(control ?g)] 'org-goto-quit)
7390 (org-defkey map "\C-i" 'org-cycle)
7391 (org-defkey map [(tab)] 'org-cycle)
7392 (org-defkey map [(down)] 'outline-next-visible-heading)
7393 (org-defkey map [(up)] 'outline-previous-visible-heading)
7394 (if org-goto-auto-isearch
7395 (if (fboundp 'define-key-after)
7396 (define-key-after map [t] 'org-goto-local-auto-isearch)
7397 nil)
7398 (org-defkey map "q" 'org-goto-quit)
7399 (org-defkey map "n" 'outline-next-visible-heading)
7400 (org-defkey map "p" 'outline-previous-visible-heading)
7401 (org-defkey map "f" 'outline-forward-same-level)
7402 (org-defkey map "b" 'outline-backward-same-level)
7403 (org-defkey map "u" 'outline-up-heading))
7404 (org-defkey map "/" 'org-occur)
7405 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7406 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7407 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7408 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7409 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7410 map)))
7412 (defconst org-goto-help
7413 "Browse buffer copy, to find location or copy text.%s
7414 RET=jump to location C-g=quit and return to previous location
7415 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7417 (defvar org-goto-start-pos) ; dynamically scoped parameter
7419 (defun org-goto (&optional alternative-interface)
7420 "Look up a different location in the current file, keeping current visibility.
7422 When you want look-up or go to a different location in a
7423 document, the fastest way is often to fold the entire buffer and
7424 then dive into the tree. This method has the disadvantage, that
7425 the previous location will be folded, which may not be what you
7426 want.
7428 This command works around this by showing a copy of the current
7429 buffer in an indirect buffer, in overview mode. You can dive
7430 into the tree in that copy, use org-occur and incremental search
7431 to find a location. When pressing RET or `Q', the command
7432 returns to the original buffer in which the visibility is still
7433 unchanged. After RET it will also jump to the location selected
7434 in the indirect buffer and expose the headline hierarchy above.
7436 With a prefix argument, use the alternative interface: e.g. if
7437 `org-goto-interface' is 'outline use 'outline-path-completion."
7438 (interactive "P")
7439 (org-goto-map)
7440 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7441 (org-refile-use-outline-path t)
7442 (org-refile-target-verify-function nil)
7443 (interface
7444 (if (not alternative-interface)
7445 org-goto-interface
7446 (if (eq org-goto-interface 'outline)
7447 'outline-path-completion
7448 'outline)))
7449 (org-goto-start-pos (point))
7450 (selected-point
7451 (if (eq interface 'outline)
7452 (car (org-get-location (current-buffer) org-goto-help))
7453 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7454 (org-refile-check-position pa)
7455 (nth 3 pa)))))
7456 (if selected-point
7457 (progn
7458 (org-mark-ring-push org-goto-start-pos)
7459 (goto-char selected-point)
7460 (if (or (outline-invisible-p) (org-invisible-p2))
7461 (org-show-context 'org-goto)))
7462 (message "Quit"))))
7464 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7465 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7466 (defvar org-goto-local-auto-isearch-map) ; defined below
7468 (defun org-get-location (buf help)
7469 "Let the user select a location in the Org-mode buffer BUF.
7470 This function uses a recursive edit. It returns the selected position
7471 or nil."
7472 (org-no-popups
7473 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7474 (isearch-hide-immediately nil)
7475 (isearch-search-fun-function
7476 (lambda () 'org-goto-local-search-headings))
7477 (org-goto-selected-point org-goto-exit-command))
7478 (save-excursion
7479 (save-window-excursion
7480 (delete-other-windows)
7481 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7482 (org-pop-to-buffer-same-window
7483 (condition-case nil
7484 (make-indirect-buffer (current-buffer) "*org-goto*")
7485 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7486 (with-output-to-temp-buffer "*Org Help*"
7487 (princ (format help (if org-goto-auto-isearch
7488 " Just type for auto-isearch."
7489 " n/p/f/b/u to navigate, q to quit."))))
7490 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7491 (setq buffer-read-only nil)
7492 (let ((org-startup-truncated t)
7493 (org-startup-folded nil)
7494 (org-startup-align-all-tables nil))
7495 (org-mode)
7496 (org-overview))
7497 (setq buffer-read-only t)
7498 (if (and (boundp 'org-goto-start-pos)
7499 (integer-or-marker-p org-goto-start-pos))
7500 (let ((org-show-hierarchy-above t)
7501 (org-show-siblings t)
7502 (org-show-following-heading t))
7503 (goto-char org-goto-start-pos)
7504 (and (outline-invisible-p) (org-show-context)))
7505 (goto-char (point-min)))
7506 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7507 (message "Select location and press RET")
7508 (use-local-map org-goto-map)
7509 (recursive-edit)))
7510 (kill-buffer "*org-goto*")
7511 (cons org-goto-selected-point org-goto-exit-command))))
7513 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7514 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7515 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7516 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7518 (defun org-goto-local-search-headings (string bound noerror)
7519 "Search and make sure that any matches are in headlines."
7520 (catch 'return
7521 (while (if isearch-forward
7522 (search-forward string bound noerror)
7523 (search-backward string bound noerror))
7524 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7525 (and (member :headline context)
7526 (not (member :tags context))))
7527 (throw 'return (point))))))
7529 (defun org-goto-local-auto-isearch ()
7530 "Start isearch."
7531 (interactive)
7532 (goto-char (point-min))
7533 (let ((keys (this-command-keys)))
7534 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7535 (isearch-mode t)
7536 (isearch-process-search-char (string-to-char keys)))))
7538 (defun org-goto-ret (&optional arg)
7539 "Finish `org-goto' by going to the new location."
7540 (interactive "P")
7541 (setq org-goto-selected-point (point)
7542 org-goto-exit-command 'return)
7543 (throw 'exit nil))
7545 (defun org-goto-left ()
7546 "Finish `org-goto' by going to the new location."
7547 (interactive)
7548 (if (org-at-heading-p)
7549 (progn
7550 (beginning-of-line 1)
7551 (setq org-goto-selected-point (point)
7552 org-goto-exit-command 'left)
7553 (throw 'exit nil))
7554 (user-error "Not on a heading")))
7556 (defun org-goto-right ()
7557 "Finish `org-goto' by going to the new location."
7558 (interactive)
7559 (if (org-at-heading-p)
7560 (progn
7561 (setq org-goto-selected-point (point)
7562 org-goto-exit-command 'right)
7563 (throw 'exit nil))
7564 (user-error "Not on a heading")))
7566 (defun org-goto-quit ()
7567 "Finish `org-goto' without cursor motion."
7568 (interactive)
7569 (setq org-goto-selected-point nil)
7570 (setq org-goto-exit-command 'quit)
7571 (throw 'exit nil))
7573 ;;; Indirect buffer display of subtrees
7575 (defvar org-indirect-dedicated-frame nil
7576 "This is the frame being used for indirect tree display.")
7577 (defvar org-last-indirect-buffer nil)
7579 (defun org-tree-to-indirect-buffer (&optional arg)
7580 "Create indirect buffer and narrow it to current subtree.
7581 With a numerical prefix ARG, go up to this level and then take that tree.
7582 If ARG is negative, go up that many levels.
7584 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7585 indirect buffer previously made with this command, to avoid proliferation of
7586 indirect buffers. However, when you call the command with a \
7587 \\[universal-argument] prefix, or
7588 when `org-indirect-buffer-display' is `new-frame', the last buffer
7589 is kept so that you can work with several indirect buffers at the same time.
7590 If `org-indirect-buffer-display' is `dedicated-frame', the \
7591 \\[universal-argument] prefix also
7592 requests that a new frame be made for the new buffer, so that the dedicated
7593 frame is not changed."
7594 (interactive "P")
7595 (let ((cbuf (current-buffer))
7596 (cwin (selected-window))
7597 (pos (point))
7598 beg end level heading ibuf)
7599 (save-excursion
7600 (org-back-to-heading t)
7601 (when (numberp arg)
7602 (setq level (org-outline-level))
7603 (if (< arg 0) (setq arg (+ level arg)))
7604 (while (> (setq level (org-outline-level)) arg)
7605 (org-up-heading-safe)))
7606 (setq beg (point)
7607 heading (org-get-heading))
7608 (org-end-of-subtree t t)
7609 (if (org-at-heading-p) (backward-char 1))
7610 (setq end (point)))
7611 (if (and (buffer-live-p org-last-indirect-buffer)
7612 (not (eq org-indirect-buffer-display 'new-frame))
7613 (not arg))
7614 (kill-buffer org-last-indirect-buffer))
7615 (setq ibuf (org-get-indirect-buffer cbuf heading)
7616 org-last-indirect-buffer ibuf)
7617 (cond
7618 ((or (eq org-indirect-buffer-display 'new-frame)
7619 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7620 (select-frame (make-frame))
7621 (delete-other-windows)
7622 (org-pop-to-buffer-same-window ibuf)
7623 (org-set-frame-title heading))
7624 ((eq org-indirect-buffer-display 'dedicated-frame)
7625 (raise-frame
7626 (select-frame (or (and org-indirect-dedicated-frame
7627 (frame-live-p org-indirect-dedicated-frame)
7628 org-indirect-dedicated-frame)
7629 (setq org-indirect-dedicated-frame (make-frame)))))
7630 (delete-other-windows)
7631 (org-pop-to-buffer-same-window ibuf)
7632 (org-set-frame-title (concat "Indirect: " heading)))
7633 ((eq org-indirect-buffer-display 'current-window)
7634 (org-pop-to-buffer-same-window ibuf))
7635 ((eq org-indirect-buffer-display 'other-window)
7636 (pop-to-buffer ibuf))
7637 (t (error "Invalid value")))
7638 (if (featurep 'xemacs)
7639 (save-excursion (org-mode) (turn-on-font-lock)))
7640 (narrow-to-region beg end)
7641 (show-all)
7642 (goto-char pos)
7643 (run-hook-with-args 'org-cycle-hook 'all)
7644 (and (window-live-p cwin) (select-window cwin))))
7646 (defun org-get-indirect-buffer (&optional buffer heading)
7647 (setq buffer (or buffer (current-buffer)))
7648 (let ((n 1) (base (buffer-name buffer)) bname)
7649 (while (buffer-live-p
7650 (get-buffer
7651 (setq bname
7652 (concat base "-"
7653 (if heading (concat heading "-" (number-to-string n))
7654 (number-to-string n))))))
7655 (setq n (1+ n)))
7656 (condition-case nil
7657 (make-indirect-buffer buffer bname 'clone)
7658 (error (make-indirect-buffer buffer bname)))))
7660 (defun org-set-frame-title (title)
7661 "Set the title of the current frame to the string TITLE."
7662 ;; FIXME: how to name a single frame in XEmacs???
7663 (unless (featurep 'xemacs)
7664 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7666 ;;;; Structure editing
7668 ;;; Inserting headlines
7670 (defun org-previous-line-empty-p (&optional next)
7671 "Is the previous line a blank line?
7672 When NEXT is non-nil, check the next line instead."
7673 (save-excursion
7674 (and (not (bobp))
7675 (or (beginning-of-line (if next 2 0)) t)
7676 (save-match-data
7677 (looking-at "[ \t]*$")))))
7679 (defun org-insert-heading (&optional arg invisible-ok)
7680 "Insert a new heading or an item with the same depth at point.
7682 If point is at the beginning of a heading or a list item, insert
7683 a new heading or a new item above the current one. If point is
7684 at the beginning of a normal line, turn the line into a heading.
7686 If point is in the middle of a headline or a list item, split the
7687 headline or the item and create a new headline/item with the text
7688 in the current line after point \(see `org-M-RET-may-split-line'
7689 on how to modify this behavior).
7691 With one universal prefix argument, set the user option
7692 `org-insert-heading-respect-content' to t for the duration of
7693 the command. This modifies the behavior described above in this
7694 ways: on list items and at the beginning of normal lines, force
7695 the insertion of a heading after the current subtree.
7697 With two universal prefix arguments, insert the heading at the
7698 end of the grandparent subtree. For example, if point is within
7699 a 2nd-level heading, then it will insert a 2nd-level heading at
7700 the end of the 1st-level parent heading.
7702 If point is at the beginning of a headline, insert a sibling
7703 before the current headline. If point is not at the beginning,
7704 split the line and create a new headline with the text in the
7705 current line after point \(see `org-M-RET-may-split-line' on how
7706 to modify this behavior).
7708 If point is at the beginning of a normal line, turn this line
7709 into a heading.
7711 When INVISIBLE-OK is set, stop at invisible headlines when going
7712 back. This is important for non-interactive uses of the
7713 command."
7714 (interactive "P")
7715 (if (org-called-interactively-p 'any) (org-reveal))
7716 (let ((itemp (org-in-item-p))
7717 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7718 (respect-content (or org-insert-heading-respect-content
7719 (equal arg '(4))))
7720 (initial-content "")
7721 (adjust-empty-lines t))
7723 (cond
7725 ((or (= (buffer-size) 0)
7726 (and (not (save-excursion
7727 (and (ignore-errors (org-back-to-heading invisible-ok))
7728 (org-at-heading-p))))
7729 (or arg (not itemp))))
7730 ;; At beginning of buffer or so high up that only a heading
7731 ;; makes sense.
7732 (cond ((and (bolp) (not respect-content)) (insert "* "))
7733 ((not respect-content)
7734 (unless may-split (end-of-line))
7735 (insert "\n* "))
7736 ((re-search-forward org-outline-regexp-bol nil t)
7737 (beginning-of-line)
7738 (insert "* \n")
7739 (backward-char))
7740 (t (goto-char (point-max))
7741 (insert "\n* ")))
7742 (run-hooks 'org-insert-heading-hook))
7744 ((and itemp (not (member arg '((4) (16)))))
7745 ;; Insert an item
7746 (org-insert-item))
7749 ;; Maybe move at the end of the subtree
7750 (when (equal arg '(16))
7751 (org-up-heading-safe)
7752 (org-end-of-subtree t))
7753 ;; Insert a heading
7754 (save-restriction
7755 (widen)
7756 (let* ((level nil)
7757 (on-heading (org-at-heading-p))
7758 (empty-line-p (if on-heading
7759 (org-previous-line-empty-p)
7760 ;; We will decide later
7761 nil))
7762 ;; Get a level string to fall back on
7763 (fix-level
7764 (if (org-before-first-heading-p) "*"
7765 (save-excursion
7766 (org-back-to-heading t)
7767 (if (org-previous-line-empty-p) (setq empty-line-p t))
7768 (looking-at org-outline-regexp)
7769 (make-string (1- (length (match-string 0))) ?*))))
7770 (stars
7771 (save-excursion
7772 (condition-case nil
7773 (progn
7774 (org-back-to-heading invisible-ok)
7775 (when (and (not on-heading)
7776 (featurep 'org-inlinetask)
7777 (integerp org-inlinetask-min-level)
7778 (>= (length (match-string 0))
7779 org-inlinetask-min-level))
7780 ;; Find a heading level before the inline task
7781 (while (and (setq level (org-up-heading-safe))
7782 (>= level org-inlinetask-min-level)))
7783 (if (org-at-heading-p)
7784 (org-back-to-heading invisible-ok)
7785 (error "This should not happen")))
7786 (unless (and (save-excursion
7787 (save-match-data
7788 (org-backward-heading-same-level
7789 1 invisible-ok))
7790 (= (point) (match-beginning 0)))
7791 (not (org-previous-line-empty-p t)))
7792 (setq empty-line-p (or empty-line-p
7793 (org-previous-line-empty-p))))
7794 (match-string 0))
7795 (error (or fix-level "* ")))))
7796 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7797 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7798 pos hide-previous previous-pos)
7800 ;; If we insert after content, move there and clean up whitespace
7801 (when (and respect-content
7802 (not (org-looking-at-p org-outline-regexp-bol)))
7803 (if (not (org-before-first-heading-p))
7804 (org-end-of-subtree nil t)
7805 (re-search-forward org-outline-regexp-bol)
7806 (beginning-of-line 0))
7807 (skip-chars-backward " \r\n")
7808 (and (not (looking-back "^\\*+"))
7809 (looking-at "[ \t]+") (replace-match ""))
7810 (unless (eobp) (forward-char 1))
7811 (when (looking-at "^\\*")
7812 (unless (bobp) (backward-char 1))
7813 (insert "\n")))
7815 ;; If we are splitting, grab the text that should be moved to the new headline
7816 (when may-split
7817 (if (org-on-heading-p)
7818 ;; This is a heading, we split intelligently (keeping tags)
7819 (let ((pos (point)))
7820 (goto-char (point-at-bol))
7821 (unless (looking-at org-complex-heading-regexp)
7822 (error "This should not happen"))
7823 (when (and (match-beginning 4)
7824 (> pos (match-beginning 4))
7825 (< pos (match-end 4)))
7826 (setq initial-content (buffer-substring pos (match-end 4)))
7827 (goto-char pos)
7828 (delete-region (point) (match-end 4))
7829 (if (looking-at "[ \t]*$")
7830 (replace-match "")
7831 (insert (make-string (length initial-content) ?\ )))
7832 (setq initial-content (org-trim initial-content)))
7833 (goto-char pos))
7834 ;; a normal line
7835 (setq initial-content
7836 (org-trim (buffer-substring (point) (point-at-eol))))
7837 (delete-region (point) (point-at-eol))))
7839 ;; If we are at the beginning of the line, insert before it. Else after
7840 (cond
7841 ((and (bolp) (looking-at "[ \t]*$")))
7842 ((and (bolp) (not (looking-at "[ \t]*$")))
7843 (open-line 1))
7845 (goto-char (point-at-eol))
7846 (insert "\n")))
7848 ;; Insert the new heading
7849 (insert stars)
7850 (just-one-space)
7851 (insert initial-content)
7852 (when adjust-empty-lines
7853 (if (or (not blank)
7854 (and blank (not (org-previous-line-empty-p))))
7855 (org-N-empty-lines-before-current (if blank 1 0))))
7856 (run-hooks 'org-insert-heading-hook)))))))
7858 (defun org-N-empty-lines-before-current (N)
7859 "Make the number of empty lines before current exactly N.
7860 So this will delete or add empty lines."
7861 (save-excursion
7862 (beginning-of-line)
7863 (let ((p (point)))
7864 (skip-chars-backward " \r\t\n")
7865 (unless (bolp) (forward-line))
7866 (delete-region (point) p))
7867 (when (> N 0) (insert (make-string N ?\n)))))
7869 (defun org-get-heading (&optional no-tags no-todo)
7870 "Return the heading of the current entry, without the stars.
7871 When NO-TAGS is non-nil, don't include tags.
7872 When NO-TODO is non-nil, don't include TODO keywords."
7873 (save-excursion
7874 (org-back-to-heading t)
7875 (cond
7876 ((and no-tags no-todo)
7877 (looking-at org-complex-heading-regexp)
7878 (match-string 4))
7879 (no-tags
7880 (looking-at (concat org-outline-regexp
7881 "\\(.*?\\)"
7882 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7883 (match-string 1))
7884 (no-todo
7885 (looking-at org-todo-line-regexp)
7886 (match-string 3))
7887 (t (looking-at org-heading-regexp)
7888 (match-string 2)))))
7890 (defvar orgstruct-mode) ; defined below
7892 (defun org-heading-components ()
7893 "Return the components of the current heading.
7894 This is a list with the following elements:
7895 - the level as an integer
7896 - the reduced level, different if `org-odd-levels-only' is set.
7897 - the TODO keyword, or nil
7898 - the priority character, like ?A, or nil if no priority is given
7899 - the headline text itself, or the tags string if no headline text
7900 - the tags string, or nil."
7901 (save-excursion
7902 (org-back-to-heading t)
7903 (if (let (case-fold-search)
7904 (looking-at
7905 (if orgstruct-mode
7906 org-heading-regexp
7907 org-complex-heading-regexp)))
7908 (if orgstruct-mode
7909 (list (length (match-string 1))
7910 (org-reduced-level (length (match-string 1)))
7913 (match-string 2)
7914 nil)
7915 (list (length (match-string 1))
7916 (org-reduced-level (length (match-string 1)))
7917 (org-match-string-no-properties 2)
7918 (and (match-end 3) (aref (match-string 3) 2))
7919 (org-match-string-no-properties 4)
7920 (org-match-string-no-properties 5))))))
7922 (defun org-get-entry ()
7923 "Get the entry text, after heading, entire subtree."
7924 (save-excursion
7925 (org-back-to-heading t)
7926 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7928 (defun org-insert-heading-after-current ()
7929 "Insert a new heading with same level as current, after current subtree."
7930 (interactive)
7931 (org-back-to-heading)
7932 (org-insert-heading)
7933 (org-move-subtree-down)
7934 (end-of-line 1))
7936 (defun org-insert-heading-respect-content (&optional invisible-ok)
7937 "Insert heading with `org-insert-heading-respect-content' set to t."
7938 (interactive)
7939 (org-insert-heading '(4) invisible-ok))
7941 (defun org-insert-todo-heading-respect-content (&optional force-state)
7942 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7943 (interactive)
7944 (org-insert-todo-heading force-state '(4)))
7946 (defun org-insert-todo-heading (arg &optional force-heading)
7947 "Insert a new heading with the same level and TODO state as current heading.
7948 If the heading has no TODO state, or if the state is DONE, use the first
7949 state (TODO by default). Also with one prefix arg, force first state. With
7950 two prefix args, force inserting at the end of the parent subtree."
7951 (interactive "P")
7952 (when (or force-heading (not (org-insert-item 'checkbox)))
7953 (org-insert-heading (or (and (equal arg '(16)) '(16))
7954 force-heading))
7955 (save-excursion
7956 (org-back-to-heading)
7957 (outline-previous-heading)
7958 (looking-at org-todo-line-regexp))
7959 (let*
7960 ((new-mark-x
7961 (if (or (equal arg '(4))
7962 (not (match-beginning 2))
7963 (member (match-string 2) org-done-keywords))
7964 (car org-todo-keywords-1)
7965 (match-string 2)))
7966 (new-mark
7968 (run-hook-with-args-until-success
7969 'org-todo-get-default-hook new-mark-x nil)
7970 new-mark-x)))
7971 (beginning-of-line 1)
7972 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7973 (if org-treat-insert-todo-heading-as-state-change
7974 (org-todo new-mark)
7975 (insert new-mark " "))))
7976 (when org-provide-todo-statistics
7977 (org-update-parent-todo-statistics))))
7979 (defun org-insert-subheading (arg)
7980 "Insert a new subheading and demote it.
7981 Works for outline headings and for plain lists alike."
7982 (interactive "P")
7983 (org-insert-heading arg)
7984 (cond
7985 ((org-at-heading-p) (org-do-demote))
7986 ((org-at-item-p) (org-indent-item))))
7988 (defun org-insert-todo-subheading (arg)
7989 "Insert a new subheading with TODO keyword or checkbox and demote it.
7990 Works for outline headings and for plain lists alike."
7991 (interactive "P")
7992 (org-insert-todo-heading arg)
7993 (cond
7994 ((org-at-heading-p) (org-do-demote))
7995 ((org-at-item-p) (org-indent-item))))
7997 ;;; Promotion and Demotion
7999 (defvar org-after-demote-entry-hook nil
8000 "Hook run after an entry has been demoted.
8001 The cursor will be at the beginning of the entry.
8002 When a subtree is being demoted, the hook will be called for each node.")
8004 (defvar org-after-promote-entry-hook nil
8005 "Hook run after an entry has been promoted.
8006 The cursor will be at the beginning of the entry.
8007 When a subtree is being promoted, the hook will be called for each node.")
8009 (defun org-promote-subtree ()
8010 "Promote the entire subtree.
8011 See also `org-promote'."
8012 (interactive)
8013 (save-excursion
8014 (org-with-limited-levels (org-map-tree 'org-promote)))
8015 (org-fix-position-after-promote))
8017 (defun org-demote-subtree ()
8018 "Demote the entire subtree. See `org-demote'.
8019 See also `org-promote'."
8020 (interactive)
8021 (save-excursion
8022 (org-with-limited-levels (org-map-tree 'org-demote)))
8023 (org-fix-position-after-promote))
8026 (defun org-do-promote ()
8027 "Promote the current heading higher up the tree.
8028 If the region is active in `transient-mark-mode', promote all headings
8029 in the region."
8030 (interactive)
8031 (save-excursion
8032 (if (org-region-active-p)
8033 (org-map-region 'org-promote (region-beginning) (region-end))
8034 (org-promote)))
8035 (org-fix-position-after-promote))
8037 (defun org-do-demote ()
8038 "Demote the current heading lower down the tree.
8039 If the region is active in `transient-mark-mode', demote all headings
8040 in the region."
8041 (interactive)
8042 (save-excursion
8043 (if (org-region-active-p)
8044 (org-map-region 'org-demote (region-beginning) (region-end))
8045 (org-demote)))
8046 (org-fix-position-after-promote))
8048 (defun org-fix-position-after-promote ()
8049 "Make sure that after pro/demotion cursor position is right."
8050 (let ((pos (point)))
8051 (when (save-excursion
8052 (beginning-of-line 1)
8053 (looking-at org-todo-line-regexp)
8054 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8055 (cond ((eobp) (insert " "))
8056 ((eolp) (insert " "))
8057 ((equal (char-after) ?\ ) (forward-char 1))))))
8059 (defun org-current-level ()
8060 "Return the level of the current entry, or nil if before the first headline.
8061 The level is the number of stars at the beginning of the headline."
8062 (save-excursion
8063 (org-with-limited-levels
8064 (if (ignore-errors (org-back-to-heading t))
8065 (funcall outline-level)))))
8067 (defun org-get-previous-line-level ()
8068 "Return the outline depth of the last headline before the current line.
8069 Returns 0 for the first headline in the buffer, and nil if before the
8070 first headline."
8071 (and (org-current-level)
8072 (or (and (/= (line-beginning-position) (point-min))
8073 (save-excursion (beginning-of-line 0) (org-current-level)))
8074 0)))
8076 (defun org-reduced-level (l)
8077 "Compute the effective level of a heading.
8078 This takes into account the setting of `org-odd-levels-only'."
8079 (cond
8080 ((zerop l) 0)
8081 (org-odd-levels-only (1+ (floor (/ l 2))))
8082 (t l)))
8084 (defun org-level-increment ()
8085 "Return the number of stars that will be added or removed at a
8086 time to headlines when structure editing, based on the value of
8087 `org-odd-levels-only'."
8088 (if org-odd-levels-only 2 1))
8090 (defun org-get-valid-level (level &optional change)
8091 "Rectify a level change under the influence of `org-odd-levels-only'
8092 LEVEL is a current level, CHANGE is by how much the level should be
8093 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8094 even level numbers will become the next higher odd number."
8095 (if org-odd-levels-only
8096 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8097 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8098 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8099 (max 1 (+ level (or change 0)))))
8101 (if (boundp 'define-obsolete-function-alias)
8102 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8103 (define-obsolete-function-alias 'org-get-legal-level
8104 'org-get-valid-level)
8105 (define-obsolete-function-alias 'org-get-legal-level
8106 'org-get-valid-level "23.1")))
8108 (defun org-promote ()
8109 "Promote the current heading higher up the tree.
8110 If the region is active in `transient-mark-mode', promote all headings
8111 in the region."
8112 (org-back-to-heading t)
8113 (let* ((level (save-match-data (funcall outline-level)))
8114 (after-change-functions (remove 'flyspell-after-change-function
8115 after-change-functions))
8116 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8117 (diff (abs (- level (length up-head) -1))))
8118 (cond ((and (= level 1) org-called-with-limited-levels
8119 org-allow-promoting-top-level-subtree)
8120 (replace-match "# " nil t))
8121 ((= level 1)
8122 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8123 (t (replace-match up-head nil t)))
8124 ;; Fixup tag positioning
8125 (unless (= level 1)
8126 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8127 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8128 (run-hooks 'org-after-promote-entry-hook)))
8130 (defun org-demote ()
8131 "Demote the current heading lower down the tree.
8132 If the region is active in `transient-mark-mode', demote all headings
8133 in the region."
8134 (org-back-to-heading t)
8135 (let* ((level (save-match-data (funcall outline-level)))
8136 (after-change-functions (remove 'flyspell-after-change-function
8137 after-change-functions))
8138 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8139 (diff (abs (- level (length down-head) -1))))
8140 (replace-match down-head nil t)
8141 ;; Fixup tag positioning
8142 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8143 (if org-adapt-indentation (org-fixup-indentation diff))
8144 (run-hooks 'org-after-demote-entry-hook)))
8146 (defun org-cycle-level ()
8147 "Cycle the level of an empty headline through possible states.
8148 This goes first to child, then to parent, level, then up the hierarchy.
8149 After top level, it switches back to sibling level."
8150 (interactive)
8151 (let ((org-adapt-indentation nil))
8152 (when (org-point-at-end-of-empty-headline)
8153 (setq this-command 'org-cycle-level) ; Only needed for caching
8154 (let ((cur-level (org-current-level))
8155 (prev-level (org-get-previous-line-level)))
8156 (cond
8157 ;; If first headline in file, promote to top-level.
8158 ((= prev-level 0)
8159 (loop repeat (/ (- cur-level 1) (org-level-increment))
8160 do (org-do-promote)))
8161 ;; If same level as prev, demote one.
8162 ((= prev-level cur-level)
8163 (org-do-demote))
8164 ;; If parent is top-level, promote to top level if not already.
8165 ((= prev-level 1)
8166 (loop repeat (/ (- cur-level 1) (org-level-increment))
8167 do (org-do-promote)))
8168 ;; If top-level, return to prev-level.
8169 ((= cur-level 1)
8170 (loop repeat (/ (- prev-level 1) (org-level-increment))
8171 do (org-do-demote)))
8172 ;; If less than prev-level, promote one.
8173 ((< cur-level prev-level)
8174 (org-do-promote))
8175 ;; If deeper than prev-level, promote until higher than
8176 ;; prev-level.
8177 ((> cur-level prev-level)
8178 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8179 do (org-do-promote))))
8180 t))))
8182 (defun org-map-tree (fun)
8183 "Call FUN for every heading underneath the current one."
8184 (org-back-to-heading)
8185 (let ((level (funcall outline-level)))
8186 (save-excursion
8187 (funcall fun)
8188 (while (and (progn
8189 (outline-next-heading)
8190 (> (funcall outline-level) level))
8191 (not (eobp)))
8192 (funcall fun)))))
8194 (defun org-map-region (fun beg end)
8195 "Call FUN for every heading between BEG and END."
8196 (let ((org-ignore-region t))
8197 (save-excursion
8198 (setq end (copy-marker end))
8199 (goto-char beg)
8200 (if (and (re-search-forward org-outline-regexp-bol nil t)
8201 (< (point) end))
8202 (funcall fun))
8203 (while (and (progn
8204 (outline-next-heading)
8205 (< (point) end))
8206 (not (eobp)))
8207 (funcall fun)))))
8209 (defvar org-property-end-re) ; silence byte-compiler
8210 (defun org-fixup-indentation (diff)
8211 "Change the indentation in the current entry by DIFF.
8212 However, if any line in the current entry has no indentation, or if it
8213 would end up with no indentation after the change, nothing at all is done."
8214 (save-excursion
8215 (let ((end (save-excursion (outline-next-heading)
8216 (point-marker)))
8217 (prohibit (if (> diff 0)
8218 "^\\S-"
8219 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8220 col)
8221 (unless (save-excursion (end-of-line 1)
8222 (re-search-forward prohibit end t))
8223 (while (and (< (point) end)
8224 (re-search-forward "^[ \t]+" end t))
8225 (goto-char (match-end 0))
8226 (setq col (current-column))
8227 (if (< diff 0) (replace-match ""))
8228 (org-indent-to-column (+ diff col))))
8229 (move-marker end nil))))
8231 (defun org-convert-to-odd-levels ()
8232 "Convert an org-mode file with all levels allowed to one with odd levels.
8233 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8234 level 5 etc."
8235 (interactive)
8236 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8237 (let ((outline-level 'org-outline-level)
8238 (org-odd-levels-only nil) n)
8239 (save-excursion
8240 (goto-char (point-min))
8241 (while (re-search-forward "^\\*\\*+ " nil t)
8242 (setq n (- (length (match-string 0)) 2))
8243 (while (>= (setq n (1- n)) 0)
8244 (org-demote))
8245 (end-of-line 1))))))
8247 (defun org-convert-to-oddeven-levels ()
8248 "Convert an org-mode file with only odd levels to one with odd/even levels.
8249 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8250 file contains a section with an even level, conversion would
8251 destroy the structure of the file. An error is signaled in this
8252 case."
8253 (interactive)
8254 (goto-char (point-min))
8255 ;; First check if there are no even levels
8256 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8257 (org-show-context t)
8258 (error "Not all levels are odd in this file. Conversion not possible"))
8259 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8260 (let ((outline-regexp org-outline-regexp)
8261 (outline-level 'org-outline-level)
8262 (org-odd-levels-only nil) n)
8263 (save-excursion
8264 (goto-char (point-min))
8265 (while (re-search-forward "^\\*\\*+ " nil t)
8266 (setq n (/ (1- (length (match-string 0))) 2))
8267 (while (>= (setq n (1- n)) 0)
8268 (org-promote))
8269 (end-of-line 1))))))
8271 (defun org-tr-level (n)
8272 "Make N odd if required."
8273 (if org-odd-levels-only (1+ (/ n 2)) n))
8275 ;;; Vertical tree motion, cutting and pasting of subtrees
8277 (defun org-move-subtree-up (&optional arg)
8278 "Move the current subtree up past ARG headlines of the same level."
8279 (interactive "p")
8280 (org-move-subtree-down (- (prefix-numeric-value arg))))
8282 (defun org-move-subtree-down (&optional arg)
8283 "Move the current subtree down past ARG headlines of the same level."
8284 (interactive "p")
8285 (setq arg (prefix-numeric-value arg))
8286 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8287 'org-get-last-sibling))
8288 (ins-point (make-marker))
8289 (cnt (abs arg))
8290 (col (current-column))
8291 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8292 ;; Select the tree
8293 (org-back-to-heading)
8294 (setq beg0 (point))
8295 (save-excursion
8296 (setq ne-beg (org-back-over-empty-lines))
8297 (setq beg (point)))
8298 (save-match-data
8299 (save-excursion (outline-end-of-heading)
8300 (setq folded (outline-invisible-p)))
8301 (progn (org-end-of-subtree nil t)
8302 (unless (eobp) (backward-char))))
8303 (outline-next-heading)
8304 (setq ne-end (org-back-over-empty-lines))
8305 (setq end (point))
8306 (goto-char beg0)
8307 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8308 ;; include less whitespace
8309 (save-excursion
8310 (goto-char beg)
8311 (forward-line (- ne-beg ne-end))
8312 (setq beg (point))))
8313 ;; Find insertion point, with error handling
8314 (while (> cnt 0)
8315 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8316 (progn (goto-char beg0)
8317 (user-error "Cannot move past superior level or buffer limit")))
8318 (setq cnt (1- cnt)))
8319 (if (> arg 0)
8320 ;; Moving forward - still need to move over subtree
8321 (progn (org-end-of-subtree t t)
8322 (save-excursion
8323 (org-back-over-empty-lines)
8324 (or (bolp) (newline)))))
8325 (setq ne-ins (org-back-over-empty-lines))
8326 (move-marker ins-point (point))
8327 (setq txt (buffer-substring beg end))
8328 (org-save-markers-in-region beg end)
8329 (delete-region beg end)
8330 (org-remove-empty-overlays-at beg)
8331 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8332 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8333 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8334 (let ((bbb (point)))
8335 (insert-before-markers txt)
8336 (org-reinstall-markers-in-region bbb)
8337 (move-marker ins-point bbb))
8338 (or (bolp) (insert "\n"))
8339 (setq ins-end (point))
8340 (goto-char ins-point)
8341 (org-skip-whitespace)
8342 (when (and (< arg 0)
8343 (org-first-sibling-p)
8344 (> ne-ins ne-beg))
8345 ;; Move whitespace back to beginning
8346 (save-excursion
8347 (goto-char ins-end)
8348 (let ((kill-whole-line t))
8349 (kill-line (- ne-ins ne-beg)) (point)))
8350 (insert (make-string (- ne-ins ne-beg) ?\n)))
8351 (move-marker ins-point nil)
8352 (if folded
8353 (hide-subtree)
8354 (org-show-entry)
8355 (show-children)
8356 (org-cycle-hide-drawers 'children))
8357 (org-clean-visibility-after-subtree-move)
8358 ;; move back to the initial column we were at
8359 (move-to-column col)))
8361 (defvar org-subtree-clip ""
8362 "Clipboard for cut and paste of subtrees.
8363 This is actually only a copy of the kill, because we use the normal kill
8364 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8366 (defvar org-subtree-clip-folded nil
8367 "Was the last copied subtree folded?
8368 This is used to fold the tree back after pasting.")
8370 (defun org-cut-subtree (&optional n)
8371 "Cut the current subtree into the clipboard.
8372 With prefix arg N, cut this many sequential subtrees.
8373 This is a short-hand for marking the subtree and then cutting it."
8374 (interactive "p")
8375 (org-copy-subtree n 'cut))
8377 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8378 "Copy the current subtree it in the clipboard.
8379 With prefix arg N, copy this many sequential subtrees.
8380 This is a short-hand for marking the subtree and then copying it.
8381 If CUT is non-nil, actually cut the subtree.
8382 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8383 of some markers in the region, even if CUT is non-nil. This is
8384 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8385 (interactive "p")
8386 (let (beg end folded (beg0 (point)))
8387 (if (org-called-interactively-p 'any)
8388 (org-back-to-heading nil) ; take what looks like a subtree
8389 (org-back-to-heading t)) ; take what is really there
8390 (setq beg (point))
8391 (skip-chars-forward " \t\r\n")
8392 (save-match-data
8393 (if nosubtrees
8394 (outline-next-heading)
8395 (save-excursion (outline-end-of-heading)
8396 (setq folded (outline-invisible-p)))
8397 (ignore-errors (org-forward-heading-same-level (1- n) t))
8398 (org-end-of-subtree t t)))
8399 (setq end (point))
8400 (goto-char beg0)
8401 (when (> end beg)
8402 (setq org-subtree-clip-folded folded)
8403 (when (or cut force-store-markers)
8404 (org-save-markers-in-region beg end))
8405 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8406 (setq org-subtree-clip (current-kill 0))
8407 (message "%s: Subtree(s) with %d characters"
8408 (if cut "Cut" "Copied")
8409 (length org-subtree-clip)))))
8411 (defun org-paste-subtree (&optional level tree for-yank remove)
8412 "Paste the clipboard as a subtree, with modification of headline level.
8413 The entire subtree is promoted or demoted in order to match a new headline
8414 level.
8416 If the cursor is at the beginning of a headline, the same level as
8417 that headline is used to paste the tree.
8419 If not, the new level is derived from the *visible* headings
8420 before and after the insertion point, and taken to be the inferior headline
8421 level of the two. So if the previous visible heading is level 3 and the
8422 next is level 4 (or vice versa), level 4 will be used for insertion.
8423 This makes sure that the subtree remains an independent subtree and does
8424 not swallow low level entries.
8426 You can also force a different level, either by using a numeric prefix
8427 argument, or by inserting the heading marker by hand. For example, if the
8428 cursor is after \"*****\", then the tree will be shifted to level 5.
8430 If optional TREE is given, use this text instead of the kill ring.
8432 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8433 move back over whitespace before inserting, and move point to the end of
8434 the inserted text when done.
8436 When REMOVE is non-nil, remove the subtree from the clipboard."
8437 (interactive "P")
8438 (setq tree (or tree (and kill-ring (current-kill 0))))
8439 (unless (org-kill-is-subtree-p tree)
8440 (user-error "%s"
8441 (substitute-command-keys
8442 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8443 (org-with-limited-levels
8444 (let* ((visp (not (outline-invisible-p)))
8445 (txt tree)
8446 (^re_ "\\(\\*+\\)[ \t]*")
8447 (old-level (if (string-match org-outline-regexp-bol txt)
8448 (- (match-end 0) (match-beginning 0) 1)
8449 -1))
8450 (force-level (cond (level (prefix-numeric-value level))
8451 ((and (looking-at "[ \t]*$")
8452 (string-match
8453 "^\\*+$" (buffer-substring
8454 (point-at-bol) (point))))
8455 (- (match-end 0) (match-beginning 0)))
8456 ((and (bolp)
8457 (looking-at org-outline-regexp))
8458 (- (match-end 0) (point) 1))))
8459 (previous-level (save-excursion
8460 (condition-case nil
8461 (progn
8462 (outline-previous-visible-heading 1)
8463 (if (looking-at ^re_)
8464 (- (match-end 0) (match-beginning 0) 1)
8466 (error 1))))
8467 (next-level (save-excursion
8468 (condition-case nil
8469 (progn
8470 (or (looking-at org-outline-regexp)
8471 (outline-next-visible-heading 1))
8472 (if (looking-at ^re_)
8473 (- (match-end 0) (match-beginning 0) 1)
8475 (error 1))))
8476 (new-level (or force-level (max previous-level next-level)))
8477 (shift (if (or (= old-level -1)
8478 (= new-level -1)
8479 (= old-level new-level))
8481 (- new-level old-level)))
8482 (delta (if (> shift 0) -1 1))
8483 (func (if (> shift 0) 'org-demote 'org-promote))
8484 (org-odd-levels-only nil)
8485 beg end newend)
8486 ;; Remove the forced level indicator
8487 (if force-level
8488 (delete-region (point-at-bol) (point)))
8489 ;; Paste
8490 (beginning-of-line (if (bolp) 1 2))
8491 (setq beg (point))
8492 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8493 (insert-before-markers txt)
8494 (unless (string-match "\n\\'" txt) (insert "\n"))
8495 (setq newend (point))
8496 (org-reinstall-markers-in-region beg)
8497 (setq end (point))
8498 (goto-char beg)
8499 (skip-chars-forward " \t\n\r")
8500 (setq beg (point))
8501 (if (and (outline-invisible-p) visp)
8502 (save-excursion (outline-show-heading)))
8503 ;; Shift if necessary
8504 (unless (= shift 0)
8505 (save-restriction
8506 (narrow-to-region beg end)
8507 (while (not (= shift 0))
8508 (org-map-region func (point-min) (point-max))
8509 (setq shift (+ delta shift)))
8510 (goto-char (point-min))
8511 (setq newend (point-max))))
8512 (when (or (org-called-interactively-p 'interactive) for-yank)
8513 (message "Clipboard pasted as level %d subtree" new-level))
8514 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8515 kill-ring
8516 (eq org-subtree-clip (current-kill 0))
8517 org-subtree-clip-folded)
8518 ;; The tree was folded before it was killed/copied
8519 (hide-subtree))
8520 (and for-yank (goto-char newend))
8521 (and remove (setq kill-ring (cdr kill-ring))))))
8523 (defun org-kill-is-subtree-p (&optional txt)
8524 "Check if the current kill is an outline subtree, or a set of trees.
8525 Returns nil if kill does not start with a headline, or if the first
8526 headline level is not the largest headline level in the tree.
8527 So this will actually accept several entries of equal levels as well,
8528 which is OK for `org-paste-subtree'.
8529 If optional TXT is given, check this string instead of the current kill."
8530 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8531 (re (org-get-limited-outline-regexp))
8532 (^re (concat "^" re))
8533 (start-level (and kill
8534 (string-match
8535 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8536 kill)
8537 (- (match-end 2) (match-beginning 2) 1)))
8538 (start (1+ (or (match-beginning 2) -1))))
8539 (if (not start-level)
8540 (progn
8541 nil) ;; does not even start with a heading
8542 (catch 'exit
8543 (while (setq start (string-match ^re kill (1+ start)))
8544 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8545 (throw 'exit nil)))
8546 t))))
8548 (defvar org-markers-to-move nil
8549 "Markers that should be moved with a cut-and-paste operation.
8550 Those markers are stored together with their positions relative to
8551 the start of the region.")
8553 (defun org-save-markers-in-region (beg end)
8554 "Check markers in region.
8555 If these markers are between BEG and END, record their position relative
8556 to BEG, so that after moving the block of text, we can put the markers back
8557 into place.
8558 This function gets called just before an entry or tree gets cut from the
8559 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8560 called immediately, to move the markers with the entries."
8561 (setq org-markers-to-move nil)
8562 (when (featurep 'org-clock)
8563 (org-clock-save-markers-for-cut-and-paste beg end))
8564 (when (featurep 'org-agenda)
8565 (org-agenda-save-markers-for-cut-and-paste beg end)))
8567 (defun org-check-and-save-marker (marker beg end)
8568 "Check if MARKER is between BEG and END.
8569 If yes, remember the marker and the distance to BEG."
8570 (when (and (marker-buffer marker)
8571 (equal (marker-buffer marker) (current-buffer)))
8572 (if (and (>= marker beg) (< marker end))
8573 (push (cons marker (- marker beg)) org-markers-to-move))))
8575 (defun org-reinstall-markers-in-region (beg)
8576 "Move all remembered markers to their position relative to BEG."
8577 (mapc (lambda (x)
8578 (move-marker (car x) (+ beg (cdr x))))
8579 org-markers-to-move)
8580 (setq org-markers-to-move nil))
8582 (defun org-narrow-to-subtree ()
8583 "Narrow buffer to the current subtree."
8584 (interactive)
8585 (save-excursion
8586 (save-match-data
8587 (org-with-limited-levels
8588 (narrow-to-region
8589 (progn (org-back-to-heading t) (point))
8590 (progn (org-end-of-subtree t t)
8591 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8592 (point)))))))
8594 (defun org-narrow-to-block ()
8595 "Narrow buffer to the current block."
8596 (interactive)
8597 (let* ((case-fold-search t)
8598 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8599 "^[ \t]*#\\+end_.*")))
8600 (if blockp
8601 (narrow-to-region (car blockp) (cdr blockp))
8602 (user-error "Not in a block"))))
8604 (defun org-clone-subtree-with-time-shift (n &optional shift)
8605 "Clone the task (subtree) at point N times.
8606 The clones will be inserted as siblings.
8608 In interactive use, the user will be prompted for the number of
8609 clones to be produced. If the entry has a timestamp, the user
8610 will also be prompted for a time shift, which may be a repeater
8611 as used in time stamps, for example `+3d'. To disable this,
8612 you can call the function with a universal prefix argument.
8614 When a valid repeater is given and the entry contains any time
8615 stamps, the clones will become a sequence in time, with time
8616 stamps in the subtree shifted for each clone produced. If SHIFT
8617 is nil or the empty string, time stamps will be left alone. The
8618 ID property of the original subtree is removed.
8620 If the original subtree did contain time stamps with a repeater,
8621 the following will happen:
8622 - the repeater will be removed in each clone
8623 - an additional clone will be produced, with the current, unshifted
8624 date(s) in the entry.
8625 - the original entry will be placed *after* all the clones, with
8626 repeater intact.
8627 - the start days in the repeater in the original entry will be shifted
8628 to past the last clone.
8629 In this way you can spell out a number of instances of a repeating task,
8630 and still retain the repeater to cover future instances of the task."
8631 (interactive "nNumber of clones to produce: ")
8632 (let ((shift
8633 (or shift
8634 (if (and (not (equal current-prefix-arg '(4)))
8635 (save-excursion
8636 (re-search-forward org-ts-regexp-both
8637 (save-excursion
8638 (org-end-of-subtree t)
8639 (point)) t)))
8640 (read-from-minibuffer
8641 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8642 ""))) ;; No time shift
8643 (n-no-remove -1)
8644 (drawer-re org-drawer-regexp)
8645 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8646 beg end template task idprop
8647 shift-n shift-what doshift nmin nmax)
8648 (if (not (and (integerp n) (> n 0)))
8649 (user-error "Invalid number of replications %s" n))
8650 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8651 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8652 shift)))
8653 (user-error "Invalid shift specification %s" shift))
8654 (when doshift
8655 (setq shift-n (string-to-number (match-string 1 shift))
8656 shift-what (cdr (assoc (match-string 2 shift)
8657 '(("d" . day) ("w" . week)
8658 ("m" . month) ("y" . year))))))
8659 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8660 (setq nmin 1 nmax n)
8661 (org-back-to-heading t)
8662 (setq beg (point))
8663 (setq idprop (org-entry-get nil "ID"))
8664 (org-end-of-subtree t t)
8665 (or (bolp) (insert "\n"))
8666 (setq end (point))
8667 (setq template (buffer-substring beg end))
8668 (when (and doshift
8669 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8670 (delete-region beg end)
8671 (setq end beg)
8672 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8673 (goto-char end)
8674 (loop for n from nmin to nmax do
8675 ;; prepare clone
8676 (with-temp-buffer
8677 (insert template)
8678 (org-mode)
8679 (goto-char (point-min))
8680 (org-show-subtree)
8681 (and idprop (if org-clone-delete-id
8682 (org-entry-delete nil "ID")
8683 (org-id-get-create t)))
8684 (unless (= n 0)
8685 (while (re-search-forward org-clock-re nil t)
8686 (kill-whole-line))
8687 (goto-char (point-min))
8688 (while (re-search-forward drawer-re nil t)
8689 (org-remove-empty-drawer-at (point))))
8690 (goto-char (point-min))
8691 (when doshift
8692 (while (re-search-forward org-ts-regexp-both nil t)
8693 (org-timestamp-change (* n shift-n) shift-what))
8694 (unless (= n n-no-remove)
8695 (goto-char (point-min))
8696 (while (re-search-forward org-ts-regexp nil t)
8697 (save-excursion
8698 (goto-char (match-beginning 0))
8699 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8700 (delete-region (match-beginning 1) (match-end 1)))))))
8701 (setq task (buffer-string)))
8702 (insert task))
8703 (goto-char beg)))
8705 ;;; Outline Sorting
8707 (defun org-sort (with-case)
8708 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8709 Optional argument WITH-CASE means sort case-sensitively."
8710 (interactive "P")
8711 (cond
8712 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8713 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8715 (org-call-with-arg 'org-sort-entries with-case))))
8717 (defun org-sort-remove-invisible (s)
8718 "Remove invisible links from string S."
8719 (remove-text-properties 0 (length s) org-rm-props s)
8720 (while (string-match org-bracket-link-regexp s)
8721 (setq s (replace-match (if (match-end 2)
8722 (match-string 3 s)
8723 (match-string 1 s)) t t s)))
8724 (let ((st (format " %s " s)))
8725 (while (string-match org-emph-re st)
8726 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8727 (setq s (substring st 1 -1)))
8730 (defvar org-priority-regexp) ; defined later in the file
8732 (defvar org-after-sorting-entries-or-items-hook nil
8733 "Hook that is run after a bunch of entries or items have been sorted.
8734 When children are sorted, the cursor is in the parent line when this
8735 hook gets called. When a region or a plain list is sorted, the cursor
8736 will be in the first entry of the sorted region/list.")
8738 (defun org-sort-entries
8739 (&optional with-case sorting-type getkey-func compare-func property)
8740 "Sort entries on a certain level of an outline tree.
8741 If there is an active region, the entries in the region are sorted.
8742 Else, if the cursor is before the first entry, sort the top-level items.
8743 Else, the children of the entry at point are sorted.
8745 Sorting can be alphabetically, numerically, by date/time as given by
8746 a time stamp, by a property, by priority order, or by a custom function.
8748 The command prompts for the sorting type unless it has been given to the
8749 function through the SORTING-TYPE argument, which needs to be a character,
8750 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8751 the precise meaning of each character:
8753 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8754 c By creation time, which is assumed to be the first inactive time stamp
8755 at the beginning of a line.
8756 d By deadline date/time.
8757 k By clocking time.
8758 n Numerically, by converting the beginning of the entry/item to a number.
8759 o By order of TODO keywords.
8760 p By priority according to the cookie.
8761 r By the value of a property.
8762 s By scheduled date/time.
8763 t By date/time, either the first active time stamp in the entry, or, if
8764 none exist, by the first inactive one.
8766 Capital letters will reverse the sort order.
8768 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8769 called with point at the beginning of the record. It must return either
8770 a string or a number that should serve as the sorting key for that record.
8772 Comparing entries ignores case by default. However, with an optional argument
8773 WITH-CASE, the sorting considers case as well.
8775 Sorting is done against the visible part of the headlines, it ignores hidden
8776 links.
8778 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8779 (interactive "P")
8780 (let ((case-func (if with-case 'identity 'downcase))
8781 (cmstr
8782 ;; The clock marker is lost when using `sort-subr', let's
8783 ;; store the clocking string.
8784 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8785 (save-excursion
8786 (goto-char org-clock-marker)
8787 (looking-back "^.*") (match-string-no-properties 0))))
8788 start beg end stars re re2
8789 txt what tmp)
8790 ;; Find beginning and end of region to sort
8791 (cond
8792 ((org-region-active-p)
8793 ;; we will sort the region
8794 (setq end (region-end)
8795 what "region")
8796 (goto-char (region-beginning))
8797 (if (not (org-at-heading-p)) (outline-next-heading))
8798 (setq start (point)))
8799 ((or (org-at-heading-p)
8800 (ignore-errors (progn (org-back-to-heading) t)))
8801 ;; we will sort the children of the current headline
8802 (org-back-to-heading)
8803 (setq start (point)
8804 end (progn (org-end-of-subtree t t)
8805 (or (bolp) (insert "\n"))
8806 (when (>= (org-back-over-empty-lines) 1)
8807 (forward-line 1))
8808 (point))
8809 what "children")
8810 (goto-char start)
8811 (show-subtree)
8812 (outline-next-heading))
8814 ;; we will sort the top-level entries in this file
8815 (goto-char (point-min))
8816 (or (org-at-heading-p) (outline-next-heading))
8817 (setq start (point))
8818 (goto-char (point-max))
8819 (beginning-of-line 1)
8820 (when (looking-at ".*?\\S-")
8821 ;; File ends in a non-white line
8822 (end-of-line 1)
8823 (insert "\n"))
8824 (setq end (point-max))
8825 (setq what "top-level")
8826 (goto-char start)
8827 (show-all)))
8829 (setq beg (point))
8830 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8832 (looking-at "\\(\\*+\\)")
8833 (setq stars (match-string 1)
8834 re (concat "^" (regexp-quote stars) " +")
8835 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8836 txt (buffer-substring beg end))
8837 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8838 (if (and (not (equal stars "*")) (string-match re2 txt))
8839 (user-error "Region to sort contains a level above the first entry"))
8841 (unless sorting-type
8842 (message
8843 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8844 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8845 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8846 what)
8847 (setq sorting-type (read-char-exclusive))
8849 (unless getkey-func
8850 (and (= (downcase sorting-type) ?f)
8851 (setq getkey-func
8852 (org-icompleting-read "Sort using function: "
8853 obarray 'fboundp t nil nil))
8854 (setq getkey-func (intern getkey-func))))
8856 (and (= (downcase sorting-type) ?r)
8857 (not property)
8858 (setq property
8859 (org-icompleting-read "Property: "
8860 (mapcar 'list (org-buffer-property-keys t))
8861 nil t))))
8863 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8864 (message "Sorting entries...")
8866 (save-restriction
8867 (narrow-to-region start end)
8868 (let ((dcst (downcase sorting-type))
8869 (case-fold-search nil)
8870 (now (current-time)))
8871 (sort-subr
8872 (/= dcst sorting-type)
8873 ;; This function moves to the beginning character of the "record" to
8874 ;; be sorted.
8875 (lambda nil
8876 (if (re-search-forward re nil t)
8877 (goto-char (match-beginning 0))
8878 (goto-char (point-max))))
8879 ;; This function moves to the last character of the "record" being
8880 ;; sorted.
8881 (lambda nil
8882 (save-match-data
8883 (condition-case nil
8884 (outline-forward-same-level 1)
8885 (error
8886 (goto-char (point-max))))))
8887 ;; This function returns the value that gets sorted against.
8888 (lambda nil
8889 (cond
8890 ((= dcst ?n)
8891 (if (looking-at org-complex-heading-regexp)
8892 (string-to-number (org-sort-remove-invisible (match-string 4)))
8893 nil))
8894 ((= dcst ?a)
8895 (if (looking-at org-complex-heading-regexp)
8896 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8897 nil))
8898 ((= dcst ?k)
8899 (or (get-text-property (point) :org-clock-minutes) 0))
8900 ((= dcst ?t)
8901 (let ((end (save-excursion (outline-next-heading) (point))))
8902 (if (or (re-search-forward org-ts-regexp end t)
8903 (re-search-forward org-ts-regexp-both end t))
8904 (org-time-string-to-seconds (match-string 0))
8905 (org-float-time now))))
8906 ((= dcst ?c)
8907 (let ((end (save-excursion (outline-next-heading) (point))))
8908 (if (re-search-forward
8909 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8910 end t)
8911 (org-time-string-to-seconds (match-string 0))
8912 (org-float-time now))))
8913 ((= dcst ?s)
8914 (let ((end (save-excursion (outline-next-heading) (point))))
8915 (if (re-search-forward org-scheduled-time-regexp end t)
8916 (org-time-string-to-seconds (match-string 1))
8917 (org-float-time now))))
8918 ((= dcst ?d)
8919 (let ((end (save-excursion (outline-next-heading) (point))))
8920 (if (re-search-forward org-deadline-time-regexp end t)
8921 (org-time-string-to-seconds (match-string 1))
8922 (org-float-time now))))
8923 ((= dcst ?p)
8924 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8925 (string-to-char (match-string 2))
8926 org-default-priority))
8927 ((= dcst ?r)
8928 (or (org-entry-get nil property) ""))
8929 ((= dcst ?o)
8930 (if (looking-at org-complex-heading-regexp)
8931 (let* ((m (match-string 2))
8932 (s (if (member m org-done-keywords) '- '+)))
8933 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8934 ((= dcst ?f)
8935 (if getkey-func
8936 (progn
8937 (setq tmp (funcall getkey-func))
8938 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8939 tmp)
8940 (error "Invalid key function `%s'" getkey-func)))
8941 (t (error "Invalid sorting type `%c'" sorting-type))))
8943 (cond
8944 ((= dcst ?a) 'string<)
8945 ((= dcst ?f) compare-func)
8946 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8947 (run-hooks 'org-after-sorting-entries-or-items-hook)
8948 ;; Reset the clock marker if needed
8949 (when cmstr
8950 (save-excursion
8951 (goto-char start)
8952 (search-forward cmstr nil t)
8953 (move-marker org-clock-marker (point))))
8954 (message "Sorting entries...done")))
8956 (defun org-do-sort (table what &optional with-case sorting-type)
8957 "Sort TABLE of WHAT according to SORTING-TYPE.
8958 The user will be prompted for the SORTING-TYPE if the call to this
8959 function does not specify it.
8960 WHAT is only for the prompt, to indicate what is being sorted.
8961 The sorting key will be extracted from the car of the elements of
8962 the table.
8963 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8964 (unless sorting-type
8965 (message
8966 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8967 what)
8968 (setq sorting-type (read-char-exclusive)))
8969 (let ((dcst (downcase sorting-type))
8970 extractfun comparefun)
8971 ;; Define the appropriate functions
8972 (cond
8973 ((= dcst ?n)
8974 (setq extractfun 'string-to-number
8975 comparefun (if (= dcst sorting-type) '< '>)))
8976 ((= dcst ?a)
8977 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8978 (lambda(x) (downcase (org-sort-remove-invisible x))))
8979 comparefun (if (= dcst sorting-type)
8980 'string<
8981 (lambda (a b) (and (not (string< a b))
8982 (not (string= a b)))))))
8983 ((= dcst ?t)
8984 (setq extractfun
8985 (lambda (x)
8986 (cond ((or (string-match org-ts-regexp x)
8987 (string-match org-ts-regexp-both x))
8988 (org-float-time
8989 (org-time-string-to-time (match-string 0 x))))
8990 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8991 (org-hh:mm-string-to-minutes x))
8992 (t 0)))
8993 comparefun (if (= dcst sorting-type) '< '>)))
8994 (t (error "Invalid sorting type `%c'" sorting-type)))
8996 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8997 table)
8998 (lambda (a b) (funcall comparefun (car a) (car b))))))
9001 ;;; The orgstruct minor mode
9003 ;; Define a minor mode which can be used in other modes in order to
9004 ;; integrate the org-mode structure editing commands.
9006 ;; This is really a hack, because the org-mode structure commands use
9007 ;; keys which normally belong to the major mode. Here is how it
9008 ;; works: The minor mode defines all the keys necessary to operate the
9009 ;; structure commands, but wraps the commands into a function which
9010 ;; tests if the cursor is currently at a headline or a plain list
9011 ;; item. If that is the case, the structure command is used,
9012 ;; temporarily setting many Org-mode variables like regular
9013 ;; expressions for filling etc. However, when any of those keys is
9014 ;; used at a different location, function uses `key-binding' to look
9015 ;; up if the key has an associated command in another currently active
9016 ;; keymap (minor modes, major mode, global), and executes that
9017 ;; command. There might be problems if any of the keys is otherwise
9018 ;; used as a prefix key.
9020 (defcustom orgstruct-heading-prefix-regexp ""
9021 "Regexp that matches the custom prefix of Org headlines in
9022 orgstruct(++)-mode."
9023 :group 'org
9024 :version "24.4"
9025 :package-version '(Org . "8.3")
9026 :type 'regexp)
9027 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9029 (defcustom orgstruct-setup-hook nil
9030 "Hook run after orgstruct-mode-map is filled."
9031 :group 'org
9032 :version "24.4"
9033 :package-version '(Org . "8.0")
9034 :type 'hook)
9036 (defvar orgstruct-initialized nil)
9038 (defvar org-local-vars nil
9039 "List of local variables, for use by `orgstruct-mode'.")
9041 ;;;###autoload
9042 (define-minor-mode orgstruct-mode
9043 "Toggle the minor mode `orgstruct-mode'.
9044 This mode is for using Org-mode structure commands in other
9045 modes. The following keys behave as if Org-mode were active, if
9046 the cursor is on a headline, or on a plain list item (both as
9047 defined by Org-mode)."
9048 nil " OrgStruct" (make-sparse-keymap)
9049 (funcall (if orgstruct-mode
9050 'add-to-invisibility-spec
9051 'remove-from-invisibility-spec)
9052 '(outline . t))
9053 (when orgstruct-mode
9054 (org-load-modules-maybe)
9055 (unless orgstruct-initialized
9056 (orgstruct-setup)
9057 (setq orgstruct-initialized t))))
9059 ;;;###autoload
9060 (defun turn-on-orgstruct ()
9061 "Unconditionally turn on `orgstruct-mode'."
9062 (orgstruct-mode 1))
9064 (defvar org-fb-vars nil)
9065 (make-variable-buffer-local 'org-fb-vars)
9066 (defun orgstruct++-mode (&optional arg)
9067 "Toggle `orgstruct-mode', the enhanced version of it.
9068 In addition to setting orgstruct-mode, this also exports all
9069 indentation and autofilling variables from org-mode into the
9070 buffer. It will also recognize item context in multiline items."
9071 (interactive "P")
9072 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9073 (if (< arg 1)
9074 (progn (orgstruct-mode -1)
9075 (mapc (lambda(v)
9076 (org-set-local (car v)
9077 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9078 org-fb-vars))
9079 (orgstruct-mode 1)
9080 (setq org-fb-vars nil)
9081 (unless org-local-vars
9082 (setq org-local-vars (org-get-local-variables)))
9083 (let (var val)
9084 (mapc
9085 (lambda (x)
9086 (when (string-match
9087 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9088 (symbol-name (car x)))
9089 (setq var (car x) val (nth 1 x))
9090 (push (list var `(quote ,(eval var))) org-fb-vars)
9091 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9092 org-local-vars)
9093 (org-set-local 'orgstruct-is-++ t))))
9095 (defvar orgstruct-is-++ nil
9096 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9097 (make-variable-buffer-local 'orgstruct-is-++)
9099 ;;;###autoload
9100 (defun turn-on-orgstruct++ ()
9101 "Unconditionally turn on `orgstruct++-mode'."
9102 (orgstruct++-mode 1))
9104 (defun orgstruct-error ()
9105 "Error when there is no default binding for a structure key."
9106 (interactive)
9107 (funcall (if (fboundp 'user-error)
9108 'user-error
9109 'error)
9110 "This key has no function outside structure elements"))
9112 (defun orgstruct-setup ()
9113 "Setup orgstruct keymap."
9114 (dolist (cell '((org-demote . t)
9115 (org-metaleft . t)
9116 (org-metaright . t)
9117 (org-promote . t)
9118 (org-shiftmetaleft . t)
9119 (org-shiftmetaright . t)
9120 org-backward-element
9121 org-backward-heading-same-level
9122 org-ctrl-c-ret
9123 org-ctrl-c-minus
9124 org-ctrl-c-star
9125 org-cycle
9126 org-forward-heading-same-level
9127 org-insert-heading
9128 org-insert-heading-respect-content
9129 org-kill-note-or-show-branches
9130 org-mark-subtree
9131 org-meta-return
9132 org-metadown
9133 org-metaup
9134 org-narrow-to-subtree
9135 org-promote-subtree
9136 org-reveal
9137 org-shiftdown
9138 org-shiftleft
9139 org-shiftmetadown
9140 org-shiftmetaup
9141 org-shiftright
9142 org-shifttab
9143 org-shifttab
9144 org-shiftup
9145 org-show-subtree
9146 org-sort
9147 org-up-element
9148 outline-demote
9149 outline-next-visible-heading
9150 outline-previous-visible-heading
9151 outline-promote
9152 outline-up-heading
9153 show-children))
9154 (let ((f (or (car-safe cell) cell))
9155 (disable-when-heading-prefix (cdr-safe cell)))
9156 (when (fboundp f)
9157 (let ((new-bindings))
9158 (dolist (binding (nconc (where-is-internal f org-mode-map)
9159 (where-is-internal f outline-mode-map)))
9160 (push binding new-bindings)
9161 ;; TODO use local-function-key-map
9162 (dolist (rep '(("<tab>" . "TAB")
9163 ("<return>" . "RET")
9164 ("<escape>" . "ESC")
9165 ("<delete>" . "DEL")))
9166 (setq binding (read-kbd-macro
9167 (let ((case-fold-search))
9168 (replace-regexp-in-string
9169 (regexp-quote (cdr rep))
9170 (car rep)
9171 (key-description binding)))))
9172 (pushnew binding new-bindings :test 'equal)))
9173 (dolist (binding new-bindings)
9174 (let ((key (lookup-key orgstruct-mode-map binding)))
9175 (when (or (not key) (numberp key))
9176 (ignore-errors
9177 (org-defkey orgstruct-mode-map
9178 binding
9179 (orgstruct-make-binding
9180 f binding disable-when-heading-prefix))))))))))
9181 (run-hooks 'orgstruct-setup-hook))
9183 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9184 "Create a function for binding in the structure minor mode.
9185 FUN is the command to call inside a table. KEY is the key that
9186 should be checked in for a command to execute outside of tables.
9187 Non-nil `disable-when-heading-prefix' means to disable the command
9188 if `orgstruct-heading-prefix-regexp' is not empty."
9189 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9190 (let ((nname name)
9191 (i 0))
9192 (while (fboundp (intern nname))
9193 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9194 (setq name (intern nname)))
9195 (eval
9196 (let ((bindings '((org-heading-regexp
9197 (concat "^"
9198 orgstruct-heading-prefix-regexp
9199 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9200 (org-outline-regexp
9201 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9202 (org-outline-regexp-bol
9203 (concat "^" org-outline-regexp))
9204 (outline-regexp org-outline-regexp)
9205 (outline-heading-end-regexp "\n")
9206 (outline-level 'org-outline-level)
9207 (outline-heading-alist))))
9208 `(defun ,name (arg)
9209 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9210 "Outside of structure, run the binding of `"
9211 (key-description key) "'."
9212 (when disable-when-heading-prefix
9213 (concat
9214 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9215 "back to the default binding due to limitations of Org's implementation of\n"
9216 "`" (symbol-name fun) "'.")))
9217 (interactive "p")
9218 (let* ((disable
9219 ,(and disable-when-heading-prefix
9220 '(not (string= orgstruct-heading-prefix-regexp ""))))
9221 (fallback
9222 (or disable
9223 (not
9224 (let* ,bindings
9225 (org-context-p 'headline 'item
9226 ,(when (memq fun
9227 '(org-insert-heading
9228 org-insert-heading-respect-content
9229 org-meta-return))
9230 '(when orgstruct-is-++
9231 'item-body))))))))
9232 (if fallback
9233 (let* ((orgstruct-mode)
9234 (binding
9235 (let ((key ,key))
9236 (catch 'exit
9237 (dolist
9238 (rep
9239 '(nil
9240 ("<\\([^>]*\\)tab>" . "\\1TAB")
9241 ("<\\([^>]*\\)return>" . "\\1RET")
9242 ("<\\([^>]*\\)escape>" . "\\1ESC")
9243 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9244 nil)
9245 (when rep
9246 (setq key (read-kbd-macro
9247 (let ((case-fold-search))
9248 (replace-regexp-in-string
9249 (car rep)
9250 (cdr rep)
9251 (key-description key))))))
9252 (when (key-binding key)
9253 (throw 'exit (key-binding key))))))))
9254 (if (keymapp binding)
9255 (org-set-transient-map binding)
9256 (let ((func (or binding
9257 (unless disable
9258 'orgstruct-error))))
9259 (when func
9260 (call-interactively func)))))
9261 (org-run-like-in-org-mode
9262 (lambda ()
9263 (interactive)
9264 (let* ,bindings
9265 (call-interactively ',fun)))))))))
9266 name))
9268 (defun org-contextualize-keys (alist contexts)
9269 "Return valid elements in ALIST depending on CONTEXTS.
9271 `org-agenda-custom-commands' or `org-capture-templates' are the
9272 values used for ALIST, and `org-agenda-custom-commands-contexts'
9273 or `org-capture-templates-contexts' are the associated contexts
9274 definitions."
9275 (let ((contexts
9276 ;; normalize contexts
9277 (mapcar
9278 (lambda(c) (cond ((listp (cadr c))
9279 (list (car c) (car c) (cadr c)))
9280 ((string= "" (cadr c))
9281 (list (car c) (car c) (caddr c)))
9282 (t c))) contexts))
9283 (a alist) c r s)
9284 ;; loop over all commands or templates
9285 (while (setq c (pop a))
9286 (let (vrules repl)
9287 (cond
9288 ((not (assoc (car c) contexts))
9289 (push c r))
9290 ((and (assoc (car c) contexts)
9291 (setq vrules (org-contextualize-validate-key
9292 (car c) contexts)))
9293 (mapc (lambda (vr)
9294 (when (not (equal (car vr) (cadr vr)))
9295 (setq repl vr))) vrules)
9296 (if (not repl) (push c r)
9297 (push (cadr repl) s)
9298 (push
9299 (cons (car c)
9300 (cdr (or (assoc (cadr repl) alist)
9301 (error "Undefined key `%s' as contextual replacement for `%s'"
9302 (cadr repl) (car c)))))
9303 r))))))
9304 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9305 (delq
9307 (delete-dups
9308 (mapcar (lambda (x)
9309 (let ((tpl (car x)))
9310 (when (not (delq
9312 (mapcar (lambda(y)
9313 (equal y tpl)) s))) x)))
9314 (reverse r))))))
9316 (defun org-contextualize-validate-key (key contexts)
9317 "Check CONTEXTS for agenda or capture KEY."
9318 (let (r rr res)
9319 (while (setq r (pop contexts))
9320 (mapc
9321 (lambda (rr)
9322 (when
9323 (and (equal key (car r))
9324 (if (functionp rr) (funcall rr)
9325 (or (and (eq (car rr) 'in-file)
9326 (buffer-file-name)
9327 (string-match (cdr rr) (buffer-file-name)))
9328 (and (eq (car rr) 'in-mode)
9329 (string-match (cdr rr) (symbol-name major-mode)))
9330 (and (eq (car rr) 'in-buffer)
9331 (string-match (cdr rr) (buffer-name)))
9332 (when (and (eq (car rr) 'not-in-file)
9333 (buffer-file-name))
9334 (not (string-match (cdr rr) (buffer-file-name))))
9335 (when (eq (car rr) 'not-in-mode)
9336 (not (string-match (cdr rr) (symbol-name major-mode))))
9337 (when (eq (car rr) 'not-in-buffer)
9338 (not (string-match (cdr rr) (buffer-name)))))))
9339 (push r res)))
9340 (car (last r))))
9341 (delete-dups (delq nil res))))
9343 (defun org-context-p (&rest contexts)
9344 "Check if local context is any of CONTEXTS.
9345 Possible values in the list of contexts are `table', `headline', and `item'."
9346 (let ((pos (point)))
9347 (goto-char (point-at-bol))
9348 (prog1 (or (and (memq 'table contexts)
9349 (looking-at "[ \t]*|"))
9350 (and (memq 'headline contexts)
9351 (looking-at org-outline-regexp))
9352 (and (memq 'item contexts)
9353 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9354 (and (memq 'item-body contexts)
9355 (org-in-item-p)))
9356 (goto-char pos))))
9358 (defun org-get-local-variables ()
9359 "Return a list of all local variables in an Org mode buffer."
9360 (let (varlist)
9361 (with-current-buffer (get-buffer-create "*Org tmp*")
9362 (erase-buffer)
9363 (org-mode)
9364 (setq varlist (buffer-local-variables)))
9365 (kill-buffer "*Org tmp*")
9366 (delq nil
9367 (mapcar
9368 (lambda (x)
9369 (setq x
9370 (if (symbolp x)
9371 (list x)
9372 (list (car x) (cdr x))))
9373 (if (and (not (get (car x) 'org-state))
9374 (string-match
9375 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9376 (symbol-name (car x))))
9377 x nil))
9378 varlist))))
9380 (defun org-clone-local-variables (from-buffer &optional regexp)
9381 "Clone local variables from FROM-BUFFER.
9382 Optional argument REGEXP selects variables to clone."
9383 (mapc
9384 (lambda (pair)
9385 (and (symbolp (car pair))
9386 (or (null regexp)
9387 (string-match regexp (symbol-name (car pair))))
9388 (set (make-local-variable (car pair))
9389 (cdr pair))))
9390 (buffer-local-variables from-buffer)))
9392 ;;;###autoload
9393 (defun org-run-like-in-org-mode (cmd)
9394 "Run a command, pretending that the current buffer is in Org-mode.
9395 This will temporarily bind local variables that are typically bound in
9396 Org-mode to the values they have in Org-mode, and then interactively
9397 call CMD."
9398 (org-load-modules-maybe)
9399 (unless org-local-vars
9400 (setq org-local-vars (org-get-local-variables)))
9401 (let (binds)
9402 (dolist (var org-local-vars)
9403 (when (or (not (boundp (car var)))
9404 (eq (symbol-value (car var))
9405 (default-value (car var))))
9406 (push (list (car var) `(quote ,(cadr var))) binds)))
9407 (eval `(let ,binds
9408 (call-interactively (quote ,cmd))))))
9410 (defun org-get-category (&optional pos force-refresh)
9411 "Get the category applying to position POS."
9412 (save-match-data
9413 (if force-refresh (org-refresh-category-properties))
9414 (let ((pos (or pos (point))))
9415 (or (get-text-property pos 'org-category)
9416 (progn (org-refresh-category-properties)
9417 (get-text-property pos 'org-category))))))
9419 ;;; Refresh properties
9421 (defun org-refresh-properties (dprop tprop)
9422 "Refresh buffer text properties.
9423 DPROP is the drawer property and TPROP is either the
9424 corresponding text property to set, or an alist with each element
9425 being a text property (as a symbol) and a function to apply to
9426 the value of the drawer property."
9427 (let ((case-fold-search t)
9428 (inhibit-read-only t))
9429 (org-with-silent-modifications
9430 (save-excursion
9431 (save-restriction
9432 (widen)
9433 (goto-char (point-min))
9434 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9435 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9437 (defun org-refresh-property (tprop p)
9438 "Refresh the buffer text property TPROP from the drawer property P.
9439 The refresh happens only for the current tree (not subtree)."
9440 (save-excursion
9441 (org-back-to-heading t)
9442 ;; tprop is a text property symbol
9443 (if (symbolp tprop)
9444 (put-text-property
9445 (point) (or (outline-next-heading) (point-max)) tprop p)
9446 ;; tprop is an alist with (properties . function) elements
9447 (mapc (lambda(al)
9448 (save-excursion
9449 (put-text-property
9450 (point-at-bol) (or (outline-next-heading) (point-max))
9451 (car al)
9452 (funcall (cdr al) p))))
9453 tprop))))
9455 (defun org-refresh-category-properties ()
9456 "Refresh category text properties in the buffer."
9457 (let ((case-fold-search t)
9458 (inhibit-read-only t)
9459 (def-cat (cond
9460 ((null org-category)
9461 (if buffer-file-name
9462 (file-name-sans-extension
9463 (file-name-nondirectory buffer-file-name))
9464 "???"))
9465 ((symbolp org-category) (symbol-name org-category))
9466 (t org-category)))
9467 beg end cat pos optionp)
9468 (org-with-silent-modifications
9469 (save-excursion
9470 (save-restriction
9471 (widen)
9472 (goto-char (point-min))
9473 (put-text-property (point) (point-max) 'org-category def-cat)
9474 (while (re-search-forward
9475 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9476 (setq pos (match-end 0)
9477 optionp (equal (char-after (match-beginning 0)) ?#)
9478 cat (org-trim (match-string 2)))
9479 (if optionp
9480 (setq beg (point-at-bol) end (point-max))
9481 (org-back-to-heading t)
9482 (setq beg (point) end (org-end-of-subtree t t)))
9483 (put-text-property beg end 'org-category cat)
9484 (goto-char pos)))))))
9486 (defun org-refresh-stats-properties ()
9487 "Refresh stats text properties in the buffer."
9488 (let (stats)
9489 (org-with-silent-modifications
9490 (save-excursion
9491 (save-restriction
9492 (widen)
9493 (goto-char (point-min))
9494 (while (re-search-forward
9495 (concat org-outline-regexp-bol ".*"
9496 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9497 nil t)
9498 (setq stats (cond ((equal (match-string 3) "0") 0)
9499 ((match-string 2)
9500 (/ (* (string-to-number (match-string 2)) 100)
9501 (string-to-number (match-string 3))))
9502 (t (string-to-number (match-string 1)))))
9503 (org-back-to-heading t)
9504 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9505 'org-stats stats)))))))
9507 (defun org-refresh-effort-properties ()
9508 "Refresh effort properties"
9509 (org-refresh-properties
9510 org-effort-property
9511 '((effort . identity)
9512 (effort-minutes . org-duration-string-to-minutes))))
9514 ;;;; Link Stuff
9516 ;;; Link abbreviations
9518 (defun org-link-expand-abbrev (link)
9519 "Apply replacements as defined in `org-link-abbrev-alist'."
9520 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9521 (let* ((key (match-string 1 link))
9522 (as (or (assoc key org-link-abbrev-alist-local)
9523 (assoc key org-link-abbrev-alist)))
9524 (tag (and (match-end 2) (match-string 3 link)))
9525 rpl)
9526 (if (not as)
9527 link
9528 (setq rpl (cdr as))
9529 (cond
9530 ((symbolp rpl) (funcall rpl tag))
9531 ((string-match "%(\\([^)]+\\))" rpl)
9532 (replace-match
9533 (save-match-data
9534 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9535 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9536 ((string-match "%h" rpl)
9537 (replace-match (url-hexify-string (or tag "")) t t rpl))
9538 (t (concat rpl tag)))))
9539 link))
9541 ;;; Storing and inserting links
9543 (defvar org-insert-link-history nil
9544 "Minibuffer history for links inserted with `org-insert-link'.")
9546 (defvar org-stored-links nil
9547 "Contains the links stored with `org-store-link'.")
9549 (defvar org-store-link-plist nil
9550 "Plist with info about the most recently link created with `org-store-link'.")
9552 (defvar org-link-protocols nil
9553 "Link protocols added to Org-mode using `org-add-link-type'.")
9555 (defvar org-store-link-functions nil
9556 "List of functions that are called to create and store a link.
9557 Each function will be called in turn until one returns a non-nil
9558 value. Each function should check if it is responsible for creating
9559 this link (for example by looking at the major mode).
9560 If not, it must exit and return nil.
9561 If yes, it should return a non-nil value after a calling
9562 `org-store-link-props' with a list of properties and values.
9563 Special properties are:
9565 :type The link prefix, like \"http\". This must be given.
9566 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9567 This is obligatory as well.
9568 :description Optional default description for the second pair
9569 of brackets in an Org-mode link. The user can still change
9570 this when inserting this link into an Org-mode buffer.
9572 In addition to these, any additional properties can be specified
9573 and then used in capture templates.")
9575 (defun org-add-link-type (type &optional follow export)
9576 "Add TYPE to the list of `org-link-types'.
9577 Re-compute all regular expressions depending on `org-link-types'
9579 FOLLOW and EXPORT are two functions.
9581 FOLLOW should take the link path as the single argument and do whatever
9582 is necessary to follow the link, for example find a file or display
9583 a mail message.
9585 EXPORT should format the link path for export to one of the export formats.
9586 It should be a function accepting three arguments:
9588 path the path of the link, the text after the prefix (like \"http:\")
9589 desc the description of the link, if any, or a description added by
9590 org-export-normalize-links if there is none
9591 format the export format, a symbol like `html' or `latex' or `ascii'..
9593 The function may use the FORMAT information to return different values
9594 depending on the format. The return value will be put literally into
9595 the exported file. If the return value is nil, this means Org should
9596 do what it normally does with links which do not have EXPORT defined.
9598 Org-mode has a built-in default for exporting links. If you are happy with
9599 this default, there is no need to define an export function for the link
9600 type. For a simple example of an export function, see `org-bbdb.el'."
9601 (add-to-list 'org-link-types type t)
9602 (org-make-link-regexps)
9603 (if (assoc type org-link-protocols)
9604 (setcdr (assoc type org-link-protocols) (list follow export))
9605 (push (list type follow export) org-link-protocols)))
9607 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9608 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9610 ;;;###autoload
9611 (defun org-store-link (arg)
9612 "\\<org-mode-map>Store an org-link to the current location.
9613 This link is added to `org-stored-links' and can later be inserted
9614 into an org-buffer with \\[org-insert-link].
9616 For some link types, a prefix arg is interpreted.
9617 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9618 For file links, arg negates `org-context-in-file-links'.
9620 A double prefix arg force skipping storing functions that are not
9621 part of Org's core.
9623 A triple prefix arg force storing a link for each line in the
9624 active region."
9625 (interactive "P")
9626 (org-load-modules-maybe)
9627 (if (and (equal arg '(64)) (org-region-active-p))
9628 (save-excursion
9629 (let ((end (region-end)))
9630 (goto-char (region-beginning))
9631 (set-mark (point))
9632 (while (< (point-at-eol) end)
9633 (move-end-of-line 1) (activate-mark)
9634 (let (current-prefix-arg)
9635 (call-interactively 'org-store-link))
9636 (move-beginning-of-line 2)
9637 (set-mark (point)))))
9638 (org-with-limited-levels
9639 (setq org-store-link-plist nil)
9640 (let (link cpltxt desc description search
9641 txt custom-id agenda-link sfuns sfunsn)
9642 (cond
9644 ;; Store a link using an external link type
9645 ((and (not (equal arg '(16)))
9646 (setq sfuns
9647 (delq
9648 nil (mapcar (lambda (f)
9649 (let (fs) (if (funcall f) (push f fs))))
9650 org-store-link-functions))
9651 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9652 (or (and (cdr sfuns)
9653 (funcall (intern
9654 (completing-read
9655 "Which function for creating the link? "
9656 sfunsn nil t (car sfunsn)))))
9657 (funcall (caar sfuns)))
9658 (setq link (plist-get org-store-link-plist :link)
9659 desc (or (plist-get org-store-link-plist
9660 :description) link))))
9662 ;; Store a link from a source code buffer
9663 ((org-src-edit-buffer-p)
9664 (let (label gc)
9665 (while (or (not label)
9666 (save-excursion
9667 (save-restriction
9668 (widen)
9669 (goto-char (point-min))
9670 (re-search-forward
9671 (regexp-quote (format org-coderef-label-format label))
9672 nil t))))
9673 (when label (message "Label exists already") (sit-for 2))
9674 (setq label (read-string "Code line label: " label)))
9675 (end-of-line 1)
9676 (setq link (format org-coderef-label-format label))
9677 (setq gc (- 79 (length link)))
9678 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9679 (insert link)
9680 (setq link (concat "(" label ")") desc nil)))
9682 ;; We are in the agenda, link to referenced location
9683 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9684 (let ((m (or (get-text-property (point) 'org-hd-marker)
9685 (get-text-property (point) 'org-marker))))
9686 (when m
9687 (org-with-point-at m
9688 (setq agenda-link
9689 (if (org-called-interactively-p 'any)
9690 (call-interactively 'org-store-link)
9691 (org-store-link nil)))))))
9693 ((eq major-mode 'calendar-mode)
9694 (let ((cd (calendar-cursor-to-date)))
9695 (setq link
9696 (format-time-string
9697 (car org-time-stamp-formats)
9698 (apply 'encode-time
9699 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9700 nil nil nil))))
9701 (org-store-link-props :type "calendar" :date cd)))
9703 ((eq major-mode 'help-mode)
9704 (setq link (concat "help:" (save-excursion
9705 (goto-char (point-min))
9706 (looking-at "^[^ ]+")
9707 (match-string 0))))
9708 (org-store-link-props :type "help"))
9710 ((eq major-mode 'w3-mode)
9711 (setq cpltxt (if (and (buffer-name)
9712 (not (string-match "Untitled" (buffer-name))))
9713 (buffer-name)
9714 (url-view-url t))
9715 link (url-view-url t))
9716 (org-store-link-props :type "w3" :url (url-view-url t)))
9718 ((eq major-mode 'image-mode)
9719 (setq cpltxt (concat "file:"
9720 (abbreviate-file-name buffer-file-name))
9721 link cpltxt)
9722 (org-store-link-props :type "image" :file buffer-file-name))
9724 ;; In dired, store a link to the file of the current line
9725 ((derived-mode-p 'dired-mode)
9726 (let ((file (dired-get-filename nil t)))
9727 (setq file (if file
9728 (abbreviate-file-name
9729 (expand-file-name (dired-get-filename nil t)))
9730 ;; otherwise, no file so use current directory.
9731 default-directory))
9732 (setq cpltxt (concat "file:" file)
9733 link cpltxt)))
9735 ((setq search (run-hook-with-args-until-success
9736 'org-create-file-search-functions))
9737 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9738 "::" search))
9739 (setq cpltxt (or description link)))
9741 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9742 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9743 (cond
9744 ;; Store a link using the target at point
9745 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9746 (setq cpltxt
9747 (concat "file:"
9748 (abbreviate-file-name
9749 (buffer-file-name (buffer-base-buffer)))
9750 "::" (match-string 1))
9751 link cpltxt))
9752 ((and (featurep 'org-id)
9753 (or (eq org-id-link-to-org-use-id t)
9754 (and (org-called-interactively-p 'any)
9755 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9756 (and (eq org-id-link-to-org-use-id
9757 'create-if-interactive-and-no-custom-id)
9758 (not custom-id))))
9759 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9760 ;; Store a link using the ID at point
9761 (setq link (condition-case nil
9762 (prog1 (org-id-store-link)
9763 (setq desc (or (plist-get org-store-link-plist
9764 :description)
9765 "")))
9766 (error
9767 ;; Probably before first headline, link only to file
9768 (concat "file:"
9769 (abbreviate-file-name
9770 (buffer-file-name (buffer-base-buffer))))))))
9772 ;; Just link to current headline
9773 (setq cpltxt (concat "file:"
9774 (abbreviate-file-name
9775 (buffer-file-name (buffer-base-buffer)))))
9776 ;; Add a context search string
9777 (when (org-xor org-context-in-file-links arg)
9778 (let* ((ee (org-element-at-point))
9779 (et (org-element-type ee))
9780 (ev (plist-get (cadr ee) :value))
9781 (ek (plist-get (cadr ee) :key))
9782 (eok (and (stringp ek) (string-match "name" ek))))
9783 (setq txt (cond
9784 ((org-at-heading-p) nil)
9785 ((and (eq et 'keyword) eok) ev)
9786 ((org-region-active-p)
9787 (buffer-substring (region-beginning) (region-end)))))
9788 (when (or (null txt) (string-match "\\S-" txt))
9789 (setq cpltxt
9790 (concat cpltxt "::"
9791 (condition-case nil
9792 (org-make-org-heading-search-string txt)
9793 (error "")))
9794 desc (or (and (eq et 'keyword) eok ev)
9795 (nth 4 (ignore-errors (org-heading-components)))
9796 "NONE")))))
9797 (if (string-match "::\\'" cpltxt)
9798 (setq cpltxt (substring cpltxt 0 -2)))
9799 (setq link cpltxt))))
9801 ((buffer-file-name (buffer-base-buffer))
9802 ;; Just link to this file here.
9803 (setq cpltxt (concat "file:"
9804 (abbreviate-file-name
9805 (buffer-file-name (buffer-base-buffer)))))
9806 ;; Add a context string.
9807 (when (org-xor org-context-in-file-links arg)
9808 (setq txt (if (org-region-active-p)
9809 (buffer-substring (region-beginning) (region-end))
9810 (buffer-substring (point-at-bol) (point-at-eol))))
9811 ;; Only use search option if there is some text.
9812 (when (string-match "\\S-" txt)
9813 (setq cpltxt
9814 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9815 desc "NONE")))
9816 (setq link cpltxt))
9818 ((org-called-interactively-p 'interactive)
9819 (user-error "No method for storing a link from this buffer"))
9821 (t (setq link nil)))
9823 ;; We're done setting link and desc, clean up
9824 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9825 (setq link (or link cpltxt)
9826 desc (or desc cpltxt))
9827 (cond ((equal desc "NONE") (setq desc nil))
9828 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9829 (let ((d0 (match-string 3 desc))
9830 (p0 (match-string 5 desc)))
9831 (setq desc
9832 (replace-regexp-in-string
9833 org-bracket-link-regexp
9834 (concat (or p0 d0)
9835 (if (equal (length (match-string 0 desc))
9836 (length desc)) "*" "")) desc)))))
9838 ;; Return the link
9839 (if (not (and (or (org-called-interactively-p 'any)
9840 executing-kbd-macro) link))
9841 (or agenda-link (and link (org-make-link-string link desc)))
9842 (push (list link desc) org-stored-links)
9843 (message "Stored: %s" (or desc link))
9844 (when custom-id
9845 (setq link (concat "file:" (abbreviate-file-name
9846 (buffer-file-name)) "::#" custom-id))
9847 (push (list link desc) org-stored-links))
9848 (car org-stored-links))))))
9850 (defun org-store-link-props (&rest plist)
9851 "Store link properties, extract names and addresses."
9852 (let (x adr)
9853 (when (setq x (plist-get plist :from))
9854 (setq adr (mail-extract-address-components x))
9855 (setq plist (plist-put plist :fromname (car adr)))
9856 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9857 (when (setq x (plist-get plist :to))
9858 (setq adr (mail-extract-address-components x))
9859 (setq plist (plist-put plist :toname (car adr)))
9860 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9861 (let ((from (plist-get plist :from))
9862 (to (plist-get plist :to)))
9863 (when (and from to org-from-is-user-regexp)
9864 (setq plist
9865 (plist-put plist :fromto
9866 (if (string-match org-from-is-user-regexp from)
9867 (concat "to %t")
9868 (concat "from %f"))))))
9869 (setq org-store-link-plist plist))
9871 (defun org-add-link-props (&rest plist)
9872 "Add these properties to the link property list."
9873 (let (key value)
9874 (while plist
9875 (setq key (pop plist) value (pop plist))
9876 (setq org-store-link-plist
9877 (plist-put org-store-link-plist key value)))))
9879 (defun org-email-link-description (&optional fmt)
9880 "Return the description part of an email link.
9881 This takes information from `org-store-link-plist' and formats it
9882 according to FMT (default from `org-email-link-description-format')."
9883 (setq fmt (or fmt org-email-link-description-format))
9884 (let* ((p org-store-link-plist)
9885 (to (plist-get p :toaddress))
9886 (from (plist-get p :fromaddress))
9887 (table
9888 (list
9889 (cons "%c" (plist-get p :fromto))
9890 (cons "%F" (plist-get p :from))
9891 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9892 (cons "%T" (plist-get p :to))
9893 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9894 (cons "%s" (plist-get p :subject))
9895 (cons "%d" (plist-get p :date))
9896 (cons "%m" (plist-get p :message-id)))))
9897 (when (string-match "%c" fmt)
9898 ;; Check if the user wrote this message
9899 (if (and org-from-is-user-regexp from to
9900 (save-match-data (string-match org-from-is-user-regexp from)))
9901 (setq fmt (replace-match "to %t" t t fmt))
9902 (setq fmt (replace-match "from %f" t t fmt))))
9903 (org-replace-escapes fmt table)))
9905 (defun org-make-org-heading-search-string (&optional string)
9906 "Make search string for the current headline or STRING."
9907 (let ((s (or string
9908 (and (derived-mode-p 'org-mode)
9909 (save-excursion
9910 (org-back-to-heading t)
9911 (org-element-property :raw-value (org-element-at-point))))))
9912 (lines org-context-in-file-links))
9913 (or string (setq s (concat "*" s))) ; Add * for headlines
9914 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9915 (when (and string (integerp lines) (> lines 0))
9916 (let ((slines (org-split-string s "\n")))
9917 (when (< lines (length slines))
9918 (setq s (mapconcat
9919 'identity
9920 (reverse (nthcdr (- (length slines) lines)
9921 (reverse slines))) "\n")))))
9922 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9924 (defun org-make-link-string (link &optional description)
9925 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9926 (unless (string-match "\\S-" link)
9927 (error "Empty link"))
9928 (when (and description
9929 (stringp description)
9930 (not (string-match "\\S-" description)))
9931 (setq description nil))
9932 (when (stringp description)
9933 ;; Remove brackets from the description, they are fatal.
9934 (while (string-match "\\[" description)
9935 (setq description (replace-match "{" t t description)))
9936 (while (string-match "\\]" description)
9937 (setq description (replace-match "}" t t description))))
9938 (when (equal link description)
9939 ;; No description needed, it is identical
9940 (setq description nil))
9941 (when (and (not description)
9942 (not (string-match (org-image-file-name-regexp) link))
9943 (not (equal link (org-link-escape link))))
9944 (setq description (org-extract-attributes link)))
9945 (setq link
9946 (cond ((string-match (org-image-file-name-regexp) link) link)
9947 ((string-match org-link-types-re link)
9948 (concat (match-string 1 link)
9949 (org-link-escape (substring link (match-end 1)))))
9950 (t (org-link-escape link))))
9951 (concat "[[" link "]"
9952 (if description (concat "[" description "]") "")
9953 "]"))
9955 (defconst org-link-escape-chars
9956 ;;%20 %5B %5D
9957 '(?\ ?\[ ?\])
9958 "List of characters that should be escaped in a link when stored to Org.
9959 This is the list that is used for internal purposes.")
9961 (defconst org-link-escape-chars-browser
9962 ;;%20 %22
9963 '(?\ ?\")
9964 "List of characters to be escaped before handing over to the browser.
9965 If you consider using this constant then you probably want to use
9966 the function `org-link-escape-browser' instead. See there why
9967 this constant is a candidate to be removed once Org drops support
9968 for Emacs 24.1 and 24.2.")
9970 (defun org-link-escape (text &optional table merge)
9971 "Return percent escaped representation of TEXT.
9972 TEXT is a string with the text to escape.
9973 Optional argument TABLE is a list with characters that should be
9974 escaped. When nil, `org-link-escape-chars' is used.
9975 If optional argument MERGE is set, merge TABLE into
9976 `org-link-escape-chars'."
9977 ;; Don't escape chars in internal links
9978 (if (string-match "^\\*[[:alnum:]]+" text)
9979 text
9980 (cond
9981 ((and table merge)
9982 (mapc (lambda (defchr)
9983 (unless (member defchr table)
9984 (setq table (cons defchr table))))
9985 org-link-escape-chars))
9986 ((null table)
9987 (setq table org-link-escape-chars)))
9988 (mapconcat
9989 (lambda (char)
9990 (if (or (member char table)
9991 (and (or (< char 32) (= char ?\%) (> char 126))
9992 org-url-hexify-p))
9993 (mapconcat (lambda (sequence-element)
9994 (format "%%%.2X" sequence-element))
9995 (or (encode-coding-char char 'utf-8)
9996 (error "Unable to percent escape character: %s"
9997 (char-to-string char))) "")
9998 (char-to-string char))) text "")))
10000 (defun org-link-escape-browser (text)
10001 "Escape some characters before handing over to the browser.
10002 This function is a candidate to be removed together with the
10003 constant `org-link-escape-chars-browser' once Org drops support
10004 for Emacs 24.1 and 24.2. All calls to this function will have to
10005 be replaced with `url-encode-url' which is available since Emacs
10006 24.3.1."
10007 ;; Example with the Org link
10008 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10009 ;; to open the browser with +subject:"Release 8.2" filled into the
10010 ;; query field: In this case the variable TEXT contains the
10011 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10012 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10013 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10014 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10015 (if (fboundp 'url-encode-url)
10016 (url-encode-url text)
10017 (if (org-string-match-p
10018 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10019 text)
10020 (org-link-escape text org-link-escape-chars-browser)
10021 text)))
10023 (defun org-link-unescape (str)
10024 "Unhex hexified Unicode strings as returned from the JavaScript function
10025 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10026 (unless (and (null str) (string= "" str))
10027 (let ((pos 0) (case-fold-search t) unhexed)
10028 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10029 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10030 (setq str (replace-match unhexed t t str))
10031 (setq pos (+ pos (length unhexed))))))
10032 str)
10034 (defun org-link-unescape-compound (hex)
10035 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10036 Note: this function also decodes single byte encodings like
10037 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10038 (save-match-data
10039 (let* ((bytes (cdr (split-string hex "%")))
10040 (ret "")
10041 (eat 0)
10042 (sum 0))
10043 (while bytes
10044 (let* ((val (string-to-number (pop bytes) 16))
10045 (shift-xor
10046 (if (= 0 eat)
10047 (cond
10048 ((>= val 252) (cons 6 252))
10049 ((>= val 248) (cons 5 248))
10050 ((>= val 240) (cons 4 240))
10051 ((>= val 224) (cons 3 224))
10052 ((>= val 192) (cons 2 192))
10053 (t (cons 0 0)))
10054 (cons 6 128))))
10055 (if (>= val 192) (setq eat (car shift-xor)))
10056 (setq val (logxor val (cdr shift-xor)))
10057 (setq sum (+ (lsh sum (car shift-xor)) val))
10058 (if (> eat 0) (setq eat (- eat 1)))
10059 (cond
10060 ((= 0 eat) ;multi byte
10061 (setq ret (concat ret (org-char-to-string sum)))
10062 (setq sum 0))
10063 ((not bytes) ; single byte(s)
10064 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10065 ret)))
10067 (defun org-link-unescape-single-byte-sequence (hex)
10068 "Unhexify hex-encoded single byte character sequences."
10069 (mapconcat (lambda (byte)
10070 (char-to-string (string-to-number byte 16)))
10071 (cdr (split-string hex "%")) ""))
10073 (defun org-xor (a b)
10074 "Exclusive or."
10075 (if a (not b) b))
10077 (defun org-fixup-message-id-for-http (s)
10078 "Replace special characters in a message id, so it can be used in an http query."
10079 (when (string-match "%" s)
10080 (setq s (mapconcat (lambda (c)
10081 (if (eq c ?%)
10082 "%25"
10083 (char-to-string c)))
10084 s "")))
10085 (while (string-match "<" s)
10086 (setq s (replace-match "%3C" t t s)))
10087 (while (string-match ">" s)
10088 (setq s (replace-match "%3E" t t s)))
10089 (while (string-match "@" s)
10090 (setq s (replace-match "%40" t t s)))
10093 (defun org-link-prettify (link)
10094 "Return a human-readable representation of LINK.
10095 The car of LINK must be a raw link.
10096 The cdr of LINK must be either a link description or nil."
10097 (let ((desc (or (cadr link) "<no description>")))
10098 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10099 "<" (car link) ">")))
10101 ;;;###autoload
10102 (defun org-insert-link-global ()
10103 "Insert a link like Org-mode does.
10104 This command can be called in any mode to insert a link in Org-mode syntax."
10105 (interactive)
10106 (org-load-modules-maybe)
10107 (org-run-like-in-org-mode 'org-insert-link))
10109 (defun org-insert-all-links (arg &optional pre post)
10110 "Insert all links in `org-stored-links'.
10111 When a universal prefix, do not delete the links from `org-stored-links'.
10112 When `ARG' is a number, insert the last N link(s).
10113 `PRE' and `POST' are optional arguments to define a string to
10114 prepend or to append."
10115 (interactive "P")
10116 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10117 (links (copy-seq org-stored-links))
10118 (pr (or pre "- "))
10119 (po (or post "\n"))
10120 (cnt 1) l)
10121 (if (null org-stored-links)
10122 (message "No link to insert")
10123 (while (and (or (listp arg) (>= arg cnt))
10124 (setq l (if (listp arg)
10125 (pop links)
10126 (pop org-stored-links))))
10127 (setq cnt (1+ cnt))
10128 (insert pr)
10129 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10130 (insert po)))))
10132 (defun org-insert-last-stored-link (arg)
10133 "Insert the last link stored in `org-stored-links'."
10134 (interactive "p")
10135 (org-insert-all-links arg "" "\n"))
10137 (defun org-link-fontify-links-to-this-file ()
10138 "Fontify links to the current file in `org-stored-links'."
10139 (let ((f (buffer-file-name)) a b)
10140 (setq a (mapcar (lambda(l)
10141 (let ((ll (car l)))
10142 (when (and (string-match "^file:\\(.+\\)::" ll)
10143 (equal f (expand-file-name (match-string 1 ll))))
10144 ll)))
10145 org-stored-links))
10146 (when (featurep 'org-id)
10147 (setq b (mapcar (lambda(l)
10148 (let ((ll (car l)))
10149 (when (and (string-match "^id:\\(.+\\)$" ll)
10150 (equal f (expand-file-name
10151 (or (org-id-find-id-file
10152 (match-string 1 ll)) ""))))
10153 ll)))
10154 org-stored-links)))
10155 (mapcar (lambda(l)
10156 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10157 (delq nil (append a b)))))
10159 (defvar org-link-links-in-this-file nil)
10160 (defun org-insert-link (&optional complete-file link-location default-description)
10161 "Insert a link. At the prompt, enter the link.
10163 Completion can be used to insert any of the link protocol prefixes like
10164 http or ftp in use.
10166 The history can be used to select a link previously stored with
10167 `org-store-link'. When the empty string is entered (i.e. if you just
10168 press RET at the prompt), the link defaults to the most recently
10169 stored link. As SPC triggers completion in the minibuffer, you need to
10170 use M-SPC or C-q SPC to force the insertion of a space character.
10172 You will also be prompted for a description, and if one is given, it will
10173 be displayed in the buffer instead of the link.
10175 If there is already a link at point, this command will allow you to edit link
10176 and description parts.
10178 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10179 be selected using completion. The path to the file will be relative to the
10180 current directory if the file is in the current directory or a subdirectory.
10181 Otherwise, the link will be the absolute path as completed in the minibuffer
10182 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10183 option `org-link-file-path-type'.
10185 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10186 the current directory or below.
10188 With three \\[universal-argument] prefixes, negate the meaning of
10189 `org-keep-stored-link-after-insertion'.
10191 If `org-make-link-description-function' is non-nil, this function will be
10192 called with the link target, and the result will be the default
10193 link description.
10195 If the LINK-LOCATION parameter is non-nil, this value will be
10196 used as the link location instead of reading one interactively.
10198 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10199 be used as the default description."
10200 (interactive "P")
10201 (let* ((wcf (current-window-configuration))
10202 (origbuf (current-buffer))
10203 (region (if (org-region-active-p)
10204 (buffer-substring (region-beginning) (region-end))))
10205 (remove (and region (list (region-beginning) (region-end))))
10206 (desc region)
10207 tmphist ; byte-compile incorrectly complains about this
10208 (link link-location)
10209 (abbrevs org-link-abbrev-alist-local)
10210 entry file all-prefixes auto-desc)
10211 (cond
10212 (link-location) ; specified by arg, just use it.
10213 ((org-in-regexp org-bracket-link-regexp 1)
10214 ;; We do have a link at point, and we are going to edit it.
10215 (setq remove (list (match-beginning 0) (match-end 0)))
10216 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10217 (setq link (read-string "Link: "
10218 (org-link-unescape
10219 (org-match-string-no-properties 1)))))
10220 ((or (org-in-regexp org-angle-link-re)
10221 (org-in-regexp org-plain-link-re))
10222 ;; Convert to bracket link
10223 (setq remove (list (match-beginning 0) (match-end 0))
10224 link (read-string "Link: "
10225 (org-remove-angle-brackets (match-string 0)))))
10226 ((member complete-file '((4) (16)))
10227 ;; Completing read for file names.
10228 (setq link (org-file-complete-link complete-file)))
10230 ;; Read link, with completion for stored links.
10231 (org-link-fontify-links-to-this-file)
10232 (org-switch-to-buffer-other-window "*Org Links*")
10233 (with-current-buffer "*Org Links*"
10234 (erase-buffer)
10235 (insert "Insert a link.
10236 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10237 (when org-stored-links
10238 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10239 (insert (mapconcat 'org-link-prettify
10240 (reverse org-stored-links) "\n")))
10241 (goto-char (point-min)))
10242 (let ((cw (selected-window)))
10243 (select-window (get-buffer-window "*Org Links*" 'visible))
10244 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10245 (unless (pos-visible-in-window-p (point-max))
10246 (org-fit-window-to-buffer))
10247 (and (window-live-p cw) (select-window cw)))
10248 ;; Fake a link history, containing the stored links.
10249 (setq tmphist (append (mapcar 'car org-stored-links)
10250 org-insert-link-history))
10251 (setq all-prefixes (append (mapcar 'car abbrevs)
10252 (mapcar 'car org-link-abbrev-alist)
10253 org-link-types))
10254 (unwind-protect
10255 (progn
10256 (setq link
10257 (org-completing-read
10258 "Link: "
10259 (append
10260 (mapcar (lambda (x) (concat x ":"))
10261 all-prefixes)
10262 (mapcar 'car org-stored-links))
10263 nil nil nil
10264 'tmphist
10265 (caar org-stored-links)))
10266 (if (not (string-match "\\S-" link))
10267 (user-error "No link selected"))
10268 (mapc (lambda(l)
10269 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10270 org-stored-links)
10271 (if (or (member link all-prefixes)
10272 (and (equal ":" (substring link -1))
10273 (member (substring link 0 -1) all-prefixes)
10274 (setq link (substring link 0 -1))))
10275 (setq link (with-current-buffer origbuf
10276 (org-link-try-special-completion link)))))
10277 (set-window-configuration wcf)
10278 (kill-buffer "*Org Links*"))
10279 (setq entry (assoc link org-stored-links))
10280 (or entry (push link org-insert-link-history))
10281 (setq desc (or desc (nth 1 entry)))))
10283 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10284 (not org-keep-stored-link-after-insertion))
10285 (setq org-stored-links (delq (assoc link org-stored-links)
10286 org-stored-links)))
10288 (if (and (string-match org-plain-link-re link)
10289 (not (string-match org-ts-regexp link)))
10290 ;; URL-like link, normalize the use of angular brackets.
10291 (setq link (org-remove-angle-brackets link)))
10293 ;; Check if we are linking to the current file with a search
10294 ;; option If yes, simplify the link by using only the search
10295 ;; option.
10296 (when (and buffer-file-name
10297 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10298 (let* ((path (match-string 1 link))
10299 (case-fold-search nil)
10300 (search (match-string 2 link)))
10301 (save-match-data
10302 (if (equal (file-truename buffer-file-name) (file-truename path))
10303 ;; We are linking to this same file, with a search option
10304 (setq link search)))))
10306 ;; Check if we can/should use a relative path. If yes, simplify the link
10307 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10308 (let* ((type (match-string 1 link))
10309 (path (match-string 2 link))
10310 (origpath path)
10311 (case-fold-search nil))
10312 (cond
10313 ((or (eq org-link-file-path-type 'absolute)
10314 (equal complete-file '(16)))
10315 (setq path (abbreviate-file-name (expand-file-name path))))
10316 ((eq org-link-file-path-type 'noabbrev)
10317 (setq path (expand-file-name path)))
10318 ((eq org-link-file-path-type 'relative)
10319 (setq path (file-relative-name path)))
10321 (save-match-data
10322 (if (string-match (concat "^" (regexp-quote
10323 (expand-file-name
10324 (file-name-as-directory
10325 default-directory))))
10326 (expand-file-name path))
10327 ;; We are linking a file with relative path name.
10328 (setq path (substring (expand-file-name path)
10329 (match-end 0)))
10330 (setq path (abbreviate-file-name (expand-file-name path)))))))
10331 (setq link (concat type path))
10332 (if (equal desc origpath)
10333 (setq desc path))))
10335 (if org-make-link-description-function
10336 (setq desc
10337 (or (condition-case nil
10338 (funcall org-make-link-description-function link desc)
10339 (error (progn (message "Can't get link description from `%s'"
10340 (symbol-name org-make-link-description-function))
10341 (sit-for 2) nil)))
10342 (read-string "Description: " default-description)))
10343 (if default-description (setq desc default-description)
10344 (setq desc (or (and auto-desc desc)
10345 (read-string "Description: " desc)))))
10347 (unless (string-match "\\S-" desc) (setq desc nil))
10348 (if remove (apply 'delete-region remove))
10349 (insert (org-make-link-string link desc))))
10351 (defun org-link-try-special-completion (type)
10352 "If there is completion support for link type TYPE, offer it."
10353 (let ((fun (intern (concat "org-" type "-complete-link"))))
10354 (if (functionp fun)
10355 (funcall fun)
10356 (read-string "Link (no completion support): " (concat type ":")))))
10358 (defun org-file-complete-link (&optional arg)
10359 "Create a file link using completion."
10360 (let (file link)
10361 (setq file (org-iread-file-name "File: "))
10362 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10363 (pwd1 (file-name-as-directory (abbreviate-file-name
10364 (expand-file-name ".")))))
10365 (cond
10366 ((equal arg '(16))
10367 (setq link (concat
10368 "file:"
10369 (abbreviate-file-name (expand-file-name file)))))
10370 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10371 (setq link (concat "file:" (match-string 1 file))))
10372 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10373 (expand-file-name file))
10374 (setq link (concat
10375 "file:" (match-string 1 (expand-file-name file)))))
10376 (t (setq link (concat "file:" file)))))
10377 link))
10379 (defun org-iread-file-name (&rest args)
10380 "Read-file-name using `ido-mode' speedup if available.
10381 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10382 See `read-file-name' for a description of parameters."
10383 (org-without-partial-completion
10384 (if (and org-completion-use-ido
10385 (fboundp 'ido-read-file-name)
10386 (boundp 'ido-mode) ido-mode
10387 (listp (second args)))
10388 (let ((ido-enter-matching-directory nil))
10389 (apply 'ido-read-file-name args))
10390 (apply 'read-file-name args))))
10392 (defun org-completing-read (&rest args)
10393 "Completing-read with SPACE being a normal character."
10394 (let ((enable-recursive-minibuffers t)
10395 (minibuffer-local-completion-map
10396 (copy-keymap minibuffer-local-completion-map)))
10397 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10398 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10399 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10400 (apply 'org-icompleting-read args)))
10402 (defun org-completing-read-no-i (&rest args)
10403 (let (org-completion-use-ido org-completion-use-iswitchb)
10404 (apply 'org-completing-read args)))
10406 (defun org-iswitchb-completing-read (prompt choices &rest args)
10407 "Use iswitch as a completing-read replacement to choose from choices.
10408 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10409 from."
10410 (let* ((iswitchb-use-virtual-buffers nil)
10411 (iswitchb-make-buflist-hook
10412 (lambda ()
10413 (setq iswitchb-temp-buflist choices))))
10414 (iswitchb-read-buffer prompt)))
10416 (defun org-icompleting-read (&rest args)
10417 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10418 (org-without-partial-completion
10419 (if (and org-completion-use-ido
10420 (fboundp 'ido-completing-read)
10421 (boundp 'ido-mode) ido-mode
10422 (listp (second args)))
10423 (let ((ido-enter-matching-directory nil))
10424 (apply 'ido-completing-read (concat (car args))
10425 (if (consp (car (nth 1 args)))
10426 (mapcar 'car (nth 1 args))
10427 (nth 1 args))
10428 (cddr args)))
10429 (if (and org-completion-use-iswitchb
10430 (boundp 'iswitchb-mode) iswitchb-mode
10431 (listp (second args)))
10432 (apply 'org-iswitchb-completing-read (concat (car args))
10433 (if (consp (car (nth 1 args)))
10434 (mapcar 'car (nth 1 args))
10435 (nth 1 args))
10436 (cddr args))
10437 (apply 'completing-read args)))))
10439 (defun org-extract-attributes (s)
10440 "Extract the attributes cookie from a string and set as text property."
10441 (let (a attr (start 0) key value)
10442 (save-match-data
10443 (when (string-match "{{\\([^}]+\\)}}$" s)
10444 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10445 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10446 (setq key (match-string 1 a) value (match-string 2 a)
10447 start (match-end 0)
10448 attr (plist-put attr (intern key) value))))
10449 (org-add-props s nil 'org-attr attr))
10452 ;;; Opening/following a link
10454 (defvar org-link-search-failed nil)
10456 (defvar org-open-link-functions nil
10457 "Hook for functions finding a plain text link.
10458 These functions must take a single argument, the link content.
10459 They will be called for links that look like [[link text][description]]
10460 when LINK TEXT does not have a protocol like \"http:\" and does not look
10461 like a filename (e.g. \"./blue.png\").
10463 These functions will be called *before* Org attempts to resolve the
10464 link by doing text searches in the current buffer - so if you want a
10465 link \"[[target]]\" to still find \"<<target>>\", your function should
10466 handle this as a special case.
10468 When the function does handle the link, it must return a non-nil value.
10469 If it decides that it is not responsible for this link, it must return
10470 nil to indicate that that Org-mode can continue with other options
10471 like exact and fuzzy text search.")
10473 (defun org-next-link (&optional search-backward)
10474 "Move forward to the next link.
10475 If the link is in hidden text, expose it."
10476 (interactive "P")
10477 (when (and org-link-search-failed (eq this-command last-command))
10478 (goto-char (point-min))
10479 (message "Link search wrapped back to beginning of buffer"))
10480 (setq org-link-search-failed nil)
10481 (let* ((pos (point))
10482 (ct (org-context))
10483 (a (assoc :link ct))
10484 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10485 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10486 ((looking-at org-any-link-re)
10487 ;; Don't stay stuck at link without an org-link face
10488 (forward-char (if search-backward -1 1))))
10489 (if (funcall srch-fun org-any-link-re nil t)
10490 (progn
10491 (goto-char (match-beginning 0))
10492 (if (outline-invisible-p) (org-show-context)))
10493 (goto-char pos)
10494 (setq org-link-search-failed t)
10495 (message "No further link found"))))
10497 (defun org-previous-link ()
10498 "Move backward to the previous link.
10499 If the link is in hidden text, expose it."
10500 (interactive)
10501 (funcall 'org-next-link t))
10503 (defun org-translate-link (s)
10504 "Translate a link string if a translation function has been defined."
10505 (if (and org-link-translation-function
10506 (fboundp org-link-translation-function)
10507 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10508 (progn
10509 (setq s (funcall org-link-translation-function
10510 (match-string 1 s) (match-string 2 s)))
10511 (concat (car s) ":" (cdr s)))
10514 (defun org-translate-link-from-planner (type path)
10515 "Translate a link from Emacs Planner syntax so that Org can follow it.
10516 This is still an experimental function, your mileage may vary."
10517 (cond
10518 ((member type '("http" "https" "news" "ftp"))
10519 ;; standard Internet links are the same.
10520 nil)
10521 ((and (equal type "irc") (string-match "^//" path))
10522 ;; Planner has two / at the beginning of an irc link, we have 1.
10523 ;; We should have zero, actually....
10524 (setq path (substring path 1)))
10525 ((and (equal type "lisp") (string-match "^/" path))
10526 ;; Planner has a slash, we do not.
10527 (setq type "elisp" path (substring path 1)))
10528 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10529 ;; A typical message link. Planner has the id after the final slash,
10530 ;; we separate it with a hash mark
10531 (setq path (concat (match-string 1 path) "#"
10532 (org-remove-angle-brackets (match-string 2 path))))))
10533 (cons type path))
10535 (defun org-find-file-at-mouse (ev)
10536 "Open file link or URL at mouse."
10537 (interactive "e")
10538 (mouse-set-point ev)
10539 (org-open-at-point 'in-emacs))
10541 (defun org-open-at-mouse (ev)
10542 "Open file link or URL at mouse.
10543 See the docstring of `org-open-file' for details."
10544 (interactive "e")
10545 (mouse-set-point ev)
10546 (if (eq major-mode 'org-agenda-mode)
10547 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10548 (org-open-at-point))
10550 (defvar org-window-config-before-follow-link nil
10551 "The window configuration before following a link.
10552 This is saved in case the need arises to restore it.")
10554 (defvar org-open-link-marker (make-marker)
10555 "Marker pointing to the location where `org-open-at-point' was called.")
10557 ;;;###autoload
10558 (defun org-open-at-point-global ()
10559 "Follow a link like Org-mode does.
10560 This command can be called in any mode to follow a link that has
10561 Org-mode syntax."
10562 (interactive)
10563 (org-run-like-in-org-mode 'org-open-at-point))
10565 ;;;###autoload
10566 (defun org-open-link-from-string (s &optional arg reference-buffer)
10567 "Open a link in the string S, as if it was in Org-mode."
10568 (interactive "sLink: \nP")
10569 (let ((reference-buffer (or reference-buffer (current-buffer))))
10570 (with-temp-buffer
10571 (let ((org-inhibit-startup (not reference-buffer)))
10572 (org-mode)
10573 (insert s)
10574 (goto-char (point-min))
10575 (when reference-buffer
10576 (setq org-link-abbrev-alist-local
10577 (with-current-buffer reference-buffer
10578 org-link-abbrev-alist-local)))
10579 (org-open-at-point arg reference-buffer)))))
10581 (defvar org-open-at-point-functions nil
10582 "Hook that is run when following a link at point.
10584 Functions in this hook must return t if they identify and follow
10585 a link at point. If they don't find anything interesting at point,
10586 they must return nil.")
10588 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10589 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10590 (defun org-open-at-point (&optional arg reference-buffer)
10591 "Open link, timestamp, footnote or tags at point.
10593 When point is on a link, follow it. Normally, files will be
10594 opened by an appropriate application. If the optional prefix
10595 argument ARG is non-nil, Emacs will visit the file. With
10596 a double prefix argument, try to open outside of Emacs, in the
10597 application the system uses for this file type.
10599 When point is on a timestamp, open the agenda at the day
10600 specified.
10602 When point is a footnote definition, move to the first reference
10603 found. If it is on a reference, move to the associated
10604 definition.
10606 When point is on a headline, display a list of every link in the
10607 entry, so it is possible to pick one, or all, of them. If point
10608 is on a tag, call `org-tags-view' instead.
10610 When optional argument REFERENCE-BUFFER is non-nil, it should
10611 specify a buffer from where the link search should happen. This
10612 is used internally by `org-open-link-from-string'.
10614 On top of syntactically correct links, this function will open
10615 the link at point in comments or comment blocks and the first
10616 link in a property drawer line."
10617 (interactive "P")
10618 ;; On a code block, open block's results.
10619 (unless (call-interactively 'org-babel-open-src-block-result)
10620 (org-load-modules-maybe)
10621 (move-marker org-open-link-marker (point))
10622 (setq org-window-config-before-follow-link (current-window-configuration))
10623 (org-remove-occur-highlights nil nil t)
10624 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10625 (let* ((context (org-element-context)) type value)
10626 ;; On an unsupported type, check if point is contained within
10627 ;; a support one.
10628 (while (and (not (memq (setq type (org-element-type context))
10629 '(comment comment-block
10630 headline inlinetask link
10631 footnote-definition footnote-reference
10632 node-property timestamp)))
10633 (setq context (org-element-property :parent context))))
10634 (setq value (org-element-property :value context))
10635 (cond
10636 ;; Blank lines at the beginning of buffer: bail out.
10637 ((not context) (user-error "No link found"))
10638 ;; Exception n°1: links in property drawers
10639 ((eq type 'node-property)
10640 (org-open-link-from-string
10641 (and (string-match org-any-link-re value)
10642 (match-string-no-properties 0 value))))
10643 ;; Exception n°2: links in comments.
10644 ((memq type '(comment comment-block))
10645 (save-excursion
10646 (skip-chars-forward "\\S-" (point-at-eol))
10647 (let ((string-rear (replace-regexp-in-string
10648 "^[ \t]*# [ \t]*" ""
10649 (buffer-substring (point) (line-beginning-position))))
10650 (string-front (buffer-substring (point) (line-end-position))))
10651 (with-temp-buffer
10652 (let ((org-inhibit-startup t)) (org-mode))
10653 (insert value)
10654 (goto-char (point-min))
10655 (when (and (search-forward string-rear nil t)
10656 (search-forward string-front (line-end-position) t))
10657 (goto-char (match-beginning 0))
10658 (org-open-at-point)
10659 (when (string= string-rear "") (forward-char)))))))
10660 ;; On a headline or an inlinetask, but not on a timestamp,
10661 ;; a link, a footnote reference or on tags.
10662 ((and (memq type '(headline inlinetask))
10663 ;; Not on tags.
10664 (progn (save-excursion (beginning-of-line)
10665 (looking-at org-complex-heading-regexp))
10666 (or (not (match-beginning 5))
10667 (< (point) (match-beginning 5)))))
10668 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10669 (links (car data))
10670 (links-end (cdr data)))
10671 (if links
10672 (dolist (link (if (stringp links) (list links) links))
10673 (search-forward link nil links-end)
10674 (goto-char (match-beginning 0))
10675 (org-open-at-point))
10676 (require 'org-attach)
10677 (org-attach-reveal 'if-exists))))
10678 ;; Do nothing on white spaces after an object, unless point
10679 ;; is right after it.
10680 ((> (point)
10681 (save-excursion
10682 (goto-char (org-element-property :end context))
10683 (skip-chars-backward " \t")
10684 (point)))
10685 (user-error "No link found"))
10686 ((eq type 'timestamp) (org-follow-timestamp-link))
10687 ;; On tags within a headline or an inlinetask.
10688 ((and (memq type '(headline inlinetask))
10689 (progn (save-excursion (beginning-of-line)
10690 (looking-at org-complex-heading-regexp))
10691 (and (match-beginning 5)
10692 (>= (point) (match-beginning 5)))))
10693 (org-tags-view arg (substring (match-string 5) 0 -1)))
10694 ((eq type 'link)
10695 (let ((type (org-element-property :type context))
10696 (path (org-link-unescape (org-element-property :path context))))
10697 ;; Switch back to REFERENCE-BUFFER needed when called in
10698 ;; a temporary buffer through `org-open-link-from-string'.
10699 (with-current-buffer (or reference-buffer (current-buffer))
10700 (cond
10701 ((equal type "file")
10702 (if (string-match "[*?{]" (file-name-nondirectory path))
10703 (dired path)
10704 ;; Look into `org-link-protocols' in order to find
10705 ;; a DEDICATED-FUNCTION to open file. The function
10706 ;; will be applied on raw link instead of parsed
10707 ;; link due to the limitation in `org-add-link-type'
10708 ;; ("open" function called with a single argument).
10709 ;; If no such function is found, fallback to
10710 ;; `org-open-file'.
10712 ;; Note : "file+emacs" and "file+sys" types are
10713 ;; hard-coded in order to escape the previous
10714 ;; limitation.
10715 (let* ((option (org-element-property :search-option context))
10716 (app (org-element-property :application context))
10717 (dedicated-function
10718 (nth 1 (assoc app org-link-protocols))))
10719 (if dedicated-function
10720 (funcall dedicated-function
10721 (concat path
10722 (and option (concat "::" option))))
10723 (apply 'org-open-file
10724 path
10725 (cond (arg)
10726 ((equal app "emacs") 'emacs)
10727 ((equal app "sys") 'system))
10728 (cond ((not option) nil)
10729 ((org-string-match-p "\\`[0-9]+\\'" option)
10730 (list (string-to-number option)))
10731 (t (list nil
10732 (org-link-unescape option)))))))))
10733 ((assoc type org-link-protocols)
10734 (funcall (nth 1 (assoc type org-link-protocols)) path))
10735 ((equal type "help")
10736 (let ((f-or-v (intern path)))
10737 (cond ((fboundp f-or-v) (describe-function f-or-v))
10738 ((boundp f-or-v) (describe-variable f-or-v))
10739 (t (error "Not a known function or variable")))))
10740 ((member type '("http" "https" "ftp" "mailto" "news"))
10741 (browse-url (org-link-escape-browser (concat type ":" path))))
10742 ((equal type "doi")
10743 (browse-url
10744 (org-link-escape-browser (concat org-doi-server-url path))))
10745 ((equal type "message") (browse-url (concat type ":" path)))
10746 ((equal type "shell")
10747 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10748 (cmd path))
10749 (if (or (and (org-string-nw-p
10750 org-confirm-shell-link-not-regexp)
10751 (string-match
10752 org-confirm-shell-link-not-regexp cmd))
10753 (not org-confirm-shell-link-function)
10754 (funcall org-confirm-shell-link-function
10755 (format "Execute \"%s\" in shell? "
10756 (org-add-props cmd nil
10757 'face 'org-warning))))
10758 (progn
10759 (message "Executing %s" cmd)
10760 (shell-command cmd buf)
10761 (when (featurep 'midnight)
10762 (setq clean-buffer-list-kill-buffer-names
10763 (cons buf
10764 clean-buffer-list-kill-buffer-names))))
10765 (user-error "Abort"))))
10766 ((equal type "elisp")
10767 (let ((cmd path))
10768 (if (or (and (org-string-nw-p
10769 org-confirm-elisp-link-not-regexp)
10770 (org-string-match-p
10771 org-confirm-elisp-link-not-regexp cmd))
10772 (not org-confirm-elisp-link-function)
10773 (funcall org-confirm-elisp-link-function
10774 (format "Execute \"%s\" as elisp? "
10775 (org-add-props cmd nil
10776 'face 'org-warning))))
10777 (message "%s => %s" cmd
10778 (if (eq (string-to-char cmd) ?\()
10779 (eval (read cmd))
10780 (call-interactively (read cmd))))
10781 (user-error "Abort"))))
10782 ((equal type "id")
10783 (require 'ord-id)
10784 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10785 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10786 (unless (run-hook-with-args-until-success
10787 'org-open-link-functions path)
10788 (if (not arg) (org-mark-ring-push)
10789 (switch-to-buffer-other-window
10790 (org-get-buffer-for-internal-link (current-buffer))))
10791 (let ((cmd `(org-link-search
10792 ,(if (member type '("custom-id" "coderef"))
10793 (org-element-property :raw-link context)
10794 path)
10795 ,(cond ((equal arg '(4)) 'occur)
10796 ((equal arg '(16)) 'org-occur))
10797 ,(org-element-property :begin context))))
10798 (condition-case nil
10799 (let ((org-link-search-inhibit-query t))
10800 (eval cmd))
10801 (error (progn (widen) (eval cmd)))))))
10802 (t (browse-url-at-point))))))
10803 ;; On a footnote reference or at a footnote definition's label.
10804 ((or (eq type 'footnote-reference)
10805 (and (eq type 'footnote-definition)
10806 (save-excursion
10807 ;; Do not validate action when point is on the
10808 ;; spaces right after the footnote label, in
10809 ;; order to be on par with behaviour on links.
10810 (skip-chars-forward " \t")
10811 (let ((begin
10812 (org-element-property :contents-begin context)))
10813 (if begin (< (point) begin)
10814 (= (org-element-property :post-affiliated context)
10815 (line-beginning-position)))))))
10816 (org-footnote-action))
10817 (t (user-error "No link found")))))
10818 (move-marker org-open-link-marker nil)
10819 (run-hook-with-args 'org-follow-link-hook)))
10821 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10822 "Offer links in the current entry and return the selected link.
10823 If there is only one link, return it.
10824 If NTH is an integer, return the NTH link found.
10825 If ZERO is a string, check also this string for a link, and if
10826 there is one, return it."
10827 (with-current-buffer buffer
10828 (save-excursion
10829 (save-restriction
10830 (widen)
10831 (goto-char marker)
10832 (let ((cnt ?0)
10833 (in-emacs (if (integerp nth) nil nth))
10834 have-zero end links link c)
10835 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10836 (push (match-string 0 zero) links)
10837 (setq cnt (1- cnt) have-zero t))
10838 (save-excursion
10839 (org-back-to-heading t)
10840 (setq end (save-excursion (outline-next-heading) (point)))
10841 (while (re-search-forward org-any-link-re end t)
10842 (push (match-string 0) links))
10843 (setq links (org-uniquify (reverse links))))
10844 (cond
10845 ((null links)
10846 (message "No links"))
10847 ((equal (length links) 1)
10848 (setq link (car links)))
10849 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10850 (setq link (nth (if have-zero nth (1- nth)) links)))
10851 (t ; we have to select a link
10852 (save-excursion
10853 (save-window-excursion
10854 (delete-other-windows)
10855 (with-output-to-temp-buffer "*Select Link*"
10856 (mapc (lambda (l)
10857 (if (not (string-match org-bracket-link-regexp l))
10858 (princ (format "[%c] %s\n" (incf cnt)
10859 (org-remove-angle-brackets l)))
10860 (if (match-end 3)
10861 (princ (format "[%c] %s (%s)\n" (incf cnt)
10862 (match-string 3 l) (match-string 1 l)))
10863 (princ (format "[%c] %s\n" (incf cnt)
10864 (match-string 1 l))))))
10865 links))
10866 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10867 (message "Select link to open, RET to open all:")
10868 (setq c (read-char-exclusive))
10869 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10870 (when (equal c ?q) (user-error "Abort"))
10871 (if (equal c ?\C-m)
10872 (setq link links)
10873 (setq nth (- c ?0))
10874 (if have-zero (setq nth (1+ nth)))
10875 (unless (and (integerp nth) (>= (length links) nth))
10876 (user-error "Invalid link selection"))
10877 (setq link (nth (1- nth) links)))))
10878 (cons link end))))))
10880 ;; TODO: These functions are deprecated since `org-open-at-point'
10881 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10882 (defun org-open-file-with-system (path)
10883 "Open file at PATH using the system way of opening it."
10884 (org-open-file path 'system))
10885 (defun org-open-file-with-emacs (path)
10886 "Open file at PATH in Emacs."
10887 (org-open-file path 'emacs))
10890 ;;; File search
10892 (defvar org-create-file-search-functions nil
10893 "List of functions to construct the right search string for a file link.
10894 These functions are called in turn with point at the location to
10895 which the link should point.
10897 A function in the hook should first test if it would like to
10898 handle this file type, for example by checking the `major-mode'
10899 or the file extension. If it decides not to handle this file, it
10900 should just return nil to give other functions a chance. If it
10901 does handle the file, it must return the search string to be used
10902 when following the link. The search string will be part of the
10903 file link, given after a double colon, and `org-open-at-point'
10904 will automatically search for it. If special measures must be
10905 taken to make the search successful, another function should be
10906 added to the companion hook `org-execute-file-search-functions',
10907 which see.
10909 A function in this hook may also use `setq' to set the variable
10910 `description' to provide a suggestion for the descriptive text to
10911 be used for this link when it gets inserted into an Org-mode
10912 buffer with \\[org-insert-link].")
10914 (defvar org-execute-file-search-functions nil
10915 "List of functions to execute a file search triggered by a link.
10917 Functions added to this hook must accept a single argument, the
10918 search string that was part of the file link, the part after the
10919 double colon. The function must first check if it would like to
10920 handle this search, for example by checking the `major-mode' or
10921 the file extension. If it decides not to handle this search, it
10922 should just return nil to give other functions a chance. If it
10923 does handle the search, it must return a non-nil value to keep
10924 other functions from trying.
10926 Each function can access the current prefix argument through the
10927 variable `current-prefix-arg'. Note that a single prefix is used
10928 to force opening a link in Emacs, so it may be good to only use a
10929 numeric or double prefix to guide the search function.
10931 In case this is needed, a function in this hook can also restore
10932 the window configuration before `org-open-at-point' was called using:
10934 (set-window-configuration org-window-config-before-follow-link)")
10936 (defun org-link-search (s &optional type avoid-pos stealth)
10937 "Search for a link search option.
10938 If S is surrounded by forward slashes, it is interpreted as a
10939 regular expression. In org-mode files, this will create an `org-occur'
10940 sparse tree. In ordinary files, `occur' will be used to list matches.
10941 If the current buffer is in `dired-mode', grep will be used to search
10942 in all files. If AVOID-POS is given, ignore matches near that position.
10944 When optional argument STEALTH is non-nil, do not modify
10945 visibility around point, thus ignoring
10946 `org-show-hierarchy-above', `org-show-following-heading' and
10947 `org-show-siblings' variables."
10948 (let ((case-fold-search t)
10949 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10950 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10951 (append '(("") (" ") ("\t") ("\n"))
10952 org-emphasis-alist)
10953 "\\|") "\\)"))
10954 (pos (point))
10955 (pre nil) (post nil)
10956 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10957 (cond
10958 ;; First check if there are any special search functions
10959 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10960 ;; Now try the builtin stuff
10961 ((and (equal (string-to-char s0) ?#)
10962 (> (length s0) 1)
10963 (save-excursion
10964 (goto-char (point-min))
10965 (and
10966 (re-search-forward
10967 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10968 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10969 (setq type 'dedicated
10970 pos (match-beginning 0))))
10971 ;; There is an exact target for this
10972 (goto-char pos)
10973 (org-back-to-heading t)))
10974 ((save-excursion
10975 (goto-char (point-min))
10976 (and
10977 (re-search-forward
10978 (concat "<<" (regexp-quote s0) ">>") nil t)
10979 (setq type 'dedicated
10980 pos (match-beginning 0))))
10981 ;; There is an exact target for this
10982 (goto-char pos))
10983 ((save-excursion
10984 (goto-char (point-min))
10985 (and
10986 (re-search-forward
10987 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10988 (setq type 'dedicated pos (match-beginning 0))))
10989 ;; Found an element with a matching #+name affiliated keyword.
10990 (goto-char pos))
10991 ((and (string-match "^(\\(.*\\))$" s0)
10992 (save-excursion
10993 (goto-char (point-min))
10994 (and
10995 (re-search-forward
10996 (concat "[^[]" (regexp-quote
10997 (format org-coderef-label-format
10998 (match-string 1 s0))))
10999 nil t)
11000 (setq type 'dedicated
11001 pos (1+ (match-beginning 0))))))
11002 ;; There is a coderef target for this
11003 (goto-char pos))
11004 ((string-match "^/\\(.*\\)/$" s)
11005 ;; A regular expression
11006 (cond
11007 ((derived-mode-p 'org-mode)
11008 (org-occur (match-string 1 s)))
11009 (t (org-do-occur (match-string 1 s)))))
11010 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11011 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11012 (goto-char (point-min))
11013 (cond
11014 ((let (case-fold-search)
11015 (re-search-forward (format org-complex-heading-regexp-format
11016 (regexp-quote s))
11017 nil t))
11018 ;; OK, found a match
11019 (setq type 'dedicated)
11020 (goto-char (match-beginning 0)))
11021 ((and (not org-link-search-inhibit-query)
11022 (eq org-link-search-must-match-exact-headline 'query-to-create)
11023 (y-or-n-p "No match - create this as a new heading? "))
11024 (goto-char (point-max))
11025 (or (bolp) (newline))
11026 (insert "* " s "\n")
11027 (beginning-of-line 0))
11029 (goto-char pos)
11030 (error "No match"))))
11032 ;; A normal search string
11033 (when (equal (string-to-char s) ?*)
11034 ;; Anchor on headlines, post may include tags.
11035 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11036 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11037 s (substring s 1)))
11038 (remove-text-properties
11039 0 (length s)
11040 '(face nil mouse-face nil keymap nil fontified nil) s)
11041 ;; Make a series of regular expressions to find a match
11042 (setq words (org-split-string s "[ \n\r\t]+")
11044 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11045 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11046 "\\)" markers)
11047 re2a_ (concat "\\(" (mapconcat 'downcase words
11048 "[ \t\r\n]+") "\\)[ \t\r\n]")
11049 re2a (concat "[ \t\r\n]" re2a_)
11050 re4_ (concat "\\(" (mapconcat 'downcase words
11051 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11052 re4 (concat "[^a-zA-Z_]" re4_)
11054 re1 (concat pre re2 post)
11055 re3 (concat pre (if pre re4_ re4) post)
11056 re5 (concat pre ".*" re4)
11057 re2 (concat pre re2)
11058 re2a (concat pre (if pre re2a_ re2a))
11059 re4 (concat pre (if pre re4_ re4))
11060 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11061 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11062 re5 "\\)"))
11063 (cond
11064 ((eq type 'org-occur) (org-occur reall))
11065 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11066 (t (goto-char (point-min))
11067 (setq type 'fuzzy)
11068 (if (or (and (org-search-not-self 1 re0 nil t)
11069 (setq type 'dedicated))
11070 (org-search-not-self 1 re1 nil t)
11071 (org-search-not-self 1 re2 nil t)
11072 (org-search-not-self 1 re2a nil t)
11073 (org-search-not-self 1 re3 nil t)
11074 (org-search-not-self 1 re4 nil t)
11075 (org-search-not-self 1 re5 nil t))
11076 (goto-char (match-beginning 1))
11077 (goto-char pos)
11078 (error "No match"))))))
11079 (and (derived-mode-p 'org-mode)
11080 (not stealth)
11081 (org-show-context 'link-search))
11082 type))
11084 (defun org-search-not-self (group &rest args)
11085 "Execute `re-search-forward', but only accept matches that do not
11086 enclose the position of `org-open-link-marker'."
11087 (let ((m org-open-link-marker))
11088 (catch 'exit
11089 (while (apply 're-search-forward args)
11090 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11091 (goto-char (match-end group))
11092 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11093 (> (match-beginning 0) (marker-position m))
11094 (< (match-end 0) (marker-position m)))
11095 (save-match-data
11096 (or (not (org-in-regexp
11097 org-bracket-link-analytic-regexp 1))
11098 (not (match-end 4)) ; no description
11099 (and (<= (match-beginning 4) (point))
11100 (>= (match-end 4) (point))))))
11101 (throw 'exit (point))))))))
11103 (defun org-get-buffer-for-internal-link (buffer)
11104 "Return a buffer to be used for displaying the link target of internal links."
11105 (cond
11106 ((not org-display-internal-link-with-indirect-buffer)
11107 buffer)
11108 ((string-match "(Clone)$" (buffer-name buffer))
11109 (message "Buffer is already a clone, not making another one")
11110 ;; we also do not modify visibility in this case
11111 buffer)
11112 (t ; make a new indirect buffer for displaying the link
11113 (let* ((bn (buffer-name buffer))
11114 (ibn (concat bn "(Clone)"))
11115 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11116 (with-current-buffer ib (org-overview))
11117 ib))))
11119 (defun org-do-occur (regexp &optional cleanup)
11120 "Call the Emacs command `occur'.
11121 If CLEANUP is non-nil, remove the printout of the regular expression
11122 in the *Occur* buffer. This is useful if the regex is long and not useful
11123 to read."
11124 (occur regexp)
11125 (when cleanup
11126 (let ((cwin (selected-window)) win beg end)
11127 (when (setq win (get-buffer-window "*Occur*"))
11128 (select-window win))
11129 (goto-char (point-min))
11130 (when (re-search-forward "match[a-z]+" nil t)
11131 (setq beg (match-end 0))
11132 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11133 (setq end (1- (match-beginning 0)))))
11134 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11135 (goto-char (point-min))
11136 (select-window cwin))))
11138 ;;; The mark ring for links jumps
11140 (defvar org-mark-ring nil
11141 "Mark ring for positions before jumps in Org-mode.")
11142 (defvar org-mark-ring-last-goto nil
11143 "Last position in the mark ring used to go back.")
11144 ;; Fill and close the ring
11145 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11146 (loop for i from 1 to org-mark-ring-length do
11147 (push (make-marker) org-mark-ring))
11148 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11149 org-mark-ring)
11151 (defun org-mark-ring-push (&optional pos buffer)
11152 "Put the current position or POS into the mark ring and rotate it."
11153 (interactive)
11154 (setq pos (or pos (point)))
11155 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11156 (move-marker (car org-mark-ring)
11157 (or pos (point))
11158 (or buffer (current-buffer)))
11159 (message "%s"
11160 (substitute-command-keys
11161 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11163 (defun org-mark-ring-goto (&optional n)
11164 "Jump to the previous position in the mark ring.
11165 With prefix arg N, jump back that many stored positions. When
11166 called several times in succession, walk through the entire ring.
11167 Org-mode commands jumping to a different position in the current file,
11168 or to another Org-mode file, automatically push the old position
11169 onto the ring."
11170 (interactive "p")
11171 (let (p m)
11172 (if (eq last-command this-command)
11173 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11174 (setq p org-mark-ring))
11175 (setq org-mark-ring-last-goto p)
11176 (setq m (car p))
11177 (org-pop-to-buffer-same-window (marker-buffer m))
11178 (goto-char m)
11179 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11181 (defun org-remove-angle-brackets (s)
11182 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11183 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11185 (defun org-add-angle-brackets (s)
11186 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11187 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11189 (defun org-remove-double-quotes (s)
11190 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11191 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11194 ;;; Following specific links
11196 (defun org-follow-timestamp-link ()
11197 "Open an agenda view for the time-stamp date/range at point."
11198 (cond
11199 ((org-at-date-range-p t)
11200 (let ((org-agenda-start-on-weekday)
11201 (t1 (match-string 1))
11202 (t2 (match-string 2)) tt1 tt2)
11203 (setq tt1 (time-to-days (org-time-string-to-time t1))
11204 tt2 (time-to-days (org-time-string-to-time t2)))
11205 (let ((org-agenda-buffer-tmp-name
11206 (format "*Org Agenda(a:%s)"
11207 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11208 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11209 ((org-at-timestamp-p t)
11210 (let ((org-agenda-buffer-tmp-name
11211 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11212 (org-agenda-list nil (time-to-days (org-time-string-to-time
11213 (substring (match-string 1) 0 10)))
11214 1)))
11215 (t (error "This should not happen"))))
11218 ;;; Following file links
11219 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11220 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11221 (declare-function mailcap-mime-info
11222 "mailcap" (string &optional request no-decode))
11223 (defvar org-wait nil)
11224 (defun org-open-file (path &optional in-emacs line search)
11225 "Open the file at PATH.
11226 First, this expands any special file name abbreviations. Then the
11227 configuration variable `org-file-apps' is checked if it contains an
11228 entry for this file type, and if yes, the corresponding command is launched.
11230 If no application is found, Emacs simply visits the file.
11232 With optional prefix argument IN-EMACS, Emacs will visit the file.
11233 With a double \\[universal-argument] \\[universal-argument] \
11234 prefix arg, Org tries to avoid opening in Emacs
11235 and to use an external application to visit the file.
11237 Optional LINE specifies a line to go to, optional SEARCH a string
11238 to search for. If LINE or SEARCH is given, the file will be
11239 opened in Emacs, unless an entry from org-file-apps that makes
11240 use of groups in a regexp matches.
11242 If you want to change the way frames are used when following a
11243 link, please customize `org-link-frame-setup'.
11245 If the file does not exist, an error is thrown."
11246 (let* ((file (if (equal path "")
11247 buffer-file-name
11248 (substitute-in-file-name (expand-file-name path))))
11249 (file-apps (append org-file-apps (org-default-apps)))
11250 (apps (org-remove-if
11251 'org-file-apps-entry-match-against-dlink-p file-apps))
11252 (apps-dlink (org-remove-if-not
11253 'org-file-apps-entry-match-against-dlink-p file-apps))
11254 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11255 (dirp (if remp nil (file-directory-p file)))
11256 (file (if (and dirp org-open-directory-means-index-dot-org)
11257 (concat (file-name-as-directory file) "index.org")
11258 file))
11259 (a-m-a-p (assq 'auto-mode apps))
11260 (dfile (downcase file))
11261 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11262 (link (cond ((and (eq line nil)
11263 (eq search nil))
11264 file)
11265 (line
11266 (concat file "::" (number-to-string line)))
11267 (search
11268 (concat file "::" search))))
11269 (dlink (downcase link))
11270 (old-buffer (current-buffer))
11271 (old-pos (point))
11272 (old-mode major-mode)
11273 ext cmd link-match-data)
11274 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11275 (setq ext (match-string 1 dfile))
11276 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11277 (setq ext (match-string 1 dfile))))
11278 (cond
11279 ((member in-emacs '((16) system))
11280 (setq cmd (cdr (assoc 'system apps))))
11281 (in-emacs (setq cmd 'emacs))
11283 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11284 (and dirp (cdr (assoc 'directory apps)))
11285 ; first, try matching against apps-dlink
11286 ; if we get a match here, store the match data for later
11287 (let ((match (assoc-default dlink apps-dlink
11288 'string-match)))
11289 (if match
11290 (progn (setq link-match-data (match-data))
11291 match)
11292 (progn (setq in-emacs (or in-emacs line search))
11293 nil))) ; if we have no match in apps-dlink,
11294 ; always open the file in emacs if line or search
11295 ; is given (for backwards compatibility)
11296 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11297 'string-match)
11298 (cdr (assoc ext apps))
11299 (cdr (assoc t apps))))))
11300 (when (eq cmd 'system)
11301 (setq cmd (cdr (assoc 'system apps))))
11302 (when (eq cmd 'default)
11303 (setq cmd (cdr (assoc t apps))))
11304 (when (eq cmd 'mailcap)
11305 (require 'mailcap)
11306 (mailcap-parse-mailcaps)
11307 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11308 (command (mailcap-mime-info mime-type)))
11309 (if (stringp command)
11310 (setq cmd command)
11311 (setq cmd 'emacs))))
11312 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11313 (not (file-exists-p file))
11314 (not org-open-non-existing-files))
11315 (user-error "No such file: %s" file))
11316 (cond
11317 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11318 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11319 (while (string-match "['\"]%s['\"]" cmd)
11320 (setq cmd (replace-match "%s" t t cmd)))
11321 (while (string-match "%s" cmd)
11322 (setq cmd (replace-match
11323 (save-match-data
11324 (shell-quote-argument
11325 (convert-standard-filename file)))
11326 t t cmd)))
11328 ;; Replace "%1", "%2" etc. in command with group matches from regex
11329 (save-match-data
11330 (let ((match-index 1)
11331 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11332 (set-match-data link-match-data)
11333 (while (<= match-index number-of-groups)
11334 (let ((regex (concat "%" (number-to-string match-index)))
11335 (replace-with (match-string match-index dlink)))
11336 (while (string-match regex cmd)
11337 (setq cmd (replace-match replace-with t t cmd))))
11338 (setq match-index (+ match-index 1)))))
11340 (save-window-excursion
11341 (message "Running %s...done" cmd)
11342 (start-process-shell-command cmd nil cmd)
11343 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11344 ((or (stringp cmd)
11345 (eq cmd 'emacs))
11346 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11347 (widen)
11348 (if line (progn (org-goto-line line)
11349 (if (derived-mode-p 'org-mode)
11350 (org-reveal)))
11351 (if search (org-link-search search))))
11352 ((consp cmd)
11353 (let ((file (convert-standard-filename file)))
11354 (save-match-data
11355 (set-match-data link-match-data)
11356 (eval cmd))))
11357 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11358 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11359 (or (not (equal old-buffer (current-buffer)))
11360 (not (equal old-pos (point))))
11361 (org-mark-ring-push old-pos old-buffer))))
11363 (defun org-file-apps-entry-match-against-dlink-p (entry)
11364 "This function returns non-nil if `entry' uses a regular
11365 expression which should be matched against the whole link by
11366 org-open-file.
11368 It assumes that is the case when the entry uses a regular
11369 expression which has at least one grouping construct and the
11370 action is either a lisp form or a command string containing
11371 '%1', i.e. using at least one subexpression match as a
11372 parameter."
11373 (let ((selector (car entry))
11374 (action (cdr entry)))
11375 (if (stringp selector)
11376 (and (> (regexp-opt-depth selector) 0)
11377 (or (and (stringp action)
11378 (string-match "%[0-9]" action))
11379 (consp action)))
11380 nil)))
11382 (defun org-default-apps ()
11383 "Return the default applications for this operating system."
11384 (cond
11385 ((eq system-type 'darwin)
11386 org-file-apps-defaults-macosx)
11387 ((eq system-type 'windows-nt)
11388 org-file-apps-defaults-windowsnt)
11389 (t org-file-apps-defaults-gnu)))
11391 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11392 "Convert extensions to regular expressions in the cars of LIST.
11393 Also, weed out any non-string entries, because the return value is used
11394 only for regexp matching.
11395 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11396 point to the symbol `emacs', indicating that the file should
11397 be opened in Emacs."
11398 (append
11399 (delq nil
11400 (mapcar (lambda (x)
11401 (if (not (stringp (car x)))
11403 (if (string-match "\\W" (car x))
11405 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11406 list))
11407 (if add-auto-mode
11408 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11410 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11411 (defun org-file-remote-p (file)
11412 "Test whether FILE specifies a location on a remote system.
11413 Return non-nil if the location is indeed remote.
11415 For example, the filename \"/user@host:/foo\" specifies a location
11416 on the system \"/user@host:\"."
11417 (cond ((fboundp 'file-remote-p)
11418 (file-remote-p file))
11419 ((fboundp 'tramp-handle-file-remote-p)
11420 (tramp-handle-file-remote-p file))
11421 ((and (boundp 'ange-ftp-name-format)
11422 (string-match (car ange-ftp-name-format) file))
11423 t)))
11426 ;;;; Refiling
11428 (defun org-get-org-file ()
11429 "Read a filename, with default directory `org-directory'."
11430 (let ((default (or org-default-notes-file remember-data-file)))
11431 (read-file-name (format "File name [%s]: " default)
11432 (file-name-as-directory org-directory)
11433 default)))
11435 (defun org-notes-order-reversed-p ()
11436 "Check if the current file should receive notes in reversed order."
11437 (cond
11438 ((not org-reverse-note-order) nil)
11439 ((eq t org-reverse-note-order) t)
11440 ((not (listp org-reverse-note-order)) nil)
11441 (t (catch 'exit
11442 (let ((all org-reverse-note-order)
11443 entry)
11444 (while (setq entry (pop all))
11445 (if (string-match (car entry) buffer-file-name)
11446 (throw 'exit (cdr entry))))
11447 nil)))))
11449 (defvar org-refile-target-table nil
11450 "The list of refile targets, created by `org-refile'.")
11452 (defvar org-agenda-new-buffers nil
11453 "Buffers created to visit agenda files.")
11455 (defvar org-refile-cache nil
11456 "Cache for refile targets.")
11458 (defvar org-refile-markers nil
11459 "All the markers used for caching refile locations.")
11461 (defun org-refile-marker (pos)
11462 "Get a new refile marker, but only if caching is in use."
11463 (if (not org-refile-use-cache)
11465 (let ((m (make-marker)))
11466 (move-marker m pos)
11467 (push m org-refile-markers)
11468 m)))
11470 (defun org-refile-cache-clear ()
11471 "Clear the refile cache and disable all the markers."
11472 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11473 (setq org-refile-markers nil)
11474 (setq org-refile-cache nil)
11475 (message "Refile cache has been cleared"))
11477 (defun org-refile-cache-check-set (set)
11478 "Check if all the markers in the cache still have live buffers."
11479 (let (marker)
11480 (catch 'exit
11481 (while (and set (setq marker (nth 3 (pop set))))
11482 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11483 (when (and marker (null (marker-buffer marker)))
11484 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11485 (sit-for 3)
11486 (throw 'exit nil)))
11487 t)))
11489 (defun org-refile-cache-put (set &rest identifiers)
11490 "Push the refile targets SET into the cache, under IDENTIFIERS."
11491 (let* ((key (sha1 (prin1-to-string identifiers)))
11492 (entry (assoc key org-refile-cache)))
11493 (if entry
11494 (setcdr entry set)
11495 (push (cons key set) org-refile-cache))))
11497 (defun org-refile-cache-get (&rest identifiers)
11498 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11499 (cond
11500 ((not org-refile-cache) nil)
11501 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11503 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11504 org-refile-cache))))
11505 (and set (org-refile-cache-check-set set) set)))))
11507 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11508 "Produce a table with refile targets."
11509 (let ((case-fold-search nil)
11510 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11511 (entries (or org-refile-targets '((nil . (:level . 1)))))
11512 targets tgs txt re files f desc descre fast-path-p level pos0)
11513 (message "Getting targets...")
11514 (with-current-buffer (or default-buffer (current-buffer))
11515 (while (setq entry (pop entries))
11516 (setq files (car entry) desc (cdr entry))
11517 (setq fast-path-p nil)
11518 (cond
11519 ((null files) (setq files (list (current-buffer))))
11520 ((eq files 'org-agenda-files)
11521 (setq files (org-agenda-files 'unrestricted)))
11522 ((and (symbolp files) (fboundp files))
11523 (setq files (funcall files)))
11524 ((and (symbolp files) (boundp files))
11525 (setq files (symbol-value files))))
11526 (if (stringp files) (setq files (list files)))
11527 (cond
11528 ((eq (car desc) :tag)
11529 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11530 ((eq (car desc) :todo)
11531 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11532 ((eq (car desc) :regexp)
11533 (setq descre (cdr desc)))
11534 ((eq (car desc) :level)
11535 (setq descre (concat "^\\*\\{" (number-to-string
11536 (if org-odd-levels-only
11537 (1- (* 2 (cdr desc)))
11538 (cdr desc)))
11539 "\\}[ \t]")))
11540 ((eq (car desc) :maxlevel)
11541 (setq fast-path-p t)
11542 (setq descre (concat "^\\*\\{1," (number-to-string
11543 (if org-odd-levels-only
11544 (1- (* 2 (cdr desc)))
11545 (cdr desc)))
11546 "\\}[ \t]")))
11547 (t (error "Bad refiling target description %s" desc)))
11548 (while (setq f (pop files))
11549 (with-current-buffer
11550 (if (bufferp f) f (org-get-agenda-file-buffer f))
11552 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11553 (progn
11554 (if (bufferp f) (setq f (buffer-file-name
11555 (buffer-base-buffer f))))
11556 (setq f (and f (expand-file-name f)))
11557 (if (eq org-refile-use-outline-path 'file)
11558 (push (list (file-name-nondirectory f) f nil nil) tgs))
11559 (save-excursion
11560 (save-restriction
11561 (widen)
11562 (goto-char (point-min))
11563 (while (re-search-forward descre nil t)
11564 (goto-char (setq pos0 (point-at-bol)))
11565 (catch 'next
11566 (when org-refile-target-verify-function
11567 (save-match-data
11568 (or (funcall org-refile-target-verify-function)
11569 (throw 'next t))))
11570 (when (and (looking-at org-complex-heading-regexp)
11571 (not (member (match-string 4) excluded-entries))
11572 (match-string 4))
11573 (setq level (org-reduced-level
11574 (- (match-end 1) (match-beginning 1)))
11575 txt (org-link-display-format (match-string 4))
11576 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11577 re (format org-complex-heading-regexp-format
11578 (regexp-quote (match-string 4))))
11579 (when org-refile-use-outline-path
11580 (setq txt (mapconcat
11581 'org-protect-slash
11582 (append
11583 (if (eq org-refile-use-outline-path
11584 'file)
11585 (list (file-name-nondirectory
11586 (buffer-file-name
11587 (buffer-base-buffer))))
11588 (if (eq org-refile-use-outline-path
11589 'full-file-path)
11590 (list (buffer-file-name
11591 (buffer-base-buffer)))))
11592 (org-get-outline-path fast-path-p
11593 level txt)
11594 (list txt))
11595 "/")))
11596 (push (list txt f re (org-refile-marker (point)))
11597 tgs)))
11598 (when (= (point) pos0)
11599 ;; verification function has not moved point
11600 (goto-char (point-at-eol))))))))
11601 (when org-refile-use-cache
11602 (org-refile-cache-put tgs (buffer-file-name) descre))
11603 (setq targets (append tgs targets))))))
11604 (message "Getting targets...done")
11605 (nreverse targets)))
11607 (defun org-protect-slash (s)
11608 (while (string-match "/" s)
11609 (setq s (replace-match "\\" t t s)))
11612 (defvar org-olpa (make-vector 20 nil))
11614 (defun org-get-outline-path (&optional fastp level heading)
11615 "Return the outline path to the current entry, as a list.
11617 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11618 routine which makes outline path derivations for an entire file,
11619 avoiding backtracing. Refile target collection makes use of that."
11620 (if fastp
11621 (progn
11622 (if (> level 19)
11623 (error "Outline path failure, more than 19 levels"))
11624 (loop for i from level upto 19 do
11625 (aset org-olpa i nil))
11626 (prog1
11627 (delq nil (append org-olpa nil))
11628 (aset org-olpa level heading)))
11629 (let (rtn case-fold-search)
11630 (save-excursion
11631 (save-restriction
11632 (widen)
11633 (while (org-up-heading-safe)
11634 (when (looking-at org-complex-heading-regexp)
11635 (push (org-trim
11636 (replace-regexp-in-string
11637 ;; Remove statistical/checkboxes cookies
11638 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11639 (org-match-string-no-properties 4)))
11640 rtn)))
11641 rtn)))))
11643 (defun org-format-outline-path (path &optional width prefix separator)
11644 "Format the outline path PATH for display.
11645 WIDTH is the maximum number of characters that is available.
11646 PREFIX is a prefix to be included in the returned string,
11647 such as the file name.
11648 SEPARATOR is inserted between the different parts of the path,
11649 the default is \"/\"."
11650 (setq width (or width 79))
11651 (if prefix (setq width (- width (length prefix))))
11652 (if (not path)
11653 (or prefix "")
11654 (let* ((nsteps (length path))
11655 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11656 (maxwidth (if (<= total-width width)
11657 10000 ;; everything fits
11658 ;; we need to shorten the level headings
11659 (/ (- width nsteps) nsteps)))
11660 (org-odd-levels-only nil)
11661 (n 0)
11662 (total (1+ (length prefix))))
11663 (setq maxwidth (max maxwidth 10))
11664 (concat prefix
11665 (if prefix (or separator "/"))
11666 (mapconcat
11667 (lambda (h)
11668 (setq n (1+ n))
11669 (if (and (= n nsteps) (< maxwidth 10000))
11670 (setq maxwidth (- total-width total)))
11671 (if (< (length h) maxwidth)
11672 (progn (setq total (+ total (length h) 1)) h)
11673 (setq h (substring h 0 (- maxwidth 2))
11674 total (+ total maxwidth 1))
11675 (if (string-match "[ \t]+\\'" h)
11676 (setq h (substring h 0 (match-beginning 0))))
11677 (setq h (concat h "..")))
11678 (org-add-props h nil 'face
11679 (nth (% (1- n) org-n-level-faces)
11680 org-level-faces))
11682 path (or separator "/"))))))
11684 (defun org-display-outline-path (&optional file current separator just-return-string)
11685 "Display the current outline path in the echo area.
11687 If FILE is non-nil, prepend the output with the file name.
11688 If CURRENT is non-nil, append the current heading to the output.
11689 SEPARATOR is passed through to `org-format-outline-path'. It separates
11690 the different parts of the path and defaults to \"/\".
11691 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11692 (interactive "P")
11693 (let* (case-fold-search
11694 (bfn (buffer-file-name (buffer-base-buffer)))
11695 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11696 res)
11697 (if current (setq path (append path
11698 (save-excursion
11699 (org-back-to-heading t)
11700 (if (looking-at org-complex-heading-regexp)
11701 (list (match-string 4)))))))
11702 (setq res
11703 (org-format-outline-path
11704 path
11705 (1- (frame-width))
11706 (and file bfn (concat (file-name-nondirectory bfn) separator))
11707 separator))
11708 (if just-return-string
11709 (org-no-properties res)
11710 (org-unlogged-message "%s" res))))
11712 (defvar org-refile-history nil
11713 "History for refiling operations.")
11715 (defvar org-after-refile-insert-hook nil
11716 "Hook run after `org-refile' has inserted its stuff at the new location.
11717 Note that this is still *before* the stuff will be removed from
11718 the *old* location.")
11720 (defvar org-capture-last-stored-marker)
11721 (defvar org-refile-keep nil
11722 "Non-nil means `org-refile' will copy instead of refile.")
11724 (defun org-copy ()
11725 "Like `org-refile', but copy."
11726 (interactive)
11727 (let ((org-refile-keep t))
11728 (funcall 'org-refile nil nil nil "Copy")))
11730 (defun org-refile (&optional arg default-buffer rfloc msg)
11731 "Move the entry or entries at point to another heading.
11732 The list of target headings is compiled using the information in
11733 `org-refile-targets', which see.
11735 At the target location, the entry is filed as a subitem of the
11736 target heading. Depending on `org-reverse-note-order', the new
11737 subitem will either be the first or the last subitem.
11739 If there is an active region, all entries in that region will be
11740 refiled. However, the region must fulfill the requirement that
11741 the first heading sets the top-level of the moved text.
11743 With prefix arg ARG, the command will only visit the target
11744 location and not actually move anything.
11746 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11747 refiling operation has put the subtree.
11749 With a numeric prefix argument of `2', refile to the running clock.
11751 With a numeric prefix argument of `3', emulate `org-refile-keep'
11752 being set to `t' and copy to the target location, don't move it.
11753 Beware that keeping refiled entries may result in duplicated ID
11754 properties.
11756 RFLOC can be a refile location obtained in a different way.
11758 MSG is a string to replace \"Refile\" in the default prompt with
11759 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11761 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11763 If you are using target caching (see `org-refile-use-cache'), you
11764 have to clear the target cache in order to find new targets.
11765 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11766 prefix argument (`C-u C-u C-u C-c C-w')."
11767 (interactive "P")
11768 (if (member arg '(0 (64)))
11769 (org-refile-cache-clear)
11770 (let* ((actionmsg (cond (msg msg)
11771 ((equal arg 3) "Refile (and keep)")
11772 (t "Refile")))
11773 (cbuf (current-buffer))
11774 (regionp (org-region-active-p))
11775 (region-start (and regionp (region-beginning)))
11776 (region-end (and regionp (region-end)))
11777 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11778 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11779 pos it nbuf file re level reversed)
11780 (setq last-command nil)
11781 (when regionp
11782 (goto-char region-start)
11783 (or (bolp) (goto-char (point-at-bol)))
11784 (setq region-start (point))
11785 (unless (or (org-kill-is-subtree-p
11786 (buffer-substring region-start region-end))
11787 (prog1 org-refile-active-region-within-subtree
11788 (let ((s (point-at-eol)))
11789 (org-toggle-heading)
11790 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11791 (user-error "The region is not a (sequence of) subtree(s)")))
11792 (if (equal arg '(16))
11793 (org-refile-goto-last-stored)
11794 (when (or
11795 (and (equal arg 2)
11796 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11797 (prog1
11798 (setq it (list (or org-clock-heading "running clock")
11799 (buffer-file-name
11800 (marker-buffer org-clock-hd-marker))
11802 (marker-position org-clock-hd-marker)))
11803 (setq arg nil)))
11804 (setq it (or rfloc
11805 (let (heading-text)
11806 (save-excursion
11807 (unless (and arg (listp arg))
11808 (org-back-to-heading t)
11809 (setq heading-text
11810 (replace-regexp-in-string
11811 org-bracket-link-regexp
11812 "\\3"
11813 (nth 4 (org-heading-components)))))
11814 (org-refile-get-location
11815 (cond ((and arg (listp arg)) "Goto")
11816 (regionp (concat actionmsg " region to"))
11817 (t (concat actionmsg " subtree \""
11818 heading-text "\" to")))
11819 default-buffer
11820 (and (not (equal '(4) arg))
11821 org-refile-allow-creating-parent-nodes)
11822 arg))))))
11823 (setq file (nth 1 it)
11824 re (nth 2 it)
11825 pos (nth 3 it))
11826 (if (and (not arg)
11828 (equal (buffer-file-name) file)
11829 (if regionp
11830 (and (>= pos region-start)
11831 (<= pos region-end))
11832 (and (>= pos (point))
11833 (< pos (save-excursion
11834 (org-end-of-subtree t t))))))
11835 (error "Cannot refile to position inside the tree or region"))
11836 (setq nbuf (or (find-buffer-visiting file)
11837 (find-file-noselect file)))
11838 (if (and arg (not (equal arg 3)))
11839 (progn
11840 (org-pop-to-buffer-same-window nbuf)
11841 (goto-char pos)
11842 (org-show-context 'org-goto))
11843 (if regionp
11844 (progn
11845 (org-kill-new (buffer-substring region-start region-end))
11846 (org-save-markers-in-region region-start region-end))
11847 (org-copy-subtree 1 nil t))
11848 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11849 (find-file-noselect file)))
11850 (setq reversed (org-notes-order-reversed-p))
11851 (save-excursion
11852 (save-restriction
11853 (widen)
11854 (if pos
11855 (progn
11856 (goto-char pos)
11857 (looking-at org-outline-regexp)
11858 (setq level (org-get-valid-level (funcall outline-level) 1))
11859 (goto-char
11860 (if reversed
11861 (or (outline-next-heading) (point-max))
11862 (or (save-excursion (org-get-next-sibling))
11863 (org-end-of-subtree t t)
11864 (point-max)))))
11865 (setq level 1)
11866 (if (not reversed)
11867 (goto-char (point-max))
11868 (goto-char (point-min))
11869 (or (outline-next-heading) (goto-char (point-max)))))
11870 (if (not (bolp)) (newline))
11871 (org-paste-subtree level nil nil t)
11872 (when org-log-refile
11873 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11874 (unless (eq org-log-refile 'note)
11875 (save-excursion (org-add-log-note))))
11876 (and org-auto-align-tags
11877 (let ((org-loop-over-headlines-in-active-region nil))
11878 (org-set-tags nil t)))
11879 (let ((bookmark-name (plist-get org-bookmark-names-plist
11880 :last-refile)))
11881 (when bookmark-name
11882 (with-demoted-errors
11883 (bookmark-set bookmark-name))))
11884 ;; If we are refiling for capture, make sure that the
11885 ;; last-capture pointers point here
11886 (when (org-bound-and-true-p org-refile-for-capture)
11887 (let ((bookmark-name (plist-get org-bookmark-names-plist
11888 :last-capture-marker)))
11889 (when bookmark-name
11890 (with-demoted-errors
11891 (bookmark-set bookmark-name))))
11892 (move-marker org-capture-last-stored-marker (point)))
11893 (if (fboundp 'deactivate-mark) (deactivate-mark))
11894 (run-hooks 'org-after-refile-insert-hook))))
11895 (unless org-refile-keep
11896 (if regionp
11897 (delete-region (point) (+ (point) (- region-end region-start)))
11898 (delete-region
11899 (and (org-back-to-heading t) (point))
11900 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11901 (when (featurep 'org-inlinetask)
11902 (org-inlinetask-remove-END-maybe))
11903 (setq org-markers-to-move nil)
11904 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11906 (defun org-refile-goto-last-stored ()
11907 "Go to the location where the last refile was stored."
11908 (interactive)
11909 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11910 (message "This is the location of the last refile"))
11912 (defun org-refile--get-location (refloc tbl)
11913 "When user refile to REFLOC, find the associated target in TBL.
11914 Also check `org-refile-target-table'."
11915 (car (delq
11917 (mapcar
11918 (lambda (r) (or (assoc r tbl)
11919 (assoc r org-refile-target-table)))
11920 (list (replace-regexp-in-string "/$" "" refloc)
11921 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11923 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11924 no-exclude)
11925 "Prompt the user for a refile location, using PROMPT.
11926 PROMPT should not be suffixed with a colon and a space, because
11927 this function appends the default value from
11928 `org-refile-history' automatically, if that is not empty.
11929 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11930 this is used for the GOTO interface."
11931 (let ((org-refile-targets org-refile-targets)
11932 (org-refile-use-outline-path org-refile-use-outline-path)
11933 excluded-entries)
11934 (when (and (derived-mode-p 'org-mode)
11935 (not org-refile-use-cache)
11936 (not no-exclude))
11937 (org-map-tree
11938 (lambda()
11939 (setq excluded-entries
11940 (append excluded-entries (list (org-get-heading t t)))))))
11941 (setq org-refile-target-table
11942 (org-refile-get-targets default-buffer excluded-entries)))
11943 (unless org-refile-target-table
11944 (user-error "No refile targets"))
11945 (let* ((cbuf (current-buffer))
11946 (partial-completion-mode nil)
11947 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11948 (cfunc (if (and org-refile-use-outline-path
11949 org-outline-path-complete-in-steps)
11950 'org-olpath-completing-read
11951 'org-icompleting-read))
11952 (extra (if org-refile-use-outline-path "/" ""))
11953 (cbnex (concat (buffer-name) extra))
11954 (filename (and cfn (expand-file-name cfn)))
11955 (tbl (mapcar
11956 (lambda (x)
11957 (if (and (not (member org-refile-use-outline-path
11958 '(file full-file-path)))
11959 (not (equal filename (nth 1 x))))
11960 (cons (concat (car x) extra " ("
11961 (file-name-nondirectory (nth 1 x)) ")")
11962 (cdr x))
11963 (cons (concat (car x) extra) (cdr x))))
11964 org-refile-target-table))
11965 (completion-ignore-case t)
11966 cdef
11967 (prompt (concat prompt
11968 (or (and (car org-refile-history)
11969 (concat " (default " (car org-refile-history) ")"))
11970 (and (assoc cbnex tbl) (setq cdef cbnex)
11971 (concat " (default " cbnex ")"))) ": "))
11972 pa answ parent-target child parent old-hist)
11973 (setq old-hist org-refile-history)
11974 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11975 nil 'org-refile-history (or cdef (car org-refile-history))))
11976 (if (setq pa (org-refile--get-location answ tbl))
11977 (progn
11978 (org-refile-check-position pa)
11979 (when (or (not org-refile-history)
11980 (not (eq old-hist org-refile-history))
11981 (not (equal (car pa) (car org-refile-history))))
11982 (setq org-refile-history
11983 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11984 org-refile-history
11985 (cdr org-refile-history))))
11986 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11987 (pop org-refile-history)))
11989 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11990 (progn
11991 (setq parent (match-string 1 answ)
11992 child (match-string 2 answ))
11993 (setq parent-target (org-refile--get-location parent tbl))
11994 (when (and parent-target
11995 (or (eq new-nodes t)
11996 (and (eq new-nodes 'confirm)
11997 (y-or-n-p (format "Create new node \"%s\"? "
11998 child)))))
11999 (org-refile-new-child parent-target child)))
12000 (user-error "Invalid target location")))))
12002 (declare-function org-string-nw-p "org-macs" (s))
12003 (defun org-refile-check-position (refile-pointer)
12004 "Check if the refile pointer matches the headline to which it points."
12005 (let* ((file (nth 1 refile-pointer))
12006 (re (nth 2 refile-pointer))
12007 (pos (nth 3 refile-pointer))
12008 buffer)
12009 (if (and (not (markerp pos)) (not file))
12010 (user-error "Please indicate a target file in the refile path")
12011 (when (org-string-nw-p re)
12012 (setq buffer (if (markerp pos)
12013 (marker-buffer pos)
12014 (or (find-buffer-visiting file)
12015 (find-file-noselect file))))
12016 (with-current-buffer buffer
12017 (save-excursion
12018 (save-restriction
12019 (widen)
12020 (goto-char pos)
12021 (beginning-of-line 1)
12022 (unless (org-looking-at-p re)
12023 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12025 (defun org-refile-new-child (parent-target child)
12026 "Use refile target PARENT-TARGET to add new CHILD below it."
12027 (unless parent-target
12028 (error "Cannot find parent for new node"))
12029 (let ((file (nth 1 parent-target))
12030 (pos (nth 3 parent-target))
12031 level)
12032 (with-current-buffer (or (find-buffer-visiting file)
12033 (find-file-noselect file))
12034 (save-excursion
12035 (save-restriction
12036 (widen)
12037 (if pos
12038 (goto-char pos)
12039 (goto-char (point-max))
12040 (if (not (bolp)) (newline)))
12041 (when (looking-at org-outline-regexp)
12042 (setq level (funcall outline-level))
12043 (org-end-of-subtree t t))
12044 (org-back-over-empty-lines)
12045 (insert "\n" (make-string
12046 (if pos (org-get-valid-level level 1) 1) ?*)
12047 " " child "\n")
12048 (beginning-of-line 0)
12049 (list (concat (car parent-target) "/" child) file "" (point)))))))
12051 (defun org-olpath-completing-read (prompt collection &rest args)
12052 "Read an outline path like a file name."
12053 (let ((thetable collection)
12054 (org-completion-use-ido nil) ; does not work with ido.
12055 (org-completion-use-iswitchb nil)) ; or iswitchb
12056 (apply
12057 'org-icompleting-read prompt
12058 (lambda (string predicate &optional flag)
12059 (let (rtn r f (l (length string)))
12060 (cond
12061 ((eq flag nil)
12062 ;; try completion
12063 (try-completion string thetable))
12064 ((eq flag t)
12065 ;; all-completions
12066 (setq rtn (all-completions string thetable predicate))
12067 (mapcar
12068 (lambda (x)
12069 (setq r (substring x l))
12070 (if (string-match " ([^)]*)$" x)
12071 (setq f (match-string 0 x))
12072 (setq f ""))
12073 (if (string-match "/" r)
12074 (concat string (substring r 0 (match-end 0)) f)
12076 rtn))
12077 ((eq flag 'lambda)
12078 ;; exact match?
12079 (assoc string thetable)))))
12080 args)))
12082 ;;;; Dynamic blocks
12084 (defun org-find-dblock (name)
12085 "Find the first dynamic block with name NAME in the buffer.
12086 If not found, stay at current position and return nil."
12087 (let ((case-fold-search t) pos)
12088 (save-excursion
12089 (goto-char (point-min))
12090 (setq pos (and (re-search-forward
12091 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12092 (match-beginning 0))))
12093 (if pos (goto-char pos))
12094 pos))
12096 (defun org-create-dblock (plist)
12097 "Create a dynamic block section, with parameters taken from PLIST.
12098 PLIST must contain a :name entry which is used as the name of the block."
12099 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12100 (end-of-line 1)
12101 (newline))
12102 (let ((col (current-column))
12103 (name (plist-get plist :name)))
12104 (insert "#+BEGIN: " name)
12105 (while plist
12106 (if (eq (car plist) :name)
12107 (setq plist (cddr plist))
12108 (insert " " (prin1-to-string (pop plist)))))
12109 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12110 (beginning-of-line -2)))
12112 (defun org-prepare-dblock ()
12113 "Prepare dynamic block for refresh.
12114 This empties the block, puts the cursor at the insert position and returns
12115 the property list including an extra property :name with the block name."
12116 (unless (looking-at org-dblock-start-re)
12117 (user-error "Not at a dynamic block"))
12118 (let* ((begdel (1+ (match-end 0)))
12119 (name (org-no-properties (match-string 1)))
12120 (params (append (list :name name)
12121 (read (concat "(" (match-string 3) ")")))))
12122 (save-excursion
12123 (beginning-of-line 1)
12124 (skip-chars-forward " \t")
12125 (setq params (plist-put params :indentation-column (current-column))))
12126 (unless (re-search-forward org-dblock-end-re nil t)
12127 (error "Dynamic block not terminated"))
12128 (setq params
12129 (append params
12130 (list :content (buffer-substring
12131 begdel (match-beginning 0)))))
12132 (delete-region begdel (match-beginning 0))
12133 (goto-char begdel)
12134 (open-line 1)
12135 params))
12137 (defun org-map-dblocks (&optional command)
12138 "Apply COMMAND to all dynamic blocks in the current buffer.
12139 If COMMAND is not given, use `org-update-dblock'."
12140 (let ((cmd (or command 'org-update-dblock)))
12141 (save-excursion
12142 (goto-char (point-min))
12143 (while (re-search-forward org-dblock-start-re nil t)
12144 (goto-char (match-beginning 0))
12145 (save-excursion
12146 (condition-case nil
12147 (funcall cmd)
12148 (error (message "Error during update of dynamic block"))))
12149 (unless (re-search-forward org-dblock-end-re nil t)
12150 (error "Dynamic block not terminated"))))))
12152 (defun org-dblock-update (&optional arg)
12153 "User command for updating dynamic blocks.
12154 Update the dynamic block at point. With prefix ARG, update all dynamic
12155 blocks in the buffer."
12156 (interactive "P")
12157 (if arg
12158 (org-update-all-dblocks)
12159 (or (looking-at org-dblock-start-re)
12160 (org-beginning-of-dblock))
12161 (org-update-dblock)))
12163 (defun org-update-dblock ()
12164 "Update the dynamic block at point.
12165 This means to empty the block, parse for parameters and then call
12166 the correct writing function."
12167 (interactive)
12168 (save-excursion
12169 (let* ((win (selected-window))
12170 (pos (point))
12171 (line (org-current-line))
12172 (params (org-prepare-dblock))
12173 (name (plist-get params :name))
12174 (indent (plist-get params :indentation-column))
12175 (cmd (intern (concat "org-dblock-write:" name))))
12176 (message "Updating dynamic block `%s' at line %d..." name line)
12177 (funcall cmd params)
12178 (message "Updating dynamic block `%s' at line %d...done" name line)
12179 (goto-char pos)
12180 (when (and indent (> indent 0))
12181 (setq indent (make-string indent ?\ ))
12182 (save-excursion
12183 (select-window win)
12184 (org-beginning-of-dblock)
12185 (forward-line 1)
12186 (while (not (looking-at org-dblock-end-re))
12187 (insert indent)
12188 (beginning-of-line 2))
12189 (when (looking-at org-dblock-end-re)
12190 (and (looking-at "[ \t]+")
12191 (replace-match ""))
12192 (insert indent)))))))
12194 (defun org-beginning-of-dblock ()
12195 "Find the beginning of the dynamic block at point.
12196 Error if there is no such block at point."
12197 (let ((pos (point))
12198 beg)
12199 (end-of-line 1)
12200 (if (and (re-search-backward org-dblock-start-re nil t)
12201 (setq beg (match-beginning 0))
12202 (re-search-forward org-dblock-end-re nil t)
12203 (> (match-end 0) pos))
12204 (goto-char beg)
12205 (goto-char pos)
12206 (error "Not in a dynamic block"))))
12208 (defun org-update-all-dblocks ()
12209 "Update all dynamic blocks in the buffer.
12210 This function can be used in a hook."
12211 (interactive)
12212 (when (derived-mode-p 'org-mode)
12213 (org-map-dblocks 'org-update-dblock)))
12216 ;;;; Completion
12218 (declare-function org-export-backend-name "org-export" (cl-x))
12219 (declare-function org-export-backend-options "org-export" (cl-x))
12220 (defun org-get-export-keywords ()
12221 "Return a list of all currently understood export keywords.
12222 Export keywords include options, block names, attributes and
12223 keywords relative to each registered export back-end."
12224 (let (keywords)
12225 (dolist (backend
12226 (org-bound-and-true-p org-export--registered-backends)
12227 (delq nil keywords))
12228 ;; Back-end name (for keywords, like #+LATEX:)
12229 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12230 (dolist (option-entry (org-export-backend-options backend))
12231 ;; Back-end options.
12232 (push (nth 1 option-entry) keywords)))))
12234 (defconst org-options-keywords
12235 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12236 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12237 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12238 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12239 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12241 (defcustom org-structure-template-alist
12242 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12243 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12244 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12245 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12246 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12247 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12248 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12249 ("L" "#+LaTeX: ")
12250 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12251 ("H" "#+HTML: ")
12252 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12253 ("A" "#+ASCII: ")
12254 ("i" "#+INDEX: ?")
12255 ("I" "#+INCLUDE: %file ?"))
12256 "Structure completion elements.
12257 This is a list of abbreviation keys and values. The value gets inserted
12258 if you type `<' followed by the key and then press the completion key,
12259 usually `TAB'. %file will be replaced by a file name after prompting
12260 for the file using completion. The cursor will be placed at the position
12261 of the `?` in the template.
12262 There are two templates for each key, the first uses the original Org syntax,
12263 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12264 the default when the /org-mtags.el/ module has been loaded. See also the
12265 variable `org-mtags-prefer-muse-templates'."
12266 :group 'org-completion
12267 :type '(repeat
12268 (list
12269 (string :tag "Key")
12270 (string :tag "Template")))
12271 :version 24.4
12272 :package-version '(Org . "8.3"))
12274 (defun org-try-structure-completion ()
12275 "Try to complete a structure template before point.
12276 This looks for strings like \"<e\" on an otherwise empty line and
12277 expands them."
12278 (let ((l (buffer-substring (point-at-bol) (point)))
12280 (when (and (looking-at "[ \t]*$")
12281 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12282 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12283 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12284 (match-beginning 1)) a)
12285 t)))
12287 (defun org-complete-expand-structure-template (start cell)
12288 "Expand a structure template."
12289 (let ((rpl (nth 1 cell))
12290 (ind ""))
12291 (delete-region start (point))
12292 (when (string-match "\\`[ \t]*#\\+" rpl)
12293 (cond
12294 ((bolp))
12295 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12296 (setq ind (buffer-substring (point-at-bol) (point))))
12297 (t (newline))))
12298 (setq start (point))
12299 (if (string-match "%file" rpl)
12300 (setq rpl (replace-match
12301 (concat
12302 "\""
12303 (save-match-data
12304 (abbreviate-file-name (read-file-name "Include file: ")))
12305 "\"")
12306 t t rpl)))
12307 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12308 (concat "\n" ind)))
12309 (insert rpl)
12310 (if (re-search-backward "\\?" start t) (delete-char 1))))
12312 ;;;; TODO, DEADLINE, Comments
12314 (defun org-toggle-comment ()
12315 "Change the COMMENT state of an entry."
12316 (interactive)
12317 (save-excursion
12318 (org-back-to-heading)
12319 (looking-at org-complex-heading-regexp)
12320 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12321 (skip-chars-forward " \t")
12322 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12323 (if (org-in-commented-heading-p t)
12324 (delete-region (point)
12325 (progn (search-forward " " (line-end-position) 'move)
12326 (skip-chars-forward " \t")
12327 (point)))
12328 (insert org-comment-string)
12329 (unless (eolp) (insert " ")))))
12331 (defvar org-last-todo-state-is-todo nil
12332 "This is non-nil when the last TODO state change led to a TODO state.
12333 If the last change removed the TODO tag or switched to DONE, then
12334 this is nil.")
12336 (defvar org-setting-tags nil) ; dynamically skipped
12338 (defvar org-todo-setup-filter-hook nil
12339 "Hook for functions that pre-filter todo specs.
12340 Each function takes a todo spec and returns either nil or the spec
12341 transformed into canonical form." )
12343 (defvar org-todo-get-default-hook nil
12344 "Hook for functions that get a default item for todo.
12345 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12346 nil or a string to be used for the todo mark." )
12348 (defvar org-agenda-headline-snapshot-before-repeat)
12350 (defun org-current-effective-time ()
12351 "Return current time adjusted for `org-extend-today-until' variable."
12352 (let* ((ct (org-current-time))
12353 (dct (decode-time ct))
12354 (ct1
12355 (cond
12356 (org-use-last-clock-out-time-as-effective-time
12357 (or (org-clock-get-last-clock-out-time) ct))
12358 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12359 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12360 (t ct))))
12361 ct1))
12363 (defun org-todo-yesterday (&optional arg)
12364 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12365 (interactive "P")
12366 (if (eq major-mode 'org-agenda-mode)
12367 (apply 'org-agenda-todo-yesterday arg)
12368 (let* ((hour (third (decode-time
12369 (org-current-time))))
12370 (org-extend-today-until (1+ hour)))
12371 (org-todo arg))))
12373 (defvar org-block-entry-blocking ""
12374 "First entry preventing the TODO state change.")
12376 (defun org-cancel-repeater ()
12377 "Cancel a repeater by setting its numeric value to zero."
12378 (interactive)
12379 (save-excursion
12380 (org-back-to-heading t)
12381 (let ((bound1 (point))
12382 (bound0 (save-excursion (outline-next-heading) (point))))
12383 (when (re-search-forward
12384 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12385 org-deadline-time-regexp "\\)\\|\\("
12386 org-ts-regexp "\\)")
12387 bound0 t)
12388 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12389 (replace-match "0" t nil nil 1))))))
12391 (defun org-todo (&optional arg)
12392 "Change the TODO state of an item.
12393 The state of an item is given by a keyword at the start of the heading,
12394 like
12395 *** TODO Write paper
12396 *** DONE Call mom
12398 The different keywords are specified in the variable `org-todo-keywords'.
12399 By default the available states are \"TODO\" and \"DONE\".
12400 So for this example: when the item starts with TODO, it is changed to DONE.
12401 When it starts with DONE, the DONE is removed. And when neither TODO nor
12402 DONE are present, add TODO at the beginning of the heading.
12404 With \\[universal-argument] prefix arg, use completion to determine the new \
12405 state.
12406 With numeric prefix arg, switch to that state.
12407 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12408 keywords (nextset).
12409 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12410 With a numeric prefix arg of 0, inhibit note taking for the change.
12411 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12413 When called through ELisp, arg is also interpreted in the following way:
12414 'none -> empty state
12415 \"\"(empty string) -> switch to empty state
12416 'done -> switch to DONE
12417 'nextset -> switch to the next set of keywords
12418 'previousset -> switch to the previous set of keywords
12419 \"WAITING\" -> switch to the specified keyword, but only if it
12420 really is a member of `org-todo-keywords'."
12421 (interactive "P")
12422 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12423 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12424 'region-start-level 'region))
12425 org-loop-over-headlines-in-active-region)
12426 (org-map-entries
12427 `(org-todo ,arg)
12428 org-loop-over-headlines-in-active-region
12429 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12430 (if (equal arg '(16)) (setq arg 'nextset))
12431 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12432 (let ((org-blocker-hook org-blocker-hook)
12433 commentp
12434 case-fold-search)
12435 (when (equal arg '(64))
12436 (setq arg nil org-blocker-hook nil))
12437 (when (and org-blocker-hook
12438 (or org-inhibit-blocking
12439 (org-entry-get nil "NOBLOCKING")))
12440 (setq org-blocker-hook nil))
12441 (save-excursion
12442 (catch 'exit
12443 (org-back-to-heading t)
12444 (when (org-in-commented-heading-p t)
12445 (org-toggle-comment)
12446 (setq commentp t))
12447 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12448 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12449 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12450 (let* ((match-data (match-data))
12451 (startpos (point-at-bol))
12452 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12453 (org-log-done org-log-done)
12454 (org-log-repeat org-log-repeat)
12455 (org-todo-log-states org-todo-log-states)
12456 (org-inhibit-logging
12457 (if (equal arg 0)
12458 (progn (setq arg nil) 'note) org-inhibit-logging))
12459 (this (match-string 1))
12460 (hl-pos (match-beginning 0))
12461 (head (org-get-todo-sequence-head this))
12462 (ass (assoc head org-todo-kwd-alist))
12463 (interpret (nth 1 ass))
12464 (done-word (nth 3 ass))
12465 (final-done-word (nth 4 ass))
12466 (org-last-state (or this ""))
12467 (completion-ignore-case t)
12468 (member (member this org-todo-keywords-1))
12469 (tail (cdr member))
12470 (org-state (cond
12471 ((and org-todo-key-trigger
12472 (or (and (equal arg '(4))
12473 (eq org-use-fast-todo-selection 'prefix))
12474 (and (not arg) org-use-fast-todo-selection
12475 (not (eq org-use-fast-todo-selection
12476 'prefix)))))
12477 ;; Use fast selection
12478 (org-fast-todo-selection))
12479 ((and (equal arg '(4))
12480 (or (not org-use-fast-todo-selection)
12481 (not org-todo-key-trigger)))
12482 ;; Read a state with completion
12483 (org-icompleting-read
12484 "State: " (mapcar 'list org-todo-keywords-1)
12485 nil t))
12486 ((eq arg 'right)
12487 (if this
12488 (if tail (car tail) nil)
12489 (car org-todo-keywords-1)))
12490 ((eq arg 'left)
12491 (if (equal member org-todo-keywords-1)
12493 (if this
12494 (nth (- (length org-todo-keywords-1)
12495 (length tail) 2)
12496 org-todo-keywords-1)
12497 (org-last org-todo-keywords-1))))
12498 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12499 (setq arg nil))) ; hack to fall back to cycling
12500 (arg
12501 ;; user or caller requests a specific state
12502 (cond
12503 ((equal arg "") nil)
12504 ((eq arg 'none) nil)
12505 ((eq arg 'done) (or done-word (car org-done-keywords)))
12506 ((eq arg 'nextset)
12507 (or (car (cdr (member head org-todo-heads)))
12508 (car org-todo-heads)))
12509 ((eq arg 'previousset)
12510 (let ((org-todo-heads (reverse org-todo-heads)))
12511 (or (car (cdr (member head org-todo-heads)))
12512 (car org-todo-heads))))
12513 ((car (member arg org-todo-keywords-1)))
12514 ((stringp arg)
12515 (user-error "State `%s' not valid in this file" arg))
12516 ((nth (1- (prefix-numeric-value arg))
12517 org-todo-keywords-1))))
12518 ((null member) (or head (car org-todo-keywords-1)))
12519 ((equal this final-done-word) nil) ;; -> make empty
12520 ((null tail) nil) ;; -> first entry
12521 ((memq interpret '(type priority))
12522 (if (eq this-command last-command)
12523 (car tail)
12524 (if (> (length tail) 0)
12525 (or done-word (car org-done-keywords))
12526 nil)))
12528 (car tail))))
12529 (org-state (or
12530 (run-hook-with-args-until-success
12531 'org-todo-get-default-hook org-state org-last-state)
12532 org-state))
12533 (next (if org-state (concat " " org-state " ") " "))
12534 (change-plist (list :type 'todo-state-change :from this :to org-state
12535 :position startpos))
12536 dolog now-done-p)
12537 (when org-blocker-hook
12538 (setq org-last-todo-state-is-todo
12539 (not (member this org-done-keywords)))
12540 (unless (save-excursion
12541 (save-match-data
12542 (org-with-wide-buffer
12543 (run-hook-with-args-until-failure
12544 'org-blocker-hook change-plist))))
12545 (if (org-called-interactively-p 'interactive)
12546 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12547 this org-state org-block-entry-blocking)
12548 ;; fail silently
12549 (message "TODO state change from %s to %s blocked (by \"%s\")"
12550 this org-state org-block-entry-blocking)
12551 (throw 'exit nil))))
12552 (store-match-data match-data)
12553 (replace-match next t t)
12554 (cond ((equal this org-state)
12555 (message "TODO state was already %s" (org-trim next)))
12556 ((pos-visible-in-window-p hl-pos)
12557 (message "TODO state changed to %s" (org-trim next))))
12558 (unless head
12559 (setq head (org-get-todo-sequence-head org-state)
12560 ass (assoc head org-todo-kwd-alist)
12561 interpret (nth 1 ass)
12562 done-word (nth 3 ass)
12563 final-done-word (nth 4 ass)))
12564 (when (memq arg '(nextset previousset))
12565 (message "Keyword-Set %d/%d: %s"
12566 (- (length org-todo-sets) -1
12567 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12568 (length org-todo-sets)
12569 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12570 (setq org-last-todo-state-is-todo
12571 (not (member org-state org-done-keywords)))
12572 (setq now-done-p (and (member org-state org-done-keywords)
12573 (not (member this org-done-keywords))))
12574 (and logging (org-local-logging logging))
12575 (when (and (or org-todo-log-states org-log-done)
12576 (not (eq org-inhibit-logging t))
12577 (not (memq arg '(nextset previousset))))
12578 ;; we need to look at recording a time and note
12579 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12580 (nth 2 (assoc this org-todo-log-states))))
12581 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12582 (setq dolog 'time))
12583 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12584 (and org-state
12585 (member org-state org-not-done-keywords)
12586 (not (member this org-not-done-keywords))))
12587 ;; This is now a todo state and was not one before
12588 ;; If there was a CLOSED time stamp, get rid of it.
12589 (org-add-planning-info nil nil 'closed))
12590 (when (and now-done-p org-log-done)
12591 ;; It is now done, and it was not done before
12592 (org-add-planning-info 'closed (org-current-effective-time))
12593 (if (and (not dolog) (eq 'note org-log-done))
12594 (org-add-log-setup 'done org-state this 'findpos 'note)))
12595 (when (and org-state dolog)
12596 ;; This is a non-nil state, and we need to log it
12597 (org-add-log-setup 'state org-state this 'findpos dolog)))
12598 ;; Fixup tag positioning
12599 (org-todo-trigger-tag-changes org-state)
12600 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12601 (when org-provide-todo-statistics
12602 (org-update-parent-todo-statistics))
12603 (run-hooks 'org-after-todo-state-change-hook)
12604 (if (and arg (not (member org-state org-done-keywords)))
12605 (setq head (org-get-todo-sequence-head org-state)))
12606 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12607 ;; Do we need to trigger a repeat?
12608 (when now-done-p
12609 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12610 ;; This is for the agenda, take a snapshot of the headline.
12611 (save-match-data
12612 (setq org-agenda-headline-snapshot-before-repeat
12613 (org-get-heading))))
12614 (org-auto-repeat-maybe org-state))
12615 ;; Fixup cursor location if close to the keyword
12616 (if (and (outline-on-heading-p)
12617 (not (bolp))
12618 (save-excursion (beginning-of-line 1)
12619 (looking-at org-todo-line-regexp))
12620 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12621 (progn
12622 (goto-char (or (match-end 2) (match-end 1)))
12623 (and (looking-at " ") (just-one-space))))
12624 (when org-trigger-hook
12625 (save-excursion
12626 (run-hook-with-args 'org-trigger-hook change-plist)))
12627 (when commentp (org-toggle-comment))))))))
12629 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12630 "Block turning an entry into a TODO, using the hierarchy.
12631 This checks whether the current task should be blocked from state
12632 changes. Such blocking occurs when:
12634 1. The task has children which are not all in a completed state.
12636 2. A task has a parent with the property :ORDERED:, and there
12637 are siblings prior to the current task with incomplete
12638 status.
12640 3. The parent of the task is blocked because it has siblings that should
12641 be done first, or is child of a block grandparent TODO entry."
12643 (if (not org-enforce-todo-dependencies)
12644 t ; if locally turned off don't block
12645 (catch 'dont-block
12646 ;; If this is not a todo state change, or if this entry is already DONE,
12647 ;; do not block
12648 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12649 (member (plist-get change-plist :from)
12650 (cons 'done org-done-keywords))
12651 (member (plist-get change-plist :to)
12652 (cons 'todo org-not-done-keywords))
12653 (not (plist-get change-plist :to)))
12654 (throw 'dont-block t))
12655 ;; If this task has children, and any are undone, it's blocked
12656 (save-excursion
12657 (org-back-to-heading t)
12658 (let ((this-level (funcall outline-level)))
12659 (outline-next-heading)
12660 (let ((child-level (funcall outline-level)))
12661 (while (and (not (eobp))
12662 (> child-level this-level))
12663 ;; this todo has children, check whether they are all
12664 ;; completed
12665 (if (and (not (org-entry-is-done-p))
12666 (org-entry-is-todo-p))
12667 (progn (setq org-block-entry-blocking (org-get-heading))
12668 (throw 'dont-block nil)))
12669 (outline-next-heading)
12670 (setq child-level (funcall outline-level))))))
12671 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12672 ;; any previous siblings are undone, it's blocked
12673 (save-excursion
12674 (org-back-to-heading t)
12675 (let* ((pos (point))
12676 (parent-pos (and (org-up-heading-safe) (point))))
12677 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12678 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12679 (forward-line 1)
12680 (re-search-forward org-not-done-heading-regexp pos t))
12681 (setq org-block-entry-blocking (match-string 0))
12682 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12683 ;; Search further up the hierarchy, to see if an ancestor is blocked
12684 (while t
12685 (goto-char parent-pos)
12686 (if (not (looking-at org-not-done-heading-regexp))
12687 (throw 'dont-block t)) ; do not block, parent is not a TODO
12688 (setq pos (point))
12689 (setq parent-pos (and (org-up-heading-safe) (point)))
12690 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12691 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12692 (forward-line 1)
12693 (re-search-forward org-not-done-heading-regexp pos t)
12694 (setq org-block-entry-blocking (org-get-heading)))
12695 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12697 (defcustom org-track-ordered-property-with-tag nil
12698 "Should the ORDERED property also be shown as a tag?
12699 The ORDERED property decides if an entry should require subtasks to be
12700 completed in sequence. Since a property is not very visible, setting
12701 this option means that toggling the ORDERED property with the command
12702 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12703 not relevant for the behavior, but it makes things more visible.
12705 Note that toggling the tag with tags commands will not change the property
12706 and therefore not influence behavior!
12708 This can be t, meaning the tag ORDERED should be used, It can also be a
12709 string to select a different tag for this task."
12710 :group 'org-todo
12711 :type '(choice
12712 (const :tag "No tracking" nil)
12713 (const :tag "Track with ORDERED tag" t)
12714 (string :tag "Use other tag")))
12716 (defun org-toggle-ordered-property ()
12717 "Toggle the ORDERED property of the current entry.
12718 For better visibility, you can track the value of this property with a tag.
12719 See variable `org-track-ordered-property-with-tag'."
12720 (interactive)
12721 (let* ((t1 org-track-ordered-property-with-tag)
12722 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12723 (save-excursion
12724 (org-back-to-heading)
12725 (if (org-entry-get nil "ORDERED")
12726 (progn
12727 (org-delete-property "ORDERED")
12728 (and tag (org-toggle-tag tag 'off))
12729 (message "Subtasks can be completed in arbitrary order"))
12730 (org-entry-put nil "ORDERED" "t")
12731 (and tag (org-toggle-tag tag 'on))
12732 (message "Subtasks must be completed in sequence")))))
12734 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12735 (defun org-block-todo-from-checkboxes (change-plist)
12736 "Block turning an entry into a TODO, using checkboxes.
12737 This checks whether the current task should be blocked from state
12738 changes because there are unchecked boxes in this entry."
12739 (if (not org-enforce-todo-checkbox-dependencies)
12740 t ; if locally turned off don't block
12741 (catch 'dont-block
12742 ;; If this is not a todo state change, or if this entry is already DONE,
12743 ;; do not block
12744 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12745 (member (plist-get change-plist :from)
12746 (cons 'done org-done-keywords))
12747 (member (plist-get change-plist :to)
12748 (cons 'todo org-not-done-keywords))
12749 (not (plist-get change-plist :to)))
12750 (throw 'dont-block t))
12751 ;; If this task has checkboxes that are not checked, it's blocked
12752 (save-excursion
12753 (org-back-to-heading t)
12754 (let ((beg (point)) end)
12755 (outline-next-heading)
12756 (setq end (point))
12757 (goto-char beg)
12758 (if (org-list-search-forward
12759 (concat (org-item-beginning-re)
12760 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12761 "\\[[- ]\\]")
12762 end t)
12763 (progn
12764 (if (boundp 'org-blocked-by-checkboxes)
12765 (setq org-blocked-by-checkboxes t))
12766 (throw 'dont-block nil)))))
12767 t))) ; do not block
12769 (defun org-entry-blocked-p ()
12770 "Is the current entry blocked?"
12771 (org-with-silent-modifications
12772 (if (org-entry-get nil "NOBLOCKING")
12773 nil ;; Never block this entry
12774 (not (run-hook-with-args-until-failure
12775 'org-blocker-hook
12776 (list :type 'todo-state-change
12777 :position (point)
12778 :from 'todo
12779 :to 'done))))))
12781 (defun org-update-statistics-cookies (all)
12782 "Update the statistics cookie, either from TODO or from checkboxes.
12783 This should be called with the cursor in a line with a statistics cookie."
12784 (interactive "P")
12785 (if all
12786 (progn
12787 (org-update-checkbox-count 'all)
12788 (org-map-entries 'org-update-parent-todo-statistics))
12789 (if (not (org-at-heading-p))
12790 (org-update-checkbox-count)
12791 (let ((pos (point-marker))
12792 end l1 l2)
12793 (ignore-errors (org-back-to-heading t))
12794 (if (not (org-at-heading-p))
12795 (org-update-checkbox-count)
12796 (setq l1 (org-outline-level))
12797 (setq end (save-excursion
12798 (outline-next-heading)
12799 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12800 (point)))
12801 (if (and (save-excursion
12802 (re-search-forward
12803 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12804 (not (save-excursion (re-search-forward
12805 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12806 (org-update-checkbox-count)
12807 (if (and l2 (> l2 l1))
12808 (progn
12809 (goto-char end)
12810 (org-update-parent-todo-statistics))
12811 (goto-char pos)
12812 (beginning-of-line 1)
12813 (while (re-search-forward
12814 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12815 (point-at-eol) t)
12816 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12817 (goto-char pos)
12818 (move-marker pos nil)))))
12820 (defvar org-entry-property-inherited-from) ;; defined below
12821 (defun org-update-parent-todo-statistics ()
12822 "Update any statistics cookie in the parent of the current headline.
12823 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12824 the entire subtree and this will travel up the hierarchy and update
12825 statistics everywhere."
12826 (let* ((prop (save-excursion (org-up-heading-safe)
12827 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12828 (recursive (or (not org-hierarchical-todo-statistics)
12829 (and prop (string-match "\\<recursive\\>" prop))))
12830 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12832 (first t)
12833 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12834 level ltoggle l1 new ndel
12835 (cnt-all 0) (cnt-done 0) is-percent kwd
12836 checkbox-beg ov ovs ove cookie-present)
12837 (catch 'exit
12838 (save-excursion
12839 (beginning-of-line 1)
12840 (setq ltoggle (funcall outline-level))
12841 ;; Three situations are to consider:
12843 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12844 ;; to the top-level ancestor on the headline;
12846 ;; 2. If parent has "recursive" property, repeat up to the
12847 ;; headline setting that property, taking inheritance into
12848 ;; account;
12850 ;; 3. Else, move up to direct parent and proceed only once.
12851 (while (and (setq level (org-up-heading-safe))
12852 (or recursive first)
12853 (>= (point) lim))
12854 (setq first nil cookie-present nil)
12855 (unless (and level
12856 (not (string-match
12857 "\\<checkbox\\>"
12858 (downcase (or (org-entry-get nil "COOKIE_DATA")
12859 "")))))
12860 (throw 'exit nil))
12861 (while (re-search-forward box-re (point-at-eol) t)
12862 (setq cnt-all 0 cnt-done 0 cookie-present t)
12863 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12864 (save-match-data
12865 (unless (outline-next-heading) (throw 'exit nil))
12866 (while (and (looking-at org-complex-heading-regexp)
12867 (> (setq l1 (length (match-string 1))) level))
12868 (setq kwd (and (or recursive (= l1 ltoggle))
12869 (match-string 2)))
12870 (if (or (eq org-provide-todo-statistics 'all-headlines)
12871 (and (eq org-provide-todo-statistics t)
12872 (or (member kwd org-done-keywords)))
12873 (and (listp org-provide-todo-statistics)
12874 (stringp (car org-provide-todo-statistics))
12875 (or (member kwd org-provide-todo-statistics)
12876 (member kwd org-done-keywords)))
12877 (and (listp org-provide-todo-statistics)
12878 (listp (car org-provide-todo-statistics))
12879 (or (member kwd (car org-provide-todo-statistics))
12880 (and (member kwd org-done-keywords)
12881 (member kwd (cadr org-provide-todo-statistics))))))
12882 (setq cnt-all (1+ cnt-all))
12883 (if (eq org-provide-todo-statistics t)
12884 (and kwd (setq cnt-all (1+ cnt-all)))))
12885 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12886 (member kwd org-done-keywords))
12887 (and (listp org-provide-todo-statistics)
12888 (listp (car org-provide-todo-statistics))
12889 (member kwd org-done-keywords)
12890 (member kwd (cadr org-provide-todo-statistics)))
12891 (and (listp org-provide-todo-statistics)
12892 (stringp (car org-provide-todo-statistics))
12893 (member kwd org-done-keywords)))
12894 (setq cnt-done (1+ cnt-done)))
12895 (outline-next-heading)))
12896 (setq new
12897 (if is-percent
12898 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12899 (format "[%d/%d]" cnt-done cnt-all))
12900 ndel (- (match-end 0) checkbox-beg))
12901 ;; handle overlays when updating cookie from column view
12902 (when (setq ov (car (overlays-at checkbox-beg)))
12903 (setq ovs (overlay-start ov) ove (overlay-end ov))
12904 (delete-overlay ov))
12905 (goto-char checkbox-beg)
12906 (insert new)
12907 (delete-region (point) (+ (point) ndel))
12908 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12909 (when ov (move-overlay ov ovs ove)))
12910 (when cookie-present
12911 (run-hook-with-args 'org-after-todo-statistics-hook
12912 cnt-done (- cnt-all cnt-done))))))
12913 (run-hooks 'org-todo-statistics-hook)))
12915 (defvar org-after-todo-statistics-hook nil
12916 "Hook that is called after a TODO statistics cookie has been updated.
12917 Each function is called with two arguments: the number of not-done entries
12918 and the number of done entries.
12920 For example, the following function, when added to this hook, will switch
12921 an entry to DONE when all children are done, and back to TODO when new
12922 entries are set to a TODO status. Note that this hook is only called
12923 when there is a statistics cookie in the headline!
12925 (defun org-summary-todo (n-done n-not-done)
12926 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12927 (let (org-log-done org-log-states) ; turn off logging
12928 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12931 (defvar org-todo-statistics-hook nil
12932 "Hook that is run whenever Org thinks TODO statistics should be updated.
12933 This hook runs even if there is no statistics cookie present, in which case
12934 `org-after-todo-statistics-hook' would not run.")
12936 (defun org-todo-trigger-tag-changes (state)
12937 "Apply the changes defined in `org-todo-state-tags-triggers'."
12938 (let ((l org-todo-state-tags-triggers)
12939 changes)
12940 (when (or (not state) (equal state ""))
12941 (setq changes (append changes (cdr (assoc "" l)))))
12942 (when (and (stringp state) (> (length state) 0))
12943 (setq changes (append changes (cdr (assoc state l)))))
12944 (when (member state org-not-done-keywords)
12945 (setq changes (append changes (cdr (assoc 'todo l)))))
12946 (when (member state org-done-keywords)
12947 (setq changes (append changes (cdr (assoc 'done l)))))
12948 (dolist (c changes)
12949 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12951 (defun org-local-logging (value)
12952 "Get logging settings from a property VALUE."
12953 (let* (words w a)
12954 ;; directly set the variables, they are already local.
12955 (setq org-log-done nil
12956 org-log-repeat nil
12957 org-todo-log-states nil)
12958 (setq words (org-split-string value))
12959 (while (setq w (pop words))
12960 (cond
12961 ((setq a (assoc w org-startup-options))
12962 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12963 (set (nth 1 a) (nth 2 a))))
12964 ((setq a (org-extract-log-state-settings w))
12965 (and (member (car a) org-todo-keywords-1)
12966 (push a org-todo-log-states)))))))
12968 (defun org-get-todo-sequence-head (kwd)
12969 "Return the head of the TODO sequence to which KWD belongs.
12970 If KWD is not set, check if there is a text property remembering the
12971 right sequence."
12972 (let (p)
12973 (cond
12974 ((not kwd)
12975 (or (get-text-property (point-at-bol) 'org-todo-head)
12976 (progn
12977 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12978 nil (point-at-eol)))
12979 (get-text-property p 'org-todo-head))))
12980 ((not (member kwd org-todo-keywords-1))
12981 (car org-todo-keywords-1))
12982 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12984 (defun org-fast-todo-selection ()
12985 "Fast TODO keyword selection with single keys.
12986 Returns the new TODO keyword, or nil if no state change should occur."
12987 (let* ((fulltable org-todo-key-alist)
12988 (done-keywords org-done-keywords) ;; needed for the faces.
12989 (maxlen (apply 'max (mapcar
12990 (lambda (x)
12991 (if (stringp (car x)) (string-width (car x)) 0))
12992 fulltable)))
12993 (expert nil)
12994 (fwidth (+ maxlen 3 1 3))
12995 (ncol (/ (- (window-width) 4) fwidth))
12996 tg cnt e c tbl
12997 groups ingroup)
12998 (save-excursion
12999 (save-window-excursion
13000 (if expert
13001 (set-buffer (get-buffer-create " *Org todo*"))
13002 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13003 (erase-buffer)
13004 (org-set-local 'org-done-keywords done-keywords)
13005 (setq tbl fulltable cnt 0)
13006 (while (setq e (pop tbl))
13007 (cond
13008 ((equal e '(:startgroup))
13009 (push '() groups) (setq ingroup t)
13010 (when (not (= cnt 0))
13011 (setq cnt 0)
13012 (insert "\n"))
13013 (insert "{ "))
13014 ((equal e '(:endgroup))
13015 (setq ingroup nil cnt 0)
13016 (insert "}\n"))
13017 ((equal e '(:newline))
13018 (when (not (= cnt 0))
13019 (setq cnt 0)
13020 (insert "\n")
13021 (setq e (car tbl))
13022 (while (equal (car tbl) '(:newline))
13023 (insert "\n")
13024 (setq tbl (cdr tbl)))))
13026 (setq tg (car e) c (cdr e))
13027 (if ingroup (push tg (car groups)))
13028 (setq tg (org-add-props tg nil 'face
13029 (org-get-todo-face tg)))
13030 (if (and (= cnt 0) (not ingroup)) (insert " "))
13031 (insert "[" c "] " tg (make-string
13032 (- fwidth 4 (length tg)) ?\ ))
13033 (when (= (setq cnt (1+ cnt)) ncol)
13034 (insert "\n")
13035 (if ingroup (insert " "))
13036 (setq cnt 0)))))
13037 (insert "\n")
13038 (goto-char (point-min))
13039 (if (not expert) (org-fit-window-to-buffer))
13040 (message "[a-z..]:Set [SPC]:clear")
13041 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13042 (cond
13043 ((or (= c ?\C-g)
13044 (and (= c ?q) (not (rassoc c fulltable))))
13045 (setq quit-flag t))
13046 ((= c ?\ ) nil)
13047 ((setq e (rassoc c fulltable) tg (car e))
13049 (t (setq quit-flag t)))))))
13051 (defun org-entry-is-todo-p ()
13052 (member (org-get-todo-state) org-not-done-keywords))
13054 (defun org-entry-is-done-p ()
13055 (member (org-get-todo-state) org-done-keywords))
13057 (defun org-get-todo-state ()
13058 "Return the TODO keyword of the current subtree."
13059 (save-excursion
13060 (org-back-to-heading t)
13061 (and (looking-at org-todo-line-regexp)
13062 (match-end 2)
13063 (match-string 2))))
13065 (defun org-at-date-range-p (&optional inactive-ok)
13066 "Is the cursor inside a date range?"
13067 (interactive)
13068 (save-excursion
13069 (catch 'exit
13070 (let ((pos (point)))
13071 (skip-chars-backward "^[<\r\n")
13072 (skip-chars-backward "<[")
13073 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13074 (>= (match-end 0) pos)
13075 (throw 'exit t))
13076 (skip-chars-backward "^<[\r\n")
13077 (skip-chars-backward "<[")
13078 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13079 (>= (match-end 0) pos)
13080 (throw 'exit t)))
13081 nil)))
13083 (defun org-get-repeat (&optional tagline)
13084 "Check if there is a deadline/schedule with repeater in this entry."
13085 (save-match-data
13086 (save-excursion
13087 (org-back-to-heading t)
13088 (and (re-search-forward (if tagline
13089 (concat tagline "\\s-*" org-repeat-re)
13090 org-repeat-re)
13091 (org-entry-end-position) t)
13092 (match-string-no-properties 1)))))
13094 (defvar org-last-changed-timestamp)
13095 (defvar org-last-inserted-timestamp)
13096 (defvar org-log-post-message)
13097 (defvar org-log-note-purpose)
13098 (defvar org-log-note-how nil)
13099 (defvar org-log-note-extra)
13100 (defun org-auto-repeat-maybe (done-word)
13101 "Check if the current headline contains a repeated deadline/schedule.
13102 If yes, set TODO state back to what it was and change the base date
13103 of repeating deadline/scheduled time stamps to new date.
13104 This function is run automatically after each state change to a DONE state."
13105 ;; last-state is dynamically scoped into this function
13106 (let* ((repeat (org-get-repeat))
13107 (aa (assoc org-last-state org-todo-kwd-alist))
13108 (interpret (nth 1 aa))
13109 (head (nth 2 aa))
13110 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13111 (msg "Entry repeats: ")
13112 (org-log-done nil)
13113 (org-todo-log-states nil)
13114 re type n what ts time to-state)
13115 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13116 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13117 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13118 org-todo-repeat-to-state))
13119 (unless (and to-state (member to-state org-todo-keywords-1))
13120 (setq to-state (if (eq interpret 'type) org-last-state head)))
13121 (org-todo to-state)
13122 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13123 (org-entry-put nil "LAST_REPEAT" (format-time-string
13124 (org-time-stamp-format t t))))
13125 (when org-log-repeat
13126 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13127 (memq 'org-add-log-note post-command-hook))
13128 ;; OK, we are already setup for some record
13129 (if (eq org-log-repeat 'note)
13130 ;; make sure we take a note, not only a time stamp
13131 (setq org-log-note-how 'note))
13132 ;; Set up for taking a record
13133 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13134 org-last-state
13135 'findpos org-log-repeat)))
13136 (org-back-to-heading t)
13137 (org-add-planning-info nil nil 'closed)
13138 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13139 org-deadline-time-regexp "\\)\\|\\("
13140 org-ts-regexp "\\)"))
13141 (while (re-search-forward
13142 re (save-excursion (outline-next-heading) (point)) t)
13143 (setq type (if (match-end 1) org-scheduled-string
13144 (if (match-end 3) org-deadline-string "Plain:"))
13145 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13146 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13147 (setq n (string-to-number (match-string 2 ts))
13148 what (match-string 3 ts))
13149 (if (equal what "w") (setq n (* n 7) what "d"))
13150 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13151 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13152 ;; Preparation, see if we need to modify the start date for the change
13153 (when (match-end 1)
13154 (setq time (save-match-data (org-time-string-to-time ts)))
13155 (cond
13156 ((equal (match-string 1 ts) ".")
13157 ;; Shift starting date to today
13158 (org-timestamp-change
13159 (- (org-today) (time-to-days time))
13160 'day))
13161 ((equal (match-string 1 ts) "+")
13162 (let ((nshiftmax 10) (nshift 0))
13163 (while (or (= nshift 0)
13164 (<= (time-to-days time)
13165 (time-to-days (current-time))))
13166 (when (= (incf nshift) nshiftmax)
13167 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13168 (user-error "Abort")))
13169 (org-timestamp-change n (cdr (assoc what whata)))
13170 (org-at-timestamp-p t)
13171 (setq ts (match-string 1))
13172 (setq time (save-match-data (org-time-string-to-time ts)))))
13173 (org-timestamp-change (- n) (cdr (assoc what whata)))
13174 ;; rematch, so that we have everything in place for the real shift
13175 (org-at-timestamp-p t)
13176 (setq ts (match-string 1))
13177 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13178 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13179 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13180 (setq org-log-post-message msg)
13181 (message "%s" msg))))
13183 (defun org-show-todo-tree (arg)
13184 "Make a compact tree which shows all headlines marked with TODO.
13185 The tree will show the lines where the regexp matches, and all higher
13186 headlines above the match.
13187 With a \\[universal-argument] prefix, prompt for a regexp to match.
13188 With a numeric prefix N, construct a sparse tree for the Nth element
13189 of `org-todo-keywords-1'."
13190 (interactive "P")
13191 (let ((case-fold-search nil)
13192 (kwd-re
13193 (cond ((null arg) org-not-done-regexp)
13194 ((equal arg '(4))
13195 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13196 (mapcar 'list org-todo-keywords-1))))
13197 (concat "\\("
13198 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13199 "\\)\\>")))
13200 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13201 (regexp-quote (nth (1- (prefix-numeric-value arg))
13202 org-todo-keywords-1)))
13203 (t (user-error "Invalid prefix argument: %s" arg)))))
13204 (message "%d TODO entries found"
13205 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13207 (defun org-deadline (arg &optional time)
13208 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13209 With one universal prefix argument, remove any deadline from the item.
13210 With two universal prefix arguments, prompt for a warning delay.
13211 With argument TIME, set the deadline at the corresponding date. TIME
13212 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13213 (interactive "P")
13214 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13215 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13216 'region-start-level 'region))
13217 org-loop-over-headlines-in-active-region)
13218 (org-map-entries
13219 `(org-deadline ',arg ,time)
13220 org-loop-over-headlines-in-active-region
13221 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13222 (let* ((old-date (org-entry-get nil "DEADLINE"))
13223 (old-date-time (if old-date (org-time-string-to-time old-date)))
13224 (repeater (and old-date
13225 (string-match
13226 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13227 old-date)
13228 (match-string 1 old-date))))
13229 (cond
13230 ((equal arg '(4))
13231 (when (and old-date org-log-redeadline)
13232 (org-add-log-setup 'deldeadline nil old-date 'findpos
13233 org-log-redeadline))
13234 (org-remove-timestamp-with-keyword org-deadline-string)
13235 (message "Item no longer has a deadline."))
13236 ((equal arg '(16))
13237 (save-excursion
13238 (org-back-to-heading t)
13239 (if (re-search-forward
13240 org-deadline-time-regexp
13241 (save-excursion (outline-next-heading) (point)) t)
13242 (let* ((rpl0 (match-string 1))
13243 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13244 (replace-match
13245 (concat org-deadline-string
13246 " <" rpl
13247 (format " -%dd"
13248 (abs
13249 (- (time-to-days
13250 (save-match-data
13251 (org-read-date nil t nil "Warn starting from" old-date-time)))
13252 (time-to-days old-date-time))))
13253 ">") t t))
13254 (user-error "No deadline information to update"))))
13256 (org-add-planning-info 'deadline time 'closed)
13257 (when (and old-date org-log-redeadline
13258 (not (equal old-date
13259 (substring org-last-inserted-timestamp 1 -1))))
13260 (org-add-log-setup 'redeadline nil old-date 'findpos
13261 org-log-redeadline))
13262 (when repeater
13263 (save-excursion
13264 (org-back-to-heading t)
13265 (when (re-search-forward (concat org-deadline-string " "
13266 org-last-inserted-timestamp)
13267 (save-excursion
13268 (outline-next-heading) (point)) t)
13269 (goto-char (1- (match-end 0)))
13270 (insert " " repeater)
13271 (setq org-last-inserted-timestamp
13272 (concat (substring org-last-inserted-timestamp 0 -1)
13273 " " repeater
13274 (substring org-last-inserted-timestamp -1))))))
13275 (message "Deadline on %s" org-last-inserted-timestamp))))))
13277 (defun org-schedule (arg &optional time)
13278 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13279 With one universal prefix argument, remove any scheduling date from the item.
13280 With two universal prefix arguments, prompt for a delay cookie.
13281 With argument TIME, scheduled at the corresponding date. TIME can
13282 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13283 (interactive "P")
13284 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13285 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13286 'region-start-level 'region))
13287 org-loop-over-headlines-in-active-region)
13288 (org-map-entries
13289 `(org-schedule ',arg ,time)
13290 org-loop-over-headlines-in-active-region
13291 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13292 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13293 (old-date-time (if old-date (org-time-string-to-time old-date)))
13294 (repeater (and old-date
13295 (string-match
13296 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13297 old-date)
13298 (match-string 1 old-date))))
13299 (cond
13300 ((equal arg '(4))
13301 (progn
13302 (when (and old-date org-log-reschedule)
13303 (org-add-log-setup 'delschedule nil old-date 'findpos
13304 org-log-reschedule))
13305 (org-remove-timestamp-with-keyword org-scheduled-string)
13306 (message "Item is no longer scheduled.")))
13307 ((equal arg '(16))
13308 (save-excursion
13309 (org-back-to-heading t)
13310 (if (re-search-forward
13311 org-scheduled-time-regexp
13312 (save-excursion (outline-next-heading) (point)) t)
13313 (let* ((rpl0 (match-string 1))
13314 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13315 (replace-match
13316 (concat org-scheduled-string
13317 " <" rpl
13318 (format " -%dd"
13319 (abs
13320 (- (time-to-days
13321 (save-match-data
13322 (org-read-date nil t nil "Delay until" old-date-time)))
13323 (time-to-days old-date-time))))
13324 ">") t t))
13325 (user-error "No scheduled information to update"))))
13327 (org-add-planning-info 'scheduled time 'closed)
13328 (when (and old-date org-log-reschedule
13329 (not (equal old-date
13330 (substring org-last-inserted-timestamp 1 -1))))
13331 (org-add-log-setup 'reschedule nil old-date 'findpos
13332 org-log-reschedule))
13333 (when repeater
13334 (save-excursion
13335 (org-back-to-heading t)
13336 (when (re-search-forward (concat org-scheduled-string " "
13337 org-last-inserted-timestamp)
13338 (save-excursion
13339 (outline-next-heading) (point)) t)
13340 (goto-char (1- (match-end 0)))
13341 (insert " " repeater)
13342 (setq org-last-inserted-timestamp
13343 (concat (substring org-last-inserted-timestamp 0 -1)
13344 " " repeater
13345 (substring org-last-inserted-timestamp -1))))))
13346 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13348 (defun org-get-scheduled-time (pom &optional inherit)
13349 "Get the scheduled time as a time tuple, of a format suitable
13350 for calling org-schedule with, or if there is no scheduling,
13351 returns nil."
13352 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13353 (when time
13354 (apply 'encode-time (org-parse-time-string time)))))
13356 (defun org-get-deadline-time (pom &optional inherit)
13357 "Get the deadline as a time tuple, of a format suitable for
13358 calling org-deadline with, or if there is no scheduling, returns
13359 nil."
13360 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13361 (when time
13362 (apply 'encode-time (org-parse-time-string time)))))
13364 (defun org-remove-timestamp-with-keyword (keyword)
13365 "Remove all time stamps with KEYWORD in the current entry."
13366 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13367 beg)
13368 (save-excursion
13369 (org-back-to-heading t)
13370 (setq beg (point))
13371 (outline-next-heading)
13372 (while (re-search-backward re beg t)
13373 (replace-match "")
13374 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13375 (equal (char-before) ?\ ))
13376 (backward-delete-char 1)
13377 (if (string-match "^[ \t]*$" (buffer-substring
13378 (point-at-bol) (point-at-eol)))
13379 (delete-region (point-at-bol)
13380 (min (point-max) (1+ (point-at-eol))))))))))
13382 (defvar org-time-was-given) ; dynamically scoped parameter
13383 (defvar org-end-time-was-given) ; dynamically scoped parameter
13385 (defun org-add-planning-info (what &optional time &rest remove)
13386 "Insert new timestamp with keyword in the line directly after the headline.
13387 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13388 If non is given, the user is prompted for a date.
13389 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13390 be removed."
13391 (interactive)
13392 (let (org-time-was-given org-end-time-was-given default-time default-input)
13393 (catch 'exit
13394 (when (and (memq what '(scheduled deadline))
13395 (or (not time)
13396 (and (stringp time)
13397 (string-match "^[-+]+[0-9]" time))))
13398 ;; Try to get a default date/time from existing timestamp
13399 (save-excursion
13400 (org-back-to-heading t)
13401 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13402 (when (re-search-forward (if (eq what 'scheduled)
13403 org-scheduled-time-regexp
13404 org-deadline-time-regexp)
13405 end t)
13406 (setq ts (match-string 1)
13407 default-time (apply 'encode-time (org-parse-time-string ts))
13408 default-input (and ts (org-get-compact-tod ts)))))))
13409 (when what
13410 (setq time
13411 (if (stringp time)
13412 ;; This is a string (relative or absolute), set proper date
13413 (apply 'encode-time
13414 (org-read-date-analyze
13415 time default-time (decode-time default-time)))
13416 ;; If necessary, get the time from the user
13417 (or time (org-read-date nil 'to-time nil nil
13418 default-time default-input)))))
13420 (when (and org-insert-labeled-timestamps-at-point
13421 (memq what '(scheduled deadline)))
13422 (insert
13423 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13424 (org-insert-time-stamp time org-time-was-given
13425 nil nil nil (list org-end-time-was-given))
13426 (setq what nil))
13427 (org-with-wide-buffer
13428 (let (col list elt ts buffer-invisibility-spec)
13429 (org-back-to-heading t)
13430 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13431 (goto-char (match-end 1))
13432 (setq col (current-column))
13433 (goto-char (match-end 0))
13434 (if (eobp) (insert "\n") (forward-char 1))
13435 (unless (or what (org-looking-at-p org-planning-line-re))
13436 ;; Nothing to add, nothing to remove...... :-)
13437 (throw 'exit nil))
13438 (if (and (not (looking-at org-outline-regexp))
13439 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13440 "[^\r\n]*"))
13441 (not (equal (match-string 1) org-clock-string)))
13442 (narrow-to-region (match-beginning 0) (match-end 0))
13443 (insert-before-markers "\n")
13444 (backward-char 1)
13445 (narrow-to-region (point) (point))
13446 (and org-adapt-indentation (org-indent-to-column col)))
13447 ;; Check if we have to remove something.
13448 (setq list (cons what remove))
13449 (while list
13450 (setq elt (pop list))
13451 (when (or (and (eq elt 'scheduled)
13452 (re-search-forward org-scheduled-time-regexp nil t))
13453 (and (eq elt 'deadline)
13454 (re-search-forward org-deadline-time-regexp nil t))
13455 (and (eq elt 'closed)
13456 (re-search-forward org-closed-time-regexp nil t)))
13457 (replace-match "")
13458 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13459 (and (looking-at "[ \t]+") (replace-match ""))
13460 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13461 (when what
13462 (insert
13463 (if (or (bolp) (eq (char-before) ?\s)) "" " ")
13464 (cond ((eq what 'scheduled) org-scheduled-string)
13465 ((eq what 'deadline) org-deadline-string)
13466 ((eq what 'closed) org-closed-string))
13467 " ")
13468 (setq ts (org-insert-time-stamp
13469 time
13470 (or org-time-was-given
13471 (and (eq what 'closed) org-log-done-with-time))
13472 (eq what 'closed)
13473 nil nil (list org-end-time-was-given)))
13474 (unless (or (bolp)
13475 (eq (char-before) ?\s)
13476 (memq (char-after) '(?\n ?\s))
13477 (eobp))
13478 (insert " "))
13479 (end-of-line 1))
13480 (goto-char (point-min))
13481 (widen)
13482 (when (and (looking-at "[ \t]*\n") (eq (char-before) ?\n))
13483 (delete-region (1- (point)) (line-end-position)))
13484 ts)))))
13486 (defvar org-log-note-marker (make-marker))
13487 (defvar org-log-note-purpose nil)
13488 (defvar org-log-note-state nil)
13489 (defvar org-log-note-previous-state nil)
13490 (defvar org-log-note-extra nil)
13491 (defvar org-log-note-window-configuration nil)
13492 (defvar org-log-note-return-to (make-marker))
13493 (defvar org-log-note-effective-time nil
13494 "Remembered current time so that dynamically scoped
13495 `org-extend-today-until' affects tha timestamps in state change
13496 log")
13498 (defvar org-log-post-message nil
13499 "Message to be displayed after a log note has been stored.
13500 The auto-repeater uses this.")
13502 (defun org-add-note ()
13503 "Add a note to the current entry.
13504 This is done in the same way as adding a state change note."
13505 (interactive)
13506 (org-add-log-setup 'note nil nil 'findpos nil))
13508 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13509 "Set up the post command hook to take a note.
13510 If this is about to TODO state change, the new state is expected in STATE.
13511 When FINDPOS is non-nil, find the correct position for the note in
13512 the current entry. If not, assume that it can be inserted at point.
13513 HOW is an indicator what kind of note should be created.
13514 EXTRA is additional text that will be inserted into the notes buffer."
13515 (let* ((org-log-into-drawer (org-log-into-drawer))
13516 (drawer (cond ((stringp org-log-into-drawer) org-log-into-drawer)
13517 (org-log-into-drawer "LOGBOOK"))))
13518 (org-with-wide-buffer
13519 (when findpos
13520 (org-back-to-heading t)
13521 ;; Skip planning info and property drawer.
13522 (forward-line)
13523 (when (org-looking-at-p org-planning-line-re) (forward-line))
13524 (when (looking-at org-property-drawer-re)
13525 (goto-char (match-end 0))
13526 (forward-line))
13527 (let ((end (if (org-at-heading-p) (point)
13528 (save-excursion (outline-next-heading) (point)))))
13529 (cond
13530 (drawer
13531 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13532 (case-fold-search t))
13533 (catch 'exit
13534 ;; Try to find existing drawer.
13535 (while (re-search-forward regexp end t)
13536 (let ((element (org-element-at-point)))
13537 (when (eq (org-element-type element) 'drawer)
13538 (when (and (not org-log-states-order-reversed)
13539 (org-element-property :contents-end element))
13540 (goto-char (org-element-property :contents-end element)))
13541 (throw 'exit nil))))
13542 ;; No drawer found. Create one.
13543 (unless (bolp) (insert "\n"))
13544 (let ((beg (point)))
13545 (insert ":" drawer ":\n:END:\n")
13546 (org-indent-region beg (point)))
13547 (end-of-line -1))))
13548 (org-log-state-notes-insert-after-drawers
13549 (while (and (looking-at org-drawer-regexp)
13550 (progn (goto-char (match-end 0))
13551 (re-search-forward org-property-end-re end t)))
13552 (forward-line)))))
13553 (unless org-log-states-order-reversed
13554 (and (= (char-after) ?\n) (forward-char 1))
13555 (org-skip-over-state-notes)
13556 (skip-chars-backward " \t\n\r")))
13557 (move-marker org-log-note-marker (point))
13558 (setq org-log-note-purpose purpose
13559 org-log-note-state state
13560 org-log-note-previous-state prev-state
13561 org-log-note-how how
13562 org-log-note-extra extra
13563 org-log-note-effective-time (org-current-effective-time))
13564 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13566 (defun org-skip-over-state-notes ()
13567 "Skip past the list of State notes in an entry."
13568 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13569 (when (ignore-errors (goto-char (org-in-item-p)))
13570 (let* ((struct (org-list-struct))
13571 (prevs (org-list-prevs-alist struct)))
13572 (while (looking-at "[ \t]*- State")
13573 (goto-char (or (org-list-get-next-item (point) struct prevs)
13574 (org-list-get-item-end (point) struct)))))))
13576 (defun org-add-log-note (&optional purpose)
13577 "Pop up a window for taking a note, and add this note later at point."
13578 (remove-hook 'post-command-hook 'org-add-log-note)
13579 (setq org-log-note-window-configuration (current-window-configuration))
13580 (delete-other-windows)
13581 (move-marker org-log-note-return-to (point))
13582 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13583 (goto-char org-log-note-marker)
13584 (org-switch-to-buffer-other-window "*Org Note*")
13585 (erase-buffer)
13586 (if (memq org-log-note-how '(time state))
13587 (let (current-prefix-arg) (org-store-log-note))
13588 (let ((org-inhibit-startup t)) (org-mode))
13589 (insert (format "# Insert note for %s.
13590 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13591 (cond
13592 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13593 ((eq org-log-note-purpose 'done) "closed todo item")
13594 ((eq org-log-note-purpose 'state)
13595 (format "state change from \"%s\" to \"%s\""
13596 (or org-log-note-previous-state "")
13597 (or org-log-note-state "")))
13598 ((eq org-log-note-purpose 'reschedule)
13599 "rescheduling")
13600 ((eq org-log-note-purpose 'delschedule)
13601 "no longer scheduled")
13602 ((eq org-log-note-purpose 'redeadline)
13603 "changing deadline")
13604 ((eq org-log-note-purpose 'deldeadline)
13605 "removing deadline")
13606 ((eq org-log-note-purpose 'refile)
13607 "refiling")
13608 ((eq org-log-note-purpose 'note)
13609 "this entry")
13610 (t (error "This should not happen")))))
13611 (if org-log-note-extra (insert org-log-note-extra))
13612 (org-set-local 'org-finish-function 'org-store-log-note)
13613 (run-hooks 'org-log-buffer-setup-hook)))
13615 (defvar org-note-abort nil) ; dynamically scoped
13616 (defun org-store-log-note ()
13617 "Finish taking a log note, and insert it to where it belongs."
13618 (let ((txt (buffer-string)))
13619 (kill-buffer (current-buffer))
13620 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13621 lines ind bul)
13622 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13623 (setq txt (replace-match "" t t txt)))
13624 (if (string-match "\\s-+\\'" txt)
13625 (setq txt (replace-match "" t t txt)))
13626 (setq lines (org-split-string txt "\n"))
13627 (when (and note (string-match "\\S-" note))
13628 (setq note
13629 (org-replace-escapes
13630 note
13631 (list (cons "%u" (user-login-name))
13632 (cons "%U" user-full-name)
13633 (cons "%t" (format-time-string
13634 (org-time-stamp-format 'long 'inactive)
13635 org-log-note-effective-time))
13636 (cons "%T" (format-time-string
13637 (org-time-stamp-format 'long nil)
13638 org-log-note-effective-time))
13639 (cons "%d" (format-time-string
13640 (org-time-stamp-format nil 'inactive)
13641 org-log-note-effective-time))
13642 (cons "%D" (format-time-string
13643 (org-time-stamp-format nil nil)
13644 org-log-note-effective-time))
13645 (cons "%s" (if org-log-note-state
13646 (concat "\"" org-log-note-state "\"")
13647 ""))
13648 (cons "%S" (if org-log-note-previous-state
13649 (concat "\"" org-log-note-previous-state "\"")
13650 "\"\"")))))
13651 (if lines (setq note (concat note " \\\\")))
13652 (push note lines))
13653 (when (or current-prefix-arg org-note-abort)
13654 (when org-log-into-drawer
13655 (org-remove-empty-drawer-at org-log-note-marker))
13656 (setq lines nil))
13657 (when lines
13658 (with-current-buffer (marker-buffer org-log-note-marker)
13659 (save-excursion
13660 (goto-char org-log-note-marker)
13661 (move-marker org-log-note-marker nil)
13662 (end-of-line 1)
13663 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13664 (setq ind (save-excursion
13665 (if (ignore-errors (goto-char (org-in-item-p)))
13666 (let ((struct (org-list-struct)))
13667 (org-list-get-ind
13668 (org-list-get-top-point struct) struct))
13669 (skip-chars-backward " \r\t\n")
13670 (cond
13671 ((and (org-at-heading-p)
13672 org-adapt-indentation)
13673 (1+ (org-current-level)))
13674 ((org-at-heading-p) 0)
13675 (t (org-get-indentation))))))
13676 (setq bul (org-list-bullet-string "-"))
13677 (org-indent-line-to ind)
13678 (insert bul (pop lines))
13679 (let ((ind-body (+ (length bul) ind)))
13680 (while lines
13681 (insert "\n")
13682 (org-indent-line-to ind-body)
13683 (insert (pop lines))))
13684 (message "Note stored")
13685 (org-back-to-heading t)
13686 (org-cycle-hide-drawers 'children))
13687 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13688 ;; from within `org-add-log-note' because `buffer-undo-list'
13689 ;; is then modified outside of `org-with-remote-undo'.
13690 (when (eq this-command 'org-agenda-todo)
13691 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13692 ;; Don't add undo information when called from `org-agenda-todo'
13693 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13694 (set-window-configuration org-log-note-window-configuration)
13695 (with-current-buffer (marker-buffer org-log-note-return-to)
13696 (goto-char org-log-note-return-to))
13697 (move-marker org-log-note-return-to nil)
13698 (and org-log-post-message (message "%s" org-log-post-message))))
13700 (defun org-remove-empty-drawer-at (pos)
13701 "Remove an empty drawer at position POS.
13702 POS may also be a marker."
13703 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13704 (org-with-wide-buffer
13705 (goto-char pos)
13706 (let ((drawer (org-element-at-point)))
13707 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13708 (not (org-element-property :contents-begin drawer)))
13709 (delete-region (org-element-property :begin drawer)
13710 (progn (goto-char (org-element-property :end drawer))
13711 (skip-chars-backward " \r\t\n")
13712 (forward-line)
13713 (point))))))))
13715 (defvar org-ts-type nil)
13716 (defun org-sparse-tree (&optional arg type)
13717 "Create a sparse tree, prompt for the details.
13718 This command can create sparse trees. You first need to select the type
13719 of match used to create the tree:
13721 t Show all TODO entries.
13722 T Show entries with a specific TODO keyword.
13723 m Show entries selected by a tags/property match.
13724 p Enter a property name and its value (both with completion on existing
13725 names/values) and show entries with that property.
13726 r Show entries matching a regular expression (`/' can be used as well).
13727 b Show deadlines and scheduled items before a date.
13728 a Show deadlines and scheduled items after a date.
13729 d Show deadlines due within `org-deadline-warning-days'.
13730 D Show deadlines and scheduled items between a date range."
13731 (interactive "P")
13732 (setq type (or type org-sparse-tree-default-date-type))
13733 (setq org-ts-type type)
13734 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13735 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13736 [c]ycle through date types: %s"
13737 (case type
13738 (all "all timestamps")
13739 (scheduled "only scheduled")
13740 (deadline "only deadline")
13741 (active "only active timestamps")
13742 (inactive "only inactive timestamps")
13743 (scheduled-or-deadline "scheduled/deadline")
13744 (closed "with a closed time-stamp")
13745 (otherwise "scheduled/deadline")))
13746 (let ((answer (read-char-exclusive)))
13747 (case answer
13749 (org-sparse-tree
13751 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13752 inactive closed)))))
13753 (?d (call-interactively 'org-check-deadlines))
13754 (?b (call-interactively 'org-check-before-date))
13755 (?a (call-interactively 'org-check-after-date))
13756 (?D (call-interactively 'org-check-dates-range))
13757 (?t (call-interactively 'org-show-todo-tree))
13758 (?T (org-show-todo-tree '(4)))
13759 (?m (call-interactively 'org-match-sparse-tree))
13760 ((?p ?P)
13761 (let* ((kwd (org-icompleting-read
13762 "Property: " (mapcar 'list (org-buffer-property-keys))))
13763 (value (org-icompleting-read
13764 "Value: " (mapcar 'list (org-property-values kwd)))))
13765 (unless (string-match "\\`{.*}\\'" value)
13766 (setq value (concat "\"" value "\"")))
13767 (org-match-sparse-tree arg (concat kwd "=" value))))
13768 ((?r ?R ?/) (call-interactively 'org-occur))
13769 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13771 (defvar org-occur-highlights nil
13772 "List of overlays used for occur matches.")
13773 (make-variable-buffer-local 'org-occur-highlights)
13774 (defvar org-occur-parameters nil
13775 "Parameters of the active org-occur calls.
13776 This is a list, each call to org-occur pushes as cons cell,
13777 containing the regular expression and the callback, onto the list.
13778 The list can contain several entries if `org-occur' has been called
13779 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13780 will only contain one set of parameters. When the highlights are
13781 removed (for example with `C-c C-c', or with the next edit (depending
13782 on `org-remove-highlights-with-change'), this variable is emptied
13783 as well.")
13784 (make-variable-buffer-local 'org-occur-parameters)
13786 (defun org-occur (regexp &optional keep-previous callback)
13787 "Make a compact tree which shows all matches of REGEXP.
13788 The tree will show the lines where the regexp matches, and all higher
13789 headlines above the match. It will also show the heading after the match,
13790 to make sure editing the matching entry is easy.
13791 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13792 call to `org-occur' will be kept, to allow stacking of calls to this
13793 command.
13794 If CALLBACK is non-nil, it is a function which is called to confirm
13795 that the match should indeed be shown."
13796 (interactive "sRegexp: \nP")
13797 (when (equal regexp "")
13798 (user-error "Regexp cannot be empty"))
13799 (unless keep-previous
13800 (org-remove-occur-highlights nil nil t))
13801 (push (cons regexp callback) org-occur-parameters)
13802 (let ((cnt 0))
13803 (save-excursion
13804 (goto-char (point-min))
13805 (if (or (not keep-previous) ; do not want to keep
13806 (not org-occur-highlights)) ; no previous matches
13807 ;; hide everything
13808 (org-overview))
13809 (while (re-search-forward regexp nil t)
13810 (when (or (not callback)
13811 (save-match-data (funcall callback)))
13812 (setq cnt (1+ cnt))
13813 (when org-highlight-sparse-tree-matches
13814 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13815 (org-show-context 'occur-tree))))
13816 (when org-remove-highlights-with-change
13817 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13818 nil 'local))
13819 (unless org-sparse-tree-open-archived-trees
13820 (org-hide-archived-subtrees (point-min) (point-max)))
13821 (run-hooks 'org-occur-hook)
13822 (if (org-called-interactively-p 'interactive)
13823 (message "%d match(es) for regexp %s" cnt regexp))
13824 cnt))
13826 (defun org-occur-next-match (&optional n reset)
13827 "Function for `next-error-function' to find sparse tree matches.
13828 N is the number of matches to move, when negative move backwards.
13829 RESET is entirely ignored - this function always goes back to the
13830 starting point when no match is found."
13831 (let* ((limit (if (< n 0) (point-min) (point-max)))
13832 (search-func (if (< n 0)
13833 'previous-single-char-property-change
13834 'next-single-char-property-change))
13835 (n (abs n))
13836 (pos (point))
13838 (catch 'exit
13839 (while (setq p1 (funcall search-func (point) 'org-type))
13840 (when (equal p1 limit)
13841 (goto-char pos)
13842 (user-error "No more matches"))
13843 (when (equal (get-char-property p1 'org-type) 'org-occur)
13844 (setq n (1- n))
13845 (when (= n 0)
13846 (goto-char p1)
13847 (throw 'exit (point))))
13848 (goto-char p1))
13849 (goto-char p1)
13850 (user-error "No more matches"))))
13852 (defun org-show-context (&optional key)
13853 "Make sure point and context are visible.
13854 How much context is shown depends upon the variables
13855 `org-show-hierarchy-above', `org-show-following-heading',
13856 `org-show-entry-below' and `org-show-siblings'."
13857 (let ((heading-p (org-at-heading-p t))
13858 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13859 (following-p (org-get-alist-option org-show-following-heading key))
13860 (entry-p (org-get-alist-option org-show-entry-below key))
13861 (siblings-p (org-get-alist-option org-show-siblings key)))
13862 ;; Show heading or entry text
13863 (if (and heading-p (not entry-p))
13864 (org-flag-heading nil) ; only show the heading
13865 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13866 (org-show-hidden-entry))) ; show entire entry
13867 (when following-p
13868 ;; Show next sibling, or heading below text
13869 (save-excursion
13870 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13871 (org-flag-heading nil))))
13872 (when siblings-p (org-show-siblings))
13873 (when hierarchy-p
13874 ;; show all higher headings, possibly with siblings
13875 (save-excursion
13876 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13877 (not (bobp)))
13878 (org-flag-heading nil)
13879 (when siblings-p (org-show-siblings)))))))
13881 (defvar org-reveal-start-hook nil
13882 "Hook run before revealing a location.")
13884 (defun org-reveal (&optional siblings)
13885 "Show current entry, hierarchy above it, and the following headline.
13886 This can be used to show a consistent set of context around locations
13887 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13888 not t for the search context.
13890 With optional argument SIBLINGS, on each level of the hierarchy all
13891 siblings are shown. This repairs the tree structure to what it would
13892 look like when opened with hierarchical calls to `org-cycle'.
13893 With double optional argument \\[universal-argument] \\[universal-argument], \
13894 go to the parent and show the
13895 entire tree."
13896 (interactive "P")
13897 (run-hooks 'org-reveal-start-hook)
13898 (let ((org-show-hierarchy-above t)
13899 (org-show-following-heading t)
13900 (org-show-siblings (if siblings t org-show-siblings)))
13901 (org-show-context nil))
13902 (when (equal siblings '(16))
13903 (save-excursion
13904 (when (org-up-heading-safe)
13905 (org-show-subtree)
13906 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13908 (defun org-highlight-new-match (beg end)
13909 "Highlight from BEG to END and mark the highlight is an occur headline."
13910 (let ((ov (make-overlay beg end)))
13911 (overlay-put ov 'face 'secondary-selection)
13912 (overlay-put ov 'org-type 'org-occur)
13913 (push ov org-occur-highlights)))
13915 (defun org-remove-occur-highlights (&optional beg end noremove)
13916 "Remove the occur highlights from the buffer.
13917 BEG and END are ignored. If NOREMOVE is nil, remove this function
13918 from the `before-change-functions' in the current buffer."
13919 (interactive)
13920 (unless org-inhibit-highlight-removal
13921 (mapc 'delete-overlay org-occur-highlights)
13922 (setq org-occur-highlights nil)
13923 (setq org-occur-parameters nil)
13924 (unless noremove
13925 (remove-hook 'before-change-functions
13926 'org-remove-occur-highlights 'local))))
13928 ;;;; Priorities
13930 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13931 "Regular expression matching the priority indicator.")
13933 (defvar org-remove-priority-next-time nil)
13935 (defun org-priority-up ()
13936 "Increase the priority of the current item."
13937 (interactive)
13938 (org-priority 'up))
13940 (defun org-priority-down ()
13941 "Decrease the priority of the current item."
13942 (interactive)
13943 (org-priority 'down))
13945 (defun org-priority (&optional action show)
13946 "Change the priority of an item.
13947 ACTION can be `set', `up', `down', or a character."
13948 (interactive "P")
13949 (if (equal action '(4))
13950 (org-show-priority)
13951 (unless org-enable-priority-commands
13952 (user-error "Priority commands are disabled"))
13953 (setq action (or action 'set))
13954 (let (current new news have remove)
13955 (save-excursion
13956 (org-back-to-heading t)
13957 (if (looking-at org-priority-regexp)
13958 (setq current (string-to-char (match-string 2))
13959 have t))
13960 (cond
13961 ((eq action 'remove)
13962 (setq remove t new ?\ ))
13963 ((or (eq action 'set)
13964 (if (featurep 'xemacs) (characterp action) (integerp action)))
13965 (if (not (eq action 'set))
13966 (setq new action)
13967 (message "Priority %c-%c, SPC to remove: "
13968 org-highest-priority org-lowest-priority)
13969 (save-match-data
13970 (setq new (read-char-exclusive))))
13971 (if (and (= (upcase org-highest-priority) org-highest-priority)
13972 (= (upcase org-lowest-priority) org-lowest-priority))
13973 (setq new (upcase new)))
13974 (cond ((equal new ?\ ) (setq remove t))
13975 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13976 (user-error "Priority must be between `%c' and `%c'"
13977 org-highest-priority org-lowest-priority))))
13978 ((eq action 'up)
13979 (setq new (if have
13980 (1- current) ; normal cycling
13981 ;; last priority was empty
13982 (if (eq last-command this-command)
13983 org-lowest-priority ; wrap around empty to lowest
13984 ;; default
13985 (if org-priority-start-cycle-with-default
13986 org-default-priority
13987 (1- org-default-priority))))))
13988 ((eq action 'down)
13989 (setq new (if have
13990 (1+ current) ; normal cycling
13991 ;; last priority was empty
13992 (if (eq last-command this-command)
13993 org-highest-priority ; wrap around empty to highest
13994 ;; default
13995 (if org-priority-start-cycle-with-default
13996 org-default-priority
13997 (1+ org-default-priority))))))
13998 (t (user-error "Invalid action")))
13999 (if (or (< (upcase new) org-highest-priority)
14000 (> (upcase new) org-lowest-priority))
14001 (if (and (memq action '(up down))
14002 (not have) (not (eq last-command this-command)))
14003 ;; `new' is from default priority
14004 (error
14005 "The default can not be set, see `org-default-priority' why")
14006 ;; normal cycling: `new' is beyond highest/lowest priority
14007 ;; and is wrapped around to the empty priority
14008 (setq remove t)))
14009 (setq news (format "%c" new))
14010 (if have
14011 (if remove
14012 (replace-match "" t t nil 1)
14013 (replace-match news t t nil 2))
14014 (if remove
14015 (user-error "No priority cookie found in line")
14016 (let ((case-fold-search nil))
14017 (looking-at org-todo-line-regexp))
14018 (if (match-end 2)
14019 (progn
14020 (goto-char (match-end 2))
14021 (insert " [#" news "]"))
14022 (goto-char (match-beginning 3))
14023 (insert "[#" news "] "))))
14024 (org-set-tags nil 'align))
14025 (if remove
14026 (message "Priority removed")
14027 (message "Priority of current item set to %s" news)))))
14029 (defun org-show-priority ()
14030 "Show the priority of the current item.
14031 This priority is composed of the main priority given with the [#A] cookies,
14032 and by additional input from the age of a schedules or deadline entry."
14033 (interactive)
14034 (let ((pri (if (eq major-mode 'org-agenda-mode)
14035 (org-get-at-bol 'priority)
14036 (save-excursion
14037 (save-match-data
14038 (beginning-of-line)
14039 (and (looking-at org-heading-regexp)
14040 (org-get-priority (match-string 0))))))))
14041 (message "Priority is %d" (if pri pri -1000))))
14043 (defun org-get-priority (s)
14044 "Find priority cookie and return priority."
14045 (save-match-data
14046 (if (functionp org-get-priority-function)
14047 (funcall org-get-priority-function)
14048 (if (not (string-match org-priority-regexp s))
14049 (* 1000 (- org-lowest-priority org-default-priority))
14050 (* 1000 (- org-lowest-priority
14051 (string-to-char (match-string 2 s))))))))
14053 ;;;; Tags
14055 (defvar org-agenda-archives-mode)
14056 (defvar org-map-continue-from nil
14057 "Position from where mapping should continue.
14058 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14060 (defvar org-scanner-tags nil
14061 "The current tag list while the tags scanner is running.")
14062 (defvar org-trust-scanner-tags nil
14063 "Should `org-get-tags-at' use the tags for the scanner.
14064 This is for internal dynamical scoping only.
14065 When this is non-nil, the function `org-get-tags-at' will return the value
14066 of `org-scanner-tags' instead of building the list by itself. This
14067 can lead to large speed-ups when the tags scanner is used in a file with
14068 many entries, and when the list of tags is retrieved, for example to
14069 obtain a list of properties. Building the tags list for each entry in such
14070 a file becomes an N^2 operation - but with this variable set, it scales
14071 as N.")
14073 (defun org-scan-tags (action matcher todo-only &optional start-level)
14074 "Scan headline tags with inheritance and produce output ACTION.
14076 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14077 or `agenda' to produce an entry list for an agenda view. It can also be
14078 a Lisp form or a function that should be called at each matched headline, in
14079 this case the return value is a list of all return values from these calls.
14081 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14082 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14083 only lines with a not-done TODO keyword are included in the output.
14084 This should be the same variable that was scoped into
14085 and set by `org-make-tags-matcher' when it constructed MATCHER.
14087 START-LEVEL can be a string with asterisks, reducing the scope to
14088 headlines matching this string."
14089 (require 'org-agenda)
14090 (let* ((re (concat "^"
14091 (if start-level
14092 ;; Get the correct level to match
14093 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14094 org-outline-regexp)
14095 " *\\(\\<\\("
14096 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14097 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14098 (props (list 'face 'default
14099 'done-face 'org-agenda-done
14100 'undone-face 'default
14101 'mouse-face 'highlight
14102 'org-not-done-regexp org-not-done-regexp
14103 'org-todo-regexp org-todo-regexp
14104 'org-complex-heading-regexp org-complex-heading-regexp
14105 'help-echo
14106 (format "mouse-2 or RET jump to org file %s"
14107 (abbreviate-file-name
14108 (or (buffer-file-name (buffer-base-buffer))
14109 (buffer-name (buffer-base-buffer)))))))
14110 (org-map-continue-from nil)
14111 lspos tags tags-list
14112 (tags-alist (list (cons 0 org-file-tags)))
14113 (llast 0) rtn rtn1 level category i txt
14114 todo marker entry priority)
14115 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14116 (setq action (list 'lambda nil action)))
14117 (save-excursion
14118 (goto-char (point-min))
14119 (when (eq action 'sparse-tree)
14120 (org-overview)
14121 (org-remove-occur-highlights))
14122 (while (let (case-fold-search)
14123 (re-search-forward re nil t))
14124 (setq org-map-continue-from nil)
14125 (catch :skip
14126 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14127 tags (if (match-end 4) (org-match-string-no-properties 4)))
14128 (goto-char (setq lspos (match-beginning 0)))
14129 (setq level (org-reduced-level (org-outline-level))
14130 category (org-get-category))
14131 (setq i llast llast level)
14132 ;; remove tag lists from same and sublevels
14133 (while (>= i level)
14134 (when (setq entry (assoc i tags-alist))
14135 (setq tags-alist (delete entry tags-alist)))
14136 (setq i (1- i)))
14137 ;; add the next tags
14138 (when tags
14139 (setq tags (org-split-string tags ":")
14140 tags-alist
14141 (cons (cons level tags) tags-alist)))
14142 ;; compile tags for current headline
14143 (setq tags-list
14144 (if org-use-tag-inheritance
14145 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14146 tags)
14147 org-scanner-tags tags-list)
14148 (when org-use-tag-inheritance
14149 (setcdr (car tags-alist)
14150 (mapcar (lambda (x)
14151 (setq x (copy-sequence x))
14152 (org-add-prop-inherited x))
14153 (cdar tags-alist))))
14154 (when (and tags org-use-tag-inheritance
14155 (or (not (eq t org-use-tag-inheritance))
14156 org-tags-exclude-from-inheritance))
14157 ;; selective inheritance, remove uninherited ones
14158 (setcdr (car tags-alist)
14159 (org-remove-uninherited-tags (cdar tags-alist))))
14160 (when (and
14162 ;; eval matcher only when the todo condition is OK
14163 (and (or (not todo-only) (member todo org-not-done-keywords))
14164 (let ((case-fold-search t) (org-trust-scanner-tags t))
14165 (eval matcher)))
14167 ;; Call the skipper, but return t if it does not skip,
14168 ;; so that the `and' form continues evaluating
14169 (progn
14170 (unless (eq action 'sparse-tree) (org-agenda-skip))
14173 ;; Check if timestamps are deselecting this entry
14174 (or (not todo-only)
14175 (and (member todo org-not-done-keywords)
14176 (or (not org-agenda-tags-todo-honor-ignore-options)
14177 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14179 ;; select this headline
14180 (cond
14181 ((eq action 'sparse-tree)
14182 (and org-highlight-sparse-tree-matches
14183 (org-get-heading) (match-end 0)
14184 (org-highlight-new-match
14185 (match-beginning 1) (match-end 1)))
14186 (org-show-context 'tags-tree))
14187 ((eq action 'agenda)
14188 (setq txt (org-agenda-format-item
14190 (concat
14191 (if (eq org-tags-match-list-sublevels 'indented)
14192 (make-string (1- level) ?.) "")
14193 (org-get-heading))
14194 level category
14195 tags-list)
14196 priority (org-get-priority txt))
14197 (goto-char lspos)
14198 (setq marker (org-agenda-new-marker))
14199 (org-add-props txt props
14200 'org-marker marker 'org-hd-marker marker 'org-category category
14201 'todo-state todo
14202 'priority priority 'type "tagsmatch")
14203 (push txt rtn))
14204 ((functionp action)
14205 (setq org-map-continue-from nil)
14206 (save-excursion
14207 (setq rtn1 (funcall action))
14208 (push rtn1 rtn)))
14209 (t (user-error "Invalid action")))
14211 ;; if we are to skip sublevels, jump to end of subtree
14212 (unless org-tags-match-list-sublevels
14213 (org-end-of-subtree t)
14214 (backward-char 1))))
14215 ;; Get the correct position from where to continue
14216 (if org-map-continue-from
14217 (goto-char org-map-continue-from)
14218 (and (= (point) lspos) (end-of-line 1)))))
14219 (when (and (eq action 'sparse-tree)
14220 (not org-sparse-tree-open-archived-trees))
14221 (org-hide-archived-subtrees (point-min) (point-max)))
14222 (nreverse rtn)))
14224 (defun org-remove-uninherited-tags (tags)
14225 "Remove all tags that are not inherited from the list TAGS."
14226 (cond
14227 ((eq org-use-tag-inheritance t)
14228 (if org-tags-exclude-from-inheritance
14229 (org-delete-all org-tags-exclude-from-inheritance tags)
14230 tags))
14231 ((not org-use-tag-inheritance) nil)
14232 ((stringp org-use-tag-inheritance)
14233 (delq nil (mapcar
14234 (lambda (x)
14235 (if (and (string-match org-use-tag-inheritance x)
14236 (not (member x org-tags-exclude-from-inheritance)))
14237 x nil))
14238 tags)))
14239 ((listp org-use-tag-inheritance)
14240 (delq nil (mapcar
14241 (lambda (x)
14242 (if (member x org-use-tag-inheritance) x nil))
14243 tags)))))
14245 (defun org-match-sparse-tree (&optional todo-only match)
14246 "Create a sparse tree according to tags string MATCH.
14247 MATCH can contain positive and negative selection of tags, like
14248 \"+WORK+URGENT-WITHBOSS\".
14249 If optional argument TODO-ONLY is non-nil, only select lines that are
14250 also TODO lines."
14251 (interactive "P")
14252 (org-agenda-prepare-buffers (list (current-buffer)))
14253 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14255 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14257 (defvar org-cached-props nil)
14258 (defun org-cached-entry-get (pom property)
14259 (if (or (eq t org-use-property-inheritance)
14260 (and (stringp org-use-property-inheritance)
14261 (string-match org-use-property-inheritance property))
14262 (and (listp org-use-property-inheritance)
14263 (member property org-use-property-inheritance)))
14264 ;; Caching is not possible, check it directly
14265 (org-entry-get pom property 'inherit)
14266 ;; Get all properties, so that we can do complicated checks easily
14267 (cdr (assoc property (or org-cached-props
14268 (setq org-cached-props
14269 (org-entry-properties pom)))))))
14271 (defun org-global-tags-completion-table (&optional files)
14272 "Return the list of all tags in all agenda buffer/files.
14273 Optional FILES argument is a list of files which can be used
14274 instead of the agenda files."
14275 (save-excursion
14276 (org-uniquify
14277 (delq nil
14278 (apply 'append
14279 (mapcar
14280 (lambda (file)
14281 (set-buffer (find-file-noselect file))
14282 (append (org-get-buffer-tags)
14283 (mapcar (lambda (x) (if (stringp (car-safe x))
14284 (list (car-safe x)) nil))
14285 org-tag-alist)))
14286 (if (and files (car files))
14287 files
14288 (org-agenda-files))))))))
14290 (defun org-make-tags-matcher (match)
14291 "Create the TAGS/TODO matcher form for the selection string MATCH.
14293 The variable `todo-only' is scoped dynamically into this function.
14294 It will be set to t if the matcher restricts matching to TODO entries,
14295 otherwise will not be touched.
14297 Returns a cons of the selection string MATCH and the constructed
14298 lisp form implementing the matcher. The matcher is to be evaluated
14299 at an Org entry, with point on the headline, and returns t if the
14300 entry matches the selection string MATCH. The returned lisp form
14301 references two variables with information about the entry, which
14302 must be bound around the form's evaluation: todo, the TODO keyword
14303 at the entry (or nil of none); and tags-list, the list of all tags
14304 at the entry including inherited ones. Additionally, the category
14305 of the entry (if any) must be specified as the text property
14306 'org-category on the headline.
14308 See also `org-scan-tags'.
14310 (declare (special todo-only))
14311 (unless (boundp 'todo-only)
14312 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14313 (unless match
14314 ;; Get a new match request, with completion against the global
14315 ;; tags table and the local tags in current buffer
14316 (let ((org-last-tags-completion-table
14317 (org-uniquify
14318 (delq nil (append (org-get-buffer-tags)
14319 (org-global-tags-completion-table))))))
14320 (setq match (org-completing-read-no-i
14321 "Match: " 'org-tags-completion-function nil nil nil
14322 'org-tags-history))))
14324 ;; Parse the string and create a lisp form
14325 (let ((match0 match)
14326 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14327 minus tag mm
14328 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14329 orterms term orlist re-p str-p level-p level-op time-p
14330 prop-p pn pv po gv rest (start 0) (ss 0))
14331 ;; Expand group tags
14332 (setq match (org-tags-expand match))
14334 ;; Check if there is a TODO part of this match, which would be the
14335 ;; part after a "/". TO make sure that this slash is not part of
14336 ;; a property value to be matched against, we also check that there
14337 ;; is no " after that slash.
14338 ;; First, find the last slash
14339 (while (string-match "/+" match ss)
14340 (setq start (match-beginning 0) ss (match-end 0)))
14341 (if (and (string-match "/+" match start)
14342 (not (save-match-data (string-match "\"" match start))))
14343 ;; match contains also a todo-matching request
14344 (progn
14345 (setq tagsmatch (substring match 0 (match-beginning 0))
14346 todomatch (substring match (match-end 0)))
14347 (if (string-match "^!" todomatch)
14348 (setq todo-only t todomatch (substring todomatch 1)))
14349 (if (string-match "^\\s-*$" todomatch)
14350 (setq todomatch nil)))
14351 ;; only matching tags
14352 (setq tagsmatch match todomatch nil))
14354 ;; Make the tags matcher
14355 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14356 (setq tagsmatcher t)
14357 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14358 (while (setq term (pop orterms))
14359 (while (and (equal (substring term -1) "\\") orterms)
14360 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14361 (while (string-match re term)
14362 (setq rest (substring term (match-end 0))
14363 minus (and (match-end 1)
14364 (equal (match-string 1 term) "-"))
14365 tag (save-match-data (replace-regexp-in-string
14366 "\\\\-" "-"
14367 (match-string 2 term)))
14368 re-p (equal (string-to-char tag) ?{)
14369 level-p (match-end 4)
14370 prop-p (match-end 5)
14371 mm (cond
14372 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14373 (level-p
14374 (setq level-op (org-op-to-function (match-string 3 term)))
14375 `(,level-op level ,(string-to-number
14376 (match-string 4 term))))
14377 (prop-p
14378 (setq pn (match-string 5 term)
14379 po (match-string 6 term)
14380 pv (match-string 7 term)
14381 re-p (equal (string-to-char pv) ?{)
14382 str-p (equal (string-to-char pv) ?\")
14383 time-p (save-match-data
14384 (string-match "^\"[[<].*[]>]\"$" pv))
14385 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14386 (if time-p (setq pv (org-matcher-time pv)))
14387 (setq po (org-op-to-function po (if time-p 'time str-p)))
14388 (cond
14389 ((equal pn "CATEGORY")
14390 (setq gv '(get-text-property (point) 'org-category)))
14391 ((equal pn "TODO")
14392 (setq gv 'todo))
14394 (setq gv `(org-cached-entry-get nil ,pn))))
14395 (if re-p
14396 (if (eq po 'org<>)
14397 `(not (string-match ,pv (or ,gv "")))
14398 `(string-match ,pv (or ,gv "")))
14399 (if str-p
14400 `(,po (or ,gv "") ,pv)
14401 `(,po (string-to-number (or ,gv ""))
14402 ,(string-to-number pv) ))))
14403 (t `(member ,tag tags-list)))
14404 mm (if minus (list 'not mm) mm)
14405 term rest)
14406 (push mm tagsmatcher))
14407 (push (if (> (length tagsmatcher) 1)
14408 (cons 'and tagsmatcher)
14409 (car tagsmatcher))
14410 orlist)
14411 (setq tagsmatcher nil))
14412 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14413 (setq tagsmatcher
14414 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14415 ;; Make the todo matcher
14416 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14417 (setq todomatcher t)
14418 (setq orterms (org-split-string todomatch "|") orlist nil)
14419 (while (setq term (pop orterms))
14420 (while (string-match re term)
14421 (setq minus (and (match-end 1)
14422 (equal (match-string 1 term) "-"))
14423 kwd (match-string 2 term)
14424 re-p (equal (string-to-char kwd) ?{)
14425 term (substring term (match-end 0))
14426 mm (if re-p
14427 `(string-match ,(substring kwd 1 -1) todo)
14428 (list 'equal 'todo kwd))
14429 mm (if minus (list 'not mm) mm))
14430 (push mm todomatcher))
14431 (push (if (> (length todomatcher) 1)
14432 (cons 'and todomatcher)
14433 (car todomatcher))
14434 orlist)
14435 (setq todomatcher nil))
14436 (setq todomatcher (if (> (length orlist) 1)
14437 (cons 'or orlist) (car orlist))))
14439 ;; Return the string and lisp forms of the matcher
14440 (setq matcher (if todomatcher
14441 (list 'and tagsmatcher todomatcher)
14442 tagsmatcher))
14443 (when todo-only
14444 (setq matcher (list 'and '(member todo org-not-done-keywords)
14445 matcher)))
14446 (cons match0 matcher)))
14448 (defun org-tags-expand (match &optional single-as-list downcased)
14449 "Expand group tags in MATCH.
14451 This replaces every group tag in MATCH with a regexp tag search.
14452 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14453 will be replaced like this:
14455 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14456 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14457 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14459 Replacing by a regexp preserves the structure of the match.
14460 E.g., this expansion
14462 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14464 will match anything tagged with \"Lab\" and \"Home\", or tagged
14465 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14467 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14468 assumed to be a single group tag, and the function will return
14469 the list of tags in this group.
14471 When DOWNCASE is non-nil, expand downcased TAGS."
14472 (if org-group-tags
14473 (let* ((case-fold-search t)
14474 (stable org-mode-syntax-table)
14475 (tal (or org-tag-groups-alist-for-agenda
14476 org-tag-groups-alist))
14477 (tal (if downcased
14478 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14479 (tml (mapcar 'car tal))
14480 (rtnmatch match) rpl)
14481 ;; @ and _ are allowed as word-components in tags
14482 (modify-syntax-entry ?@ "w" stable)
14483 (modify-syntax-entry ?_ "w" stable)
14484 (while (and tml
14485 (with-syntax-table stable
14486 (string-match
14487 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14488 (regexp-opt tml) "\\>\\)") rtnmatch)))
14489 (let* ((dir (match-string 1 rtnmatch))
14490 (tag (match-string 2 rtnmatch))
14491 (tag (if downcased (downcase tag) tag)))
14492 (setq tml (delete tag tml))
14493 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14494 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14495 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14496 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14497 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14498 (if single-as-list
14499 (or (reverse rpl) (list rtnmatch))
14500 rtnmatch))
14501 (if single-as-list (list (if downcased (downcase match) match))
14502 match)))
14504 (defun org-op-to-function (op &optional stringp)
14505 "Turn an operator into the appropriate function."
14506 (setq op
14507 (cond
14508 ((equal op "<" ) '(< string< org-time<))
14509 ((equal op ">" ) '(> org-string> org-time>))
14510 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14511 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14512 ((member op '("=" "==")) '(= string= org-time=))
14513 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14514 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14516 (defun org<> (a b) (not (= a b)))
14517 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14518 (defun org-string>= (a b) (not (string< a b)))
14519 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14520 (defun org-string<> (a b) (not (string= a b)))
14521 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14522 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14523 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14524 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14525 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14526 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14527 (defun org-2ft (s)
14528 "Convert S to a floating point time.
14529 If S is already a number, just return it. If it is a string, parse
14530 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14531 (cond
14532 ((numberp s) s)
14533 ((stringp s)
14534 (condition-case nil
14535 (float-time (apply 'encode-time (org-parse-time-string s)))
14536 (error 0.)))
14537 (t 0.)))
14539 (defun org-time-today ()
14540 "Time in seconds today at 0:00.
14541 Returns the float number of seconds since the beginning of the
14542 epoch to the beginning of today (00:00)."
14543 (float-time (apply 'encode-time
14544 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14546 (defun org-matcher-time (s)
14547 "Interpret a time comparison value."
14548 (save-match-data
14549 (cond
14550 ((string= s "<now>") (float-time))
14551 ((string= s "<today>") (org-time-today))
14552 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14553 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14554 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14555 (+ (org-time-today)
14556 (* (string-to-number (match-string 1 s))
14557 (cdr (assoc (match-string 2 s)
14558 '(("d" . 86400.0) ("w" . 604800.0)
14559 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14560 (t (org-2ft s)))))
14562 (defun org-match-any-p (re list)
14563 "Does re match any element of list?"
14564 (setq list (mapcar (lambda (x) (string-match re x)) list))
14565 (delq nil list))
14567 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14568 (defvar org-tags-overlay (make-overlay 1 1))
14569 (org-detach-overlay org-tags-overlay)
14571 (defun org-get-local-tags-at (&optional pos)
14572 "Get a list of tags defined in the current headline."
14573 (org-get-tags-at pos 'local))
14575 (defun org-get-local-tags ()
14576 "Get a list of tags defined in the current headline."
14577 (org-get-tags-at nil 'local))
14579 (defun org-get-tags-at (&optional pos local)
14580 "Get a list of all headline tags applicable at POS.
14581 POS defaults to point. If tags are inherited, the list contains
14582 the targets in the same sequence as the headlines appear, i.e.
14583 the tags of the current headline come last.
14584 When LOCAL is non-nil, only return tags from the current headline,
14585 ignore inherited ones."
14586 (interactive)
14587 (if (and org-trust-scanner-tags
14588 (or (not pos) (equal pos (point)))
14589 (not local))
14590 org-scanner-tags
14591 (let (tags ltags lastpos parent)
14592 (save-excursion
14593 (save-restriction
14594 (widen)
14595 (goto-char (or pos (point)))
14596 (save-match-data
14597 (catch 'done
14598 (condition-case nil
14599 (progn
14600 (org-back-to-heading t)
14601 (while (not (equal lastpos (point)))
14602 (setq lastpos (point))
14603 (when (looking-at
14604 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14605 (setq ltags (org-split-string
14606 (org-match-string-no-properties 1) ":"))
14607 (when parent
14608 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14609 (setq tags (append
14610 (if parent
14611 (org-remove-uninherited-tags ltags)
14612 ltags)
14613 tags)))
14614 (or org-use-tag-inheritance (throw 'done t))
14615 (if local (throw 'done t))
14616 (or (org-up-heading-safe) (error nil))
14617 (setq parent t)))
14618 (error nil)))))
14619 (if local
14620 tags
14621 (reverse (delete-dups
14622 (reverse (append
14623 (org-remove-uninherited-tags
14624 org-file-tags) tags)))))))))
14626 (defun org-add-prop-inherited (s)
14627 (add-text-properties 0 (length s) '(inherited t) s)
14630 (defun org-toggle-tag (tag &optional onoff)
14631 "Toggle the tag TAG for the current line.
14632 If ONOFF is `on' or `off', don't toggle but set to this state."
14633 (let (res current)
14634 (save-excursion
14635 (org-back-to-heading t)
14636 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14637 (point-at-eol) t)
14638 (progn
14639 (setq current (match-string 1))
14640 (replace-match ""))
14641 (setq current ""))
14642 (setq current (nreverse (org-split-string current ":")))
14643 (cond
14644 ((eq onoff 'on)
14645 (setq res t)
14646 (or (member tag current) (push tag current)))
14647 ((eq onoff 'off)
14648 (or (not (member tag current)) (setq current (delete tag current))))
14649 (t (if (member tag current)
14650 (setq current (delete tag current))
14651 (setq res t)
14652 (push tag current))))
14653 (end-of-line 1)
14654 (if current
14655 (progn
14656 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14657 (org-set-tags nil t))
14658 (delete-horizontal-space))
14659 (run-hooks 'org-after-tags-change-hook))
14660 res))
14662 (defun org-align-tags-here (to-col)
14663 ;; Assumes that this is a headline
14664 "Align tags on the current headline to TO-COL."
14665 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14666 (beginning-of-line 1)
14667 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14668 (< pos (match-beginning 2)))
14669 (progn
14670 (setq tags-l (- (match-end 2) (match-beginning 2)))
14671 (goto-char (match-beginning 1))
14672 (insert " ")
14673 (delete-region (point) (1+ (match-beginning 2)))
14674 (setq ncol (max (current-column)
14675 (1+ col)
14676 (if (> to-col 0)
14677 to-col
14678 (- (abs to-col) tags-l))))
14679 (setq p (point))
14680 (insert (make-string (- ncol (current-column)) ?\ ))
14681 (setq ncol (current-column))
14682 (when indent-tabs-mode (tabify p (point-at-eol)))
14683 (org-move-to-column (min ncol col)))
14684 (goto-char pos))))
14686 (defun org-set-tags-command (&optional arg just-align)
14687 "Call the set-tags command for the current entry."
14688 (interactive "P")
14689 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14690 (org-set-tags arg just-align)
14691 (save-excursion
14692 (unless (and (org-region-active-p)
14693 org-loop-over-headlines-in-active-region)
14694 (org-back-to-heading t))
14695 (org-set-tags arg just-align))))
14697 (defun org-set-tags-to (data)
14698 "Set the tags of the current entry to DATA, replacing the current tags.
14699 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14700 If DATA is nil or the empty string, any tags will be removed."
14701 (interactive "sTags: ")
14702 (setq data
14703 (cond
14704 ((eq data nil) "")
14705 ((equal data "") "")
14706 ((stringp data)
14707 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14708 ":"))
14709 ((listp data)
14710 (concat ":" (mapconcat 'identity data ":") ":"))))
14711 (when data
14712 (save-excursion
14713 (org-back-to-heading t)
14714 (when (looking-at org-complex-heading-regexp)
14715 (if (match-end 5)
14716 (progn
14717 (goto-char (match-beginning 5))
14718 (insert data)
14719 (delete-region (point) (point-at-eol))
14720 (org-set-tags nil 'align))
14721 (goto-char (point-at-eol))
14722 (insert " " data)
14723 (org-set-tags nil 'align)))
14724 (beginning-of-line 1)
14725 (if (looking-at ".*?\\([ \t]+\\)$")
14726 (delete-region (match-beginning 1) (match-end 1))))))
14728 (defun org-align-all-tags ()
14729 "Align the tags i all headings."
14730 (interactive)
14731 (save-excursion
14732 (or (ignore-errors (org-back-to-heading t))
14733 (outline-next-heading))
14734 (if (org-at-heading-p)
14735 (org-set-tags t)
14736 (message "No headings"))))
14738 (defvar org-indent-indentation-per-level)
14739 (defun org-set-tags (&optional arg just-align)
14740 "Set the tags for the current headline.
14741 With prefix ARG, realign all tags in headings in the current buffer.
14742 When JUST-ALIGN is non-nil, only align tags."
14743 (interactive "P")
14744 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14745 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14746 'region-start-level 'region))
14747 org-loop-over-headlines-in-active-region)
14748 (org-map-entries
14749 ;; We don't use ARG and JUST-ALIGN here because these args
14750 ;; are not useful when looping over headlines.
14751 `(org-set-tags)
14752 org-loop-over-headlines-in-active-region
14753 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14754 (let* ((re org-outline-regexp-bol)
14755 (current (unless arg (org-get-tags-string)))
14756 (col (current-column))
14757 (org-setting-tags t)
14758 table current-tags inherited-tags ; computed below when needed
14759 tags p0 c0 c1 rpl di tc level)
14760 (if arg
14761 (save-excursion
14762 (goto-char (point-min))
14763 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14764 (while (re-search-forward re nil t)
14765 (org-set-tags nil t)
14766 (end-of-line 1)))
14767 (message "All tags realigned to column %d" org-tags-column))
14768 (if just-align
14769 (setq tags current)
14770 ;; Get a new set of tags from the user
14771 (save-excursion
14772 (setq table (append org-tag-persistent-alist
14773 (or org-tag-alist (org-get-buffer-tags))
14774 (and
14775 org-complete-tags-always-offer-all-agenda-tags
14776 (org-global-tags-completion-table
14777 (org-agenda-files))))
14778 org-last-tags-completion-table table
14779 current-tags (org-split-string current ":")
14780 inherited-tags (nreverse
14781 (nthcdr (length current-tags)
14782 (nreverse (org-get-tags-at))))
14783 tags
14784 (if (or (eq t org-use-fast-tag-selection)
14785 (and org-use-fast-tag-selection
14786 (delq nil (mapcar 'cdr table))))
14787 (org-fast-tag-selection
14788 current-tags inherited-tags table
14789 (if org-fast-tag-selection-include-todo
14790 org-todo-key-alist))
14791 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14792 (org-trim
14793 (org-icompleting-read "Tags: "
14794 'org-tags-completion-function
14795 nil nil current 'org-tags-history))))))
14796 (while (string-match "[-+&]+" tags)
14797 ;; No boolean logic, just a list
14798 (setq tags (replace-match ":" t t tags))))
14800 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14802 (if org-tags-sort-function
14803 (setq tags (mapconcat 'identity
14804 (sort (org-split-string
14805 tags (org-re "[^[:alnum:]_@#%]+"))
14806 org-tags-sort-function) ":")))
14808 (if (string-match "\\`[\t ]*\\'" tags)
14809 (setq tags "")
14810 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14811 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14813 ;; Insert new tags at the correct column
14814 (beginning-of-line 1)
14815 (setq level (or (and (looking-at org-outline-regexp)
14816 (- (match-end 0) (point) 1))
14818 (cond
14819 ((and (equal current "") (equal tags "")))
14820 ((re-search-forward
14821 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14822 (point-at-eol) t)
14823 (if (equal tags "")
14824 (setq rpl "")
14825 (goto-char (match-beginning 0))
14826 (setq c0 (current-column)
14827 ;; compute offset for the case of org-indent-mode active
14828 di (if (org-bound-and-true-p org-indent-mode)
14829 (* (1- org-indent-indentation-per-level) (1- level))
14831 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14832 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14833 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14834 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14835 (replace-match rpl t t)
14836 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14837 tags)
14838 (t (error "Tags alignment failed")))
14839 (org-move-to-column col)
14840 (unless just-align
14841 (run-hooks 'org-after-tags-change-hook))))))
14843 (defun org-change-tag-in-region (beg end tag off)
14844 "Add or remove TAG for each entry in the region.
14845 This works in the agenda, and also in an org-mode buffer."
14846 (interactive
14847 (list (region-beginning) (region-end)
14848 (let ((org-last-tags-completion-table
14849 (if (derived-mode-p 'org-mode)
14850 (org-uniquify
14851 (delq nil (append (org-get-buffer-tags)
14852 (org-global-tags-completion-table))))
14853 (org-global-tags-completion-table))))
14854 (org-icompleting-read
14855 "Tag: " 'org-tags-completion-function nil nil nil
14856 'org-tags-history))
14857 (progn
14858 (message "[s]et or [r]emove? ")
14859 (equal (read-char-exclusive) ?r))))
14860 (if (fboundp 'deactivate-mark) (deactivate-mark))
14861 (let ((agendap (equal major-mode 'org-agenda-mode))
14862 l1 l2 m buf pos newhead (cnt 0))
14863 (goto-char end)
14864 (setq l2 (1- (org-current-line)))
14865 (goto-char beg)
14866 (setq l1 (org-current-line))
14867 (loop for l from l1 to l2 do
14868 (org-goto-line l)
14869 (setq m (get-text-property (point) 'org-hd-marker))
14870 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14871 (and agendap m))
14872 (setq buf (if agendap (marker-buffer m) (current-buffer))
14873 pos (if agendap m (point)))
14874 (with-current-buffer buf
14875 (save-excursion
14876 (save-restriction
14877 (goto-char pos)
14878 (setq cnt (1+ cnt))
14879 (org-toggle-tag tag (if off 'off 'on))
14880 (setq newhead (org-get-heading)))))
14881 (and agendap (org-agenda-change-all-lines newhead m))))
14882 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14884 (defun org-tags-completion-function (string predicate &optional flag)
14885 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14886 (confirm (lambda (x) (stringp (car x)))))
14887 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14888 (setq s1 (match-string 1 string)
14889 s2 (match-string 2 string))
14890 (setq s1 "" s2 string))
14891 (cond
14892 ((eq flag nil)
14893 ;; try completion
14894 (setq rtn (try-completion s2 ctable confirm))
14895 (if (stringp rtn)
14896 (setq rtn
14897 (concat s1 s2 (substring rtn (length s2))
14898 (if (and org-add-colon-after-tag-completion
14899 (assoc rtn ctable))
14900 ":" ""))))
14901 rtn)
14902 ((eq flag t)
14903 ;; all-completions
14904 (all-completions s2 ctable confirm))
14905 ((eq flag 'lambda)
14906 ;; exact match?
14907 (assoc s2 ctable)))))
14909 (defun org-fast-tag-insert (kwd tags face &optional end)
14910 "Insert KDW, and the TAGS, the latter with face FACE.
14911 Also insert END."
14912 (insert (format "%-12s" (concat kwd ":"))
14913 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14914 (or end "")))
14916 (defun org-fast-tag-show-exit (flag)
14917 (save-excursion
14918 (org-goto-line 3)
14919 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14920 (replace-match ""))
14921 (when flag
14922 (end-of-line 1)
14923 (org-move-to-column (- (window-width) 19) t)
14924 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14926 (defun org-set-current-tags-overlay (current prefix)
14927 "Add an overlay to CURRENT tag with PREFIX."
14928 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14929 (if (featurep 'xemacs)
14930 (org-overlay-display org-tags-overlay (concat prefix s)
14931 'secondary-selection)
14932 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14933 (org-overlay-display org-tags-overlay (concat prefix s)))))
14935 (defvar org-last-tag-selection-key nil)
14936 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14937 "Fast tag selection with single keys.
14938 CURRENT is the current list of tags in the headline, INHERITED is the
14939 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14940 possibly with grouping information. TODO-TABLE is a similar table with
14941 TODO keywords, should these have keys assigned to them.
14942 If the keys are nil, a-z are automatically assigned.
14943 Returns the new tags string, or nil to not change the current settings."
14944 (let* ((fulltable (append table todo-table))
14945 (maxlen (apply 'max (mapcar
14946 (lambda (x)
14947 (if (stringp (car x)) (string-width (car x)) 0))
14948 fulltable)))
14949 (buf (current-buffer))
14950 (expert (eq org-fast-tag-selection-single-key 'expert))
14951 (buffer-tags nil)
14952 (fwidth (+ maxlen 3 1 3))
14953 (ncol (/ (- (window-width) 4) fwidth))
14954 (i-face 'org-done)
14955 (c-face 'org-todo)
14956 tg cnt e c char c1 c2 ntable tbl rtn
14957 ov-start ov-end ov-prefix
14958 (exit-after-next org-fast-tag-selection-single-key)
14959 (done-keywords org-done-keywords)
14960 groups ingroup)
14961 (save-excursion
14962 (beginning-of-line 1)
14963 (if (looking-at
14964 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14965 (setq ov-start (match-beginning 1)
14966 ov-end (match-end 1)
14967 ov-prefix "")
14968 (setq ov-start (1- (point-at-eol))
14969 ov-end (1+ ov-start))
14970 (skip-chars-forward "^\n\r")
14971 (setq ov-prefix
14972 (concat
14973 (buffer-substring (1- (point)) (point))
14974 (if (> (current-column) org-tags-column)
14976 (make-string (- org-tags-column (current-column)) ?\ ))))))
14977 (move-overlay org-tags-overlay ov-start ov-end)
14978 (save-window-excursion
14979 (if expert
14980 (set-buffer (get-buffer-create " *Org tags*"))
14981 (delete-other-windows)
14982 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14983 (org-switch-to-buffer-other-window " *Org tags*"))
14984 (erase-buffer)
14985 (org-set-local 'org-done-keywords done-keywords)
14986 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14987 (org-fast-tag-insert "Current" current c-face "\n\n")
14988 (org-fast-tag-show-exit exit-after-next)
14989 (org-set-current-tags-overlay current ov-prefix)
14990 (setq tbl fulltable char ?a cnt 0)
14991 (while (setq e (pop tbl))
14992 (cond
14993 ((equal (car e) :startgroup)
14994 (push '() groups) (setq ingroup t)
14995 (when (not (= cnt 0))
14996 (setq cnt 0)
14997 (insert "\n"))
14998 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14999 ((equal (car e) :endgroup)
15000 (setq ingroup nil cnt 0)
15001 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15002 ((equal e '(:newline))
15003 (when (not (= cnt 0))
15004 (setq cnt 0)
15005 (insert "\n")
15006 (setq e (car tbl))
15007 (while (equal (car tbl) '(:newline))
15008 (insert "\n")
15009 (setq tbl (cdr tbl)))))
15010 ((equal e '(:grouptags)) nil)
15012 (setq tg (copy-sequence (car e)) c2 nil)
15013 (if (cdr e)
15014 (setq c (cdr e))
15015 ;; automatically assign a character.
15016 (setq c1 (string-to-char
15017 (downcase (substring
15018 tg (if (= (string-to-char tg) ?@) 1 0)))))
15019 (if (or (rassoc c1 ntable) (rassoc c1 table))
15020 (while (or (rassoc char ntable) (rassoc char table))
15021 (setq char (1+ char)))
15022 (setq c2 c1))
15023 (setq c (or c2 char)))
15024 (if ingroup (push tg (car groups)))
15025 (setq tg (org-add-props tg nil 'face
15026 (cond
15027 ((not (assoc tg table))
15028 (org-get-todo-face tg))
15029 ((member tg current) c-face)
15030 ((member tg inherited) i-face))))
15031 (if (equal (caar tbl) :grouptags)
15032 (org-add-props tg nil 'face 'org-tag-group))
15033 (if (and (= cnt 0) (not ingroup)) (insert " "))
15034 (insert "[" c "] " tg (make-string
15035 (- fwidth 4 (length tg)) ?\ ))
15036 (push (cons tg c) ntable)
15037 (when (= (setq cnt (1+ cnt)) ncol)
15038 (insert "\n")
15039 (if ingroup (insert " "))
15040 (setq cnt 0)))))
15041 (setq ntable (nreverse ntable))
15042 (insert "\n")
15043 (goto-char (point-min))
15044 (if (not expert) (org-fit-window-to-buffer))
15045 (setq rtn
15046 (catch 'exit
15047 (while t
15048 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15049 (if (not groups) "no " "")
15050 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15051 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15052 (setq org-last-tag-selection-key c)
15053 (cond
15054 ((= c ?\r) (throw 'exit t))
15055 ((= c ?!)
15056 (setq groups (not groups))
15057 (goto-char (point-min))
15058 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15059 ((= c ?\C-c)
15060 (if (not expert)
15061 (org-fast-tag-show-exit
15062 (setq exit-after-next (not exit-after-next)))
15063 (setq expert nil)
15064 (delete-other-windows)
15065 (set-window-buffer (split-window-vertically) " *Org tags*")
15066 (org-switch-to-buffer-other-window " *Org tags*")
15067 (org-fit-window-to-buffer)))
15068 ((or (= c ?\C-g)
15069 (and (= c ?q) (not (rassoc c ntable))))
15070 (org-detach-overlay org-tags-overlay)
15071 (setq quit-flag t))
15072 ((= c ?\ )
15073 (setq current nil)
15074 (if exit-after-next (setq exit-after-next 'now)))
15075 ((= c ?\t)
15076 (condition-case nil
15077 (setq tg (org-icompleting-read
15078 "Tag: "
15079 (or buffer-tags
15080 (with-current-buffer buf
15081 (org-get-buffer-tags)))))
15082 (quit (setq tg "")))
15083 (when (string-match "\\S-" tg)
15084 (add-to-list 'buffer-tags (list tg))
15085 (if (member tg current)
15086 (setq current (delete tg current))
15087 (push tg current)))
15088 (if exit-after-next (setq exit-after-next 'now)))
15089 ((setq e (rassoc c todo-table) tg (car e))
15090 (with-current-buffer buf
15091 (save-excursion (org-todo tg)))
15092 (if exit-after-next (setq exit-after-next 'now)))
15093 ((setq e (rassoc c ntable) tg (car e))
15094 (if (member tg current)
15095 (setq current (delete tg current))
15096 (loop for g in groups do
15097 (if (member tg g)
15098 (mapc (lambda (x)
15099 (setq current (delete x current)))
15100 g)))
15101 (push tg current))
15102 (if exit-after-next (setq exit-after-next 'now))))
15104 ;; Create a sorted list
15105 (setq current
15106 (sort current
15107 (lambda (a b)
15108 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15109 (if (eq exit-after-next 'now) (throw 'exit t))
15110 (goto-char (point-min))
15111 (beginning-of-line 2)
15112 (delete-region (point) (point-at-eol))
15113 (org-fast-tag-insert "Current" current c-face)
15114 (org-set-current-tags-overlay current ov-prefix)
15115 (while (re-search-forward
15116 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15117 (setq tg (match-string 1))
15118 (add-text-properties
15119 (match-beginning 1) (match-end 1)
15120 (list 'face
15121 (cond
15122 ((member tg current) c-face)
15123 ((member tg inherited) i-face)
15124 (t (get-text-property (match-beginning 1) 'face))))))
15125 (goto-char (point-min)))))
15126 (org-detach-overlay org-tags-overlay)
15127 (if rtn
15128 (mapconcat 'identity current ":")
15129 nil))))
15131 (defun org-get-tags-string ()
15132 "Get the TAGS string in the current headline."
15133 (unless (org-at-heading-p t)
15134 (user-error "Not on a heading"))
15135 (save-excursion
15136 (beginning-of-line 1)
15137 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15138 (org-match-string-no-properties 1)
15139 "")))
15141 (defun org-get-tags ()
15142 "Get the list of tags specified in the current headline."
15143 (org-split-string (org-get-tags-string) ":"))
15145 (defun org-get-buffer-tags ()
15146 "Get a table of all tags used in the buffer, for completion."
15147 (let (tags)
15148 (save-excursion
15149 (goto-char (point-min))
15150 (while (re-search-forward
15151 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15152 (when (equal (char-after (point-at-bol 0)) ?*)
15153 (mapc (lambda (x) (add-to-list 'tags x))
15154 (org-split-string (org-match-string-no-properties 1) ":")))))
15155 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15156 (mapcar 'list tags)))
15158 ;;;; The mapping API
15160 (defun org-map-entries (func &optional match scope &rest skip)
15161 "Call FUNC at each headline selected by MATCH in SCOPE.
15163 FUNC is a function or a lisp form. The function will be called without
15164 arguments, with the cursor positioned at the beginning of the headline.
15165 The return values of all calls to the function will be collected and
15166 returned as a list.
15168 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15169 does not need to preserve point. After evaluation, the cursor will be
15170 moved to the end of the line (presumably of the headline of the
15171 processed entry) and search continues from there. Under some
15172 circumstances, this may not produce the wanted results. For example,
15173 if you have removed (e.g. archived) the current (sub)tree it could
15174 mean that the next entry will be skipped entirely. In such cases, you
15175 can specify the position from where search should continue by making
15176 FUNC set the variable `org-map-continue-from' to the desired buffer
15177 position.
15179 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15180 Only headlines that are matched by this query will be considered during
15181 the iteration. When MATCH is nil or t, all headlines will be
15182 visited by the iteration.
15184 SCOPE determines the scope of this command. It can be any of:
15186 nil The current buffer, respecting the restriction if any
15187 tree The subtree started with the entry at point
15188 region The entries within the active region, if any
15189 region-start-level
15190 The entries within the active region, but only those at
15191 the same level than the first one.
15192 file The current buffer, without restriction
15193 file-with-archives
15194 The current buffer, and any archives associated with it
15195 agenda All agenda files
15196 agenda-with-archives
15197 All agenda files with any archive files associated with them
15198 \(file1 file2 ...)
15199 If this is a list, all files in the list will be scanned
15201 The remaining args are treated as settings for the skipping facilities of
15202 the scanner. The following items can be given here:
15204 archive skip trees with the archive tag
15205 comment skip trees with the COMMENT keyword
15206 function or Emacs Lisp form:
15207 will be used as value for `org-agenda-skip-function', so
15208 whenever the function returns a position, FUNC will not be
15209 called for that entry and search will continue from the
15210 position returned
15212 If your function needs to retrieve the tags including inherited tags
15213 at the *current* entry, you can use the value of the variable
15214 `org-scanner-tags' which will be much faster than getting the value
15215 with `org-get-tags-at'. If your function gets properties with
15216 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15217 to t around the call to `org-entry-properties' to get the same speedup.
15218 Note that if your function moves around to retrieve tags and properties at
15219 a *different* entry, you cannot use these techniques."
15220 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15221 (not (org-region-active-p)))
15222 (let* ((org-agenda-archives-mode nil) ; just to make sure
15223 (org-agenda-skip-archived-trees (memq 'archive skip))
15224 (org-agenda-skip-comment-trees (memq 'comment skip))
15225 (org-agenda-skip-function
15226 (car (org-delete-all '(comment archive) skip)))
15227 (org-tags-match-list-sublevels t)
15228 (start-level (eq scope 'region-start-level))
15229 matcher file res
15230 org-todo-keywords-for-agenda
15231 org-done-keywords-for-agenda
15232 org-todo-keyword-alist-for-agenda
15233 org-tag-alist-for-agenda
15234 todo-only)
15236 (cond
15237 ((eq match t) (setq matcher t))
15238 ((eq match nil) (setq matcher t))
15239 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15241 (save-excursion
15242 (save-restriction
15243 (cond ((eq scope 'tree)
15244 (org-back-to-heading t)
15245 (org-narrow-to-subtree)
15246 (setq scope nil))
15247 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15248 (org-region-active-p))
15249 ;; If needed, set start-level to a string like "2"
15250 (when start-level
15251 (save-excursion
15252 (goto-char (region-beginning))
15253 (unless (org-at-heading-p) (outline-next-heading))
15254 (setq start-level (org-current-level))))
15255 (narrow-to-region (region-beginning)
15256 (save-excursion
15257 (goto-char (region-end))
15258 (unless (and (bolp) (org-at-heading-p))
15259 (outline-next-heading))
15260 (point)))
15261 (setq scope nil)))
15263 (if (not scope)
15264 (progn
15265 (org-agenda-prepare-buffers
15266 (list (buffer-file-name (current-buffer))))
15267 (setq res (org-scan-tags func matcher todo-only start-level)))
15268 ;; Get the right scope
15269 (cond
15270 ((and scope (listp scope) (symbolp (car scope)))
15271 (setq scope (eval scope)))
15272 ((eq scope 'agenda)
15273 (setq scope (org-agenda-files t)))
15274 ((eq scope 'agenda-with-archives)
15275 (setq scope (org-agenda-files t))
15276 (setq scope (org-add-archive-files scope)))
15277 ((eq scope 'file)
15278 (setq scope (list (buffer-file-name))))
15279 ((eq scope 'file-with-archives)
15280 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15281 (org-agenda-prepare-buffers scope)
15282 (while (setq file (pop scope))
15283 (with-current-buffer (org-find-base-buffer-visiting file)
15284 (save-excursion
15285 (save-restriction
15286 (widen)
15287 (goto-char (point-min))
15288 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15289 res)))
15291 ;;; Properties API
15293 (defconst org-special-properties
15294 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOSED" "PRIORITY"
15295 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15296 "The special properties valid in Org-mode.
15297 These are properties that are not defined in the property drawer,
15298 but in some other way.")
15300 (defconst org-default-properties
15301 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15302 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15303 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15304 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15305 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15306 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15307 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15308 "Some properties that are used by Org mode for various purposes.
15309 Being in this list makes sure that they are offered for completion.")
15311 (defun org--update-property-plist (key val props)
15312 "Associate KEY to VAL in alist PROPS.
15313 Modifications are made by side-effect. Return new alist."
15314 (let* ((appending (string= (substring key -1) "+"))
15315 (key (if appending (substring key 0 -1) key))
15316 (old (assoc-string key props t)))
15317 (if (not old) (cons (cons key val) props)
15318 (setcdr old (if appending (concat (cdr old) " " val) val))
15319 props)))
15321 (defun org-get-property-block (&optional beg force)
15322 "Return the (beg . end) range of the body of the property drawer.
15323 BEG is the beginning of the current subtree, or of the part
15324 before the first headline. If it is not given, it will be found.
15325 If the drawer does not exist, create it if FORCE is non-nil, or
15326 return nil."
15327 (org-with-wide-buffer
15328 (when beg (goto-char beg))
15329 (unless (org-before-first-heading-p)
15330 (let ((beg (cond (beg)
15331 ((or (not (featurep 'org-inlinetask))
15332 (org-inlinetask-in-task-p))
15333 (org-back-to-heading t))
15334 (t (org-with-limited-levels (org-back-to-heading t))))))
15335 (forward-line)
15336 (when (org-looking-at-p org-planning-line-re) (forward-line))
15337 (cond ((looking-at org-property-drawer-re)
15338 (forward-line)
15339 (cons (point) (progn (goto-char (match-end 0))
15340 (line-beginning-position))))
15341 (force
15342 (org-insert-property-drawer)
15343 (let ((pos (save-excursion (search-forward ":END:")
15344 (line-beginning-position))))
15345 (cons pos pos))))))))
15347 (defun org-at-property-p ()
15348 "Non-nil when point is inside a property drawer.
15349 See `org-property-re' for match data, if applicable."
15350 (save-excursion
15351 (beginning-of-line)
15352 (and (looking-at org-property-re)
15353 (let ((property-drawer (save-match-data (org-get-property-block))))
15354 (and property-drawer (< (point) (cdr property-drawer)))))))
15356 (defun org-property-action ()
15357 "Do an action on properties."
15358 (interactive)
15359 (unless (org-at-property-p) (user-error "Not at a property"))
15360 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15361 (let ((c (read-char-exclusive)))
15362 (case c
15363 (?s (call-interactively #'org-set-property))
15364 (?d (call-interactively #'org-delete-property))
15365 (?D (call-interactively #'org-delete-property-globally))
15366 (?c (call-interactively #'org-compute-property-at-point))
15367 (otherwise (user-error "No such property action %c" c)))))
15369 (defun org-inc-effort ()
15370 "Increment the value of the effort property in the current entry."
15371 (interactive)
15372 (org-set-effort nil t))
15374 (defvar org-clock-effort) ; Defined in org-clock.el.
15375 (defvar org-clock-current-task) ; Defined in org-clock.el.
15376 (defun org-set-effort (&optional value increment)
15377 "Set the effort property of the current entry.
15378 With numerical prefix arg, use the nth allowed value, 0 stands for the
15379 10th allowed value.
15381 When INCREMENT is non-nil, set the property to the next allowed value."
15382 (interactive "P")
15383 (if (equal value 0) (setq value 10))
15384 (let* ((completion-ignore-case t)
15385 (prop org-effort-property)
15386 (cur (org-entry-get nil prop))
15387 (allowed (org-property-get-allowed-values nil prop 'table))
15388 (existing (mapcar 'list (org-property-values prop)))
15389 (heading (nth 4 (org-heading-components)))
15391 (val (cond
15392 ((stringp value) value)
15393 ((and allowed (integerp value))
15394 (or (car (nth (1- value) allowed))
15395 (car (org-last allowed))))
15396 ((and allowed increment)
15397 (or (caadr (member (list cur) allowed))
15398 (user-error "Allowed effort values are not set")))
15399 (allowed
15400 (message "Select 1-9,0, [RET%s]: %s"
15401 (if cur (concat "=" cur) "")
15402 (mapconcat 'car allowed " "))
15403 (setq rpl (read-char-exclusive))
15404 (if (equal rpl ?\r)
15406 (setq rpl (- rpl ?0))
15407 (if (equal rpl 0) (setq rpl 10))
15408 (if (and (> rpl 0) (<= rpl (length allowed)))
15409 (car (nth (1- rpl) allowed))
15410 (org-completing-read "Effort: " allowed nil))))
15412 (let (org-completion-use-ido org-completion-use-iswitchb)
15413 (org-completing-read
15414 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15415 (concat "[" cur "]") "")
15416 ": ")
15417 existing nil nil "" nil cur))))))
15418 (unless (equal (org-entry-get nil prop) val)
15419 (org-entry-put nil prop val))
15420 (org-refresh-property
15421 '((effort . identity)
15422 (effort-minutes . org-duration-string-to-minutes))
15423 val)
15424 (when (string= heading org-clock-current-task)
15425 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15426 (org-clock-update-mode-line))
15427 (message "%s is now %s" prop val)))
15429 (defun org-entry-properties (&optional pom which)
15430 "Get all properties of the current entry.
15432 When POM is a buffer position, get all properties from the entry
15433 there instead.
15435 This includes the TODO keyword, the tags, time strings for
15436 deadline, scheduled, and clocking, and any additional properties
15437 defined in the entry.
15439 If WHICH is nil or `all', get all properties. If WHICH is
15440 `special' or `standard', only get that subclass. If WHICH is
15441 a string, only get that property.
15443 Return value is an alist. Keys are properties, as upcased
15444 strings."
15445 (org-with-point-at pom
15446 (when (and (derived-mode-p 'org-mode)
15447 (ignore-errors (org-back-to-heading t)))
15448 (catch 'exit
15449 (let* ((beg (point))
15450 (specific (and (stringp which) (upcase which)))
15451 (which (cond ((not specific) which)
15452 ((member specific org-special-properties) 'special)
15453 (t 'standard)))
15454 props)
15455 ;; Get the special properties, like TODO and TAGS.
15456 (when (memq which '(nil all special))
15457 (when (or (not specific) (string= specific "CLOCKSUM"))
15458 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15459 (when clocksum
15460 (push (cons "CLOCKSUM"
15461 (org-columns-number-to-string
15462 (/ (float clocksum) 60.) 'add_times))
15463 props)))
15464 (when specific (throw 'exit props)))
15465 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15466 (let ((clocksumt (get-text-property (point)
15467 :org-clock-minutes-today)))
15468 (when clocksumt
15469 (push (cons "CLOCKSUM_T"
15470 (org-columns-number-to-string
15471 (/ (float clocksumt) 60.) 'add_times))
15472 props)))
15473 (when specific (throw 'exit props)))
15474 (when (or (not specific) (string= specific "TODO"))
15475 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15476 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15477 (when specific (throw 'exit props)))
15478 (when (or (not specific) (string= specific "PRIORITY"))
15479 (when (looking-at org-priority-regexp)
15480 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15481 (when specific (throw 'exit props)))
15482 (when (or (not specific) (string= specific "FILE"))
15483 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15484 props)
15485 (when specific (throw 'exit props)))
15486 (when (or (not specific) (string= specific "TAGS"))
15487 (let ((value (org-string-nw-p (org-get-tags-string))))
15488 (when value (push (cons "TAGS" value) props)))
15489 (when specific (throw 'exit props)))
15490 (when (or (not specific) (string= specific "ALLTAGS"))
15491 (let ((value (org-get-tags-at)))
15492 (when value
15493 (push (cons "ALLTAGS"
15494 (format ":%s:" (mapconcat #'identity value ":")))
15495 props)))
15496 (when specific (throw 'exit props)))
15497 (when (or (not specific) (string= specific "BLOCKED"))
15498 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15499 (when specific (throw 'exit props)))
15500 (when (or (not specific)
15501 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15502 (forward-line)
15503 (when (org-looking-at-p org-planning-line-re)
15504 (end-of-line)
15505 (let ((bol (line-beginning-position)))
15506 ;; Backward compatibility: time keywords used to be
15507 ;; configurable (before 8.3). Make sure we get the
15508 ;; correct keyword.
15509 (dolist (k (if (not specific)
15510 (list org-closed-string
15511 org-deadline-string
15512 org-scheduled-string)
15513 (list (cond ((string= specific "CLOSED")
15514 org-closed-string)
15515 ((string= specific "DEADLINE")
15516 org-deadline-string)
15517 (t org-scheduled-string)))))
15518 (save-excursion
15519 (when (search-backward k bol t)
15520 (goto-char (match-end 0))
15521 (skip-chars-forward " \t")
15522 (and (looking-at org-ts-regexp-both)
15523 (push (cons specific (match-string 0)) props)))))))
15524 (when specific (throw 'exit props)))
15525 (when (or (not specific)
15526 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15527 (let ((find-ts
15528 (lambda (end ts)
15529 (let ((regexp (if (or (string= specific "TIMESTAMP")
15530 (assoc "TIMESTAMP_IA" ts))
15531 org-ts-regexp
15532 org-ts-regexp-both)))
15533 (catch 'next
15534 (while (re-search-forward regexp end t)
15535 (backward-char)
15536 (let ((object (org-element-context)))
15537 ;; Accept to match timestamps in node
15538 ;; properties, too.
15539 (when (memq (org-element-type object)
15540 '(node-property timestamp))
15541 (let ((type
15542 (org-element-property :type object)))
15543 (cond
15544 ((and (memq type '(active active-range))
15545 (not (equal specific "TIMESTAMP_IA")))
15546 (unless (assoc "TIMESTAMP" ts)
15547 (push (cons "TIMESTAMP"
15548 (org-element-property
15549 :raw-value object))
15551 (when specific (throw 'exit ts))))
15552 ((and (memq type '(inactive inactive-range))
15553 (not (string= specific "TIMESTAMP")))
15554 (unless (assoc "TIMESTAMP_IA" ts)
15555 (push (cons "TIMESTAMP_IA"
15556 (org-element-property
15557 :raw-value object))
15559 (when specific (throw 'exit ts))))))
15560 ;; Both timestamp types are found,
15561 ;; move to next part.
15562 (when (= (length ts) 2) (throw 'next ts)))))
15563 ts)))))
15564 (goto-char beg)
15565 ;; First look for timestamps within headline.
15566 (let ((ts (funcall find-ts (line-end-position) nil)))
15567 (if (= (length ts) 2) (setq props (nconc ts props))
15568 (forward-line)
15569 ;; Then find timestamps in the section, skipping
15570 ;; planning line.
15571 (when (org-looking-at-p org-planning-line-re)
15572 (forward-line))
15573 (let ((end (save-excursion (outline-next-heading))))
15574 (setq props (nconc (funcall find-ts end ts) props))))))))
15575 ;; Get the standard properties, like :PROP:.
15576 (when (memq which '(nil all standard))
15577 ;; If we are looking after a specific property, delegate
15578 ;; to `org-entry-get', which is faster. However, make an
15579 ;; exception for "CATEGORY", since it can be also set
15580 ;; through keywords (i.e. #+CATEGORY).
15581 (if (and specific (not (equal specific "CATEGORY")))
15582 (let ((value (org-entry-get beg specific nil t)))
15583 (throw 'exit (and value (list (cons specific value)))))
15584 (let ((range (org-get-property-block beg)))
15585 (when range
15586 (let ((end (cdr range)) seen-base)
15587 (goto-char (car range))
15588 ;; Unlike to `org--update-property-plist', we
15589 ;; handle the case where base values is found
15590 ;; after its extension. We also forbid standard
15591 ;; properties to be named as special properties.
15592 (while (re-search-forward org-property-re end t)
15593 (let* ((key (upcase (org-match-string-no-properties 2)))
15594 (extendp (org-string-match-p "\\+\\'" key))
15595 (key-base (if extendp (substring key 0 -1) key))
15596 (value (org-match-string-no-properties 3)))
15597 (cond
15598 ((member-ignore-case key-base org-special-properties))
15599 (extendp
15600 (setq props
15601 (org--update-property-plist key value props)))
15602 ((member key seen-base))
15603 (t (push key seen-base)
15604 (let ((p (assoc-string key props t)))
15605 (if p (setcdr p (concat value " " (cdr p)))
15606 (push (cons key value) props))))))))))))
15607 (unless (assoc "CATEGORY" props)
15608 (push (cons "CATEGORY" (org-get-category)) props)
15609 (when (string= specific "CATEGORY") (throw 'exit props)))
15610 ;; Return value.
15611 (append (get-text-property beg 'org-summaries) props))))))
15613 (defun org-entry-get (pom property &optional inherit literal-nil)
15614 "Get value of PROPERTY for entry or content at point-or-marker POM.
15616 If INHERIT is non-nil and the entry does not have the property,
15617 then also check higher levels of the hierarchy. If INHERIT is
15618 the symbol `selective', use inheritance only if the setting in
15619 `org-use-property-inheritance' selects PROPERTY for inheritance.
15621 If the property is present but empty, the return value is the
15622 empty string. If the property is not present at all, nil is
15623 returned. In any other case, return the value as a string.
15624 Search is case-insensitive.
15626 If LITERAL-NIL is set, return the string value \"nil\" as
15627 a string, do not interpret it as the list atom nil. This is used
15628 for inheritance when a \"nil\" value can supersede a non-nil
15629 value higher up the hierarchy."
15630 (org-with-point-at pom
15631 (cond
15632 ((and inherit
15633 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15634 (org-entry-get-with-inheritance property literal-nil))
15635 ((member-ignore-case property org-special-properties)
15636 ;; We need a special property. Use `org-entry-properties' to
15637 ;; retrieve it, but specify the wanted property.
15638 (cdr (assoc-string property (org-entry-properties nil property))))
15640 (let ((range (org-get-property-block)))
15641 (when range
15642 (let* ((case-fold-search t)
15643 (end (cdr range))
15644 (props
15645 (let ((global
15646 (or (assoc-string property org-file-properties t)
15647 (assoc-string property org-global-properties t)
15648 (assoc-string
15649 property org-global-properties-fixed t))))
15650 ;; Make sure to not re-use GLOBAL as
15651 ;; `org--update-property-plist' would alter it by
15652 ;; side-effect.
15653 (and global (list (cons property (cdr global))))))
15654 (find-value
15655 (lambda (key)
15656 (when (re-search-forward (org-re-property key nil t) end t)
15657 (setq props
15658 (org--update-property-plist
15659 key (org-match-string-no-properties 3) props))))))
15660 (goto-char (car range))
15661 ;; Find base value.
15662 (save-excursion (funcall find-value property))
15663 ;; Find additional values.
15664 (let ((property+ (concat property "+")))
15665 (while (funcall find-value property+)))
15666 ;; Return final value.
15667 (let ((val (cdr (assoc-string property props t))))
15668 (if literal-nil val (org-not-nil val))))))))))
15670 (defun org-property-or-variable-value (var &optional inherit)
15671 "Check if there is a property fixing the value of VAR.
15672 If yes, return this value. If not, return the current value of the variable."
15673 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15674 (if (and prop (stringp prop) (string-match "\\S-" prop))
15675 (read prop)
15676 (symbol-value var))))
15678 (defun org-entry-delete (pom property)
15679 "Delete the property PROPERTY from entry at point-or-marker POM."
15680 (unless (member property org-special-properties)
15681 (org-with-point-at pom
15682 (let ((range (org-get-property-block)))
15683 (when range
15684 (let ((begin (car range))
15685 (end (copy-marker (cdr range))))
15686 (goto-char begin)
15687 (when (re-search-forward (org-re-property property nil t) end t)
15688 (delete-region (match-beginning 0) (line-beginning-position 2))
15689 ;; If drawer is empty, remove it altogether.
15690 (when (= begin end)
15691 (delete-region (line-beginning-position 0)
15692 (line-beginning-position 2)))
15693 (set-marker end nil))))))))
15695 ;; Multi-values properties are properties that contain multiple values
15696 ;; These values are assumed to be single words, separated by whitespace.
15697 (defun org-entry-add-to-multivalued-property (pom property value)
15698 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15699 (let* ((old (org-entry-get pom property))
15700 (values (and old (org-split-string old "[ \t]"))))
15701 (setq value (org-entry-protect-space value))
15702 (unless (member value values)
15703 (setq values (append values (list value)))
15704 (org-entry-put pom property
15705 (mapconcat 'identity values " ")))))
15707 (defun org-entry-remove-from-multivalued-property (pom property value)
15708 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15709 (let* ((old (org-entry-get pom property))
15710 (values (and old (org-split-string old "[ \t]"))))
15711 (setq value (org-entry-protect-space value))
15712 (when (member value values)
15713 (setq values (delete value values))
15714 (org-entry-put pom property
15715 (mapconcat 'identity values " ")))))
15717 (defun org-entry-member-in-multivalued-property (pom property value)
15718 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15719 (let* ((old (org-entry-get pom property))
15720 (values (and old (org-split-string old "[ \t]"))))
15721 (setq value (org-entry-protect-space value))
15722 (member value values)))
15724 (defun org-entry-get-multivalued-property (pom property)
15725 "Return a list of values in a multivalued property."
15726 (let* ((value (org-entry-get pom property))
15727 (values (and value (org-split-string value "[ \t]"))))
15728 (mapcar 'org-entry-restore-space values)))
15730 (defun org-entry-put-multivalued-property (pom property &rest values)
15731 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15732 VALUES should be a list of strings. Spaces will be protected."
15733 (org-entry-put pom property
15734 (mapconcat 'org-entry-protect-space values " "))
15735 (let* ((value (org-entry-get pom property))
15736 (values (and value (org-split-string value "[ \t]"))))
15737 (mapcar 'org-entry-restore-space values)))
15739 (defun org-entry-protect-space (s)
15740 "Protect spaces and newline in string S."
15741 (while (string-match " " s)
15742 (setq s (replace-match "%20" t t s)))
15743 (while (string-match "\n" s)
15744 (setq s (replace-match "%0A" t t s)))
15747 (defun org-entry-restore-space (s)
15748 "Restore spaces and newline in string S."
15749 (while (string-match "%20" s)
15750 (setq s (replace-match " " t t s)))
15751 (while (string-match "%0A" s)
15752 (setq s (replace-match "\n" t t s)))
15755 (defvar org-entry-property-inherited-from (make-marker)
15756 "Marker pointing to the entry from where a property was inherited.
15757 Each call to `org-entry-get-with-inheritance' will set this marker to the
15758 location of the entry where the inheritance search matched. If there was
15759 no match, the marker will point nowhere.
15760 Note that also `org-entry-get' calls this function, if the INHERIT flag
15761 is set.")
15763 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15764 "Get PROPERTY of entry or content at point, search higher levels if needed.
15765 The search will stop at the first ancestor which has the property defined.
15766 If the value found is \"nil\", return nil to show that the property
15767 should be considered as undefined (this is the meaning of nil here).
15768 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15769 (move-marker org-entry-property-inherited-from nil)
15770 (let (value)
15771 (org-with-wide-buffer
15772 (catch 'exit
15773 (while t
15774 (when (setq value (org-entry-get nil property nil literal-nil))
15775 (org-back-to-heading t)
15776 (move-marker org-entry-property-inherited-from (point))
15777 (throw 'exit nil))
15778 (or (org-up-heading-safe) (throw 'exit nil)))))
15779 (unless value
15780 (setq value
15781 (cdr (or (assoc-string property org-file-properties t)
15782 (assoc-string property org-global-properties t)
15783 (assoc-string property org-global-properties-fixed t)))))
15784 (if literal-nil value (org-not-nil value))))
15786 (defvar org-property-changed-functions nil
15787 "Hook called when the value of a property has changed.
15788 Each hook function should accept two arguments, the name of the property
15789 and the new value.")
15791 (defun org-entry-put (pom property value)
15792 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15794 If the value is `nil', it is converted to the empty string. If
15795 it is not a string, an error is raised.
15797 PROPERTY can be any regular property (see
15798 `org-special-properties'). It can also be \"TODO\",
15799 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15801 For the last two properties, VALUE may have any of the special
15802 values \"earlier\" and \"later\". The function then increases or
15803 decreases scheduled or deadline date by one day."
15804 (cond ((null value) (setq value ""))
15805 ((not (stringp value)) (error "Properties values should be strings")))
15806 (org-with-point-at pom
15807 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15808 (org-back-to-heading t)
15809 (org-with-limited-levels (org-back-to-heading t)))
15810 (let ((beg (point)))
15811 (cond
15812 ((equal property "TODO")
15813 (cond ((not (org-string-nw-p value)) (setq value 'none))
15814 ((not (member value org-todo-keywords-1))
15815 (user-error "\"%s\" is not a valid TODO state" value)))
15816 (org-todo value)
15817 (org-set-tags nil 'align))
15818 ((equal property "PRIORITY")
15819 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15820 (org-set-tags nil 'align))
15821 ((equal property "SCHEDULED")
15822 (forward-line)
15823 (if (and (org-looking-at-p org-planning-line-re)
15824 (re-search-forward
15825 org-scheduled-time-regexp (line-end-position) t))
15826 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15827 ((string= value "later") (org-timestamp-change 1 'day))
15828 ((string= value "") (org-schedule '(4)))
15829 (t (org-schedule nil value)))
15830 (if (member value '("earlier" "later" ""))
15831 (call-interactively #'org-schedule)
15832 (org-schedule nil value))))
15833 ((equal property "DEADLINE")
15834 (forward-line)
15835 (if (and (org-looking-at-p org-planning-line-re)
15836 (re-search-forward
15837 org-deadline-time-regexp (line-end-position) t))
15838 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15839 ((string= value "later") (org-timestamp-change 1 'day))
15840 ((string= value "") (org-deadline '(4)))
15841 (t (org-deadline nil value)))
15842 (if (member value '("earlier" "later" ""))
15843 (call-interactively #'org-deadline)
15844 (org-deadline nil value))))
15845 ((member property org-special-properties)
15846 (error "The %s property cannot be set with `org-entry-put'" property))
15848 (let* ((range (org-get-property-block beg 'force))
15849 (end (cdr range))
15850 (case-fold-search t))
15851 (goto-char (car range))
15852 (if (re-search-forward (org-re-property property nil t) end t)
15853 (progn (delete-region (match-beginning 0) (match-end 0))
15854 (goto-char (match-beginning 0)))
15855 (goto-char end)
15856 (insert "\n")
15857 (backward-char))
15858 (insert ":" property ":")
15859 (when value (insert " " value))
15860 (org-indent-line)))))
15861 (run-hook-with-args 'org-property-changed-functions property value)))
15863 (defun org-buffer-property-keys (&optional specials defaults columns)
15864 "Get all property keys in the current buffer.
15866 When SPECIALS is non-nil, also list the special properties that
15867 reflect things like tags and TODO state.
15869 When DEFAULTS is non-nil, also include properties that has
15870 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15871 DESCRIPTION, LOCATION, and LOGGING and others.
15873 When COLUMNS in non-nil, also include property names given in
15874 COLUMN formats in the current buffer."
15875 (let ((case-fold-search t)
15876 (props (append
15877 (and specials org-special-properties)
15878 (and defaults (cons org-effort-property org-default-properties))
15879 nil)))
15880 (org-with-wide-buffer
15881 (goto-char (point-min))
15882 (while (re-search-forward org-property-start-re nil t)
15883 (let ((range (org-get-property-block)))
15884 (catch 'skip
15885 (unless range
15886 (when (and (not (org-before-first-heading-p))
15887 (y-or-n-p (format "Malformed drawer at %d, repair?"
15888 (line-beginning-position))))
15889 (org-get-property-block nil t))
15890 (throw 'skip nil))
15891 (goto-char (car range))
15892 (let ((begin (car range))
15893 (end (cdr range)))
15894 ;; Make sure that found property block is not located
15895 ;; before current point, as it would generate an infloop.
15896 ;; It can happen, for example, in the following
15897 ;; situation:
15899 ;; * Headline
15900 ;; :PROPERTIES:
15901 ;; ...
15902 ;; :END:
15903 ;; *************** Inlinetask
15904 ;; #+BEGIN_EXAMPLE
15905 ;; :PROPERTIES:
15906 ;; #+END_EXAMPLE
15908 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
15909 (while (< (point) end)
15910 (let ((p (progn (looking-at org-property-re)
15911 (org-match-string-no-properties 2))))
15912 ;; Only add true property name, not extension symbol.
15913 (add-to-list 'props
15914 (if (not (org-string-match-p "\\+\\'" p)) p
15915 (substring p 0 -1))))
15916 (forward-line))))
15917 (outline-next-heading)))
15918 (when columns
15919 (goto-char (point-min))
15920 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15921 (let ((element (org-element-at-point)))
15922 (when (memq (org-element-type element) '(keyword node-property))
15923 (let ((value (org-element-property :value element))
15924 (start 0))
15925 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
15926 (setq start (match-end 0))
15927 (let ((p (org-match-string-no-properties 1 value)))
15928 (unless (member-ignore-case
15929 p (cons "ITEM" org-special-properties))
15930 (add-to-list 'props p))))))))))
15931 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
15933 (defun org-property-values (key)
15934 "List all non-nil values of property KEY in current buffer."
15935 (org-with-wide-buffer
15936 (goto-char (point-min))
15937 (let ((case-fold-search t)
15938 (re (org-re-property key))
15939 values)
15940 (while (re-search-forward re nil t)
15941 (add-to-list 'values (org-entry-get (point) key)))
15942 values)))
15944 (defun org-insert-property-drawer ()
15945 "Insert a property drawer into the current entry."
15946 (org-with-wide-buffer
15947 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15948 (org-back-to-heading t)
15949 (org-with-limited-levels (org-back-to-heading t)))
15950 (forward-line)
15951 (when (org-looking-at-p org-planning-line-re) (forward-line))
15952 (unless (org-looking-at-p org-property-drawer-re)
15953 (let ((inhibit-read-only t))
15954 (unless (bolp) (insert "\n"))
15955 (let ((begin (point)))
15956 (insert ":PROPERTIES:\n:END:\n")
15957 (org-indent-region begin (point)))))))
15959 (defun org-insert-drawer (&optional arg drawer)
15960 "Insert a drawer at point.
15962 When optional argument ARG is non-nil, insert a property drawer.
15964 Optional argument DRAWER, when non-nil, is a string representing
15965 drawer's name. Otherwise, the user is prompted for a name.
15967 If a region is active, insert the drawer around that region
15968 instead.
15970 Point is left between drawer's boundaries."
15971 (interactive "P")
15972 (let* ((drawer (if arg "PROPERTIES"
15973 (or drawer (read-from-minibuffer "Drawer: ")))))
15974 (cond
15975 ;; With C-u, fall back on `org-insert-property-drawer'
15976 (arg (org-insert-property-drawer))
15977 ;; Check validity of suggested drawer's name.
15978 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15979 (user-error "Invalid drawer name"))
15980 ;; With an active region, insert a drawer at point.
15981 ((not (org-region-active-p))
15982 (progn
15983 (unless (bolp) (insert "\n"))
15984 (insert (format ":%s:\n\n:END:\n" drawer))
15985 (forward-line -2)))
15986 ;; Otherwise, insert the drawer at point
15988 (let ((rbeg (region-beginning))
15989 (rend (copy-marker (region-end))))
15990 (unwind-protect
15991 (progn
15992 (goto-char rbeg)
15993 (beginning-of-line)
15994 (when (save-excursion
15995 (re-search-forward org-outline-regexp-bol rend t))
15996 (user-error "Drawers cannot contain headlines"))
15997 ;; Position point at the beginning of the first
15998 ;; non-blank line in region. Insert drawer's opening
15999 ;; there, then indent it.
16000 (org-skip-whitespace)
16001 (beginning-of-line)
16002 (insert ":" drawer ":\n")
16003 (forward-line -1)
16004 (indent-for-tab-command)
16005 ;; Move point to the beginning of the first blank line
16006 ;; after the last non-blank line in region. Insert
16007 ;; drawer's closing, then indent it.
16008 (goto-char rend)
16009 (skip-chars-backward " \r\t\n")
16010 (insert "\n:END:")
16011 (deactivate-mark t)
16012 (indent-for-tab-command)
16013 (unless (eolp) (insert "\n")))
16014 ;; Clear marker, whatever the outcome of insertion is.
16015 (set-marker rend nil)))))))
16017 (defvar org-property-set-functions-alist nil
16018 "Property set function alist.
16019 Each entry should have the following format:
16021 (PROPERTY . READ-FUNCTION)
16023 The read function will be called with the same argument as
16024 `org-completing-read'.")
16026 (defun org-set-property-function (property)
16027 "Get the function that should be used to set PROPERTY.
16028 This is computed according to `org-property-set-functions-alist'."
16029 (or (cdr (assoc property org-property-set-functions-alist))
16030 'org-completing-read))
16032 (defun org-read-property-value (property)
16033 "Read PROPERTY value from user."
16034 (let* ((completion-ignore-case t)
16035 (allowed (org-property-get-allowed-values nil property 'table))
16036 (cur (org-entry-get nil property))
16037 (prompt (concat property " value"
16038 (if (and cur (string-match "\\S-" cur))
16039 (concat " [" cur "]") "") ": "))
16040 (set-function (org-set-property-function property))
16041 (val (if allowed
16042 (funcall set-function prompt allowed nil
16043 (not (get-text-property 0 'org-unrestricted
16044 (caar allowed))))
16045 (let (org-completion-use-ido org-completion-use-iswitchb)
16046 (funcall set-function prompt
16047 (mapcar 'list (org-property-values property))
16048 nil nil "" nil cur)))))
16049 (org-trim val)))
16051 (defvar org-last-set-property nil)
16052 (defvar org-last-set-property-value nil)
16053 (defun org-read-property-name ()
16054 "Read a property name."
16055 (let* ((completion-ignore-case t)
16056 (keys (org-buffer-property-keys nil t t))
16057 (default-prop (or (save-excursion
16058 (save-match-data
16059 (beginning-of-line)
16060 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16061 (null (string= (match-string 1) "END"))
16062 (match-string 1))))
16063 org-last-set-property))
16064 (property (org-icompleting-read
16065 (concat "Property"
16066 (if default-prop (concat " [" default-prop "]") "")
16067 ": ")
16068 (mapcar 'list keys)
16069 nil nil nil nil
16070 default-prop)))
16071 (if (member property keys)
16072 property
16073 (or (cdr (assoc (downcase property)
16074 (mapcar (lambda (x) (cons (downcase x) x))
16075 keys)))
16076 property))))
16078 (defun org-set-property-and-value (use-last)
16079 "Allow to set [PROPERTY]: [value] direction from prompt.
16080 When use-default, don't even ask, just use the last
16081 \"[PROPERTY]: [value]\" string from the history."
16082 (interactive "P")
16083 (let* ((completion-ignore-case t)
16084 (pv (or (and use-last org-last-set-property-value)
16085 (org-completing-read
16086 "Enter a \"[Property]: [value]\" pair: "
16087 nil nil nil nil nil
16088 org-last-set-property-value)))
16089 prop val)
16090 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16091 (setq prop (match-string 1 pv)
16092 val (match-string 2 pv))
16093 (org-set-property prop val))))
16095 (defun org-set-property (property value)
16096 "In the current entry, set PROPERTY to VALUE.
16097 When called interactively, this will prompt for a property name, offering
16098 completion on existing and default properties. And then it will prompt
16099 for a value, offering completion either on allowed values (via an inherited
16100 xxx_ALL property) or on existing values in other instances of this property
16101 in the current file."
16102 (interactive (list nil nil))
16103 (let* ((property (or property (org-read-property-name)))
16104 (value (or value (org-read-property-value property)))
16105 (fn (cdr (assoc property org-properties-postprocess-alist))))
16106 (setq org-last-set-property property)
16107 (setq org-last-set-property-value (concat property ": " value))
16108 ;; Possibly postprocess the inserted value:
16109 (when fn (setq value (funcall fn value)))
16110 (unless (equal (org-entry-get nil property) value)
16111 (org-entry-put nil property value))))
16113 (defun org-delete-property (property)
16114 "In the current entry, delete PROPERTY."
16115 (interactive
16116 (let* ((completion-ignore-case t)
16117 (cat (org-entry-get (point) "CATEGORY"))
16118 (props0 (org-entry-properties nil 'standard))
16119 (props (if cat props0
16120 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16121 (prop (if (< 1 (length props))
16122 (org-icompleting-read "Property: " props nil t)
16123 (caar props))))
16124 (list prop)))
16125 (if (not property)
16126 (message "No property to delete in this entry")
16127 (org-entry-delete nil property)
16128 (message "Property \"%s\" deleted" property)))
16130 (defun org-delete-property-globally (property)
16131 "Remove PROPERTY globally, from all entries."
16132 (interactive
16133 (let* ((completion-ignore-case t)
16134 (prop (org-icompleting-read
16135 "Globally remove property: "
16136 (mapcar 'list (org-buffer-property-keys)))))
16137 (list prop)))
16138 (save-excursion
16139 (save-restriction
16140 (widen)
16141 (goto-char (point-min))
16142 (let ((cnt 0))
16143 (while (re-search-forward
16144 (org-re-property property)
16145 nil t)
16146 (setq cnt (1+ cnt))
16147 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16148 (message "Property \"%s\" removed from %d entries" property cnt)))))
16150 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16152 (defun org-compute-property-at-point ()
16153 "Compute the property at point.
16154 This looks for an enclosing column format, extracts the operator and
16155 then applies it to the property in the column format's scope."
16156 (interactive)
16157 (unless (org-at-property-p)
16158 (user-error "Not at a property"))
16159 (let ((prop (org-match-string-no-properties 2)))
16160 (org-columns-get-format-and-top-level)
16161 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16162 (user-error "No operator defined for property %s" prop))
16163 (org-columns-compute prop)))
16165 (defvar org-property-allowed-value-functions nil
16166 "Hook for functions supplying allowed values for a specific property.
16167 The functions must take a single argument, the name of the property, and
16168 return a flat list of allowed values. If \":ETC\" is one of
16169 the values, this means that these values are intended as defaults for
16170 completion, but that other values should be allowed too.
16171 The functions must return nil if they are not responsible for this
16172 property.")
16174 (defun org-property-get-allowed-values (pom property &optional table)
16175 "Get allowed values for the property PROPERTY.
16176 When TABLE is non-nil, return an alist that can directly be used for
16177 completion."
16178 (let (vals)
16179 (cond
16180 ((equal property "TODO")
16181 (setq vals (org-with-point-at pom
16182 (append org-todo-keywords-1 '("")))))
16183 ((equal property "PRIORITY")
16184 (let ((n org-lowest-priority))
16185 (while (>= n org-highest-priority)
16186 (push (char-to-string n) vals)
16187 (setq n (1- n)))))
16188 ((member property org-special-properties))
16189 ((setq vals (run-hook-with-args-until-success
16190 'org-property-allowed-value-functions property)))
16192 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16193 (when (and vals (string-match "\\S-" vals))
16194 (setq vals (car (read-from-string (concat "(" vals ")"))))
16195 (setq vals (mapcar (lambda (x)
16196 (cond ((stringp x) x)
16197 ((numberp x) (number-to-string x))
16198 ((symbolp x) (symbol-name x))
16199 (t "???")))
16200 vals)))))
16201 (when (member ":ETC" vals)
16202 (setq vals (remove ":ETC" vals))
16203 (org-add-props (car vals) '(org-unrestricted t)))
16204 (if table (mapcar 'list vals) vals)))
16206 (defun org-property-previous-allowed-value (&optional previous)
16207 "Switch to the next allowed value for this property."
16208 (interactive)
16209 (org-property-next-allowed-value t))
16211 (defun org-property-next-allowed-value (&optional previous)
16212 "Switch to the next allowed value for this property."
16213 (interactive)
16214 (unless (org-at-property-p)
16215 (user-error "Not at a property"))
16216 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16217 (key (match-string 2))
16218 (value (match-string 3))
16219 (allowed (or (org-property-get-allowed-values (point) key)
16220 (and (member value '("[ ]" "[-]" "[X]"))
16221 '("[ ]" "[X]"))))
16222 (heading (save-match-data (nth 4 (org-heading-components))))
16223 nval)
16224 (unless allowed
16225 (user-error "Allowed values for this property have not been defined"))
16226 (if previous (setq allowed (reverse allowed)))
16227 (if (member value allowed)
16228 (setq nval (car (cdr (member value allowed)))))
16229 (setq nval (or nval (car allowed)))
16230 (if (equal nval value)
16231 (user-error "Only one allowed value for this property"))
16232 (org-at-property-p)
16233 (replace-match (concat " :" key ": " nval) t t)
16234 (org-indent-line)
16235 (beginning-of-line 1)
16236 (skip-chars-forward " \t")
16237 (when (equal prop org-effort-property)
16238 (org-refresh-property
16239 '((effort . identity)
16240 (effort-minutes . org-duration-string-to-minutes))
16241 nval)
16242 (when (string= org-clock-current-task heading)
16243 (setq org-clock-effort nval)
16244 (org-clock-update-mode-line)))
16245 (run-hook-with-args 'org-property-changed-functions key nval)))
16247 (defun org-find-olp (path &optional this-buffer)
16248 "Return a marker pointing to the entry at outline path OLP.
16249 If anything goes wrong, throw an error.
16250 You can wrap this call to catch the error like this:
16252 (condition-case msg
16253 (org-mobile-locate-entry (match-string 4))
16254 (error (nth 1 msg)))
16256 The return value will then be either a string with the error message,
16257 or a marker if everything is OK.
16259 If THIS-BUFFER is set, the outline path does not contain a file,
16260 only headings."
16261 (let* ((file (if this-buffer buffer-file-name (pop path)))
16262 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16263 (level 1)
16264 (lmin 1)
16265 (lmax 1)
16266 limit re end found pos heading cnt flevel)
16267 (unless buffer (error "File not found :%s" file))
16268 (with-current-buffer buffer
16269 (save-excursion
16270 (save-restriction
16271 (widen)
16272 (setq limit (point-max))
16273 (goto-char (point-min))
16274 (while (setq heading (pop path))
16275 (setq re (format org-complex-heading-regexp-format
16276 (regexp-quote heading)))
16277 (setq cnt 0 pos (point))
16278 (while (re-search-forward re end t)
16279 (setq level (- (match-end 1) (match-beginning 1)))
16280 (if (and (>= level lmin) (<= level lmax))
16281 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16282 (when (= cnt 0) (error "Heading not found on level %d: %s"
16283 lmax heading))
16284 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16285 lmax heading))
16286 (goto-char found)
16287 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16288 (setq end (save-excursion (org-end-of-subtree t t))))
16289 (when (org-at-heading-p)
16290 (point-marker)))))))
16292 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16293 "Find node HEADING in BUFFER.
16294 Return a marker to the heading if it was found, or nil if not.
16295 If POS-ONLY is set, return just the position instead of a marker.
16297 The heading text must match exact, but it may have a TODO keyword,
16298 a priority cookie and tags in the standard locations."
16299 (with-current-buffer (or buffer (current-buffer))
16300 (save-excursion
16301 (save-restriction
16302 (widen)
16303 (goto-char (point-min))
16304 (let (case-fold-search)
16305 (if (re-search-forward
16306 (format org-complex-heading-regexp-format
16307 (regexp-quote heading)) nil t)
16308 (if pos-only
16309 (match-beginning 0)
16310 (move-marker (make-marker) (match-beginning 0)))))))))
16312 (defun org-find-exact-heading-in-directory (heading &optional dir)
16313 "Find Org node headline HEADING in all .org files in directory DIR.
16314 When the target headline is found, return a marker to this location."
16315 (let ((files (directory-files (or dir default-directory)
16316 t "\\`[^.#].*\\.org\\'"))
16317 file visiting m buffer)
16318 (catch 'found
16319 (while (setq file (pop files))
16320 (message "trying %s" file)
16321 (setq visiting (org-find-base-buffer-visiting file))
16322 (setq buffer (or visiting (find-file-noselect file)))
16323 (setq m (org-find-exact-headline-in-buffer
16324 heading buffer))
16325 (when (and (not m) (not visiting)) (kill-buffer buffer))
16326 (and m (throw 'found m))))))
16328 (defun org-find-entry-with-id (ident)
16329 "Locate the entry that contains the ID property with exact value IDENT.
16330 IDENT can be a string, a symbol or a number, this function will search for
16331 the string representation of it.
16332 Return the position where this entry starts, or nil if there is no such entry."
16333 (interactive "sID: ")
16334 (let ((id (cond
16335 ((stringp ident) ident)
16336 ((symbol-name ident) (symbol-name ident))
16337 ((numberp ident) (number-to-string ident))
16338 (t (error "IDENT %s must be a string, symbol or number" ident))))
16339 (case-fold-search nil))
16340 (save-excursion
16341 (save-restriction
16342 (widen)
16343 (goto-char (point-min))
16344 (when (re-search-forward
16345 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16346 nil t)
16347 (org-back-to-heading t)
16348 (point))))))
16350 ;;;; Timestamps
16352 (defvar org-last-changed-timestamp nil)
16353 (defvar org-last-inserted-timestamp nil
16354 "The last time stamp inserted with `org-insert-time-stamp'.")
16355 (defvar org-ts-what) ; dynamically scoped parameter
16357 (defun org-time-stamp (arg &optional inactive)
16358 "Prompt for a date/time and insert a time stamp.
16359 If the user specifies a time like HH:MM or if this command is
16360 called with at least one prefix argument, the time stamp contains
16361 the date and the time. Otherwise, only the date is be included.
16363 All parts of a date not specified by the user is filled in from
16364 the current date/time. So if you just press return without
16365 typing anything, the time stamp will represent the current
16366 date/time.
16368 If there is already a timestamp at the cursor, it will be
16369 modified.
16371 With two universal prefix arguments, insert an active timestamp
16372 with the current time without prompting the user.
16374 When called from lisp, the timestamp is inactive if INACTIVE is
16375 non-nil."
16376 (interactive "P")
16377 (let* ((ts nil)
16378 (default-time
16379 ;; Default time is either today, or, when entering a range,
16380 ;; the range start.
16381 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16382 (save-excursion
16383 (re-search-backward
16384 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16385 (- (point) 20) t)))
16386 (apply 'encode-time (org-parse-time-string (match-string 1)))
16387 (current-time)))
16388 (default-input (and ts (org-get-compact-tod ts)))
16389 (repeater (save-excursion
16390 (save-match-data
16391 (beginning-of-line)
16392 (when (re-search-forward
16393 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16394 (save-excursion (progn (end-of-line) (point))) t)
16395 (match-string 0)))))
16396 org-time-was-given org-end-time-was-given time)
16397 (cond
16398 ((and (org-at-timestamp-p t)
16399 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16400 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16401 (insert "--")
16402 (setq time (let ((this-command this-command))
16403 (org-read-date arg 'totime nil nil
16404 default-time default-input inactive)))
16405 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16406 ((org-at-timestamp-p t)
16407 (setq time (let ((this-command this-command))
16408 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16409 (when (org-at-timestamp-p t) ; just to get the match data
16410 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16411 (replace-match "")
16412 (setq org-last-changed-timestamp
16413 (org-insert-time-stamp
16414 time (or org-time-was-given arg)
16415 inactive nil nil (list org-end-time-was-given)))
16416 (when repeater (goto-char (1- (point))) (insert " " repeater)
16417 (setq org-last-changed-timestamp
16418 (concat (substring org-last-inserted-timestamp 0 -1)
16419 " " repeater ">"))))
16420 (message "Timestamp updated"))
16421 ((equal arg '(16))
16422 (org-insert-time-stamp (current-time) t inactive))
16424 (setq time (let ((this-command this-command))
16425 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16426 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16427 nil nil (list org-end-time-was-given))))))
16429 ;; FIXME: can we use this for something else, like computing time differences?
16430 (defun org-get-compact-tod (s)
16431 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16432 (let* ((t1 (match-string 1 s))
16433 (h1 (string-to-number (match-string 2 s)))
16434 (m1 (string-to-number (match-string 3 s)))
16435 (t2 (and (match-end 4) (match-string 5 s)))
16436 (h2 (and t2 (string-to-number (match-string 6 s))))
16437 (m2 (and t2 (string-to-number (match-string 7 s))))
16438 dh dm)
16439 (if (not t2)
16441 (setq dh (- h2 h1) dm (- m2 m1))
16442 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16443 (concat t1 "+" (number-to-string dh)
16444 (and (/= 0 dm) (format ":%02d" dm)))))))
16446 (defun org-time-stamp-inactive (&optional arg)
16447 "Insert an inactive time stamp.
16448 An inactive time stamp is enclosed in square brackets instead of angle
16449 brackets. It is inactive in the sense that it does not trigger agenda entries,
16450 does not link to the calendar and cannot be changed with the S-cursor keys.
16451 So these are more for recording a certain time/date."
16452 (interactive "P")
16453 (org-time-stamp arg 'inactive))
16455 (defvar org-date-ovl (make-overlay 1 1))
16456 (overlay-put org-date-ovl 'face 'org-date-selected)
16457 (org-detach-overlay org-date-ovl)
16459 (defvar org-ans1) ; dynamically scoped parameter
16460 (defvar org-ans2) ; dynamically scoped parameter
16462 (defvar org-plain-time-of-day-regexp) ; defined below
16464 (defvar org-overriding-default-time nil) ; dynamically scoped
16465 (defvar org-read-date-overlay nil)
16466 (defvar org-dcst nil) ; dynamically scoped
16467 (defvar org-read-date-history nil)
16468 (defvar org-read-date-final-answer nil)
16469 (defvar org-read-date-analyze-futurep nil)
16470 (defvar org-read-date-analyze-forced-year nil)
16471 (defvar org-read-date-inactive)
16473 (defvar org-read-date-minibuffer-local-map
16474 (let* ((org-replace-disputed-keys nil)
16475 (map (make-sparse-keymap)))
16476 (set-keymap-parent map minibuffer-local-map)
16477 (org-defkey map (kbd ".")
16478 (lambda () (interactive)
16479 ;; Are we at the beginning of the prompt?
16480 (if (looking-back "^[^:]+: ")
16481 (org-eval-in-calendar '(calendar-goto-today))
16482 (insert "."))))
16483 (org-defkey map (kbd "C-.")
16484 (lambda () (interactive)
16485 (org-eval-in-calendar '(calendar-goto-today))))
16486 (org-defkey map [(meta shift left)]
16487 (lambda () (interactive)
16488 (org-eval-in-calendar '(calendar-backward-month 1))))
16489 (org-defkey map [(meta shift right)]
16490 (lambda () (interactive)
16491 (org-eval-in-calendar '(calendar-forward-month 1))))
16492 (org-defkey map [(meta shift up)]
16493 (lambda () (interactive)
16494 (org-eval-in-calendar '(calendar-backward-year 1))))
16495 (org-defkey map [(meta shift down)]
16496 (lambda () (interactive)
16497 (org-eval-in-calendar '(calendar-forward-year 1))))
16498 (org-defkey map [?\e (shift left)]
16499 (lambda () (interactive)
16500 (org-eval-in-calendar '(calendar-backward-month 1))))
16501 (org-defkey map [?\e (shift right)]
16502 (lambda () (interactive)
16503 (org-eval-in-calendar '(calendar-forward-month 1))))
16504 (org-defkey map [?\e (shift up)]
16505 (lambda () (interactive)
16506 (org-eval-in-calendar '(calendar-backward-year 1))))
16507 (org-defkey map [?\e (shift down)]
16508 (lambda () (interactive)
16509 (org-eval-in-calendar '(calendar-forward-year 1))))
16510 (org-defkey map [(shift up)]
16511 (lambda () (interactive)
16512 (org-eval-in-calendar '(calendar-backward-week 1))))
16513 (org-defkey map [(shift down)]
16514 (lambda () (interactive)
16515 (org-eval-in-calendar '(calendar-forward-week 1))))
16516 (org-defkey map [(shift left)]
16517 (lambda () (interactive)
16518 (org-eval-in-calendar '(calendar-backward-day 1))))
16519 (org-defkey map [(shift right)]
16520 (lambda () (interactive)
16521 (org-eval-in-calendar '(calendar-forward-day 1))))
16522 (org-defkey map "!"
16523 (lambda () (interactive)
16524 (org-eval-in-calendar '(diary-view-entries))
16525 (message "")))
16526 (org-defkey map ">"
16527 (lambda () (interactive)
16528 (org-eval-in-calendar '(calendar-scroll-left 1))))
16529 (org-defkey map "<"
16530 (lambda () (interactive)
16531 (org-eval-in-calendar '(calendar-scroll-right 1))))
16532 (org-defkey map "\C-v"
16533 (lambda () (interactive)
16534 (org-eval-in-calendar
16535 '(calendar-scroll-left-three-months 1))))
16536 (org-defkey map "\M-v"
16537 (lambda () (interactive)
16538 (org-eval-in-calendar
16539 '(calendar-scroll-right-three-months 1))))
16540 map)
16541 "Keymap for minibuffer commands when using `org-read-date'.")
16543 (defvar org-def)
16544 (defvar org-defdecode)
16545 (defvar org-with-time)
16547 (defun org-read-date (&optional org-with-time to-time from-string prompt
16548 default-time default-input inactive)
16549 "Read a date, possibly a time, and make things smooth for the user.
16550 The prompt will suggest to enter an ISO date, but you can also enter anything
16551 which will at least partially be understood by `parse-time-string'.
16552 Unrecognized parts of the date will default to the current day, month, year,
16553 hour and minute. If this command is called to replace a timestamp at point,
16554 or to enter the second timestamp of a range, the default time is taken
16555 from the existing stamp. Furthermore, the command prefers the future,
16556 so if you are giving a date where the year is not given, and the day-month
16557 combination is already past in the current year, it will assume you
16558 mean next year. For details, see the manual. A few examples:
16560 3-2-5 --> 2003-02-05
16561 feb 15 --> currentyear-02-15
16562 2/15 --> currentyear-02-15
16563 sep 12 9 --> 2009-09-12
16564 12:45 --> today 12:45
16565 22 sept 0:34 --> currentyear-09-22 0:34
16566 12 --> currentyear-currentmonth-12
16567 Fri --> nearest Friday after today
16568 -Tue --> last Tuesday
16569 etc.
16571 Furthermore you can specify a relative date by giving, as the *first* thing
16572 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16573 change in days weeks, months, years.
16574 With a single plus or minus, the date is relative to today. With a double
16575 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16576 +4d --> four days from today
16577 +4 --> same as above
16578 +2w --> two weeks from today
16579 ++5 --> five days from default date
16581 The function understands only English month and weekday abbreviations.
16583 While prompting, a calendar is popped up - you can also select the
16584 date with the mouse (button 1). The calendar shows a period of three
16585 months. To scroll it to other months, use the keys `>' and `<'.
16586 If you don't like the calendar, turn it off with
16587 \(setq org-read-date-popup-calendar nil)
16589 With optional argument TO-TIME, the date will immediately be converted
16590 to an internal time.
16591 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16592 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16593 still enter a time, and this function will inform the calling routine
16594 about this change. The calling routine may then choose to change the
16595 format used to insert the time stamp into the buffer to include the time.
16596 With optional argument FROM-STRING, read from this string instead from
16597 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16598 the time/date that is used for everything that is not specified by the
16599 user."
16600 (require 'parse-time)
16601 (let* ((org-time-stamp-rounding-minutes
16602 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16603 (org-dcst org-display-custom-times)
16604 (ct (org-current-time))
16605 (org-def (or org-overriding-default-time default-time ct))
16606 (org-defdecode (decode-time org-def))
16607 (dummy (progn
16608 (when (< (nth 2 org-defdecode) org-extend-today-until)
16609 (setcar (nthcdr 2 org-defdecode) -1)
16610 (setcar (nthcdr 1 org-defdecode) 59)
16611 (setq org-def (apply 'encode-time org-defdecode)
16612 org-defdecode (decode-time org-def)))))
16613 (mouse-autoselect-window nil) ; Don't let the mouse jump
16614 (calendar-frame-setup nil)
16615 (calendar-setup nil)
16616 (calendar-move-hook nil)
16617 (calendar-view-diary-initially-flag nil)
16618 (calendar-view-holidays-initially-flag nil)
16619 (timestr (format-time-string
16620 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16621 (prompt (concat (if prompt (concat prompt " ") "")
16622 (format "Date+time [%s]: " timestr)))
16623 ans (org-ans0 "") org-ans1 org-ans2 final)
16625 (cond
16626 (from-string (setq ans from-string))
16627 (org-read-date-popup-calendar
16628 (save-excursion
16629 (save-window-excursion
16630 (calendar)
16631 (org-eval-in-calendar '(setq cursor-type nil) t)
16632 (unwind-protect
16633 (progn
16634 (calendar-forward-day (- (time-to-days org-def)
16635 (calendar-absolute-from-gregorian
16636 (calendar-current-date))))
16637 (org-eval-in-calendar nil t)
16638 (let* ((old-map (current-local-map))
16639 (map (copy-keymap calendar-mode-map))
16640 (minibuffer-local-map
16641 (copy-keymap org-read-date-minibuffer-local-map)))
16642 (org-defkey map (kbd "RET") 'org-calendar-select)
16643 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16644 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16645 (unwind-protect
16646 (progn
16647 (use-local-map map)
16648 (setq org-read-date-inactive inactive)
16649 (add-hook 'post-command-hook 'org-read-date-display)
16650 (setq org-ans0 (read-string prompt default-input
16651 'org-read-date-history nil))
16652 ;; org-ans0: from prompt
16653 ;; org-ans1: from mouse click
16654 ;; org-ans2: from calendar motion
16655 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16656 (remove-hook 'post-command-hook 'org-read-date-display)
16657 (use-local-map old-map)
16658 (when org-read-date-overlay
16659 (delete-overlay org-read-date-overlay)
16660 (setq org-read-date-overlay nil)))))
16661 (bury-buffer "*Calendar*")))))
16663 (t ; Naked prompt only
16664 (unwind-protect
16665 (setq ans (read-string prompt default-input
16666 'org-read-date-history timestr))
16667 (when org-read-date-overlay
16668 (delete-overlay org-read-date-overlay)
16669 (setq org-read-date-overlay nil)))))
16671 (setq final (org-read-date-analyze ans org-def org-defdecode))
16673 (when org-read-date-analyze-forced-year
16674 (message "Year was forced into %s"
16675 (if org-read-date-force-compatible-dates
16676 "compatible range (1970-2037)"
16677 "range representable on this machine"))
16678 (ding))
16680 ;; One round trip to get rid of 34th of August and stuff like that....
16681 (setq final (decode-time (apply 'encode-time final)))
16683 (setq org-read-date-final-answer ans)
16685 (if to-time
16686 (apply 'encode-time final)
16687 (if (and (boundp 'org-time-was-given) org-time-was-given)
16688 (format "%04d-%02d-%02d %02d:%02d"
16689 (nth 5 final) (nth 4 final) (nth 3 final)
16690 (nth 2 final) (nth 1 final))
16691 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16693 (defun org-read-date-display ()
16694 "Display the current date prompt interpretation in the minibuffer."
16695 (when org-read-date-display-live
16696 (when org-read-date-overlay
16697 (delete-overlay org-read-date-overlay))
16698 (when (minibufferp (current-buffer))
16699 (save-excursion
16700 (end-of-line 1)
16701 (while (not (equal (buffer-substring
16702 (max (point-min) (- (point) 4)) (point))
16703 " "))
16704 (insert " ")))
16705 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16706 " " (or org-ans1 org-ans2)))
16707 (org-end-time-was-given nil)
16708 (f (org-read-date-analyze ans org-def org-defdecode))
16709 (fmts (if org-dcst
16710 org-time-stamp-custom-formats
16711 org-time-stamp-formats))
16712 (fmt (if (or org-with-time
16713 (and (boundp 'org-time-was-given) org-time-was-given))
16714 (cdr fmts)
16715 (car fmts)))
16716 (txt (format-time-string fmt (apply 'encode-time f)))
16717 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16718 (txt (concat "=> " txt)))
16719 (when (and org-end-time-was-given
16720 (string-match org-plain-time-of-day-regexp txt))
16721 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16722 org-end-time-was-given
16723 (substring txt (match-end 0)))))
16724 (when org-read-date-analyze-futurep
16725 (setq txt (concat txt " (=>F)")))
16726 (setq org-read-date-overlay
16727 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16728 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16730 (defun org-read-date-analyze (ans org-def org-defdecode)
16731 "Analyze the combined answer of the date prompt."
16732 ;; FIXME: cleanup and comment
16733 (let ((nowdecode (decode-time (current-time)))
16734 delta deltan deltaw deltadef year month day
16735 hour minute second wday pm h2 m2 tl wday1
16736 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16737 (setq org-read-date-analyze-futurep nil
16738 org-read-date-analyze-forced-year nil)
16739 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16740 (setq ans "+0"))
16742 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16743 (setq ans (replace-match "" t t ans)
16744 deltan (car delta)
16745 deltaw (nth 1 delta)
16746 deltadef (nth 2 delta)))
16748 ;; Check if there is an iso week date in there. If yes, store the
16749 ;; info and postpone interpreting it until the rest of the parsing
16750 ;; is done.
16751 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16752 (setq iso-year (if (match-end 1)
16753 (org-small-year-to-year
16754 (string-to-number (match-string 1 ans))))
16755 iso-weekday (if (match-end 3)
16756 (string-to-number (match-string 3 ans)))
16757 iso-week (string-to-number (match-string 2 ans)))
16758 (setq ans (replace-match "" t t ans)))
16760 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16761 (when (string-match
16762 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16763 (setq year (if (match-end 2)
16764 (string-to-number (match-string 2 ans))
16765 (progn (setq kill-year t)
16766 (string-to-number (format-time-string "%Y"))))
16767 month (string-to-number (match-string 3 ans))
16768 day (string-to-number (match-string 4 ans)))
16769 (if (< year 100) (setq year (+ 2000 year)))
16770 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16771 t nil ans)))
16773 ;; Help matching dotted european dates
16774 (when (string-match
16775 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16776 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16777 (setq kill-year t)
16778 (string-to-number (format-time-string "%Y")))
16779 day (string-to-number (match-string 1 ans))
16780 month (string-to-number (match-string 2 ans))
16781 ans (replace-match (format "%04d-%02d-%02d" year month day)
16782 t nil ans)))
16784 ;; Help matching american dates, like 5/30 or 5/30/7
16785 (when (string-match
16786 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16787 (setq year (if (match-end 4)
16788 (string-to-number (match-string 4 ans))
16789 (progn (setq kill-year t)
16790 (string-to-number (format-time-string "%Y"))))
16791 month (string-to-number (match-string 1 ans))
16792 day (string-to-number (match-string 2 ans)))
16793 (if (< year 100) (setq year (+ 2000 year)))
16794 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16795 t nil ans)))
16796 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16797 ;; If there is a time with am/pm, and *no* time without it, we convert
16798 ;; so that matching will be successful.
16799 (loop for i from 1 to 2 do ; twice, for end time as well
16800 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16801 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16802 (setq hour (string-to-number (match-string 1 ans))
16803 minute (if (match-end 3)
16804 (string-to-number (match-string 3 ans))
16806 pm (equal ?p
16807 (string-to-char (downcase (match-string 4 ans)))))
16808 (if (and (= hour 12) (not pm))
16809 (setq hour 0)
16810 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16811 (setq ans (replace-match (format "%02d:%02d" hour minute)
16812 t t ans))))
16814 ;; Check if a time range is given as a duration
16815 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16816 (setq hour (string-to-number (match-string 1 ans))
16817 h2 (+ hour (string-to-number (match-string 3 ans)))
16818 minute (string-to-number (match-string 2 ans))
16819 m2 (+ minute (if (match-end 5) (string-to-number
16820 (match-string 5 ans))0)))
16821 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16822 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16823 t t ans)))
16825 ;; Check if there is a time range
16826 (when (boundp 'org-end-time-was-given)
16827 (setq org-time-was-given nil)
16828 (when (and (string-match org-plain-time-of-day-regexp ans)
16829 (match-end 8))
16830 (setq org-end-time-was-given (match-string 8 ans))
16831 (setq ans (concat (substring ans 0 (match-beginning 7))
16832 (substring ans (match-end 7))))))
16834 (setq tl (parse-time-string ans)
16835 day (or (nth 3 tl) (nth 3 org-defdecode))
16836 month (or (nth 4 tl)
16837 (if (and org-read-date-prefer-future
16838 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16839 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16840 (nth 4 org-defdecode)))
16841 year (or (and (not kill-year) (nth 5 tl))
16842 (if (and org-read-date-prefer-future
16843 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16844 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16845 (nth 5 org-defdecode)))
16846 hour (or (nth 2 tl) (nth 2 org-defdecode))
16847 minute (or (nth 1 tl) (nth 1 org-defdecode))
16848 second (or (nth 0 tl) 0)
16849 wday (nth 6 tl))
16851 (when (and (eq org-read-date-prefer-future 'time)
16852 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16853 (equal day (nth 3 nowdecode))
16854 (equal month (nth 4 nowdecode))
16855 (equal year (nth 5 nowdecode))
16856 (nth 2 tl)
16857 (or (< (nth 2 tl) (nth 2 nowdecode))
16858 (and (= (nth 2 tl) (nth 2 nowdecode))
16859 (nth 1 tl)
16860 (< (nth 1 tl) (nth 1 nowdecode)))))
16861 (setq day (1+ day)
16862 futurep t))
16864 ;; Special date definitions below
16865 (cond
16866 (iso-week
16867 ;; There was an iso week
16868 (require 'cal-iso)
16869 (setq futurep nil)
16870 (setq year (or iso-year year)
16871 day (or iso-weekday wday 1)
16872 wday nil ; to make sure that the trigger below does not match
16873 iso-date (calendar-gregorian-from-absolute
16874 (calendar-absolute-from-iso
16875 (list iso-week day year))))
16876 ; FIXME: Should we also push ISO weeks into the future?
16877 ; (when (and org-read-date-prefer-future
16878 ; (not iso-year)
16879 ; (< (calendar-absolute-from-gregorian iso-date)
16880 ; (time-to-days (current-time))))
16881 ; (setq year (1+ year)
16882 ; iso-date (calendar-gregorian-from-absolute
16883 ; (calendar-absolute-from-iso
16884 ; (list iso-week day year)))))
16885 (setq month (car iso-date)
16886 year (nth 2 iso-date)
16887 day (nth 1 iso-date)))
16888 (deltan
16889 (setq futurep nil)
16890 (unless deltadef
16891 (let ((now (decode-time (current-time))))
16892 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16893 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16894 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16895 ((equal deltaw "m") (setq month (+ month deltan)))
16896 ((equal deltaw "y") (setq year (+ year deltan)))))
16897 ((and wday (not (nth 3 tl)))
16898 ;; Weekday was given, but no day, so pick that day in the week
16899 ;; on or after the derived date.
16900 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16901 (unless (equal wday wday1)
16902 (setq day (+ day (% (- wday wday1 -7) 7))))))
16903 (if (and (boundp 'org-time-was-given)
16904 (nth 2 tl))
16905 (setq org-time-was-given t))
16906 (if (< year 100) (setq year (+ 2000 year)))
16907 ;; Check of the date is representable
16908 (if org-read-date-force-compatible-dates
16909 (progn
16910 (if (< year 1970)
16911 (setq year 1970 org-read-date-analyze-forced-year t))
16912 (if (> year 2037)
16913 (setq year 2037 org-read-date-analyze-forced-year t)))
16914 (condition-case nil
16915 (ignore (encode-time second minute hour day month year))
16916 (error
16917 (setq year (nth 5 org-defdecode))
16918 (setq org-read-date-analyze-forced-year t))))
16919 (setq org-read-date-analyze-futurep futurep)
16920 (list second minute hour day month year)))
16922 (defvar parse-time-weekdays)
16923 (defun org-read-date-get-relative (s today default)
16924 "Check string S for special relative date string.
16925 TODAY and DEFAULT are internal times, for today and for a default.
16926 Return shift list (N what def-flag)
16927 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16928 N is the number of WHATs to shift.
16929 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16930 the DEFAULT date rather than TODAY."
16931 (require 'parse-time)
16932 (when (and
16933 (string-match
16934 (concat
16935 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16936 "\\([0-9]+\\)?"
16937 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16938 "\\([ \t]\\|$\\)") s)
16939 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16940 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16941 (string-to-char (substring (match-string 1 s) -1))
16942 ?+))
16943 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16944 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16945 (what (if (match-end 3) (match-string 3 s) "d"))
16946 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16947 (date (if rel default today))
16948 (wday (nth 6 (decode-time date)))
16949 delta)
16950 (if wday1
16951 (progn
16952 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16953 (if (= delta 0) (setq delta 7))
16954 (if (= dir ?-)
16955 (progn
16956 (setq delta (- delta 7))
16957 (if (= delta 0) (setq delta -7))))
16958 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16959 (list delta "d" rel))
16960 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16962 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16963 "Turn a user-specified date into the internal representation.
16964 The internal representation needed by the calendar is (month day year).
16965 This is a wrapper to handle the brain-dead convention in calendar that
16966 user function argument order change dependent on argument order."
16967 (if (boundp 'calendar-date-style)
16968 (cond
16969 ((eq calendar-date-style 'american)
16970 (list arg1 arg2 arg3))
16971 ((eq calendar-date-style 'european)
16972 (list arg2 arg1 arg3))
16973 ((eq calendar-date-style 'iso)
16974 (list arg2 arg3 arg1)))
16975 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16976 (if (org-bound-and-true-p european-calendar-style)
16977 (list arg2 arg1 arg3)
16978 (list arg1 arg2 arg3)))))
16980 (defun org-eval-in-calendar (form &optional keepdate)
16981 "Eval FORM in the calendar window and return to current window.
16982 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16983 otherwise stick to the current value of `org-ans2'."
16984 (let ((sf (selected-frame))
16985 (sw (selected-window)))
16986 (select-window (get-buffer-window "*Calendar*" t))
16987 (eval form)
16988 (when (and (not keepdate) (calendar-cursor-to-date))
16989 (let* ((date (calendar-cursor-to-date))
16990 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16991 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16992 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16993 (select-window sw)
16994 (org-select-frame-set-input-focus sf)))
16996 (defun org-calendar-select ()
16997 "Return to `org-read-date' with the date currently selected.
16998 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16999 (interactive)
17000 (when (calendar-cursor-to-date)
17001 (let* ((date (calendar-cursor-to-date))
17002 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17003 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17004 (if (active-minibuffer-window) (exit-minibuffer))))
17006 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17007 "Insert a date stamp for the date given by the internal TIME.
17008 WITH-HM means use the stamp format that includes the time of the day.
17009 INACTIVE means use square brackets instead of angular ones, so that the
17010 stamp will not contribute to the agenda.
17011 PRE and POST are optional strings to be inserted before and after the
17012 stamp.
17013 The command returns the inserted time stamp."
17014 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17015 stamp)
17016 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17017 (insert-before-markers (or pre ""))
17018 (when (listp extra)
17019 (setq extra (car extra))
17020 (if (and (stringp extra)
17021 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17022 (setq extra (format "-%02d:%02d"
17023 (string-to-number (match-string 1 extra))
17024 (string-to-number (match-string 2 extra))))
17025 (setq extra nil)))
17026 (when extra
17027 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17028 (insert-before-markers (setq stamp (format-time-string fmt time)))
17029 (insert-before-markers (or post ""))
17030 (setq org-last-inserted-timestamp stamp)))
17032 (defun org-toggle-time-stamp-overlays ()
17033 "Toggle the use of custom time stamp formats."
17034 (interactive)
17035 (setq org-display-custom-times (not org-display-custom-times))
17036 (unless org-display-custom-times
17037 (let ((p (point-min)) (bmp (buffer-modified-p)))
17038 (while (setq p (next-single-property-change p 'display))
17039 (if (and (get-text-property p 'display)
17040 (eq (get-text-property p 'face) 'org-date))
17041 (remove-text-properties
17042 p (setq p (next-single-property-change p 'display))
17043 '(display t))))
17044 (set-buffer-modified-p bmp)))
17045 (if (featurep 'xemacs)
17046 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17047 (org-restart-font-lock)
17048 (setq org-table-may-need-update t)
17049 (if org-display-custom-times
17050 (message "Time stamps are overlaid with custom format")
17051 (message "Time stamp overlays removed")))
17053 (defun org-display-custom-time (beg end)
17054 "Overlay modified time stamp format over timestamp between BEG and END."
17055 (let* ((ts (buffer-substring beg end))
17056 t1 w1 with-hm tf time str w2 (off 0))
17057 (save-match-data
17058 (setq t1 (org-parse-time-string ts t))
17059 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17060 (setq off (- (match-end 0) (match-beginning 0)))))
17061 (setq end (- end off))
17062 (setq w1 (- end beg)
17063 with-hm (and (nth 1 t1) (nth 2 t1))
17064 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17065 time (org-fix-decoded-time t1)
17066 str (org-add-props
17067 (format-time-string
17068 (substring tf 1 -1) (apply 'encode-time time))
17069 nil 'mouse-face 'highlight)
17070 w2 (length str))
17071 (if (not (= w2 w1))
17072 (add-text-properties (1+ beg) (+ 2 beg)
17073 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17074 (if (featurep 'xemacs)
17075 (progn
17076 (put-text-property beg end 'invisible t)
17077 (put-text-property beg end 'end-glyph (make-glyph str)))
17078 (put-text-property beg end 'display str))))
17080 (defun org-translate-time (string)
17081 "Translate all timestamps in STRING to custom format.
17082 But do this only if the variable `org-display-custom-times' is set."
17083 (when org-display-custom-times
17084 (save-match-data
17085 (let* ((start 0)
17086 (re org-ts-regexp-both)
17087 t1 with-hm inactive tf time str beg end)
17088 (while (setq start (string-match re string start))
17089 (setq beg (match-beginning 0)
17090 end (match-end 0)
17091 t1 (save-match-data
17092 (org-parse-time-string (substring string beg end) t))
17093 with-hm (and (nth 1 t1) (nth 2 t1))
17094 inactive (equal (substring string beg (1+ beg)) "[")
17095 tf (funcall (if with-hm 'cdr 'car)
17096 org-time-stamp-custom-formats)
17097 time (org-fix-decoded-time t1)
17098 str (format-time-string
17099 (concat
17100 (if inactive "[" "<") (substring tf 1 -1)
17101 (if inactive "]" ">"))
17102 (apply 'encode-time time))
17103 string (replace-match str t t string)
17104 start (+ start (length str)))))))
17105 string)
17107 (defun org-fix-decoded-time (time)
17108 "Set 0 instead of nil for the first 6 elements of time.
17109 Don't touch the rest."
17110 (let ((n 0))
17111 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17113 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17115 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17116 "Difference between TIMESTAMP-STRING and now in days.
17117 If SECONDS is non-nil, return the difference in seconds."
17118 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17119 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17120 (funcall fdiff (current-time)))))
17122 (defun org-deadline-close (timestamp-string &optional ndays)
17123 "Is the time in TIMESTAMP-STRING close to the current date?"
17124 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17125 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17126 (not (org-entry-is-done-p))))
17128 (defun org-get-wdays (ts &optional delay zero-delay)
17129 "Get the deadline lead time appropriate for timestring TS.
17130 When DELAY is non-nil, get the delay time for scheduled items
17131 instead of the deadline lead time. When ZERO-DELAY is non-nil
17132 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17133 don't try to find the delay cookie in the scheduled timestamp."
17134 (let ((tv (if delay org-scheduled-delay-days
17135 org-deadline-warning-days)))
17136 (cond
17137 ((or (and delay (< tv 0))
17138 (and delay zero-delay (<= tv 0))
17139 (and (not delay) (<= tv 0)))
17140 ;; Enforce this value no matter what
17141 (- tv))
17142 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17143 ;; lead time is specified.
17144 (floor (* (string-to-number (match-string 1 ts))
17145 (cdr (assoc (match-string 2 ts)
17146 '(("d" . 1) ("w" . 7)
17147 ("m" . 30.4) ("y" . 365.25)
17148 ("h" . 0.041667)))))))
17149 ;; go for the default.
17150 (t tv))))
17152 (defun org-calendar-select-mouse (ev)
17153 "Return to `org-read-date' with the date currently selected.
17154 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17155 (interactive "e")
17156 (mouse-set-point ev)
17157 (when (calendar-cursor-to-date)
17158 (let* ((date (calendar-cursor-to-date))
17159 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17160 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17161 (if (active-minibuffer-window) (exit-minibuffer))))
17163 (defun org-check-deadlines (ndays)
17164 "Check if there are any deadlines due or past due.
17165 A deadline is considered due if it happens within `org-deadline-warning-days'
17166 days from today's date. If the deadline appears in an entry marked DONE,
17167 it is not shown. The prefix arg NDAYS can be used to test that many
17168 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17169 (interactive "P")
17170 (let* ((org-warn-days
17171 (cond
17172 ((equal ndays '(4)) 100000)
17173 (ndays (prefix-numeric-value ndays))
17174 (t (abs org-deadline-warning-days))))
17175 (case-fold-search nil)
17176 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17177 (callback
17178 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17180 (message "%d deadlines past-due or due within %d days"
17181 (org-occur regexp nil callback)
17182 org-warn-days)))
17184 (defsubst org-re-timestamp (type)
17185 "Return a regexp for timestamp TYPE.
17186 Allowed values for TYPE are:
17188 all: all timestamps
17189 active: only active timestamps (<...>)
17190 inactive: only inactive timestamps ([...])
17191 scheduled: only scheduled timestamps
17192 deadline: only deadline timestamps
17193 closed: only closed time-stamps
17195 When TYPE is nil, fall back on returning a regexp that matches
17196 both scheduled and deadline timestamps."
17197 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17198 ((eq type 'active) org-ts-regexp)
17199 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17200 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17201 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17202 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17203 ((eq type 'scheduled-or-deadline)
17204 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17206 (defun org-check-before-date (date)
17207 "Check if there are deadlines or scheduled entries before DATE."
17208 (interactive (list (org-read-date)))
17209 (let ((case-fold-search nil)
17210 (regexp (org-re-timestamp org-ts-type))
17211 (callback
17212 (lambda () (time-less-p
17213 (org-time-string-to-time (match-string 1))
17214 (org-time-string-to-time date)))))
17215 (message "%d entries before %s"
17216 (org-occur regexp nil callback) date)))
17218 (defun org-check-after-date (date)
17219 "Check if there are deadlines or scheduled entries after DATE."
17220 (interactive (list (org-read-date)))
17221 (let ((case-fold-search nil)
17222 (regexp (org-re-timestamp org-ts-type))
17223 (callback
17224 (lambda () (not
17225 (time-less-p
17226 (org-time-string-to-time (match-string 1))
17227 (org-time-string-to-time date))))))
17228 (message "%d entries after %s"
17229 (org-occur regexp nil callback) date)))
17231 (defun org-check-dates-range (start-date end-date)
17232 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17233 (interactive (list (org-read-date nil nil nil "Range starts")
17234 (org-read-date nil nil nil "Range end")))
17235 (let ((case-fold-search nil)
17236 (regexp (org-re-timestamp org-ts-type))
17237 (callback
17238 (lambda ()
17239 (let ((match (match-string 1)))
17240 (and
17241 (not (time-less-p
17242 (org-time-string-to-time match)
17243 (org-time-string-to-time start-date)))
17244 (time-less-p
17245 (org-time-string-to-time match)
17246 (org-time-string-to-time end-date)))))))
17247 (message "%d entries between %s and %s"
17248 (org-occur regexp nil callback) start-date end-date)))
17250 (defun org-evaluate-time-range (&optional to-buffer)
17251 "Evaluate a time range by computing the difference between start and end.
17252 Normally the result is just printed in the echo area, but with prefix arg
17253 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17254 If the time range is actually in a table, the result is inserted into the
17255 next column.
17256 For time difference computation, a year is assumed to be exactly 365
17257 days in order to avoid rounding problems."
17258 (interactive "P")
17260 (org-clock-update-time-maybe)
17261 (save-excursion
17262 (unless (org-at-date-range-p t)
17263 (goto-char (point-at-bol))
17264 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17265 (if (not (org-at-date-range-p t))
17266 (user-error "Not at a time-stamp range, and none found in current line")))
17267 (let* ((ts1 (match-string 1))
17268 (ts2 (match-string 2))
17269 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17270 (match-end (match-end 0))
17271 (time1 (org-time-string-to-time ts1))
17272 (time2 (org-time-string-to-time ts2))
17273 (t1 (org-float-time time1))
17274 (t2 (org-float-time time2))
17275 (diff (abs (- t2 t1)))
17276 (negative (< (- t2 t1) 0))
17277 ;; (ys (floor (* 365 24 60 60)))
17278 (ds (* 24 60 60))
17279 (hs (* 60 60))
17280 (fy "%dy %dd %02d:%02d")
17281 (fy1 "%dy %dd")
17282 (fd "%dd %02d:%02d")
17283 (fd1 "%dd")
17284 (fh "%02d:%02d")
17285 y d h m align)
17286 (if havetime
17287 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17289 d (floor (/ diff ds)) diff (mod diff ds)
17290 h (floor (/ diff hs)) diff (mod diff hs)
17291 m (floor (/ diff 60)))
17292 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17294 d (floor (+ (/ diff ds) 0.5))
17295 h 0 m 0))
17296 (if (not to-buffer)
17297 (message "%s" (org-make-tdiff-string y d h m))
17298 (if (org-at-table-p)
17299 (progn
17300 (goto-char match-end)
17301 (setq align t)
17302 (and (looking-at " *|") (goto-char (match-end 0))))
17303 (goto-char match-end))
17304 (if (looking-at
17305 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17306 (replace-match ""))
17307 (if negative (insert " -"))
17308 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17309 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17310 (insert " " (format fh h m))))
17311 (if align (org-table-align))
17312 (message "Time difference inserted")))))
17314 (defun org-make-tdiff-string (y d h m)
17315 (let ((fmt "")
17316 (l nil))
17317 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17318 l (push y l)))
17319 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17320 l (push d l)))
17321 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17322 l (push h l)))
17323 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17324 l (push m l)))
17325 (apply 'format fmt (nreverse l))))
17327 (defun org-time-string-to-time (s &optional buffer pos)
17328 "Convert a timestamp string into internal time."
17329 (condition-case errdata
17330 (apply 'encode-time (org-parse-time-string s))
17331 (error (error "Bad timestamp `%s'%s\nError was: %s"
17332 s (if (not (and buffer pos))
17334 (format " at %d in buffer `%s'" pos buffer))
17335 (cdr errdata)))))
17337 (defun org-time-string-to-seconds (s)
17338 "Convert a timestamp string to a number of seconds."
17339 (org-float-time (org-time-string-to-time s)))
17341 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17342 "Convert a time stamp to an absolute day number.
17343 If there is a specifier for a cyclic time stamp, get the closest
17344 date to DAYNR.
17345 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17346 The variable `date' is bound by the calendar when this is called."
17347 (cond
17348 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17349 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17350 daynr
17351 (+ daynr 1000)))
17352 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17353 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17354 (time-to-days (current-time))) (match-string 0 s)
17355 prefer show-all))
17356 (t (time-to-days
17357 (condition-case errdata
17358 (apply 'encode-time (org-parse-time-string s))
17359 (error (error "Bad timestamp `%s'%s\nError was: %s"
17360 s (if (not (and buffer pos))
17362 (format " at %d in buffer `%s'" pos buffer))
17363 (cdr errdata))))))))
17365 (defun org-days-to-iso-week (days)
17366 "Return the iso week number."
17367 (require 'cal-iso)
17368 (car (calendar-iso-from-absolute days)))
17370 (defun org-small-year-to-year (year)
17371 "Convert 2-digit years into 4-digit years.
17372 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17373 The year 2000 cannot be abbreviated. Any year larger than 99
17374 is returned unchanged."
17375 (if (< year 38)
17376 (setq year (+ 2000 year))
17377 (if (< year 100)
17378 (setq year (+ 1900 year))))
17379 year)
17381 (defun org-time-from-absolute (d)
17382 "Return the time corresponding to date D.
17383 D may be an absolute day number, or a calendar-type list (month day year)."
17384 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17385 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17387 (defun org-calendar-holiday ()
17388 "List of holidays, for Diary display in Org-mode."
17389 (require 'holidays)
17390 (let ((hl (funcall
17391 (if (fboundp 'calendar-check-holidays)
17392 'calendar-check-holidays 'check-calendar-holidays) date)))
17393 (if hl (mapconcat 'identity hl "; "))))
17395 (defun org-diary-sexp-entry (sexp entry date)
17396 "Process a SEXP diary ENTRY for DATE."
17397 (require 'diary-lib)
17398 (let ((result (if calendar-debug-sexp
17399 (let ((stack-trace-on-error t))
17400 (eval (car (read-from-string sexp))))
17401 (condition-case nil
17402 (eval (car (read-from-string sexp)))
17403 (error
17404 (beep)
17405 (message "Bad sexp at line %d in %s: %s"
17406 (org-current-line)
17407 (buffer-file-name) sexp)
17408 (sleep-for 2))))))
17409 (cond ((stringp result) (split-string result "; "))
17410 ((and (consp result)
17411 (not (consp (cdr result)))
17412 (stringp (cdr result))) (cdr result))
17413 ((and (consp result)
17414 (stringp (car result))) result)
17415 (result entry))))
17417 (defun org-diary-to-ical-string (frombuf)
17418 "Get iCalendar entries from diary entries in buffer FROMBUF.
17419 This uses the icalendar.el library."
17420 (let* ((tmpdir (if (featurep 'xemacs)
17421 (temp-directory)
17422 temporary-file-directory))
17423 (tmpfile (make-temp-name
17424 (expand-file-name "orgics" tmpdir)))
17425 buf rtn b e)
17426 (with-current-buffer frombuf
17427 (icalendar-export-region (point-min) (point-max) tmpfile)
17428 (setq buf (find-buffer-visiting tmpfile))
17429 (set-buffer buf)
17430 (goto-char (point-min))
17431 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17432 (setq b (match-beginning 0)))
17433 (goto-char (point-max))
17434 (if (re-search-backward "^END:VEVENT" nil t)
17435 (setq e (match-end 0)))
17436 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17437 (kill-buffer buf)
17438 (delete-file tmpfile)
17439 rtn))
17441 (defun org-closest-date (start current change prefer show-all)
17442 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17443 When PREFER is `past', return a date that is either CURRENT or past.
17444 When PREFER is `future', return a date that is either CURRENT or future.
17445 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17446 ;; Make the proper lists from the dates
17447 (catch 'exit
17448 (let ((a1 '(("h" . hour)
17449 ("d" . day)
17450 ("w" . week)
17451 ("m" . month)
17452 ("y" . year)))
17453 (shour (nth 2 (org-parse-time-string start)))
17454 dn dw sday cday n1 n2 n0
17455 d m y y1 y2 date1 date2 nmonths nm ny m2)
17457 (setq start (org-date-to-gregorian start)
17458 current (org-date-to-gregorian
17459 (if show-all
17460 current
17461 (time-to-days (current-time))))
17462 sday (calendar-absolute-from-gregorian start)
17463 cday (calendar-absolute-from-gregorian current))
17465 (if (<= cday sday) (throw 'exit sday))
17467 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17468 (setq dn (string-to-number (match-string 1 change))
17469 dw (cdr (assoc (match-string 2 change) a1)))
17470 (user-error "Invalid change specifier: %s" change))
17471 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17472 (cond
17473 ((eq dw 'hour)
17474 (let ((missing-hours
17475 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17476 dn)))
17477 (setq n1 (if (zerop missing-hours) cday
17478 (- cday (1+ (floor (/ missing-hours 24)))))
17479 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17480 ((eq dw 'day)
17481 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17482 n2 (+ n1 dn)))
17483 ((eq dw 'year)
17484 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17485 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17486 (setq date1 (list m d y1)
17487 n1 (calendar-absolute-from-gregorian date1)
17488 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17489 n2 (calendar-absolute-from-gregorian date2)))
17490 ((eq dw 'month)
17491 ;; approx number of month between the two dates
17492 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17493 ;; How often does dn fit in there?
17494 (setq d (nth 1 start) m (car start) y (nth 2 start)
17495 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17496 m (+ m nm)
17497 ny (floor (/ m 12))
17498 y (+ y ny)
17499 m (- m (* ny 12)))
17500 (while (> m 12) (setq m (- m 12) y (1+ y)))
17501 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17502 (setq m2 (+ m dn) y2 y)
17503 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17504 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17505 (while (<= n2 cday)
17506 (setq n1 n2 m m2 y y2)
17507 (setq m2 (+ m dn) y2 y)
17508 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17509 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17510 ;; Make sure n1 is the earlier date
17511 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17512 (if show-all
17513 (cond
17514 ((eq prefer 'past) (if (= cday n2) n2 n1))
17515 ((eq prefer 'future) (if (= cday n1) n1 n2))
17516 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17517 (cond
17518 ((eq prefer 'past) (if (= cday n2) n2 n1))
17519 ((eq prefer 'future) (if (= cday n1) n1 n2))
17520 (t (if (= cday n1) n1 n2)))))))
17522 (defun org-date-to-gregorian (date)
17523 "Turn any specification of DATE into a Gregorian date for the calendar."
17524 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17525 ((and (listp date) (= (length date) 3)) date)
17526 ((stringp date)
17527 (setq date (org-parse-time-string date))
17528 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17529 ((listp date)
17530 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17532 (defun org-parse-time-string (s &optional nodefault)
17533 "Parse the standard Org-mode time string.
17534 This should be a lot faster than the normal `parse-time-string'.
17535 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17536 hour and minute fields will be nil if not given."
17537 (cond ((string-match org-ts-regexp0 s)
17538 (list 0
17539 (if (or (match-beginning 8) (not nodefault))
17540 (string-to-number (or (match-string 8 s) "0")))
17541 (if (or (match-beginning 7) (not nodefault))
17542 (string-to-number (or (match-string 7 s) "0")))
17543 (string-to-number (match-string 4 s))
17544 (string-to-number (match-string 3 s))
17545 (string-to-number (match-string 2 s))
17546 nil nil nil))
17547 ((string-match "^<[^>]+>$" s)
17548 (decode-time (seconds-to-time (org-matcher-time s))))
17549 (t (error "Not a standard Org-mode time string: %s" s))))
17551 (defun org-timestamp-up (&optional arg)
17552 "Increase the date item at the cursor by one.
17553 If the cursor is on the year, change the year. If it is on the month,
17554 the day or the time, change that.
17555 With prefix ARG, change by that many units."
17556 (interactive "p")
17557 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17559 (defun org-timestamp-down (&optional arg)
17560 "Decrease the date item at the cursor by one.
17561 If the cursor is on the year, change the year. If it is on the month,
17562 the day or the time, change that.
17563 With prefix ARG, change by that many units."
17564 (interactive "p")
17565 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17567 (defun org-timestamp-up-day (&optional arg)
17568 "Increase the date in the time stamp by one day.
17569 With prefix ARG, change that many days."
17570 (interactive "p")
17571 (if (and (not (org-at-timestamp-p t))
17572 (org-at-heading-p))
17573 (org-todo 'up)
17574 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17576 (defun org-timestamp-down-day (&optional arg)
17577 "Decrease the date in the time stamp by one day.
17578 With prefix ARG, change that many days."
17579 (interactive "p")
17580 (if (and (not (org-at-timestamp-p t))
17581 (org-at-heading-p))
17582 (org-todo 'down)
17583 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17585 (defun org-at-timestamp-p (&optional inactive-ok)
17586 "Determine if the cursor is in or at a timestamp."
17587 (interactive)
17588 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17589 (pos (point))
17590 (ans (or (looking-at tsr)
17591 (save-excursion
17592 (skip-chars-backward "^[<\n\r\t")
17593 (if (> (point) (point-min)) (backward-char 1))
17594 (and (looking-at tsr)
17595 (> (- (match-end 0) pos) -1))))))
17596 (and ans
17597 (boundp 'org-ts-what)
17598 (setq org-ts-what
17599 (cond
17600 ((= pos (match-beginning 0)) 'bracket)
17601 ;; Point is considered to be "on the bracket" whether
17602 ;; it's really on it or right after it.
17603 ((= pos (1- (match-end 0))) 'bracket)
17604 ((= pos (match-end 0)) 'after)
17605 ((org-pos-in-match-range pos 2) 'year)
17606 ((org-pos-in-match-range pos 3) 'month)
17607 ((org-pos-in-match-range pos 7) 'hour)
17608 ((org-pos-in-match-range pos 8) 'minute)
17609 ((or (org-pos-in-match-range pos 4)
17610 (org-pos-in-match-range pos 5)) 'day)
17611 ((and (> pos (or (match-end 8) (match-end 5)))
17612 (< pos (match-end 0)))
17613 (- pos (or (match-end 8) (match-end 5))))
17614 (t 'day))))
17615 ans))
17617 (defun org-toggle-timestamp-type ()
17618 "Toggle the type (<active> or [inactive]) of a time stamp."
17619 (interactive)
17620 (when (org-at-timestamp-p t)
17621 (let ((beg (match-beginning 0)) (end (match-end 0))
17622 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17623 (save-excursion
17624 (goto-char beg)
17625 (while (re-search-forward "[][<>]" end t)
17626 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17627 t t)))
17628 (message "Timestamp is now %sactive"
17629 (if (equal (char-after beg) ?<) "" "in")))))
17631 (defun org-at-clock-log-p nil
17632 "Is the cursor on the clock log line?"
17633 (save-excursion
17634 (move-beginning-of-line 1)
17635 (looking-at org-clock-line-re)))
17637 (defvar org-clock-history) ; defined in org-clock.el
17638 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17639 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17640 "Change the date in the time stamp at point.
17641 The date will be changed by N times WHAT. WHAT can be `day', `month',
17642 `year', `minute', `second'. If WHAT is not given, the cursor position
17643 in the timestamp determines what will be changed.
17644 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17645 (let ((origin (point)) origin-cat
17646 with-hm inactive
17647 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17648 org-ts-what
17649 extra rem
17650 ts time time0 fixnext clrgx)
17651 (if (not (org-at-timestamp-p t))
17652 (user-error "Not at a timestamp"))
17653 (if (and (not what) (eq org-ts-what 'bracket))
17654 (org-toggle-timestamp-type)
17655 ;; Point isn't on brackets. Remember the part of the time-stamp
17656 ;; the point was in. Indeed, size of time-stamps may change,
17657 ;; but point must be kept in the same category nonetheless.
17658 (setq origin-cat org-ts-what)
17659 (if (and (not what) (not (eq org-ts-what 'day))
17660 org-display-custom-times
17661 (get-text-property (point) 'display)
17662 (not (get-text-property (1- (point)) 'display)))
17663 (setq org-ts-what 'day))
17664 (setq org-ts-what (or what org-ts-what)
17665 inactive (= (char-after (match-beginning 0)) ?\[)
17666 ts (match-string 0))
17667 (replace-match "")
17668 (when (string-match
17669 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17671 (setq extra (match-string 1 ts))
17672 (if suppress-tmp-delay
17673 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17674 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17675 (setq with-hm t))
17676 (setq time0 (org-parse-time-string ts))
17677 (when (and updown
17678 (eq org-ts-what 'minute)
17679 (not current-prefix-arg))
17680 ;; This looks like s-up and s-down. Change by one rounding step.
17681 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17682 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17683 (setcar (cdr time0) (+ (nth 1 time0)
17684 (if (> n 0) (- rem) (- dm rem))))))
17685 (setq time
17686 (encode-time (or (car time0) 0)
17687 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17688 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17689 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17690 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17691 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17692 (nthcdr 6 time0)))
17693 (when (and (member org-ts-what '(hour minute))
17694 extra
17695 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17696 (setq extra (org-modify-ts-extra
17697 extra
17698 (if (eq org-ts-what 'hour) 2 5)
17699 n dm)))
17700 (when (integerp org-ts-what)
17701 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17702 (if (eq what 'calendar)
17703 (let ((cal-date (org-get-date-from-calendar)))
17704 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17705 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17706 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17707 (setcar time0 (or (car time0) 0))
17708 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17709 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17710 (setq time (apply 'encode-time time0))))
17711 ;; Insert the new time-stamp, and ensure point stays in the same
17712 ;; category as before (i.e. not after the last position in that
17713 ;; category).
17714 (let ((pos (point)))
17715 ;; Stay before inserted string. `save-excursion' is of no use.
17716 (setq org-last-changed-timestamp
17717 (org-insert-time-stamp time with-hm inactive nil nil extra))
17718 (goto-char pos))
17719 (save-match-data
17720 (looking-at org-ts-regexp3)
17721 (goto-char (cond
17722 ;; `day' category ends before `hour' if any, or at
17723 ;; the end of the day name.
17724 ((eq origin-cat 'day)
17725 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17726 ((eq origin-cat 'hour) (min (match-end 7) origin))
17727 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17728 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17729 ;; `year' and `month' have both fixed size: point
17730 ;; couldn't have moved into another part.
17731 (t origin))))
17732 ;; Update clock if on a CLOCK line.
17733 (org-clock-update-time-maybe)
17734 ;; Maybe adjust the closest clock in `org-clock-history'
17735 (when org-clock-adjust-closest
17736 (if (not (and (org-at-clock-log-p)
17737 (< 1 (length (delq nil (mapcar 'marker-position
17738 org-clock-history))))))
17739 (message "No clock to adjust")
17740 (cond ((save-excursion ; fix previous clock?
17741 (re-search-backward org-ts-regexp0 nil t)
17742 (org-looking-back (concat org-clock-string " \\[")))
17743 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17744 ((save-excursion ; fix next clock?
17745 (re-search-backward org-ts-regexp0 nil t)
17746 (looking-at (concat org-ts-regexp0 "\\] =>")))
17747 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17748 (save-window-excursion
17749 ;; Find closest clock to point, adjust the previous/next one in history
17750 (let* ((p (save-excursion (org-back-to-heading t)))
17751 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17752 (clfixnth
17753 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17754 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17755 (if (not clfixpos)
17756 (message "No clock to adjust")
17757 (save-excursion
17758 (org-goto-marker-or-bmk clfixpos)
17759 (org-show-subtree)
17760 (when (re-search-forward clrgx nil t)
17761 (goto-char (match-beginning 1))
17762 (let (org-clock-adjust-closest)
17763 (org-timestamp-change n org-ts-what updown))
17764 (message "Clock adjusted in %s for heading: %s"
17765 (file-name-nondirectory (buffer-file-name))
17766 (org-get-heading t t)))))))))
17767 ;; Try to recenter the calendar window, if any.
17768 (if (and org-calendar-follow-timestamp-change
17769 (get-buffer-window "*Calendar*" t)
17770 (memq org-ts-what '(day month year)))
17771 (org-recenter-calendar (time-to-days time))))))
17773 (defun org-modify-ts-extra (s pos n dm)
17774 "Change the different parts of the lead-time and repeat fields in timestamp."
17775 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17776 ng h m new rem)
17777 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17778 (cond
17779 ((or (org-pos-in-match-range pos 2)
17780 (org-pos-in-match-range pos 3))
17781 (setq m (string-to-number (match-string 3 s))
17782 h (string-to-number (match-string 2 s)))
17783 (if (org-pos-in-match-range pos 2)
17784 (setq h (+ h n))
17785 (setq n (* dm (org-no-warnings (signum n))))
17786 (when (not (= 0 (setq rem (% m dm))))
17787 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17788 (setq m (+ m n)))
17789 (if (< m 0) (setq m (+ m 60) h (1- h)))
17790 (if (> m 59) (setq m (- m 60) h (1+ h)))
17791 (setq h (min 24 (max 0 h)))
17792 (setq ng 1 new (format "-%02d:%02d" h m)))
17793 ((org-pos-in-match-range pos 6)
17794 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17795 ((org-pos-in-match-range pos 5)
17796 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17798 ((org-pos-in-match-range pos 9)
17799 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17800 ((org-pos-in-match-range pos 8)
17801 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17803 (when ng
17804 (setq s (concat
17805 (substring s 0 (match-beginning ng))
17807 (substring s (match-end ng))))))
17810 (defun org-recenter-calendar (date)
17811 "If the calendar is visible, recenter it to DATE."
17812 (let ((cwin (get-buffer-window "*Calendar*" t)))
17813 (when cwin
17814 (let ((calendar-move-hook nil))
17815 (with-selected-window cwin
17816 (calendar-goto-date (if (listp date) date
17817 (calendar-gregorian-from-absolute date))))))))
17819 (defun org-goto-calendar (&optional arg)
17820 "Go to the Emacs calendar at the current date.
17821 If there is a time stamp in the current line, go to that date.
17822 A prefix ARG can be used to force the current date."
17823 (interactive "P")
17824 (let ((tsr org-ts-regexp) diff
17825 (calendar-move-hook nil)
17826 (calendar-view-holidays-initially-flag nil)
17827 (calendar-view-diary-initially-flag nil))
17828 (if (or (org-at-timestamp-p)
17829 (save-excursion
17830 (beginning-of-line 1)
17831 (looking-at (concat ".*" tsr))))
17832 (let ((d1 (time-to-days (current-time)))
17833 (d2 (time-to-days
17834 (org-time-string-to-time (match-string 1)))))
17835 (setq diff (- d2 d1))))
17836 (calendar)
17837 (calendar-goto-today)
17838 (if (and diff (not arg)) (calendar-forward-day diff))))
17840 (defun org-get-date-from-calendar ()
17841 "Return a list (month day year) of date at point in calendar."
17842 (with-current-buffer "*Calendar*"
17843 (save-match-data
17844 (calendar-cursor-to-date))))
17846 (defun org-date-from-calendar ()
17847 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17848 If there is already a time stamp at the cursor position, update it."
17849 (interactive)
17850 (if (org-at-timestamp-p t)
17851 (org-timestamp-change 0 'calendar)
17852 (let ((cal-date (org-get-date-from-calendar)))
17853 (org-insert-time-stamp
17854 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17856 (defcustom org-effort-durations
17857 `(("h" . 60)
17858 ("d" . ,(* 60 8))
17859 ("w" . ,(* 60 8 5))
17860 ("m" . ,(* 60 8 5 4))
17861 ("y" . ,(* 60 8 5 40)))
17862 "Conversion factor to minutes for an effort modifier.
17864 Each entry has the form (MODIFIER . MINUTES).
17866 In an effort string, a number followed by MODIFIER is multiplied
17867 by the specified number of MINUTES to obtain an effort in
17868 minutes.
17870 For example, if the value of this variable is ((\"hours\" . 60)), then an
17871 effort string \"2hours\" is equivalent to 120 minutes."
17872 :group 'org-agenda
17873 :version "24.1"
17874 :type '(alist :key-type (string :tag "Modifier")
17875 :value-type (number :tag "Minutes")))
17877 (defun org-minutes-to-clocksum-string (m)
17878 "Format number of minutes as a clocksum string.
17879 The format is determined by `org-time-clocksum-format',
17880 `org-time-clocksum-use-fractional' and
17881 `org-time-clocksum-fractional-format' and
17882 `org-time-clocksum-use-effort-durations'."
17883 (let ((clocksum "")
17884 (m (round m)) ; Don't allow fractions of minutes
17885 h d w mo y fmt n)
17886 (setq h (if org-time-clocksum-use-effort-durations
17887 (cdr (assoc "h" org-effort-durations)) 60)
17888 d (if org-time-clocksum-use-effort-durations
17889 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17890 w (if org-time-clocksum-use-effort-durations
17891 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17892 mo (if org-time-clocksum-use-effort-durations
17893 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17894 y (if org-time-clocksum-use-effort-durations
17895 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17896 ;; fractional format
17897 (if org-time-clocksum-use-fractional
17898 (cond
17899 ;; single format string
17900 ((stringp org-time-clocksum-fractional-format)
17901 (format org-time-clocksum-fractional-format (/ m (float h))))
17902 ;; choice of fractional formats for different time units
17903 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17904 (> (/ (truncate m) (* y d h)) 0))
17905 (format fmt (/ m (* y d (float h)))))
17906 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17907 (> (/ (truncate m) (* mo d h)) 0))
17908 (format fmt (/ m (* mo d (float h)))))
17909 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17910 (> (/ (truncate m) (* w d h)) 0))
17911 (format fmt (/ m (* w d (float h)))))
17912 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17913 (> (/ (truncate m) (* d h)) 0))
17914 (format fmt (/ m (* d (float h)))))
17915 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17916 (> (/ (truncate m) h) 0))
17917 (format fmt (/ m (float h))))
17918 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17919 (format fmt m))
17920 ;; fall back to smallest time unit with a format
17921 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17922 (format fmt (/ m (float h))))
17923 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17924 (format fmt (/ m (* d (float h)))))
17925 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17926 (format fmt (/ m (* w d (float h)))))
17927 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17928 (format fmt (/ m (* mo d (float h)))))
17929 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17930 (format fmt (/ m (* y d (float h))))))
17931 ;; standard (non-fractional) format, with single format string
17932 (if (stringp org-time-clocksum-format)
17933 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17934 ;; separate formats components
17935 (and (setq fmt (plist-get org-time-clocksum-format :years))
17936 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17937 (plist-get org-time-clocksum-format :require-years))
17938 (setq clocksum (concat clocksum (format fmt n))
17939 m (- m (* n y d h))))
17940 (and (setq fmt (plist-get org-time-clocksum-format :months))
17941 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17942 (plist-get org-time-clocksum-format :require-months))
17943 (setq clocksum (concat clocksum (format fmt n))
17944 m (- m (* n mo d h))))
17945 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17946 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17947 (plist-get org-time-clocksum-format :require-weeks))
17948 (setq clocksum (concat clocksum (format fmt n))
17949 m (- m (* n w d h))))
17950 (and (setq fmt (plist-get org-time-clocksum-format :days))
17951 (or (> (setq n (/ (truncate m) (* d h))) 0)
17952 (plist-get org-time-clocksum-format :require-days))
17953 (setq clocksum (concat clocksum (format fmt n))
17954 m (- m (* n d h))))
17955 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17956 (or (> (setq n (/ (truncate m) h)) 0)
17957 (plist-get org-time-clocksum-format :require-hours))
17958 (setq clocksum (concat clocksum (format fmt n))
17959 m (- m (* n h))))
17960 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17961 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17962 (setq clocksum (concat clocksum (format fmt m))))
17963 ;; return formatted time duration
17964 clocksum))))
17966 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17967 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17968 "Org mode version 8.0")
17970 (defun org-hours-to-clocksum-string (n)
17971 (org-minutes-to-clocksum-string (* n 60)))
17973 (defun org-hh:mm-string-to-minutes (s)
17974 "Convert a string H:MM to a number of minutes.
17975 If the string is just a number, interpret it as minutes.
17976 In fact, the first hh:mm or number in the string will be taken,
17977 there can be extra stuff in the string.
17978 If no number is found, the return value is 0."
17979 (cond
17980 ((integerp s) s)
17981 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17982 (+ (* (string-to-number (match-string 1 s)) 60)
17983 (string-to-number (match-string 2 s))))
17984 ((string-match "\\([0-9]+\\)" s)
17985 (string-to-number (match-string 1 s)))
17986 (t 0)))
17988 (defcustom org-image-actual-width t
17989 "Should we use the actual width of images when inlining them?
17991 When set to `t', always use the image width.
17993 When set to a number, use imagemagick (when available) to set
17994 the image's width to this value.
17996 When set to a number in a list, try to get the width from any
17997 #+ATTR.* keyword if it matches a width specification like
17999 #+ATTR_HTML: :width 300px
18001 and fall back on that number if none is found.
18003 When set to nil, try to get the width from an #+ATTR.* keyword
18004 and fall back on the original width if none is found.
18006 This requires Emacs >= 24.1, build with imagemagick support."
18007 :group 'org-appearance
18008 :version "24.4"
18009 :package-version '(Org . "8.0")
18010 :type '(choice
18011 (const :tag "Use the image width" t)
18012 (integer :tag "Use a number of pixels")
18013 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18014 (const :tag "Use #+ATTR* or don't resize" nil)))
18016 (defcustom org-agenda-inhibit-startup nil
18017 "Inhibit startup when preparing agenda buffers.
18018 When this variable is `t', the initialization of the Org agenda
18019 buffers is inhibited: e.g. the visibility state is not set, the
18020 tables are not re-aligned, etc."
18021 :type 'boolean
18022 :version "24.3"
18023 :group 'org-agenda)
18025 (define-obsolete-variable-alias
18026 'org-agenda-ignore-drawer-properties
18027 'org-agenda-ignore-properties "25.1")
18029 (defcustom org-agenda-ignore-properties nil
18030 "Avoid updating text properties when building the agenda.
18031 Properties are used to prepare buffers for effort estimates,
18032 appointments, statistics and subtree-local categories.
18033 If you don't use these in the agenda, you can add them to this
18034 list and agenda building will be a bit faster.
18035 The value is a list, with zero or more of the symbols `effort', `appt',
18036 `stats' or `category'."
18037 :type '(set :greedy t
18038 (const effort)
18039 (const appt)
18040 (const stats)
18041 (const category))
18042 :version "25.1"
18043 :package-version '(Org . "8.3")
18044 :group 'org-agenda)
18046 (defun org-duration-string-to-minutes (s &optional output-to-string)
18047 "Convert a duration string S to minutes.
18049 A bare number is interpreted as minutes, modifiers can be set by
18050 customizing `org-effort-durations' (which see).
18052 Entries containing a colon are interpreted as H:MM by
18053 `org-hh:mm-string-to-minutes'."
18054 (let ((result 0)
18055 (re (concat "\\([0-9.]+\\) *\\("
18056 (regexp-opt (mapcar 'car org-effort-durations))
18057 "\\)")))
18058 (while (string-match re s)
18059 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18060 (string-to-number (match-string 1 s))))
18061 (setq s (replace-match "" nil t s)))
18062 (setq result (floor result))
18063 (incf result (org-hh:mm-string-to-minutes s))
18064 (if output-to-string (number-to-string result) result)))
18066 ;;;; Files
18068 (defun org-save-all-org-buffers ()
18069 "Save all Org-mode buffers without user confirmation."
18070 (interactive)
18071 (message "Saving all Org-mode buffers...")
18072 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18073 (when (featurep 'org-id) (org-id-locations-save))
18074 (message "Saving all Org-mode buffers... done"))
18076 (defun org-revert-all-org-buffers ()
18077 "Revert all Org-mode buffers.
18078 Prompt for confirmation when there are unsaved changes.
18079 Be sure you know what you are doing before letting this function
18080 overwrite your changes.
18082 This function is useful in a setup where one tracks org files
18083 with a version control system, to revert on one machine after pulling
18084 changes from another. I believe the procedure must be like this:
18086 1. M-x org-save-all-org-buffers
18087 2. Pull changes from the other machine, resolve conflicts
18088 3. M-x org-revert-all-org-buffers"
18089 (interactive)
18090 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18091 (user-error "Abort"))
18092 (save-excursion
18093 (save-window-excursion
18094 (mapc
18095 (lambda (b)
18096 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18097 (with-current-buffer b buffer-file-name))
18098 (org-pop-to-buffer-same-window b)
18099 (revert-buffer t 'no-confirm)))
18100 (buffer-list))
18101 (when (and (featurep 'org-id) org-id-track-globally)
18102 (org-id-locations-load)))))
18104 ;;;; Agenda files
18106 ;;;###autoload
18107 (defun org-switchb (&optional arg)
18108 "Switch between Org buffers.
18109 With one prefix argument, restrict available buffers to files.
18110 With two prefix arguments, restrict available buffers to agenda files.
18112 Defaults to `iswitchb' for buffer name completion.
18113 Set `org-completion-use-ido' to make it use ido instead."
18114 (interactive "P")
18115 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18116 ((equal arg '(16)) (org-buffer-list 'agenda))
18117 (t (org-buffer-list))))
18118 (org-completion-use-iswitchb org-completion-use-iswitchb)
18119 (org-completion-use-ido org-completion-use-ido))
18120 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18121 (setq org-completion-use-iswitchb t))
18122 (org-pop-to-buffer-same-window
18123 (org-icompleting-read "Org buffer: "
18124 (mapcar 'list (mapcar 'buffer-name blist))
18125 nil t))))
18127 ;;; Define some older names previously used for this functionality
18128 ;;;###autoload
18129 (defalias 'org-ido-switchb 'org-switchb)
18130 ;;;###autoload
18131 (defalias 'org-iswitchb 'org-switchb)
18133 (defun org-buffer-list (&optional predicate exclude-tmp)
18134 "Return a list of Org buffers.
18135 PREDICATE can be `export', `files' or `agenda'.
18137 export restrict the list to Export buffers.
18138 files restrict the list to buffers visiting Org files.
18139 agenda restrict the list to buffers visiting agenda files.
18141 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18142 (let* ((bfn nil)
18143 (agenda-files (and (eq predicate 'agenda)
18144 (mapcar 'file-truename (org-agenda-files t))))
18145 (filter
18146 (cond
18147 ((eq predicate 'files)
18148 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18149 ((eq predicate 'export)
18150 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18151 ((eq predicate 'agenda)
18152 (lambda (b)
18153 (with-current-buffer b
18154 (and (derived-mode-p 'org-mode)
18155 (setq bfn (buffer-file-name b))
18156 (member (file-truename bfn) agenda-files)))))
18157 (t (lambda (b) (with-current-buffer b
18158 (or (derived-mode-p 'org-mode)
18159 (string-match "\*Org .*Export"
18160 (buffer-name b)))))))))
18161 (delq nil
18162 (mapcar
18163 (lambda(b)
18164 (if (and (funcall filter b)
18165 (or (not exclude-tmp)
18166 (not (string-match "tmp" (buffer-name b)))))
18168 nil))
18169 (buffer-list)))))
18171 (defun org-agenda-files (&optional unrestricted archives)
18172 "Get the list of agenda files.
18173 Optional UNRESTRICTED means return the full list even if a restriction
18174 is currently in place.
18175 When ARCHIVES is t, include all archive files that are really being
18176 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18177 `org-agenda-archives-mode' is t."
18178 (let ((files
18179 (cond
18180 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18181 ((stringp org-agenda-files) (org-read-agenda-file-list))
18182 ((listp org-agenda-files) org-agenda-files)
18183 (t (error "Invalid value of `org-agenda-files'")))))
18184 (setq files (apply 'append
18185 (mapcar (lambda (f)
18186 (if (file-directory-p f)
18187 (directory-files
18188 f t org-agenda-file-regexp)
18189 (list f)))
18190 files)))
18191 (when org-agenda-skip-unavailable-files
18192 (setq files (delq nil
18193 (mapcar (function
18194 (lambda (file)
18195 (and (file-readable-p file) file)))
18196 files))))
18197 (when (or (eq archives t)
18198 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18199 (setq files (org-add-archive-files files)))
18200 files))
18202 (defun org-agenda-file-p (&optional file)
18203 "Return non-nil, if FILE is an agenda file.
18204 If FILE is omitted, use the file associated with the current
18205 buffer."
18206 (let ((fname (or file (buffer-file-name))))
18207 (and fname
18208 (member (file-truename fname)
18209 (mapcar #'file-truename (org-agenda-files t))))))
18211 (defun org-edit-agenda-file-list ()
18212 "Edit the list of agenda files.
18213 Depending on setup, this either uses customize to edit the variable
18214 `org-agenda-files', or it visits the file that is holding the list. In the
18215 latter case, the buffer is set up in a way that saving it automatically kills
18216 the buffer and restores the previous window configuration."
18217 (interactive)
18218 (if (stringp org-agenda-files)
18219 (let ((cw (current-window-configuration)))
18220 (find-file org-agenda-files)
18221 (org-set-local 'org-window-configuration cw)
18222 (org-add-hook 'after-save-hook
18223 (lambda ()
18224 (set-window-configuration
18225 (prog1 org-window-configuration
18226 (kill-buffer (current-buffer))))
18227 (org-install-agenda-files-menu)
18228 (message "New agenda file list installed"))
18229 nil 'local)
18230 (message "%s" (substitute-command-keys
18231 "Edit list and finish with \\[save-buffer]")))
18232 (customize-variable 'org-agenda-files)))
18234 (defun org-store-new-agenda-file-list (list)
18235 "Set new value for the agenda file list and save it correctly."
18236 (if (stringp org-agenda-files)
18237 (let ((fe (org-read-agenda-file-list t)) b u)
18238 (while (setq b (find-buffer-visiting org-agenda-files))
18239 (kill-buffer b))
18240 (with-temp-file org-agenda-files
18241 (insert
18242 (mapconcat
18243 (lambda (f) ;; Keep un-expanded entries.
18244 (if (setq u (assoc f fe))
18245 (cdr u)
18247 list "\n")
18248 "\n")))
18249 (let ((org-mode-hook nil) (org-inhibit-startup t)
18250 (org-insert-mode-line-in-empty-file nil))
18251 (setq org-agenda-files list)
18252 (customize-save-variable 'org-agenda-files org-agenda-files))))
18254 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18255 "Read the list of agenda files from a file.
18256 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18257 filenames, used by `org-store-new-agenda-file-list' to write back
18258 un-expanded file names."
18259 (when (file-directory-p org-agenda-files)
18260 (error "`org-agenda-files' cannot be a single directory"))
18261 (when (stringp org-agenda-files)
18262 (with-temp-buffer
18263 (insert-file-contents org-agenda-files)
18264 (mapcar
18265 (lambda (f)
18266 (let ((e (expand-file-name (substitute-in-file-name f)
18267 org-directory)))
18268 (if pair-with-expansion
18269 (cons e f)
18270 e)))
18271 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18273 ;;;###autoload
18274 (defun org-cycle-agenda-files ()
18275 "Cycle through the files in `org-agenda-files'.
18276 If the current buffer visits an agenda file, find the next one in the list.
18277 If the current buffer does not, find the first agenda file."
18278 (interactive)
18279 (let* ((fs (org-agenda-files t))
18280 (files (append fs (list (car fs))))
18281 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18282 file)
18283 (unless files (user-error "No agenda files"))
18284 (catch 'exit
18285 (while (setq file (pop files))
18286 (if (equal (file-truename file) tcf)
18287 (when (car files)
18288 (find-file (car files))
18289 (throw 'exit t))))
18290 (find-file (car fs)))
18291 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18293 (defun org-agenda-file-to-front (&optional to-end)
18294 "Move/add the current file to the top of the agenda file list.
18295 If the file is not present in the list, it is added to the front. If it is
18296 present, it is moved there. With optional argument TO-END, add/move to the
18297 end of the list."
18298 (interactive "P")
18299 (let ((org-agenda-skip-unavailable-files nil)
18300 (file-alist (mapcar (lambda (x)
18301 (cons (file-truename x) x))
18302 (org-agenda-files t)))
18303 (ctf (file-truename
18304 (or buffer-file-name
18305 (user-error "Please save the current buffer to a file"))))
18306 x had)
18307 (setq x (assoc ctf file-alist) had x)
18309 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18310 (if to-end
18311 (setq file-alist (append (delq x file-alist) (list x)))
18312 (setq file-alist (cons x (delq x file-alist))))
18313 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18314 (org-install-agenda-files-menu)
18315 (message "File %s to %s of agenda file list"
18316 (if had "moved" "added") (if to-end "end" "front"))))
18318 (defun org-remove-file (&optional file)
18319 "Remove current file from the list of files in variable `org-agenda-files'.
18320 These are the files which are being checked for agenda entries.
18321 Optional argument FILE means use this file instead of the current."
18322 (interactive)
18323 (let* ((org-agenda-skip-unavailable-files nil)
18324 (file (or file buffer-file-name
18325 (user-error "Current buffer does not visit a file")))
18326 (true-file (file-truename file))
18327 (afile (abbreviate-file-name file))
18328 (files (delq nil (mapcar
18329 (lambda (x)
18330 (if (equal true-file
18331 (file-truename x))
18332 nil x))
18333 (org-agenda-files t)))))
18334 (if (not (= (length files) (length (org-agenda-files t))))
18335 (progn
18336 (org-store-new-agenda-file-list files)
18337 (org-install-agenda-files-menu)
18338 (message "Removed file: %s" afile))
18339 (message "File was not in list: %s (not removed)" afile))))
18341 (defun org-file-menu-entry (file)
18342 (vector file (list 'find-file file) t))
18344 (defun org-check-agenda-file (file)
18345 "Make sure FILE exists. If not, ask user what to do."
18346 (when (not (file-exists-p file))
18347 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18348 (abbreviate-file-name file))
18349 (let ((r (downcase (read-char-exclusive))))
18350 (cond
18351 ((equal r ?r)
18352 (org-remove-file file)
18353 (throw 'nextfile t))
18354 (t (user-error "Abort"))))))
18356 (defun org-get-agenda-file-buffer (file)
18357 "Get an agenda buffer visiting FILE.
18358 If the buffer needs to be created, add it to the list of buffers
18359 which might be released later."
18360 (let ((buf (org-find-base-buffer-visiting file)))
18361 (if buf
18362 buf ; just return it
18363 ;; Make a new buffer and remember it
18364 (setq buf (find-file-noselect file))
18365 (if buf (push buf org-agenda-new-buffers))
18366 buf)))
18368 (defun org-release-buffers (blist)
18369 "Release all buffers in list, asking the user for confirmation when needed.
18370 When a buffer is unmodified, it is just killed. When modified, it is saved
18371 \(if the user agrees) and then killed."
18372 (let (buf file)
18373 (while (setq buf (pop blist))
18374 (setq file (buffer-file-name buf))
18375 (when (and (buffer-modified-p buf)
18376 file
18377 (y-or-n-p (format "Save file %s? " file)))
18378 (with-current-buffer buf (save-buffer)))
18379 (kill-buffer buf))))
18381 (defun org-agenda-prepare-buffers (files)
18382 "Create buffers for all agenda files, protect archived trees and comments."
18383 (interactive)
18384 (let ((pa '(:org-archived t))
18385 (pc '(:org-comment t))
18386 (pall '(:org-archived t :org-comment t))
18387 (inhibit-read-only t)
18388 (org-inhibit-startup org-agenda-inhibit-startup)
18389 (rea (concat ":" org-archive-tag ":"))
18390 file re pos)
18391 (setq org-tag-alist-for-agenda nil
18392 org-tag-groups-alist-for-agenda nil)
18393 (save-excursion
18394 (save-restriction
18395 (while (setq file (pop files))
18396 (catch 'nextfile
18397 (if (bufferp file)
18398 (set-buffer file)
18399 (org-check-agenda-file file)
18400 (set-buffer (org-get-agenda-file-buffer file)))
18401 (widen)
18402 (org-set-regexps-and-options-for-tags)
18403 (setq pos (point))
18404 (goto-char (point-min))
18405 (let ((case-fold-search t))
18406 (when (search-forward "#+setupfile" nil t)
18407 ;; Don't set all regexps and options systematically as
18408 ;; this is only run for setting agenda tags from setup
18409 ;; file
18410 (org-set-regexps-and-options)))
18411 (or (memq 'category org-agenda-ignore-properties)
18412 (org-refresh-category-properties))
18413 (or (memq 'stats org-agenda-ignore-properties)
18414 (org-refresh-stats-properties))
18415 (or (memq 'effort org-agenda-ignore-properties)
18416 (org-refresh-effort-properties))
18417 (or (memq 'appt org-agenda-ignore-properties)
18418 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18419 (setq org-todo-keywords-for-agenda
18420 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18421 (setq org-done-keywords-for-agenda
18422 (append org-done-keywords-for-agenda org-done-keywords))
18423 (setq org-todo-keyword-alist-for-agenda
18424 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18425 (setq org-tag-alist-for-agenda
18426 (org-uniquify
18427 (append org-tag-alist-for-agenda
18428 org-tag-alist
18429 org-tag-persistent-alist)))
18430 (if org-group-tags
18431 (setq org-tag-groups-alist-for-agenda
18432 (org-uniquify-alist
18433 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18434 (org-with-silent-modifications
18435 (save-excursion
18436 (remove-text-properties (point-min) (point-max) pall)
18437 (when org-agenda-skip-archived-trees
18438 (goto-char (point-min))
18439 (while (re-search-forward rea nil t)
18440 (if (org-at-heading-p t)
18441 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18442 (goto-char (point-min))
18443 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18444 (while (re-search-forward re nil t)
18445 (when (save-match-data (org-in-commented-heading-p t))
18446 (add-text-properties
18447 (match-beginning 0) (org-end-of-subtree t) pc)))))
18448 (goto-char pos)))))
18449 (setq org-todo-keywords-for-agenda
18450 (org-uniquify org-todo-keywords-for-agenda))
18451 (setq org-todo-keyword-alist-for-agenda
18452 (org-uniquify org-todo-keyword-alist-for-agenda))))
18455 ;;;; CDLaTeX minor mode
18457 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18458 "Keymap for the minor `org-cdlatex-mode'.")
18460 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18461 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18462 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18463 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18464 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18466 (defvar org-cdlatex-texmathp-advice-is-done nil
18467 "Flag remembering if we have applied the advice to texmathp already.")
18469 (define-minor-mode org-cdlatex-mode
18470 "Toggle the minor `org-cdlatex-mode'.
18471 This mode supports entering LaTeX environment and math in LaTeX fragments
18472 in Org-mode.
18473 \\{org-cdlatex-mode-map}"
18474 nil " OCDL" nil
18475 (when org-cdlatex-mode
18476 (require 'cdlatex)
18477 (run-hooks 'cdlatex-mode-hook)
18478 (cdlatex-compute-tables))
18479 (unless org-cdlatex-texmathp-advice-is-done
18480 (setq org-cdlatex-texmathp-advice-is-done t)
18481 (defadvice texmathp (around org-math-always-on activate)
18482 "Always return t in org-mode buffers.
18483 This is because we want to insert math symbols without dollars even outside
18484 the LaTeX math segments. If Orgmode thinks that point is actually inside
18485 an embedded LaTeX fragment, let texmathp do its job.
18486 \\[org-cdlatex-mode-map]"
18487 (interactive)
18488 (let (p)
18489 (cond
18490 ((not (derived-mode-p 'org-mode)) ad-do-it)
18491 ((eq this-command 'cdlatex-math-symbol)
18492 (setq ad-return-value t
18493 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18495 (let ((p (org-inside-LaTeX-fragment-p)))
18496 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18497 (setq ad-return-value t
18498 texmathp-why '("Org-mode embedded math" . 0))
18499 (if p ad-do-it)))))))))
18501 (defun turn-on-org-cdlatex ()
18502 "Unconditionally turn on `org-cdlatex-mode'."
18503 (org-cdlatex-mode 1))
18505 (defun org-try-cdlatex-tab ()
18506 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18507 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18508 - inside a LaTeX fragment, or
18509 - after the first word in a line, where an abbreviation expansion could
18510 insert a LaTeX environment."
18511 (when org-cdlatex-mode
18512 (cond
18513 ;; Before any word on the line: No expansion possible.
18514 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18515 ;; Just after first word on the line: Expand it. Make sure it
18516 ;; cannot happen on headlines, though.
18517 ((save-excursion
18518 (skip-chars-backward "a-zA-Z0-9*")
18519 (skip-chars-backward " \t")
18520 (and (bolp) (not (org-at-heading-p))))
18521 (cdlatex-tab) t)
18522 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18524 (defun org-cdlatex-underscore-caret (&optional arg)
18525 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18526 Revert to the normal definition outside of these fragments."
18527 (interactive "P")
18528 (if (org-inside-LaTeX-fragment-p)
18529 (call-interactively 'cdlatex-sub-superscript)
18530 (let (org-cdlatex-mode)
18531 (call-interactively (key-binding (vector last-input-event))))))
18533 (defun org-cdlatex-math-modify (&optional arg)
18534 "Execute `cdlatex-math-modify' in LaTeX fragments.
18535 Revert to the normal definition outside of these fragments."
18536 (interactive "P")
18537 (if (org-inside-LaTeX-fragment-p)
18538 (call-interactively 'cdlatex-math-modify)
18539 (let (org-cdlatex-mode)
18540 (call-interactively (key-binding (vector last-input-event))))))
18542 (defun org-cdlatex-environment-indent (&optional environment item)
18543 "Execute `cdlatex-environment' and indent the inserted environment."
18544 (interactive)
18545 (cdlatex-environment environment item)
18546 (let ((element (org-element-at-point)))
18547 (org-indent-region (org-element-property :begin element)
18548 (org-element-property :end element))))
18551 ;;;; LaTeX fragments
18553 (defun org-inside-LaTeX-fragment-p ()
18554 "Test if point is inside a LaTeX fragment.
18555 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18556 sequence appearing also before point.
18557 Even though the matchers for math are configurable, this function assumes
18558 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18559 delimiters are skipped when they have been removed by customization.
18560 The return value is nil, or a cons cell with the delimiter and the
18561 position of this delimiter.
18563 This function does a reasonably good job, but can locally be fooled by
18564 for example currency specifications. For example it will assume being in
18565 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18566 fragments that are properly closed, but during editing, we have to live
18567 with the uncertainty caused by missing closing delimiters. This function
18568 looks only before point, not after."
18569 (catch 'exit
18570 (let ((pos (point))
18571 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18572 (lim (progn
18573 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18574 (point)))
18575 dd-on str (start 0) m re)
18576 (goto-char pos)
18577 (when dodollar
18578 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18579 re (nth 1 (assoc "$" org-latex-regexps)))
18580 (while (string-match re str start)
18581 (cond
18582 ((= (match-end 0) (length str))
18583 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18584 ((= (match-end 0) (- (length str) 5))
18585 (throw 'exit nil))
18586 (t (setq start (match-end 0))))))
18587 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18588 (goto-char pos)
18589 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18590 (and (match-beginning 2) (throw 'exit nil))
18591 ;; count $$
18592 (while (re-search-backward "\\$\\$" lim t)
18593 (setq dd-on (not dd-on)))
18594 (goto-char pos)
18595 (if dd-on (cons "$$" m))))))
18597 (defun org-inside-latex-macro-p ()
18598 "Is point inside a LaTeX macro or its arguments?"
18599 (save-match-data
18600 (org-in-regexp
18601 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18603 (defvar org-latex-fragment-image-overlays nil
18604 "List of overlays carrying the images of latex fragments.")
18605 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18607 (defun org-remove-latex-fragment-image-overlays ()
18608 "Remove all overlays with LaTeX fragment images in current buffer."
18609 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18610 (setq org-latex-fragment-image-overlays nil))
18612 (define-obsolete-function-alias
18613 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18614 (defun org-toggle-latex-fragment (&optional subtree)
18615 "Preview the LaTeX fragment at point, or all locally or globally.
18616 If the cursor is in a LaTeX fragment, create the image and overlay
18617 it over the source code. If there is no fragment at point, display
18618 all fragments in the current text, from one headline to the next. With
18619 prefix SUBTREE, display all fragments in the current subtree. With a
18620 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18621 the cursor is before the first headline,
18622 display all fragments in the buffer.
18623 The images can be removed again with \\[org-toggle-latex-fragment]."
18624 (interactive "P")
18625 (unless buffer-file-name
18626 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18627 (if org-latex-fragment-image-overlays
18628 (progn (org-remove-latex-fragment-image-overlays)
18629 (message "LaTeX fragments images removed"))
18630 (when (display-graphic-p)
18631 (org-remove-latex-fragment-image-overlays)
18632 (save-excursion
18633 (save-restriction
18634 (let (beg end at msg)
18635 (cond
18636 ((or (equal subtree '(16))
18637 (not (save-excursion
18638 (re-search-backward org-outline-regexp-bol nil t))))
18639 (setq beg (point-min) end (point-max)
18640 msg "Creating images for buffer...%s"))
18641 ((equal subtree '(4))
18642 (org-back-to-heading)
18643 (setq beg (point) end (org-end-of-subtree t)
18644 msg "Creating images for subtree...%s"))
18646 (if (setq at (org-inside-LaTeX-fragment-p))
18647 (goto-char (max (point-min) (- (cdr at) 2)))
18648 (org-back-to-heading))
18649 (setq beg (point) end (progn (outline-next-heading) (point))
18650 msg (if at "Creating image...%s"
18651 "Creating images for entry...%s"))))
18652 (message msg "")
18653 (narrow-to-region beg end)
18654 (goto-char beg)
18655 (org-format-latex
18656 (concat org-latex-preview-ltxpng-directory
18657 (file-name-sans-extension
18658 (file-name-nondirectory buffer-file-name)))
18659 default-directory 'overlays msg at 'forbuffer
18660 org-latex-create-formula-image-program)
18661 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18663 (defun org-format-latex (prefix &optional dir overlays msg at
18664 forbuffer processing-type)
18665 "Replace LaTeX fragments with links to an image, and produce images.
18666 Some of the options can be changed using the variable
18667 `org-format-latex-options'."
18668 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18669 (let* ((prefixnodir (file-name-nondirectory prefix))
18670 (absprefix (expand-file-name prefix dir))
18671 (todir (file-name-directory absprefix))
18672 (opt org-format-latex-options)
18673 (optnew org-format-latex-options)
18674 (matchers (plist-get opt :matchers))
18675 (re-list org-latex-regexps)
18676 (cnt 0) txt hash link beg end re e checkdir
18677 string
18678 m n block-type block linkfile movefile ov)
18679 ;; Check the different regular expressions
18680 (while (setq e (pop re-list))
18681 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18682 block (if block-type "\n\n" ""))
18683 (when (member m matchers)
18684 (goto-char (point-min))
18685 (while (re-search-forward re nil t)
18686 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18687 (or (not overlays)
18688 (not (eq (get-char-property (match-beginning n)
18689 'org-overlay-type)
18690 'org-latex-overlay))))
18691 (cond
18692 ((eq processing-type 'verbatim))
18693 ((eq processing-type 'mathjax)
18694 ;; Prepare for MathJax processing.
18695 (setq string (match-string n))
18696 (when (member m '("$" "$1"))
18697 (save-excursion
18698 (delete-region (match-beginning n) (match-end n))
18699 (goto-char (match-beginning n))
18700 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18701 ((or (eq processing-type 'dvipng)
18702 (eq processing-type 'imagemagick))
18703 ;; Process to an image.
18704 (setq txt (match-string n)
18705 beg (match-beginning n) end (match-end n)
18706 cnt (1+ cnt))
18707 (let ((face (face-at-point))
18708 (fg (plist-get opt :foreground))
18709 (bg (plist-get opt :background))
18710 ;; Ensure full list is printed.
18711 print-length print-level)
18712 (when forbuffer
18713 ;; Get the colors from the face at point.
18714 (goto-char beg)
18715 (when (eq fg 'auto)
18716 (setq fg (face-attribute face :foreground nil 'default)))
18717 (when (eq bg 'auto)
18718 (setq bg (face-attribute face :background nil 'default)))
18719 (setq optnew (copy-sequence opt))
18720 (plist-put optnew :foreground fg)
18721 (plist-put optnew :background bg))
18722 (setq hash (sha1 (prin1-to-string
18723 (list org-format-latex-header
18724 org-latex-default-packages-alist
18725 org-latex-packages-alist
18726 org-format-latex-options
18727 forbuffer txt fg bg)))
18728 linkfile (format "%s_%s.png" prefix hash)
18729 movefile (format "%s_%s.png" absprefix hash)))
18730 (setq link (concat block "[[file:" linkfile "]]" block))
18731 (if msg (message msg cnt))
18732 (goto-char beg)
18733 (unless checkdir ; Ensure the directory exists.
18734 (setq checkdir t)
18735 (or (file-directory-p todir) (make-directory todir t)))
18736 (unless (file-exists-p movefile)
18737 (org-create-formula-image
18738 txt movefile optnew forbuffer processing-type))
18739 (if overlays
18740 (progn
18741 (mapc (lambda (o)
18742 (if (eq (overlay-get o 'org-overlay-type)
18743 'org-latex-overlay)
18744 (delete-overlay o)))
18745 (overlays-in beg end))
18746 (setq ov (make-overlay beg end))
18747 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18748 (if (featurep 'xemacs)
18749 (progn
18750 (overlay-put ov 'invisible t)
18751 (overlay-put
18752 ov 'end-glyph
18753 (make-glyph (vector 'png :file movefile))))
18754 (overlay-put
18755 ov 'display
18756 (list 'image :type 'png :file movefile :ascent 'center)))
18757 (push ov org-latex-fragment-image-overlays)
18758 (goto-char end))
18759 (delete-region beg end)
18760 (insert (org-add-props link
18761 (list 'org-latex-src
18762 (replace-regexp-in-string
18763 "\"" "" txt)
18764 'org-latex-src-embed-type
18765 (if block-type 'paragraph 'character))))))
18766 ((eq processing-type 'mathml)
18767 ;; Process to MathML
18768 (unless (save-match-data (org-format-latex-mathml-available-p))
18769 (user-error "LaTeX to MathML converter not configured"))
18770 (setq txt (match-string n)
18771 beg (match-beginning n) end (match-end n)
18772 cnt (1+ cnt))
18773 (if msg (message msg cnt))
18774 (goto-char beg)
18775 (delete-region beg end)
18776 (insert (org-format-latex-as-mathml
18777 txt block-type prefix dir)))
18779 (error "Unknown conversion type %s for LaTeX fragments"
18780 processing-type)))))))))
18782 (defun org-create-math-formula (latex-frag &optional mathml-file)
18783 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18784 Use `org-latex-to-mathml-convert-command'. If the conversion is
18785 sucessful, return the portion between \"<math...> </math>\"
18786 elements otherwise return nil. When MATHML-FILE is specified,
18787 write the results in to that file. When invoked as an
18788 interactive command, prompt for LATEX-FRAG, with initial value
18789 set to the current active region and echo the results for user
18790 inspection."
18791 (interactive (list (let ((frag (when (org-region-active-p)
18792 (buffer-substring-no-properties
18793 (region-beginning) (region-end)))))
18794 (read-string "LaTeX Fragment: " frag nil frag))))
18795 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18796 (let* ((tmp-in-file (file-relative-name
18797 (make-temp-name (expand-file-name "ltxmathml-in"))))
18798 (ignore (write-region latex-frag nil tmp-in-file))
18799 (tmp-out-file (file-relative-name
18800 (make-temp-name (expand-file-name "ltxmathml-out"))))
18801 (cmd (format-spec
18802 org-latex-to-mathml-convert-command
18803 `((?j . ,(shell-quote-argument
18804 (expand-file-name org-latex-to-mathml-jar-file)))
18805 (?I . ,(shell-quote-argument tmp-in-file))
18806 (?o . ,(shell-quote-argument tmp-out-file)))))
18807 mathml shell-command-output)
18808 (when (org-called-interactively-p 'any)
18809 (unless (org-format-latex-mathml-available-p)
18810 (user-error "LaTeX to MathML converter not configured")))
18811 (message "Running %s" cmd)
18812 (setq shell-command-output (shell-command-to-string cmd))
18813 (setq mathml
18814 (when (file-readable-p tmp-out-file)
18815 (with-current-buffer (find-file-noselect tmp-out-file t)
18816 (goto-char (point-min))
18817 (when (re-search-forward
18818 (concat
18819 (regexp-quote
18820 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18821 "\\(.\\|\n\\)*"
18822 (regexp-quote "</math>")) nil t)
18823 (prog1 (match-string 0) (kill-buffer))))))
18824 (cond
18825 (mathml
18826 (setq mathml
18827 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18828 (when mathml-file
18829 (write-region mathml nil mathml-file))
18830 (when (org-called-interactively-p 'any)
18831 (message mathml)))
18832 ((message "LaTeX to MathML conversion failed")
18833 (message shell-command-output)))
18834 (delete-file tmp-in-file)
18835 (when (file-exists-p tmp-out-file)
18836 (delete-file tmp-out-file))
18837 mathml))
18839 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18840 prefix &optional dir)
18841 "Use `org-create-math-formula' but check local cache first."
18842 (let* ((absprefix (expand-file-name prefix dir))
18843 (print-length nil) (print-level nil)
18844 (formula-id (concat
18845 "formula-"
18846 (sha1
18847 (prin1-to-string
18848 (list latex-frag
18849 org-latex-to-mathml-convert-command)))))
18850 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18851 (formula-cache-dir (file-name-directory formula-cache)))
18853 (unless (file-directory-p formula-cache-dir)
18854 (make-directory formula-cache-dir t))
18856 (unless (file-exists-p formula-cache)
18857 (org-create-math-formula latex-frag formula-cache))
18859 (if (file-exists-p formula-cache)
18860 ;; Successful conversion. Return the link to MathML file.
18861 (org-add-props
18862 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18863 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18864 'org-latex-src-embed-type (if latex-frag-type
18865 'paragraph 'character)))
18866 ;; Failed conversion. Return the LaTeX fragment verbatim
18867 latex-frag)))
18869 (defun org-create-formula-image (string tofile options buffer &optional type)
18870 "Create an image from LaTeX source using dvipng or convert.
18871 This function calls either `org-create-formula-image-with-dvipng'
18872 or `org-create-formula-image-with-imagemagick' depending on the
18873 value of `org-latex-create-formula-image-program' or on the value
18874 of the optional TYPE variable.
18876 Note: ultimately these two function should be combined as they
18877 share a good deal of logic."
18878 (org-check-external-command
18879 "latex" "needed to convert LaTeX fragments to images")
18880 (funcall
18881 (case (or type org-latex-create-formula-image-program)
18882 ('dvipng
18883 (org-check-external-command
18884 "dvipng" "needed to convert LaTeX fragments to images")
18885 'org-create-formula-image-with-dvipng)
18886 ('imagemagick
18887 (org-check-external-command
18888 "convert" "you need to install imagemagick")
18889 'org-create-formula-image-with-imagemagick)
18890 (t (error
18891 "Invalid value of `org-latex-create-formula-image-program'")))
18892 string tofile options buffer))
18894 (declare-function org-export-get-backend "ox" (name))
18895 (declare-function org-export--get-global-options "ox" (&optional backend))
18896 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18897 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18898 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18899 (defun org-create-formula--latex-header ()
18900 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18901 (let ((info (org-combine-plists (org-export--get-global-options
18902 (org-export-get-backend 'latex))
18903 (org-export--get-inbuffer-options
18904 (org-export-get-backend 'latex)))))
18905 (org-latex-guess-babel-language
18906 (org-latex-guess-inputenc
18907 (org-splice-latex-header
18908 org-format-latex-header
18909 org-latex-default-packages-alist
18910 org-latex-packages-alist t
18911 (plist-get info :latex-header)))
18912 info)))
18914 ;; This function borrows from Ganesh Swami's latex2png.el
18915 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18916 "This calls dvipng."
18917 (require 'ox-latex)
18918 (let* ((tmpdir (if (featurep 'xemacs)
18919 (temp-directory)
18920 temporary-file-directory))
18921 (texfilebase (make-temp-name
18922 (expand-file-name "orgtex" tmpdir)))
18923 (texfile (concat texfilebase ".tex"))
18924 (dvifile (concat texfilebase ".dvi"))
18925 (pngfile (concat texfilebase ".png"))
18926 (fnh (if (featurep 'xemacs)
18927 (font-height (face-font 'default))
18928 (face-attribute 'default :height nil)))
18929 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18930 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18931 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18932 "Black"))
18933 (bg (or (plist-get options (if buffer :background :html-background))
18934 "Transparent")))
18935 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18936 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18937 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18938 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18939 (let ((latex-header (org-create-formula--latex-header)))
18940 (with-temp-file texfile
18941 (insert latex-header)
18942 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18943 (let ((dir default-directory))
18944 (ignore-errors
18945 (cd tmpdir)
18946 (call-process "latex" nil nil nil texfile))
18947 (cd dir))
18948 (if (not (file-exists-p dvifile))
18949 (progn (message "Failed to create dvi file from %s" texfile) nil)
18950 (ignore-errors
18951 (if (featurep 'xemacs)
18952 (call-process "dvipng" nil nil nil
18953 "-fg" fg "-bg" bg
18954 "-T" "tight"
18955 "-o" pngfile
18956 dvifile)
18957 (call-process "dvipng" nil nil nil
18958 "-fg" fg "-bg" bg
18959 "-D" dpi
18960 ;;"-x" scale "-y" scale
18961 "-T" "tight"
18962 "-o" pngfile
18963 dvifile)))
18964 (if (not (file-exists-p pngfile))
18965 (if org-format-latex-signal-error
18966 (error "Failed to create png file from %s" texfile)
18967 (message "Failed to create png file from %s" texfile)
18968 nil)
18969 ;; Use the requested file name and clean up
18970 (copy-file pngfile tofile 'replace)
18971 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18972 (if (file-exists-p (concat texfilebase e))
18973 (delete-file (concat texfilebase e))))
18974 pngfile))))
18976 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18977 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18978 "This calls convert, which is included into imagemagick."
18979 (require 'ox-latex)
18980 (let* ((tmpdir (if (featurep 'xemacs)
18981 (temp-directory)
18982 temporary-file-directory))
18983 (texfilebase (make-temp-name
18984 (expand-file-name "orgtex" tmpdir)))
18985 (texfile (concat texfilebase ".tex"))
18986 (pdffile (concat texfilebase ".pdf"))
18987 (pngfile (concat texfilebase ".png"))
18988 (fnh (if (featurep 'xemacs)
18989 (font-height (face-font 'default))
18990 (face-attribute 'default :height nil)))
18991 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18992 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18993 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18994 "black"))
18995 (bg (or (plist-get options (if buffer :background :html-background))
18996 "white")))
18997 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18998 (setq fg (org-latex-color-format fg)))
18999 (if (eq bg 'default) (setq bg (org-latex-color :background))
19000 (setq bg (org-latex-color-format
19001 (if (string= bg "Transparent") "white" bg))))
19002 (let ((latex-header (org-create-formula--latex-header)))
19003 (with-temp-file texfile
19004 (insert latex-header)
19005 (insert "\n\\begin{document}\n"
19006 "\\definecolor{fg}{rgb}{" fg "}\n"
19007 "\\definecolor{bg}{rgb}{" bg "}\n"
19008 "\n\\pagecolor{bg}\n"
19009 "\n{\\color{fg}\n"
19010 string
19011 "\n}\n"
19012 "\n\\end{document}\n")))
19013 (org-latex-compile texfile t)
19014 (if (not (file-exists-p pdffile))
19015 (progn (message "Failed to create pdf file from %s" texfile) nil)
19016 (ignore-errors
19017 (if (featurep 'xemacs)
19018 (call-process "convert" nil nil nil
19019 "-density" "96"
19020 "-trim"
19021 "-antialias"
19022 pdffile
19023 "-quality" "100"
19024 ;; "-sharpen" "0x1.0"
19025 pngfile)
19026 (call-process "convert" nil nil nil
19027 "-density" dpi
19028 "-trim"
19029 "-antialias"
19030 pdffile
19031 "-quality" "100"
19032 ;; "-sharpen" "0x1.0"
19033 pngfile)))
19034 (if (not (file-exists-p pngfile))
19035 (if org-format-latex-signal-error
19036 (error "Failed to create png file from %s" texfile)
19037 (message "Failed to create png file from %s" texfile)
19038 nil)
19039 ;; Use the requested file name and clean up
19040 (copy-file pngfile tofile 'replace)
19041 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19042 (if (file-exists-p (concat texfilebase e))
19043 (delete-file (concat texfilebase e))))
19044 pngfile))))
19046 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19047 "Fill a LaTeX header template TPL.
19048 In the template, the following place holders will be recognized:
19050 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19051 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19052 [PACKAGES] \\usepackage statements for PKG
19053 [NO-PACKAGES] do not include PKG
19054 [EXTRA] the string EXTRA
19055 [NO-EXTRA] do not include EXTRA
19057 For backward compatibility, if both the positive and the negative place
19058 holder is missing, the positive one (without the \"NO-\") will be
19059 assumed to be present at the end of the template.
19060 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19061 EXTRA is a string.
19062 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19063 (let (rpl (end ""))
19064 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19065 (setq rpl (if (or (match-end 1) (not def-pkg))
19066 "" (org-latex-packages-to-string def-pkg snippets-p t))
19067 tpl (replace-match rpl t t tpl))
19068 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19070 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19071 (setq rpl (if (or (match-end 1) (not pkg))
19072 "" (org-latex-packages-to-string pkg snippets-p t))
19073 tpl (replace-match rpl t t tpl))
19074 (if pkg (setq end
19075 (concat end "\n"
19076 (org-latex-packages-to-string pkg snippets-p)))))
19078 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19079 (setq rpl (if (or (match-end 1) (not extra))
19080 "" (concat extra "\n"))
19081 tpl (replace-match rpl t t tpl))
19082 (if (and extra (string-match "\\S-" extra))
19083 (setq end (concat end "\n" extra))))
19085 (if (string-match "\\S-" end)
19086 (concat tpl "\n" end)
19087 tpl)))
19089 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19090 "Turn an alist of packages into a string with the \\usepackage macros."
19091 (setq pkg (mapconcat (lambda(p)
19092 (cond
19093 ((stringp p) p)
19094 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19095 (format "%% Package %s omitted" (cadr p)))
19096 ((equal "" (car p))
19097 (format "\\usepackage{%s}" (cadr p)))
19099 (format "\\usepackage[%s]{%s}"
19100 (car p) (cadr p)))))
19102 "\n"))
19103 (if newline (concat pkg "\n") pkg))
19105 (defun org-dvipng-color (attr)
19106 "Return a RGB color specification for dvipng."
19107 (apply 'format "rgb %s %s %s"
19108 (mapcar 'org-normalize-color
19109 (if (featurep 'xemacs)
19110 (color-rgb-components
19111 (face-property 'default
19112 (cond ((eq attr :foreground) 'foreground)
19113 ((eq attr :background) 'background))))
19114 (color-values (face-attribute 'default attr nil))))))
19116 (defun org-dvipng-color-format (color-name)
19117 "Convert COLOR-NAME to a RGB color value for dvipng."
19118 (apply 'format "rgb %s %s %s"
19119 (mapcar 'org-normalize-color
19120 (color-values color-name))))
19122 (defun org-latex-color (attr)
19123 "Return a RGB color for the LaTeX color package."
19124 (apply 'format "%s,%s,%s"
19125 (mapcar 'org-normalize-color
19126 (if (featurep 'xemacs)
19127 (color-rgb-components
19128 (face-property 'default
19129 (cond ((eq attr :foreground) 'foreground)
19130 ((eq attr :background) 'background))))
19131 (color-values (face-attribute 'default attr nil))))))
19133 (defun org-latex-color-format (color-name)
19134 "Convert COLOR-NAME to a RGB color value."
19135 (apply 'format "%s,%s,%s"
19136 (mapcar 'org-normalize-color
19137 (color-values color-name))))
19139 (defun org-normalize-color (value)
19140 "Return string to be used as color value for an RGB component."
19141 (format "%g" (/ value 65535.0)))
19145 ;; Image display
19147 (defvar org-inline-image-overlays nil)
19148 (make-variable-buffer-local 'org-inline-image-overlays)
19150 (defun org-toggle-inline-images (&optional include-linked)
19151 "Toggle the display of inline images.
19152 INCLUDE-LINKED is passed to `org-display-inline-images'."
19153 (interactive "P")
19154 (if org-inline-image-overlays
19155 (progn
19156 (org-remove-inline-images)
19157 (message "Inline image display turned off"))
19158 (org-display-inline-images include-linked)
19159 (if (and (org-called-interactively-p)
19160 org-inline-image-overlays)
19161 (message "%d images displayed inline"
19162 (length org-inline-image-overlays))
19163 (message "No images to display inline"))))
19165 (defun org-redisplay-inline-images ()
19166 "Refresh the display of inline images."
19167 (interactive)
19168 (if (not org-inline-image-overlays)
19169 (org-toggle-inline-images)
19170 (org-toggle-inline-images)
19171 (org-toggle-inline-images)))
19173 (defun org-display-inline-images (&optional include-linked refresh beg end)
19174 "Display inline images.
19176 An inline image is a link which follows either of these
19177 conventions:
19179 1. Its path is a file with an extension matching return value
19180 from `image-file-name-regexp' and it has no contents.
19182 2. Its description consists in a single link of the previous
19183 type.
19185 When optional argument INCLUDE-LINKED is non-nil, also links with
19186 a text description part will be inlined. This can be nice for
19187 a quick look at those images, but it does not reflect what
19188 exported files will look like.
19190 When optional argument REFRESH is non-nil, refresh existing
19191 images between BEG and END. This will create new image displays
19192 only if necessary. BEG and END default to the buffer
19193 boundaries."
19194 (interactive "P")
19195 (when (display-graphic-p)
19196 (unless refresh
19197 (org-remove-inline-images)
19198 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19199 (org-with-wide-buffer
19200 (goto-char (or beg (point-min)))
19201 (let ((case-fold-search t)
19202 (file-extension-re (org-image-file-name-regexp)))
19203 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19204 (let ((link (save-match-data (org-element-context))))
19205 ;; Check if we're at an inline image.
19206 (when (and (equal (org-element-property :type link) "file")
19207 (or include-linked
19208 (not (org-element-property :contents-begin link)))
19209 (let ((parent (org-element-property :parent link)))
19210 (or (not (eq (org-element-type parent) 'link))
19211 (not (cdr (org-element-contents parent)))))
19212 (org-string-match-p file-extension-re
19213 (org-element-property :path link)))
19214 (let ((file (expand-file-name (org-element-property :path link))))
19215 (when (file-exists-p file)
19216 (let ((width
19217 ;; Apply `org-image-actual-width' specifications.
19218 (cond
19219 ((not (image-type-available-p 'imagemagick)) nil)
19220 ((eq org-image-actual-width t) nil)
19221 ((listp org-image-actual-width)
19223 ;; First try to find a width among
19224 ;; attributes associated to the paragraph
19225 ;; containing link.
19226 (let ((paragraph
19227 (let ((e link))
19228 (while (and (setq e (org-element-property
19229 :parent e))
19230 (not (eq (org-element-type e)
19231 'paragraph))))
19232 e)))
19233 (when paragraph
19234 (save-excursion
19235 (goto-char (org-element-property :begin paragraph))
19236 (when
19237 (re-search-forward
19238 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19239 (org-element-property
19240 :post-affiliated paragraph)
19242 (string-to-number (match-string 1))))))
19243 ;; Otherwise, fall-back to provided number.
19244 (car org-image-actual-width)))
19245 ((numberp org-image-actual-width)
19246 org-image-actual-width)))
19247 (old (get-char-property-and-overlay
19248 (org-element-property :begin link)
19249 'org-image-overlay)))
19250 (if (and (car-safe old) refresh)
19251 (image-refresh (overlay-get (cdr old) 'display))
19252 (let ((image (create-image file
19253 (and width 'imagemagick)
19255 :width width)))
19256 (when image
19257 (let* ((link
19258 ;; If inline image is the description
19259 ;; of another link, be sure to
19260 ;; consider the latter as the one to
19261 ;; apply the overlay on.
19262 (let ((parent
19263 (org-element-property :parent link)))
19264 (if (eq (org-element-type parent) 'link)
19265 parent
19266 link)))
19267 (ov (make-overlay
19268 (org-element-property :begin link)
19269 (progn
19270 (goto-char
19271 (org-element-property :end link))
19272 (skip-chars-backward " \t")
19273 (point)))))
19274 (overlay-put ov 'display image)
19275 (overlay-put ov 'face 'default)
19276 (overlay-put ov 'org-image-overlay t)
19277 (overlay-put
19278 ov 'modification-hooks
19279 (list 'org-display-inline-remove-overlay))
19280 (push ov org-inline-image-overlays)))))))))))))))
19282 (define-obsolete-function-alias
19283 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19285 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19286 "Remove inline-display overlay if a corresponding region is modified."
19287 (let ((inhibit-modification-hooks t))
19288 (when (and ov after)
19289 (delete ov org-inline-image-overlays)
19290 (delete-overlay ov))))
19292 (defun org-remove-inline-images ()
19293 "Remove inline display of images."
19294 (interactive)
19295 (mapc 'delete-overlay org-inline-image-overlays)
19296 (setq org-inline-image-overlays nil))
19298 ;;;; Key bindings
19300 ;; Outline functions from `outline-mode-prefix-map'
19301 ;; that can be remapped in Org:
19302 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19303 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19304 (define-key org-mode-map [remap outline-forward-same-level]
19305 'org-forward-heading-same-level)
19306 (define-key org-mode-map [remap outline-backward-same-level]
19307 'org-backward-heading-same-level)
19308 (define-key org-mode-map [remap show-branches]
19309 'org-kill-note-or-show-branches)
19310 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19311 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19312 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19314 ;; Outline functions from `outline-mode-prefix-map' that can not
19315 ;; be remapped in Org:
19317 ;; - the column "key binding" shows whether the Outline function is still
19318 ;; available in Org mode on the same key that it has been bound to in
19319 ;; Outline mode:
19320 ;; - "overridden": key used for a different functionality in Org mode
19321 ;; - else: key still bound to the same Outline function in Org mode
19323 ;; | Outline function | key binding | Org replacement |
19324 ;; |------------------------------------+-------------+-----------------------|
19325 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19326 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19327 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19328 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19329 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19330 ;; | `show-entry' | overridden | no replacement |
19331 ;; | `show-children' | `C-c C-i' | visibility cycling |
19332 ;; | `show-branches' | `C-c C-k' | still same function |
19333 ;; | `show-subtree' | overridden | visibility cycling |
19334 ;; | `show-all' | overridden | no replacement |
19335 ;; | `hide-subtree' | overridden | visibility cycling |
19336 ;; | `hide-body' | overridden | no replacement |
19337 ;; | `hide-entry' | overridden | visibility cycling |
19338 ;; | `hide-leaves' | overridden | no replacement |
19339 ;; | `hide-sublevels' | overridden | no replacement |
19340 ;; | `hide-other' | overridden | no replacement |
19342 ;; Make `C-c C-x' a prefix key
19343 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19345 ;; TAB key with modifiers
19346 (org-defkey org-mode-map "\C-i" 'org-cycle)
19347 (org-defkey org-mode-map [(tab)] 'org-cycle)
19348 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19349 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19350 ;; The following line is necessary under Suse GNU/Linux
19351 (unless (featurep 'xemacs)
19352 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19353 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19354 (define-key org-mode-map [backtab] 'org-shifttab)
19356 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19357 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19358 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19360 ;; Cursor keys with modifiers
19361 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19362 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19363 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19364 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19366 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19367 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19368 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19369 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19370 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19371 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19373 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19374 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19375 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19376 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19378 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19379 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19380 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19381 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19383 ;; Babel keys
19384 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19385 (mapc (lambda (pair)
19386 (define-key org-babel-map (car pair) (cdr pair)))
19387 org-babel-key-bindings)
19389 ;;; Extra keys for tty access.
19390 ;; We only set them when really needed because otherwise the
19391 ;; menus don't show the simple keys
19393 (when (or org-use-extra-keys
19394 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19395 (not window-system))
19396 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19397 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19398 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19399 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19400 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19401 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19402 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19403 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19404 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19405 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19406 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19407 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19408 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19409 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19410 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19411 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19412 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19413 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19414 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19415 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19416 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19417 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19418 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19419 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19420 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19421 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19422 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19423 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19425 ;; All the other keys
19427 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19428 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19429 (if (boundp 'narrow-map)
19430 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19431 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19432 (if (boundp 'narrow-map)
19433 (org-defkey narrow-map "b" 'org-narrow-to-block)
19434 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19435 (if (boundp 'narrow-map)
19436 (org-defkey narrow-map "e" 'org-narrow-to-element)
19437 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19438 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19439 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19440 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19441 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19442 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19443 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19444 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19445 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19446 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19447 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19448 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19449 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19450 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19451 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19452 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19453 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19454 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19455 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19456 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19457 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19458 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19459 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19460 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19461 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19462 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19463 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19464 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19465 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19466 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19467 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19468 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19469 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19470 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19471 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19472 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19473 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19474 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19475 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19476 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19477 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19478 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19479 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19480 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19481 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19482 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19483 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19484 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19485 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19486 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19487 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19488 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19489 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19490 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19491 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19492 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19493 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19494 (org-defkey org-mode-map "\C-c^" 'org-sort)
19495 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19496 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19497 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19498 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19499 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19500 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19501 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19502 (org-defkey org-mode-map "\C-m" 'org-return)
19503 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19504 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19505 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19506 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19507 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19508 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19509 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19510 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19511 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19512 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19513 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19514 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19515 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19516 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19517 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19518 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19519 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19520 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19521 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19522 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19523 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19524 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19525 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19526 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19527 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19529 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19530 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19531 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19533 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19534 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19535 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19536 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19537 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19538 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19539 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19540 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19541 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19542 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19543 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19544 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19545 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19546 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19547 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19548 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19549 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19550 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19551 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19552 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19553 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19554 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19555 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19557 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19558 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19559 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19560 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19561 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19563 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19565 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19567 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19568 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19570 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19573 (when (featurep 'xemacs)
19574 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19577 (defconst org-speed-commands-default
19579 ("Outline Navigation")
19580 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19581 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19582 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19583 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19584 ("F" . org-next-block)
19585 ("B" . org-previous-block)
19586 ("u" . (org-speed-move-safe 'outline-up-heading))
19587 ("j" . org-goto)
19588 ("g" . (org-refile t))
19589 ("Outline Visibility")
19590 ("c" . org-cycle)
19591 ("C" . org-shifttab)
19592 (" " . org-display-outline-path)
19593 ("s" . org-narrow-to-subtree)
19594 ("=" . org-columns)
19595 ("Outline Structure Editing")
19596 ("U" . org-metaup)
19597 ("D" . org-metadown)
19598 ("r" . org-metaright)
19599 ("l" . org-metaleft)
19600 ("R" . org-shiftmetaright)
19601 ("L" . org-shiftmetaleft)
19602 ("i" . (progn (forward-char 1) (call-interactively
19603 'org-insert-heading-respect-content)))
19604 ("^" . org-sort)
19605 ("w" . org-refile)
19606 ("a" . org-archive-subtree-default-with-confirmation)
19607 ("@" . org-mark-subtree)
19608 ("#" . org-toggle-comment)
19609 ("Clock Commands")
19610 ("I" . org-clock-in)
19611 ("O" . org-clock-out)
19612 ("Meta Data Editing")
19613 ("t" . org-todo)
19614 ("," . (org-priority))
19615 ("0" . (org-priority ?\ ))
19616 ("1" . (org-priority ?A))
19617 ("2" . (org-priority ?B))
19618 ("3" . (org-priority ?C))
19619 (":" . org-set-tags-command)
19620 ("e" . org-set-effort)
19621 ("E" . org-inc-effort)
19622 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19623 (org-entry-put (point) "APPT_WARNTIME" m)))
19624 ("Agenda Views etc")
19625 ("v" . org-agenda)
19626 ("/" . org-sparse-tree)
19627 ("Misc")
19628 ("o" . org-open-at-point)
19629 ("?" . org-speed-command-help)
19630 ("<" . (org-agenda-set-restriction-lock 'subtree))
19631 (">" . (org-agenda-remove-restriction-lock))
19633 "The default speed commands.")
19635 (defun org-print-speed-command (e)
19636 (if (> (length (car e)) 1)
19637 (progn
19638 (princ "\n")
19639 (princ (car e))
19640 (princ "\n")
19641 (princ (make-string (length (car e)) ?-))
19642 (princ "\n"))
19643 (princ (car e))
19644 (princ " ")
19645 (if (symbolp (cdr e))
19646 (princ (symbol-name (cdr e)))
19647 (prin1 (cdr e)))
19648 (princ "\n")))
19650 (defun org-speed-command-help ()
19651 "Show the available speed commands."
19652 (interactive)
19653 (if (not org-use-speed-commands)
19654 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19655 (with-output-to-temp-buffer "*Help*"
19656 (princ "User-defined Speed commands\n===========================\n")
19657 (mapc 'org-print-speed-command org-speed-commands-user)
19658 (princ "\n")
19659 (princ "Built-in Speed commands\n=======================\n")
19660 (mapc 'org-print-speed-command org-speed-commands-default))
19661 (with-current-buffer "*Help*"
19662 (setq truncate-lines t))))
19664 (defun org-speed-move-safe (cmd)
19665 "Execute CMD, but make sure that the cursor always ends up in a headline.
19666 If not, return to the original position and throw an error."
19667 (interactive)
19668 (let ((pos (point)))
19669 (call-interactively cmd)
19670 (unless (and (bolp) (org-at-heading-p))
19671 (goto-char pos)
19672 (error "Boundary reached while executing %s" cmd))))
19674 (defvar org-self-insert-command-undo-counter 0)
19676 (defvar org-table-auto-blank-field) ; defined in org-table.el
19677 (defvar org-speed-command nil)
19679 (define-obsolete-function-alias
19680 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19682 (defun org-speed-command-activate (keys)
19683 "Hook for activating single-letter speed commands.
19684 `org-speed-commands-default' specifies a minimal command set.
19685 Use `org-speed-commands-user' for further customization."
19686 (when (or (and (bolp) (looking-at org-outline-regexp))
19687 (and (functionp org-use-speed-commands)
19688 (funcall org-use-speed-commands)))
19689 (cdr (assoc keys (append org-speed-commands-user
19690 org-speed-commands-default)))))
19692 (define-obsolete-function-alias
19693 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19695 (defun org-babel-speed-command-activate (keys)
19696 "Hook for activating single-letter code block commands."
19697 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19698 (cdr (assoc keys org-babel-key-bindings))))
19700 (defcustom org-speed-command-hook
19701 '(org-speed-command-default-hook org-babel-speed-command-hook)
19702 "Hook for activating speed commands at strategic locations.
19703 Hook functions are called in sequence until a valid handler is
19704 found.
19706 Each hook takes a single argument, a user-pressed command key
19707 which is also a `self-insert-command' from the global map.
19709 Within the hook, examine the cursor position and the command key
19710 and return nil or a valid handler as appropriate. Handler could
19711 be one of an interactive command, a function, or a form.
19713 Set `org-use-speed-commands' to non-nil value to enable this
19714 hook. The default setting is `org-speed-command-activate'."
19715 :group 'org-structure
19716 :version "24.1"
19717 :type 'hook)
19719 (defun org-self-insert-command (N)
19720 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19721 If the cursor is in a table looking at whitespace, the whitespace is
19722 overwritten, and the table is not marked as requiring realignment."
19723 (interactive "p")
19724 (org-check-before-invisible-edit 'insert)
19725 (cond
19726 ((and org-use-speed-commands
19727 (let ((kv (this-command-keys-vector)))
19728 (setq org-speed-command
19729 (run-hook-with-args-until-success
19730 'org-speed-command-hook
19731 (make-string 1 (aref kv (1- (length kv))))))))
19732 (cond
19733 ((commandp org-speed-command)
19734 (setq this-command org-speed-command)
19735 (call-interactively org-speed-command))
19736 ((functionp org-speed-command)
19737 (funcall org-speed-command))
19738 ((and org-speed-command (listp org-speed-command))
19739 (eval org-speed-command))
19740 (t (let (org-use-speed-commands)
19741 (call-interactively 'org-self-insert-command)))))
19742 ((and
19743 (org-table-p)
19744 (progn
19745 ;; check if we blank the field, and if that triggers align
19746 (and (featurep 'org-table) org-table-auto-blank-field
19747 (member last-command
19748 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19749 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19750 ;; got extra space, this field does not determine column width
19751 (let (org-table-may-need-update) (org-table-blank-field))
19752 ;; no extra space, this field may determine column width
19753 (org-table-blank-field)))
19755 (eq N 1)
19756 (looking-at "[^|\n]* |"))
19757 (let (org-table-may-need-update)
19758 (goto-char (1- (match-end 0)))
19759 (backward-delete-char 1)
19760 (goto-char (match-beginning 0))
19761 (self-insert-command N)))
19763 (setq org-table-may-need-update t)
19764 (self-insert-command N)
19765 (org-fix-tags-on-the-fly)
19766 (if org-self-insert-cluster-for-undo
19767 (if (not (eq last-command 'org-self-insert-command))
19768 (setq org-self-insert-command-undo-counter 1)
19769 (if (>= org-self-insert-command-undo-counter 20)
19770 (setq org-self-insert-command-undo-counter 1)
19771 (and (> org-self-insert-command-undo-counter 0)
19772 buffer-undo-list (listp buffer-undo-list)
19773 (not (cadr buffer-undo-list)) ; remove nil entry
19774 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19775 (setq org-self-insert-command-undo-counter
19776 (1+ org-self-insert-command-undo-counter))))))))
19778 (defun org-check-before-invisible-edit (kind)
19779 "Check is editing if kind KIND would be dangerous with invisible text around.
19780 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19781 ;; First, try to get out of here as quickly as possible, to reduce overhead
19782 (if (and org-catch-invisible-edits
19783 (or (not (boundp 'visible-mode)) (not visible-mode))
19784 (or (get-char-property (point) 'invisible)
19785 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19786 ;; OK, we need to take a closer look
19787 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19788 (invisible-before-point (if (bobp) nil (get-char-property
19789 (1- (point)) 'invisible)))
19790 (border-and-ok-direction
19792 ;; Check if we are acting predictably before invisible text
19793 (and invisible-at-point (not invisible-before-point)
19794 (memq kind '(insert delete-backward)))
19795 ;; Check if we are acting predictably after invisible text
19796 ;; This works not well, and I have turned it off. It seems
19797 ;; better to always show and stop after invisible text.
19798 ;; (and (not invisible-at-point) invisible-before-point
19799 ;; (memq kind '(insert delete)))
19801 (when (or (memq invisible-at-point '(outline org-hide-block t))
19802 (memq invisible-before-point '(outline org-hide-block t)))
19803 (if (eq org-catch-invisible-edits 'error)
19804 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19805 (if (and org-custom-properties-overlays
19806 (y-or-n-p "Display invisible properties in this buffer? "))
19807 (org-toggle-custom-properties-visibility)
19808 ;; Make the area visible
19809 (save-excursion
19810 (if invisible-before-point
19811 (goto-char (previous-single-char-property-change
19812 (point) 'invisible)))
19813 (show-subtree))
19814 (cond
19815 ((eq org-catch-invisible-edits 'show)
19816 ;; That's it, we do the edit after showing
19817 (message
19818 "Unfolding invisible region around point before editing")
19819 (sit-for 1))
19820 ((and (eq org-catch-invisible-edits 'smart)
19821 border-and-ok-direction)
19822 (message "Unfolding invisible region around point before editing"))
19824 ;; Don't do the edit, make the user repeat it in full visibility
19825 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19827 (defun org-fix-tags-on-the-fly ()
19828 (when (and (equal (char-after (point-at-bol)) ?*)
19829 (org-at-heading-p))
19830 (org-align-tags-here org-tags-column)))
19832 (defun org-delete-backward-char (N)
19833 "Like `delete-backward-char', insert whitespace at field end in tables.
19834 When deleting backwards, in tables this function will insert whitespace in
19835 front of the next \"|\" separator, to keep the table aligned. The table will
19836 still be marked for re-alignment if the field did fill the entire column,
19837 because, in this case the deletion might narrow the column."
19838 (interactive "p")
19839 (save-match-data
19840 (org-check-before-invisible-edit 'delete-backward)
19841 (if (and (org-table-p)
19842 (eq N 1)
19843 (string-match "|" (buffer-substring (point-at-bol) (point)))
19844 (looking-at ".*?|"))
19845 (let ((pos (point))
19846 (noalign (looking-at "[^|\n\r]* |"))
19847 (c org-table-may-need-update))
19848 (backward-delete-char N)
19849 (if (not overwrite-mode)
19850 (progn
19851 (skip-chars-forward "^|")
19852 (insert " ")
19853 (goto-char (1- pos))))
19854 ;; noalign: if there were two spaces at the end, this field
19855 ;; does not determine the width of the column.
19856 (if noalign (setq org-table-may-need-update c)))
19857 (backward-delete-char N)
19858 (org-fix-tags-on-the-fly))))
19860 (defun org-delete-char (N)
19861 "Like `delete-char', but insert whitespace at field end in tables.
19862 When deleting characters, in tables this function will insert whitespace in
19863 front of the next \"|\" separator, to keep the table aligned. The table will
19864 still be marked for re-alignment if the field did fill the entire column,
19865 because, in this case the deletion might narrow the column."
19866 (interactive "p")
19867 (save-match-data
19868 (org-check-before-invisible-edit 'delete)
19869 (if (and (org-table-p)
19870 (not (bolp))
19871 (not (= (char-after) ?|))
19872 (eq N 1))
19873 (if (looking-at ".*?|")
19874 (let ((pos (point))
19875 (noalign (looking-at "[^|\n\r]* |"))
19876 (c org-table-may-need-update))
19877 (replace-match
19878 (concat (substring (match-string 0) 1 -1) " |") nil t)
19879 (goto-char pos)
19880 ;; noalign: if there were two spaces at the end, this field
19881 ;; does not determine the width of the column.
19882 (if noalign (setq org-table-may-need-update c)))
19883 (delete-char N))
19884 (delete-char N)
19885 (org-fix-tags-on-the-fly))))
19887 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19888 (put 'org-self-insert-command 'delete-selection
19889 (lambda ()
19890 (not (run-hook-with-args-until-success
19891 'self-insert-uses-region-functions))))
19892 (put 'orgtbl-self-insert-command 'delete-selection
19893 (lambda ()
19894 (not (run-hook-with-args-until-success
19895 'self-insert-uses-region-functions))))
19896 (put 'org-delete-char 'delete-selection 'supersede)
19897 (put 'org-delete-backward-char 'delete-selection 'supersede)
19898 (put 'org-yank 'delete-selection 'yank)
19900 ;; Make `flyspell-mode' delay after some commands
19901 (put 'org-self-insert-command 'flyspell-delayed t)
19902 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19903 (put 'org-delete-char 'flyspell-delayed t)
19904 (put 'org-delete-backward-char 'flyspell-delayed t)
19906 ;; Make pabbrev-mode expand after org-mode commands
19907 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19908 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19910 (defun org-remap (map &rest commands)
19911 "In MAP, remap the functions given in COMMANDS.
19912 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19913 (let (new old)
19914 (while commands
19915 (setq old (pop commands) new (pop commands))
19916 (if (fboundp 'command-remapping)
19917 (org-defkey map (vector 'remap old) new)
19918 (substitute-key-definition old new map global-map)))))
19920 (defun org-transpose-words ()
19921 "Transpose words for Org.
19922 This uses the `org-mode-transpose-word-syntax-table' syntax
19923 table, which interprets characters in `org-emphasis-alist' as
19924 word constituents."
19925 (interactive)
19926 (with-syntax-table org-mode-transpose-word-syntax-table
19927 (call-interactively 'transpose-words)))
19928 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19930 (when (eq org-enable-table-editor 'optimized)
19931 ;; If the user wants maximum table support, we need to hijack
19932 ;; some standard editing functions
19933 (org-remap org-mode-map
19934 'self-insert-command 'org-self-insert-command
19935 'delete-char 'org-delete-char
19936 'delete-backward-char 'org-delete-backward-char)
19937 (org-defkey org-mode-map "|" 'org-force-self-insert))
19939 (defvar org-ctrl-c-ctrl-c-hook nil
19940 "Hook for functions attaching themselves to `C-c C-c'.
19942 This can be used to add additional functionality to the C-c C-c
19943 key which executes context-dependent commands. This hook is run
19944 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19945 run after the last test.
19947 Each function will be called with no arguments. The function
19948 must check if the context is appropriate for it to act. If yes,
19949 it should do its thing and then return a non-nil value. If the
19950 context is wrong, just do nothing and return nil.")
19952 (defvar org-ctrl-c-ctrl-c-final-hook nil
19953 "Hook for functions attaching themselves to `C-c C-c'.
19955 This can be used to add additional functionality to the C-c C-c
19956 key which executes context-dependent commands. This hook is run
19957 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19958 before the first test.
19960 Each function will be called with no arguments. The function
19961 must check if the context is appropriate for it to act. If yes,
19962 it should do its thing and then return a non-nil value. If the
19963 context is wrong, just do nothing and return nil.")
19965 (defvar org-tab-first-hook nil
19966 "Hook for functions to attach themselves to TAB.
19967 See `org-ctrl-c-ctrl-c-hook' for more information.
19968 This hook runs as the first action when TAB is pressed, even before
19969 `org-cycle' messes around with the `outline-regexp' to cater for
19970 inline tasks and plain list item folding.
19971 If any function in this hook returns t, any other actions that
19972 would have been caused by TAB (such as table field motion or visibility
19973 cycling) will not occur.")
19975 (defvar org-tab-after-check-for-table-hook nil
19976 "Hook for functions to attach themselves to TAB.
19977 See `org-ctrl-c-ctrl-c-hook' for more information.
19978 This hook runs after it has been established that the cursor is not in a
19979 table, but before checking if the cursor is in a headline or if global cycling
19980 should be done.
19981 If any function in this hook returns t, not other actions like visibility
19982 cycling will be done.")
19984 (defvar org-tab-after-check-for-cycling-hook nil
19985 "Hook for functions to attach themselves to TAB.
19986 See `org-ctrl-c-ctrl-c-hook' for more information.
19987 This hook runs after it has been established that not table field motion and
19988 not visibility should be done because of current context. This is probably
19989 the place where a package like yasnippets can hook in.")
19991 (defvar org-tab-before-tab-emulation-hook nil
19992 "Hook for functions to attach themselves to TAB.
19993 See `org-ctrl-c-ctrl-c-hook' for more information.
19994 This hook runs after every other options for TAB have been exhausted, but
19995 before indentation and \t insertion takes place.")
19997 (defvar org-metaleft-hook nil
19998 "Hook for functions attaching themselves to `M-left'.
19999 See `org-ctrl-c-ctrl-c-hook' for more information.")
20000 (defvar org-metaright-hook nil
20001 "Hook for functions attaching themselves to `M-right'.
20002 See `org-ctrl-c-ctrl-c-hook' for more information.")
20003 (defvar org-metaup-hook nil
20004 "Hook for functions attaching themselves to `M-up'.
20005 See `org-ctrl-c-ctrl-c-hook' for more information.")
20006 (defvar org-metadown-hook nil
20007 "Hook for functions attaching themselves to `M-down'.
20008 See `org-ctrl-c-ctrl-c-hook' for more information.")
20009 (defvar org-shiftmetaleft-hook nil
20010 "Hook for functions attaching themselves to `M-S-left'.
20011 See `org-ctrl-c-ctrl-c-hook' for more information.")
20012 (defvar org-shiftmetaright-hook nil
20013 "Hook for functions attaching themselves to `M-S-right'.
20014 See `org-ctrl-c-ctrl-c-hook' for more information.")
20015 (defvar org-shiftmetaup-hook nil
20016 "Hook for functions attaching themselves to `M-S-up'.
20017 See `org-ctrl-c-ctrl-c-hook' for more information.")
20018 (defvar org-shiftmetadown-hook nil
20019 "Hook for functions attaching themselves to `M-S-down'.
20020 See `org-ctrl-c-ctrl-c-hook' for more information.")
20021 (defvar org-metareturn-hook nil
20022 "Hook for functions attaching themselves to `M-RET'.
20023 See `org-ctrl-c-ctrl-c-hook' for more information.")
20024 (defvar org-shiftup-hook nil
20025 "Hook for functions attaching themselves to `S-up'.
20026 See `org-ctrl-c-ctrl-c-hook' for more information.")
20027 (defvar org-shiftup-final-hook nil
20028 "Hook for functions attaching themselves to `S-up'.
20029 This one runs after all other options except shift-select have been excluded.
20030 See `org-ctrl-c-ctrl-c-hook' for more information.")
20031 (defvar org-shiftdown-hook nil
20032 "Hook for functions attaching themselves to `S-down'.
20033 See `org-ctrl-c-ctrl-c-hook' for more information.")
20034 (defvar org-shiftdown-final-hook nil
20035 "Hook for functions attaching themselves to `S-down'.
20036 This one runs after all other options except shift-select have been excluded.
20037 See `org-ctrl-c-ctrl-c-hook' for more information.")
20038 (defvar org-shiftleft-hook nil
20039 "Hook for functions attaching themselves to `S-left'.
20040 See `org-ctrl-c-ctrl-c-hook' for more information.")
20041 (defvar org-shiftleft-final-hook nil
20042 "Hook for functions attaching themselves to `S-left'.
20043 This one runs after all other options except shift-select have been excluded.
20044 See `org-ctrl-c-ctrl-c-hook' for more information.")
20045 (defvar org-shiftright-hook nil
20046 "Hook for functions attaching themselves to `S-right'.
20047 See `org-ctrl-c-ctrl-c-hook' for more information.")
20048 (defvar org-shiftright-final-hook nil
20049 "Hook for functions attaching themselves to `S-right'.
20050 This one runs after all other options except shift-select have been excluded.
20051 See `org-ctrl-c-ctrl-c-hook' for more information.")
20053 (defun org-modifier-cursor-error ()
20054 "Throw an error, a modified cursor command was applied in wrong context."
20055 (user-error "This command is active in special context like tables, headlines or items"))
20057 (defun org-shiftselect-error ()
20058 "Throw an error because Shift-Cursor command was applied in wrong context."
20059 (if (and (boundp 'shift-select-mode) shift-select-mode)
20060 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20061 (user-error "This command works only in special context like headlines or timestamps")))
20063 (defun org-call-for-shift-select (cmd)
20064 (let ((this-command-keys-shift-translated t))
20065 (call-interactively cmd)))
20067 (defun org-shifttab (&optional arg)
20068 "Global visibility cycling or move to previous table field.
20069 Call `org-table-previous-field' within a table.
20070 When ARG is nil, cycle globally through visibility states.
20071 When ARG is a numeric prefix, show contents of this level."
20072 (interactive "P")
20073 (cond
20074 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20075 ((integerp arg)
20076 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20077 (message "Content view to level: %d" arg)
20078 (org-content (prefix-numeric-value arg2))
20079 (org-cycle-show-empty-lines t)
20080 (setq org-cycle-global-status 'overview)))
20081 (t (call-interactively 'org-global-cycle))))
20083 (defun org-shiftmetaleft ()
20084 "Promote subtree or delete table column.
20085 Calls `org-promote-subtree', `org-outdent-item-tree', or
20086 `org-table-delete-column', depending on context. See the
20087 individual commands for more information."
20088 (interactive)
20089 (cond
20090 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20091 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20092 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20093 ((if (not (org-region-active-p)) (org-at-item-p)
20094 (save-excursion (goto-char (region-beginning))
20095 (org-at-item-p)))
20096 (call-interactively 'org-outdent-item-tree))
20097 (t (org-modifier-cursor-error))))
20099 (defun org-shiftmetaright ()
20100 "Demote subtree or insert table column.
20101 Calls `org-demote-subtree', `org-indent-item-tree', or
20102 `org-table-insert-column', depending on context. See the
20103 individual commands for more information."
20104 (interactive)
20105 (cond
20106 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20107 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20108 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20109 ((if (not (org-region-active-p)) (org-at-item-p)
20110 (save-excursion (goto-char (region-beginning))
20111 (org-at-item-p)))
20112 (call-interactively 'org-indent-item-tree))
20113 (t (org-modifier-cursor-error))))
20115 (defun org-shiftmetaup (&optional arg)
20116 "Drag the line at point up.
20117 In a table, kill the current row.
20118 On a clock timestamp, update the value of the timestamp like `S-<up>'
20119 but also adjust the previous clocked item in the clock history.
20120 Everywhere else, drag the line at point up."
20121 (interactive "P")
20122 (cond
20123 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20124 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20125 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20126 (call-interactively 'org-timestamp-up)))
20127 (t (call-interactively 'org-drag-line-backward))))
20129 (defun org-shiftmetadown (&optional arg)
20130 "Drag the line at point down.
20131 In a table, insert an empty row at the current line.
20132 On a clock timestamp, update the value of the timestamp like `S-<down>'
20133 but also adjust the previous clocked item in the clock history.
20134 Everywhere else, drag the line at point down."
20135 (interactive "P")
20136 (cond
20137 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20138 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20139 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20140 (call-interactively 'org-timestamp-down)))
20141 (t (call-interactively 'org-drag-line-forward))))
20143 (defsubst org-hidden-tree-error ()
20144 (user-error
20145 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20147 (defun org-metaleft (&optional arg)
20148 "Promote heading or move table column to left.
20149 Calls `org-do-promote' or `org-table-move-column', depending on context.
20150 With no specific context, calls the Emacs default `backward-word'.
20151 See the individual commands for more information."
20152 (interactive "P")
20153 (cond
20154 ((run-hook-with-args-until-success 'org-metaleft-hook))
20155 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20156 ((org-with-limited-levels
20157 (or (org-at-heading-p)
20158 (and (org-region-active-p)
20159 (save-excursion
20160 (goto-char (region-beginning))
20161 (org-at-heading-p)))))
20162 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20163 (call-interactively 'org-do-promote))
20164 ;; At an inline task.
20165 ((org-at-heading-p)
20166 (call-interactively 'org-inlinetask-promote))
20167 ((or (org-at-item-p)
20168 (and (org-region-active-p)
20169 (save-excursion
20170 (goto-char (region-beginning))
20171 (org-at-item-p))))
20172 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20173 (call-interactively 'org-outdent-item))
20174 (t (call-interactively 'backward-word))))
20176 (defun org-metaright (&optional arg)
20177 "Demote a subtree, a list item or move table column to right.
20178 In front of a drawer or a block keyword, indent it correctly.
20179 With no specific context, calls the Emacs default `forward-word'.
20180 See the individual commands for more information."
20181 (interactive "P")
20182 (cond
20183 ((run-hook-with-args-until-success 'org-metaright-hook))
20184 ((org-at-table-p) (call-interactively 'org-table-move-column))
20185 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20186 ((org-at-block-p) (call-interactively 'org-indent-block))
20187 ((org-with-limited-levels
20188 (or (org-at-heading-p)
20189 (and (org-region-active-p)
20190 (save-excursion
20191 (goto-char (region-beginning))
20192 (org-at-heading-p)))))
20193 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20194 (call-interactively 'org-do-demote))
20195 ;; At an inline task.
20196 ((org-at-heading-p)
20197 (call-interactively 'org-inlinetask-demote))
20198 ((or (org-at-item-p)
20199 (and (org-region-active-p)
20200 (save-excursion
20201 (goto-char (region-beginning))
20202 (org-at-item-p))))
20203 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20204 (call-interactively 'org-indent-item))
20205 (t (call-interactively 'forward-word))))
20207 (defun org-check-for-hidden (what)
20208 "Check if there are hidden headlines/items in the current visual line.
20209 WHAT can be either `headlines' or `items'. If the current line is
20210 an outline or item heading and it has a folded subtree below it,
20211 this function returns t, nil otherwise."
20212 (let ((re (cond
20213 ((eq what 'headlines) org-outline-regexp-bol)
20214 ((eq what 'items) (org-item-beginning-re))
20215 (t (error "This should not happen"))))
20216 beg end)
20217 (save-excursion
20218 (catch 'exit
20219 (unless (org-region-active-p)
20220 (setq beg (point-at-bol))
20221 (beginning-of-line 2)
20222 (while (and (not (eobp)) ;; this is like `next-line'
20223 (get-char-property (1- (point)) 'invisible))
20224 (beginning-of-line 2))
20225 (setq end (point))
20226 (goto-char beg)
20227 (goto-char (point-at-eol))
20228 (setq end (max end (point)))
20229 (while (re-search-forward re end t)
20230 (if (get-char-property (match-beginning 0) 'invisible)
20231 (throw 'exit t))))
20232 nil))))
20234 (defun org-metaup (&optional arg)
20235 "Move subtree up or move table row up.
20236 Calls `org-move-subtree-up' or `org-table-move-row' or
20237 `org-move-item-up', depending on context. See the individual commands
20238 for more information."
20239 (interactive "P")
20240 (cond
20241 ((run-hook-with-args-until-success 'org-metaup-hook))
20242 ((org-region-active-p)
20243 (let* ((a (min (region-beginning) (region-end)))
20244 (b (1- (max (region-beginning) (region-end))))
20245 (c (save-excursion (goto-char a)
20246 (move-beginning-of-line 0)))
20247 (d (save-excursion (goto-char a)
20248 (move-end-of-line 0) (point))))
20249 (transpose-regions a b c d)
20250 (goto-char c)))
20251 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20252 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20253 ((org-at-item-p) (call-interactively 'org-move-item-up))
20254 (t (org-drag-element-backward))))
20256 (defun org-metadown (&optional arg)
20257 "Move subtree down or move table row down.
20258 Calls `org-move-subtree-down' or `org-table-move-row' or
20259 `org-move-item-down', depending on context. See the individual
20260 commands for more information."
20261 (interactive "P")
20262 (cond
20263 ((run-hook-with-args-until-success 'org-metadown-hook))
20264 ((org-region-active-p)
20265 (let* ((a (min (region-beginning) (region-end)))
20266 (b (max (region-beginning) (region-end)))
20267 (c (save-excursion (goto-char b)
20268 (move-beginning-of-line 1)))
20269 (d (save-excursion (goto-char b)
20270 (move-end-of-line 1) (1+ (point)))))
20271 (transpose-regions a b c d)
20272 (goto-char d)))
20273 ((org-at-table-p) (call-interactively 'org-table-move-row))
20274 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20275 ((org-at-item-p) (call-interactively 'org-move-item-down))
20276 (t (org-drag-element-forward))))
20278 (defun org-shiftup (&optional arg)
20279 "Increase item in timestamp or increase priority of current headline.
20280 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20281 depending on context. See the individual commands for more information."
20282 (interactive "P")
20283 (cond
20284 ((run-hook-with-args-until-success 'org-shiftup-hook))
20285 ((and org-support-shift-select (org-region-active-p))
20286 (org-call-for-shift-select 'previous-line))
20287 ((org-at-timestamp-p t)
20288 (call-interactively (if org-edit-timestamp-down-means-later
20289 'org-timestamp-down 'org-timestamp-up)))
20290 ((and (not (eq org-support-shift-select 'always))
20291 org-enable-priority-commands
20292 (org-at-heading-p))
20293 (call-interactively 'org-priority-up))
20294 ((and (not org-support-shift-select) (org-at-item-p))
20295 (call-interactively 'org-previous-item))
20296 ((org-clocktable-try-shift 'up arg))
20297 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20298 (org-support-shift-select
20299 (org-call-for-shift-select 'previous-line))
20300 (t (org-shiftselect-error))))
20302 (defun org-shiftdown (&optional arg)
20303 "Decrease item in timestamp or decrease priority of current headline.
20304 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20305 depending on context. See the individual commands for more information."
20306 (interactive "P")
20307 (cond
20308 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20309 ((and org-support-shift-select (org-region-active-p))
20310 (org-call-for-shift-select 'next-line))
20311 ((org-at-timestamp-p t)
20312 (call-interactively (if org-edit-timestamp-down-means-later
20313 'org-timestamp-up 'org-timestamp-down)))
20314 ((and (not (eq org-support-shift-select 'always))
20315 org-enable-priority-commands
20316 (org-at-heading-p))
20317 (call-interactively 'org-priority-down))
20318 ((and (not org-support-shift-select) (org-at-item-p))
20319 (call-interactively 'org-next-item))
20320 ((org-clocktable-try-shift 'down arg))
20321 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20322 (org-support-shift-select
20323 (org-call-for-shift-select 'next-line))
20324 (t (org-shiftselect-error))))
20326 (defun org-shiftright (&optional arg)
20327 "Cycle the thing at point or in the current line, depending on context.
20328 Depending on context, this does one of the following:
20330 - switch a timestamp at point one day into the future
20331 - on a headline, switch to the next TODO keyword.
20332 - on an item, switch entire list to the next bullet type
20333 - on a property line, switch to the next allowed value
20334 - on a clocktable definition line, move time block into the future"
20335 (interactive "P")
20336 (cond
20337 ((run-hook-with-args-until-success 'org-shiftright-hook))
20338 ((and org-support-shift-select (org-region-active-p))
20339 (org-call-for-shift-select 'forward-char))
20340 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20341 ((and (not (eq org-support-shift-select 'always))
20342 (org-at-heading-p))
20343 (let ((org-inhibit-logging
20344 (not org-treat-S-cursor-todo-selection-as-state-change))
20345 (org-inhibit-blocking
20346 (not org-treat-S-cursor-todo-selection-as-state-change)))
20347 (org-call-with-arg 'org-todo 'right)))
20348 ((or (and org-support-shift-select
20349 (not (eq org-support-shift-select 'always))
20350 (org-at-item-bullet-p))
20351 (and (not org-support-shift-select) (org-at-item-p)))
20352 (org-call-with-arg 'org-cycle-list-bullet nil))
20353 ((and (not (eq org-support-shift-select 'always))
20354 (org-at-property-p))
20355 (call-interactively 'org-property-next-allowed-value))
20356 ((org-clocktable-try-shift 'right arg))
20357 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20358 (org-support-shift-select
20359 (org-call-for-shift-select 'forward-char))
20360 (t (org-shiftselect-error))))
20362 (defun org-shiftleft (&optional arg)
20363 "Cycle the thing at point or in the current line, depending on context.
20364 Depending on context, this does one of the following:
20366 - switch a timestamp at point one day into the past
20367 - on a headline, switch to the previous TODO keyword.
20368 - on an item, switch entire list to the previous bullet type
20369 - on a property line, switch to the previous allowed value
20370 - on a clocktable definition line, move time block into the past"
20371 (interactive "P")
20372 (cond
20373 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20374 ((and org-support-shift-select (org-region-active-p))
20375 (org-call-for-shift-select 'backward-char))
20376 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20377 ((and (not (eq org-support-shift-select 'always))
20378 (org-at-heading-p))
20379 (let ((org-inhibit-logging
20380 (not org-treat-S-cursor-todo-selection-as-state-change))
20381 (org-inhibit-blocking
20382 (not org-treat-S-cursor-todo-selection-as-state-change)))
20383 (org-call-with-arg 'org-todo 'left)))
20384 ((or (and org-support-shift-select
20385 (not (eq org-support-shift-select 'always))
20386 (org-at-item-bullet-p))
20387 (and (not org-support-shift-select) (org-at-item-p)))
20388 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20389 ((and (not (eq org-support-shift-select 'always))
20390 (org-at-property-p))
20391 (call-interactively 'org-property-previous-allowed-value))
20392 ((org-clocktable-try-shift 'left arg))
20393 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20394 (org-support-shift-select
20395 (org-call-for-shift-select 'backward-char))
20396 (t (org-shiftselect-error))))
20398 (defun org-shiftcontrolright ()
20399 "Switch to next TODO set."
20400 (interactive)
20401 (cond
20402 ((and org-support-shift-select (org-region-active-p))
20403 (org-call-for-shift-select 'forward-word))
20404 ((and (not (eq org-support-shift-select 'always))
20405 (org-at-heading-p))
20406 (org-call-with-arg 'org-todo 'nextset))
20407 (org-support-shift-select
20408 (org-call-for-shift-select 'forward-word))
20409 (t (org-shiftselect-error))))
20411 (defun org-shiftcontrolleft ()
20412 "Switch to previous TODO set."
20413 (interactive)
20414 (cond
20415 ((and org-support-shift-select (org-region-active-p))
20416 (org-call-for-shift-select 'backward-word))
20417 ((and (not (eq org-support-shift-select 'always))
20418 (org-at-heading-p))
20419 (org-call-with-arg 'org-todo 'previousset))
20420 (org-support-shift-select
20421 (org-call-for-shift-select 'backward-word))
20422 (t (org-shiftselect-error))))
20424 (defun org-shiftcontrolup (&optional n)
20425 "Change timestamps synchronously up in CLOCK log lines.
20426 Optional argument N tells to change by that many units."
20427 (interactive "P")
20428 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20429 (let (org-support-shift-select)
20430 (org-clock-timestamps-up n))
20431 (user-error "Not at a clock log")))
20433 (defun org-shiftcontroldown (&optional n)
20434 "Change timestamps synchronously down in CLOCK log lines.
20435 Optional argument N tells to change by that many units."
20436 (interactive "P")
20437 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20438 (let (org-support-shift-select)
20439 (org-clock-timestamps-down n))
20440 (user-error "Not at a clock log")))
20442 (defun org-increase-number-at-point (&optional inc)
20443 "Increment the number at point.
20444 With an optional prefix numeric argument INC, increment using
20445 this numeric value."
20446 (interactive "p")
20447 (if (not (number-at-point))
20448 (user-error "Not on a number")
20449 (unless inc (setq inc 1))
20450 (let ((pos (point))
20451 (beg (skip-chars-backward "-+^/*0-9eE."))
20452 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20453 (setq nap (buffer-substring-no-properties
20454 (+ pos beg) (+ pos beg end)))
20455 (delete-region (+ pos beg) (+ pos beg end))
20456 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20457 (when (org-at-table-p)
20458 (org-table-align)
20459 (org-table-end-of-field 1))))
20461 (defun org-decrease-number-at-point (&optional inc)
20462 "Decrement the number at point.
20463 With an optional prefix numeric argument INC, decrement using
20464 this numeric value."
20465 (interactive "p")
20466 (org-increase-number-at-point (- inc)))
20468 (defun org-ctrl-c-ret ()
20469 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20470 (interactive)
20471 (cond
20472 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20473 (t (call-interactively 'org-insert-heading))))
20475 (defun org-find-visible ()
20476 (let ((s (point)))
20477 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20478 (get-char-property s 'invisible)))
20480 (defun org-find-invisible ()
20481 (let ((s (point)))
20482 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20483 (not (get-char-property s 'invisible))))
20486 (defun org-copy-visible (beg end)
20487 "Copy the visible parts of the region."
20488 (interactive "r")
20489 (let (snippets s)
20490 (save-excursion
20491 (save-restriction
20492 (narrow-to-region beg end)
20493 (setq s (goto-char (point-min)))
20494 (while (not (= (point) (point-max)))
20495 (goto-char (org-find-invisible))
20496 (push (buffer-substring s (point)) snippets)
20497 (setq s (goto-char (org-find-visible))))))
20498 (kill-new (apply 'concat (nreverse snippets)))))
20500 (defun org-copy-special ()
20501 "Copy region in table or copy current subtree.
20502 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20503 See the individual commands for more information."
20504 (interactive)
20505 (call-interactively
20506 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20508 (defun org-cut-special ()
20509 "Cut region in table or cut current subtree.
20510 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20511 See the individual commands for more information."
20512 (interactive)
20513 (call-interactively
20514 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20516 (defun org-paste-special (arg)
20517 "Paste rectangular region into table, or past subtree relative to level.
20518 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20519 See the individual commands for more information."
20520 (interactive "P")
20521 (if (org-at-table-p)
20522 (org-table-paste-rectangle)
20523 (org-paste-subtree arg)))
20525 (defsubst org-in-fixed-width-region-p ()
20526 "Is point in a fixed-width region?"
20527 (save-match-data
20528 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20530 (defun org-edit-special (&optional arg)
20531 "Call a special editor for the element at point.
20532 When at a table, call the formula editor with `org-table-edit-formulas'.
20533 When in a source code block, call `org-edit-src-code'.
20534 When in a fixed-width region, call `org-edit-fixed-width-region'.
20535 When at an #+INCLUDE keyword, visit the included file.
20536 On a link, call `ffap' to visit the link at point.
20537 Otherwise, return a user error."
20538 (interactive "P")
20539 (let ((element (org-element-at-point)))
20540 (assert (not buffer-read-only) nil
20541 "Buffer is read-only: %s" (buffer-name))
20542 (case (org-element-type element)
20543 (src-block
20544 (if (not arg) (org-edit-src-code)
20545 (let* ((info (org-babel-get-src-block-info))
20546 (lang (nth 0 info))
20547 (params (nth 2 info))
20548 (session (cdr (assq :session params))))
20549 (if (not session) (org-edit-src-code)
20550 ;; At a src-block with a session and function called with
20551 ;; an ARG: switch to the buffer related to the inferior
20552 ;; process.
20553 (switch-to-buffer
20554 (funcall (intern (concat "org-babel-prep-session:" lang))
20555 session params))))))
20556 (keyword
20557 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20558 (org-open-link-from-string
20559 (format "[[%s]]"
20560 (expand-file-name
20561 (let ((value (org-element-property :value element)))
20562 (cond ((not (org-string-nw-p value))
20563 (user-error "No file to edit"))
20564 ((string-match "\\`\"\\(.*?\\)\"" value)
20565 (match-string 1 value))
20566 ((string-match "\\`[^ \t\"]\\S-*" value)
20567 (match-string 0 value))
20568 (t (user-error "No valid file specified")))))))
20569 (user-error "No special environment to edit here")))
20570 (table
20571 (if (eq (org-element-property :type element) 'table.el)
20572 (org-edit-src-code)
20573 (call-interactively 'org-table-edit-formulas)))
20574 ;; Only Org tables contain `table-row' type elements.
20575 (table-row (call-interactively 'org-table-edit-formulas))
20576 ((example-block export-block) (org-edit-src-code))
20577 (fixed-width (org-edit-fixed-width-region))
20578 (otherwise
20579 ;; No notable element at point. Though, we may be at a link,
20580 ;; which is an object. Thus, scan deeper.
20581 (if (eq (org-element-type (org-element-context element)) 'link)
20582 (call-interactively 'ffap)
20583 (user-error "No special environment to edit here"))))))
20585 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20586 (defun org-ctrl-c-ctrl-c (&optional arg)
20587 "Set tags in headline, or update according to changed information at point.
20589 This command does many different things, depending on context:
20591 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20592 this is what we do.
20594 - If the cursor is on a statistics cookie, update it.
20596 - If the cursor is in a headline, prompt for tags and insert them
20597 into the current line, aligned to `org-tags-column'. When called
20598 with prefix arg, realign all tags in the current buffer.
20600 - If the cursor is in one of the special #+KEYWORD lines, this
20601 triggers scanning the buffer for these lines and updating the
20602 information.
20604 - If the cursor is inside a table, realign the table. This command
20605 works even if the automatic table editor has been turned off.
20607 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20608 the entire table.
20610 - If the cursor is at a footnote reference or definition, jump to
20611 the corresponding definition or references, respectively.
20613 - If the cursor is a the beginning of a dynamic block, update it.
20615 - If the current buffer is a capture buffer, close note and file it.
20617 - If the cursor is on a <<<target>>>, update radio targets and
20618 corresponding links in this buffer.
20620 - If the cursor is on a numbered item in a plain list, renumber the
20621 ordered list.
20623 - If the cursor is on a checkbox, toggle it.
20625 - If the cursor is on a code block, evaluate it. The variable
20626 `org-confirm-babel-evaluate' can be used to control prompting
20627 before code block evaluation, by default every code block
20628 evaluation requires confirmation. Code block evaluation can be
20629 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20630 (interactive "P")
20631 (cond
20632 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20633 org-occur-highlights)
20634 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20635 (org-remove-occur-highlights)
20636 (message "Temporary highlights/overlays removed from current buffer"))
20637 ((and (local-variable-p 'org-finish-function (current-buffer))
20638 (fboundp org-finish-function))
20639 (funcall org-finish-function))
20640 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20642 (let* ((context (org-element-context)) (type (org-element-type context)))
20643 ;; Test if point is within a blank line.
20644 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20645 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20646 (user-error "C-c C-c can do nothing useful at this location"))
20647 (case type
20648 ;; When at a link, act according to the parent instead.
20649 (link (setq context (org-element-property :parent context))
20650 (setq type (org-element-type context)))
20651 ;; Unsupported object types: refer to the first supported
20652 ;; element or object containing it.
20653 ((bold code entity export-snippet inline-babel-call inline-src-block
20654 italic latex-fragment line-break macro strike-through subscript
20655 superscript underline verbatim)
20656 (while (and (setq context (org-element-property :parent context))
20657 (not (memq (setq type (org-element-type context))
20658 '(radio-target paragraph verse-block
20659 table-cell)))))))
20660 ;; For convenience: at the first line of a paragraph on the
20661 ;; same line as an item, apply function on that item instead.
20662 (when (eq type 'paragraph)
20663 (let ((parent (org-element-property :parent context)))
20664 (when (and (eq (org-element-type parent) 'item)
20665 (= (point-at-bol) (org-element-property :begin parent)))
20666 (setq context parent type 'item))))
20667 ;; Act according to type of element or object at point.
20668 (case type
20669 (clock (org-clock-update-time-maybe))
20670 (dynamic-block
20671 (save-excursion
20672 (goto-char (org-element-property :post-affiliated context))
20673 (org-update-dblock)))
20674 (footnote-definition
20675 (goto-char (org-element-property :post-affiliated context))
20676 (call-interactively 'org-footnote-action))
20677 (footnote-reference (call-interactively 'org-footnote-action))
20678 ((headline inlinetask)
20679 (save-excursion (goto-char (org-element-property :begin context))
20680 (call-interactively 'org-set-tags)))
20681 (item
20682 ;; At an item: a double C-u set checkbox to "[-]"
20683 ;; unconditionally, whereas a single one will toggle its
20684 ;; presence. Without an universal argument, if the item
20685 ;; has a checkbox, toggle it. Otherwise repair the list.
20686 (let* ((box (org-element-property :checkbox context))
20687 (struct (org-element-property :structure context))
20688 (old-struct (copy-tree struct))
20689 (parents (org-list-parents-alist struct))
20690 (prevs (org-list-prevs-alist struct))
20691 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20692 (org-list-set-checkbox
20693 (org-element-property :begin context) struct
20694 (cond ((equal arg '(16)) "[-]")
20695 ((and (not box) (equal arg '(4))) "[ ]")
20696 ((or (not box) (equal arg '(4))) nil)
20697 ((eq box 'on) "[ ]")
20698 (t "[X]")))
20699 ;; Mimic `org-list-write-struct' but with grabbing
20700 ;; a return value from `org-list-struct-fix-box'.
20701 (org-list-struct-fix-ind struct parents 2)
20702 (org-list-struct-fix-item-end struct)
20703 (org-list-struct-fix-bul struct prevs)
20704 (org-list-struct-fix-ind struct parents)
20705 (let ((block-item
20706 (org-list-struct-fix-box struct parents prevs orderedp)))
20707 (if (and box (equal struct old-struct))
20708 (if (equal arg '(16))
20709 (message "Checkboxes already reset")
20710 (user-error "Cannot toggle this checkbox: %s"
20711 (if (eq box 'on)
20712 "all subitems checked"
20713 "unchecked subitems")))
20714 (org-list-struct-apply-struct struct old-struct)
20715 (org-update-checkbox-count-maybe))
20716 (when block-item
20717 (message "Checkboxes were removed due to empty box at line %d"
20718 (org-current-line block-item))))))
20719 (keyword
20720 (let ((org-inhibit-startup-visibility-stuff t)
20721 (org-startup-align-all-tables nil))
20722 (when (boundp 'org-table-coordinate-overlays)
20723 (mapc 'delete-overlay org-table-coordinate-overlays)
20724 (setq org-table-coordinate-overlays nil))
20725 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20726 (message "Local setup has been refreshed"))
20727 (plain-list
20728 ;; At a plain list, with a double C-u argument, set
20729 ;; checkboxes of each item to "[-]", whereas a single one
20730 ;; will toggle their presence according to the state of the
20731 ;; first item in the list. Without an argument, repair the
20732 ;; list.
20733 (let* ((begin (org-element-property :contents-begin context))
20734 (beginm (move-marker (make-marker) begin))
20735 (struct (org-element-property :structure context))
20736 (old-struct (copy-tree struct))
20737 (first-box (save-excursion
20738 (goto-char begin)
20739 (looking-at org-list-full-item-re)
20740 (match-string-no-properties 3)))
20741 (new-box (cond ((equal arg '(16)) "[-]")
20742 ((equal arg '(4)) (unless first-box "[ ]"))
20743 ((equal first-box "[X]") "[ ]")
20744 (t "[X]"))))
20745 (cond
20746 (arg
20747 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20748 (org-list-get-all-items
20749 begin struct (org-list-prevs-alist struct))))
20750 ((and first-box (eq (point) begin))
20751 ;; For convenience, when point is at bol on the first
20752 ;; item of the list and no argument is provided, simply
20753 ;; toggle checkbox of that item, if any.
20754 (org-list-set-checkbox begin struct new-box)))
20755 (org-list-write-struct
20756 struct (org-list-parents-alist struct) old-struct)
20757 (org-update-checkbox-count-maybe)
20758 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20759 ((property-drawer node-property)
20760 (call-interactively 'org-property-action))
20761 ((radio-target target)
20762 (call-interactively 'org-update-radio-target-regexp))
20763 (statistics-cookie
20764 (call-interactively 'org-update-statistics-cookies))
20765 ((table table-cell table-row)
20766 ;; At a table, recalculate every field and align it. Also
20767 ;; send the table if necessary. If the table has
20768 ;; a `table.el' type, just give up. At a table row or
20769 ;; cell, maybe recalculate line but always align table.
20770 (if (eq (org-element-property :type context) 'table.el)
20771 (message "Use C-c ' to edit table.el tables")
20772 (let ((org-enable-table-editor t))
20773 (if (or (eq type 'table)
20774 ;; Check if point is at a TBLFM line.
20775 (and (eq type 'table-row)
20776 (= (point) (org-element-property :end context))))
20777 (save-excursion
20778 (if (org-at-TBLFM-p)
20779 (progn (require 'org-table)
20780 (org-table-calc-current-TBLFM))
20781 (goto-char (org-element-property :contents-begin context))
20782 (org-call-with-arg 'org-table-recalculate (or arg t))
20783 (orgtbl-send-table 'maybe)))
20784 (org-table-maybe-eval-formula)
20785 (cond (arg (call-interactively 'org-table-recalculate))
20786 ((org-table-maybe-recalculate-line))
20787 (t (org-table-align)))))))
20788 (timestamp (org-timestamp-change 0 'day))
20789 (otherwise
20790 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20791 (user-error
20792 "C-c C-c can do nothing useful at this location")))))))))
20794 (defun org-mode-restart ()
20795 (interactive)
20796 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20797 (funcall major-mode)
20798 (hack-local-variables)
20799 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20800 (org-indent-mode -1)))
20801 (message "%s restarted" major-mode))
20803 (defun org-kill-note-or-show-branches ()
20804 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20805 (interactive)
20806 (if (not org-finish-function)
20807 (progn
20808 (hide-subtree)
20809 (call-interactively 'show-branches))
20810 (let ((org-note-abort t))
20811 (funcall org-finish-function))))
20813 (defun org-open-line (n)
20814 "Insert a new row in tables, call `open-line' elsewhere.
20815 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20816 (interactive "*p")
20817 (cond
20818 ((not org-special-ctrl-o)
20819 (open-line n))
20820 ((org-at-table-p)
20821 (org-table-insert-row))
20823 (open-line n))))
20825 (defun org-return (&optional indent)
20826 "Goto next table row or insert a newline.
20827 Calls `org-table-next-row' or `newline', depending on context.
20828 See the individual commands for more information."
20829 (interactive)
20830 (let (org-ts-what)
20831 (cond
20832 ((or (bobp) (org-in-src-block-p))
20833 (if indent (newline-and-indent) (newline)))
20834 ((org-at-table-p)
20835 (org-table-justify-field-maybe)
20836 (call-interactively 'org-table-next-row))
20837 ;; when `newline-and-indent' is called within a list, make sure
20838 ;; text moved stays inside the item.
20839 ((and (org-in-item-p) indent)
20840 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20841 (progn
20842 (save-match-data (newline))
20843 (org-indent-line-to (length (match-string 0))))
20844 (let ((ind (org-get-indentation)))
20845 (newline)
20846 (if (org-looking-back org-list-end-re)
20847 (org-indent-line)
20848 (org-indent-line-to ind)))))
20849 ((and org-return-follows-link
20850 (org-at-timestamp-p t)
20851 (not (eq org-ts-what 'after)))
20852 (org-follow-timestamp-link))
20853 ((and org-return-follows-link
20854 (let ((tprop (get-text-property (point) 'face)))
20855 (or (eq tprop 'org-link)
20856 (and (listp tprop) (memq 'org-link tprop)))))
20857 (call-interactively 'org-open-at-point))
20858 ((and (org-at-heading-p)
20859 (looking-at
20860 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20861 (org-show-entry)
20862 (end-of-line 1)
20863 (newline))
20864 (t (if indent (newline-and-indent) (newline))))))
20866 (defun org-return-indent ()
20867 "Goto next table row or insert a newline and indent.
20868 Calls `org-table-next-row' or `newline-and-indent', depending on
20869 context. See the individual commands for more information."
20870 (interactive)
20871 (org-return t))
20873 (defun org-ctrl-c-star ()
20874 "Compute table, or change heading status of lines.
20875 Calls `org-table-recalculate' or `org-toggle-heading',
20876 depending on context."
20877 (interactive)
20878 (cond
20879 ((org-at-table-p)
20880 (call-interactively 'org-table-recalculate))
20882 ;; Convert all lines in region to list items
20883 (call-interactively 'org-toggle-heading))))
20885 (defun org-ctrl-c-minus ()
20886 "Insert separator line in table or modify bullet status of line.
20887 Also turns a plain line or a region of lines into list items.
20888 Calls `org-table-insert-hline', `org-toggle-item', or
20889 `org-cycle-list-bullet', depending on context."
20890 (interactive)
20891 (cond
20892 ((org-at-table-p)
20893 (call-interactively 'org-table-insert-hline))
20894 ((org-region-active-p)
20895 (call-interactively 'org-toggle-item))
20896 ((org-in-item-p)
20897 (call-interactively 'org-cycle-list-bullet))
20899 (call-interactively 'org-toggle-item))))
20901 (defun org-toggle-item (arg)
20902 "Convert headings or normal lines to items, items to normal lines.
20903 If there is no active region, only the current line is considered.
20905 If the first non blank line in the region is a headline, convert
20906 all headlines to items, shifting text accordingly.
20908 If it is an item, convert all items to normal lines.
20910 If it is normal text, change region into a list of items.
20911 With a prefix argument ARG, change the region in a single item."
20912 (interactive "P")
20913 (let ((shift-text
20914 (function
20915 ;; Shift text in current section to IND, from point to END.
20916 ;; The function leaves point to END line.
20917 (lambda (ind end)
20918 (let ((min-i 1000) (end (copy-marker end)))
20919 ;; First determine the minimum indentation (MIN-I) of
20920 ;; the text.
20921 (save-excursion
20922 (catch 'exit
20923 (while (< (point) end)
20924 (let ((i (org-get-indentation)))
20925 (cond
20926 ;; Skip blank lines and inline tasks.
20927 ((looking-at "^[ \t]*$"))
20928 ((looking-at org-outline-regexp-bol))
20929 ;; We can't find less than 0 indentation.
20930 ((zerop i) (throw 'exit (setq min-i 0)))
20931 ((< i min-i) (setq min-i i))))
20932 (forward-line))))
20933 ;; Then indent each line so that a line indented to
20934 ;; MIN-I becomes indented to IND. Ignore blank lines
20935 ;; and inline tasks in the process.
20936 (let ((delta (- ind min-i)))
20937 (while (< (point) end)
20938 (unless (or (looking-at "^[ \t]*$")
20939 (looking-at org-outline-regexp-bol))
20940 (org-indent-line-to (+ (org-get-indentation) delta)))
20941 (forward-line)))))))
20942 (skip-blanks
20943 (function
20944 ;; Return beginning of first non-blank line, starting from
20945 ;; line at POS.
20946 (lambda (pos)
20947 (save-excursion
20948 (goto-char pos)
20949 (skip-chars-forward " \r\t\n")
20950 (point-at-bol)))))
20951 beg end)
20952 ;; Determine boundaries of changes.
20953 (if (org-region-active-p)
20954 (setq beg (funcall skip-blanks (region-beginning))
20955 end (copy-marker (region-end)))
20956 (setq beg (funcall skip-blanks (point-at-bol))
20957 end (copy-marker (point-at-eol))))
20958 ;; Depending on the starting line, choose an action on the text
20959 ;; between BEG and END.
20960 (org-with-limited-levels
20961 (save-excursion
20962 (goto-char beg)
20963 (cond
20964 ;; Case 1. Start at an item: de-itemize. Note that it only
20965 ;; happens when a region is active: `org-ctrl-c-minus'
20966 ;; would call `org-cycle-list-bullet' otherwise.
20967 ((org-at-item-p)
20968 (while (< (point) end)
20969 (when (org-at-item-p)
20970 (skip-chars-forward " \t")
20971 (delete-region (point) (match-end 0)))
20972 (forward-line)))
20973 ;; Case 2. Start at an heading: convert to items.
20974 ((org-at-heading-p)
20975 (let* ((bul (org-list-bullet-string "-"))
20976 (bul-len (length bul))
20977 (done (org-entry-is-done-p))
20978 (todo (org-entry-is-todo-p))
20979 ;; Indentation of the first heading. It should be
20980 ;; relative to the indentation of its parent, if any.
20981 (start-ind (save-excursion
20982 (cond
20983 ((not org-adapt-indentation) 0)
20984 ((not (outline-previous-heading)) 0)
20985 (t (length (match-string 0))))))
20986 ;; Level of first heading. Further headings will be
20987 ;; compared to it to determine hierarchy in the list.
20988 (ref-level (org-reduced-level (org-outline-level))))
20989 (when (or done todo) (org-todo ""))
20990 (while (< (point) end)
20991 (let* ((level (org-reduced-level (org-outline-level)))
20992 (delta (max 0 (- level ref-level))))
20993 ;; If current headline is less indented than the first
20994 ;; one, set it as reference, in order to preserve
20995 ;; subtrees.
20996 (when (< level ref-level) (setq ref-level level))
20997 (replace-match bul t t)
20998 (org-indent-line-to (+ start-ind (* delta bul-len)))
20999 (when (or done todo)
21000 (let* ((struct (org-list-struct))
21001 (old (copy-tree struct)))
21002 (org-list-set-checkbox (line-beginning-position)
21003 struct
21004 (if done "[X]" "[ ]"))
21005 (org-list-write-struct struct
21006 (org-list-parents-alist struct)
21007 old)))
21008 ;; Ensure all text down to END (or SECTION-END) belongs
21009 ;; to the newly created item.
21010 (let ((section-end (save-excursion
21011 (or (outline-next-heading) (point)))))
21012 (forward-line)
21013 (funcall shift-text
21014 (+ start-ind (* (1+ delta) bul-len))
21015 (min end section-end)))))))
21016 ;; Case 3. Normal line with ARG: make the first line of region
21017 ;; an item, and shift indentation of others lines to
21018 ;; set them as item's body.
21019 (arg (let* ((bul (org-list-bullet-string "-"))
21020 (bul-len (length bul))
21021 (ref-ind (org-get-indentation)))
21022 (skip-chars-forward " \t")
21023 (insert bul)
21024 (forward-line)
21025 (while (< (point) end)
21026 ;; Ensure that lines less indented than first one
21027 ;; still get included in item body.
21028 (funcall shift-text
21029 (+ ref-ind bul-len)
21030 (min end (save-excursion (or (outline-next-heading)
21031 (point)))))
21032 (forward-line))))
21033 ;; Case 4. Normal line without ARG: turn each non-item line
21034 ;; into an item.
21036 (while (< (point) end)
21037 (unless (or (org-at-heading-p) (org-at-item-p))
21038 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21039 (replace-match
21040 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21041 (forward-line))))))))
21043 (defun org-toggle-heading (&optional nstars)
21044 "Convert headings to normal text, or items or text to headings.
21045 If there is no active region, only convert the current line.
21047 With a \\[universal-argument] prefix, convert the whole list at
21048 point into heading.
21050 In a region:
21052 - If the first non blank line is a headline, remove the stars
21053 from all headlines in the region.
21055 - If it is a normal line, turn each and every normal line (i.e.,
21056 not an heading or an item) in the region into headings. If you
21057 want to convert only the first line of this region, use one
21058 universal prefix argument.
21060 - If it is a plain list item, turn all plain list items into headings.
21062 When converting a line into a heading, the number of stars is chosen
21063 such that the lines become children of the current entry. However,
21064 when a numeric prefix argument is given, its value determines the
21065 number of stars to add."
21066 (interactive "P")
21067 (let ((skip-blanks
21068 (function
21069 ;; Return beginning of first non-blank line, starting from
21070 ;; line at POS.
21071 (lambda (pos)
21072 (save-excursion
21073 (goto-char pos)
21074 (while (org-at-comment-p) (forward-line))
21075 (skip-chars-forward " \r\t\n")
21076 (point-at-bol)))))
21077 beg end toggled)
21078 ;; Determine boundaries of changes. If a universal prefix has
21079 ;; been given, put the list in a region. If region ends at a bol,
21080 ;; do not consider the last line to be in the region.
21082 (when (and current-prefix-arg (org-at-item-p))
21083 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21084 (org-mark-element))
21086 (if (org-region-active-p)
21087 (setq beg (funcall skip-blanks (region-beginning))
21088 end (copy-marker (save-excursion
21089 (goto-char (region-end))
21090 (if (bolp) (point) (point-at-eol)))))
21091 (setq beg (funcall skip-blanks (point-at-bol))
21092 end (copy-marker (point-at-eol))))
21093 ;; Ensure inline tasks don't count as headings.
21094 (org-with-limited-levels
21095 (save-excursion
21096 (goto-char beg)
21097 (cond
21098 ;; Case 1. Started at an heading: de-star headings.
21099 ((org-at-heading-p)
21100 (while (< (point) end)
21101 (when (org-at-heading-p t)
21102 (looking-at org-outline-regexp) (replace-match "")
21103 (setq toggled t))
21104 (forward-line)))
21105 ;; Case 2. Started at an item: change items into headlines.
21106 ;; One star will be added by `org-list-to-subtree'.
21107 ((org-at-item-p)
21108 (let* ((stars (make-string
21109 ;; subtract the star that will be added again by
21110 ;; `org-list-to-subtree'
21111 (if (numberp nstars) (1- nstars)
21112 (or (org-current-level) 0))
21113 ?*))
21114 (add-stars
21115 (cond (nstars "") ; stars from prefix only
21116 ((equal stars "") "") ; before first heading
21117 (org-odd-levels-only "*") ; inside heading, odd
21118 (t "")))) ; inside heading, oddeven
21119 (while (< (point) end)
21120 (when (org-at-item-p)
21121 ;; Pay attention to cases when region ends before list.
21122 (let* ((struct (org-list-struct))
21123 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21124 (save-restriction
21125 (narrow-to-region (point) list-end)
21126 (insert
21127 (org-list-to-subtree
21128 (org-list-parse-list t)
21129 '(:istart (concat stars add-stars (funcall get-stars depth))
21130 :icount (concat stars add-stars (funcall get-stars depth)))))))
21131 (setq toggled t))
21132 (forward-line))))
21133 ;; Case 3. Started at normal text: make every line an heading,
21134 ;; skipping headlines and items.
21135 (t (let* ((stars
21136 (make-string
21137 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21138 (add-stars
21139 (cond (nstars "") ; stars from prefix only
21140 ((equal stars "") "*") ; before first heading
21141 (org-odd-levels-only "**") ; inside heading, odd
21142 (t "*"))) ; inside heading, oddeven
21143 (rpl (concat stars add-stars " "))
21144 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21145 (while (< (point) (if (equal nstars '(4)) lend end))
21146 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21147 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21148 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21149 (forward-line)))))))
21150 (unless toggled (message "Cannot toggle heading from here"))))
21152 (defun org-meta-return (&optional arg)
21153 "Insert a new heading or wrap a region in a table.
21154 Calls `org-insert-heading' or `org-table-wrap-region', depending
21155 on context. See the individual commands for more information."
21156 (interactive "P")
21157 (org-check-before-invisible-edit 'insert)
21158 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21159 (let* ((element (org-element-at-point))
21160 (type (org-element-type element)))
21161 (when (eq type 'table-row)
21162 (setq element (org-element-property :parent element))
21163 (setq type 'table))
21164 (if (and (eq type 'table)
21165 (eq (org-element-property :type element) 'org)
21166 (>= (point) (org-element-property :contents-begin element))
21167 (< (point) (org-element-property :contents-end element)))
21168 (call-interactively 'org-table-wrap-region)
21169 (call-interactively 'org-insert-heading)))))
21171 ;;; Menu entries
21173 (defsubst org-in-subtree-not-table-p ()
21174 "Are we in a subtree and not in a table?"
21175 (and (not (org-before-first-heading-p))
21176 (not (org-at-table-p))))
21178 ;; Define the Org-mode menus
21179 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21180 '("Tbl"
21181 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21182 ["Next Field" org-cycle (org-at-table-p)]
21183 ["Previous Field" org-shifttab (org-at-table-p)]
21184 ["Next Row" org-return (org-at-table-p)]
21185 "--"
21186 ["Blank Field" org-table-blank-field (org-at-table-p)]
21187 ["Edit Field" org-table-edit-field (org-at-table-p)]
21188 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21189 "--"
21190 ("Column"
21191 ["Move Column Left" org-metaleft (org-at-table-p)]
21192 ["Move Column Right" org-metaright (org-at-table-p)]
21193 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21194 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21195 ("Row"
21196 ["Move Row Up" org-metaup (org-at-table-p)]
21197 ["Move Row Down" org-metadown (org-at-table-p)]
21198 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21199 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21200 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21201 "--"
21202 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21203 ("Rectangle"
21204 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21205 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21206 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21207 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21208 "--"
21209 ("Calculate"
21210 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21211 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21212 ["Edit Formulas" org-edit-special (org-at-table-p)]
21213 "--"
21214 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21215 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21216 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21217 "--"
21218 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21219 "--"
21220 ["Sum Column/Rectangle" org-table-sum
21221 (or (org-at-table-p) (org-region-active-p))]
21222 ["Which Column?" org-table-current-column (org-at-table-p)])
21223 ["Debug Formulas"
21224 org-table-toggle-formula-debugger
21225 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21226 ["Show Col/Row Numbers"
21227 org-table-toggle-coordinate-overlays
21228 :style toggle
21229 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21230 "--"
21231 ["Create" org-table-create (and (not (org-at-table-p))
21232 org-enable-table-editor)]
21233 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21234 ["Import from File" org-table-import (not (org-at-table-p))]
21235 ["Export to File" org-table-export (org-at-table-p)]
21236 "--"
21237 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21238 "--"
21239 ("Plot"
21240 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21241 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21243 (easy-menu-define org-org-menu org-mode-map "Org menu"
21244 '("Org"
21245 ("Show/Hide"
21246 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21247 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21248 ["Sparse Tree..." org-sparse-tree t]
21249 ["Reveal Context" org-reveal t]
21250 ["Show All" show-all t]
21251 "--"
21252 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21253 "--"
21254 ["New Heading" org-insert-heading t]
21255 ("Navigate Headings"
21256 ["Up" outline-up-heading t]
21257 ["Next" outline-next-visible-heading t]
21258 ["Previous" outline-previous-visible-heading t]
21259 ["Next Same Level" outline-forward-same-level t]
21260 ["Previous Same Level" outline-backward-same-level t]
21261 "--"
21262 ["Jump" org-goto t])
21263 ("Edit Structure"
21264 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21265 "--"
21266 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21267 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21268 "--"
21269 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21270 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21271 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21272 "--"
21273 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21274 "--"
21275 ["Copy visible text" org-copy-visible t]
21276 "--"
21277 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21278 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21279 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21280 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21281 "--"
21282 ["Sort Region/Children" org-sort t]
21283 "--"
21284 ["Convert to odd levels" org-convert-to-odd-levels t]
21285 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21286 ("Editing"
21287 ["Emphasis..." org-emphasize t]
21288 ["Edit Source Example" org-edit-special t]
21289 "--"
21290 ["Footnote new/jump" org-footnote-action t]
21291 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21292 ("Archive"
21293 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21294 "--"
21295 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21296 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21297 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21299 "--"
21300 ("Hyperlinks"
21301 ["Store Link (Global)" org-store-link t]
21302 ["Find existing link to here" org-occur-link-in-agenda-files t]
21303 ["Insert Link" org-insert-link t]
21304 ["Follow Link" org-open-at-point t]
21305 "--"
21306 ["Next link" org-next-link t]
21307 ["Previous link" org-previous-link t]
21308 "--"
21309 ["Descriptive Links"
21310 org-toggle-link-display
21311 :style radio
21312 :selected org-descriptive-links
21314 ["Literal Links"
21315 org-toggle-link-display
21316 :style radio
21317 :selected (not org-descriptive-links)])
21318 "--"
21319 ("TODO Lists"
21320 ["TODO/DONE/-" org-todo t]
21321 ("Select keyword"
21322 ["Next keyword" org-shiftright (org-at-heading-p)]
21323 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21324 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21325 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21326 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21327 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21328 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21329 "--"
21330 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21331 :selected org-enforce-todo-dependencies :style toggle :active t]
21332 "Settings for tree at point"
21333 ["Do Children sequentially" org-toggle-ordered-property :style radio
21334 :selected (org-entry-get nil "ORDERED")
21335 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21336 ["Do Children parallel" org-toggle-ordered-property :style radio
21337 :selected (not (org-entry-get nil "ORDERED"))
21338 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21339 "--"
21340 ["Set Priority" org-priority t]
21341 ["Priority Up" org-shiftup t]
21342 ["Priority Down" org-shiftdown t]
21343 "--"
21344 ["Get news from all feeds" org-feed-update-all t]
21345 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21346 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21347 ("TAGS and Properties"
21348 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21349 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21350 "--"
21351 ["Set property" org-set-property (not (org-before-first-heading-p))]
21352 ["Column view of properties" org-columns t]
21353 ["Insert Column View DBlock" org-insert-columns-dblock t])
21354 ("Dates and Scheduling"
21355 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21356 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21357 ("Change Date"
21358 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21359 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21360 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21361 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21362 ["Compute Time Range" org-evaluate-time-range t]
21363 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21364 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21365 "--"
21366 ["Custom time format" org-toggle-time-stamp-overlays
21367 :style radio :selected org-display-custom-times]
21368 "--"
21369 ["Goto Calendar" org-goto-calendar t]
21370 ["Date from Calendar" org-date-from-calendar t]
21371 "--"
21372 ["Start/Restart Timer" org-timer-start t]
21373 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21374 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21375 ["Insert Timer String" org-timer t]
21376 ["Insert Timer Item" org-timer-item t])
21377 ("Logging work"
21378 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21379 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21380 ["Clock out" org-clock-out t]
21381 ["Clock cancel" org-clock-cancel t]
21382 "--"
21383 ["Mark as default task" org-clock-mark-default-task t]
21384 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21385 ["Goto running clock" org-clock-goto t]
21386 "--"
21387 ["Display times" org-clock-display t]
21388 ["Create clock table" org-clock-report t]
21389 "--"
21390 ["Record DONE time"
21391 (progn (setq org-log-done (not org-log-done))
21392 (message "Switching to %s will %s record a timestamp"
21393 (car org-done-keywords)
21394 (if org-log-done "automatically" "not")))
21395 :style toggle :selected org-log-done])
21396 "--"
21397 ["Agenda Command..." org-agenda t]
21398 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21399 ("File List for Agenda")
21400 ("Special views current file"
21401 ["TODO Tree" org-show-todo-tree t]
21402 ["Check Deadlines" org-check-deadlines t]
21403 ["Timeline" org-timeline t]
21404 ["Tags/Property tree" org-match-sparse-tree t])
21405 "--"
21406 ["Export/Publish..." org-export-dispatch t]
21407 ("LaTeX"
21408 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21409 :selected org-cdlatex-mode]
21410 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21411 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21412 ["Modify math symbol" org-cdlatex-math-modify
21413 (org-inside-LaTeX-fragment-p)]
21414 ["Insert citation" org-reftex-citation t]
21415 "--"
21416 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21417 "--"
21418 ("MobileOrg"
21419 ["Push Files and Views" org-mobile-push t]
21420 ["Get Captured and Flagged" org-mobile-pull t]
21421 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21422 "--"
21423 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21424 "--"
21425 ("Documentation"
21426 ["Show Version" org-version t]
21427 ["Info Documentation" org-info t])
21428 ("Customize"
21429 ["Browse Org Group" org-customize t]
21430 "--"
21431 ["Expand This Menu" org-create-customize-menu
21432 (fboundp 'customize-menu-create)])
21433 ["Send bug report" org-submit-bug-report t]
21434 "--"
21435 ("Refresh/Reload"
21436 ["Refresh setup current buffer" org-mode-restart t]
21437 ["Reload Org (after update)" org-reload t]
21438 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21441 (defun org-info (&optional node)
21442 "Read documentation for Org-mode in the info system.
21443 With optional NODE, go directly to that node."
21444 (interactive)
21445 (info (format "(org)%s" (or node ""))))
21447 ;;;###autoload
21448 (defun org-submit-bug-report ()
21449 "Submit a bug report on Org-mode via mail.
21451 Don't hesitate to report any problems or inaccurate documentation.
21453 If you don't have setup sending mail from (X)Emacs, please copy the
21454 output buffer into your mail program, as it gives us important
21455 information about your Org-mode version and configuration."
21456 (interactive)
21457 (require 'reporter)
21458 (org-load-modules-maybe)
21459 (org-require-autoloaded-modules)
21460 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21461 (reporter-submit-bug-report
21462 "emacs-orgmode@gnu.org"
21463 (org-version nil 'full)
21464 (let (list)
21465 (save-window-excursion
21466 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21467 (delete-other-windows)
21468 (erase-buffer)
21469 (insert "You are about to submit a bug report to the Org-mode mailing list.
21471 We would like to add your full Org-mode and Outline configuration to the
21472 bug report. This greatly simplifies the work of the maintainer and
21473 other experts on the mailing list.
21475 HOWEVER, some variables you have customized may contain private
21476 information. The names of customers, colleagues, or friends, might
21477 appear in the form of file names, tags, todo states, or search strings.
21478 If you answer yes to the prompt, you might want to check and remove
21479 such private information before sending the email.")
21480 (add-text-properties (point-min) (point-max) '(face org-warning))
21481 (when (yes-or-no-p "Include your Org-mode configuration ")
21482 (mapatoms
21483 (lambda (v)
21484 (and (boundp v)
21485 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21486 (or (and (symbol-value v)
21487 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21488 (and
21489 (get v 'custom-type) (get v 'standard-value)
21490 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21491 (push v list)))))
21492 (kill-buffer (get-buffer "*Warn about privacy*"))
21493 list))
21494 nil nil
21495 "Remember to cover the basics, that is, what you expected to happen and
21496 what in fact did happen. You don't know how to make a good report? See
21498 http://orgmode.org/manual/Feedback.html#Feedback
21500 Your bug report will be posted to the Org-mode mailing list.
21501 ------------------------------------------------------------------------")
21502 (save-excursion
21503 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21504 (replace-match "\\1Bug: \\3 [\\2]")))))
21507 (defun org-install-agenda-files-menu ()
21508 (let ((bl (buffer-list)))
21509 (save-excursion
21510 (while bl
21511 (set-buffer (pop bl))
21512 (if (derived-mode-p 'org-mode) (setq bl nil)))
21513 (when (derived-mode-p 'org-mode)
21514 (easy-menu-change
21515 '("Org") "File List for Agenda"
21516 (append
21517 (list
21518 ["Edit File List" (org-edit-agenda-file-list) t]
21519 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21520 ["Remove Current File from List" org-remove-file t]
21521 ["Cycle through agenda files" org-cycle-agenda-files t]
21522 ["Occur in all agenda files" org-occur-in-agenda-files t]
21523 "--")
21524 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21526 ;;;; Documentation
21528 (defun org-require-autoloaded-modules ()
21529 (interactive)
21530 (mapc 'require
21531 '(org-agenda org-archive org-attach org-clock org-colview org-id
21532 org-table org-timer)))
21534 ;;;###autoload
21535 (defun org-reload (&optional uncompiled)
21536 "Reload all org lisp files.
21537 With prefix arg UNCOMPILED, load the uncompiled versions."
21538 (interactive "P")
21539 (require 'loadhist)
21540 (let* ((org-dir (org-find-library-dir "org"))
21541 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21542 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21543 (remove-re (mapconcat 'identity
21544 (mapcar (lambda (f) (concat "^" f "$"))
21545 (list (if (featurep 'xemacs)
21546 "org-colview"
21547 "org-colview-xemacs")
21548 "org" "org-loaddefs" "org-version"))
21549 "\\|"))
21550 (feats (delete-dups
21551 (mapcar 'file-name-sans-extension
21552 (mapcar 'file-name-nondirectory
21553 (delq nil
21554 (mapcar 'feature-file
21555 features))))))
21556 (lfeat (append
21557 (sort
21558 (setq feats
21559 (delq nil (mapcar
21560 (lambda (f)
21561 (if (and (string-match feature-re f)
21562 (not (string-match remove-re f)))
21563 f nil))
21564 feats)))
21565 'string-lessp)
21566 (list "org-version" "org")))
21567 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21568 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21569 load-uncore load-misses)
21570 (setq load-misses
21571 (delq 't
21572 (mapcar (lambda (f)
21573 (or (org-load-noerror-mustsuffix (concat org-dir f))
21574 (and (string= org-dir contrib-dir)
21575 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21576 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21577 (add-to-list 'load-uncore f 'append)
21580 lfeat)))
21581 (if load-uncore
21582 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21583 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21584 (if load-misses
21585 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21586 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21587 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21589 ;;;###autoload
21590 (defun org-customize ()
21591 "Call the customize function with org as argument."
21592 (interactive)
21593 (org-load-modules-maybe)
21594 (org-require-autoloaded-modules)
21595 (customize-browse 'org))
21597 (defun org-create-customize-menu ()
21598 "Create a full customization menu for Org-mode, insert it into the menu."
21599 (interactive)
21600 (org-load-modules-maybe)
21601 (org-require-autoloaded-modules)
21602 (if (fboundp 'customize-menu-create)
21603 (progn
21604 (easy-menu-change
21605 '("Org") "Customize"
21606 `(["Browse Org group" org-customize t]
21607 "--"
21608 ,(customize-menu-create 'org)
21609 ["Set" Custom-set t]
21610 ["Save" Custom-save t]
21611 ["Reset to Current" Custom-reset-current t]
21612 ["Reset to Saved" Custom-reset-saved t]
21613 ["Reset to Standard Settings" Custom-reset-standard t]))
21614 (message "\"Org\"-menu now contains full customization menu"))
21615 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21617 ;;;; Miscellaneous stuff
21619 ;;; Generally useful functions
21621 (defsubst org-get-at-eol (property n)
21622 "Get text property PROPERTY at the end of line less N characters."
21623 (get-text-property (- (point-at-eol) n) property))
21625 (defun org-find-text-property-in-string (prop s)
21626 "Return the first non-nil value of property PROP in string S."
21627 (or (get-text-property 0 prop s)
21628 (get-text-property (or (next-single-property-change 0 prop s) 0)
21629 prop s)))
21631 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21632 "Display the given MESSAGE as a warning."
21633 (if (fboundp 'display-warning)
21634 (display-warning 'org message
21635 (if (featurep 'xemacs) 'warning :warning))
21636 (let ((buf (get-buffer-create "*Org warnings*")))
21637 (with-current-buffer buf
21638 (goto-char (point-max))
21639 (insert "Warning (Org): " message)
21640 (unless (bolp)
21641 (newline)))
21642 (display-buffer buf)
21643 (sit-for 0))))
21645 (defun org-eval (form)
21646 "Eval FORM and return result."
21647 (condition-case error
21648 (eval form)
21649 (error (format "%%![Error: %s]" error))))
21651 (defun org-in-clocktable-p ()
21652 "Check if the cursor is in a clocktable."
21653 (let ((pos (point)) start)
21654 (save-excursion
21655 (end-of-line 1)
21656 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21657 (setq start (match-beginning 0))
21658 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21659 (>= (match-end 0) pos)
21660 start))))
21662 (defun org-in-verbatim-emphasis ()
21663 (save-match-data
21664 (and (org-in-regexp org-emph-re 2)
21665 (>= (point) (match-beginning 3))
21666 (<= (point) (match-end 4))
21667 (member (match-string 3) '("=" "~")))))
21669 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21670 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21671 (if (and marker (marker-buffer marker)
21672 (buffer-live-p (marker-buffer marker)))
21673 (progn
21674 (org-pop-to-buffer-same-window (marker-buffer marker))
21675 (if (or (> marker (point-max)) (< marker (point-min)))
21676 (widen))
21677 (goto-char marker)
21678 (org-show-context 'org-goto))
21679 (if bookmark
21680 (bookmark-jump bookmark)
21681 (error "Cannot find location"))))
21683 (defun org-quote-csv-field (s)
21684 "Quote field for inclusion in CSV material."
21685 (if (string-match "[\",]" s)
21686 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21689 (defun org-force-self-insert (N)
21690 "Needed to enforce self-insert under remapping."
21691 (interactive "p")
21692 (self-insert-command N))
21694 (defun org-string-width (s)
21695 "Compute width of string, ignoring invisible characters.
21696 This ignores character with invisibility property `org-link', and also
21697 characters with property `org-cwidth', because these will become invisible
21698 upon the next fontification round."
21699 (let (b l)
21700 (when (or (eq t buffer-invisibility-spec)
21701 (assq 'org-link buffer-invisibility-spec))
21702 (while (setq b (text-property-any 0 (length s)
21703 'invisible 'org-link s))
21704 (setq s (concat (substring s 0 b)
21705 (substring s (or (next-single-property-change
21706 b 'invisible s) (length s)))))))
21707 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21708 (setq s (concat (substring s 0 b)
21709 (substring s (or (next-single-property-change
21710 b 'org-cwidth s) (length s))))))
21711 (setq l (string-width s) b -1)
21712 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21713 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21716 (defun org-shorten-string (s maxlength)
21717 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21718 If the string is shorter or has length MAXLENGTH, just return the
21719 original string. If it is longer, the functions finds a space in the
21720 string, breaks this string off at that locations and adds three dots
21721 as ellipsis. Including the ellipsis, the string will not be longer
21722 than MAXLENGTH. If finding a good breaking point in the string does
21723 not work, the string is just chopped off in the middle of a word
21724 if necessary."
21725 (if (<= (length s) maxlength)
21727 (let* ((n (max (- maxlength 4) 1))
21728 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21729 (if (string-match re s)
21730 (concat (match-string 1 s) "...")
21731 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21733 (defun org-get-indentation (&optional line)
21734 "Get the indentation of the current line, interpreting tabs.
21735 When LINE is given, assume it represents a line and compute its indentation."
21736 (if line
21737 (if (string-match "^ *" (org-remove-tabs line))
21738 (match-end 0))
21739 (save-excursion
21740 (beginning-of-line 1)
21741 (skip-chars-forward " \t")
21742 (current-column))))
21744 (defun org-get-string-indentation (s)
21745 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21746 (let ((n -1) (i 0) (w tab-width) c)
21747 (catch 'exit
21748 (while (< (setq n (1+ n)) (length s))
21749 (setq c (aref s n))
21750 (cond ((= c ?\ ) (setq i (1+ i)))
21751 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21752 (t (throw 'exit t)))))
21755 (defun org-remove-tabs (s &optional width)
21756 "Replace tabulators in S with spaces.
21757 Assumes that s is a single line, starting in column 0."
21758 (setq width (or width tab-width))
21759 (while (string-match "\t" s)
21760 (setq s (replace-match
21761 (make-string
21762 (- (* width (/ (+ (match-beginning 0) width) width))
21763 (match-beginning 0)) ?\ )
21764 t t s)))
21767 (defun org-fix-indentation (line ind)
21768 "Fix indentation in LINE.
21769 IND is a cons cell with target and minimum indentation.
21770 If the current indentation in LINE is smaller than the minimum,
21771 leave it alone. If it is larger than ind, set it to the target."
21772 (let* ((l (org-remove-tabs line))
21773 (i (org-get-indentation l))
21774 (i1 (car ind)) (i2 (cdr ind)))
21775 (if (>= i i2) (setq l (substring line i2)))
21776 (if (> i1 0)
21777 (concat (make-string i1 ?\ ) l)
21778 l)))
21780 (defun org-remove-indentation (code &optional n)
21781 "Remove the maximum common indentation from the lines in CODE.
21782 N may optionally be the number of spaces to remove."
21783 (with-temp-buffer
21784 (insert code)
21785 (org-do-remove-indentation n)
21786 (buffer-string)))
21788 (defun org-do-remove-indentation (&optional n)
21789 "Remove the maximum common indentation from the buffer."
21790 (untabify (point-min) (point-max))
21791 (let ((min 10000) re)
21792 (if n
21793 (setq min n)
21794 (goto-char (point-min))
21795 (while (re-search-forward "^ *[^ \n]" nil t)
21796 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21797 (unless (or (= min 0) (= min 10000))
21798 (setq re (format "^ \\{%d\\}" min))
21799 (goto-char (point-min))
21800 (while (re-search-forward re nil t)
21801 (replace-match "")
21802 (end-of-line 1))
21803 min)))
21805 (defun org-fill-template (template alist)
21806 "Find each %key of ALIST in TEMPLATE and replace it."
21807 (let ((case-fold-search nil)
21808 entry key value)
21809 (setq alist (sort (copy-sequence alist)
21810 (lambda (a b) (< (length (car a)) (length (car b))))))
21811 (while (setq entry (pop alist))
21812 (setq template
21813 (replace-regexp-in-string
21814 (concat "%" (regexp-quote (car entry)))
21815 (or (cdr entry) "") template t t)))
21816 template))
21818 (defun org-base-buffer (buffer)
21819 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21820 (if (not buffer)
21821 buffer
21822 (or (buffer-base-buffer buffer)
21823 buffer)))
21825 (defun org-wrap (string &optional width lines)
21826 "Wrap string to either a number of lines, or a width in characters.
21827 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21828 that costs. If there is a word longer than WIDTH, the text is actually
21829 wrapped to the length of that word.
21830 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21831 many lines, whatever width that takes.
21832 The return value is a list of lines, without newlines at the end."
21833 (let* ((words (org-split-string string "[ \t\n]+"))
21834 (maxword (apply 'max (mapcar 'org-string-width words)))
21835 w ll)
21836 (cond (width
21837 (org-do-wrap words (max maxword width)))
21838 (lines
21839 (setq w maxword)
21840 (setq ll (org-do-wrap words maxword))
21841 (if (<= (length ll) lines)
21843 (setq ll words)
21844 (while (> (length ll) lines)
21845 (setq w (1+ w))
21846 (setq ll (org-do-wrap words w)))
21847 ll))
21848 (t (error "Cannot wrap this")))))
21850 (defun org-do-wrap (words width)
21851 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21852 (let (lines line)
21853 (while words
21854 (setq line (pop words))
21855 (while (and words (< (+ (length line) (length (car words))) width))
21856 (setq line (concat line " " (pop words))))
21857 (setq lines (push line lines)))
21858 (nreverse lines)))
21860 (defun org-split-string (string &optional separators)
21861 "Splits STRING into substrings at SEPARATORS.
21862 No empty strings are returned if there are matches at the beginning
21863 and end of string."
21864 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21865 (start 0)
21866 notfirst
21867 (list nil))
21868 (while (and (string-match rexp string
21869 (if (and notfirst
21870 (= start (match-beginning 0))
21871 (< start (length string)))
21872 (1+ start) start))
21873 (< (match-beginning 0) (length string)))
21874 (setq notfirst t)
21875 (or (eq (match-beginning 0) 0)
21876 (and (eq (match-beginning 0) (match-end 0))
21877 (eq (match-beginning 0) start))
21878 (setq list
21879 (cons (substring string start (match-beginning 0))
21880 list)))
21881 (setq start (match-end 0)))
21882 (or (eq start (length string))
21883 (setq list
21884 (cons (substring string start)
21885 list)))
21886 (nreverse list)))
21888 (defun org-quote-vert (s)
21889 "Replace \"|\" with \"\\vert\"."
21890 (while (string-match "|" s)
21891 (setq s (replace-match "\\vert" t t s)))
21894 (defun org-uuidgen-p (s)
21895 "Is S an ID created by UUIDGEN?"
21896 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21898 (defun org-in-src-block-p (&optional inside)
21899 "Whether point is in a code source block.
21900 When INSIDE is non-nil, don't consider we are within a src block
21901 when point is at #+BEGIN_SRC or #+END_SRC."
21902 (let ((case-fold-search t) ov)
21903 (or (and (eq (get-char-property (point) 'src-block) t))
21904 (and (not inside)
21905 (save-match-data
21906 (save-excursion
21907 (beginning-of-line)
21908 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21910 (defun org-context ()
21911 "Return a list of contexts of the current cursor position.
21912 If several contexts apply, all are returned.
21913 Each context entry is a list with a symbol naming the context, and
21914 two positions indicating start and end of the context. Possible
21915 contexts are:
21917 :headline anywhere in a headline
21918 :headline-stars on the leading stars in a headline
21919 :todo-keyword on a TODO keyword (including DONE) in a headline
21920 :tags on the TAGS in a headline
21921 :priority on the priority cookie in a headline
21922 :item on the first line of a plain list item
21923 :item-bullet on the bullet/number of a plain list item
21924 :checkbox on the checkbox in a plain list item
21925 :table in an org-mode table
21926 :table-special on a special filed in a table
21927 :table-table in a table.el table
21928 :clocktable in a clocktable
21929 :src-block in a source block
21930 :link on a hyperlink
21931 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21932 :target on a <<target>>
21933 :radio-target on a <<<radio-target>>>
21934 :latex-fragment on a LaTeX fragment
21935 :latex-preview on a LaTeX fragment with overlaid preview image
21937 This function expects the position to be visible because it uses font-lock
21938 faces as a help to recognize the following contexts: :table-special, :link,
21939 and :keyword."
21940 (let* ((f (get-text-property (point) 'face))
21941 (faces (if (listp f) f (list f)))
21942 (case-fold-search t)
21943 (p (point)) clist o)
21944 ;; First the large context
21945 (cond
21946 ((org-at-heading-p t)
21947 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21948 (when (progn
21949 (beginning-of-line 1)
21950 (looking-at org-todo-line-tags-regexp))
21951 (push (org-point-in-group p 1 :headline-stars) clist)
21952 (push (org-point-in-group p 2 :todo-keyword) clist)
21953 (push (org-point-in-group p 4 :tags) clist))
21954 (goto-char p)
21955 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21956 (if (looking-at "\\[#[A-Z0-9]\\]")
21957 (push (org-point-in-group p 0 :priority) clist)))
21959 ((org-at-item-p)
21960 (push (org-point-in-group p 2 :item-bullet) clist)
21961 (push (list :item (point-at-bol)
21962 (save-excursion (org-end-of-item) (point)))
21963 clist)
21964 (and (org-at-item-checkbox-p)
21965 (push (org-point-in-group p 0 :checkbox) clist)))
21967 ((org-at-table-p)
21968 (push (list :table (org-table-begin) (org-table-end)) clist)
21969 (if (memq 'org-formula faces)
21970 (push (list :table-special
21971 (previous-single-property-change p 'face)
21972 (next-single-property-change p 'face)) clist)))
21973 ((org-at-table-p 'any)
21974 (push (list :table-table) clist)))
21975 (goto-char p)
21977 (let ((case-fold-search t))
21978 ;; New the "medium" contexts: clocktables, source blocks
21979 (cond ((org-in-clocktable-p)
21980 (push (list :clocktable
21981 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21982 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21983 (match-beginning 1))
21984 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21985 (match-end 0))) clist))
21986 ((org-in-src-block-p)
21987 (push (list :src-block
21988 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21989 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21990 (match-beginning 1))
21991 (and (search-forward "#+END_SRC" nil t)
21992 (match-beginning 0))) clist))))
21993 (goto-char p)
21995 ;; Now the small context
21996 (cond
21997 ((org-at-timestamp-p)
21998 (push (org-point-in-group p 0 :timestamp) clist))
21999 ((memq 'org-link faces)
22000 (push (list :link
22001 (previous-single-property-change p 'face)
22002 (next-single-property-change p 'face)) clist))
22003 ((memq 'org-special-keyword faces)
22004 (push (list :keyword
22005 (previous-single-property-change p 'face)
22006 (next-single-property-change p 'face)) clist))
22007 ((org-at-target-p)
22008 (push (org-point-in-group p 0 :target) clist)
22009 (goto-char (1- (match-beginning 0)))
22010 (if (looking-at org-radio-target-regexp)
22011 (push (org-point-in-group p 0 :radio-target) clist))
22012 (goto-char p))
22013 ((setq o (car (delq nil
22014 (mapcar
22015 (lambda (x)
22016 (if (memq x org-latex-fragment-image-overlays) x))
22017 (overlays-at (point))))))
22018 (push (list :latex-fragment
22019 (overlay-start o) (overlay-end o)) clist)
22020 (push (list :latex-preview
22021 (overlay-start o) (overlay-end o)) clist))
22022 ((org-inside-LaTeX-fragment-p)
22023 ;; FIXME: positions wrong.
22024 (push (list :latex-fragment (point) (point)) clist)))
22026 (setq clist (nreverse (delq nil clist)))
22027 clist))
22029 ;; FIXME: Compare with at-regexp-p Do we need both?
22030 (defun org-in-regexp (re &optional nlines visually)
22031 "Check if point is inside a match of regexp.
22032 Normally only the current line is checked, but you can include NLINES extra
22033 lines both before and after point into the search.
22034 If VISUALLY is set, require that the cursor is not after the match but
22035 really on, so that the block visually is on the match."
22036 (catch 'exit
22037 (let ((pos (point))
22038 (eol (point-at-eol (+ 1 (or nlines 0))))
22039 (inc (if visually 1 0)))
22040 (save-excursion
22041 (beginning-of-line (- 1 (or nlines 0)))
22042 (while (re-search-forward re eol t)
22043 (if (and (<= (match-beginning 0) pos)
22044 (>= (+ inc (match-end 0)) pos))
22045 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22047 (defun org-at-regexp-p (regexp)
22048 "Is point inside a match of REGEXP in the current line?"
22049 (catch 'exit
22050 (save-excursion
22051 (let ((pos (point)) (end (point-at-eol)))
22052 (beginning-of-line 1)
22053 (while (re-search-forward regexp end t)
22054 (if (and (<= (match-beginning 0) pos)
22055 (>= (match-end 0) pos))
22056 (throw 'exit t)))
22057 nil))))
22059 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22060 "Non-nil when point is between matches of START-RE and END-RE.
22062 Also return a non-nil value when point is on one of the matches.
22064 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22065 buffer positions. Default values are the positions of headlines
22066 surrounding the point.
22068 The functions returns a cons cell whose car (resp. cdr) is the
22069 position before START-RE (resp. after END-RE)."
22070 (save-match-data
22071 (let ((pos (point))
22072 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22073 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22074 beg end)
22075 (save-excursion
22076 ;; Point is on a block when on START-RE or if START-RE can be
22077 ;; found before it...
22078 (and (or (org-at-regexp-p start-re)
22079 (re-search-backward start-re limit-up t))
22080 (setq beg (match-beginning 0))
22081 ;; ... and END-RE after it...
22082 (goto-char (match-end 0))
22083 (re-search-forward end-re limit-down t)
22084 (> (setq end (match-end 0)) pos)
22085 ;; ... without another START-RE in-between.
22086 (goto-char (match-beginning 0))
22087 (not (re-search-backward start-re (1+ beg) t))
22088 ;; Return value.
22089 (cons beg end))))))
22091 (defun org-in-block-p (names)
22092 "Non-nil when point belongs to a block whose name belongs to NAMES.
22094 NAMES is a list of strings containing names of blocks.
22096 Return first block name matched, or nil. Beware that in case of
22097 nested blocks, the returned name may not belong to the closest
22098 block from point."
22099 (save-match-data
22100 (catch 'exit
22101 (let ((case-fold-search t)
22102 (lim-up (save-excursion (outline-previous-heading)))
22103 (lim-down (save-excursion (outline-next-heading))))
22104 (mapc (lambda (name)
22105 (let ((n (regexp-quote name)))
22106 (when (org-between-regexps-p
22107 (concat "^[ \t]*#\\+begin_" n)
22108 (concat "^[ \t]*#\\+end_" n)
22109 lim-up lim-down)
22110 (throw 'exit n))))
22111 names))
22112 nil)))
22114 (defun org-in-drawer-p ()
22115 "Non-nil if point is within a drawer.
22116 If point is within a drawer, return it, as parsed data."
22117 (let ((element (save-match-data (org-element-at-point))))
22118 (while (and element (not (memq (org-element-type element)
22119 '(drawer property-drawer))))
22120 (setq element (org-element-property :parent element)))
22121 element))
22123 (defun org-occur-in-agenda-files (regexp &optional nlines)
22124 "Call `multi-occur' with buffers for all agenda files."
22125 (interactive "sOrg-files matching: \np")
22126 (let* ((files (org-agenda-files))
22127 (tnames (mapcar 'file-truename files))
22128 (extra org-agenda-text-search-extra-files)
22130 (when (eq (car extra) 'agenda-archives)
22131 (setq extra (cdr extra))
22132 (setq files (org-add-archive-files files)))
22133 (while (setq f (pop extra))
22134 (unless (member (file-truename f) tnames)
22135 (add-to-list 'files f 'append)
22136 (add-to-list 'tnames (file-truename f) 'append)))
22137 (multi-occur
22138 (mapcar (lambda (x)
22139 (with-current-buffer
22140 (or (get-file-buffer x) (find-file-noselect x))
22141 (widen)
22142 (current-buffer)))
22143 files)
22144 regexp)))
22146 (if (boundp 'occur-mode-find-occurrence-hook)
22147 ;; Emacs 23
22148 (add-hook 'occur-mode-find-occurrence-hook
22149 (lambda ()
22150 (when (derived-mode-p 'org-mode)
22151 (org-reveal))))
22152 ;; Emacs 22
22153 (defadvice occur-mode-goto-occurrence
22154 (after org-occur-reveal activate)
22155 (and (derived-mode-p 'org-mode) (org-reveal)))
22156 (defadvice occur-mode-goto-occurrence-other-window
22157 (after org-occur-reveal activate)
22158 (and (derived-mode-p 'org-mode) (org-reveal)))
22159 (defadvice occur-mode-display-occurrence
22160 (after org-occur-reveal activate)
22161 (when (derived-mode-p 'org-mode)
22162 (let ((pos (occur-mode-find-occurrence)))
22163 (with-current-buffer (marker-buffer pos)
22164 (save-excursion
22165 (goto-char pos)
22166 (org-reveal)))))))
22168 (defun org-occur-link-in-agenda-files ()
22169 "Create a link and search for it in the agendas.
22170 The link is not stored in `org-stored-links', it is just created
22171 for the search purpose."
22172 (interactive)
22173 (let ((link (condition-case nil
22174 (org-store-link nil)
22175 (error "Unable to create a link to here"))))
22176 (org-occur-in-agenda-files (regexp-quote link))))
22178 (defun org-reverse-string (string)
22179 "Return the reverse of STRING."
22180 (apply 'string (reverse (string-to-list string))))
22182 ;; defsubst org-uniquify must be defined before first use
22184 (defun org-uniquify-alist (alist)
22185 "Merge elements of ALIST with the same key.
22187 For example, in this alist:
22189 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22190 => '((a 1 3) (b 2))
22192 merge (a 1) and (a 3) into (a 1 3).
22194 The function returns the new ALIST."
22195 (let (rtn)
22196 (mapc
22197 (lambda (e)
22198 (let (n)
22199 (if (not (assoc (car e) rtn))
22200 (push e rtn)
22201 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22202 (setq rtn (assq-delete-all (car e) rtn))
22203 (push n rtn))))
22204 alist)
22205 rtn))
22207 (defun org-delete-all (elts list)
22208 "Remove all elements in ELTS from LIST."
22209 (while elts
22210 (setq list (delete (pop elts) list)))
22211 list)
22213 (defun org-count (cl-item cl-seq)
22214 "Count the number of occurrences of ITEM in SEQ.
22215 Taken from `count' in cl-seq.el with all keyword arguments removed."
22216 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22217 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22218 (while (< cl-start cl-end)
22219 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22220 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22221 (setq cl-start (1+ cl-start)))
22222 cl-count))
22224 (defun org-remove-if (predicate seq)
22225 "Remove everything from SEQ that fulfills PREDICATE."
22226 (let (res e)
22227 (while seq
22228 (setq e (pop seq))
22229 (if (not (funcall predicate e)) (push e res)))
22230 (nreverse res)))
22232 (defun org-remove-if-not (predicate seq)
22233 "Remove everything from SEQ that does not fulfill PREDICATE."
22234 (let (res e)
22235 (while seq
22236 (setq e (pop seq))
22237 (if (funcall predicate e) (push e res)))
22238 (nreverse res)))
22240 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22241 "Reduce two-argument FUNCTION across SEQ.
22242 Taken from `reduce' in cl-seq.el with all keyword arguments but
22243 \":initial-value\" removed."
22244 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22245 (cadr (memq :initial-value cl-keys)))
22246 (cl-seq (pop cl-seq))
22247 (t (funcall cl-func)))))
22248 (while cl-seq
22249 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22250 cl-accum))
22252 (defun org-every (pred seq)
22253 "Return true if PREDICATE is true of every element of SEQ.
22254 Adapted from `every' in cl.el."
22255 (catch 'org-every
22256 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22259 (defun org-some (pred seq)
22260 "Return true if PREDICATE is true of any element of SEQ.
22261 Adapted from `some' in cl.el."
22262 (catch 'org-some
22263 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22264 nil))
22266 (defun org-back-over-empty-lines ()
22267 "Move backwards over whitespace, to the beginning of the first empty line.
22268 Returns the number of empty lines passed."
22269 (let ((pos (point)))
22270 (if (cdr (assoc 'heading org-blank-before-new-entry))
22271 (skip-chars-backward " \t\n\r")
22272 (unless (eobp)
22273 (forward-line -1)))
22274 (beginning-of-line 2)
22275 (goto-char (min (point) pos))
22276 (count-lines (point) pos)))
22278 (defun org-skip-whitespace ()
22279 (skip-chars-forward " \t\n\r"))
22281 (defun org-point-in-group (point group &optional context)
22282 "Check if POINT is in match-group GROUP.
22283 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22284 match. If the match group does not exist or point is not inside it,
22285 return nil."
22286 (and (match-beginning group)
22287 (>= point (match-beginning group))
22288 (<= point (match-end group))
22289 (if context
22290 (list context (match-beginning group) (match-end group))
22291 t)))
22293 (defun org-switch-to-buffer-other-window (&rest args)
22294 "Switch to buffer in a second window on the current frame.
22295 In particular, do not allow pop-up frames.
22296 Returns the newly created buffer."
22297 (org-no-popups
22298 (apply 'switch-to-buffer-other-window args)))
22300 (defun org-combine-plists (&rest plists)
22301 "Create a single property list from all plists in PLISTS.
22302 The process starts by copying the first list, and then setting properties
22303 from the other lists. Settings in the last list are the most significant
22304 ones and overrule settings in the other lists."
22305 (let ((rtn (copy-sequence (pop plists)))
22306 p v ls)
22307 (while plists
22308 (setq ls (pop plists))
22309 (while ls
22310 (setq p (pop ls) v (pop ls))
22311 (setq rtn (plist-put rtn p v))))
22312 rtn))
22314 (defun org-replace-escapes (string table)
22315 "Replace %-escapes in STRING with values in TABLE.
22316 TABLE is an association list with keys like \"%a\" and string values.
22317 The sequences in STRING may contain normal field width and padding information,
22318 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22319 so values can contain further %-escapes if they are define later in TABLE."
22320 (let ((tbl (copy-alist table))
22321 (case-fold-search nil)
22322 (pchg 0)
22323 e re rpl)
22324 (while (setq e (pop tbl))
22325 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22326 (when (and (cdr e) (string-match re (cdr e)))
22327 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22328 (safe "SREF"))
22329 (add-text-properties 0 3 (list 'sref sref) safe)
22330 (setcdr e (replace-match safe t t (cdr e)))))
22331 (while (string-match re string)
22332 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22333 (cdr e)))
22334 (setq string (replace-match rpl t t string))))
22335 (while (setq pchg (next-property-change pchg string))
22336 (let ((sref (get-text-property pchg 'sref string)))
22337 (when (and sref (string-match "SREF" string pchg))
22338 (setq string (replace-match sref t t string)))))
22339 string))
22341 (defun org-sublist (list start end)
22342 "Return a section of LIST, from START to END.
22343 Counting starts at 1."
22344 (let (rtn (c start))
22345 (setq list (nthcdr (1- start) list))
22346 (while (and list (<= c end))
22347 (push (pop list) rtn)
22348 (setq c (1+ c)))
22349 (nreverse rtn)))
22351 (defun org-find-base-buffer-visiting (file)
22352 "Like `find-buffer-visiting' but always return the base buffer and
22353 not an indirect buffer."
22354 (let ((buf (or (get-file-buffer file)
22355 (find-buffer-visiting file))))
22356 (if buf
22357 (or (buffer-base-buffer buf) buf)
22358 nil)))
22360 (defun org-image-file-name-regexp (&optional extensions)
22361 "Return regexp matching the file names of images.
22362 If EXTENSIONS is given, only match these."
22363 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22364 (image-file-name-regexp)
22365 (let ((image-file-name-extensions
22366 (or extensions
22367 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22368 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22369 (concat "\\."
22370 (regexp-opt (nconc (mapcar 'upcase
22371 image-file-name-extensions)
22372 image-file-name-extensions)
22374 "\\'"))))
22376 (defun org-file-image-p (file &optional extensions)
22377 "Return non-nil if FILE is an image."
22378 (save-match-data
22379 (string-match (org-image-file-name-regexp extensions) file)))
22381 (defun org-get-cursor-date (&optional with-time)
22382 "Return the date at cursor in as a time.
22383 This works in the calendar and in the agenda, anywhere else it just
22384 returns the current time.
22385 If WITH-TIME is non-nil, returns the time of the event at point (in
22386 the agenda) or the current time of the day."
22387 (let (date day defd tp tm hod mod)
22388 (when with-time
22389 (setq tp (get-text-property (point) 'time))
22390 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22391 (setq hod (string-to-number (match-string 1 tp))
22392 mod (string-to-number (match-string 2 tp))))
22393 (or tp (setq hod (nth 2 (decode-time (current-time)))
22394 mod (nth 1 (decode-time (current-time))))))
22395 (cond
22396 ((eq major-mode 'calendar-mode)
22397 (setq date (calendar-cursor-to-date)
22398 defd (encode-time 0 (or mod 0) (or hod 0)
22399 (nth 1 date) (nth 0 date) (nth 2 date))))
22400 ((eq major-mode 'org-agenda-mode)
22401 (setq day (get-text-property (point) 'day))
22402 (if day
22403 (setq date (calendar-gregorian-from-absolute day)
22404 defd (encode-time 0 (or mod 0) (or hod 0)
22405 (nth 1 date) (nth 0 date) (nth 2 date))))))
22406 (or defd (current-time))))
22408 (defun org-mark-subtree (&optional up)
22409 "Mark the current subtree.
22410 This puts point at the start of the current subtree, and mark at
22411 the end. If a numeric prefix UP is given, move up into the
22412 hierarchy of headlines by UP levels before marking the subtree."
22413 (interactive "P")
22414 (org-with-limited-levels
22415 (cond ((org-at-heading-p) (beginning-of-line))
22416 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22417 (t (outline-previous-visible-heading 1))))
22418 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22419 (if (org-called-interactively-p 'any)
22420 (call-interactively 'org-mark-element)
22421 (org-mark-element)))
22424 ;;; Indentation
22426 (defun org--get-expected-indentation (element contentsp)
22427 "Expected indentation column for current line, according to ELEMENT.
22428 ELEMENT is an element containing point. CONTENTSP is non-nil
22429 when indentation is to be computed according to contents of
22430 ELEMENT."
22431 (let ((type (org-element-type element))
22432 (start (org-element-property :begin element)))
22433 (org-with-wide-buffer
22434 (cond
22435 (contentsp
22436 (case type
22437 (footnote-definition 0)
22438 ((headline inlinetask nil)
22439 (if (not org-adapt-indentation) 0
22440 (let ((level (org-current-level)))
22441 (if level (1+ level) 0))))
22442 (item
22443 (org-list-item-body-column
22444 (org-element-property :post-affiliated element)))
22445 (plain-list
22446 (save-excursion
22447 (goto-char (org-element-property :post-affiliated element))
22448 (org-get-indentation)))
22449 (otherwise
22450 (goto-char start)
22451 (org-get-indentation))))
22452 ((memq type '(headline inlinetask nil))
22453 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22454 (org--get-expected-indentation element t)
22456 ((eq type 'footnote-definition) 0)
22457 ;; First paragraph of a footnote definition or an item.
22458 ;; Indent like parent.
22459 ((< (line-beginning-position) start)
22460 (org--get-expected-indentation
22461 (org-element-property :parent element) t))
22462 ;; At first line: indent according to previous sibling, if any,
22463 ;; ignoring footnote definitions and inline tasks, or parent's
22464 ;; contents.
22465 ((= (line-beginning-position) start)
22466 (catch 'exit
22467 (while t
22468 (if (= (point-min) start) (throw 'exit 0)
22469 (goto-char (1- start))
22470 (let* ((previous (org-element-at-point))
22471 (parent previous))
22472 (while (and parent (<= (org-element-property :end parent) start))
22473 (setq previous parent
22474 parent (org-element-property :parent parent)))
22475 (cond
22476 ((not previous) (throw 'exit 0))
22477 ((> (org-element-property :end previous) start)
22478 (throw 'exit (org--get-expected-indentation previous t)))
22479 ((memq (org-element-type previous)
22480 '(footnote-definition inlinetask))
22481 (setq start (org-element-property :begin previous)))
22482 (t (goto-char (org-element-property :begin previous))
22483 (throw 'exit
22484 (if (bolp) (org-get-indentation)
22485 ;; At first paragraph in an item or
22486 ;; a footnote definition.
22487 (org--get-expected-indentation
22488 (org-element-property :parent previous) t))))))))))
22489 ;; Otherwise, move to the first non-blank line above.
22491 (beginning-of-line)
22492 (let ((pos (point)))
22493 (skip-chars-backward " \r\t\n")
22494 (cond
22495 ;; Two blank lines end a footnote definition or a plain
22496 ;; list. When we indent an empty line after them, the
22497 ;; containing list or footnote definition is over, so it
22498 ;; qualifies as a previous sibling. Therefore, we indent
22499 ;; like its first line.
22500 ((and (memq type '(footnote-definition plain-list))
22501 (> (count-lines (point) pos) 2))
22502 (goto-char start)
22503 (org-get-indentation))
22504 ;; Line above is the first one of a paragraph at the
22505 ;; beginning of an item or a footnote definition. Indent
22506 ;; like parent.
22507 ((< (line-beginning-position) start)
22508 (org--get-expected-indentation
22509 (org-element-property :parent element) t))
22510 ;; POS is after contents in a greater element. Indent like
22511 ;; the beginning of the element.
22513 ;; As a special case, if point is at the end of a footnote
22514 ;; definition or an item, indent like the very last element
22515 ;; within.
22516 ((let ((cend (org-element-property :contents-end element)))
22517 (and cend (<= cend pos)))
22518 (if (memq type '(footnote-definition item plain-list))
22519 (org--get-expected-indentation (org-element-at-point) nil)
22520 (goto-char start)
22521 (org-get-indentation)))
22522 ;; In any other case, indent like the current line.
22523 (t (org-get-indentation)))))))))
22525 (defun org--align-node-property ()
22526 "Align node property at point.
22527 Alignment is done according to `org-property-format', which see."
22528 (when (save-excursion
22529 (beginning-of-line)
22530 (looking-at org-property-re))
22531 (replace-match
22532 (concat (match-string 4)
22533 (org-trim
22534 (format org-property-format (match-string 1) (match-string 3))))
22535 t t)))
22537 (defun org-indent-line ()
22538 "Indent line depending on context.
22540 Indentation is done according to the following rules:
22542 - Footnote definitions, headlines and inline tasks have to
22543 start at column 0.
22545 - On the very first line of an element, consider, in order, the
22546 next rules until one matches:
22548 1. If there's a sibling element before, ignoring footnote
22549 definitions and inline tasks, indent like its first line.
22551 2. If element has a parent, indent like its contents. More
22552 precisely, if parent is an item, indent after the
22553 description part, if any, or the bullet (see
22554 ``org-list-description-max-indent'). Else, indent like
22555 parent's first line.
22557 3. Otherwise, indent relatively to current level, if
22558 `org-adapt-indentation' is non-nil, or to left margin.
22560 - On a blank line at the end of a plain list, an item, or
22561 a footnote definition, indent like the very last element
22562 within.
22564 - In the code part of a source block, use language major mode
22565 to indent current line if `org-src-tab-acts-natively' is
22566 non-nil. If it is nil, do nothing.
22568 - Otherwise, indent like the first non-blank line above.
22570 The function doesn't indent an item as it could break the whole
22571 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22572 \\[org-shiftmetaright].
22574 Also align node properties according to `org-property-format'."
22575 (interactive)
22576 (cond
22577 (orgstruct-is-++
22578 (let ((indent-line-function
22579 (cadadr (assq 'indent-line-function org-fb-vars))))
22580 (indent-according-to-mode)))
22581 ((org-at-heading-p) 'noindent)
22583 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22584 (type (org-element-type element)))
22585 (cond ((and (memq type '(plain-list item))
22586 (= (line-beginning-position)
22587 (org-element-property :post-affiliated element)))
22588 'noindent)
22589 ((and (eq type 'src-block)
22590 org-src-tab-acts-natively
22591 (> (line-beginning-position)
22592 (org-element-property :post-affiliated element))
22593 (< (line-beginning-position)
22594 (org-with-wide-buffer
22595 (goto-char (org-element-property :end element))
22596 (skip-chars-backward " \r\t\n")
22597 (line-beginning-position))))
22598 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22599 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22601 (let ((column (org--get-expected-indentation element nil)))
22602 ;; Preserve current column.
22603 (if (<= (current-column) (current-indentation))
22604 (org-indent-line-to column)
22605 (save-excursion (org-indent-line-to column))))
22606 ;; Align node property. Also preserve current column.
22607 (when (eq type 'node-property)
22608 (let ((column (current-column)))
22609 (org--align-node-property)
22610 (org-move-to-column column)))))))))
22612 (defun org-indent-region (start end)
22613 "Indent each non-blank line in the region.
22614 Called from a program, START and END specify the region to
22615 indent. The function will not indent contents of example blocks,
22616 verse blocks and export blocks as leading white spaces are
22617 assumed to be significant there."
22618 (interactive "r")
22619 (save-excursion
22620 (goto-char start)
22621 (skip-chars-forward " \r\t\n")
22622 (unless (eobp) (beginning-of-line))
22623 (let ((indent-to
22624 (lambda (ind pos)
22625 ;; Set IND as indentation for all lines between point and
22626 ;; POS or END, whichever comes first. Blank lines are
22627 ;; ignored. Leave point after POS once done.
22628 (let ((limit (copy-marker (min end pos))))
22629 (while (< (point) limit)
22630 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22631 (forward-line))
22632 (set-marker limit nil))))
22633 (end (copy-marker end)))
22634 (while (< (point) end)
22635 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22636 (let* ((element (org-element-at-point))
22637 (type (org-element-type element))
22638 (element-end (copy-marker (org-element-property :end element)))
22639 (ind (org--get-expected-indentation element nil)))
22640 (cond
22641 ((or (memq type '(paragraph table table-row))
22642 (not (or (org-element-property :contents-begin element)
22643 (memq type
22644 '(example-block export-block src-block)))))
22645 ;; Elements here are indented as a single block. Also
22646 ;; align node properties.
22647 (when (eq type 'node-property)
22648 (org--align-node-property)
22649 (beginning-of-line))
22650 (funcall indent-to ind element-end))
22652 ;; Elements in this category consist of three parts:
22653 ;; before the contents, the contents, and after the
22654 ;; contents. The contents are treated specially,
22655 ;; according to the element type, or not indented at
22656 ;; all. Other parts are indented as a single block.
22657 (let* ((post (copy-marker
22658 (org-element-property :post-affiliated element)))
22659 (cbeg
22660 (copy-marker
22661 (cond
22662 ((not (org-element-property :contents-begin element))
22663 ;; Fake contents for source blocks.
22664 (org-with-wide-buffer
22665 (goto-char post)
22666 (forward-line)
22667 (point)))
22668 ((memq type '(footnote-definition item plain-list))
22669 ;; Contents in these elements could start on
22670 ;; the same line as the beginning of the
22671 ;; element. Make sure we start indenting
22672 ;; from the second line.
22673 (org-with-wide-buffer
22674 (goto-char post)
22675 (end-of-line)
22676 (skip-chars-forward " \r\t\n")
22677 (if (eobp) (point) (line-beginning-position))))
22678 (t (org-element-property :contents-begin element)))))
22679 (cend (copy-marker
22680 (or (org-element-property :contents-end element)
22681 ;; Fake contents for source blocks.
22682 (org-with-wide-buffer
22683 (goto-char element-end)
22684 (skip-chars-backward " \r\t\n")
22685 (line-beginning-position))))))
22686 ;; Do not change items indentation individually as it
22687 ;; might break the list as a whole. On the other
22688 ;; hand, when at a plain list, indent it as a whole.
22689 (cond ((eq type 'plain-list)
22690 (let ((offset (- ind (org-get-indentation))))
22691 (unless (zerop offset)
22692 (indent-rigidly (org-element-property :begin element)
22693 (org-element-property :end element)
22694 offset))
22695 (goto-char cbeg)))
22696 ((eq type 'item) (goto-char cbeg))
22697 (t (funcall indent-to ind cbeg)))
22698 (when (< (point) end)
22699 (case type
22700 ((example-block export-block verse-block))
22701 (src-block
22702 ;; In a source block, indent source code
22703 ;; according to language major mode, but only if
22704 ;; `org-src-tab-acts-natively' is non-nil.
22705 (when (and (< (point) end) org-src-tab-acts-natively)
22706 (ignore-errors
22707 (let (org-src-strip-leading-and-trailing-blank-lines
22708 ;; Region boundaries in edit buffer.
22709 (start (1+ (- (point) cbeg)))
22710 (end (- (min cend end) cbeg)))
22711 (org-babel-do-in-edit-buffer
22712 (indent-region start end))))))
22713 (t (org-indent-region (point) (min cend end))))
22714 (goto-char (min cend end))
22715 (when (< (point) end) (funcall indent-to ind element-end)))
22716 (set-marker post nil)
22717 (set-marker cbeg nil)
22718 (set-marker cend nil))))
22719 (set-marker element-end nil))))
22720 (set-marker end nil))))
22722 (defun org-indent-drawer ()
22723 "Indent the drawer at point."
22724 (interactive)
22725 (unless (save-excursion
22726 (beginning-of-line)
22727 (org-looking-at-p org-drawer-regexp))
22728 (user-error "Not at a drawer"))
22729 (let ((element (org-element-at-point)))
22730 (unless (memq (org-element-type element) '(drawer property-drawer))
22731 (user-error "Not at a drawer"))
22732 (org-with-wide-buffer
22733 (org-indent-region (org-element-property :begin element)
22734 (org-element-property :end element))))
22735 (message "Drawer at point indented"))
22737 (defun org-indent-block ()
22738 "Indent the block at point."
22739 (interactive)
22740 (unless (save-excursion
22741 (beginning-of-line)
22742 (let ((case-fold-search t))
22743 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22744 (user-error "Not at a block"))
22745 (let ((element (org-element-at-point)))
22746 (unless (memq (org-element-type element)
22747 '(comment-block center-block dynamic-block example-block
22748 export-block quote-block special-block
22749 src-block verse-block))
22750 (user-error "Not at a block"))
22751 (org-with-wide-buffer
22752 (org-indent-region (org-element-property :begin element)
22753 (org-element-property :end element))))
22754 (message "Block at point indented"))
22757 ;;; Filling
22759 ;; We use our own fill-paragraph and auto-fill functions.
22761 ;; `org-fill-paragraph' relies on adaptive filling and context
22762 ;; checking. Appropriate `fill-prefix' is computed with
22763 ;; `org-adaptive-fill-function'.
22765 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22766 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22767 ;; `org-adaptive-fill-function' value. Internally,
22768 ;; `org-comment-line-break-function' breaks the line.
22770 ;; `org-setup-filling' installs filling and auto-filling related
22771 ;; variables during `org-mode' initialization.
22773 (defvar org-element-paragraph-separate) ; org-element.el
22774 (defun org-setup-filling ()
22775 (require 'org-element)
22776 ;; Prevent auto-fill from inserting unwanted new items.
22777 (when (boundp 'fill-nobreak-predicate)
22778 (org-set-local
22779 'fill-nobreak-predicate
22780 (org-uniquify
22781 (append fill-nobreak-predicate
22782 '(org-fill-line-break-nobreak-p
22783 org-fill-paragraph-with-timestamp-nobreak-p)))))
22784 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22785 (org-set-local 'paragraph-start paragraph-ending)
22786 (org-set-local 'paragraph-separate paragraph-ending))
22787 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22788 (org-set-local 'auto-fill-inhibit-regexp nil)
22789 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22790 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22791 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22793 (defun org-fill-line-break-nobreak-p ()
22794 "Non-nil when a new line at point would create an Org line break."
22795 (save-excursion
22796 (skip-chars-backward "[ \t]")
22797 (skip-chars-backward "\\\\")
22798 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22800 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22801 "Non-nil when a new line at point would split a timestamp."
22802 (and (org-at-timestamp-p t)
22803 (not (looking-at org-ts-regexp-both))))
22805 (declare-function message-in-body-p "message" ())
22806 (defvar orgtbl-line-start-regexp) ; From org-table.el
22807 (defun org-adaptive-fill-function ()
22808 "Compute a fill prefix for the current line.
22809 Return fill prefix, as a string, or nil if current line isn't
22810 meant to be filled. For convenience, if `adaptive-fill-regexp'
22811 matches in paragraphs or comments, use it."
22812 (catch 'exit
22813 (when (derived-mode-p 'message-mode)
22814 (save-excursion
22815 (beginning-of-line)
22816 (cond ((or (not (message-in-body-p))
22817 (looking-at orgtbl-line-start-regexp))
22818 (throw 'exit nil))
22819 ((looking-at message-cite-prefix-regexp)
22820 (throw 'exit (match-string-no-properties 0)))
22821 ((looking-at org-outline-regexp)
22822 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22823 (org-with-wide-buffer
22824 (unless (org-at-heading-p)
22825 (let* ((p (line-beginning-position))
22826 (element (save-excursion
22827 (beginning-of-line)
22828 (org-element-at-point)))
22829 (type (org-element-type element))
22830 (post-affiliated (org-element-property :post-affiliated element)))
22831 (unless (< p post-affiliated)
22832 (case type
22833 (comment
22834 (save-excursion
22835 (beginning-of-line)
22836 (looking-at "[ \t]*")
22837 (concat (match-string 0) "# ")))
22838 (footnote-definition "")
22839 ((item plain-list)
22840 (make-string (org-list-item-body-column post-affiliated) ?\s))
22841 (paragraph
22842 ;; Fill prefix is usually the same as the current line,
22843 ;; unless the paragraph is at the beginning of an item.
22844 (let ((parent (org-element-property :parent element)))
22845 (save-excursion
22846 (beginning-of-line)
22847 (cond ((eq (org-element-type parent) 'item)
22848 (make-string (org-list-item-body-column
22849 (org-element-property :begin parent))
22850 ?\s))
22851 ((and adaptive-fill-regexp
22852 ;; Locally disable
22853 ;; `adaptive-fill-function' to let
22854 ;; `fill-context-prefix' handle
22855 ;; `adaptive-fill-regexp' variable.
22856 (let (adaptive-fill-function)
22857 (fill-context-prefix
22858 post-affiliated
22859 (org-element-property :end element)))))
22860 ((looking-at "[ \t]+") (match-string 0))
22861 (t "")))))
22862 (comment-block
22863 ;; Only fill contents if P is within block boundaries.
22864 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22865 (forward-line)
22866 (point)))
22867 (cend (save-excursion
22868 (goto-char (org-element-property :end element))
22869 (skip-chars-backward " \r\t\n")
22870 (line-beginning-position))))
22871 (when (and (>= p cbeg) (< p cend))
22872 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22873 (match-string 0)
22874 "")))))))))))
22876 (declare-function message-goto-body "message" ())
22877 (defvar message-cite-prefix-regexp) ; From message.el
22878 (defun org-fill-paragraph (&optional justify)
22879 "Fill element at point, when applicable.
22881 This function only applies to comment blocks, comments, example
22882 blocks and paragraphs. Also, as a special case, re-align table
22883 when point is at one.
22885 If JUSTIFY is non-nil (interactively, with prefix argument),
22886 justify as well. If `sentence-end-double-space' is non-nil, then
22887 period followed by one space does not end a sentence, so don't
22888 break a line there. The variable `fill-column' controls the
22889 width for filling.
22891 For convenience, when point is at a plain list, an item or
22892 a footnote definition, try to fill the first paragraph within."
22893 (interactive)
22894 (if (and (derived-mode-p 'message-mode)
22895 (or (not (message-in-body-p))
22896 (save-excursion (move-beginning-of-line 1)
22897 (looking-at message-cite-prefix-regexp))))
22898 ;; First ensure filling is correct in message-mode.
22899 (let ((fill-paragraph-function
22900 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22901 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22902 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22903 (paragraph-separate
22904 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22905 (fill-paragraph nil))
22906 (with-syntax-table org-mode-transpose-word-syntax-table
22907 ;; Move to end of line in order to get the first paragraph
22908 ;; within a plain list or a footnote definition.
22909 (let ((element (save-excursion
22910 (end-of-line)
22911 (or (ignore-errors (org-element-at-point))
22912 (user-error "An element cannot be parsed line %d"
22913 (line-number-at-pos (point)))))))
22914 ;; First check if point is in a blank line at the beginning of
22915 ;; the buffer. In that case, ignore filling.
22916 (case (org-element-type element)
22917 ;; Use major mode filling function is src blocks.
22918 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22919 ;; Align Org tables, leave table.el tables as-is.
22920 (table-row (org-table-align) t)
22921 (table
22922 (when (eq (org-element-property :type element) 'org)
22923 (save-excursion
22924 (goto-char (org-element-property :post-affiliated element))
22925 (org-table-align)))
22927 (paragraph
22928 ;; Paragraphs may contain `line-break' type objects.
22929 (let ((beg (max (point-min)
22930 (org-element-property :contents-begin element)))
22931 (end (min (point-max)
22932 (org-element-property :contents-end element))))
22933 ;; Do nothing if point is at an affiliated keyword.
22934 (if (< (line-end-position) beg) t
22935 (when (derived-mode-p 'message-mode)
22936 ;; In `message-mode', do not fill following citation
22937 ;; in current paragraph nor text before message body.
22938 (let ((body-start (save-excursion (message-goto-body))))
22939 (when body-start (setq beg (max body-start beg))))
22940 (when (save-excursion
22941 (re-search-forward
22942 (concat "^" message-cite-prefix-regexp) end t))
22943 (setq end (match-beginning 0))))
22944 ;; Fill paragraph, taking line breaks into account.
22945 (save-excursion
22946 (goto-char beg)
22947 (let ((cuts (list beg)))
22948 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22949 (when (eq 'line-break
22950 (org-element-type
22951 (save-excursion (backward-char)
22952 (org-element-context))))
22953 (push (point) cuts)))
22954 (dolist (c (delq end cuts))
22955 (fill-region-as-paragraph c end justify)
22956 (setq end c))))
22957 t)))
22958 ;; Contents of `comment-block' type elements should be
22959 ;; filled as plain text, but only if point is within block
22960 ;; markers.
22961 (comment-block
22962 (let* ((case-fold-search t)
22963 (beg (save-excursion
22964 (goto-char (org-element-property :begin element))
22965 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22966 (forward-line)
22967 (point)))
22968 (end (save-excursion
22969 (goto-char (org-element-property :end element))
22970 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22971 (line-beginning-position))))
22972 (if (or (< (point) beg) (> (point) end)) t
22973 (fill-region-as-paragraph
22974 (save-excursion (end-of-line)
22975 (re-search-backward "^[ \t]*$" beg 'move)
22976 (line-beginning-position))
22977 (save-excursion (beginning-of-line)
22978 (re-search-forward "^[ \t]*$" end 'move)
22979 (line-beginning-position))
22980 justify))))
22981 ;; Fill comments.
22982 (comment
22983 (let ((begin (org-element-property :post-affiliated element))
22984 (end (org-element-property :end element)))
22985 (when (and (>= (point) begin) (<= (point) end))
22986 (let ((begin (save-excursion
22987 (end-of-line)
22988 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22989 (progn (forward-line) (point))
22990 begin)))
22991 (end (save-excursion
22992 (end-of-line)
22993 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22994 (1- (line-beginning-position))
22995 (skip-chars-backward " \r\t\n")
22996 (line-end-position)))))
22997 ;; Do not fill comments when at a blank line.
22998 (when (> end begin)
22999 (let ((fill-prefix
23000 (save-excursion
23001 (beginning-of-line)
23002 (looking-at "[ \t]*#")
23003 (let ((comment-prefix (match-string 0)))
23004 (goto-char (match-end 0))
23005 (if (looking-at adaptive-fill-regexp)
23006 (concat comment-prefix (match-string 0))
23007 (concat comment-prefix " "))))))
23008 (save-excursion
23009 (fill-region-as-paragraph begin end justify))))))
23011 ;; Ignore every other element.
23012 (otherwise t))))))
23014 (defun org-auto-fill-function ()
23015 "Auto-fill function."
23016 ;; Check if auto-filling is meaningful.
23017 (let ((fc (current-fill-column)))
23018 (when (and fc (> (current-column) fc))
23019 (let* ((fill-prefix (org-adaptive-fill-function))
23020 ;; Enforce empty fill prefix, if required. Otherwise, it
23021 ;; will be computed again.
23022 (adaptive-fill-mode (not (equal fill-prefix ""))))
23023 (when fill-prefix (do-auto-fill))))))
23025 (defun org-comment-line-break-function (&optional soft)
23026 "Break line at point and indent, continuing comment if within one.
23027 The inserted newline is marked hard if variable
23028 `use-hard-newlines' is true, unless optional argument SOFT is
23029 non-nil."
23030 (if soft (insert-and-inherit ?\n) (newline 1))
23031 (save-excursion (forward-char -1) (delete-horizontal-space))
23032 (delete-horizontal-space)
23033 (indent-to-left-margin)
23034 (insert-before-markers-and-inherit fill-prefix))
23037 ;;; Fixed Width Areas
23039 (defun org-toggle-fixed-width ()
23040 "Toggle fixed-width markup.
23042 Add or remove fixed-width markup on current line, whenever it
23043 makes sense. Return an error otherwise.
23045 If a region is active and if it contains only fixed-width areas
23046 or blank lines, remove all fixed-width markup in it. If the
23047 region contains anything else, convert all non-fixed-width lines
23048 to fixed-width ones.
23050 Blank lines at the end of the region are ignored unless the
23051 region only contains such lines."
23052 (interactive)
23053 (if (not (org-region-active-p))
23054 ;; No region:
23056 ;; Remove fixed width marker only in a fixed-with element.
23058 ;; Add fixed width maker in paragraphs, in blank lines after
23059 ;; elements or at the beginning of a headline or an inlinetask,
23060 ;; and before any one-line elements (e.g., a clock).
23061 (progn
23062 (beginning-of-line)
23063 (let* ((element (org-element-at-point))
23064 (type (org-element-type element)))
23065 (cond
23066 ((and (eq type 'fixed-width)
23067 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23068 (replace-match
23069 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23070 ((and (memq type '(babel-call clock comment diary-sexp headline
23071 horizontal-rule keyword paragraph
23072 planning))
23073 (<= (org-element-property :post-affiliated element) (point)))
23074 (skip-chars-forward " \t")
23075 (insert ": "))
23076 ((and (org-looking-at-p "[ \t]*$")
23077 (or (eq type 'inlinetask)
23078 (save-excursion
23079 (skip-chars-forward " \r\t\n")
23080 (<= (org-element-property :end element) (point)))))
23081 (delete-region (point) (line-end-position))
23082 (org-indent-line)
23083 (insert ": "))
23084 (t (user-error "Cannot insert a fixed-width line here")))))
23085 ;; Region active.
23086 (let* ((begin (save-excursion
23087 (goto-char (region-beginning))
23088 (line-beginning-position)))
23089 (end (copy-marker
23090 (save-excursion
23091 (goto-char (region-end))
23092 (unless (eolp) (beginning-of-line))
23093 (if (save-excursion (re-search-backward "\\S-" begin t))
23094 (progn (skip-chars-backward " \r\t\n") (point))
23095 (point)))))
23096 (all-fixed-width-p
23097 (catch 'not-all-p
23098 (save-excursion
23099 (goto-char begin)
23100 (skip-chars-forward " \r\t\n")
23101 (when (eobp) (throw 'not-all-p nil))
23102 (while (< (point) end)
23103 (let ((element (org-element-at-point)))
23104 (if (eq (org-element-type element) 'fixed-width)
23105 (goto-char (org-element-property :end element))
23106 (throw 'not-all-p nil))))
23107 t))))
23108 (if all-fixed-width-p
23109 (save-excursion
23110 (goto-char begin)
23111 (while (< (point) end)
23112 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23113 (replace-match
23114 "" nil nil nil
23115 (if (= (line-end-position) (match-end 0)) 0 1)))
23116 (forward-line)))
23117 (let ((min-ind (point-max)))
23118 ;; Find minimum indentation across all lines.
23119 (save-excursion
23120 (goto-char begin)
23121 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23122 (setq min-ind 0)
23123 (catch 'zerop
23124 (while (< (point) end)
23125 (unless (org-looking-at-p "[ \t]*$")
23126 (let ((ind (org-get-indentation)))
23127 (setq min-ind (min min-ind ind))
23128 (when (zerop ind) (throw 'zerop t))))
23129 (forward-line)))))
23130 ;; Loop over all lines and add fixed-width markup everywhere
23131 ;; but in fixed-width lines.
23132 (save-excursion
23133 (goto-char begin)
23134 (while (< (point) end)
23135 (cond
23136 ((org-at-heading-p)
23137 (insert ": ")
23138 (forward-line)
23139 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23140 (insert ":")
23141 (forward-line)))
23142 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23143 (let* ((element (org-element-at-point))
23144 (element-end (org-element-property :end element)))
23145 (if (eq (org-element-type element) 'fixed-width)
23146 (progn (goto-char element-end)
23147 (skip-chars-backward " \r\t\n")
23148 (forward-line))
23149 (let ((limit (min end element-end)))
23150 (while (< (point) limit)
23151 (org-move-to-column min-ind t)
23152 (insert ": ")
23153 (forward-line))))))
23155 (org-move-to-column min-ind t)
23156 (insert ": ")
23157 (forward-line)))))))
23158 (set-marker end nil))))
23161 ;;; Comments
23163 ;; Org comments syntax is quite complex. It requires the entire line
23164 ;; to be just a comment. Also, even with the right syntax at the
23165 ;; beginning of line, some some elements (i.e. verse-block or
23166 ;; example-block) don't accept comments. Usual Emacs comment commands
23167 ;; cannot cope with those requirements. Therefore, Org replaces them.
23169 ;; Org still relies on `comment-dwim', but cannot trust
23170 ;; `comment-only-p'. So, `comment-region-function' and
23171 ;; `uncomment-region-function' both point
23172 ;; to`org-comment-or-uncomment-region'. Eventually,
23173 ;; `org-insert-comment' takes care of insertion of comments at the
23174 ;; beginning of line.
23176 ;; `org-setup-comments-handling' install comments related variables
23177 ;; during `org-mode' initialization.
23179 (defun org-setup-comments-handling ()
23180 (interactive)
23181 (org-set-local 'comment-use-syntax nil)
23182 (org-set-local 'comment-start "# ")
23183 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23184 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23185 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23186 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23188 (defun org-insert-comment ()
23189 "Insert an empty comment above current line.
23190 If the line is empty, insert comment at its beginning. When
23191 point is within a source block, comment according to the related
23192 major mode."
23193 (if (let ((element (org-element-at-point)))
23194 (and (eq (org-element-type element) 'src-block)
23195 (< (save-excursion
23196 (goto-char (org-element-property :post-affiliated element))
23197 (line-end-position))
23198 (point))
23199 (> (save-excursion
23200 (goto-char (org-element-property :end element))
23201 (skip-chars-backward " \r\t\n")
23202 (line-beginning-position))
23203 (point))))
23204 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23205 (beginning-of-line)
23206 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23207 (open-line 1))
23208 (org-indent-line)
23209 (insert "# ")))
23211 (defvar comment-empty-lines) ; From newcomment.el.
23212 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23213 "Comment or uncomment each non-blank line in the region.
23214 Uncomment each non-blank line between BEG and END if it only
23215 contains commented lines. Otherwise, comment them. If region is
23216 strictly within a source block, use appropriate comment syntax."
23217 (if (let ((element (org-element-at-point)))
23218 (and (eq (org-element-type element) 'src-block)
23219 (< (save-excursion
23220 (goto-char (org-element-property :post-affiliated element))
23221 (line-end-position))
23222 beg)
23223 (>= (save-excursion
23224 (goto-char (org-element-property :end element))
23225 (skip-chars-backward " \r\t\n")
23226 (line-beginning-position))
23227 end)))
23228 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23229 (save-restriction
23230 ;; Restrict region
23231 (narrow-to-region (save-excursion (goto-char beg)
23232 (skip-chars-forward " \r\t\n" end)
23233 (line-beginning-position))
23234 (save-excursion (goto-char end)
23235 (skip-chars-backward " \r\t\n" beg)
23236 (line-end-position)))
23237 (let ((uncommentp
23238 ;; UNCOMMENTP is non-nil when every non blank line between
23239 ;; BEG and END is a comment.
23240 (save-excursion
23241 (goto-char (point-min))
23242 (while (and (not (eobp))
23243 (let ((element (org-element-at-point)))
23244 (and (eq (org-element-type element) 'comment)
23245 (goto-char (min (point-max)
23246 (org-element-property
23247 :end element)))))))
23248 (eobp))))
23249 (if uncommentp
23250 ;; Only blank lines and comments in region: uncomment it.
23251 (save-excursion
23252 (goto-char (point-min))
23253 (while (not (eobp))
23254 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23255 (replace-match "" nil nil nil 1))
23256 (forward-line)))
23257 ;; Comment each line in region.
23258 (let ((min-indent (point-max)))
23259 ;; First find the minimum indentation across all lines.
23260 (save-excursion
23261 (goto-char (point-min))
23262 (while (and (not (eobp)) (not (zerop min-indent)))
23263 (unless (looking-at "[ \t]*$")
23264 (setq min-indent (min min-indent (current-indentation))))
23265 (forward-line)))
23266 ;; Then loop over all lines.
23267 (save-excursion
23268 (goto-char (point-min))
23269 (while (not (eobp))
23270 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23271 ;; Don't get fooled by invisible text (e.g. link path)
23272 ;; when moving to column MIN-INDENT.
23273 (let ((buffer-invisibility-spec nil))
23274 (org-move-to-column min-indent t))
23275 (insert comment-start))
23276 (forward-line)))))))))
23278 (defun org-comment-dwim (arg)
23279 "Call `comment-dwim' within a source edit buffer if needed."
23280 (interactive "*P")
23281 (if (org-in-src-block-p)
23282 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23283 (call-interactively 'comment-dwim)))
23286 ;;; Planning
23288 ;; This section contains tools to operate on timestamp objects, as
23289 ;; returned by, e.g. `org-element-context'.
23291 (defun org-timestamp-has-time-p (timestamp)
23292 "Non-nil when TIMESTAMP has a time specified."
23293 (org-element-property :hour-start timestamp))
23295 (defun org-timestamp-format (timestamp format &optional end utc)
23296 "Format a TIMESTAMP element into a string.
23298 FORMAT is a format specifier to be passed to
23299 `format-time-string'.
23301 When optional argument END is non-nil, use end of date-range or
23302 time-range, if possible.
23304 When optional argument UTC is non-nil, time will be expressed as
23305 Universal Time."
23306 (format-time-string
23307 format
23308 (apply 'encode-time
23309 (cons 0
23310 (mapcar
23311 (lambda (prop) (or (org-element-property prop timestamp) 0))
23312 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23313 '(:minute-start :hour-start :day-start :month-start
23314 :year-start)))))
23315 utc))
23317 (defun org-timestamp-split-range (timestamp &optional end)
23318 "Extract a timestamp object from a date or time range.
23320 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23321 the end of the range. Otherwise, extract its start.
23323 Return a new timestamp object sharing the same parent as
23324 TIMESTAMP."
23325 (let ((type (org-element-property :type timestamp)))
23326 (if (memq type '(active inactive diary)) timestamp
23327 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23328 ;; Set new type.
23329 (org-element-put-property
23330 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23331 ;; Copy start properties over end properties if END is
23332 ;; non-nil. Otherwise, copy end properties over `start' ones.
23333 (let ((p-alist '((:minute-start . :minute-end)
23334 (:hour-start . :hour-end)
23335 (:day-start . :day-end)
23336 (:month-start . :month-end)
23337 (:year-start . :year-end))))
23338 (dolist (p-cell p-alist)
23339 (org-element-put-property
23340 split-ts
23341 (funcall (if end 'car 'cdr) p-cell)
23342 (org-element-property
23343 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23344 ;; Eventually refresh `:raw-value'.
23345 (org-element-put-property split-ts :raw-value nil)
23346 (org-element-put-property
23347 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23349 (defun org-timestamp-translate (timestamp &optional boundary)
23350 "Apply `org-translate-time' on a TIMESTAMP object.
23351 When optional argument BOUNDARY is non-nil, it is either the
23352 symbol `start' or `end'. In this case, only translate the
23353 starting or ending part of TIMESTAMP if it is a date or time
23354 range. Otherwise, translate both parts."
23355 (if (and (not boundary)
23356 (memq (org-element-property :type timestamp)
23357 '(active-range inactive-range)))
23358 (concat
23359 (org-translate-time
23360 (org-element-property :raw-value
23361 (org-timestamp-split-range timestamp)))
23362 "--"
23363 (org-translate-time
23364 (org-element-property :raw-value
23365 (org-timestamp-split-range timestamp t))))
23366 (org-translate-time
23367 (org-element-property
23368 :raw-value
23369 (if (not boundary) timestamp
23370 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23374 ;;; Other stuff.
23376 (defun org-reftex-citation ()
23377 "Use reftex-citation to insert a citation into the buffer.
23378 This looks for a line like
23380 #+BIBLIOGRAPHY: foo plain option:-d
23382 and derives from it that foo.bib is the bibliography file relevant
23383 for this document. It then installs the necessary environment for RefTeX
23384 to work in this buffer and calls `reftex-citation' to insert a citation
23385 into the buffer.
23387 Export of such citations to both LaTeX and HTML is handled by the contributed
23388 package ox-bibtex by Taru Karttunen."
23389 (interactive)
23390 (let ((reftex-docstruct-symbol 'rds)
23391 (reftex-cite-format "\\cite{%l}")
23392 rds bib)
23393 (save-excursion
23394 (save-restriction
23395 (widen)
23396 (let ((case-fold-search t)
23397 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23398 (if (not (save-excursion
23399 (or (re-search-forward re nil t)
23400 (re-search-backward re nil t))))
23401 (user-error "No bibliography defined in file")
23402 (setq bib (concat (match-string 1) ".bib")
23403 rds (list (list 'bib bib)))))))
23404 (call-interactively 'reftex-citation)))
23406 ;;;; Functions extending outline functionality
23408 (defun org-beginning-of-line (&optional arg)
23409 "Go to the beginning of the current line. If that is invisible, continue
23410 to a visible line beginning. This makes the function of C-a more intuitive.
23411 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23412 first attempt, and only move to after the tags when the cursor is already
23413 beyond the end of the headline."
23414 (interactive "P")
23415 (let ((pos (point))
23416 (special (if (consp org-special-ctrl-a/e)
23417 (car org-special-ctrl-a/e)
23418 org-special-ctrl-a/e))
23419 deactivate-mark refpos)
23420 (if (org-bound-and-true-p visual-line-mode)
23421 (beginning-of-visual-line 1)
23422 (beginning-of-line 1))
23423 (if (and arg (fboundp 'move-beginning-of-line))
23424 (call-interactively 'move-beginning-of-line)
23425 (if (bobp)
23427 (backward-char 1)
23428 (if (org-truely-invisible-p)
23429 (while (and (not (bobp)) (org-truely-invisible-p))
23430 (backward-char 1)
23431 (beginning-of-line 1))
23432 (forward-char 1))))
23433 (when special
23434 (cond
23435 ((and (looking-at org-complex-heading-regexp)
23436 (= (char-after (match-end 1)) ?\ ))
23437 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23438 (point-at-eol)))
23439 (goto-char
23440 (if (eq special t)
23441 (cond ((> pos refpos) refpos)
23442 ((= pos (point)) refpos)
23443 (t (point)))
23444 (cond ((> pos (point)) (point))
23445 ((not (eq last-command this-command)) (point))
23446 (t refpos)))))
23447 ((org-at-item-p)
23448 ;; Being at an item and not looking at an the item means point
23449 ;; was previously moved to beginning of a visual line, which
23450 ;; doesn't contain the item. Therefore, do nothing special,
23451 ;; just stay here.
23452 (when (looking-at org-list-full-item-re)
23453 ;; Set special position at first white space character after
23454 ;; bullet, and check-box, if any.
23455 (let ((after-bullet
23456 (let ((box (match-end 3)))
23457 (if (not box) (match-end 1)
23458 (let ((after (char-after box)))
23459 (if (and after (= after ? )) (1+ box) box))))))
23460 ;; Special case: Move point to special position when
23461 ;; currently after it or at beginning of line.
23462 (if (eq special t)
23463 (when (or (> pos after-bullet) (= (point) pos))
23464 (goto-char after-bullet))
23465 ;; Reversed case: Move point to special position when
23466 ;; point was already at beginning of line and command is
23467 ;; repeated.
23468 (when (and (= (point) pos) (eq last-command this-command))
23469 (goto-char after-bullet))))))))
23470 (org-no-warnings
23471 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23472 (setq disable-point-adjustment
23473 (or (not (invisible-p (point)))
23474 (not (invisible-p (max (point-min) (1- (point))))))))
23476 (defun org-end-of-line (&optional arg)
23477 "Go to the end of the line.
23478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23479 tags on the first attempt, and only move to after the tags when
23480 the cursor is already beyond the end of the headline."
23481 (interactive "P")
23482 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23483 org-special-ctrl-a/e))
23484 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23485 'end-of-visual-line)
23486 ((fboundp 'move-end-of-line) 'move-end-of-line)
23487 (t 'end-of-line)))
23488 deactivate-mark)
23489 (if (or (not special) arg) (call-interactively move-fun)
23490 (let* ((element (save-excursion (beginning-of-line)
23491 (org-element-at-point)))
23492 (type (org-element-type element)))
23493 (cond
23494 ((memq type '(headline inlinetask))
23495 (let ((pos (point)))
23496 (beginning-of-line 1)
23497 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23498 (if (eq special t)
23499 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23500 (goto-char (match-beginning 1))
23501 (goto-char (match-end 0)))
23502 (if (or (< pos (match-end 0))
23503 (not (eq this-command last-command)))
23504 (goto-char (match-end 0))
23505 (goto-char (match-beginning 1))))
23506 (call-interactively move-fun))))
23507 ((outline-invisible-p (line-end-position))
23508 ;; If element is hidden, `move-end-of-line' would put point
23509 ;; after it. Use `end-of-line' to stay on current line.
23510 (call-interactively 'end-of-line))
23511 (t (call-interactively move-fun)))))
23512 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23513 (setq disable-point-adjustment
23514 (or (not (invisible-p (point)))
23515 (not (invisible-p (max (point-min) (1- (point))))))))
23517 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23518 (define-key org-mode-map "\C-e" 'org-end-of-line)
23520 (defun org-backward-sentence (&optional arg)
23521 "Go to beginning of sentence, or beginning of table field.
23522 This will call `backward-sentence' or `org-table-beginning-of-field',
23523 depending on context."
23524 (interactive "P")
23525 (cond
23526 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23527 (t (call-interactively 'backward-sentence))))
23529 (defun org-forward-sentence (&optional arg)
23530 "Go to end of sentence, or end of table field.
23531 This will call `forward-sentence' or `org-table-end-of-field',
23532 depending on context."
23533 (interactive "P")
23534 (cond
23535 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23536 (t (call-interactively 'forward-sentence))))
23538 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23539 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23541 (defun org-kill-line (&optional arg)
23542 "Kill line, to tags or end of line."
23543 (interactive "P")
23544 (cond
23545 ((or (not org-special-ctrl-k)
23546 (bolp)
23547 (not (org-at-heading-p)))
23548 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23549 org-ctrl-k-protect-subtree)
23550 (if (or (eq org-ctrl-k-protect-subtree 'error)
23551 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23552 (user-error "C-k aborted as it would kill a hidden subtree")))
23553 (call-interactively
23554 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23555 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23556 (kill-region (point) (match-beginning 1))
23557 (org-set-tags nil t))
23558 (t (kill-region (point) (point-at-eol)))))
23560 (define-key org-mode-map "\C-k" 'org-kill-line)
23562 (defun org-yank (&optional arg)
23563 "Yank. If the kill is a subtree, treat it specially.
23564 This command will look at the current kill and check if is a single
23565 subtree, or a series of subtrees[1]. If it passes the test, and if the
23566 cursor is at the beginning of a line or after the stars of a currently
23567 empty headline, then the yank is handled specially. How exactly depends
23568 on the value of the following variables, both set by default.
23570 `org-yank-folded-subtrees'
23571 When set, the subtree(s) will be folded after insertion, but only
23572 if doing so would now swallow text after the yanked text.
23574 `org-yank-adjusted-subtrees'
23575 When set, the subtree will be promoted or demoted in order to
23576 fit into the local outline tree structure, which means that the
23577 level will be adjusted so that it becomes the smaller one of the
23578 two *visible* surrounding headings.
23580 Any prefix to this command will cause `yank' to be called directly with
23581 no special treatment. In particular, a simple \\[universal-argument] prefix \
23582 will just
23583 plainly yank the text as it is.
23585 \[1] The test checks if the first non-white line is a heading
23586 and if there are no other headings with fewer stars."
23587 (interactive "P")
23588 (org-yank-generic 'yank arg))
23590 (defun org-yank-generic (command arg)
23591 "Perform some yank-like command.
23593 This function implements the behavior described in the `org-yank'
23594 documentation. However, it has been generalized to work for any
23595 interactive command with similar behavior."
23597 ;; pretend to be command COMMAND
23598 (setq this-command command)
23600 (if arg
23601 (call-interactively command)
23603 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23604 (and (org-kill-is-subtree-p)
23605 (or (bolp)
23606 (and (looking-at "[ \t]*$")
23607 (string-match
23608 "\\`\\*+\\'"
23609 (buffer-substring (point-at-bol) (point)))))))
23610 swallowp)
23611 (cond
23612 ((and subtreep org-yank-folded-subtrees)
23613 (let ((beg (point))
23614 end)
23615 (if (and subtreep org-yank-adjusted-subtrees)
23616 (org-paste-subtree nil nil 'for-yank)
23617 (call-interactively command))
23619 (setq end (point))
23620 (goto-char beg)
23621 (when (and (bolp) subtreep
23622 (not (setq swallowp
23623 (org-yank-folding-would-swallow-text beg end))))
23624 (org-with-limited-levels
23625 (or (looking-at org-outline-regexp)
23626 (re-search-forward org-outline-regexp-bol end t))
23627 (while (and (< (point) end) (looking-at org-outline-regexp))
23628 (hide-subtree)
23629 (org-cycle-show-empty-lines 'folded)
23630 (condition-case nil
23631 (outline-forward-same-level 1)
23632 (error (goto-char end))))))
23633 (when swallowp
23634 (message
23635 "Inserted text not folded because that would swallow text"))
23637 (goto-char end)
23638 (skip-chars-forward " \t\n\r")
23639 (beginning-of-line 1)
23640 (push-mark beg 'nomsg)))
23641 ((and subtreep org-yank-adjusted-subtrees)
23642 (let ((beg (point-at-bol)))
23643 (org-paste-subtree nil nil 'for-yank)
23644 (push-mark beg 'nomsg)))
23646 (call-interactively command))))))
23648 (defun org-yank-folding-would-swallow-text (beg end)
23649 "Would hide-subtree at BEG swallow any text after END?"
23650 (let (level)
23651 (org-with-limited-levels
23652 (save-excursion
23653 (goto-char beg)
23654 (when (or (looking-at org-outline-regexp)
23655 (re-search-forward org-outline-regexp-bol end t))
23656 (setq level (org-outline-level)))
23657 (goto-char end)
23658 (skip-chars-forward " \t\r\n\v\f")
23659 (if (or (eobp)
23660 (and (bolp) (looking-at org-outline-regexp)
23661 (<= (org-outline-level) level)))
23662 nil ; Nothing would be swallowed
23663 t))))) ; something would swallow
23665 (define-key org-mode-map "\C-y" 'org-yank)
23667 (defun org-truely-invisible-p ()
23668 "Check if point is at a character currently not visible.
23669 This version does not only check the character property, but also
23670 `visible-mode'."
23671 ;; Early versions of noutline don't have `outline-invisible-p'.
23672 (if (org-bound-and-true-p visible-mode)
23674 (outline-invisible-p)))
23676 (defun org-invisible-p2 ()
23677 "Check if point is at a character currently not visible."
23678 (save-excursion
23679 (if (and (eolp) (not (bobp))) (backward-char 1))
23680 ;; Early versions of noutline don't have `outline-invisible-p'.
23681 (outline-invisible-p)))
23683 (defun org-back-to-heading (&optional invisible-ok)
23684 "Call `outline-back-to-heading', but provide a better error message."
23685 (condition-case nil
23686 (outline-back-to-heading invisible-ok)
23687 (error (error "Before first headline at position %d in buffer %s"
23688 (point) (current-buffer)))))
23690 (defun org-before-first-heading-p ()
23691 "Before first heading?"
23692 (save-excursion
23693 (end-of-line)
23694 (null (re-search-backward org-outline-regexp-bol nil t))))
23696 (defun org-at-heading-p (&optional ignored)
23697 (outline-on-heading-p t))
23698 ;; Compatibility alias with Org versions < 7.8.03
23699 (defalias 'org-on-heading-p 'org-at-heading-p)
23701 (defun org-in-commented-heading-p (&optional no-inheritance)
23702 "Non-nil if point is under a commented heading.
23703 This function also checks ancestors of the current headline,
23704 unless optional argument NO-INHERITANCE is non-nil."
23705 (cond
23706 ((org-before-first-heading-p) nil)
23707 ((let ((headline (nth 4 (org-heading-components))))
23708 (and headline
23709 (let ((case-fold-search nil))
23710 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23711 headline)))))
23712 (no-inheritance nil)
23714 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23716 (defun org-at-comment-p nil
23717 "Is cursor in a commented line?"
23718 (save-excursion
23719 (save-match-data
23720 (beginning-of-line)
23721 (looking-at "^[ \t]*# "))))
23723 (defun org-at-drawer-p nil
23724 "Is cursor at a drawer keyword?"
23725 (save-excursion
23726 (move-beginning-of-line 1)
23727 (looking-at org-drawer-regexp)))
23729 (defun org-at-block-p nil
23730 "Is cursor at a block keyword?"
23731 (save-excursion
23732 (move-beginning-of-line 1)
23733 (looking-at org-block-regexp)))
23735 (defun org-point-at-end-of-empty-headline ()
23736 "If point is at the end of an empty headline, return t, else nil.
23737 If the heading only contains a TODO keyword, it is still still considered
23738 empty."
23739 (and (looking-at "[ \t]*$")
23740 (when org-todo-line-regexp
23741 (save-excursion
23742 (beginning-of-line 1)
23743 (let ((case-fold-search nil))
23744 (looking-at org-todo-line-regexp)
23745 (string= (match-string 3) ""))))))
23747 (defun org-at-heading-or-item-p ()
23748 (or (org-at-heading-p) (org-at-item-p)))
23750 (defun org-at-target-p ()
23751 (or (org-in-regexp org-radio-target-regexp)
23752 (org-in-regexp org-target-regexp)))
23753 ;; Compatibility alias with Org versions < 7.8.03
23754 (defalias 'org-on-target-p 'org-at-target-p)
23756 (defun org-up-heading-all (arg)
23757 "Move to the heading line of which the present line is a subheading.
23758 This function considers both visible and invisible heading lines.
23759 With argument, move up ARG levels."
23760 (if (fboundp 'outline-up-heading-all)
23761 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23762 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23764 (defun org-up-heading-safe ()
23765 "Move to the heading line of which the present line is a subheading.
23766 This version will not throw an error. It will return the level of the
23767 headline found, or nil if no higher level is found.
23769 Also, this function will be a lot faster than `outline-up-heading',
23770 because it relies on stars being the outline starters. This can really
23771 make a significant difference in outlines with very many siblings."
23772 (when (ignore-errors (org-back-to-heading t))
23773 (let ((level-up (1- (funcall outline-level))))
23774 (and (> level-up 0)
23775 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23776 (funcall outline-level)))))
23778 (defun org-first-sibling-p ()
23779 "Is this heading the first child of its parents?"
23780 (interactive)
23781 (let ((re org-outline-regexp-bol)
23782 level l)
23783 (unless (org-at-heading-p t)
23784 (user-error "Not at a heading"))
23785 (setq level (funcall outline-level))
23786 (save-excursion
23787 (if (not (re-search-backward re nil t))
23789 (setq l (funcall outline-level))
23790 (< l level)))))
23792 (defun org-goto-sibling (&optional previous)
23793 "Goto the next sibling, even if it is invisible.
23794 When PREVIOUS is set, go to the previous sibling instead. Returns t
23795 when a sibling was found. When none is found, return nil and don't
23796 move point."
23797 (let ((fun (if previous 're-search-backward 're-search-forward))
23798 (pos (point))
23799 (re org-outline-regexp-bol)
23800 level l)
23801 (when (ignore-errors (org-back-to-heading t))
23802 (setq level (funcall outline-level))
23803 (catch 'exit
23804 (or previous (forward-char 1))
23805 (while (funcall fun re nil t)
23806 (setq l (funcall outline-level))
23807 (when (< l level) (goto-char pos) (throw 'exit nil))
23808 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23809 (goto-char pos)
23810 nil))))
23812 (defun org-show-siblings ()
23813 "Show all siblings of the current headline."
23814 (save-excursion
23815 (while (org-goto-sibling) (org-flag-heading nil)))
23816 (save-excursion
23817 (while (org-goto-sibling 'previous)
23818 (org-flag-heading nil))))
23820 (defun org-goto-first-child ()
23821 "Goto the first child, even if it is invisible.
23822 Return t when a child was found. Otherwise don't move point and
23823 return nil."
23824 (let (level (pos (point)) (re org-outline-regexp-bol))
23825 (when (ignore-errors (org-back-to-heading t))
23826 (setq level (outline-level))
23827 (forward-char 1)
23828 (if (and (re-search-forward re nil t) (> (outline-level) level))
23829 (progn (goto-char (match-beginning 0)) t)
23830 (goto-char pos) nil))))
23832 (defun org-show-hidden-entry ()
23833 "Show an entry where even the heading is hidden."
23834 (save-excursion
23835 (org-show-entry)))
23837 (defun org-flag-heading (flag &optional entry)
23838 "Flag the current heading. FLAG non-nil means make invisible.
23839 When ENTRY is non-nil, show the entire entry."
23840 (save-excursion
23841 (org-back-to-heading t)
23842 ;; Check if we should show the entire entry
23843 (if entry
23844 (progn
23845 (org-show-entry)
23846 (save-excursion
23847 (and (outline-next-heading)
23848 (org-flag-heading nil))))
23849 (outline-flag-region (max (point-min) (1- (point)))
23850 (save-excursion (outline-end-of-heading) (point))
23851 flag))))
23853 (defun org-get-next-sibling ()
23854 "Move to next heading of the same level, and return point.
23855 If there is no such heading, return nil.
23856 This is like outline-next-sibling, but invisible headings are ok."
23857 (let ((level (funcall outline-level)))
23858 (outline-next-heading)
23859 (while (and (not (eobp)) (> (funcall outline-level) level))
23860 (outline-next-heading))
23861 (if (or (eobp) (< (funcall outline-level) level))
23863 (point))))
23865 (defun org-get-last-sibling ()
23866 "Move to previous heading of the same level, and return point.
23867 If there is no such heading, return nil."
23868 (let ((opoint (point))
23869 (level (funcall outline-level)))
23870 (outline-previous-heading)
23871 (when (and (/= (point) opoint) (outline-on-heading-p t))
23872 (while (and (> (funcall outline-level) level)
23873 (not (bobp)))
23874 (outline-previous-heading))
23875 (if (< (funcall outline-level) level)
23877 (point)))))
23879 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23880 "Goto to the end of a subtree."
23881 ;; This contains an exact copy of the original function, but it uses
23882 ;; `org-back-to-heading', to make it work also in invisible
23883 ;; trees. And is uses an invisible-ok argument.
23884 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23885 ;; Furthermore, when used inside Org, finding the end of a large subtree
23886 ;; with many children and grandchildren etc, this can be much faster
23887 ;; than the outline version.
23888 (org-back-to-heading invisible-ok)
23889 (let ((first t)
23890 (level (funcall outline-level)))
23891 (if (and (derived-mode-p 'org-mode) (< level 1000))
23892 ;; A true heading (not a plain list item), in Org-mode
23893 ;; This means we can easily find the end by looking
23894 ;; only for the right number of stars. Using a regexp to do
23895 ;; this is so much faster than using a Lisp loop.
23896 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23897 (forward-char 1)
23898 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23899 ;; something else, do it the slow way
23900 (while (and (not (eobp))
23901 (or first (> (funcall outline-level) level)))
23902 (setq first nil)
23903 (outline-next-heading)))
23904 (unless to-heading
23905 (if (memq (preceding-char) '(?\n ?\^M))
23906 (progn
23907 ;; Go to end of line before heading
23908 (forward-char -1)
23909 (if (memq (preceding-char) '(?\n ?\^M))
23910 ;; leave blank line before heading
23911 (forward-char -1))))))
23912 (point))
23914 (defun org-end-of-meta-data-and-drawers ()
23915 "Jump to the first text after meta data and drawers in the current entry.
23916 This will move over empty lines, lines with planning time stamps,
23917 clocking lines, and drawers."
23918 (org-back-to-heading t)
23919 (let ((end (save-excursion (outline-next-heading) (point)))
23920 (re (concat "\\(" org-drawer-regexp "\\)"
23921 "\\|" "[ \t]*" org-keyword-time-regexp)))
23922 (forward-line 1)
23923 (while (re-search-forward re end t)
23924 (if (not (match-end 1))
23925 ;; empty or planning line
23926 (forward-line 1)
23927 ;; a drawer, find the end
23928 (re-search-forward "^[ \t]*:END:" end 'move)
23929 (forward-line 1)))
23930 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23931 (point)))
23933 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23934 "Move forward to the ARG'th subheading at same level as this one.
23935 Stop at the first and last subheadings of a superior heading.
23936 Normally this only looks at visible headings, but when INVISIBLE-OK is
23937 non-nil it will also look at invisible ones."
23938 (interactive "p")
23939 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23940 (if (and arg (< arg 0))
23941 (goto-char (point-min))
23942 (outline-next-heading))
23943 (org-at-heading-p)
23944 (let ((level (- (match-end 0) (match-beginning 0) 1))
23945 (f (if (and arg (< arg 0))
23946 're-search-backward
23947 're-search-forward))
23948 (count (if arg (abs arg) 1))
23949 (result (point)))
23950 (while (and (prog1 (> count 0)
23951 (forward-char (if (and arg (< arg 0)) -1 1)))
23952 (funcall f org-outline-regexp-bol nil 'move))
23953 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23954 (cond ((< l level) (setq count 0))
23955 ((and (= l level)
23956 (or invisible-ok
23957 (progn
23958 (goto-char (line-beginning-position))
23959 (not (outline-invisible-p)))))
23960 (setq count (1- count))
23961 (when (eq l level)
23962 (setq result (point)))))))
23963 (goto-char result))
23964 (beginning-of-line 1)))
23966 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23967 "Move backward to the ARG'th subheading at same level as this one.
23968 Stop at the first and last subheadings of a superior heading."
23969 (interactive "p")
23970 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23972 (defun org-next-block (arg &optional backward block-regexp)
23973 "Jump to the next block.
23974 With a prefix argument ARG, jump forward ARG many source blocks.
23975 When BACKWARD is non-nil, jump to the previous block.
23976 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23977 (interactive "p")
23978 (let ((re (or block-regexp org-block-regexp))
23979 (re-search-fn (or (and backward 're-search-backward)
23980 're-search-forward)))
23981 (if (looking-at re) (forward-char 1))
23982 (condition-case nil
23983 (funcall re-search-fn re nil nil arg)
23984 (error (user-error "No %s code blocks"
23985 (if backward "previous" "further" ))))
23986 (goto-char (match-beginning 0)) (org-show-context)))
23988 (defun org-previous-block (arg &optional block-regexp)
23989 "Jump to the previous block.
23990 With a prefix argument ARG, jump backward ARG many source blocks.
23991 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23992 (interactive "p")
23993 (org-next-block arg t block-regexp))
23995 (defun org-forward-paragraph ()
23996 "Move forward to beginning of next paragraph or equivalent.
23998 The function moves point to the beginning of the next visible
23999 structural element, which can be a paragraph, a table, a list
24000 item, etc. It also provides some special moves for convenience:
24002 - On an affiliated keyword, jump to the beginning of the
24003 relative element.
24004 - On an item or a footnote definition, move to the second
24005 element inside, if any.
24006 - On a table or a property drawer, jump after it.
24007 - On a verse or source block, stop after blank lines."
24008 (interactive)
24009 (when (eobp) (user-error "Cannot move further down"))
24010 (let* ((deactivate-mark nil)
24011 (element (org-element-at-point))
24012 (type (org-element-type element))
24013 (post-affiliated (org-element-property :post-affiliated element))
24014 (contents-begin (org-element-property :contents-begin element))
24015 (contents-end (org-element-property :contents-end element))
24016 (end (let ((end (org-element-property :end element)) (parent element))
24017 (while (and (setq parent (org-element-property :parent parent))
24018 (= (org-element-property :contents-end parent) end))
24019 (setq end (org-element-property :end parent)))
24020 end)))
24021 (cond ((not element)
24022 (skip-chars-forward " \r\t\n")
24023 (or (eobp) (beginning-of-line)))
24024 ;; On affiliated keywords, move to element's beginning.
24025 ((< (point) post-affiliated)
24026 (goto-char post-affiliated))
24027 ;; At a table row, move to the end of the table. Similarly,
24028 ;; at a node property, move to the end of the property
24029 ;; drawer.
24030 ((memq type '(node-property table-row))
24031 (goto-char (org-element-property
24032 :end (org-element-property :parent element))))
24033 ((memq type '(property-drawer table)) (goto-char end))
24034 ;; Consider blank lines as separators in verse and source
24035 ;; blocks to ease editing.
24036 ((memq type '(src-block verse-block))
24037 (when (eq type 'src-block)
24038 (setq contents-end
24039 (save-excursion (goto-char end)
24040 (skip-chars-backward " \r\t\n")
24041 (line-beginning-position))))
24042 (beginning-of-line)
24043 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24044 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24045 (goto-char end)
24046 (skip-chars-forward " \r\t\n")
24047 (if (= (point) contents-end) (goto-char end)
24048 (beginning-of-line))))
24049 ;; With no contents, just skip element.
24050 ((not contents-begin) (goto-char end))
24051 ;; If contents are invisible, skip the element altogether.
24052 ((outline-invisible-p (line-end-position))
24053 (case type
24054 (headline
24055 (org-with-limited-levels (outline-next-visible-heading 1)))
24056 ;; At a plain list, make sure we move to the next item
24057 ;; instead of skipping the whole list.
24058 (plain-list (forward-char)
24059 (org-forward-paragraph))
24060 (otherwise (goto-char end))))
24061 ((>= (point) contents-end) (goto-char end))
24062 ((>= (point) contents-begin)
24063 ;; This can only happen on paragraphs and plain lists.
24064 (case type
24065 (paragraph (goto-char end))
24066 ;; At a plain list, try to move to second element in
24067 ;; first item, if possible.
24068 (plain-list (end-of-line)
24069 (org-forward-paragraph))))
24070 ;; When contents start on the middle of a line (e.g. in
24071 ;; items and footnote definitions), try to reach first
24072 ;; element starting after current line.
24073 ((> (line-end-position) contents-begin)
24074 (end-of-line)
24075 (org-forward-paragraph))
24076 (t (goto-char contents-begin)))))
24078 (defun org-backward-paragraph ()
24079 "Move backward to start of previous paragraph or equivalent.
24081 The function moves point to the beginning of the current
24082 structural element, which can be a paragraph, a table, a list
24083 item, etc., or to the beginning of the previous visible one if
24084 point is already there. It also provides some special moves for
24085 convenience:
24087 - On an affiliated keyword, jump to the first one.
24088 - On a table or a property drawer, move to its beginning.
24089 - On a verse or source block, stop before blank lines."
24090 (interactive)
24091 (when (bobp) (user-error "Cannot move further up"))
24092 (let* ((deactivate-mark nil)
24093 (element (org-element-at-point))
24094 (type (org-element-type element))
24095 (contents-begin (org-element-property :contents-begin element))
24096 (contents-end (org-element-property :contents-end element))
24097 (post-affiliated (org-element-property :post-affiliated element))
24098 (begin (org-element-property :begin element)))
24099 (cond
24100 ((not element) (goto-char (point-min)))
24101 ((= (point) begin)
24102 (backward-char)
24103 (org-backward-paragraph))
24104 ((<= (point) post-affiliated) (goto-char begin))
24105 ((memq type '(node-property table-row))
24106 (goto-char (org-element-property
24107 :post-affiliated (org-element-property :parent element))))
24108 ((memq type '(property-drawer table)) (goto-char begin))
24109 ((memq type '(src-block verse-block))
24110 (when (eq type 'src-block)
24111 (setq contents-begin
24112 (save-excursion (goto-char begin) (forward-line) (point))))
24113 (if (= (point) contents-begin) (goto-char post-affiliated)
24114 ;; Inside a verse block, see blank lines as paragraph
24115 ;; separators.
24116 (let ((origin (point)))
24117 (skip-chars-backward " \r\t\n" contents-begin)
24118 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24119 (skip-chars-forward " \r\t\n" origin)
24120 (if (= (point) origin) (goto-char contents-begin)
24121 (beginning-of-line))))))
24122 ((not contents-begin) (goto-char (or post-affiliated begin)))
24123 ((eq type 'paragraph)
24124 (goto-char contents-begin)
24125 ;; When at first paragraph in an item or a footnote definition,
24126 ;; move directly to beginning of line.
24127 (let ((parent-contents
24128 (org-element-property
24129 :contents-begin (org-element-property :parent element))))
24130 (when (and parent-contents (= parent-contents contents-begin))
24131 (beginning-of-line))))
24132 ;; At the end of a greater element, move to the beginning of the
24133 ;; last element within.
24134 ((>= (point) contents-end)
24135 (goto-char (1- contents-end))
24136 (org-backward-paragraph))
24137 (t (goto-char (or post-affiliated begin))))
24138 ;; Ensure we never leave point invisible.
24139 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24141 (defun org-forward-element ()
24142 "Move forward by one element.
24143 Move to the next element at the same level, when possible."
24144 (interactive)
24145 (cond ((eobp) (user-error "Cannot move further down"))
24146 ((org-with-limited-levels (org-at-heading-p))
24147 (let ((origin (point)))
24148 (goto-char (org-end-of-subtree nil t))
24149 (unless (org-with-limited-levels (org-at-heading-p))
24150 (goto-char origin)
24151 (user-error "Cannot move further down"))))
24153 (let* ((elem (org-element-at-point))
24154 (end (org-element-property :end elem))
24155 (parent (org-element-property :parent elem)))
24156 (cond ((and parent (= (org-element-property :contents-end parent) end))
24157 (goto-char (org-element-property :end parent)))
24158 ((integer-or-marker-p end) (goto-char end))
24159 (t (message "No element at point")))))))
24161 (defun org-backward-element ()
24162 "Move backward by one element.
24163 Move to the previous element at the same level, when possible."
24164 (interactive)
24165 (cond ((bobp) (user-error "Cannot move further up"))
24166 ((org-with-limited-levels (org-at-heading-p))
24167 ;; At a headline, move to the previous one, if any, or stay
24168 ;; here.
24169 (let ((origin (point)))
24170 (org-with-limited-levels (org-backward-heading-same-level 1))
24171 ;; When current headline has no sibling above, move to its
24172 ;; parent.
24173 (when (= (point) origin)
24174 (or (org-with-limited-levels (org-up-heading-safe))
24175 (progn (goto-char origin)
24176 (user-error "Cannot move further up"))))))
24178 (let* ((elem (org-element-at-point))
24179 (beg (org-element-property :begin elem)))
24180 (cond
24181 ;; Move to beginning of current element if point isn't
24182 ;; there already.
24183 ((null beg) (message "No element at point"))
24184 ((/= (point) beg) (goto-char beg))
24185 (t (goto-char beg)
24186 (skip-chars-backward " \r\t\n")
24187 (unless (bobp)
24188 (let ((prev (org-element-at-point)))
24189 (goto-char (org-element-property :begin prev))
24190 (while (and (setq prev (org-element-property :parent prev))
24191 (<= (org-element-property :end prev) beg))
24192 (goto-char (org-element-property :begin prev)))))))))))
24194 (defun org-up-element ()
24195 "Move to upper element."
24196 (interactive)
24197 (if (org-with-limited-levels (org-at-heading-p))
24198 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24199 (let* ((elem (org-element-at-point))
24200 (parent (org-element-property :parent elem)))
24201 (if parent (goto-char (org-element-property :begin parent))
24202 (if (org-with-limited-levels (org-before-first-heading-p))
24203 (user-error "No surrounding element")
24204 (org-with-limited-levels (org-back-to-heading)))))))
24206 (defvar org-element-greater-elements)
24207 (defun org-down-element ()
24208 "Move to inner element."
24209 (interactive)
24210 (let ((element (org-element-at-point)))
24211 (cond
24212 ((memq (org-element-type element) '(plain-list table))
24213 (goto-char (org-element-property :contents-begin element))
24214 (forward-char))
24215 ((memq (org-element-type element) org-element-greater-elements)
24216 ;; If contents are hidden, first disclose them.
24217 (when (outline-invisible-p (line-end-position)) (org-cycle))
24218 (goto-char (or (org-element-property :contents-begin element)
24219 (user-error "No content for this element"))))
24220 (t (user-error "No inner element")))))
24222 (defun org-drag-element-backward ()
24223 "Move backward element at point."
24224 (interactive)
24225 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24226 (let* ((elem (org-element-at-point))
24227 (prev-elem
24228 (save-excursion
24229 (goto-char (org-element-property :begin elem))
24230 (skip-chars-backward " \r\t\n")
24231 (unless (bobp)
24232 (let* ((beg (org-element-property :begin elem))
24233 (prev (org-element-at-point))
24234 (up prev))
24235 (while (and (setq up (org-element-property :parent up))
24236 (<= (org-element-property :end up) beg))
24237 (setq prev up))
24238 prev)))))
24239 ;; Error out if no previous element or previous element is
24240 ;; a parent of the current one.
24241 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24242 (user-error "Cannot drag element backward")
24243 (let ((pos (point)))
24244 (org-element-swap-A-B prev-elem elem)
24245 (goto-char (+ (org-element-property :begin prev-elem)
24246 (- pos (org-element-property :begin elem)))))))))
24248 (defun org-drag-element-forward ()
24249 "Move forward element at point."
24250 (interactive)
24251 (let* ((pos (point))
24252 (elem (org-element-at-point)))
24253 (when (= (point-max) (org-element-property :end elem))
24254 (user-error "Cannot drag element forward"))
24255 (goto-char (org-element-property :end elem))
24256 (let ((next-elem (org-element-at-point)))
24257 (when (or (org-element-nested-p elem next-elem)
24258 (and (eq (org-element-type next-elem) 'headline)
24259 (not (eq (org-element-type elem) 'headline))))
24260 (goto-char pos)
24261 (user-error "Cannot drag element forward"))
24262 ;; Compute new position of point: it's shifted by NEXT-ELEM
24263 ;; body's length (without final blanks) and by the length of
24264 ;; blanks between ELEM and NEXT-ELEM.
24265 (let ((size-next (- (save-excursion
24266 (goto-char (org-element-property :end next-elem))
24267 (skip-chars-backward " \r\t\n")
24268 (forward-line)
24269 ;; Small correction if buffer doesn't end
24270 ;; with a newline character.
24271 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24272 (org-element-property :begin next-elem)))
24273 (size-blank (- (org-element-property :end elem)
24274 (save-excursion
24275 (goto-char (org-element-property :end elem))
24276 (skip-chars-backward " \r\t\n")
24277 (forward-line)
24278 (point)))))
24279 (org-element-swap-A-B elem next-elem)
24280 (goto-char (+ pos size-next size-blank))))))
24282 (defun org-drag-line-forward (arg)
24283 "Drag the line at point ARG lines forward."
24284 (interactive "p")
24285 (dotimes (n (abs arg))
24286 (let ((c (current-column)))
24287 (if (< 0 arg)
24288 (progn
24289 (beginning-of-line 2)
24290 (transpose-lines 1)
24291 (beginning-of-line 0))
24292 (transpose-lines 1)
24293 (beginning-of-line -1))
24294 (org-move-to-column c))))
24296 (defun org-drag-line-backward (arg)
24297 "Drag the line at point ARG lines backward."
24298 (interactive "p")
24299 (org-drag-line-forward (- arg)))
24301 (defun org-mark-element ()
24302 "Put point at beginning of this element, mark at end.
24304 Interactively, if this command is repeated or (in Transient Mark
24305 mode) if the mark is active, it marks the next element after the
24306 ones already marked."
24307 (interactive)
24308 (let (deactivate-mark)
24309 (if (and (org-called-interactively-p 'any)
24310 (or (and (eq last-command this-command) (mark t))
24311 (and transient-mark-mode mark-active)))
24312 (set-mark
24313 (save-excursion
24314 (goto-char (mark))
24315 (goto-char (org-element-property :end (org-element-at-point)))))
24316 (let ((element (org-element-at-point)))
24317 (end-of-line)
24318 (push-mark (org-element-property :end element) t t)
24319 (goto-char (org-element-property :begin element))))))
24321 (defun org-narrow-to-element ()
24322 "Narrow buffer to current element."
24323 (interactive)
24324 (let ((elem (org-element-at-point)))
24325 (cond
24326 ((eq (car elem) 'headline)
24327 (narrow-to-region
24328 (org-element-property :begin elem)
24329 (org-element-property :end elem)))
24330 ((memq (car elem) org-element-greater-elements)
24331 (narrow-to-region
24332 (org-element-property :contents-begin elem)
24333 (org-element-property :contents-end elem)))
24335 (narrow-to-region
24336 (org-element-property :begin elem)
24337 (org-element-property :end elem))))))
24339 (defun org-transpose-element ()
24340 "Transpose current and previous elements, keeping blank lines between.
24341 Point is moved after both elements."
24342 (interactive)
24343 (org-skip-whitespace)
24344 (let ((end (org-element-property :end (org-element-at-point))))
24345 (org-drag-element-backward)
24346 (goto-char end)))
24348 (defun org-unindent-buffer ()
24349 "Un-indent the visible part of the buffer.
24350 Relative indentation (between items, inside blocks, etc.) isn't
24351 modified."
24352 (interactive)
24353 (unless (eq major-mode 'org-mode)
24354 (user-error "Cannot un-indent a buffer not in Org mode"))
24355 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24356 unindent-tree ; For byte-compiler.
24357 (unindent-tree
24358 (function
24359 (lambda (contents)
24360 (mapc
24361 (lambda (element)
24362 (if (memq (org-element-type element) '(headline section))
24363 (funcall unindent-tree (org-element-contents element))
24364 (save-excursion
24365 (save-restriction
24366 (narrow-to-region
24367 (org-element-property :begin element)
24368 (org-element-property :end element))
24369 (org-do-remove-indentation)))))
24370 (reverse contents))))))
24371 (funcall unindent-tree (org-element-contents parse-tree))))
24373 (defun org-show-subtree ()
24374 "Show everything after this heading at deeper levels."
24375 (interactive)
24376 (outline-flag-region
24377 (point)
24378 (save-excursion
24379 (org-end-of-subtree t t))
24380 nil))
24382 (defun org-show-entry ()
24383 "Show the body directly following this heading.
24384 Show the heading too, if it is currently invisible."
24385 (interactive)
24386 (save-excursion
24387 (ignore-errors
24388 (org-back-to-heading t)
24389 (outline-flag-region
24390 (max (point-min) (1- (point)))
24391 (save-excursion
24392 (if (re-search-forward
24393 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24394 (match-beginning 1)
24395 (point-max)))
24396 nil)
24397 (org-cycle-hide-drawers 'children))))
24399 (defun org-make-options-regexp (kwds &optional extra)
24400 "Make a regular expression for keyword lines."
24401 (concat
24402 "^[ \t]*#\\+\\("
24403 (mapconcat 'regexp-quote kwds "\\|")
24404 (if extra (concat "\\|" extra))
24405 "\\):[ \t]*\\(.*\\)"))
24407 ;; Make isearch reveal the necessary context
24408 (defun org-isearch-end ()
24409 "Reveal context after isearch exits."
24410 (when isearch-success ; only if search was successful
24411 (if (featurep 'xemacs)
24412 ;; Under XEmacs, the hook is run in the correct place,
24413 ;; we directly show the context.
24414 (org-show-context 'isearch)
24415 ;; In Emacs the hook runs *before* restoring the overlays.
24416 ;; So we have to use a one-time post-command-hook to do this.
24417 ;; (Emacs 22 has a special variable, see function `org-mode')
24418 (unless (and (boundp 'isearch-mode-end-hook-quit)
24419 isearch-mode-end-hook-quit)
24420 ;; Only when the isearch was not quitted.
24421 (org-add-hook 'post-command-hook 'org-isearch-post-command
24422 'append 'local)))))
24424 (defun org-isearch-post-command ()
24425 "Remove self from hook, and show context."
24426 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24427 (org-show-context 'isearch))
24430 ;;;; Integration with and fixes for other packages
24432 ;;; Imenu support
24434 (defvar org-imenu-markers nil
24435 "All markers currently used by Imenu.")
24436 (make-variable-buffer-local 'org-imenu-markers)
24438 (defun org-imenu-new-marker (&optional pos)
24439 "Return a new marker for use by Imenu, and remember the marker."
24440 (let ((m (make-marker)))
24441 (move-marker m (or pos (point)))
24442 (push m org-imenu-markers)
24445 (defun org-imenu-get-tree ()
24446 "Produce the index for Imenu."
24447 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24448 (setq org-imenu-markers nil)
24449 (let* ((n org-imenu-depth)
24450 (re (concat "^" (org-get-limited-outline-regexp)))
24451 (subs (make-vector (1+ n) nil))
24452 (last-level 0)
24453 m level head0 head)
24454 (save-excursion
24455 (save-restriction
24456 (widen)
24457 (goto-char (point-max))
24458 (while (re-search-backward re nil t)
24459 (setq level (org-reduced-level (funcall outline-level)))
24460 (when (and (<= level n)
24461 (looking-at org-complex-heading-regexp)
24462 (setq head0 (org-match-string-no-properties 4)))
24463 (setq head (org-link-display-format head0)
24464 m (org-imenu-new-marker))
24465 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24466 (if (>= level last-level)
24467 (push (cons head m) (aref subs level))
24468 (push (cons head (aref subs (1+ level))) (aref subs level))
24469 (loop for i from (1+ level) to n do (aset subs i nil)))
24470 (setq last-level level)))))
24471 (aref subs 1)))
24473 (eval-after-load "imenu"
24474 '(progn
24475 (add-hook 'imenu-after-jump-hook
24476 (lambda ()
24477 (if (derived-mode-p 'org-mode)
24478 (org-show-context 'org-goto))))))
24480 (defun org-link-display-format (link)
24481 "Replace a link with its the description.
24482 If there is no description, use the link target."
24483 (save-match-data
24484 (if (string-match org-bracket-link-analytic-regexp link)
24485 (replace-match (if (match-end 5)
24486 (match-string 5 link)
24487 (concat (match-string 1 link)
24488 (match-string 3 link)))
24489 nil t link)
24490 link)))
24492 (defun org-toggle-link-display ()
24493 "Toggle the literal or descriptive display of links."
24494 (interactive)
24495 (if org-descriptive-links
24496 (progn (org-remove-from-invisibility-spec '(org-link))
24497 (org-restart-font-lock)
24498 (setq org-descriptive-links nil))
24499 (progn (add-to-invisibility-spec '(org-link))
24500 (org-restart-font-lock)
24501 (setq org-descriptive-links t))))
24503 ;; Speedbar support
24505 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24506 "Overlay marking the agenda restriction line in speedbar.")
24507 (overlay-put org-speedbar-restriction-lock-overlay
24508 'face 'org-agenda-restriction-lock)
24509 (overlay-put org-speedbar-restriction-lock-overlay
24510 'help-echo "Agendas are currently limited to this item.")
24511 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24513 (defun org-speedbar-set-agenda-restriction ()
24514 "Restrict future agenda commands to the location at point in speedbar.
24515 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24516 (interactive)
24517 (require 'org-agenda)
24518 (let (p m tp np dir txt)
24519 (cond
24520 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24521 'org-imenu t))
24522 (setq m (get-text-property p 'org-imenu-marker))
24523 (with-current-buffer (marker-buffer m)
24524 (goto-char m)
24525 (org-agenda-set-restriction-lock 'subtree)))
24526 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24527 'speedbar-function 'speedbar-find-file))
24528 (setq tp (previous-single-property-change
24529 (1+ p) 'speedbar-function)
24530 np (next-single-property-change
24531 tp 'speedbar-function)
24532 dir (speedbar-line-directory)
24533 txt (buffer-substring-no-properties (or tp (point-min))
24534 (or np (point-max))))
24535 (with-current-buffer (find-file-noselect
24536 (let ((default-directory dir))
24537 (expand-file-name txt)))
24538 (unless (derived-mode-p 'org-mode)
24539 (user-error "Cannot restrict to non-Org-mode file"))
24540 (org-agenda-set-restriction-lock 'file)))
24541 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24542 (move-overlay org-speedbar-restriction-lock-overlay
24543 (point-at-bol) (point-at-eol))
24544 (setq current-prefix-arg nil)
24545 (org-agenda-maybe-redo)))
24547 (defvar speedbar-file-key-map)
24548 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24549 (eval-after-load "speedbar"
24550 '(progn
24551 (speedbar-add-supported-extension ".org")
24552 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24553 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24554 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24555 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24556 (add-hook 'speedbar-visiting-tag-hook
24557 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24559 ;;; Fixes and Hacks for problems with other packages
24561 (defun org--flyspell-object-check-p (element)
24562 "Non-nil when Flyspell can check object at point.
24563 ELEMENT is the element at point."
24564 (let ((object (save-excursion
24565 (when (org-looking-at-p "\\>") (backward-char))
24566 (org-element-context element))))
24567 (case (org-element-type object)
24568 ;; Prevent checks in links due to keybinding conflict with
24569 ;; Flyspell.
24570 ((code entity export-snippet inline-babel-call
24571 inline-src-block line-break latex-fragment link macro
24572 statistics-cookie target timestamp verbatim)
24573 nil)
24574 (footnote-reference
24575 ;; Only in inline footnotes, within the definition.
24576 (and (eq (org-element-property :type object) 'inline)
24577 (< (save-excursion
24578 (goto-char (org-element-property :begin object))
24579 (search-forward ":" nil t 2))
24580 (point))))
24581 (otherwise t))))
24583 (defun org-mode-flyspell-verify ()
24584 "Function used for `flyspell-generic-check-word-predicate'."
24585 (if (org-at-heading-p)
24586 ;; At a headline or an inlinetask, check title only. This is
24587 ;; faster than relying on `org-element-at-point'.
24588 (and (save-excursion (beginning-of-line)
24589 (and (let ((case-fold-search t))
24590 (not (looking-at "\\*+ END[ \t]*$")))
24591 (looking-at org-complex-heading-regexp)))
24592 (match-beginning 4)
24593 (>= (point) (match-beginning 4))
24594 (or (not (match-beginning 5))
24595 (< (point) (match-beginning 5))))
24596 (let* ((element (org-element-at-point))
24597 (post-affiliated (org-element-property :post-affiliated element)))
24598 (cond
24599 ;; Ignore checks in all affiliated keywords but captions.
24600 ((< (point) post-affiliated)
24601 (and (save-excursion
24602 (beginning-of-line)
24603 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24604 (> (point) (match-end 0))
24605 (org--flyspell-object-check-p element)))
24606 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24607 ((and org-log-into-drawer
24608 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24609 (parent element))
24610 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24611 (setq parent (org-element-property :parent parent)))
24612 (and parent
24613 (eq (compare-strings
24614 log nil nil
24615 (org-element-property :drawer-name parent) nil nil t)
24616 t))))
24617 nil)
24619 (case (org-element-type element)
24620 ((comment quote-section) t)
24621 (comment-block
24622 ;; Allow checks between block markers, not on them.
24623 (and (> (line-beginning-position) post-affiliated)
24624 (save-excursion
24625 (end-of-line)
24626 (skip-chars-forward " \r\t\n")
24627 (< (point) (org-element-property :end element)))))
24628 ;; Arbitrary list of keywords where checks are meaningful.
24629 ;; Make sure point is on the value part of the element.
24630 (keyword
24631 (and (member (org-element-property :key element)
24632 '("DESCRIPTION" "TITLE"))
24633 (< (save-excursion
24634 (beginning-of-line) (search-forward ":") (point))
24635 (point))))
24636 ;; Check is globally allowed in paragraphs verse blocks and
24637 ;; table rows (after affiliated keywords) but some objects
24638 ;; must not be affected.
24639 ((paragraph table-row verse-block)
24640 (let ((cbeg (org-element-property :contents-begin element))
24641 (cend (org-element-property :contents-end element)))
24642 (and cbeg (>= (point) cbeg) (< (point) cend)
24643 (org--flyspell-object-check-p element))))))))))
24644 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24646 (defun org-remove-flyspell-overlays-in (beg end)
24647 "Remove flyspell overlays in region."
24648 (and (org-bound-and-true-p flyspell-mode)
24649 (fboundp 'flyspell-delete-region-overlays)
24650 (flyspell-delete-region-overlays beg end)))
24652 (defvar flyspell-delayed-commands)
24653 (eval-after-load "flyspell"
24654 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24656 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24657 (eval-after-load "bookmark"
24658 '(if (boundp 'bookmark-after-jump-hook)
24659 ;; We can use the hook
24660 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24661 ;; Hook not available, use advice
24662 (defadvice bookmark-jump (after org-make-visible activate)
24663 "Make the position visible."
24664 (org-bookmark-jump-unhide))))
24666 ;; Make sure saveplace shows the location if it was hidden
24667 (eval-after-load "saveplace"
24668 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24669 "Make the position visible."
24670 (org-bookmark-jump-unhide)))
24672 ;; Make sure ecb shows the location if it was hidden
24673 (eval-after-load "ecb"
24674 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24675 "Make hierarchy visible when jumping into location from ECB tree buffer."
24676 (if (derived-mode-p 'org-mode)
24677 (org-show-context))))
24679 (defun org-bookmark-jump-unhide ()
24680 "Unhide the current position, to show the bookmark location."
24681 (and (derived-mode-p 'org-mode)
24682 (or (outline-invisible-p)
24683 (save-excursion (goto-char (max (point-min) (1- (point))))
24684 (outline-invisible-p)))
24685 (org-show-context 'bookmark-jump)))
24687 (defun org-mark-jump-unhide ()
24688 "Make the point visible with `org-show-context' after jumping to the mark."
24689 (when (and (derived-mode-p 'org-mode)
24690 (outline-invisible-p))
24691 (org-show-context 'mark-goto)))
24693 (eval-after-load "simple"
24694 '(defadvice pop-to-mark-command (after org-make-visible activate)
24695 "Make the point visible with `org-show-context'."
24696 (org-mark-jump-unhide)))
24698 (eval-after-load "simple"
24699 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24700 "Make the point visible with `org-show-context'."
24701 (org-mark-jump-unhide)))
24703 (eval-after-load "simple"
24704 '(defadvice pop-global-mark (after org-make-visible activate)
24705 "Make the point visible with `org-show-context'."
24706 (org-mark-jump-unhide)))
24708 ;; Make session.el ignore our circular variable
24709 (defvar session-globals-exclude)
24710 (eval-after-load "session"
24711 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24713 ;;;; Finish up
24715 (provide 'org)
24717 (run-hooks 'org-load-hook)
24719 ;;; org.el ends here