org.el: use a shy regex for fontifying macros
[org-mode/org-tableheadings.git] / lisp / org.el
blob59f55a8a92179f98bdbaa09b248bd8f409c48b73
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 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 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "Java" java)
256 (const :tag "Javascript" js)
257 (const :tag "LaTeX" latex)
258 (const :tag "Ledger" ledger)
259 (const :tag "Lilypond" lilypond)
260 (const :tag "Lisp" lisp)
261 (const :tag "Makefile" makefile)
262 (const :tag "Maxima" maxima)
263 (const :tag "Matlab" matlab)
264 (const :tag "Mscgen" mscgen)
265 (const :tag "Ocaml" ocaml)
266 (const :tag "Octave" octave)
267 (const :tag "Org" org)
268 (const :tag "Perl" perl)
269 (const :tag "Pico Lisp" picolisp)
270 (const :tag "PlantUML" plantuml)
271 (const :tag "Python" python)
272 (const :tag "Ruby" ruby)
273 (const :tag "Sass" sass)
274 (const :tag "Scala" scala)
275 (const :tag "Scheme" scheme)
276 (const :tag "Screen" screen)
277 (const :tag "Shell Script" sh)
278 (const :tag "Shen" shen)
279 (const :tag "Sql" sql)
280 (const :tag "Sqlite" sqlite)
281 (const :tag "ebnf2ps" ebnf2ps))
282 :value-type (boolean :tag "Activate" :value t)))
284 ;;;; Customization variables
285 (defcustom org-clone-delete-id nil
286 "Remove ID property of clones of a subtree.
287 When non-nil, clones of a subtree don't inherit the ID property.
288 Otherwise they inherit the ID property with a new unique
289 identifier."
290 :type 'boolean
291 :version "24.1"
292 :group 'org-id)
294 ;;; Version
295 (org-check-version)
297 ;;;###autoload
298 (defun org-version (&optional here full message)
299 "Show the org-mode version in the echo area.
300 With prefix argument HERE, insert it at point.
301 When FULL is non-nil, use a verbose version string.
302 When MESSAGE is non-nil, display a message with the version."
303 (interactive "P")
304 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
305 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
306 (load-suffixes (list ".el"))
307 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
308 (org-trash (or
309 (and (fboundp 'org-release) (fboundp 'org-git-version))
310 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
311 (load-suffixes save-load-suffixes)
312 (org-version (org-release))
313 (git-version (org-git-version))
314 (version (format "Org-mode version %s (%s @ %s)"
315 org-version
316 git-version
317 (if org-install-dir
318 (if (string= org-dir org-install-dir)
319 org-install-dir
320 (concat "mixed installation! " org-install-dir " and " org-dir))
321 "org-loaddefs.el can not be found!")))
322 (version1 (if full version org-version)))
323 (if (org-called-interactively-p 'interactive)
324 (if here
325 (insert version)
326 (message version))
327 (if message (message version1))
328 version1)))
330 (defconst org-version (org-version))
333 ;;; Syntax Constants
335 ;;;; Block
337 (defconst org-block-regexp
338 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
339 "Regular expression for hiding blocks.")
341 (defconst org-dblock-start-re
342 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
343 "Matches the start line of a dynamic block, with parameters.")
345 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
346 "Matches the end of a dynamic block.")
348 ;;;; Clock and Planning
350 (defconst org-clock-string "CLOCK:"
351 "String used as prefix for timestamps clocking work hours on an item.")
353 (defconst org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry.")
356 (defconst org-deadline-string "DEADLINE:"
357 "String to mark deadline entries.
358 A deadline is this string, followed by a time stamp. Should be a word,
359 terminated by a colon. You can insert a schedule keyword and
360 a timestamp with \\[org-deadline].")
362 (defconst org-scheduled-string "SCHEDULED:"
363 "String to mark scheduled TODO entries.
364 A schedule is this string, followed by a time stamp. Should be a word,
365 terminated by a colon. You can insert a schedule keyword and
366 a timestamp with \\[org-schedule].")
368 (defconst org-planning-or-clock-line-re
369 (concat "^[ \t]*"
370 (regexp-opt
371 (list org-clock-string org-closed-string org-deadline-string
372 org-scheduled-string)
374 "Matches a line with planning or clock info.
375 Matched keyword is in group 1.")
377 ;;;; Drawer
379 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
380 "Matches first or last line of a hidden block.
381 Group 1 contains drawer's name or \"END\".")
383 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
384 "Regular expression matching the first line of a property drawer.")
386 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
387 "Regular expression matching the last line of a property drawer.")
389 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
390 "Regular expression matching the first line of a clock drawer.")
392 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
393 "Regular expression matching the last line of a clock drawer.")
395 (defconst org-property-drawer-re
396 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
397 org-property-end-re "\\)\n?")
398 "Matches an entire property drawer.")
400 (defconst org-clock-drawer-re
401 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
402 org-clock-drawer-end-re "\\)\n?")
403 "Matches an entire clock drawer.")
405 ;;;; Headline
407 (defconst org-heading-keyword-regexp-format
408 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
409 "Printf format for a regexp matching a headline with some keyword.
410 This regexp will match the headline of any node which has the
411 exact keyword that is put into the format. The keyword isn't in
412 any group by default, but the stars and the body are.")
414 (defconst org-heading-keyword-maybe-regexp-format
415 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
416 "Printf format for a regexp matching a headline, possibly with some keyword.
417 This regexp can match any headline with the specified keyword, or
418 without a keyword. The keyword isn't in any group by default,
419 but the stars and the body are.")
421 (defconst org-archive-tag "ARCHIVE"
422 "The tag that marks a subtree as archived.
423 An archived subtree does not open during visibility cycling, and does
424 not contribute to the agenda listings.")
426 (defconst org-comment-string "COMMENT"
427 "Entries starting with this keyword will never be exported.
428 An entry can be toggled between COMMENT and normal with
429 \\[org-toggle-comment].")
431 (defconst org-quote-string "QUOTE"
432 "Entries starting with this keyword will be exported in fixed-width font.
433 Quoting applies only to the text in the entry following the headline, and does
434 not extend beyond the next headline, even if that is lower level.
435 An entry can be toggled between QUOTE and normal with
436 \\[org-toggle-fixed-width-section].")
438 ;;;; LaTeX Environments and Fragments
440 (defconst org-latex-regexps
441 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
442 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
443 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
444 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
445 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
446 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
447 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
448 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
449 "Regular expressions for matching embedded LaTeX.")
451 ;;;; Node Property
453 (defconst org-effort-property "Effort"
454 "The property that is being used to keep track of effort estimates.
455 Effort estimates given in this property need to have the format H:MM.")
457 ;;;; Table
459 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
460 "Detect an org-type or table-type table.")
462 (defconst org-table-line-regexp "^[ \t]*|"
463 "Detect an org-type table line.")
465 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
466 "Detect an org-type table line.")
468 (defconst org-table-hline-regexp "^[ \t]*|-"
469 "Detect an org-type table hline.")
471 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
472 "Detect a table-type table hline.")
474 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
475 "Detect the first line outside a table when searching from within it.
476 This works for both table types.")
478 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
479 "Detect a #+TBLFM line.")
481 ;;;; Timestamp
483 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
484 "Regular expression for fast time stamp matching.")
486 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
487 "Regular expression for fast time stamp matching.")
489 (defconst org-ts-regexp0
490 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
491 "Regular expression matching time strings for analysis.
492 This one does not require the space after the date, so it can be used
493 on a string that terminates immediately after the date.")
495 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
496 "Regular expression matching time strings for analysis.")
498 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
499 "Regular expression matching time stamps, with groups.")
501 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
502 "Regular expression matching time stamps (also [..]), with groups.")
504 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
505 "Regular expression matching a time stamp range.")
507 (defconst org-tr-regexp-both
508 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
509 "Regular expression matching a time stamp range.")
511 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
512 org-ts-regexp "\\)?")
513 "Regular expression matching a time stamp or time stamp range.")
515 (defconst org-tsr-regexp-both
516 (concat org-ts-regexp-both "\\(--?-?"
517 org-ts-regexp-both "\\)?")
518 "Regular expression matching a time stamp or time stamp range.
519 The time stamps may be either active or inactive.")
521 (defconst org-repeat-re
522 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
523 "Regular expression for specifying repeated events.
524 After a match, group 1 contains the repeat expression.")
526 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
527 "Formats for `format-time-string' which are used for time stamps.")
530 ;;; The custom variables
532 (defgroup org nil
533 "Outline-based notes management and organizer."
534 :tag "Org"
535 :group 'outlines
536 :group 'calendar)
538 (defcustom org-mode-hook nil
539 "Mode hook for Org-mode, run after the mode was turned on."
540 :group 'org
541 :type 'hook)
543 (defcustom org-load-hook nil
544 "Hook that is run after org.el has been loaded."
545 :group 'org
546 :type 'hook)
548 (defcustom org-log-buffer-setup-hook nil
549 "Hook that is run after an Org log buffer is created."
550 :group 'org
551 :version "24.1"
552 :type 'hook)
554 (defvar org-modules) ; defined below
555 (defvar org-modules-loaded nil
556 "Have the modules been loaded already?")
558 (defun org-load-modules-maybe (&optional force)
559 "Load all extensions listed in `org-modules'."
560 (when (or force (not org-modules-loaded))
561 (mapc (lambda (ext)
562 (condition-case nil (require ext)
563 (error (message "Problems while trying to load feature `%s'" ext))))
564 org-modules)
565 (setq org-modules-loaded t)))
567 (defun org-set-modules (var value)
568 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
569 (set var value)
570 (when (featurep 'org)
571 (org-load-modules-maybe 'force)
572 (org-element-cache-reset 'all)))
574 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
575 "Modules that should always be loaded together with org.el.
577 If a description starts with <C>, the file is not part of Emacs
578 and loading it will require that you have downloaded and properly
579 installed the Org mode distribution.
581 You can also use this system to load external packages (i.e. neither Org
582 core modules, nor modules from the CONTRIB directory). Just add symbols
583 to the end of the list. If the package is called org-xyz.el, then you need
584 to add the symbol `xyz', and the package must have a call to:
586 \(provide 'org-xyz)
588 For export specific modules, see also `org-export-backends'."
589 :group 'org
590 :set 'org-set-modules
591 :version "24.4"
592 :package-version '(Org . "8.0")
593 :type
594 '(set :greedy t
595 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
596 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
597 (const :tag " crypt: Encryption of subtrees" org-crypt)
598 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
599 (const :tag " docview: Links to doc-view buffers" org-docview)
600 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
601 (const :tag " habit: Track your consistency with habits" org-habit)
602 (const :tag " id: Global IDs for identifying entries" org-id)
603 (const :tag " info: Links to Info nodes" org-info)
604 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
605 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
606 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
607 (const :tag " mouse: Additional mouse support" org-mouse)
608 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
609 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
610 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
612 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
613 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
614 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
615 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
616 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
617 (const :tag "C collector: Collect properties into tables" org-collector)
618 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
619 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
620 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
621 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
622 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
623 (const :tag "C eval: Include command output as text" org-eval)
624 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
625 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
626 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
627 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
628 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
629 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
630 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
631 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
632 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
633 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
634 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
635 (const :tag "C mew: Links to Mew folders/messages" org-mew)
636 (const :tag "C mtags: Support for muse-like tags" org-mtags)
637 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
638 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
639 (const :tag "C registry: A registry for Org-mode links" org-registry)
640 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
641 (const :tag "C secretary: Team management with org-mode" org-secretary)
642 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
643 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
644 (const :tag "C track: Keep up with Org-mode development" org-track)
645 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
646 (const :tag "C vm: Links to VM folders/messages" org-vm)
647 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
648 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
649 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
651 (defvar org-export--registered-backends) ; From ox.el.
652 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
653 (declare-function org-export-backend-name "ox" (backend))
654 (defcustom org-export-backends '(ascii html icalendar latex)
655 "List of export back-ends that should be always available.
657 If a description starts with <C>, the file is not part of Emacs
658 and loading it will require that you have downloaded and properly
659 installed the Org mode distribution.
661 Unlike to `org-modules', libraries in this list will not be
662 loaded along with Org, but only once the export framework is
663 needed.
665 This variable needs to be set before org.el is loaded. If you
666 need to make a change while Emacs is running, use the customize
667 interface or run the following code, where VAL stands for the new
668 value of the variable, after updating it:
670 \(progn
671 \(setq org-export--registered-backends
672 \(org-remove-if-not
673 \(lambda (backend)
674 \(let ((name (org-export-backend-name backend)))
675 \(or (memq name val)
676 \(catch 'parentp
677 \(dolist (b val)
678 \(and (org-export-derived-backend-p b name)
679 \(throw 'parentp t)))))))
680 org-export--registered-backends))
681 \(let ((new-list (mapcar 'org-export-backend-name
682 org-export--registered-backends)))
683 \(dolist (backend val)
684 \(cond
685 \((not (load (format \"ox-%s\" backend) t t))
686 \(message \"Problems while trying to load export back-end `%s'\"
687 backend))
688 \((not (memq backend new-list)) (push backend new-list))))
689 \(set-default 'org-export-backends new-list)))
691 Adding a back-end to this list will also pull the back-end it
692 depends on, if any."
693 :group 'org
694 :group 'org-export
695 :version "24.4"
696 :package-version '(Org . "8.0")
697 :initialize 'custom-initialize-set
698 :set (lambda (var val)
699 (if (not (featurep 'ox)) (set-default var val)
700 ;; Any back-end not required anymore (not present in VAL and not
701 ;; a parent of any back-end in the new value) is removed from the
702 ;; list of registered back-ends.
703 (setq org-export--registered-backends
704 (org-remove-if-not
705 (lambda (backend)
706 (let ((name (org-export-backend-name backend)))
707 (or (memq name val)
708 (catch 'parentp
709 (dolist (b val)
710 (and (org-export-derived-backend-p b name)
711 (throw 'parentp t)))))))
712 org-export--registered-backends))
713 ;; Now build NEW-LIST of both new back-ends and required
714 ;; parents.
715 (let ((new-list (mapcar 'org-export-backend-name
716 org-export--registered-backends)))
717 (dolist (backend val)
718 (cond
719 ((not (load (format "ox-%s" backend) t t))
720 (message "Problems while trying to load export back-end `%s'"
721 backend))
722 ((not (memq backend new-list)) (push backend new-list))))
723 ;; Set VAR to that list with fixed dependencies.
724 (set-default var new-list))))
725 :type '(set :greedy t
726 (const :tag " ascii Export buffer to ASCII format" ascii)
727 (const :tag " beamer Export buffer to Beamer presentation" beamer)
728 (const :tag " html Export buffer to HTML format" html)
729 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
730 (const :tag " latex Export buffer to LaTeX format" latex)
731 (const :tag " man Export buffer to MAN format" man)
732 (const :tag " md Export buffer to Markdown format" md)
733 (const :tag " odt Export buffer to ODT format" odt)
734 (const :tag " org Export buffer to Org format" org)
735 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
736 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
737 (const :tag "C deck Export buffer to deck.js presentations" deck)
738 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
739 (const :tag "C groff Export buffer to Groff format" groff)
740 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
741 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
742 (const :tag "C s5 Export buffer to s5 presentations" s5)
743 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
745 (eval-after-load 'ox
746 '(mapc
747 (lambda (backend)
748 (condition-case nil (require (intern (format "ox-%s" backend)))
749 (error (message "Problems while trying to load export back-end `%s'"
750 backend))))
751 org-export-backends))
753 (defcustom org-support-shift-select nil
754 "Non-nil means make shift-cursor commands select text when possible.
756 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
757 start selecting a region, or enlarge regions started in this way.
758 In Org-mode, in special contexts, these same keys are used for
759 other purposes, important enough to compete with shift selection.
760 Org tries to balance these needs by supporting `shift-select-mode'
761 outside these special contexts, under control of this variable.
763 The default of this variable is nil, to avoid confusing behavior. Shifted
764 cursor keys will then execute Org commands in the following contexts:
765 - on a headline, changing TODO state (left/right) and priority (up/down)
766 - on a time stamp, changing the time
767 - in a plain list item, changing the bullet type
768 - in a property definition line, switching between allowed values
769 - in the BEGIN line of a clock table (changing the time block).
770 Outside these contexts, the commands will throw an error.
772 When this variable is t and the cursor is not in a special
773 context, Org-mode will support shift-selection for making and
774 enlarging regions. To make this more effective, the bullet
775 cycling will no longer happen anywhere in an item line, but only
776 if the cursor is exactly on the bullet.
778 If you set this variable to the symbol `always', then the keys
779 will not be special in headlines, property lines, and item lines,
780 to make shift selection work there as well. If this is what you
781 want, you can use the following alternative commands: `C-c C-t'
782 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
783 can be used to switch TODO sets, `C-c -' to cycle item bullet
784 types, and properties can be edited by hand or in column view.
786 However, when the cursor is on a timestamp, shift-cursor commands
787 will still edit the time stamp - this is just too good to give up.
789 XEmacs user should have this variable set to nil, because
790 `shift-select-mode' is in Emacs 23 or later only."
791 :group 'org
792 :type '(choice
793 (const :tag "Never" nil)
794 (const :tag "When outside special context" t)
795 (const :tag "Everywhere except timestamps" always)))
797 (defcustom org-loop-over-headlines-in-active-region nil
798 "Shall some commands act upon headlines in the active region?
800 When set to `t', some commands will be performed in all headlines
801 within the active region.
803 When set to `start-level', some commands will be performed in all
804 headlines within the active region, provided that these headlines
805 are of the same level than the first one.
807 When set to a string, those commands will be performed on the
808 matching headlines within the active region. Such string must be
809 a tags/property/todo match as it is used in the agenda tags view.
811 The list of commands is: `org-schedule', `org-deadline',
812 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
813 `org-archive-to-archive-sibling'. The archiving commands skip
814 already archived entries."
815 :type '(choice (const :tag "Don't loop" nil)
816 (const :tag "All headlines in active region" t)
817 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
818 (string :tag "Tags/Property/Todo matcher"))
819 :version "24.1"
820 :group 'org-todo
821 :group 'org-archive)
823 (defgroup org-startup nil
824 "Options concerning startup of Org-mode."
825 :tag "Org Startup"
826 :group 'org)
828 (defcustom org-startup-folded t
829 "Non-nil means entering Org-mode will switch to OVERVIEW.
830 This can also be configured on a per-file basis by adding one of
831 the following lines anywhere in the buffer:
833 #+STARTUP: fold (or `overview', this is equivalent)
834 #+STARTUP: nofold (or `showall', this is equivalent)
835 #+STARTUP: content
836 #+STARTUP: showeverything
838 By default, this option is ignored when Org opens agenda files
839 for the first time. If you want the agenda to honor the startup
840 option, set `org-agenda-inhibit-startup' to nil."
841 :group 'org-startup
842 :type '(choice
843 (const :tag "nofold: show all" nil)
844 (const :tag "fold: overview" t)
845 (const :tag "content: all headlines" content)
846 (const :tag "show everything, even drawers" showeverything)))
848 (defcustom org-startup-truncated t
849 "Non-nil means entering Org-mode will set `truncate-lines'.
850 This is useful since some lines containing links can be very long and
851 uninteresting. Also tables look terrible when wrapped."
852 :group 'org-startup
853 :type 'boolean)
855 (defcustom org-startup-indented nil
856 "Non-nil means turn on `org-indent-mode' on startup.
857 This can also be configured on a per-file basis by adding one of
858 the following lines anywhere in the buffer:
860 #+STARTUP: indent
861 #+STARTUP: noindent"
862 :group 'org-structure
863 :type '(choice
864 (const :tag "Not" nil)
865 (const :tag "Globally (slow on startup in large files)" t)))
867 (defcustom org-use-sub-superscripts t
868 "Non-nil means interpret \"_\" and \"^\" for display.
870 If you want to control how Org exports those characters, see
871 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
872 used to be an alias for `org-export-with-sub-superscripts' in
873 Org <8.0, it is not anymore.
875 When this option is turned on, you can use TeX-like syntax for
876 sub- and superscripts within the buffer. Several characters after
877 \"_\" or \"^\" will be considered as a single item - so grouping
878 with {} is normally not needed. For example, the following things
879 will be parsed as single sub- or superscripts:
881 10^24 or 10^tau several digits will be considered 1 item.
882 10^-12 or 10^-tau a leading sign with digits or a word
883 x^2-y^3 will be read as x^2 - y^3, because items are
884 terminated by almost any nonword/nondigit char.
885 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
887 Still, ambiguity is possible. So when in doubt, use {} to enclose
888 the sub/superscript. If you set this variable to the symbol `{}',
889 the braces are *required* in order to trigger interpretations as
890 sub/superscript. This can be helpful in documents that need \"_\"
891 frequently in plain text."
892 :group 'org-startup
893 :version "24.4"
894 :package-version '(Org . "8.0")
895 :type '(choice
896 (const :tag "Always interpret" t)
897 (const :tag "Only with braces" {})
898 (const :tag "Never interpret" nil)))
900 (defcustom org-startup-with-beamer-mode nil
901 "Non-nil means turn on `org-beamer-mode' on startup.
902 This can also be configured on a per-file basis by adding one of
903 the following lines anywhere in the buffer:
905 #+STARTUP: beamer"
906 :group 'org-startup
907 :version "24.1"
908 :type 'boolean)
910 (defcustom org-startup-align-all-tables nil
911 "Non-nil means align all tables when visiting a file.
912 This is useful when the column width in tables is forced with <N> cookies
913 in table fields. Such tables will look correct only after the first re-align.
914 This can also be configured on a per-file basis by adding one of
915 the following lines anywhere in the buffer:
916 #+STARTUP: align
917 #+STARTUP: noalign"
918 :group 'org-startup
919 :type 'boolean)
921 (defcustom org-startup-with-inline-images nil
922 "Non-nil means show inline images when loading a new Org file.
923 This can also be configured on a per-file basis by adding one of
924 the following lines anywhere in the buffer:
925 #+STARTUP: inlineimages
926 #+STARTUP: noinlineimages"
927 :group 'org-startup
928 :version "24.1"
929 :type 'boolean)
931 (defcustom org-startup-with-latex-preview nil
932 "Non-nil means preview LaTeX fragments when loading a new Org file.
934 This can also be configured on a per-file basis by adding one of
935 the following lines anywhere in the buffer:
936 #+STARTUP: latexpreview
937 #+STARTUP: nolatexpreview"
938 :group 'org-startup
939 :version "24.4"
940 :package-version '(Org . "8.0")
941 :type 'boolean)
943 (defcustom org-insert-mode-line-in-empty-file nil
944 "Non-nil means insert the first line setting Org-mode in empty files.
945 When the function `org-mode' is called interactively in an empty file, this
946 normally means that the file name does not automatically trigger Org-mode.
947 To ensure that the file will always be in Org-mode in the future, a
948 line enforcing Org-mode will be inserted into the buffer, if this option
949 has been set."
950 :group 'org-startup
951 :type 'boolean)
953 (defcustom org-replace-disputed-keys nil
954 "Non-nil means use alternative key bindings for some keys.
955 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
956 These keys are also used by other packages like shift-selection-mode'
957 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
958 If you want to use Org-mode together with one of these other modes,
959 or more generally if you would like to move some Org-mode commands to
960 other keys, set this variable and configure the keys with the variable
961 `org-disputed-keys'.
963 This option is only relevant at load-time of Org-mode, and must be set
964 *before* org.el is loaded. Changing it requires a restart of Emacs to
965 become effective."
966 :group 'org-startup
967 :type 'boolean)
969 (defcustom org-use-extra-keys nil
970 "Non-nil means use extra key sequence definitions for certain commands.
971 This happens automatically if you run XEmacs or if `window-system'
972 is nil. This variable lets you do the same manually. You must
973 set it before loading org.
975 Example: on Carbon Emacs 22 running graphically, with an external
976 keyboard on a Powerbook, the default way of setting M-left might
977 not work for either Alt or ESC. Setting this variable will make
978 it work for ESC."
979 :group 'org-startup
980 :type 'boolean)
982 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
984 (defcustom org-disputed-keys
985 '(([(shift up)] . [(meta p)])
986 ([(shift down)] . [(meta n)])
987 ([(shift left)] . [(meta -)])
988 ([(shift right)] . [(meta +)])
989 ([(control shift right)] . [(meta shift +)])
990 ([(control shift left)] . [(meta shift -)]))
991 "Keys for which Org-mode and other modes compete.
992 This is an alist, cars are the default keys, second element specifies
993 the alternative to use when `org-replace-disputed-keys' is t.
995 Keys can be specified in any syntax supported by `define-key'.
996 The value of this option takes effect only at Org-mode's startup,
997 therefore you'll have to restart Emacs to apply it after changing."
998 :group 'org-startup
999 :type 'alist)
1001 (defun org-key (key)
1002 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1003 Or return the original if not disputed.
1004 Also apply the translations defined in `org-xemacs-key-equivalents'."
1005 (when org-replace-disputed-keys
1006 (let* ((nkey (key-description key))
1007 (x (org-find-if (lambda (x)
1008 (equal (key-description (car x)) nkey))
1009 org-disputed-keys)))
1010 (setq key (if x (cdr x) key))))
1011 (when (featurep 'xemacs)
1012 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1013 key)
1015 (defun org-find-if (predicate seq)
1016 (catch 'exit
1017 (while seq
1018 (if (funcall predicate (car seq))
1019 (throw 'exit (car seq))
1020 (pop seq)))))
1022 (defun org-defkey (keymap key def)
1023 "Define a key, possibly translated, as returned by `org-key'."
1024 (define-key keymap (org-key key) def))
1026 (defcustom org-ellipsis nil
1027 "The ellipsis to use in the Org-mode outline.
1028 When nil, just use the standard three dots. When a string, use that instead,
1029 When a face, use the standard 3 dots, but with the specified face.
1030 The change affects only Org-mode (which will then use its own display table).
1031 Changing this requires executing `M-x org-mode' in a buffer to become
1032 effective."
1033 :group 'org-startup
1034 :type '(choice (const :tag "Default" nil)
1035 (face :tag "Face" :value org-warning)
1036 (string :tag "String" :value "...#")))
1038 (defvar org-display-table nil
1039 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1041 (defgroup org-keywords nil
1042 "Keywords in Org-mode."
1043 :tag "Org Keywords"
1044 :group 'org)
1046 (defcustom org-closed-keep-when-no-todo nil
1047 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1048 :group 'org-todo
1049 :group 'org-keywords
1050 :version "24.4"
1051 :package-version '(Org . "8.0")
1052 :type 'boolean)
1054 (defgroup org-structure nil
1055 "Options concerning the general structure of Org-mode files."
1056 :tag "Org Structure"
1057 :group 'org)
1059 (defgroup org-reveal-location nil
1060 "Options about how to make context of a location visible."
1061 :tag "Org Reveal Location"
1062 :group 'org-structure)
1064 (defconst org-context-choice
1065 '(choice
1066 (const :tag "Always" t)
1067 (const :tag "Never" nil)
1068 (repeat :greedy t :tag "Individual contexts"
1069 (cons
1070 (choice :tag "Context"
1071 (const agenda)
1072 (const org-goto)
1073 (const occur-tree)
1074 (const tags-tree)
1075 (const link-search)
1076 (const mark-goto)
1077 (const bookmark-jump)
1078 (const isearch)
1079 (const default))
1080 (boolean))))
1081 "Contexts for the reveal options.")
1083 (defcustom org-show-hierarchy-above '((default . t))
1084 "Non-nil means show full hierarchy when revealing a location.
1085 Org-mode often shows locations in an org-mode file which might have
1086 been invisible before. When this is set, the hierarchy of headings
1087 above the exposed location is shown.
1088 Turning this off for example for sparse trees makes them very compact.
1089 Instead of t, this can also be an alist specifying this option for different
1090 contexts. Valid contexts are
1091 agenda when exposing an entry from the agenda
1092 org-goto when using the command `org-goto' on key C-c C-j
1093 occur-tree when using the command `org-occur' on key C-c /
1094 tags-tree when constructing a sparse tree based on tags matches
1095 link-search when exposing search matches associated with a link
1096 mark-goto when exposing the jump goal of a mark
1097 bookmark-jump when exposing a bookmark location
1098 isearch when exiting from an incremental search
1099 default default for all contexts not set explicitly"
1100 :group 'org-reveal-location
1101 :type org-context-choice)
1103 (defcustom org-show-following-heading '((default . nil))
1104 "Non-nil means show following heading when revealing a location.
1105 Org-mode often shows locations in an org-mode file which might have
1106 been invisible before. When this is set, the heading following the
1107 match is shown.
1108 Turning this off for example for sparse trees makes them very compact,
1109 but makes it harder to edit the location of the match. In such a case,
1110 use the command \\[org-reveal] to show more context.
1111 Instead of t, this can also be an alist specifying this option for different
1112 contexts. See `org-show-hierarchy-above' for valid contexts."
1113 :group 'org-reveal-location
1114 :type org-context-choice)
1116 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1117 "Non-nil means show all sibling heading when revealing a location.
1118 Org-mode often shows locations in an org-mode file which might have
1119 been invisible before. When this is set, the sibling of the current entry
1120 heading are all made visible. If `org-show-hierarchy-above' is t,
1121 the same happens on each level of the hierarchy above the current entry.
1123 By default this is on for the isearch context, off for all other contexts.
1124 Turning this off for example for sparse trees makes them very compact,
1125 but makes it harder to edit the location of the match. In such a case,
1126 use the command \\[org-reveal] to show more context.
1127 Instead of t, this can also be an alist specifying this option for different
1128 contexts. See `org-show-hierarchy-above' for valid contexts."
1129 :group 'org-reveal-location
1130 :type org-context-choice
1131 :version "24.4"
1132 :package-version '(Org . "8.0"))
1134 (defcustom org-show-entry-below '((default . nil))
1135 "Non-nil means show the entry below a headline when revealing a location.
1136 Org-mode often shows locations in an org-mode file which might have
1137 been invisible before. When this is set, the text below the headline that is
1138 exposed is also shown.
1140 By default this is off for all contexts.
1141 Instead of t, this can also be an alist specifying this option for different
1142 contexts. See `org-show-hierarchy-above' for valid contexts."
1143 :group 'org-reveal-location
1144 :type org-context-choice)
1146 (defcustom org-indirect-buffer-display 'other-window
1147 "How should indirect tree buffers be displayed?
1148 This applies to indirect buffers created with the commands
1149 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1150 Valid values are:
1151 current-window Display in the current window
1152 other-window Just display in another window.
1153 dedicated-frame Create one new frame, and re-use it each time.
1154 new-frame Make a new frame each time. Note that in this case
1155 previously-made indirect buffers are kept, and you need to
1156 kill these buffers yourself."
1157 :group 'org-structure
1158 :group 'org-agenda-windows
1159 :type '(choice
1160 (const :tag "In current window" current-window)
1161 (const :tag "In current frame, other window" other-window)
1162 (const :tag "Each time a new frame" new-frame)
1163 (const :tag "One dedicated frame" dedicated-frame)))
1165 (defcustom org-use-speed-commands nil
1166 "Non-nil means activate single letter commands at beginning of a headline.
1167 This may also be a function to test for appropriate locations where speed
1168 commands should be active.
1170 For example, to activate speed commands when the point is on any
1171 star at the beginning of the headline, you can do this:
1173 (setq org-use-speed-commands
1174 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1175 :group 'org-structure
1176 :type '(choice
1177 (const :tag "Never" nil)
1178 (const :tag "At beginning of headline stars" t)
1179 (function)))
1181 (defcustom org-speed-commands-user nil
1182 "Alist of additional speed commands.
1183 This list will be checked before `org-speed-commands-default'
1184 when the variable `org-use-speed-commands' is non-nil
1185 and when the cursor is at the beginning of a headline.
1186 The car if each entry is a string with a single letter, which must
1187 be assigned to `self-insert-command' in the global map.
1188 The cdr is either a command to be called interactively, a function
1189 to be called, or a form to be evaluated.
1190 An entry that is just a list with a single string will be interpreted
1191 as a descriptive headline that will be added when listing the speed
1192 commands in the Help buffer using the `?' speed command."
1193 :group 'org-structure
1194 :type '(repeat :value ("k" . ignore)
1195 (choice :value ("k" . ignore)
1196 (list :tag "Descriptive Headline" (string :tag "Headline"))
1197 (cons :tag "Letter and Command"
1198 (string :tag "Command letter")
1199 (choice
1200 (function)
1201 (sexp))))))
1203 (defcustom org-bookmark-names-plist
1204 '(:last-capture "org-capture-last-stored"
1205 :last-refile "org-refile-last-stored"
1206 :last-capture-marker "org-capture-last-stored-marker")
1207 "Names for bookmarks automatically set by some Org commands.
1208 This can provide strings as names for a number of bookmarks Org sets
1209 automatically. The following keys are currently implemented:
1210 :last-capture
1211 :last-capture-marker
1212 :last-refile
1213 When a key does not show up in the property list, the corresponding bookmark
1214 is not set."
1215 :group 'org-structure
1216 :type 'plist)
1218 (defgroup org-cycle nil
1219 "Options concerning visibility cycling in Org-mode."
1220 :tag "Org Cycle"
1221 :group 'org-structure)
1223 (defcustom org-cycle-skip-children-state-if-no-children t
1224 "Non-nil means skip CHILDREN state in entries that don't have any."
1225 :group 'org-cycle
1226 :type 'boolean)
1228 (defcustom org-cycle-max-level nil
1229 "Maximum level which should still be subject to visibility cycling.
1230 Levels higher than this will, for cycling, be treated as text, not a headline.
1231 When `org-odd-levels-only' is set, a value of N in this variable actually
1232 means 2N-1 stars as the limiting headline.
1233 When nil, cycle all levels.
1234 Note that the limiting level of cycling is also influenced by
1235 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1236 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1237 than its value."
1238 :group 'org-cycle
1239 :type '(choice
1240 (const :tag "No limit" nil)
1241 (integer :tag "Maximum level")))
1243 (defcustom org-hide-block-startup nil
1244 "Non-nil means entering Org-mode will fold all blocks.
1245 This can also be set in on a per-file basis with
1247 #+STARTUP: hideblocks
1248 #+STARTUP: showblocks"
1249 :group 'org-startup
1250 :group 'org-cycle
1251 :type 'boolean)
1253 (defcustom org-cycle-global-at-bob nil
1254 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1255 This makes it possible to do global cycling without having to use S-TAB or
1256 \\[universal-argument] TAB. For this special case to work, the first line
1257 of the buffer must not be a headline -- it may be empty or some other text.
1258 When used in this way, `org-cycle-hook' is disabled temporarily to make
1259 sure the cursor stays at the beginning of the buffer. When this option is
1260 nil, don't do anything special at the beginning of the buffer."
1261 :group 'org-cycle
1262 :type 'boolean)
1264 (defcustom org-cycle-level-after-item/entry-creation t
1265 "Non-nil means cycle entry level or item indentation in new empty entries.
1267 When the cursor is at the end of an empty headline, i.e., with only stars
1268 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1269 and then all possible ancestor states, before returning to the original state.
1270 This makes data entry extremely fast: M-RET to create a new headline,
1271 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1273 When the cursor is at the end of an empty plain list item, one TAB will
1274 make it a subitem, two or more tabs will back up to make this an item
1275 higher up in the item hierarchy."
1276 :group 'org-cycle
1277 :type 'boolean)
1279 (defcustom org-cycle-emulate-tab t
1280 "Where should `org-cycle' emulate TAB.
1281 nil Never
1282 white Only in completely white lines
1283 whitestart Only at the beginning of lines, before the first non-white char
1284 t Everywhere except in headlines
1285 exc-hl-bol Everywhere except at the start of a headline
1286 If TAB is used in a place where it does not emulate TAB, the current subtree
1287 visibility is cycled."
1288 :group 'org-cycle
1289 :type '(choice (const :tag "Never" nil)
1290 (const :tag "Only in completely white lines" white)
1291 (const :tag "Before first char in a line" whitestart)
1292 (const :tag "Everywhere except in headlines" t)
1293 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1295 (defcustom org-cycle-separator-lines 2
1296 "Number of empty lines needed to keep an empty line between collapsed trees.
1297 If you leave an empty line between the end of a subtree and the following
1298 headline, this empty line is hidden when the subtree is folded.
1299 Org-mode will leave (exactly) one empty line visible if the number of
1300 empty lines is equal or larger to the number given in this variable.
1301 So the default 2 means at least 2 empty lines after the end of a subtree
1302 are needed to produce free space between a collapsed subtree and the
1303 following headline.
1305 If the number is negative, and the number of empty lines is at least -N,
1306 all empty lines are shown.
1308 Special case: when 0, never leave empty lines in collapsed view."
1309 :group 'org-cycle
1310 :type 'integer)
1311 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1313 (defcustom org-pre-cycle-hook nil
1314 "Hook that is run before visibility cycling is happening.
1315 The function(s) in this hook must accept a single argument which indicates
1316 the new state that will be set right after running this hook. The
1317 argument is a symbol. Before a global state change, it can have the values
1318 `overview', `content', or `all'. Before a local state change, it can have
1319 the values `folded', `children', or `subtree'."
1320 :group 'org-cycle
1321 :type 'hook)
1323 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1324 org-cycle-hide-drawers
1325 org-cycle-hide-inline-tasks
1326 org-cycle-show-empty-lines
1327 org-optimize-window-after-visibility-change)
1328 "Hook that is run after `org-cycle' has changed the buffer visibility.
1329 The function(s) in this hook must accept a single argument which indicates
1330 the new state that was set by the most recent `org-cycle' command. The
1331 argument is a symbol. After a global state change, it can have the values
1332 `overview', `contents', or `all'. After a local state change, it can have
1333 the values `folded', `children', or `subtree'."
1334 :group 'org-cycle
1335 :type 'hook)
1337 (defgroup org-edit-structure nil
1338 "Options concerning structure editing in Org-mode."
1339 :tag "Org Edit Structure"
1340 :group 'org-structure)
1342 (defcustom org-odd-levels-only nil
1343 "Non-nil means skip even levels and only use odd levels for the outline.
1344 This has the effect that two stars are being added/taken away in
1345 promotion/demotion commands. It also influences how levels are
1346 handled by the exporters.
1347 Changing it requires restart of `font-lock-mode' to become effective
1348 for fontification also in regions already fontified.
1349 You may also set this on a per-file basis by adding one of the following
1350 lines to the buffer:
1352 #+STARTUP: odd
1353 #+STARTUP: oddeven"
1354 :group 'org-edit-structure
1355 :group 'org-appearance
1356 :type 'boolean)
1358 (defcustom org-adapt-indentation t
1359 "Non-nil means adapt indentation to outline node level.
1361 When this variable is set, Org assumes that you write outlines by
1362 indenting text in each node to align with the headline (after the stars).
1363 The following issues are influenced by this variable:
1365 - When this is set and the *entire* text in an entry is indented, the
1366 indentation is increased by one space in a demotion command, and
1367 decreased by one in a promotion command. If any line in the entry
1368 body starts with text at column 0, indentation is not changed at all.
1370 - Property drawers and planning information is inserted indented when
1371 this variable s set. When nil, they will not be indented.
1373 - TAB indents a line relative to context. The lines below a headline
1374 will be indented when this variable is set.
1376 Note that this is all about true indentation, by adding and removing
1377 space characters. See also `org-indent.el' which does level-dependent
1378 indentation in a virtual way, i.e. at display time in Emacs."
1379 :group 'org-edit-structure
1380 :type 'boolean)
1382 (defcustom org-special-ctrl-a/e nil
1383 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1385 When t, `C-a' will bring back the cursor to the beginning of the
1386 headline text, i.e. after the stars and after a possible TODO
1387 keyword. In an item, this will be the position after bullet and
1388 check-box, if any. When the cursor is already at that position,
1389 another `C-a' will bring it to the beginning of the line.
1391 `C-e' will jump to the end of the headline, ignoring the presence
1392 of tags in the headline. A second `C-e' will then jump to the
1393 true end of the line, after any tags. This also means that, when
1394 this variable is non-nil, `C-e' also will never jump beyond the
1395 end of the heading of a folded section, i.e. not after the
1396 ellipses.
1398 When set to the symbol `reversed', the first `C-a' or `C-e' works
1399 normally, going to the true line boundary first. Only a directly
1400 following, identical keypress will bring the cursor to the
1401 special positions.
1403 This may also be a cons cell where the behavior for `C-a' and
1404 `C-e' is set separately."
1405 :group 'org-edit-structure
1406 :type '(choice
1407 (const :tag "off" nil)
1408 (const :tag "on: after stars/bullet and before tags first" t)
1409 (const :tag "reversed: true line boundary first" reversed)
1410 (cons :tag "Set C-a and C-e separately"
1411 (choice :tag "Special C-a"
1412 (const :tag "off" nil)
1413 (const :tag "on: after stars/bullet first" t)
1414 (const :tag "reversed: before stars/bullet first" reversed))
1415 (choice :tag "Special C-e"
1416 (const :tag "off" nil)
1417 (const :tag "on: before tags first" t)
1418 (const :tag "reversed: after tags first" reversed)))))
1419 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1421 (defcustom org-special-ctrl-k nil
1422 "Non-nil means `C-k' will behave specially in headlines.
1423 When nil, `C-k' will call the default `kill-line' command.
1424 When t, the following will happen while the cursor is in the headline:
1426 - When the cursor is at the beginning of a headline, kill the entire
1427 line and possible the folded subtree below the line.
1428 - When in the middle of the headline text, kill the headline up to the tags.
1429 - When after the headline text, kill the tags."
1430 :group 'org-edit-structure
1431 :type 'boolean)
1433 (defcustom org-ctrl-k-protect-subtree nil
1434 "Non-nil means, do not delete a hidden subtree with C-k.
1435 When set to the symbol `error', simply throw an error when C-k is
1436 used to kill (part-of) a headline that has hidden text behind it.
1437 Any other non-nil value will result in a query to the user, if it is
1438 OK to kill that hidden subtree. When nil, kill without remorse."
1439 :group 'org-edit-structure
1440 :version "24.1"
1441 :type '(choice
1442 (const :tag "Do not protect hidden subtrees" nil)
1443 (const :tag "Protect hidden subtrees with a security query" t)
1444 (const :tag "Never kill a hidden subtree with C-k" error)))
1446 (defcustom org-special-ctrl-o t
1447 "Non-nil means, make `C-o' insert a row in tables."
1448 :group 'org-edit-structure
1449 :type 'boolean)
1451 (defcustom org-catch-invisible-edits nil
1452 "Check if in invisible region before inserting or deleting a character.
1453 Valid values are:
1455 nil Do not check, so just do invisible edits.
1456 error Throw an error and do nothing.
1457 show Make point visible, and do the requested edit.
1458 show-and-error Make point visible, then throw an error and abort the edit.
1459 smart Make point visible, and do insertion/deletion if it is
1460 adjacent to visible text and the change feels predictable.
1461 Never delete a previously invisible character or add in the
1462 middle or right after an invisible region. Basically, this
1463 allows insertion and backward-delete right before ellipses.
1464 FIXME: maybe in this case we should not even show?"
1465 :group 'org-edit-structure
1466 :version "24.1"
1467 :type '(choice
1468 (const :tag "Do not check" nil)
1469 (const :tag "Throw error when trying to edit" error)
1470 (const :tag "Unhide, but do not do the edit" show-and-error)
1471 (const :tag "Show invisible part and do the edit" show)
1472 (const :tag "Be smart and do the right thing" smart)))
1474 (defcustom org-yank-folded-subtrees t
1475 "Non-nil means when yanking subtrees, fold them.
1476 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1477 it starts with a heading and all other headings in it are either children
1478 or siblings, then fold all the subtrees. However, do this only if no
1479 text after the yank would be swallowed into a folded tree by this action."
1480 :group 'org-edit-structure
1481 :type 'boolean)
1483 (defcustom org-yank-adjusted-subtrees nil
1484 "Non-nil means when yanking subtrees, adjust the level.
1485 With this setting, `org-paste-subtree' is used to insert the subtree, see
1486 this function for details."
1487 :group 'org-edit-structure
1488 :type 'boolean)
1490 (defcustom org-M-RET-may-split-line '((default . t))
1491 "Non-nil means M-RET will split the line at the cursor position.
1492 When nil, it will go to the end of the line before making a
1493 new line.
1494 You may also set this option in a different way for different
1495 contexts. Valid contexts are:
1497 headline when creating a new headline
1498 item when creating a new item
1499 table in a table field
1500 default the value to be used for all contexts not explicitly
1501 customized"
1502 :group 'org-structure
1503 :group 'org-table
1504 :type '(choice
1505 (const :tag "Always" t)
1506 (const :tag "Never" nil)
1507 (repeat :greedy t :tag "Individual contexts"
1508 (cons
1509 (choice :tag "Context"
1510 (const headline)
1511 (const item)
1512 (const table)
1513 (const default))
1514 (boolean)))))
1517 (defcustom org-insert-heading-respect-content nil
1518 "Non-nil means insert new headings after the current subtree.
1519 When nil, the new heading is created directly after the current line.
1520 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1521 this variable on for the duration of the command."
1522 :group 'org-structure
1523 :type 'boolean)
1525 (defcustom org-blank-before-new-entry '((heading . auto)
1526 (plain-list-item . auto))
1527 "Should `org-insert-heading' leave a blank line before new heading/item?
1528 The value is an alist, with `heading' and `plain-list-item' as CAR,
1529 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1530 which case Org will look at the surrounding headings/items and try to
1531 make an intelligent decision whether to insert a blank line or not.
1533 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1534 the setting here is ignored and no empty line is inserted to avoid breaking
1535 the list structure."
1536 :group 'org-edit-structure
1537 :type '(list
1538 (cons (const heading)
1539 (choice (const :tag "Never" nil)
1540 (const :tag "Always" t)
1541 (const :tag "Auto" auto)))
1542 (cons (const plain-list-item)
1543 (choice (const :tag "Never" nil)
1544 (const :tag "Always" t)
1545 (const :tag "Auto" auto)))))
1547 (defcustom org-insert-heading-hook nil
1548 "Hook being run after inserting a new heading."
1549 :group 'org-edit-structure
1550 :type 'hook)
1552 (defcustom org-enable-fixed-width-editor t
1553 "Non-nil means lines starting with \":\" are treated as fixed-width.
1554 This currently only means they are never auto-wrapped.
1555 When nil, such lines will be treated like ordinary lines.
1556 See also the QUOTE keyword."
1557 :group 'org-edit-structure
1558 :type 'boolean)
1560 (defcustom org-goto-auto-isearch t
1561 "Non-nil means typing characters in `org-goto' starts incremental search.
1562 When nil, you can use these keybindings to navigate the buffer:
1564 q Quit the org-goto interface
1565 n Go to the next visible heading
1566 p Go to the previous visible heading
1567 f Go one heading forward on same level
1568 b Go one heading backward on same level
1569 u Go one heading up"
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defgroup org-sparse-trees nil
1574 "Options concerning sparse trees in Org-mode."
1575 :tag "Org Sparse Trees"
1576 :group 'org-structure)
1578 (defcustom org-highlight-sparse-tree-matches t
1579 "Non-nil means highlight all matches that define a sparse tree.
1580 The highlights will automatically disappear the next time the buffer is
1581 changed by an edit command."
1582 :group 'org-sparse-trees
1583 :type 'boolean)
1585 (defcustom org-remove-highlights-with-change t
1586 "Non-nil means any change to the buffer will remove temporary highlights.
1587 Such highlights are created by `org-occur' and `org-clock-display'.
1588 When nil, `C-c C-c needs to be used to get rid of the highlights.
1589 The highlights created by `org-preview-latex-fragment' always need
1590 `C-c C-c' to be removed."
1591 :group 'org-sparse-trees
1592 :group 'org-time
1593 :type 'boolean)
1596 (defcustom org-occur-hook '(org-first-headline-recenter)
1597 "Hook that is run after `org-occur' has constructed a sparse tree.
1598 This can be used to recenter the window to show as much of the structure
1599 as possible."
1600 :group 'org-sparse-trees
1601 :type 'hook)
1603 (defgroup org-imenu-and-speedbar nil
1604 "Options concerning imenu and speedbar in Org-mode."
1605 :tag "Org Imenu and Speedbar"
1606 :group 'org-structure)
1608 (defcustom org-imenu-depth 2
1609 "The maximum level for Imenu access to Org-mode headlines.
1610 This also applied for speedbar access."
1611 :group 'org-imenu-and-speedbar
1612 :type 'integer)
1614 (defgroup org-table nil
1615 "Options concerning tables in Org-mode."
1616 :tag "Org Table"
1617 :group 'org)
1619 (defcustom org-enable-table-editor 'optimized
1620 "Non-nil means lines starting with \"|\" are handled by the table editor.
1621 When nil, such lines will be treated like ordinary lines.
1623 When equal to the symbol `optimized', the table editor will be optimized to
1624 do the following:
1625 - Automatic overwrite mode in front of whitespace in table fields.
1626 This makes the structure of the table stay in tact as long as the edited
1627 field does not exceed the column width.
1628 - Minimize the number of realigns. Normally, the table is aligned each time
1629 TAB or RET are pressed to move to another field. With optimization this
1630 happens only if changes to a field might have changed the column width.
1631 Optimization requires replacing the functions `self-insert-command',
1632 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1633 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1634 very good at guessing when a re-align will be necessary, but you can always
1635 force one with \\[org-ctrl-c-ctrl-c].
1637 If you would like to use the optimized version in Org-mode, but the
1638 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1640 This variable can be used to turn on and off the table editor during a session,
1641 but in order to toggle optimization, a restart is required.
1643 See also the variable `org-table-auto-blank-field'."
1644 :group 'org-table
1645 :type '(choice
1646 (const :tag "off" nil)
1647 (const :tag "on" t)
1648 (const :tag "on, optimized" optimized)))
1650 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1651 (version<= emacs-version "24.1"))
1652 "Non-nil means cluster self-insert commands for undo when possible.
1653 If this is set, then, like in the Emacs command loop, 20 consecutive
1654 characters will be undone together.
1655 This is configurable, because there is some impact on typing performance."
1656 :group 'org-table
1657 :type 'boolean)
1659 (defcustom org-table-tab-recognizes-table.el t
1660 "Non-nil means TAB will automatically notice a table.el table.
1661 When it sees such a table, it moves point into it and - if necessary -
1662 calls `table-recognize-table'."
1663 :group 'org-table-editing
1664 :type 'boolean)
1666 (defgroup org-link nil
1667 "Options concerning links in Org-mode."
1668 :tag "Org Link"
1669 :group 'org)
1671 (defvar org-link-abbrev-alist-local nil
1672 "Buffer-local version of `org-link-abbrev-alist', which see.
1673 The value of this is taken from the #+LINK lines.")
1674 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1676 (defcustom org-link-abbrev-alist nil
1677 "Alist of link abbreviations.
1678 The car of each element is a string, to be replaced at the start of a link.
1679 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1680 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1682 [[linkkey:tag][description]]
1684 The 'linkkey' must be a word word, starting with a letter, followed
1685 by letters, numbers, '-' or '_'.
1687 If REPLACE is a string, the tag will simply be appended to create the link.
1688 If the string contains \"%s\", the tag will be inserted there. If the string
1689 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1690 at that point (see the function `url-hexify-string'). If the string contains
1691 the specifier \"%(my-function)\", then the custom function `my-function' will
1692 be invoked: this function takes the tag as its only argument and must return
1693 a string.
1695 REPLACE may also be a function that will be called with the tag as the
1696 only argument to create the link, which should be returned as a string.
1698 See the manual for examples."
1699 :group 'org-link
1700 :type '(repeat
1701 (cons
1702 (string :tag "Protocol")
1703 (choice
1704 (string :tag "Format")
1705 (function)))))
1707 (defcustom org-descriptive-links t
1708 "Non-nil means Org will display descriptive links.
1709 E.g. [[http://orgmode.org][Org website]] will be displayed as
1710 \"Org Website\", hiding the link itself and just displaying its
1711 description. When set to `nil', Org will display the full links
1712 literally.
1714 You can interactively set the value of this variable by calling
1715 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1716 :group 'org-link
1717 :type 'boolean)
1719 (defcustom org-link-file-path-type 'adaptive
1720 "How the path name in file links should be stored.
1721 Valid values are:
1723 relative Relative to the current directory, i.e. the directory of the file
1724 into which the link is being inserted.
1725 absolute Absolute path, if possible with ~ for home directory.
1726 noabbrev Absolute path, no abbreviation of home directory.
1727 adaptive Use relative path for files in the current directory and sub-
1728 directories of it. For other files, use an absolute path."
1729 :group 'org-link
1730 :type '(choice
1731 (const relative)
1732 (const absolute)
1733 (const noabbrev)
1734 (const adaptive)))
1736 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1737 "Types of links that should be activated in Org-mode files.
1738 This is a list of symbols, each leading to the activation of a certain link
1739 type. In principle, it does not hurt to turn on most link types - there may
1740 be a small gain when turning off unused link types. The types are:
1742 bracket The recommended [[link][description]] or [[link]] links with hiding.
1743 angle Links in angular brackets that may contain whitespace like
1744 <bbdb:Carsten Dominik>.
1745 plain Plain links in normal text, no whitespace, like http://google.com.
1746 radio Text that is matched by a radio target, see manual for details.
1747 tag Tag settings in a headline (link to tag search).
1748 date Time stamps (link to calendar).
1749 footnote Footnote labels.
1751 Changing this variable requires a restart of Emacs to become effective."
1752 :group 'org-link
1753 :type '(set :greedy t
1754 (const :tag "Double bracket links" bracket)
1755 (const :tag "Angular bracket links" angle)
1756 (const :tag "Plain text links" plain)
1757 (const :tag "Radio target matches" radio)
1758 (const :tag "Tags" tag)
1759 (const :tag "Timestamps" date)
1760 (const :tag "Footnotes" footnote)))
1762 (defcustom org-make-link-description-function nil
1763 "Function to use for generating link descriptions from links.
1764 When nil, the link location will be used. This function must take
1765 two parameters: the first one is the link, the second one is the
1766 description generated by `org-insert-link'. The function should
1767 return the description to use."
1768 :group 'org-link
1769 :type '(choice (const nil) (function)))
1771 (defgroup org-link-store nil
1772 "Options concerning storing links in Org-mode."
1773 :tag "Org Store Link"
1774 :group 'org-link)
1776 (defcustom org-url-hexify-p t
1777 "When non-nil, hexify URL when creating a link."
1778 :type 'boolean
1779 :version "24.3"
1780 :group 'org-link-store)
1782 (defcustom org-email-link-description-format "Email %c: %.30s"
1783 "Format of the description part of a link to an email or usenet message.
1784 The following %-escapes will be replaced by corresponding information:
1786 %F full \"From\" field
1787 %f name, taken from \"From\" field, address if no name
1788 %T full \"To\" field
1789 %t first name in \"To\" field, address if no name
1790 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1791 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1792 %s subject
1793 %d date
1794 %m message-id.
1796 You may use normal field width specification between the % and the letter.
1797 This is for example useful to limit the length of the subject.
1799 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1800 :group 'org-link-store
1801 :type 'string)
1803 (defcustom org-from-is-user-regexp
1804 (let (r1 r2)
1805 (when (and user-mail-address (not (string= user-mail-address "")))
1806 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1807 (when (and user-full-name (not (string= user-full-name "")))
1808 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1809 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1810 "Regexp matched against the \"From:\" header of an email or usenet message.
1811 It should match if the message is from the user him/herself."
1812 :group 'org-link-store
1813 :type 'regexp)
1815 (defcustom org-context-in-file-links t
1816 "Non-nil means file links from `org-store-link' contain context.
1817 A search string will be added to the file name with :: as separator and
1818 used to find the context when the link is activated by the command
1819 `org-open-at-point'. When this option is t, the entire active region
1820 will be placed in the search string of the file link. If set to a
1821 positive integer, only the first n lines of context will be stored.
1823 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1824 negates this setting for the duration of the command."
1825 :group 'org-link-store
1826 :type '(choice boolean integer))
1828 (defcustom org-keep-stored-link-after-insertion nil
1829 "Non-nil means keep link in list for entire session.
1831 The command `org-store-link' adds a link pointing to the current
1832 location to an internal list. These links accumulate during a session.
1833 The command `org-insert-link' can be used to insert links into any
1834 Org-mode file (offering completion for all stored links). When this
1835 option is nil, every link which has been inserted once using \\[org-insert-link]
1836 will be removed from the list, to make completing the unused links
1837 more efficient."
1838 :group 'org-link-store
1839 :type 'boolean)
1841 (defgroup org-link-follow nil
1842 "Options concerning following links in Org-mode."
1843 :tag "Org Follow Link"
1844 :group 'org-link)
1846 (defcustom org-link-translation-function nil
1847 "Function to translate links with different syntax to Org syntax.
1848 This can be used to translate links created for example by the Planner
1849 or emacs-wiki packages to Org syntax.
1850 The function must accept two parameters, a TYPE containing the link
1851 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1852 which is everything after the link protocol. It should return a cons
1853 with possibly modified values of type and path.
1854 Org contains a function for this, so if you set this variable to
1855 `org-translate-link-from-planner', you should be able follow many
1856 links created by planner."
1857 :group 'org-link-follow
1858 :type '(choice (const nil) (function)))
1860 (defcustom org-follow-link-hook nil
1861 "Hook that is run after a link has been followed."
1862 :group 'org-link-follow
1863 :type 'hook)
1865 (defcustom org-tab-follows-link nil
1866 "Non-nil means on links TAB will follow the link.
1867 Needs to be set before org.el is loaded.
1868 This really should not be used, it does not make sense, and the
1869 implementation is bad."
1870 :group 'org-link-follow
1871 :type 'boolean)
1873 (defcustom org-return-follows-link nil
1874 "Non-nil means on links RET will follow the link.
1875 In tables, the special behavior of RET has precedence."
1876 :group 'org-link-follow
1877 :type 'boolean)
1879 (defcustom org-mouse-1-follows-link
1880 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1881 "Non-nil means mouse-1 on a link will follow the link.
1882 A longer mouse click will still set point. Does not work on XEmacs.
1883 Needs to be set before org.el is loaded."
1884 :group 'org-link-follow
1885 :version "24.4"
1886 :package-version '(Org . "8.3")
1887 :type '(choice
1888 (const :tag "A double click follows the link" 'double)
1889 (const :tag "Unconditionally follow the link with mouse-1" t)
1890 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1892 (defcustom org-mark-ring-length 4
1893 "Number of different positions to be recorded in the ring.
1894 Changing this requires a restart of Emacs to work correctly."
1895 :group 'org-link-follow
1896 :type 'integer)
1898 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1899 "Non-nil means internal links in Org files must exactly match a headline.
1900 When nil, the link search tries to match a phrase with all words
1901 in the search text."
1902 :group 'org-link-follow
1903 :version "24.1"
1904 :type '(choice
1905 (const :tag "Use fuzzy text search" nil)
1906 (const :tag "Match only exact headline" t)
1907 (const :tag "Match exact headline or query to create it"
1908 query-to-create)))
1910 (defcustom org-link-frame-setup
1911 '((vm . vm-visit-folder-other-frame)
1912 (vm-imap . vm-visit-imap-folder-other-frame)
1913 (gnus . org-gnus-no-new-news)
1914 (file . find-file-other-window)
1915 (wl . wl-other-frame))
1916 "Setup the frame configuration for following links.
1917 When following a link with Emacs, it may often be useful to display
1918 this link in another window or frame. This variable can be used to
1919 set this up for the different types of links.
1920 For VM, use any of
1921 `vm-visit-folder'
1922 `vm-visit-folder-other-window'
1923 `vm-visit-folder-other-frame'
1924 For Gnus, use any of
1925 `gnus'
1926 `gnus-other-frame'
1927 `org-gnus-no-new-news'
1928 For FILE, use any of
1929 `find-file'
1930 `find-file-other-window'
1931 `find-file-other-frame'
1932 For Wanderlust use any of
1933 `wl'
1934 `wl-other-frame'
1935 For the calendar, use the variable `calendar-setup'.
1936 For BBDB, it is currently only possible to display the matches in
1937 another window."
1938 :group 'org-link-follow
1939 :type '(list
1940 (cons (const vm)
1941 (choice
1942 (const vm-visit-folder)
1943 (const vm-visit-folder-other-window)
1944 (const vm-visit-folder-other-frame)))
1945 (cons (const vm-imap)
1946 (choice
1947 (const vm-visit-imap-folder)
1948 (const vm-visit-imap-folder-other-window)
1949 (const vm-visit-imap-folder-other-frame)))
1950 (cons (const gnus)
1951 (choice
1952 (const gnus)
1953 (const gnus-other-frame)
1954 (const org-gnus-no-new-news)))
1955 (cons (const file)
1956 (choice
1957 (const find-file)
1958 (const find-file-other-window)
1959 (const find-file-other-frame)))
1960 (cons (const wl)
1961 (choice
1962 (const wl)
1963 (const wl-other-frame)))))
1965 (defcustom org-display-internal-link-with-indirect-buffer nil
1966 "Non-nil means use indirect buffer to display infile links.
1967 Activating internal links (from one location in a file to another location
1968 in the same file) normally just jumps to the location. When the link is
1969 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1970 is displayed in
1971 another window. When this option is set, the other window actually displays
1972 an indirect buffer clone of the current buffer, to avoid any visibility
1973 changes to the current buffer."
1974 :group 'org-link-follow
1975 :type 'boolean)
1977 (defcustom org-open-non-existing-files nil
1978 "Non-nil means `org-open-file' will open non-existing files.
1979 When nil, an error will be generated.
1980 This variable applies only to external applications because they
1981 might choke on non-existing files. If the link is to a file that
1982 will be opened in Emacs, the variable is ignored."
1983 :group 'org-link-follow
1984 :type 'boolean)
1986 (defcustom org-open-directory-means-index-dot-org nil
1987 "Non-nil means a link to a directory really means to index.org.
1988 When nil, following a directory link will run dired or open a finder/explorer
1989 window on that directory."
1990 :group 'org-link-follow
1991 :type 'boolean)
1993 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1994 "Function and arguments to call for following mailto links.
1995 This is a list with the first element being a Lisp function, and the
1996 remaining elements being arguments to the function. In string arguments,
1997 %a will be replaced by the address, and %s will be replaced by the subject
1998 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1999 :group 'org-link-follow
2000 :type '(choice
2001 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
2002 (const :tag "compose-mail" (compose-mail "%a" "%s"))
2003 (const :tag "message-mail" (message-mail "%a" "%s"))
2004 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2006 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2007 "Non-nil means ask for confirmation before executing shell links.
2008 Shell links can be dangerous: just think about a link
2010 [[shell:rm -rf ~/*][Google Search]]
2012 This link would show up in your Org-mode document as \"Google Search\",
2013 but really it would remove your entire home directory.
2014 Therefore we advise against setting this variable to nil.
2015 Just change it to `y-or-n-p' if you want to confirm with a
2016 single keystroke rather than having to type \"yes\"."
2017 :group 'org-link-follow
2018 :type '(choice
2019 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2020 (const :tag "with y-or-n (faster)" y-or-n-p)
2021 (const :tag "no confirmation (dangerous)" nil)))
2022 (put 'org-confirm-shell-link-function
2023 'safe-local-variable
2024 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2026 (defcustom org-confirm-shell-link-not-regexp ""
2027 "A regexp to skip confirmation for shell links."
2028 :group 'org-link-follow
2029 :version "24.1"
2030 :type 'regexp)
2032 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2033 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2034 Elisp links can be dangerous: just think about a link
2036 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2038 This link would show up in your Org-mode document as \"Google Search\",
2039 but really it would remove your entire home directory.
2040 Therefore we advise against setting this variable to nil.
2041 Just change it to `y-or-n-p' if you want to confirm with a
2042 single keystroke rather than having to type \"yes\"."
2043 :group 'org-link-follow
2044 :type '(choice
2045 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2046 (const :tag "with y-or-n (faster)" y-or-n-p)
2047 (const :tag "no confirmation (dangerous)" nil)))
2048 (put 'org-confirm-shell-link-function
2049 'safe-local-variable
2050 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2052 (defcustom org-confirm-elisp-link-not-regexp ""
2053 "A regexp to skip confirmation for Elisp links."
2054 :group 'org-link-follow
2055 :version "24.1"
2056 :type 'regexp)
2058 (defconst org-file-apps-defaults-gnu
2059 '((remote . emacs)
2060 (system . mailcap)
2061 (t . mailcap))
2062 "Default file applications on a UNIX or GNU/Linux system.
2063 See `org-file-apps'.")
2065 (defconst org-file-apps-defaults-macosx
2066 '((remote . emacs)
2067 (t . "open %s")
2068 (system . "open %s")
2069 ("ps.gz" . "gv %s")
2070 ("eps.gz" . "gv %s")
2071 ("dvi" . "xdvi %s")
2072 ("fig" . "xfig %s"))
2073 "Default file applications on a MacOS X system.
2074 The system \"open\" is known as a default, but we use X11 applications
2075 for some files for which the OS does not have a good default.
2076 See `org-file-apps'.")
2078 (defconst org-file-apps-defaults-windowsnt
2079 (list
2080 '(remote . emacs)
2081 (cons t
2082 (list (if (featurep 'xemacs)
2083 'mswindows-shell-execute
2084 'w32-shell-execute)
2085 "open" 'file))
2086 (cons 'system
2087 (list (if (featurep 'xemacs)
2088 'mswindows-shell-execute
2089 'w32-shell-execute)
2090 "open" 'file)))
2091 "Default file applications on a Windows NT system.
2092 The system \"open\" is used for most files.
2093 See `org-file-apps'.")
2095 (defcustom org-file-apps
2096 '((auto-mode . emacs)
2097 ("\\.mm\\'" . default)
2098 ("\\.x?html?\\'" . default)
2099 ("\\.pdf\\'" . default))
2100 "External applications for opening `file:path' items in a document.
2101 Org-mode uses system defaults for different file types, but
2102 you can use this variable to set the application for a given file
2103 extension. The entries in this list are cons cells where the car identifies
2104 files and the cdr the corresponding command. Possible values for the
2105 file identifier are
2106 \"string\" A string as a file identifier can be interpreted in different
2107 ways, depending on its contents:
2109 - Alphanumeric characters only:
2110 Match links with this file extension.
2111 Example: (\"pdf\" . \"evince %s\")
2112 to open PDFs with evince.
2114 - Regular expression: Match links where the
2115 filename matches the regexp. If you want to
2116 use groups here, use shy groups.
2118 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2119 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2120 to open *.html and *.xhtml with firefox.
2122 - Regular expression which contains (non-shy) groups:
2123 Match links where the whole link, including \"::\", and
2124 anything after that, matches the regexp.
2125 In a custom command string, %1, %2, etc. are replaced with
2126 the parts of the link that were matched by the groups.
2127 For backwards compatibility, if a command string is given
2128 that does not use any of the group matches, this case is
2129 handled identically to the second one (i.e. match against
2130 file name only).
2131 In a custom lisp form, you can access the group matches with
2132 (match-string n link).
2134 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2135 to open [[file:document.pdf::5]] with evince at page 5.
2137 `directory' Matches a directory
2138 `remote' Matches a remote file, accessible through tramp or efs.
2139 Remote files most likely should be visited through Emacs
2140 because external applications cannot handle such paths.
2141 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2142 so all files Emacs knows how to handle. Using this with
2143 command `emacs' will open most files in Emacs. Beware that this
2144 will also open html files inside Emacs, unless you add
2145 (\"html\" . default) to the list as well.
2146 t Default for files not matched by any of the other options.
2147 `system' The system command to open files, like `open' on Windows
2148 and Mac OS X, and mailcap under GNU/Linux. This is the command
2149 that will be selected if you call `C-c C-o' with a double
2150 \\[universal-argument] \\[universal-argument] prefix.
2152 Possible values for the command are:
2153 `emacs' The file will be visited by the current Emacs process.
2154 `default' Use the default application for this file type, which is the
2155 association for t in the list, most likely in the system-specific
2156 part.
2157 This can be used to overrule an unwanted setting in the
2158 system-specific variable.
2159 `system' Use the system command for opening files, like \"open\".
2160 This command is specified by the entry whose car is `system'.
2161 Most likely, the system-specific version of this variable
2162 does define this command, but you can overrule/replace it
2163 here.
2164 string A command to be executed by a shell; %s will be replaced
2165 by the path to the file.
2166 sexp A Lisp form which will be evaluated. The file path will
2167 be available in the Lisp variable `file'.
2168 For more examples, see the system specific constants
2169 `org-file-apps-defaults-macosx'
2170 `org-file-apps-defaults-windowsnt'
2171 `org-file-apps-defaults-gnu'."
2172 :group 'org-link-follow
2173 :type '(repeat
2174 (cons (choice :value ""
2175 (string :tag "Extension")
2176 (const :tag "System command to open files" system)
2177 (const :tag "Default for unrecognized files" t)
2178 (const :tag "Remote file" remote)
2179 (const :tag "Links to a directory" directory)
2180 (const :tag "Any files that have Emacs modes"
2181 auto-mode))
2182 (choice :value ""
2183 (const :tag "Visit with Emacs" emacs)
2184 (const :tag "Use default" default)
2185 (const :tag "Use the system command" system)
2186 (string :tag "Command")
2187 (sexp :tag "Lisp form")))))
2189 (defcustom org-doi-server-url "http://dx.doi.org/"
2190 "The URL of the DOI server."
2191 :type 'string
2192 :version "24.3"
2193 :group 'org-link-follow)
2195 (defgroup org-refile nil
2196 "Options concerning refiling entries in Org-mode."
2197 :tag "Org Refile"
2198 :group 'org)
2200 (defcustom org-directory "~/org"
2201 "Directory with org files.
2202 This is just a default location to look for Org files. There is no need
2203 at all to put your files into this directory. It is only used in the
2204 following situations:
2206 1. When a capture template specifies a target file that is not an
2207 absolute path. The path will then be interpreted relative to
2208 `org-directory'
2209 2. When a capture note is filed away in an interactive way (when exiting the
2210 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2211 with `org-directory' as the default path."
2212 :group 'org-refile
2213 :group 'org-capture
2214 :type 'directory)
2216 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2217 "Default target for storing notes.
2218 Used as a fall back file for org-capture.el, for templates that
2219 do not specify a target file."
2220 :group 'org-refile
2221 :group 'org-capture
2222 :type '(choice
2223 (const :tag "Default from remember-data-file" nil)
2224 file))
2226 (defcustom org-goto-interface 'outline
2227 "The default interface to be used for `org-goto'.
2228 Allowed values are:
2229 outline The interface shows an outline of the relevant file
2230 and the correct heading is found by moving through
2231 the outline or by searching with incremental search.
2232 outline-path-completion Headlines in the current buffer are offered via
2233 completion. This is the interface also used by
2234 the refile command."
2235 :group 'org-refile
2236 :type '(choice
2237 (const :tag "Outline" outline)
2238 (const :tag "Outline-path-completion" outline-path-completion)))
2240 (defcustom org-goto-max-level 5
2241 "Maximum target level when running `org-goto' with refile interface."
2242 :group 'org-refile
2243 :type 'integer)
2245 (defcustom org-reverse-note-order nil
2246 "Non-nil means store new notes at the beginning of a file or entry.
2247 When nil, new notes will be filed to the end of a file or entry.
2248 This can also be a list with cons cells of regular expressions that
2249 are matched against file names, and values."
2250 :group 'org-capture
2251 :group 'org-refile
2252 :type '(choice
2253 (const :tag "Reverse always" t)
2254 (const :tag "Reverse never" nil)
2255 (repeat :tag "By file name regexp"
2256 (cons regexp boolean))))
2258 (defcustom org-log-refile nil
2259 "Information to record when a task is refiled.
2261 Possible values are:
2263 nil Don't add anything
2264 time Add a time stamp to the task
2265 note Prompt for a note and add it with template `org-log-note-headings'
2267 This option can also be set with on a per-file-basis with
2269 #+STARTUP: nologrefile
2270 #+STARTUP: logrefile
2271 #+STARTUP: lognoterefile
2273 You can have local logging settings for a subtree by setting the LOGGING
2274 property to one or more of these keywords.
2276 When bulk-refiling from the agenda, the value `note' is forbidden and
2277 will temporarily be changed to `time'."
2278 :group 'org-refile
2279 :group 'org-progress
2280 :version "24.1"
2281 :type '(choice
2282 (const :tag "No logging" nil)
2283 (const :tag "Record timestamp" time)
2284 (const :tag "Record timestamp with note." note)))
2286 (defcustom org-refile-targets nil
2287 "Targets for refiling entries with \\[org-refile].
2288 This is a list of cons cells. Each cell contains:
2289 - a specification of the files to be considered, either a list of files,
2290 or a symbol whose function or variable value will be used to retrieve
2291 a file name or a list of file names. If you use `org-agenda-files' for
2292 that, all agenda files will be scanned for targets. Nil means consider
2293 headings in the current buffer.
2294 - A specification of how to find candidate refile targets. This may be
2295 any of:
2296 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2297 This tag has to be present in all target headlines, inheritance will
2298 not be considered.
2299 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2300 todo keyword.
2301 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2302 headlines that are refiling targets.
2303 - a cons cell (:level . N). Any headline of level N is considered a target.
2304 Note that, when `org-odd-levels-only' is set, level corresponds to
2305 order in hierarchy, not to the number of stars.
2306 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2307 Note that, when `org-odd-levels-only' is set, level corresponds to
2308 order in hierarchy, not to the number of stars.
2310 Each element of this list generates a set of possible targets.
2311 The union of these sets is presented (with completion) to
2312 the user by `org-refile'.
2314 You can set the variable `org-refile-target-verify-function' to a function
2315 to verify each headline found by the simple criteria above.
2317 When this variable is nil, all top-level headlines in the current buffer
2318 are used, equivalent to the value `((nil . (:level . 1))'."
2319 :group 'org-refile
2320 :type '(repeat
2321 (cons
2322 (choice :value org-agenda-files
2323 (const :tag "All agenda files" org-agenda-files)
2324 (const :tag "Current buffer" nil)
2325 (function) (variable) (file))
2326 (choice :tag "Identify target headline by"
2327 (cons :tag "Specific tag" (const :value :tag) (string))
2328 (cons :tag "TODO keyword" (const :value :todo) (string))
2329 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2330 (cons :tag "Level number" (const :value :level) (integer))
2331 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2333 (defcustom org-refile-target-verify-function nil
2334 "Function to verify if the headline at point should be a refile target.
2335 The function will be called without arguments, with point at the
2336 beginning of the headline. It should return t and leave point
2337 where it is if the headline is a valid target for refiling.
2339 If the target should not be selected, the function must return nil.
2340 In addition to this, it may move point to a place from where the search
2341 should be continued. For example, the function may decide that the entire
2342 subtree of the current entry should be excluded and move point to the end
2343 of the subtree."
2344 :group 'org-refile
2345 :type '(choice
2346 (const nil)
2347 (function)))
2349 (defcustom org-refile-use-cache nil
2350 "Non-nil means cache refile targets to speed up the process.
2351 The cache for a particular file will be updated automatically when
2352 the buffer has been killed, or when any of the marker used for flagging
2353 refile targets no longer points at a live buffer.
2354 If you have added new entries to a buffer that might themselves be targets,
2355 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2356 find that easier, `C-u C-u C-u C-c C-w'."
2357 :group 'org-refile
2358 :version "24.1"
2359 :type 'boolean)
2361 (defcustom org-refile-use-outline-path nil
2362 "Non-nil means provide refile targets as paths.
2363 So a level 3 headline will be available as level1/level2/level3.
2365 When the value is `file', also include the file name (without directory)
2366 into the path. In this case, you can also stop the completion after
2367 the file name, to get entries inserted as top level in the file.
2369 When `full-file-path', include the full file path."
2370 :group 'org-refile
2371 :type '(choice
2372 (const :tag "Not" nil)
2373 (const :tag "Yes" t)
2374 (const :tag "Start with file name" file)
2375 (const :tag "Start with full file path" full-file-path)))
2377 (defcustom org-outline-path-complete-in-steps t
2378 "Non-nil means complete the outline path in hierarchical steps.
2379 When Org-mode uses the refile interface to select an outline path
2380 \(see variable `org-refile-use-outline-path'), the completion of
2381 the path can be done is a single go, or if can be done in steps down
2382 the headline hierarchy. Going in steps is probably the best if you
2383 do not use a special completion package like `ido' or `icicles'.
2384 However, when using these packages, going in one step can be very
2385 fast, while still showing the whole path to the entry."
2386 :group 'org-refile
2387 :type 'boolean)
2389 (defcustom org-refile-allow-creating-parent-nodes nil
2390 "Non-nil means allow to create new nodes as refile targets.
2391 New nodes are then created by adding \"/new node name\" to the completion
2392 of an existing node. When the value of this variable is `confirm',
2393 new node creation must be confirmed by the user (recommended)
2394 When nil, the completion must match an existing entry.
2396 Note that, if the new heading is not seen by the criteria
2397 listed in `org-refile-targets', multiple instances of the same
2398 heading would be created by trying again to file under the new
2399 heading."
2400 :group 'org-refile
2401 :type '(choice
2402 (const :tag "Never" nil)
2403 (const :tag "Always" t)
2404 (const :tag "Prompt for confirmation" confirm)))
2406 (defcustom org-refile-active-region-within-subtree nil
2407 "Non-nil means also refile active region within a subtree.
2409 By default `org-refile' doesn't allow refiling regions if they
2410 don't contain a set of subtrees, but it might be convenient to
2411 do so sometimes: in that case, the first line of the region is
2412 converted to a headline before refiling."
2413 :group 'org-refile
2414 :version "24.1"
2415 :type 'boolean)
2417 (defgroup org-todo nil
2418 "Options concerning TODO items in Org-mode."
2419 :tag "Org TODO"
2420 :group 'org)
2422 (defgroup org-progress nil
2423 "Options concerning Progress logging in Org-mode."
2424 :tag "Org Progress"
2425 :group 'org-time)
2427 (defvar org-todo-interpretation-widgets
2428 '((:tag "Sequence (cycling hits every state)" sequence)
2429 (:tag "Type (cycling directly to DONE)" type))
2430 "The available interpretation symbols for customizing `org-todo-keywords'.
2431 Interested libraries should add to this list.")
2433 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2434 "List of TODO entry keyword sequences and their interpretation.
2435 \\<org-mode-map>This is a list of sequences.
2437 Each sequence starts with a symbol, either `sequence' or `type',
2438 indicating if the keywords should be interpreted as a sequence of
2439 action steps, or as different types of TODO items. The first
2440 keywords are states requiring action - these states will select a headline
2441 for inclusion into the global TODO list Org-mode produces. If one of
2442 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2443 signify that no further action is necessary. If \"|\" is not found,
2444 the last keyword is treated as the only DONE state of the sequence.
2446 The command \\[org-todo] cycles an entry through these states, and one
2447 additional state where no keyword is present. For details about this
2448 cycling, see the manual.
2450 TODO keywords and interpretation can also be set on a per-file basis with
2451 the special #+SEQ_TODO and #+TYP_TODO lines.
2453 Each keyword can optionally specify a character for fast state selection
2454 \(in combination with the variable `org-use-fast-todo-selection')
2455 and specifiers for state change logging, using the same syntax that
2456 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2457 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2458 indicates to record a time stamp each time this state is selected.
2460 Each keyword may also specify if a timestamp or a note should be
2461 recorded when entering or leaving the state, by adding additional
2462 characters in the parenthesis after the keyword. This looks like this:
2463 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2464 record only the time of the state change. With X and Y being either
2465 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2466 Y when leaving the state if and only if the *target* state does not
2467 define X. You may omit any of the fast-selection key or X or /Y,
2468 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2470 For backward compatibility, this variable may also be just a list
2471 of keywords. In this case the interpretation (sequence or type) will be
2472 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2473 :group 'org-todo
2474 :group 'org-keywords
2475 :type '(choice
2476 (repeat :tag "Old syntax, just keywords"
2477 (string :tag "Keyword"))
2478 (repeat :tag "New syntax"
2479 (cons
2480 (choice
2481 :tag "Interpretation"
2482 ;;Quick and dirty way to see
2483 ;;`org-todo-interpretations'. This takes the
2484 ;;place of item arguments
2485 :convert-widget
2486 (lambda (widget)
2487 (widget-put widget
2488 :args (mapcar
2489 #'(lambda (x)
2490 (widget-convert
2491 (cons 'const x)))
2492 org-todo-interpretation-widgets))
2493 widget))
2494 (repeat
2495 (string :tag "Keyword"))))))
2497 (defvar org-todo-keywords-1 nil
2498 "All TODO and DONE keywords active in a buffer.")
2499 (make-variable-buffer-local 'org-todo-keywords-1)
2500 (defvar org-todo-keywords-for-agenda nil)
2501 (defvar org-done-keywords-for-agenda nil)
2502 (defvar org-todo-keyword-alist-for-agenda nil)
2503 (defvar org-tag-alist-for-agenda nil
2504 "Alist of all tags from all agenda files.")
2505 (defvar org-tag-groups-alist-for-agenda nil
2506 "Alist of all groups tags from all current agenda files.")
2507 (defvar org-tag-groups-alist nil)
2508 (make-variable-buffer-local 'org-tag-groups-alist)
2509 (defvar org-agenda-contributing-files nil)
2510 (defvar org-not-done-keywords nil)
2511 (make-variable-buffer-local 'org-not-done-keywords)
2512 (defvar org-done-keywords nil)
2513 (make-variable-buffer-local 'org-done-keywords)
2514 (defvar org-todo-heads nil)
2515 (make-variable-buffer-local 'org-todo-heads)
2516 (defvar org-todo-sets nil)
2517 (make-variable-buffer-local 'org-todo-sets)
2518 (defvar org-todo-log-states nil)
2519 (make-variable-buffer-local 'org-todo-log-states)
2520 (defvar org-todo-kwd-alist nil)
2521 (make-variable-buffer-local 'org-todo-kwd-alist)
2522 (defvar org-todo-key-alist nil)
2523 (make-variable-buffer-local 'org-todo-key-alist)
2524 (defvar org-todo-key-trigger nil)
2525 (make-variable-buffer-local 'org-todo-key-trigger)
2527 (defcustom org-todo-interpretation 'sequence
2528 "Controls how TODO keywords are interpreted.
2529 This variable is in principle obsolete and is only used for
2530 backward compatibility, if the interpretation of todo keywords is
2531 not given already in `org-todo-keywords'. See that variable for
2532 more information."
2533 :group 'org-todo
2534 :group 'org-keywords
2535 :type '(choice (const sequence)
2536 (const type)))
2538 (defcustom org-use-fast-todo-selection t
2539 "Non-nil means use the fast todo selection scheme with C-c C-t.
2540 This variable describes if and under what circumstances the cycling
2541 mechanism for TODO keywords will be replaced by a single-key, direct
2542 selection scheme.
2544 When nil, fast selection is never used.
2546 When the symbol `prefix', it will be used when `org-todo' is called
2547 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2548 `C-u t' in an agenda buffer.
2550 When t, fast selection is used by default. In this case, the prefix
2551 argument forces cycling instead.
2553 In all cases, the special interface is only used if access keys have
2554 actually been assigned by the user, i.e. if keywords in the configuration
2555 are followed by a letter in parenthesis, like TODO(t)."
2556 :group 'org-todo
2557 :type '(choice
2558 (const :tag "Never" nil)
2559 (const :tag "By default" t)
2560 (const :tag "Only with C-u C-c C-t" prefix)))
2562 (defcustom org-provide-todo-statistics t
2563 "Non-nil means update todo statistics after insert and toggle.
2564 ALL-HEADLINES means update todo statistics by including headlines
2565 with no TODO keyword as well, counting them as not done.
2566 A list of TODO keywords means the same, but skip keywords that are
2567 not in this list.
2569 When this is set, todo statistics is updated in the parent of the
2570 current entry each time a todo state is changed."
2571 :group 'org-todo
2572 :type '(choice
2573 (const :tag "Yes, only for TODO entries" t)
2574 (const :tag "Yes, including all entries" 'all-headlines)
2575 (repeat :tag "Yes, for TODOs in this list"
2576 (string :tag "TODO keyword"))
2577 (other :tag "No TODO statistics" nil)))
2579 (defcustom org-hierarchical-todo-statistics t
2580 "Non-nil means TODO statistics covers just direct children.
2581 When nil, all entries in the subtree are considered.
2582 This has only an effect if `org-provide-todo-statistics' is set.
2583 To set this to nil for only a single subtree, use a COOKIE_DATA
2584 property and include the word \"recursive\" into the value."
2585 :group 'org-todo
2586 :type 'boolean)
2588 (defcustom org-after-todo-state-change-hook nil
2589 "Hook which is run after the state of a TODO item was changed.
2590 The new state (a string with a TODO keyword, or nil) is available in the
2591 Lisp variable `org-state'."
2592 :group 'org-todo
2593 :type 'hook)
2595 (defvar org-blocker-hook nil
2596 "Hook for functions that are allowed to block a state change.
2598 Functions in this hook should not modify the buffer.
2599 Each function gets as its single argument a property list,
2600 see `org-trigger-hook' for more information about this list.
2602 If any of the functions in this hook returns nil, the state change
2603 is blocked.")
2605 (defvar org-trigger-hook nil
2606 "Hook for functions that are triggered by a state change.
2608 Each function gets as its single argument a property list with at
2609 least the following elements:
2611 (:type type-of-change :position pos-at-entry-start
2612 :from old-state :to new-state)
2614 Depending on the type, more properties may be present.
2616 This mechanism is currently implemented for:
2618 TODO state changes
2619 ------------------
2620 :type todo-state-change
2621 :from previous state (keyword as a string), or nil, or a symbol
2622 'todo' or 'done', to indicate the general type of state.
2623 :to new state, like in :from")
2625 (defcustom org-enforce-todo-dependencies nil
2626 "Non-nil means undone TODO entries will block switching the parent to DONE.
2627 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2628 be blocked if any prior sibling is not yet done.
2629 Finally, if the parent is blocked because of ordered siblings of its own,
2630 the child will also be blocked."
2631 :set (lambda (var val)
2632 (set var val)
2633 (if val
2634 (add-hook 'org-blocker-hook
2635 'org-block-todo-from-children-or-siblings-or-parent)
2636 (remove-hook 'org-blocker-hook
2637 'org-block-todo-from-children-or-siblings-or-parent)))
2638 :group 'org-todo
2639 :type 'boolean)
2641 (defcustom org-enforce-todo-checkbox-dependencies nil
2642 "Non-nil means unchecked boxes will block switching the parent to DONE.
2643 When this is nil, checkboxes have no influence on switching TODO states.
2644 When non-nil, you first need to check off all check boxes before the TODO
2645 entry can be switched to DONE.
2646 This variable needs to be set before org.el is loaded, and you need to
2647 restart Emacs after a change to make the change effective. The only way
2648 to change is while Emacs is running is through the customize interface."
2649 :set (lambda (var val)
2650 (set var val)
2651 (if val
2652 (add-hook 'org-blocker-hook
2653 'org-block-todo-from-checkboxes)
2654 (remove-hook 'org-blocker-hook
2655 'org-block-todo-from-checkboxes)))
2656 :group 'org-todo
2657 :type 'boolean)
2659 (defcustom org-treat-insert-todo-heading-as-state-change nil
2660 "Non-nil means inserting a TODO heading is treated as state change.
2661 So when the command \\[org-insert-todo-heading] is used, state change
2662 logging will apply if appropriate. When nil, the new TODO item will
2663 be inserted directly, and no logging will take place."
2664 :group 'org-todo
2665 :type 'boolean)
2667 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2668 "Non-nil means switching TODO states with S-cursor counts as state change.
2669 This is the default behavior. However, setting this to nil allows a
2670 convenient way to select a TODO state and bypass any logging associated
2671 with that."
2672 :group 'org-todo
2673 :type 'boolean)
2675 (defcustom org-todo-state-tags-triggers nil
2676 "Tag changes that should be triggered by TODO state changes.
2677 This is a list. Each entry is
2679 (state-change (tag . flag) .......)
2681 State-change can be a string with a state, and empty string to indicate the
2682 state that has no TODO keyword, or it can be one of the symbols `todo'
2683 or `done', meaning any not-done or done state, respectively."
2684 :group 'org-todo
2685 :group 'org-tags
2686 :type '(repeat
2687 (cons (choice :tag "When changing to"
2688 (const :tag "Not-done state" todo)
2689 (const :tag "Done state" done)
2690 (string :tag "State"))
2691 (repeat
2692 (cons :tag "Tag action"
2693 (string :tag "Tag")
2694 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2696 (defcustom org-log-done nil
2697 "Information to record when a task moves to the DONE state.
2699 Possible values are:
2701 nil Don't add anything, just change the keyword
2702 time Add a time stamp to the task
2703 note Prompt for a note and add it with template `org-log-note-headings'
2705 This option can also be set with on a per-file-basis with
2707 #+STARTUP: nologdone
2708 #+STARTUP: logdone
2709 #+STARTUP: lognotedone
2711 You can have local logging settings for a subtree by setting the LOGGING
2712 property to one or more of these keywords."
2713 :group 'org-todo
2714 :group 'org-progress
2715 :type '(choice
2716 (const :tag "No logging" nil)
2717 (const :tag "Record CLOSED timestamp" time)
2718 (const :tag "Record CLOSED timestamp with note." note)))
2720 ;; Normalize old uses of org-log-done.
2721 (cond
2722 ((eq org-log-done t) (setq org-log-done 'time))
2723 ((and (listp org-log-done) (memq 'done org-log-done))
2724 (setq org-log-done 'note)))
2726 (defcustom org-log-reschedule nil
2727 "Information to record when the scheduling date of a tasks is modified.
2729 Possible values are:
2731 nil Don't add anything, just change the date
2732 time Add a time stamp to the task
2733 note Prompt for a note and add it with template `org-log-note-headings'
2735 This option can also be set with on a per-file-basis with
2737 #+STARTUP: nologreschedule
2738 #+STARTUP: logreschedule
2739 #+STARTUP: lognotereschedule"
2740 :group 'org-todo
2741 :group 'org-progress
2742 :type '(choice
2743 (const :tag "No logging" nil)
2744 (const :tag "Record timestamp" time)
2745 (const :tag "Record timestamp with note." note)))
2747 (defcustom org-log-redeadline nil
2748 "Information to record when the deadline date of a tasks is modified.
2750 Possible values are:
2752 nil Don't add anything, just change the date
2753 time Add a time stamp to the task
2754 note Prompt for a note and add it with template `org-log-note-headings'
2756 This option can also be set with on a per-file-basis with
2758 #+STARTUP: nologredeadline
2759 #+STARTUP: logredeadline
2760 #+STARTUP: lognoteredeadline
2762 You can have local logging settings for a subtree by setting the LOGGING
2763 property to one or more of these keywords."
2764 :group 'org-todo
2765 :group 'org-progress
2766 :type '(choice
2767 (const :tag "No logging" nil)
2768 (const :tag "Record timestamp" time)
2769 (const :tag "Record timestamp with note." note)))
2771 (defcustom org-log-note-clock-out nil
2772 "Non-nil means record a note when clocking out of an item.
2773 This can also be configured on a per-file basis by adding one of
2774 the following lines anywhere in the buffer:
2776 #+STARTUP: lognoteclock-out
2777 #+STARTUP: nolognoteclock-out"
2778 :group 'org-todo
2779 :group 'org-progress
2780 :type 'boolean)
2782 (defcustom org-log-done-with-time t
2783 "Non-nil means the CLOSED time stamp will contain date and time.
2784 When nil, only the date will be recorded."
2785 :group 'org-progress
2786 :type 'boolean)
2788 (defcustom org-log-note-headings
2789 '((done . "CLOSING NOTE %t")
2790 (state . "State %-12s from %-12S %t")
2791 (note . "Note taken on %t")
2792 (reschedule . "Rescheduled from %S on %t")
2793 (delschedule . "Not scheduled, was %S on %t")
2794 (redeadline . "New deadline from %S on %t")
2795 (deldeadline . "Removed deadline, was %S on %t")
2796 (refile . "Refiled on %t")
2797 (clock-out . ""))
2798 "Headings for notes added to entries.
2799 The value is an alist, with the car being a symbol indicating the note
2800 context, and the cdr is the heading to be used. The heading may also be the
2801 empty string.
2802 %t in the heading will be replaced by a time stamp.
2803 %T will be an active time stamp instead the default inactive one
2804 %d will be replaced by a short-format time stamp.
2805 %D will be replaced by an active short-format time stamp.
2806 %s will be replaced by the new TODO state, in double quotes.
2807 %S will be replaced by the old TODO state, in double quotes.
2808 %u will be replaced by the user name.
2809 %U will be replaced by the full user name.
2811 In fact, it is not a good idea to change the `state' entry, because
2812 agenda log mode depends on the format of these entries."
2813 :group 'org-todo
2814 :group 'org-progress
2815 :type '(list :greedy t
2816 (cons (const :tag "Heading when closing an item" done) string)
2817 (cons (const :tag
2818 "Heading when changing todo state (todo sequence only)"
2819 state) string)
2820 (cons (const :tag "Heading when just taking a note" note) string)
2821 (cons (const :tag "Heading when rescheduling" reschedule) string)
2822 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2823 (cons (const :tag "Heading when changing deadline" redeadline) string)
2824 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2825 (cons (const :tag "Heading when refiling" refile) string)
2826 (cons (const :tag "Heading when clocking out" clock-out) string)))
2828 (unless (assq 'note org-log-note-headings)
2829 (push '(note . "%t") org-log-note-headings))
2831 (defcustom org-log-into-drawer nil
2832 "Non-nil means insert state change notes and time stamps into a drawer.
2833 When nil, state changes notes will be inserted after the headline and
2834 any scheduling and clock lines, but not inside a drawer.
2836 The value of this variable should be the name of the drawer to use.
2837 LOGBOOK is proposed as the default drawer for this purpose, you can
2838 also set this to a string to define the drawer of your choice.
2840 A value of t is also allowed, representing \"LOGBOOK\".
2842 A value of t or nil can also be set with on a per-file-basis with
2844 #+STARTUP: logdrawer
2845 #+STARTUP: nologdrawer
2847 If this variable is set, `org-log-state-notes-insert-after-drawers'
2848 will be ignored.
2850 You can set the property LOG_INTO_DRAWER to overrule this setting for
2851 a subtree."
2852 :group 'org-todo
2853 :group 'org-progress
2854 :type '(choice
2855 (const :tag "Not into a drawer" nil)
2856 (const :tag "LOGBOOK" t)
2857 (string :tag "Other")))
2859 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2861 (defun org-log-into-drawer ()
2862 "Return the value of `org-log-into-drawer', but let properties overrule.
2863 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2864 used instead of the default value."
2865 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2866 (cond
2867 ((not p) org-log-into-drawer)
2868 ((equal p "nil") nil)
2869 ((equal p "t") "LOGBOOK")
2870 (t p))))
2872 (defcustom org-log-state-notes-insert-after-drawers nil
2873 "Non-nil means insert state change notes after any drawers in entry.
2874 Only the drawers that *immediately* follow the headline and the
2875 deadline/scheduled line are skipped.
2876 When nil, insert notes right after the heading and perhaps the line
2877 with deadline/scheduling if present.
2879 This variable will have no effect if `org-log-into-drawer' is
2880 set."
2881 :group 'org-todo
2882 :group 'org-progress
2883 :type 'boolean)
2885 (defcustom org-log-states-order-reversed t
2886 "Non-nil means the latest state note will be directly after heading.
2887 When nil, the state change notes will be ordered according to time.
2889 This option can also be set with on a per-file-basis with
2891 #+STARTUP: logstatesreversed
2892 #+STARTUP: nologstatesreversed"
2893 :group 'org-todo
2894 :group 'org-progress
2895 :type 'boolean)
2897 (defcustom org-todo-repeat-to-state nil
2898 "The TODO state to which a repeater should return the repeating task.
2899 By default this is the first task in a TODO sequence, or the previous state
2900 in a TODO_TYP set. But you can specify another task here.
2901 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2902 :group 'org-todo
2903 :version "24.1"
2904 :type '(choice (const :tag "Head of sequence" nil)
2905 (string :tag "Specific state")))
2907 (defcustom org-log-repeat 'time
2908 "Non-nil means record moving through the DONE state when triggering repeat.
2909 An auto-repeating task is immediately switched back to TODO when
2910 marked DONE. If you are not logging state changes (by adding \"@\"
2911 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2912 record a closing note, there will be no record of the task moving
2913 through DONE. This variable forces taking a note anyway.
2915 nil Don't force a record
2916 time Record a time stamp
2917 note Prompt for a note and add it with template `org-log-note-headings'
2919 This option can also be set with on a per-file-basis with
2921 #+STARTUP: nologrepeat
2922 #+STARTUP: logrepeat
2923 #+STARTUP: lognoterepeat
2925 You can have local logging settings for a subtree by setting the LOGGING
2926 property to one or more of these keywords."
2927 :group 'org-todo
2928 :group 'org-progress
2929 :type '(choice
2930 (const :tag "Don't force a record" nil)
2931 (const :tag "Force recording the DONE state" time)
2932 (const :tag "Force recording a note with the DONE state" note)))
2935 (defgroup org-priorities nil
2936 "Priorities in Org-mode."
2937 :tag "Org Priorities"
2938 :group 'org-todo)
2940 (defcustom org-enable-priority-commands t
2941 "Non-nil means priority commands are active.
2942 When nil, these commands will be disabled, so that you never accidentally
2943 set a priority."
2944 :group 'org-priorities
2945 :type 'boolean)
2947 (defcustom org-highest-priority ?A
2948 "The highest priority of TODO items. A character like ?A, ?B etc.
2949 Must have a smaller ASCII number than `org-lowest-priority'."
2950 :group 'org-priorities
2951 :type 'character)
2953 (defcustom org-lowest-priority ?C
2954 "The lowest priority of TODO items. A character like ?A, ?B etc.
2955 Must have a larger ASCII number than `org-highest-priority'."
2956 :group 'org-priorities
2957 :type 'character)
2959 (defcustom org-default-priority ?B
2960 "The default priority of TODO items.
2961 This is the priority an item gets if no explicit priority is given.
2962 When starting to cycle on an empty priority the first step in the cycle
2963 depends on `org-priority-start-cycle-with-default'. The resulting first
2964 step priority must not exceed the range from `org-highest-priority' to
2965 `org-lowest-priority' which means that `org-default-priority' has to be
2966 in this range exclusive or inclusive the range boundaries. Else the
2967 first step refuses to set the default and the second will fall back
2968 to (depending on the command used) the highest or lowest priority."
2969 :group 'org-priorities
2970 :type 'character)
2972 (defcustom org-priority-start-cycle-with-default t
2973 "Non-nil means start with default priority when starting to cycle.
2974 When this is nil, the first step in the cycle will be (depending on the
2975 command used) one higher or lower than the default priority.
2976 See also `org-default-priority'."
2977 :group 'org-priorities
2978 :type 'boolean)
2980 (defcustom org-get-priority-function nil
2981 "Function to extract the priority from a string.
2982 The string is normally the headline. If this is nil Org computes the
2983 priority from the priority cookie like [#A] in the headline. It returns
2984 an integer, increasing by 1000 for each priority level.
2985 The user can set a different function here, which should take a string
2986 as an argument and return the numeric priority."
2987 :group 'org-priorities
2988 :version "24.1"
2989 :type '(choice
2990 (const nil)
2991 (function)))
2993 (defgroup org-time nil
2994 "Options concerning time stamps and deadlines in Org-mode."
2995 :tag "Org Time"
2996 :group 'org)
2998 (defcustom org-insert-labeled-timestamps-at-point nil
2999 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3000 When nil, these labeled time stamps are forces into the second line of an
3001 entry, just after the headline. When scheduling from the global TODO list,
3002 the time stamp will always be forced into the second line."
3003 :group 'org-time
3004 :type 'boolean)
3006 (defcustom org-time-stamp-rounding-minutes '(0 5)
3007 "Number of minutes to round time stamps to.
3008 These are two values, the first applies when first creating a time stamp.
3009 The second applies when changing it with the commands `S-up' and `S-down'.
3010 When changing the time stamp, this means that it will change in steps
3011 of N minutes, as given by the second value.
3013 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3014 numbers should be factors of 60, so for example 5, 10, 15.
3016 When this is larger than 1, you can still force an exact time stamp by using
3017 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3018 and by using a prefix arg to `S-up/down' to specify the exact number
3019 of minutes to shift."
3020 :group 'org-time
3021 :get #'(lambda (var) ; Make sure both elements are there
3022 (if (integerp (default-value var))
3023 (list (default-value var) 5)
3024 (default-value var)))
3025 :type '(list
3026 (integer :tag "when inserting times")
3027 (integer :tag "when modifying times")))
3029 ;; Normalize old customizations of this variable.
3030 (when (integerp org-time-stamp-rounding-minutes)
3031 (setq org-time-stamp-rounding-minutes
3032 (list org-time-stamp-rounding-minutes
3033 org-time-stamp-rounding-minutes)))
3035 (defcustom org-display-custom-times nil
3036 "Non-nil means overlay custom formats over all time stamps.
3037 The formats are defined through the variable `org-time-stamp-custom-formats'.
3038 To turn this on on a per-file basis, insert anywhere in the file:
3039 #+STARTUP: customtime"
3040 :group 'org-time
3041 :set 'set-default
3042 :type 'sexp)
3043 (make-variable-buffer-local 'org-display-custom-times)
3045 (defcustom org-time-stamp-custom-formats
3046 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3047 "Custom formats for time stamps. See `format-time-string' for the syntax.
3048 These are overlaid over the default ISO format if the variable
3049 `org-display-custom-times' is set. Time like %H:%M should be at the
3050 end of the second format. The custom formats are also honored by export
3051 commands, if custom time display is turned on at the time of export."
3052 :group 'org-time
3053 :type 'sexp)
3055 (defun org-time-stamp-format (&optional long inactive)
3056 "Get the right format for a time string."
3057 (let ((f (if long (cdr org-time-stamp-formats)
3058 (car org-time-stamp-formats))))
3059 (if inactive
3060 (concat "[" (substring f 1 -1) "]")
3061 f)))
3063 (defcustom org-time-clocksum-format
3064 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3065 "The format string used when creating CLOCKSUM lines.
3066 This is also used when Org mode generates a time duration.
3068 The value can be a single format string containing two
3069 %-sequences, which will be filled with the number of hours and
3070 minutes in that order.
3072 Alternatively, the value can be a plist associating any of the
3073 keys :years, :months, :weeks, :days, :hours or :minutes with
3074 format strings. The time duration is formatted using only the
3075 time components that are needed and concatenating the results.
3076 If a time unit in absent, it falls back to the next smallest
3077 unit.
3079 The keys :require-years, :require-months, :require-days,
3080 :require-weeks, :require-hours, :require-minutes are also
3081 meaningful. A non-nil value for these keys indicates that the
3082 corresponding time component should always be included, even if
3083 its value is 0.
3086 For example,
3088 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3089 :require-minutes t)
3091 means durations longer than a day will be expressed in days,
3092 hours and minutes, and durations less than a day will always be
3093 expressed in hours and minutes (even for durations less than an
3094 hour).
3096 The value
3098 \(:days \"%dd\" :minutes \"%dm\")
3100 means durations longer than a day will be expressed in days and
3101 minutes, and durations less than a day will be expressed entirely
3102 in minutes (even for durations longer than an hour)."
3103 :group 'org-time
3104 :group 'org-clock
3105 :version "24.4"
3106 :package-version '(Org . "8.0")
3107 :type '(choice (string :tag "Format string")
3108 (set :tag "Plist"
3109 (group :inline t (const :tag "Years" :years)
3110 (string :tag "Format string"))
3111 (group :inline t
3112 (const :tag "Always show years" :require-years)
3113 (const t))
3114 (group :inline t (const :tag "Months" :months)
3115 (string :tag "Format string"))
3116 (group :inline t
3117 (const :tag "Always show months" :require-months)
3118 (const t))
3119 (group :inline t (const :tag "Weeks" :weeks)
3120 (string :tag "Format string"))
3121 (group :inline t
3122 (const :tag "Always show weeks" :require-weeks)
3123 (const t))
3124 (group :inline t (const :tag "Days" :days)
3125 (string :tag "Format string"))
3126 (group :inline t
3127 (const :tag "Always show days" :require-days)
3128 (const t))
3129 (group :inline t (const :tag "Hours" :hours)
3130 (string :tag "Format string"))
3131 (group :inline t
3132 (const :tag "Always show hours" :require-hours)
3133 (const t))
3134 (group :inline t (const :tag "Minutes" :minutes)
3135 (string :tag "Format string"))
3136 (group :inline t
3137 (const :tag "Always show minutes" :require-minutes)
3138 (const t)))))
3140 (defcustom org-time-clocksum-use-fractional nil
3141 "When non-nil, \\[org-clock-display] uses fractional times.
3142 See `org-time-clocksum-format' for more on time clock formats."
3143 :group 'org-time
3144 :group 'org-clock
3145 :version "24.3"
3146 :type 'boolean)
3148 (defcustom org-time-clocksum-use-effort-durations nil
3149 "When non-nil, \\[org-clock-display] uses effort durations.
3150 E.g. by default, one day is considered to be a 8 hours effort,
3151 so a task that has been clocked for 16 hours will be displayed
3152 as during 2 days in the clock display or in the clocktable.
3154 See `org-effort-durations' on how to set effort durations
3155 and `org-time-clocksum-format' for more on time clock formats."
3156 :group 'org-time
3157 :group 'org-clock
3158 :version "24.4"
3159 :package-version '(Org . "8.0")
3160 :type 'boolean)
3162 (defcustom org-time-clocksum-fractional-format "%.2f"
3163 "The format string used when creating CLOCKSUM lines,
3164 or when Org mode generates a time duration, if
3165 `org-time-clocksum-use-fractional' is enabled.
3167 The value can be a single format string containing one
3168 %-sequence, which will be filled with the number of hours as
3169 a float.
3171 Alternatively, the value can be a plist associating any of the
3172 keys :years, :months, :weeks, :days, :hours or :minutes with
3173 a format string. The time duration is formatted using the
3174 largest time unit which gives a non-zero integer part. If all
3175 specified formats have zero integer part, the smallest time unit
3176 is used."
3177 :group 'org-time
3178 :type '(choice (string :tag "Format string")
3179 (set (group :inline t (const :tag "Years" :years)
3180 (string :tag "Format string"))
3181 (group :inline t (const :tag "Months" :months)
3182 (string :tag "Format string"))
3183 (group :inline t (const :tag "Weeks" :weeks)
3184 (string :tag "Format string"))
3185 (group :inline t (const :tag "Days" :days)
3186 (string :tag "Format string"))
3187 (group :inline t (const :tag "Hours" :hours)
3188 (string :tag "Format string"))
3189 (group :inline t (const :tag "Minutes" :minutes)
3190 (string :tag "Format string")))))
3192 (defcustom org-deadline-warning-days 14
3193 "Number of days before expiration during which a deadline becomes active.
3194 This variable governs the display in sparse trees and in the agenda.
3195 When 0 or negative, it means use this number (the absolute value of it)
3196 even if a deadline has a different individual lead time specified.
3198 Custom commands can set this variable in the options section."
3199 :group 'org-time
3200 :group 'org-agenda-daily/weekly
3201 :type 'integer)
3203 (defcustom org-scheduled-delay-days 0
3204 "Number of days before a scheduled item becomes active.
3205 This variable governs the display in sparse trees and in the agenda.
3206 The default value (i.e. 0) means: don't delay scheduled item.
3207 When negative, it means use this number (the absolute value of it)
3208 even if a scheduled item has a different individual delay time
3209 specified.
3211 Custom commands can set this variable in the options section."
3212 :group 'org-time
3213 :group 'org-agenda-daily/weekly
3214 :version "24.4"
3215 :package-version '(Org . "8.0")
3216 :type 'integer)
3218 (defcustom org-read-date-prefer-future t
3219 "Non-nil means assume future for incomplete date input from user.
3220 This affects the following situations:
3221 1. The user gives a month but not a year.
3222 For example, if it is April and you enter \"feb 2\", this will be read
3223 as Feb 2, *next* year. \"May 5\", however, will be this year.
3224 2. The user gives a day, but no month.
3225 For example, if today is the 15th, and you enter \"3\", Org-mode will
3226 read this as the third of *next* month. However, if you enter \"17\",
3227 it will be considered as *this* month.
3229 If you set this variable to the symbol `time', then also the following
3230 will work:
3232 3. If the user gives a time.
3233 If the time is before now, it will be interpreted as tomorrow.
3235 Currently none of this works for ISO week specifications.
3237 When this option is nil, the current day, month and year will always be
3238 used as defaults.
3240 See also `org-agenda-jump-prefer-future'."
3241 :group 'org-time
3242 :type '(choice
3243 (const :tag "Never" nil)
3244 (const :tag "Check month and day" t)
3245 (const :tag "Check month, day, and time" time)))
3247 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3248 "Should the agenda jump command prefer the future for incomplete dates?
3249 The default is to do the same as configured in `org-read-date-prefer-future'.
3250 But you can also set a deviating value here.
3251 This may t or nil, or the symbol `org-read-date-prefer-future'."
3252 :group 'org-agenda
3253 :group 'org-time
3254 :version "24.1"
3255 :type '(choice
3256 (const :tag "Use org-read-date-prefer-future"
3257 org-read-date-prefer-future)
3258 (const :tag "Never" nil)
3259 (const :tag "Always" t)))
3261 (defcustom org-read-date-force-compatible-dates t
3262 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3264 Depending on the system Emacs is running on, certain dates cannot
3265 be represented with the type used internally to represent time.
3266 Dates between 1970-1-1 and 2038-1-1 can always be represented
3267 correctly. Some systems allow for earlier dates, some for later,
3268 some for both. One way to find out it to insert any date into an
3269 Org buffer, putting the cursor on the year and hitting S-up and
3270 S-down to test the range.
3272 When this variable is set to t, the date/time prompt will not let
3273 you specify dates outside the 1970-2037 range, so it is certain that
3274 these dates will work in whatever version of Emacs you are
3275 running, and also that you can move a file from one Emacs implementation
3276 to another. WHenever Org is forcing the year for you, it will display
3277 a message and beep.
3279 When this variable is nil, Org will check if the date is
3280 representable in the specific Emacs implementation you are using.
3281 If not, it will force a year, usually the current year, and beep
3282 to remind you. Currently this setting is not recommended because
3283 the likelihood that you will open your Org files in an Emacs that
3284 has limited date range is not negligible.
3286 A workaround for this problem is to use diary sexp dates for time
3287 stamps outside of this range."
3288 :group 'org-time
3289 :version "24.1"
3290 :type 'boolean)
3292 (defcustom org-read-date-display-live t
3293 "Non-nil means display current interpretation of date prompt live.
3294 This display will be in an overlay, in the minibuffer."
3295 :group 'org-time
3296 :type 'boolean)
3298 (defcustom org-read-date-popup-calendar t
3299 "Non-nil means pop up a calendar when prompting for a date.
3300 In the calendar, the date can be selected with mouse-1. However, the
3301 minibuffer will also be active, and you can simply enter the date as well.
3302 When nil, only the minibuffer will be available."
3303 :group 'org-time
3304 :type 'boolean)
3305 (org-defvaralias 'org-popup-calendar-for-date-prompt
3306 'org-read-date-popup-calendar)
3308 (make-obsolete-variable
3309 'org-read-date-minibuffer-setup-hook
3310 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3311 (defcustom org-read-date-minibuffer-setup-hook nil
3312 "Hook to be used to set up keys for the date/time interface.
3313 Add key definitions to `minibuffer-local-map', which will be a
3314 temporary copy.
3316 WARNING: This option is obsolete, you should use
3317 `org-read-date-minibuffer-local-map' to set up keys."
3318 :group 'org-time
3319 :type 'hook)
3321 (defcustom org-extend-today-until 0
3322 "The hour when your day really ends. Must be an integer.
3323 This has influence for the following applications:
3324 - When switching the agenda to \"today\". It it is still earlier than
3325 the time given here, the day recognized as TODAY is actually yesterday.
3326 - When a date is read from the user and it is still before the time given
3327 here, the current date and time will be assumed to be yesterday, 23:59.
3328 Also, timestamps inserted in capture templates follow this rule.
3330 IMPORTANT: This is a feature whose implementation is and likely will
3331 remain incomplete. Really, it is only here because past midnight seems to
3332 be the favorite working time of John Wiegley :-)"
3333 :group 'org-time
3334 :type 'integer)
3336 (defcustom org-use-effective-time nil
3337 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3338 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3339 \"effective time\" of any timestamps between midnight and 8am will be
3340 23:59 of the previous day."
3341 :group 'org-time
3342 :version "24.1"
3343 :type 'boolean)
3345 (defcustom org-use-last-clock-out-time-as-effective-time nil
3346 "When non-nil, use the last clock out time for `org-todo'.
3347 Note that this option has precedence over the combined use of
3348 `org-use-effective-time' and `org-extend-today-until'."
3349 :group 'org-time
3350 :version "24.4"
3351 :package-version '(Org . "8.0")
3352 :type 'boolean)
3354 (defcustom org-edit-timestamp-down-means-later nil
3355 "Non-nil means S-down will increase the time in a time stamp.
3356 When nil, S-up will increase."
3357 :group 'org-time
3358 :type 'boolean)
3360 (defcustom org-calendar-follow-timestamp-change t
3361 "Non-nil means make the calendar window follow timestamp changes.
3362 When a timestamp is modified and the calendar window is visible, it will be
3363 moved to the new date."
3364 :group 'org-time
3365 :type 'boolean)
3367 (defgroup org-tags nil
3368 "Options concerning tags in Org-mode."
3369 :tag "Org Tags"
3370 :group 'org)
3372 (defcustom org-tag-alist nil
3373 "List of tags allowed in Org-mode files.
3374 When this list is nil, Org-mode will base TAG input on what is already in the
3375 buffer.
3376 The value of this variable is an alist, the car of each entry must be a
3377 keyword as a string, the cdr may be a character that is used to select
3378 that tag through the fast-tag-selection interface.
3379 See the manual for details."
3380 :group 'org-tags
3381 :type '(repeat
3382 (choice
3383 (cons (string :tag "Tag name")
3384 (character :tag "Access char"))
3385 (list :tag "Start radio group"
3386 (const :startgroup)
3387 (option (string :tag "Group description")))
3388 (list :tag "Group tags delimiter"
3389 (const :grouptags))
3390 (list :tag "End radio group"
3391 (const :endgroup)
3392 (option (string :tag "Group description")))
3393 (const :tag "New line" (:newline)))))
3395 (defcustom org-tag-persistent-alist nil
3396 "List of tags that will always appear in all Org-mode files.
3397 This is in addition to any in buffer settings or customizations
3398 of `org-tag-alist'.
3399 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3400 The value of this variable is an alist, the car of each entry must be a
3401 keyword as a string, the cdr may be a character that is used to select
3402 that tag through the fast-tag-selection interface.
3403 See the manual for details.
3404 To disable these tags on a per-file basis, insert anywhere in the file:
3405 #+STARTUP: noptag"
3406 :group 'org-tags
3407 :type '(repeat
3408 (choice
3409 (cons (string :tag "Tag name")
3410 (character :tag "Access char"))
3411 (const :tag "Start radio group" (:startgroup))
3412 (const :tag "Group tags delimiter" (:grouptags))
3413 (const :tag "End radio group" (:endgroup))
3414 (const :tag "New line" (:newline)))))
3416 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3417 "If non-nil, always offer completion for all tags of all agenda files.
3418 Instead of customizing this variable directly, you might want to
3419 set it locally for capture buffers, because there no list of
3420 tags in that file can be created dynamically (there are none).
3422 (add-hook 'org-capture-mode-hook
3423 (lambda ()
3424 (set (make-local-variable
3425 'org-complete-tags-always-offer-all-agenda-tags)
3426 t)))"
3427 :group 'org-tags
3428 :version "24.1"
3429 :type 'boolean)
3431 (defvar org-file-tags nil
3432 "List of tags that can be inherited by all entries in the file.
3433 The tags will be inherited if the variable `org-use-tag-inheritance'
3434 says they should be.
3435 This variable is populated from #+FILETAGS lines.")
3437 (defcustom org-use-fast-tag-selection 'auto
3438 "Non-nil means use fast tag selection scheme.
3439 This is a special interface to select and deselect tags with single keys.
3440 When nil, fast selection is never used.
3441 When the symbol `auto', fast selection is used if and only if selection
3442 characters for tags have been configured, either through the variable
3443 `org-tag-alist' or through a #+TAGS line in the buffer.
3444 When t, fast selection is always used and selection keys are assigned
3445 automatically if necessary."
3446 :group 'org-tags
3447 :type '(choice
3448 (const :tag "Always" t)
3449 (const :tag "Never" nil)
3450 (const :tag "When selection characters are configured" auto)))
3452 (defcustom org-fast-tag-selection-single-key nil
3453 "Non-nil means fast tag selection exits after first change.
3454 When nil, you have to press RET to exit it.
3455 During fast tag selection, you can toggle this flag with `C-c'.
3456 This variable can also have the value `expert'. In this case, the window
3457 displaying the tags menu is not even shown, until you press C-c again."
3458 :group 'org-tags
3459 :type '(choice
3460 (const :tag "No" nil)
3461 (const :tag "Yes" t)
3462 (const :tag "Expert" expert)))
3464 (defvar org-fast-tag-selection-include-todo nil
3465 "Non-nil means fast tags selection interface will also offer TODO states.
3466 This is an undocumented feature, you should not rely on it.")
3468 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3469 "The column to which tags should be indented in a headline.
3470 If this number is positive, it specifies the column. If it is negative,
3471 it means that the tags should be flushright to that column. For example,
3472 -80 works well for a normal 80 character screen.
3473 When 0, place tags directly after headline text, with only one space in
3474 between."
3475 :group 'org-tags
3476 :type 'integer)
3478 (defcustom org-auto-align-tags t
3479 "Non-nil keeps tags aligned when modifying headlines.
3480 Some operations (i.e. demoting) change the length of a headline and
3481 therefore shift the tags around. With this option turned on, after
3482 each such operation the tags are again aligned to `org-tags-column'."
3483 :group 'org-tags
3484 :type 'boolean)
3486 (defcustom org-use-tag-inheritance t
3487 "Non-nil means tags in levels apply also for sublevels.
3488 When nil, only the tags directly given in a specific line apply there.
3489 This may also be a list of tags that should be inherited, or a regexp that
3490 matches tags that should be inherited. Additional control is possible
3491 with the variable `org-tags-exclude-from-inheritance' which gives an
3492 explicit list of tags to be excluded from inheritance, even if the value of
3493 `org-use-tag-inheritance' would select it for inheritance.
3495 If this option is t, a match early-on in a tree can lead to a large
3496 number of matches in the subtree when constructing the agenda or creating
3497 a sparse tree. If you only want to see the first match in a tree during
3498 a search, check out the variable `org-tags-match-list-sublevels'."
3499 :group 'org-tags
3500 :type '(choice
3501 (const :tag "Not" nil)
3502 (const :tag "Always" t)
3503 (repeat :tag "Specific tags" (string :tag "Tag"))
3504 (regexp :tag "Tags matched by regexp")))
3506 (defcustom org-tags-exclude-from-inheritance nil
3507 "List of tags that should never be inherited.
3508 This is a way to exclude a few tags from inheritance. For way to do
3509 the opposite, to actively allow inheritance for selected tags,
3510 see the variable `org-use-tag-inheritance'."
3511 :group 'org-tags
3512 :type '(repeat (string :tag "Tag")))
3514 (defun org-tag-inherit-p (tag)
3515 "Check if TAG is one that should be inherited."
3516 (cond
3517 ((member tag org-tags-exclude-from-inheritance) nil)
3518 ((eq org-use-tag-inheritance t) t)
3519 ((not org-use-tag-inheritance) nil)
3520 ((stringp org-use-tag-inheritance)
3521 (string-match org-use-tag-inheritance tag))
3522 ((listp org-use-tag-inheritance)
3523 (member tag org-use-tag-inheritance))
3524 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3526 (defcustom org-tags-match-list-sublevels t
3527 "Non-nil means list also sublevels of headlines matching a search.
3528 This variable applies to tags/property searches, and also to stuck
3529 projects because this search is based on a tags match as well.
3531 When set to the symbol `indented', sublevels are indented with
3532 leading dots.
3534 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3535 the sublevels of a headline matching a tag search often also match
3536 the same search. Listing all of them can create very long lists.
3537 Setting this variable to nil causes subtrees of a match to be skipped.
3539 This variable is semi-obsolete and probably should always be true. It
3540 is better to limit inheritance to certain tags using the variables
3541 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3542 :group 'org-tags
3543 :type '(choice
3544 (const :tag "No, don't list them" nil)
3545 (const :tag "Yes, do list them" t)
3546 (const :tag "List them, indented with leading dots" indented)))
3548 (defcustom org-tags-sort-function nil
3549 "When set, tags are sorted using this function as a comparator."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "No sorting" nil)
3553 (const :tag "Alphabetical" string<)
3554 (const :tag "Reverse alphabetical" string>)
3555 (function :tag "Custom function" nil)))
3557 (defvar org-tags-history nil
3558 "History of minibuffer reads for tags.")
3559 (defvar org-last-tags-completion-table nil
3560 "The last used completion table for tags.")
3561 (defvar org-after-tags-change-hook nil
3562 "Hook that is run after the tags in a line have changed.")
3564 (defgroup org-properties nil
3565 "Options concerning properties in Org-mode."
3566 :tag "Org Properties"
3567 :group 'org)
3569 (defcustom org-property-format "%-10s %s"
3570 "How property key/value pairs should be formatted by `indent-line'.
3571 When `indent-line' hits a property definition, it will format the line
3572 according to this format, mainly to make sure that the values are
3573 lined-up with respect to each other."
3574 :group 'org-properties
3575 :type 'string)
3577 (defcustom org-properties-postprocess-alist nil
3578 "Alist of properties and functions to adjust inserted values.
3579 Elements of this alist must be of the form
3581 ([string] [function])
3583 where [string] must be a property name and [function] must be a
3584 lambda expression: this lambda expression must take one argument,
3585 the value to adjust, and return the new value as a string.
3587 For example, this element will allow the property \"Remaining\"
3588 to be updated wrt the relation between the \"Effort\" property
3589 and the clock summary:
3591 ((\"Remaining\" (lambda(value)
3592 (let ((clocksum (org-clock-sum-current-item))
3593 (effort (org-duration-string-to-minutes
3594 (org-entry-get (point) \"Effort\"))))
3595 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3596 :group 'org-properties
3597 :version "24.1"
3598 :type '(alist :key-type (string :tag "Property")
3599 :value-type (function :tag "Function")))
3601 (defcustom org-use-property-inheritance nil
3602 "Non-nil means properties apply also for sublevels.
3604 This setting is chiefly used during property searches. Turning it on can
3605 cause significant overhead when doing a search, which is why it is not
3606 on by default.
3608 When nil, only the properties directly given in the current entry count.
3609 When t, every property is inherited. The value may also be a list of
3610 properties that should have inheritance, or a regular expression matching
3611 properties that should be inherited.
3613 However, note that some special properties use inheritance under special
3614 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3615 and the properties ending in \"_ALL\" when they are used as descriptor
3616 for valid values of a property.
3618 Note for programmers:
3619 When querying an entry with `org-entry-get', you can control if inheritance
3620 should be used. By default, `org-entry-get' looks only at the local
3621 properties. You can request inheritance by setting the inherit argument
3622 to t (to force inheritance) or to `selective' (to respect the setting
3623 in this variable)."
3624 :group 'org-properties
3625 :type '(choice
3626 (const :tag "Not" nil)
3627 (const :tag "Always" t)
3628 (repeat :tag "Specific properties" (string :tag "Property"))
3629 (regexp :tag "Properties matched by regexp")))
3631 (defun org-property-inherit-p (property)
3632 "Check if PROPERTY is one that should be inherited."
3633 (cond
3634 ((eq org-use-property-inheritance t) t)
3635 ((not org-use-property-inheritance) nil)
3636 ((stringp org-use-property-inheritance)
3637 (string-match org-use-property-inheritance property))
3638 ((listp org-use-property-inheritance)
3639 (member property org-use-property-inheritance))
3640 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3642 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3643 "The default column format, if no other format has been defined.
3644 This variable can be set on the per-file basis by inserting a line
3646 #+COLUMNS: %25ITEM ....."
3647 :group 'org-properties
3648 :type 'string)
3650 (defcustom org-columns-ellipses ".."
3651 "The ellipses to be used when a field in column view is truncated.
3652 When this is the empty string, as many characters as possible are shown,
3653 but then there will be no visual indication that the field has been truncated.
3654 When this is a string of length N, the last N characters of a truncated
3655 field are replaced by this string. If the column is narrower than the
3656 ellipses string, only part of the ellipses string will be shown."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-columns-modify-value-for-display-function nil
3661 "Function that modifies values for display in column view.
3662 For example, it can be used to cut out a certain part from a time stamp.
3663 The function must take 2 arguments:
3665 column-title The title of the column (*not* the property name)
3666 value The value that should be modified.
3668 The function should return the value that should be displayed,
3669 or nil if the normal value should be used."
3670 :group 'org-properties
3671 :type '(choice (const nil) (function)))
3673 (defconst org-global-properties-fixed
3674 '(("VISIBILITY_ALL" . "folded children content all")
3675 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3676 "List of property/value pairs that can be inherited by any entry.
3678 These are fixed values, for the preset properties. The user variable
3679 that can be used to add to this list is `org-global-properties'.
3681 The entries in this list are cons cells where the car is a property
3682 name and cdr is a string with the value. If the value represents
3683 multiple items like an \"_ALL\" property, separate the items by
3684 spaces.")
3686 (defcustom org-global-properties nil
3687 "List of property/value pairs that can be inherited by any entry.
3689 This list will be combined with the constant `org-global-properties-fixed'.
3691 The entries in this list are cons cells where the car is a property
3692 name and cdr is a string with the value.
3694 You can set buffer-local values for the same purpose in the variable
3695 `org-file-properties' this by adding lines like
3697 #+PROPERTY: NAME VALUE"
3698 :group 'org-properties
3699 :type '(repeat
3700 (cons (string :tag "Property")
3701 (string :tag "Value"))))
3703 (defvar org-file-properties nil
3704 "List of property/value pairs that can be inherited by any entry.
3705 Valid for the current buffer.
3706 This variable is populated from #+PROPERTY lines.")
3707 (make-variable-buffer-local 'org-file-properties)
3709 (defgroup org-agenda nil
3710 "Options concerning agenda views in Org-mode."
3711 :tag "Org Agenda"
3712 :group 'org)
3714 (defvar org-category nil
3715 "Variable used by org files to set a category for agenda display.
3716 Such files should use a file variable to set it, for example
3718 # -*- mode: org; org-category: \"ELisp\"
3720 or contain a special line
3722 #+CATEGORY: ELisp
3724 If the file does not specify a category, then file's base name
3725 is used instead.")
3726 (make-variable-buffer-local 'org-category)
3727 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3729 (defcustom org-agenda-files nil
3730 "The files to be used for agenda display.
3731 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3732 \\[org-remove-file]. You can also use customize to edit the list.
3734 If an entry is a directory, all files in that directory that are matched by
3735 `org-agenda-file-regexp' will be part of the file list.
3737 If the value of the variable is not a list but a single file name, then
3738 the list of agenda files is actually stored and maintained in that file, one
3739 agenda file per line. In this file paths can be given relative to
3740 `org-directory'. Tilde expansion and environment variable substitution
3741 are also made."
3742 :group 'org-agenda
3743 :type '(choice
3744 (repeat :tag "List of files and directories" file)
3745 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3747 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3748 "Regular expression to match files for `org-agenda-files'.
3749 If any element in the list in that variable contains a directory instead
3750 of a normal file, all files in that directory that are matched by this
3751 regular expression will be included."
3752 :group 'org-agenda
3753 :type 'regexp)
3755 (defcustom org-agenda-text-search-extra-files nil
3756 "List of extra files to be searched by text search commands.
3757 These files will be searched in addition to the agenda files by the
3758 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3759 Note that these files will only be searched for text search commands,
3760 not for the other agenda views like todo lists, tag searches or the weekly
3761 agenda. This variable is intended to list notes and possibly archive files
3762 that should also be searched by these two commands.
3763 In fact, if the first element in the list is the symbol `agenda-archives',
3764 then all archive files of all agenda files will be added to the search
3765 scope."
3766 :group 'org-agenda
3767 :type '(set :greedy t
3768 (const :tag "Agenda Archives" agenda-archives)
3769 (repeat :inline t (file))))
3771 (org-defvaralias 'org-agenda-multi-occur-extra-files
3772 'org-agenda-text-search-extra-files)
3774 (defcustom org-agenda-skip-unavailable-files nil
3775 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3776 A nil value means to remove them, after a query, from the list."
3777 :group 'org-agenda
3778 :type 'boolean)
3780 (defcustom org-calendar-to-agenda-key [?c]
3781 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3782 The command `org-calendar-goto-agenda' will be bound to this key. The
3783 default is the character `c' because then `c' can be used to switch back and
3784 forth between agenda and calendar."
3785 :group 'org-agenda
3786 :type 'sexp)
3788 (defcustom org-calendar-insert-diary-entry-key [?i]
3789 "The key to be installed in `calendar-mode-map' for adding diary entries.
3790 This option is irrelevant until `org-agenda-diary-file' has been configured
3791 to point to an Org-mode file. When that is the case, the command
3792 `org-agenda-diary-entry' will be bound to the key given here, by default
3793 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3794 if you want to continue doing this, you need to change this to a different
3795 key."
3796 :group 'org-agenda
3797 :type 'sexp)
3799 (defcustom org-agenda-diary-file 'diary-file
3800 "File to which to add new entries with the `i' key in agenda and calendar.
3801 When this is the symbol `diary-file', the functionality in the Emacs
3802 calendar will be used to add entries to the `diary-file'. But when this
3803 points to a file, `org-agenda-diary-entry' will be used instead."
3804 :group 'org-agenda
3805 :type '(choice
3806 (const :tag "The standard Emacs diary file" diary-file)
3807 (file :tag "Special Org file diary entries")))
3809 (eval-after-load "calendar"
3810 '(progn
3811 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3812 'org-calendar-goto-agenda)
3813 (add-hook 'calendar-mode-hook
3814 (lambda ()
3815 (unless (eq org-agenda-diary-file 'diary-file)
3816 (define-key calendar-mode-map
3817 org-calendar-insert-diary-entry-key
3818 'org-agenda-diary-entry))))))
3820 (defgroup org-latex nil
3821 "Options for embedding LaTeX code into Org-mode."
3822 :tag "Org LaTeX"
3823 :group 'org)
3825 (defcustom org-format-latex-options
3826 '(:foreground default :background default :scale 1.0
3827 :html-foreground "Black" :html-background "Transparent"
3828 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3829 "Options for creating images from LaTeX fragments.
3830 This is a property list with the following properties:
3831 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3832 `default' means use the foreground of the default face.
3833 `auto' means use the foreground from the text face.
3834 :background the background color, or \"Transparent\".
3835 `default' means use the background of the default face.
3836 `auto' means use the background from the text face.
3837 :scale a scaling factor for the size of the images, to get more pixels
3838 :html-foreground, :html-background, :html-scale
3839 the same numbers for HTML export.
3840 :matchers a list indicating which matchers should be used to
3841 find LaTeX fragments. Valid members of this list are:
3842 \"begin\" find environments
3843 \"$1\" find single characters surrounded by $.$
3844 \"$\" find math expressions surrounded by $...$
3845 \"$$\" find math expressions surrounded by $$....$$
3846 \"\\(\" find math expressions surrounded by \\(...\\)
3847 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3848 :group 'org-latex
3849 :type 'plist)
3851 (defcustom org-format-latex-signal-error t
3852 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3853 When nil, just push out a message."
3854 :group 'org-latex
3855 :version "24.1"
3856 :type 'boolean)
3858 (defcustom org-latex-to-mathml-jar-file nil
3859 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3860 Use this to specify additional executable file say a jar file.
3862 When using MathToWeb as the converter, specify the full-path to
3863 your mathtoweb.jar file."
3864 :group 'org-latex
3865 :version "24.1"
3866 :type '(choice
3867 (const :tag "None" nil)
3868 (file :tag "JAR file" :must-match t)))
3870 (defcustom org-latex-to-mathml-convert-command nil
3871 "Command to convert LaTeX fragments to MathML.
3872 Replace format-specifiers in the command as noted below and use
3873 `shell-command' to convert LaTeX to MathML.
3874 %j: Executable file in fully expanded form as specified by
3875 `org-latex-to-mathml-jar-file'.
3876 %I: Input LaTeX file in fully expanded form
3877 %o: Output MathML file
3878 This command is used by `org-create-math-formula'.
3880 When using MathToWeb as the converter, set this to
3881 \"java -jar %j -unicode -force -df %o %I\"."
3882 :group 'org-latex
3883 :version "24.1"
3884 :type '(choice
3885 (const :tag "None" nil)
3886 (string :tag "\nShell command")))
3888 (defcustom org-latex-create-formula-image-program 'dvipng
3889 "Program to convert LaTeX fragments with.
3891 dvipng Process the LaTeX fragments to dvi file, then convert
3892 dvi files to png files using dvipng.
3893 This will also include processing of non-math environments.
3894 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3895 to convert pdf files to png files"
3896 :group 'org-latex
3897 :version "24.1"
3898 :type '(choice
3899 (const :tag "dvipng" dvipng)
3900 (const :tag "imagemagick" imagemagick)))
3902 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3903 "Path to store latex preview images.
3904 A relative path here creates many directories relative to the
3905 processed org files paths. An absolute path puts all preview
3906 images at the same place."
3907 :group 'org-latex
3908 :version "24.3"
3909 :type 'string)
3911 (defun org-format-latex-mathml-available-p ()
3912 "Return t if `org-latex-to-mathml-convert-command' is usable."
3913 (save-match-data
3914 (when (and (boundp 'org-latex-to-mathml-convert-command)
3915 org-latex-to-mathml-convert-command)
3916 (let ((executable (car (split-string
3917 org-latex-to-mathml-convert-command))))
3918 (when (executable-find executable)
3919 (if (string-match
3920 "%j" org-latex-to-mathml-convert-command)
3921 (file-readable-p org-latex-to-mathml-jar-file)
3922 t))))))
3924 (defcustom org-format-latex-header "\\documentclass{article}
3925 \\usepackage[usenames]{color}
3926 \[PACKAGES]
3927 \[DEFAULT-PACKAGES]
3928 \\pagestyle{empty} % do not remove
3929 % The settings below are copied from fullpage.sty
3930 \\setlength{\\textwidth}{\\paperwidth}
3931 \\addtolength{\\textwidth}{-3cm}
3932 \\setlength{\\oddsidemargin}{1.5cm}
3933 \\addtolength{\\oddsidemargin}{-2.54cm}
3934 \\setlength{\\evensidemargin}{\\oddsidemargin}
3935 \\setlength{\\textheight}{\\paperheight}
3936 \\addtolength{\\textheight}{-\\headheight}
3937 \\addtolength{\\textheight}{-\\headsep}
3938 \\addtolength{\\textheight}{-\\footskip}
3939 \\addtolength{\\textheight}{-3cm}
3940 \\setlength{\\topmargin}{1.5cm}
3941 \\addtolength{\\topmargin}{-2.54cm}"
3942 "The document header used for processing LaTeX fragments.
3943 It is imperative that this header make sure that no page number
3944 appears on the page. The package defined in the variables
3945 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3946 will either replace the placeholder \"[PACKAGES]\" in this
3947 header, or they will be appended."
3948 :group 'org-latex
3949 :type 'string)
3951 (defun org-set-packages-alist (var val)
3952 "Set the packages alist and make sure it has 3 elements per entry."
3953 (set var (mapcar (lambda (x)
3954 (if (and (consp x) (= (length x) 2))
3955 (list (car x) (nth 1 x) t)
3957 val)))
3959 (defun org-get-packages-alist (var)
3960 "Get the packages alist and make sure it has 3 elements per entry."
3961 (mapcar (lambda (x)
3962 (if (and (consp x) (= (length x) 2))
3963 (list (car x) (nth 1 x) t)
3965 (default-value var)))
3967 (defcustom org-latex-default-packages-alist
3968 '(("AUTO" "inputenc" t)
3969 ("T1" "fontenc" t)
3970 ("" "fixltx2e" nil)
3971 ("" "graphicx" t)
3972 ("" "longtable" nil)
3973 ("" "float" nil)
3974 ("" "wrapfig" nil)
3975 ("" "rotating" nil)
3976 ("normalem" "ulem" t)
3977 ("" "amsmath" t)
3978 ("" "textcomp" t)
3979 ("" "marvosym" t)
3980 ("" "wasysym" t)
3981 ("" "amssymb" t)
3982 ("" "hyperref" nil)
3983 "\\tolerance=1000")
3984 "Alist of default packages to be inserted in the header.
3986 Change this only if one of the packages here causes an
3987 incompatibility with another package you are using.
3989 The packages in this list are needed by one part or another of
3990 Org mode to function properly:
3992 - inputenc, fontenc: for basic font and character selection
3993 - fixltx2e: Important patches of LaTeX itself
3994 - graphicx: for including images
3995 - longtable: For multipage tables
3996 - float, wrapfig: for figure placement
3997 - rotating: for sideways figures and tables
3998 - ulem: for underline and strike-through
3999 - amsmath: for subscript and superscript and math environments
4000 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4001 for interpreting the entities in `org-entities'. You can skip
4002 some of these packages if you don't use any of their symbols.
4003 - hyperref: for cross references
4005 Therefore you should not modify this variable unless you know
4006 what you are doing. The one reason to change it anyway is that
4007 you might be loading some other package that conflicts with one
4008 of the default packages. Each cell is of the format
4009 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4010 the package also needs to be included when compiling LaTeX
4011 snippets into images for inclusion into non-LaTeX output."
4012 :group 'org-latex
4013 :group 'org-export-latex
4014 :set 'org-set-packages-alist
4015 :get 'org-get-packages-alist
4016 :version "24.1"
4017 :type '(repeat
4018 (choice
4019 (list :tag "options/package pair"
4020 (string :tag "options")
4021 (string :tag "package")
4022 (boolean :tag "Snippet"))
4023 (string :tag "A line of LaTeX"))))
4025 (defcustom org-latex-packages-alist nil
4026 "Alist of packages to be inserted in every LaTeX header.
4028 These will be inserted after `org-latex-default-packages-alist'.
4029 Each cell is of the format:
4031 \(\"options\" \"package\" snippet-flag)
4033 SNIPPET-FLAG, when t, indicates that this package is also needed
4034 when turning LaTeX snippets into images for inclusion into
4035 non-LaTeX output.
4037 Make sure that you only list packages here which:
4039 - you want in every file
4040 - do not conflict with the setup in `org-format-latex-header'.
4041 - do not conflict with the default packages in
4042 `org-latex-default-packages-alist'."
4043 :group 'org-latex
4044 :group 'org-export-latex
4045 :set 'org-set-packages-alist
4046 :get 'org-get-packages-alist
4047 :type '(repeat
4048 (choice
4049 (list :tag "options/package pair"
4050 (string :tag "options")
4051 (string :tag "package")
4052 (boolean :tag "Snippet"))
4053 (string :tag "A line of LaTeX"))))
4055 (defgroup org-appearance nil
4056 "Settings for Org-mode appearance."
4057 :tag "Org Appearance"
4058 :group 'org)
4060 (defcustom org-level-color-stars-only nil
4061 "Non-nil means fontify only the stars in each headline.
4062 When nil, the entire headline is fontified.
4063 Changing it requires restart of `font-lock-mode' to become effective
4064 also in regions already fontified."
4065 :group 'org-appearance
4066 :type 'boolean)
4068 (defcustom org-hide-leading-stars nil
4069 "Non-nil means hide the first N-1 stars in a headline.
4070 This works by using the face `org-hide' for these stars. This
4071 face is white for a light background, and black for a dark
4072 background. You may have to customize the face `org-hide' to
4073 make this work.
4074 Changing it requires restart of `font-lock-mode' to become effective
4075 also in regions already fontified.
4076 You may also set this on a per-file basis by adding one of the following
4077 lines to the buffer:
4079 #+STARTUP: hidestars
4080 #+STARTUP: showstars"
4081 :group 'org-appearance
4082 :type 'boolean)
4084 (defcustom org-hidden-keywords nil
4085 "List of symbols corresponding to keywords to be hidden the org buffer.
4086 For example, a value '(title) for this list will make the document's title
4087 appear in the buffer without the initial #+TITLE: keyword."
4088 :group 'org-appearance
4089 :version "24.1"
4090 :type '(set (const :tag "#+AUTHOR" author)
4091 (const :tag "#+DATE" date)
4092 (const :tag "#+EMAIL" email)
4093 (const :tag "#+TITLE" title)))
4095 (defcustom org-custom-properties nil
4096 "List of properties (as strings) with a special meaning.
4097 The default use of these custom properties is to let the user
4098 hide them with `org-toggle-custom-properties-visibility'."
4099 :group 'org-properties
4100 :group 'org-appearance
4101 :version "24.3"
4102 :type '(repeat (string :tag "Property Name")))
4104 (defcustom org-fontify-done-headline nil
4105 "Non-nil means change the face of a headline if it is marked DONE.
4106 Normally, only the TODO/DONE keyword indicates the state of a headline.
4107 When this is non-nil, the headline after the keyword is set to the
4108 `org-headline-done' as an additional indication."
4109 :group 'org-appearance
4110 :type 'boolean)
4112 (defcustom org-fontify-emphasized-text t
4113 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4114 Changing this variable requires a restart of Emacs to take effect."
4115 :group 'org-appearance
4116 :type 'boolean)
4118 (defcustom org-fontify-whole-heading-line nil
4119 "Non-nil means fontify the whole line for headings.
4120 This is useful when setting a background color for the
4121 org-level-* faces."
4122 :group 'org-appearance
4123 :type 'boolean)
4125 (defcustom org-highlight-latex-and-related nil
4126 "Non-nil means highlight LaTeX related syntax in the buffer.
4127 When non nil, the value should be a list containing any of the
4128 following symbols:
4129 `latex' Highlight LaTeX snippets and environments.
4130 `script' Highlight subscript and superscript.
4131 `entities' Highlight entities."
4132 :group 'org-appearance
4133 :version "24.4"
4134 :package-version '(Org . "8.0")
4135 :type '(choice
4136 (const :tag "No highlighting" nil)
4137 (set :greedy t :tag "Highlight"
4138 (const :tag "LaTeX snippets and environments" latex)
4139 (const :tag "Subscript and superscript" script)
4140 (const :tag "Entities" entities))))
4142 (defcustom org-hide-emphasis-markers nil
4143 "Non-nil mean font-lock should hide the emphasis marker characters."
4144 :group 'org-appearance
4145 :type 'boolean)
4147 (defcustom org-pretty-entities nil
4148 "Non-nil means show entities as UTF8 characters.
4149 When nil, the \\name form remains in the buffer."
4150 :group 'org-appearance
4151 :version "24.1"
4152 :type 'boolean)
4154 (defcustom org-pretty-entities-include-sub-superscripts t
4155 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4156 :group 'org-appearance
4157 :version "24.1"
4158 :type 'boolean)
4160 (defvar org-emph-re nil
4161 "Regular expression for matching emphasis.
4162 After a match, the match groups contain these elements:
4163 0 The match of the full regular expression, including the characters
4164 before and after the proper match
4165 1 The character before the proper match, or empty at beginning of line
4166 2 The proper match, including the leading and trailing markers
4167 3 The leading marker like * or /, indicating the type of highlighting
4168 4 The text between the emphasis markers, not including the markers
4169 5 The character after the match, empty at the end of a line")
4170 (defvar org-verbatim-re nil
4171 "Regular expression for matching verbatim text.")
4172 (defvar org-emphasis-regexp-components) ; defined just below
4173 (defvar org-emphasis-alist) ; defined just below
4174 (defun org-set-emph-re (var val)
4175 "Set variable and compute the emphasis regular expression."
4176 (set var val)
4177 (when (and (boundp 'org-emphasis-alist)
4178 (boundp 'org-emphasis-regexp-components)
4179 org-emphasis-alist org-emphasis-regexp-components)
4180 (let* ((e org-emphasis-regexp-components)
4181 (pre (car e))
4182 (post (nth 1 e))
4183 (border (nth 2 e))
4184 (body (nth 3 e))
4185 (nl (nth 4 e))
4186 (body1 (concat body "*?"))
4187 (markers (mapconcat 'car org-emphasis-alist ""))
4188 (vmarkers (mapconcat
4189 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4190 org-emphasis-alist "")))
4191 ;; make sure special characters appear at the right position in the class
4192 (if (string-match "\\^" markers)
4193 (setq markers (concat (replace-match "" t t markers) "^")))
4194 (if (string-match "-" markers)
4195 (setq markers (concat (replace-match "" t t markers) "-")))
4196 (if (string-match "\\^" vmarkers)
4197 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4198 (if (string-match "-" vmarkers)
4199 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4200 (if (> nl 0)
4201 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4202 (int-to-string nl) "\\}")))
4203 ;; Make the regexp
4204 (setq org-emph-re
4205 (concat "\\([" pre "]\\|^\\)"
4206 "\\("
4207 "\\([" markers "]\\)"
4208 "\\("
4209 "[^" border "]\\|"
4210 "[^" border "]"
4211 body1
4212 "[^" border "]"
4213 "\\)"
4214 "\\3\\)"
4215 "\\([" post "]\\|$\\)"))
4216 (setq org-verbatim-re
4217 (concat "\\([" pre "]\\|^\\)"
4218 "\\("
4219 "\\([" vmarkers "]\\)"
4220 "\\("
4221 "[^" border "]\\|"
4222 "[^" border "]"
4223 body1
4224 "[^" border "]"
4225 "\\)"
4226 "\\3\\)"
4227 "\\([" post "]\\|$\\)")))))
4229 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4230 ;; set this option proved cumbersome. See this message/thread:
4231 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4232 (defvar org-emphasis-regexp-components
4233 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4234 "Components used to build the regular expression for emphasis.
4235 This is a list with five entries. Terminology: In an emphasis string
4236 like \" *strong word* \", we call the initial space PREMATCH, the final
4237 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4238 and \"trong wor\" is the body. The different components in this variable
4239 specify what is allowed/forbidden in each part:
4241 pre Chars allowed as prematch. Beginning of line will be allowed too.
4242 post Chars allowed as postmatch. End of line will be allowed too.
4243 border The chars *forbidden* as border characters.
4244 body-regexp A regexp like \".\" to match a body character. Don't use
4245 non-shy groups here, and don't allow newline here.
4246 newline The maximum number of newlines allowed in an emphasis exp.
4248 You need to reload Org or to restart Emacs after customizing this.")
4250 (defcustom org-emphasis-alist
4251 `(("*" bold)
4252 ("/" italic)
4253 ("_" underline)
4254 ("=" org-code verbatim)
4255 ("~" org-verbatim verbatim)
4256 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4257 "Alist of characters and faces to emphasize text.
4258 Text starting and ending with a special character will be emphasized,
4259 for example *bold*, _underlined_ and /italic/. This variable sets the
4260 marker characters and the face to be used by font-lock for highlighting
4261 in Org-mode Emacs buffers.
4263 You need to reload Org or to restart Emacs after customizing this."
4264 :group 'org-appearance
4265 :set 'org-set-emph-re
4266 :version "24.4"
4267 :package-version '(Org . "8.0")
4268 :type '(repeat
4269 (list
4270 (string :tag "Marker character")
4271 (choice
4272 (face :tag "Font-lock-face")
4273 (plist :tag "Face property list"))
4274 (option (const verbatim)))))
4276 (defvar org-protecting-blocks
4277 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4278 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4279 This is needed for font-lock setup.")
4281 ;;; Miscellaneous options
4283 (defgroup org-completion nil
4284 "Completion in Org-mode."
4285 :tag "Org Completion"
4286 :group 'org)
4288 (defcustom org-completion-use-ido nil
4289 "Non-nil means use ido completion wherever possible.
4290 Note that `ido-mode' must be active for this variable to be relevant.
4291 If you decide to turn this variable on, you might well want to turn off
4292 `org-outline-path-complete-in-steps'.
4293 See also `org-completion-use-iswitchb'."
4294 :group 'org-completion
4295 :type 'boolean)
4297 (defcustom org-completion-use-iswitchb nil
4298 "Non-nil means use iswitchb completion wherever possible.
4299 Note that `iswitchb-mode' must be active for this variable to be relevant.
4300 If you decide to turn this variable on, you might well want to turn off
4301 `org-outline-path-complete-in-steps'.
4302 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4303 :group 'org-completion
4304 :type 'boolean)
4306 (defcustom org-completion-fallback-command 'hippie-expand
4307 "The expansion command called by \\[pcomplete] in normal context.
4308 Normal means, no org-mode-specific context."
4309 :group 'org-completion
4310 :type 'function)
4312 ;;; Functions and variables from their packages
4313 ;; Declared here to avoid compiler warnings
4315 ;; XEmacs only
4316 (defvar outline-mode-menu-heading)
4317 (defvar outline-mode-menu-show)
4318 (defvar outline-mode-menu-hide)
4319 (defvar zmacs-regions) ; XEmacs regions
4321 ;; Emacs only
4322 (defvar mark-active)
4324 ;; Various packages
4325 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4326 (declare-function calendar-forward-day "cal-move" (arg))
4327 (declare-function calendar-goto-date "cal-move" (date))
4328 (declare-function calendar-goto-today "cal-move" ())
4329 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4330 (defvar calc-embedded-close-formula)
4331 (defvar calc-embedded-open-formula)
4332 (declare-function cdlatex-tab "ext:cdlatex" ())
4333 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4334 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4335 (defvar font-lock-unfontify-region-function)
4336 (declare-function iswitchb-read-buffer "iswitchb"
4337 (prompt &optional default require-match start matches-set))
4338 (defvar iswitchb-temp-buflist)
4339 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4340 (defvar org-agenda-tags-todo-honor-ignore-options)
4341 (declare-function org-agenda-skip "org-agenda" ())
4342 (declare-function
4343 org-agenda-format-item "org-agenda"
4344 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4345 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4346 (declare-function org-agenda-change-all-lines "org-agenda"
4347 (newhead hdmarker &optional fixface just-this))
4348 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4349 (declare-function org-agenda-maybe-redo "org-agenda" ())
4350 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4351 (beg end))
4352 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4353 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4354 "org-agenda" (&optional end))
4355 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4356 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4357 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4358 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4359 (declare-function org-indent-mode "org-indent" (&optional arg))
4360 (declare-function parse-time-string "parse-time" (string))
4361 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4362 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4363 (defvar remember-data-file)
4364 (defvar texmathp-why)
4365 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4366 (declare-function table--at-cell-p "table" (position &optional object at-column))
4368 ;;;###autoload
4369 (defun turn-on-orgtbl ()
4370 "Unconditionally turn on `orgtbl-mode'."
4371 (require 'org-table)
4372 (orgtbl-mode 1))
4374 (defun org-at-table-p (&optional table-type)
4375 "Return t if the cursor is inside an org-type table.
4376 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4377 (if org-enable-table-editor
4378 (save-excursion
4379 (beginning-of-line 1)
4380 (looking-at (if table-type org-table-any-line-regexp
4381 org-table-line-regexp)))
4382 nil))
4383 (defsubst org-table-p () (org-at-table-p))
4385 (defun org-at-table.el-p ()
4386 "Return t if and only if we are at a table.el table."
4387 (and (org-at-table-p 'any)
4388 (save-excursion
4389 (goto-char (org-table-begin 'any))
4390 (looking-at org-table1-hline-regexp))))
4392 (defun org-table-recognize-table.el ()
4393 "If there is a table.el table nearby, recognize it and move into it."
4394 (if org-table-tab-recognizes-table.el
4395 (if (org-at-table.el-p)
4396 (progn
4397 (beginning-of-line 1)
4398 (if (looking-at org-table-dataline-regexp)
4400 (if (looking-at org-table1-hline-regexp)
4401 (progn
4402 (beginning-of-line 2)
4403 (if (looking-at org-table-any-border-regexp)
4404 (beginning-of-line -1)))))
4405 (if (re-search-forward "|" (org-table-end t) t)
4406 (progn
4407 (require 'table)
4408 (if (table--at-cell-p (point))
4410 (message "recognizing table.el table...")
4411 (table-recognize-table)
4412 (message "recognizing table.el table...done")))
4413 (error "This should not happen"))
4415 nil)
4416 nil))
4418 (defun org-at-table-hline-p ()
4419 "Return t if the cursor is inside a hline in a table."
4420 (if org-enable-table-editor
4421 (save-excursion
4422 (beginning-of-line 1)
4423 (looking-at org-table-hline-regexp))
4424 nil))
4426 (defun org-table-map-tables (function &optional quietly)
4427 "Apply FUNCTION to the start of all tables in the buffer."
4428 (save-excursion
4429 (save-restriction
4430 (widen)
4431 (goto-char (point-min))
4432 (while (re-search-forward org-table-any-line-regexp nil t)
4433 (unless quietly
4434 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4435 (beginning-of-line 1)
4436 (when (and (looking-at org-table-line-regexp)
4437 ;; Exclude tables in src/example/verbatim/clocktable blocks
4438 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4439 (save-excursion (funcall function))
4440 (or (looking-at org-table-line-regexp)
4441 (forward-char 1)))
4442 (re-search-forward org-table-any-border-regexp nil 1))))
4443 (unless quietly (message "Mapping tables: done")))
4445 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4446 (declare-function org-clock-update-mode-line "org-clock" ())
4447 (declare-function org-resolve-clocks "org-clock"
4448 (&optional also-non-dangling-p prompt last-valid))
4450 (defun org-at-TBLFM-p (&optional pos)
4451 "Return t when point (or POS) is in #+TBLFM line."
4452 (save-excursion
4453 (let ((pos pos)))
4454 (goto-char (or pos (point)))
4455 (beginning-of-line 1)
4456 (looking-at org-TBLFM-regexp)))
4458 (defvar org-clock-start-time)
4459 (defvar org-clock-marker (make-marker)
4460 "Marker recording the last clock-in.")
4461 (defvar org-clock-hd-marker (make-marker)
4462 "Marker recording the last clock-in, but the headline position.")
4463 (defvar org-clock-heading ""
4464 "The heading of the current clock entry.")
4465 (defun org-clock-is-active ()
4466 "Return the buffer where the clock is currently running.
4467 Return nil if no clock is running."
4468 (marker-buffer org-clock-marker))
4470 (defun org-check-running-clock ()
4471 "Check if the current buffer contains the running clock.
4472 If yes, offer to stop it and to save the buffer with the changes."
4473 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4474 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4475 (buffer-name))))
4476 (org-clock-out)
4477 (when (y-or-n-p "Save changed buffer?")
4478 (save-buffer))))
4480 (defun org-clocktable-try-shift (dir n)
4481 "Check if this line starts a clock table, if yes, shift the time block."
4482 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4483 (org-clocktable-shift dir n)))
4485 ;;;###autoload
4486 (defun org-clock-persistence-insinuate ()
4487 "Set up hooks for clock persistence."
4488 (require 'org-clock)
4489 (add-hook 'org-mode-hook 'org-clock-load)
4490 (add-hook 'kill-emacs-hook 'org-clock-save))
4492 ;; Define the variable already here, to make sure we have it.
4493 (defvar org-indent-mode nil
4494 "Non-nil if Org-Indent mode is enabled.
4495 Use the command `org-indent-mode' to change this variable.")
4497 ;; Autoload archiving code
4498 ;; The stuff that is needed for cycling and tags has to be defined here.
4500 (defgroup org-archive nil
4501 "Options concerning archiving in Org-mode."
4502 :tag "Org Archive"
4503 :group 'org-structure)
4505 (defcustom org-archive-location "%s_archive::"
4506 "The location where subtrees should be archived.
4508 The value of this variable is a string, consisting of two parts,
4509 separated by a double-colon. The first part is a filename and
4510 the second part is a headline.
4512 When the filename is omitted, archiving happens in the same file.
4513 %s in the filename will be replaced by the current file
4514 name (without the directory part). Archiving to a different file
4515 is useful to keep archived entries from contributing to the
4516 Org-mode Agenda.
4518 The archived entries will be filed as subtrees of the specified
4519 headline. When the headline is omitted, the subtrees are simply
4520 filed away at the end of the file, as top-level entries. Also in
4521 the heading you can use %s to represent the file name, this can be
4522 useful when using the same archive for a number of different files.
4524 Here are a few examples:
4525 \"%s_archive::\"
4526 If the current file is Projects.org, archive in file
4527 Projects.org_archive, as top-level trees. This is the default.
4529 \"::* Archived Tasks\"
4530 Archive in the current file, under the top-level headline
4531 \"* Archived Tasks\".
4533 \"~/org/archive.org::\"
4534 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4536 \"~/org/archive.org::* From %s\"
4537 Archive in file ~/org/archive.org (absolute path), under headlines
4538 \"From FILENAME\" where file name is the current file name.
4540 \"~/org/datetree.org::datetree/* Finished Tasks\"
4541 The \"datetree/\" string is special, signifying to archive
4542 items to the datetree. Items are placed in either the CLOSED
4543 date of the item, or the current date if there is no CLOSED date.
4544 The heading will be a subentry to the current date. There doesn't
4545 need to be a heading, but there always needs to be a slash after
4546 datetree. For example, to store archived items directly in the
4547 datetree, use \"~/org/datetree.org::datetree/\".
4549 \"basement::** Finished Tasks\"
4550 Archive in file ./basement (relative path), as level 3 trees
4551 below the level 2 heading \"** Finished Tasks\".
4553 You may set this option on a per-file basis by adding to the buffer a
4554 line like
4556 #+ARCHIVE: basement::** Finished Tasks
4558 You may also define it locally for a subtree by setting an ARCHIVE property
4559 in the entry. If such a property is found in an entry, or anywhere up
4560 the hierarchy, it will be used."
4561 :group 'org-archive
4562 :type 'string)
4564 (defcustom org-agenda-skip-archived-trees t
4565 "Non-nil means the agenda will skip any items located in archived trees.
4566 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4567 variable is no longer recommended, you should leave it at the value t.
4568 Instead, use the key `v' to cycle the archives-mode in the agenda."
4569 :group 'org-archive
4570 :group 'org-agenda-skip
4571 :type 'boolean)
4573 (defcustom org-columns-skip-archived-trees t
4574 "Non-nil means ignore archived trees when creating column view."
4575 :group 'org-archive
4576 :group 'org-properties
4577 :type 'boolean)
4579 (defcustom org-cycle-open-archived-trees nil
4580 "Non-nil means `org-cycle' will open archived trees.
4581 An archived tree is a tree marked with the tag ARCHIVE.
4582 When nil, archived trees will stay folded. You can still open them with
4583 normal outline commands like `show-all', but not with the cycling commands."
4584 :group 'org-archive
4585 :group 'org-cycle
4586 :type 'boolean)
4588 (defcustom org-sparse-tree-open-archived-trees nil
4589 "Non-nil means sparse tree construction shows matches in archived trees.
4590 When nil, matches in these trees are highlighted, but the trees are kept in
4591 collapsed state."
4592 :group 'org-archive
4593 :group 'org-sparse-trees
4594 :type 'boolean)
4596 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4597 "The default date type when building a sparse tree.
4598 When this is nil, a date is a scheduled or a deadline timestamp.
4599 Otherwise, these types are allowed:
4601 all: all timestamps
4602 active: only active timestamps (<...>)
4603 inactive: only inactive timestamps (<...)
4604 scheduled: only scheduled timestamps
4605 deadline: only deadline timestamps"
4606 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4607 (const :tag "All timestamps" all)
4608 (const :tag "Only active timestamps" active)
4609 (const :tag "Only inactive timestamps" inactive)
4610 (const :tag "Only scheduled timestamps" scheduled)
4611 (const :tag "Only deadline timestamps" deadline)
4612 (const :tag "Only closed timestamps" closed))
4613 :version "24.3"
4614 :group 'org-sparse-trees)
4616 (defun org-cycle-hide-archived-subtrees (state)
4617 "Re-hide all archived subtrees after a visibility state change."
4618 (when (and (not org-cycle-open-archived-trees)
4619 (not (memq state '(overview folded))))
4620 (save-excursion
4621 (let* ((globalp (memq state '(contents all)))
4622 (beg (if globalp (point-min) (point)))
4623 (end (if globalp (point-max) (org-end-of-subtree t))))
4624 (org-hide-archived-subtrees beg end)
4625 (goto-char beg)
4626 (if (looking-at (concat ".*:" org-archive-tag ":"))
4627 (message "%s" (substitute-command-keys
4628 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4630 (defun org-force-cycle-archived ()
4631 "Cycle subtree even if it is archived."
4632 (interactive)
4633 (setq this-command 'org-cycle)
4634 (let ((org-cycle-open-archived-trees t))
4635 (call-interactively 'org-cycle)))
4637 (defun org-hide-archived-subtrees (beg end)
4638 "Re-hide all archived subtrees after a visibility state change."
4639 (save-excursion
4640 (let* ((re (concat ":" org-archive-tag ":")))
4641 (goto-char beg)
4642 (while (re-search-forward re end t)
4643 (when (org-at-heading-p)
4644 (org-flag-subtree t)
4645 (org-end-of-subtree t))))))
4647 (declare-function outline-end-of-heading "outline" ())
4648 (declare-function outline-flag-region "outline" (from to flag))
4649 (defun org-flag-subtree (flag)
4650 (save-excursion
4651 (org-back-to-heading t)
4652 (outline-end-of-heading)
4653 (outline-flag-region (point)
4654 (progn (org-end-of-subtree t) (point))
4655 flag)))
4657 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4659 ;; Declare Column View Code
4661 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4662 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4663 (declare-function org-columns-compute "org-colview" (property))
4665 ;; Declare ID code
4667 (declare-function org-id-store-link "org-id")
4668 (declare-function org-id-locations-load "org-id")
4669 (declare-function org-id-locations-save "org-id")
4670 (defvar org-id-track-globally)
4672 ;;; Variables for pre-computed regular expressions, all buffer local
4674 (defvar org-todo-regexp nil
4675 "Matches any of the TODO state keywords.")
4676 (make-variable-buffer-local 'org-todo-regexp)
4677 (defvar org-not-done-regexp nil
4678 "Matches any of the TODO state keywords except the last one.")
4679 (make-variable-buffer-local 'org-not-done-regexp)
4680 (defvar org-not-done-heading-regexp nil
4681 "Matches a TODO headline that is not done.")
4682 (make-variable-buffer-local 'org-not-done-regexp)
4683 (defvar org-todo-line-regexp nil
4684 "Matches a headline and puts TODO state into group 2 if present.")
4685 (make-variable-buffer-local 'org-todo-line-regexp)
4686 (defvar org-complex-heading-regexp nil
4687 "Matches a headline and puts everything into groups:
4688 group 1: the stars
4689 group 2: The todo keyword, maybe
4690 group 3: Priority cookie
4691 group 4: True headline
4692 group 5: Tags")
4693 (make-variable-buffer-local 'org-complex-heading-regexp)
4694 (defvar org-complex-heading-regexp-format nil
4695 "Printf format to make regexp to match an exact headline.
4696 This regexp will match the headline of any node which has the
4697 exact headline text that is put into the format, but may have any
4698 TODO state, priority and tags.")
4699 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4700 (defvar org-todo-line-tags-regexp nil
4701 "Matches a headline and puts TODO state into group 2 if present.
4702 Also put tags into group 4 if tags are present.")
4703 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4704 (defvar org-ds-keyword-length 12
4705 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4706 (make-variable-buffer-local 'org-ds-keyword-length)
4707 (defvar org-deadline-regexp nil
4708 "Matches the DEADLINE keyword.")
4709 (make-variable-buffer-local 'org-deadline-regexp)
4710 (defvar org-deadline-time-regexp nil
4711 "Matches the DEADLINE keyword together with a time stamp.")
4712 (make-variable-buffer-local 'org-deadline-time-regexp)
4713 (defvar org-deadline-time-hour-regexp nil
4714 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4715 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4716 (defvar org-deadline-line-regexp nil
4717 "Matches the DEADLINE keyword and the rest of the line.")
4718 (make-variable-buffer-local 'org-deadline-line-regexp)
4719 (defvar org-scheduled-regexp nil
4720 "Matches the SCHEDULED keyword.")
4721 (make-variable-buffer-local 'org-scheduled-regexp)
4722 (defvar org-scheduled-time-regexp nil
4723 "Matches the SCHEDULED keyword together with a time stamp.")
4724 (make-variable-buffer-local 'org-scheduled-time-regexp)
4725 (defvar org-scheduled-time-hour-regexp nil
4726 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4727 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4728 (defvar org-closed-time-regexp nil
4729 "Matches the CLOSED keyword together with a time stamp.")
4730 (make-variable-buffer-local 'org-closed-time-regexp)
4732 (defvar org-keyword-time-regexp nil
4733 "Matches any of the 4 keywords, together with the time stamp.")
4734 (make-variable-buffer-local 'org-keyword-time-regexp)
4735 (defvar org-keyword-time-not-clock-regexp nil
4736 "Matches any of the 3 keywords, together with the time stamp.")
4737 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4738 (defvar org-maybe-keyword-time-regexp nil
4739 "Matches a timestamp, possibly preceded by a keyword.")
4740 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4741 (defvar org-all-time-keywords nil
4742 "List of time keywords.")
4743 (make-variable-buffer-local 'org-all-time-keywords)
4745 (defconst org-plain-time-of-day-regexp
4746 (concat
4747 "\\(\\<[012]?[0-9]"
4748 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4749 "\\(--?"
4750 "\\(\\<[012]?[0-9]"
4751 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4752 "\\)?")
4753 "Regular expression to match a plain time or time range.
4754 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4755 groups carry important information:
4756 0 the full match
4757 1 the first time, range or not
4758 8 the second time, if it is a range.")
4760 (defconst org-plain-time-extension-regexp
4761 (concat
4762 "\\(\\<[012]?[0-9]"
4763 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4764 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4765 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4766 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4767 groups carry important information:
4768 0 the full match
4769 7 hours of duration
4770 9 minutes of duration")
4772 (defconst org-stamp-time-of-day-regexp
4773 (concat
4774 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4775 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4776 "\\(--?"
4777 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4778 "Regular expression to match a timestamp time or time range.
4779 After a match, the following groups carry important information:
4780 0 the full match
4781 1 date plus weekday, for back referencing to make sure both times are on the same day
4782 2 the first time, range or not
4783 4 the second time, if it is a range.")
4785 (defconst org-startup-options
4786 '(("fold" org-startup-folded t)
4787 ("overview" org-startup-folded t)
4788 ("nofold" org-startup-folded nil)
4789 ("showall" org-startup-folded nil)
4790 ("showeverything" org-startup-folded showeverything)
4791 ("content" org-startup-folded content)
4792 ("indent" org-startup-indented t)
4793 ("noindent" org-startup-indented nil)
4794 ("hidestars" org-hide-leading-stars t)
4795 ("showstars" org-hide-leading-stars nil)
4796 ("odd" org-odd-levels-only t)
4797 ("oddeven" org-odd-levels-only nil)
4798 ("align" org-startup-align-all-tables t)
4799 ("noalign" org-startup-align-all-tables nil)
4800 ("inlineimages" org-startup-with-inline-images t)
4801 ("noinlineimages" org-startup-with-inline-images nil)
4802 ("latexpreview" org-startup-with-latex-preview t)
4803 ("nolatexpreview" org-startup-with-latex-preview nil)
4804 ("customtime" org-display-custom-times t)
4805 ("logdone" org-log-done time)
4806 ("lognotedone" org-log-done note)
4807 ("nologdone" org-log-done nil)
4808 ("lognoteclock-out" org-log-note-clock-out t)
4809 ("nolognoteclock-out" org-log-note-clock-out nil)
4810 ("logrepeat" org-log-repeat state)
4811 ("lognoterepeat" org-log-repeat note)
4812 ("logdrawer" org-log-into-drawer t)
4813 ("nologdrawer" org-log-into-drawer nil)
4814 ("logstatesreversed" org-log-states-order-reversed t)
4815 ("nologstatesreversed" org-log-states-order-reversed nil)
4816 ("nologrepeat" org-log-repeat nil)
4817 ("logreschedule" org-log-reschedule time)
4818 ("lognotereschedule" org-log-reschedule note)
4819 ("nologreschedule" org-log-reschedule nil)
4820 ("logredeadline" org-log-redeadline time)
4821 ("lognoteredeadline" org-log-redeadline note)
4822 ("nologredeadline" org-log-redeadline nil)
4823 ("logrefile" org-log-refile time)
4824 ("lognoterefile" org-log-refile note)
4825 ("nologrefile" org-log-refile nil)
4826 ("fninline" org-footnote-define-inline t)
4827 ("nofninline" org-footnote-define-inline nil)
4828 ("fnlocal" org-footnote-section nil)
4829 ("fnauto" org-footnote-auto-label t)
4830 ("fnprompt" org-footnote-auto-label nil)
4831 ("fnconfirm" org-footnote-auto-label confirm)
4832 ("fnplain" org-footnote-auto-label plain)
4833 ("fnadjust" org-footnote-auto-adjust t)
4834 ("nofnadjust" org-footnote-auto-adjust nil)
4835 ("constcgs" constants-unit-system cgs)
4836 ("constSI" constants-unit-system SI)
4837 ("noptag" org-tag-persistent-alist nil)
4838 ("hideblocks" org-hide-block-startup t)
4839 ("nohideblocks" org-hide-block-startup nil)
4840 ("beamer" org-startup-with-beamer-mode t)
4841 ("entitiespretty" org-pretty-entities t)
4842 ("entitiesplain" org-pretty-entities nil))
4843 "Variable associated with STARTUP options for org-mode.
4844 Each element is a list of three items: the startup options (as written
4845 in the #+STARTUP line), the corresponding variable, and the value to set
4846 this variable to if the option is found. An optional forth element PUSH
4847 means to push this value onto the list in the variable.")
4849 (defun org-update-property-plist (key val props)
4850 "Update PROPS with KEY and VAL."
4851 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4852 (key (if appending (substring key 0 (- (length key) 1)) key))
4853 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4854 (previous (cdr (assoc key props))))
4855 (if appending
4856 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4857 (cons (cons key val) remainder))))
4859 (defcustom org-group-tags t
4860 "When non-nil (the default), use group tags.
4861 This can be turned on/off through `org-toggle-tags-groups'."
4862 :group 'org-tags
4863 :group 'org-startup
4864 :type 'boolean)
4866 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4868 (defun org-toggle-tags-groups ()
4869 "Toggle support for group tags.
4870 Support for group tags is controlled by the option
4871 `org-group-tags', which is non-nil by default."
4872 (interactive)
4873 (setq org-group-tags (not org-group-tags))
4874 (cond ((and (derived-mode-p 'org-agenda-mode)
4875 org-group-tags)
4876 (org-agenda-redo))
4877 ((derived-mode-p 'org-mode)
4878 (let ((org-inhibit-startup t)) (org-mode))))
4879 (message "Groups tags support has been turned %s"
4880 (if org-group-tags "on" "off")))
4882 (defun org-set-regexps-and-options-for-tags ()
4883 "Precompute variables used for tags."
4884 (when (derived-mode-p 'org-mode)
4885 (org-set-local 'org-file-tags nil)
4886 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4887 (splitre "[ \t]+")
4888 (start 0)
4889 tags ftags key value)
4890 (save-excursion
4891 (save-restriction
4892 (widen)
4893 (goto-char (point-min))
4894 (while (re-search-forward re nil t)
4895 (setq key (upcase (org-match-string-no-properties 1))
4896 value (org-match-string-no-properties 2))
4897 (if (stringp value) (setq value (org-trim value)))
4898 (cond
4899 ((equal key "TAGS")
4900 (setq tags (append tags (if tags '("\\n") nil)
4901 (org-split-string value splitre))))
4902 ((equal key "FILETAGS")
4903 (when (string-match "\\S-" value)
4904 (setq ftags
4905 (append
4906 ftags
4907 (apply 'append
4908 (mapcar (lambda (x) (org-split-string x ":"))
4909 (org-split-string value)))))))))))
4910 ;; Process the file tags.
4911 (and ftags (org-set-local 'org-file-tags
4912 (mapcar 'org-add-prop-inherited ftags)))
4913 (org-set-local 'org-tag-groups-alist nil)
4914 ;; Process the tags.
4915 (when (and (not tags) org-tag-alist)
4916 (setq tags
4917 (mapcar
4918 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4919 ((eq (car tg) :endgroup) "}")
4920 ((eq (car tg) :grouptags) ":")
4921 ((eq (car tg) :newline) "\n")
4922 (t (concat (car tg)
4923 (if (characterp (cdr tg))
4924 (format "(%s)" (char-to-string (cdr tg))) "")))))
4925 org-tag-alist)))
4926 (let (e tgs g)
4927 (while (setq e (pop tags))
4928 (cond
4929 ((equal e "{")
4930 (progn (push '(:startgroup) tgs)
4931 (when (equal (nth 1 tags) ":")
4932 (push (list (replace-regexp-in-string
4933 "(.+)$" "" (nth 0 tags)))
4934 org-tag-groups-alist)
4935 (setq g 0))))
4936 ((equal e ":") (push '(:grouptags) tgs))
4937 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4938 ((equal e "\\n") (push '(:newline) tgs))
4939 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4940 (push (cons (match-string 1 e)
4941 (string-to-char (match-string 2 e))) tgs)
4942 (if (and g (> g 0))
4943 (setcar org-tag-groups-alist
4944 (append (car org-tag-groups-alist)
4945 (list (match-string 1 e)))))
4946 (if g (setq g (1+ g))))
4947 (t (push (list e) tgs)
4948 (if (and g (> g 0))
4949 (setcar org-tag-groups-alist
4950 (append (car org-tag-groups-alist) (list e))))
4951 (if g (setq g (1+ g))))))
4952 (org-set-local 'org-tag-alist nil)
4953 (while (setq e (pop tgs))
4954 (or (and (stringp (car e))
4955 (assoc (car e) org-tag-alist))
4956 (push e org-tag-alist)))
4957 ;; Return a list with tag variables
4958 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4960 (defvar org-ota nil)
4961 (defun org-set-regexps-and-options ()
4962 "Precompute regular expressions used in the current buffer."
4963 (when (derived-mode-p 'org-mode)
4964 (org-set-local 'org-todo-kwd-alist nil)
4965 (org-set-local 'org-todo-key-alist nil)
4966 (org-set-local 'org-todo-key-trigger nil)
4967 (org-set-local 'org-todo-keywords-1 nil)
4968 (org-set-local 'org-done-keywords nil)
4969 (org-set-local 'org-todo-heads nil)
4970 (org-set-local 'org-todo-sets nil)
4971 (org-set-local 'org-todo-log-states nil)
4972 (org-set-local 'org-file-properties nil)
4973 (let ((re (org-make-options-regexp
4974 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4975 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4976 "SETUPFILE" "OPTIONS")
4977 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4978 (splitre "[ \t]+")
4979 (scripts org-use-sub-superscripts)
4980 kwds kws0 kwsa key log value cat arch const links hw dws
4981 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4982 (start 0))
4983 (save-excursion
4984 (save-restriction
4985 (widen)
4986 (goto-char (point-min))
4987 (while
4988 (or (and
4989 ext-setup-or-nil
4990 (not org-ota)
4991 (let (ret)
4992 (with-temp-buffer
4993 (insert ext-setup-or-nil)
4994 (let ((major-mode 'org-mode) org-ota)
4995 (setq ret (save-match-data
4996 (org-set-regexps-and-options-for-tags)))))
4997 ;; Append setupfile tags to existing tags
4998 (setq org-ota t)
4999 (setq org-file-tags
5000 (delq nil (append org-file-tags (nth 0 ret)))
5001 org-tag-alist
5002 (delq nil (append org-tag-alist (nth 1 ret)))
5003 org-tag-groups-alist
5004 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5005 (and ext-setup-or-nil
5006 (string-match re ext-setup-or-nil start)
5007 (setq start (match-end 0)))
5008 (and (setq ext-setup-or-nil nil start 0)
5009 (re-search-forward re nil t)))
5010 (setq key (upcase (match-string 1 ext-setup-or-nil))
5011 value (org-match-string-no-properties 2 ext-setup-or-nil))
5012 (if (stringp value) (setq value (org-trim value)))
5013 (cond
5014 ((equal key "CATEGORY")
5015 (setq cat value))
5016 ((member key '("SEQ_TODO" "TODO"))
5017 (push (cons 'sequence (org-split-string value splitre)) kwds))
5018 ((equal key "TYP_TODO")
5019 (push (cons 'type (org-split-string value splitre)) kwds))
5020 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5021 ;; general TODO-like setup
5022 (push (cons (intern (downcase (match-string 1 key)))
5023 (org-split-string value splitre)) kwds))
5024 ((equal key "COLUMNS")
5025 (org-set-local 'org-columns-default-format value))
5026 ((equal key "LINK")
5027 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5028 (push (cons (match-string 1 value)
5029 (org-trim (match-string 2 value)))
5030 links)))
5031 ((equal key "PRIORITIES")
5032 (setq prio (org-split-string value " +")))
5033 ((equal key "PROPERTY")
5034 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5035 (setq props (org-update-property-plist (match-string 1 value)
5036 (match-string 2 value)
5037 props))))
5038 ((equal key "CONSTANTS")
5039 (org-table-set-constants))
5040 ((equal key "STARTUP")
5041 (let ((opts (org-split-string value splitre))
5042 l var val)
5043 (while (setq l (pop opts))
5044 (when (setq l (assoc l org-startup-options))
5045 (setq var (nth 1 l) val (nth 2 l))
5046 (if (not (nth 3 l))
5047 (set (make-local-variable var) val)
5048 (if (not (listp (symbol-value var)))
5049 (set (make-local-variable var) nil))
5050 (set (make-local-variable var) (symbol-value var))
5051 (add-to-list var val))))))
5052 ((equal key "ARCHIVE")
5053 (setq arch value)
5054 (remove-text-properties 0 (length arch)
5055 '(face t fontified t) arch))
5056 ((equal key "OPTIONS")
5057 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5058 (setq scripts (read (match-string 2 value)))))
5059 ((and (equal key "SETUPFILE")
5060 ;; Prevent checking in Gnus messages
5061 (not buffer-read-only))
5062 (setq setup-contents (org-file-contents
5063 (expand-file-name
5064 (org-remove-double-quotes value))
5065 'noerror))
5066 (if (not ext-setup-or-nil)
5067 (setq ext-setup-or-nil setup-contents start 0)
5068 (setq ext-setup-or-nil
5069 (concat (substring ext-setup-or-nil 0 start)
5070 "\n" setup-contents "\n"
5071 (substring ext-setup-or-nil start)))))))
5072 ;; search for property blocks
5073 (goto-char (point-min))
5074 (while (re-search-forward org-block-regexp nil t)
5075 (when (equal "PROPERTY" (upcase (match-string 1)))
5076 (setq value (replace-regexp-in-string
5077 "[\n\r]" " " (match-string 4)))
5078 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5079 (setq props (org-update-property-plist (match-string 1 value)
5080 (match-string 2 value)
5081 props)))))))
5082 (org-set-local 'org-use-sub-superscripts scripts)
5083 (when cat
5084 (org-set-local 'org-category (intern cat))
5085 (push (cons "CATEGORY" cat) props))
5086 (when prio
5087 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5088 (setq prio (mapcar 'string-to-char prio))
5089 (org-set-local 'org-highest-priority (nth 0 prio))
5090 (org-set-local 'org-lowest-priority (nth 1 prio))
5091 (org-set-local 'org-default-priority (nth 2 prio)))
5092 (and props (org-set-local 'org-file-properties (nreverse props)))
5093 (and arch (org-set-local 'org-archive-location arch))
5094 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5095 ;; Process the TODO keywords
5096 (unless kwds
5097 ;; Use the global values as if they had been given locally.
5098 (setq kwds (default-value 'org-todo-keywords))
5099 (if (stringp (car kwds))
5100 (setq kwds (list (cons org-todo-interpretation
5101 (default-value 'org-todo-keywords)))))
5102 (setq kwds (reverse kwds)))
5103 (setq kwds (nreverse kwds))
5104 (let (inter kws kw)
5105 (while (setq kws (pop kwds))
5106 (let ((kws (or
5107 (run-hook-with-args-until-success
5108 'org-todo-setup-filter-hook kws)
5109 kws)))
5110 (setq inter (pop kws) sep (member "|" kws)
5111 kws0 (delete "|" (copy-sequence kws))
5112 kwsa nil
5113 kws1 (mapcar
5114 (lambda (x)
5115 ;; 1 2
5116 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5117 (progn
5118 (setq kw (match-string 1 x)
5119 key (and (match-end 2) (match-string 2 x))
5120 log (org-extract-log-state-settings x))
5121 (push (cons kw (and key (string-to-char key))) kwsa)
5122 (and log (push log org-todo-log-states))
5124 (error "Invalid TODO keyword %s" x)))
5125 kws0)
5126 kwsa (if kwsa (append '((:startgroup))
5127 (nreverse kwsa)
5128 '((:endgroup))))
5129 hw (car kws1)
5130 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5131 tail (list inter hw (car dws) (org-last dws))))
5132 (add-to-list 'org-todo-heads hw 'append)
5133 (push kws1 org-todo-sets)
5134 (setq org-done-keywords (append org-done-keywords dws nil))
5135 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5136 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5137 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5138 (setq org-todo-sets (nreverse org-todo-sets)
5139 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5140 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5141 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5142 ;; Compute the regular expressions and other local variables.
5143 ;; Using `org-outline-regexp-bol' would complicate them much,
5144 ;; because of the fixed white space at the end of that string.
5145 (if (not org-done-keywords)
5146 (setq org-done-keywords (and org-todo-keywords-1
5147 (list (org-last org-todo-keywords-1)))))
5148 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5149 (length org-scheduled-string)
5150 (length org-clock-string)
5151 (length org-closed-string)))
5152 org-not-done-keywords
5153 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5154 org-todo-regexp
5155 (concat "\\("
5156 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5157 "\\)")
5158 org-not-done-regexp
5159 (concat "\\("
5160 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5161 "\\)")
5162 org-not-done-heading-regexp
5163 (format org-heading-keyword-regexp-format org-not-done-regexp)
5164 org-todo-line-regexp
5165 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5166 org-complex-heading-regexp
5167 (concat "^\\(\\*+\\)"
5168 "\\(?: +" org-todo-regexp "\\)?"
5169 "\\(?: +\\(\\[#.\\]\\)\\)?"
5170 "\\(?: +\\(.*?\\)\\)??"
5171 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5172 "[ \t]*$")
5173 org-complex-heading-regexp-format
5174 (concat "^\\(\\*+\\)"
5175 "\\(?: +" org-todo-regexp "\\)?"
5176 "\\(?: +\\(\\[#.\\]\\)\\)?"
5177 "\\(?: +"
5178 ;; Stats cookies can be stuck to body.
5179 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5180 "\\(%s\\)"
5181 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5182 "\\)"
5183 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5184 "[ \t]*$")
5185 org-todo-line-tags-regexp
5186 (concat "^\\(\\*+\\)"
5187 "\\(?: +" org-todo-regexp "\\)?"
5188 "\\(?: +\\(.*?\\)\\)??"
5189 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5190 "[ \t]*$")
5191 org-deadline-regexp (concat "\\<" org-deadline-string)
5192 org-deadline-time-regexp
5193 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5194 org-deadline-time-hour-regexp
5195 (concat "\\<" org-deadline-string
5196 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5197 org-deadline-line-regexp
5198 (concat "\\<\\(" org-deadline-string "\\).*")
5199 org-scheduled-regexp
5200 (concat "\\<" org-scheduled-string)
5201 org-scheduled-time-regexp
5202 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5203 org-scheduled-time-hour-regexp
5204 (concat "\\<" org-scheduled-string
5205 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5206 org-closed-time-regexp
5207 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5208 org-keyword-time-regexp
5209 (concat "\\<\\(" org-scheduled-string
5210 "\\|" org-deadline-string
5211 "\\|" org-closed-string
5212 "\\|" org-clock-string "\\)"
5213 " *[[<]\\([^]>]+\\)[]>]")
5214 org-keyword-time-not-clock-regexp
5215 (concat "\\<\\(" org-scheduled-string
5216 "\\|" org-deadline-string
5217 "\\|" org-closed-string
5218 "\\)"
5219 " *[[<]\\([^]>]+\\)[]>]")
5220 org-maybe-keyword-time-regexp
5221 (concat "\\(\\<\\(" org-scheduled-string
5222 "\\|" org-deadline-string
5223 "\\|" org-closed-string
5224 "\\|" org-clock-string "\\)\\)?"
5225 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5226 org-all-time-keywords
5227 (mapcar (lambda (w) (substring w 0 -1))
5228 (list org-scheduled-string org-deadline-string
5229 org-clock-string org-closed-string)))
5230 (setq org-ota nil)
5231 (org-compute-latex-and-related-regexp))))
5233 (defun org-file-contents (file &optional noerror)
5234 "Return the contents of FILE, as a string."
5235 (if (or (not file)
5236 (not (file-readable-p file)))
5237 (if noerror
5238 (message "Cannot read file \"%s\"" file)
5239 (error "Cannot read file \"%s\"" file))
5240 (with-temp-buffer
5241 (insert-file-contents file)
5242 (buffer-string))))
5244 (defun org-extract-log-state-settings (x)
5245 "Extract the log state setting from a TODO keyword string.
5246 This will extract info from a string like \"WAIT(w@/!)\"."
5247 (let (kw key log1 log2)
5248 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5249 (setq kw (match-string 1 x)
5250 key (and (match-end 2) (match-string 2 x))
5251 log1 (and (match-end 3) (match-string 3 x))
5252 log2 (and (match-end 4) (match-string 4 x)))
5253 (and (or log1 log2)
5254 (list kw
5255 (and log1 (if (equal log1 "!") 'time 'note))
5256 (and log2 (if (equal log2 "!") 'time 'note)))))))
5258 (defun org-remove-keyword-keys (list)
5259 "Remove a pair of parenthesis at the end of each string in LIST."
5260 (mapcar (lambda (x)
5261 (if (string-match "(.*)$" x)
5262 (substring x 0 (match-beginning 0))
5264 list))
5266 (defun org-assign-fast-keys (alist)
5267 "Assign fast keys to a keyword-key alist.
5268 Respect keys that are already there."
5269 (let (new e (alt ?0))
5270 (while (setq e (pop alist))
5271 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5272 (cdr e)) ;; Key already assigned.
5273 (push e new)
5274 (let ((clist (string-to-list (downcase (car e))))
5275 (used (append new alist)))
5276 (when (= (car clist) ?@)
5277 (pop clist))
5278 (while (and clist (rassoc (car clist) used))
5279 (pop clist))
5280 (unless clist
5281 (while (rassoc alt used)
5282 (incf alt)))
5283 (push (cons (car e) (or (car clist) alt)) new))))
5284 (nreverse new)))
5286 ;;; Some variables used in various places
5288 (defvar org-window-configuration nil
5289 "Used in various places to store a window configuration.")
5290 (defvar org-selected-window nil
5291 "Used in various places to store a window configuration.")
5292 (defvar org-finish-function nil
5293 "Function to be called when `C-c C-c' is used.
5294 This is for getting out of special buffers like capture.")
5297 ;; FIXME: Occasionally check by commenting these, to make sure
5298 ;; no other functions uses these, forgetting to let-bind them.
5299 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5300 (defvar org-last-state)
5301 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5303 ;; Defined somewhere in this file, but used before definition.
5304 (defvar org-entities) ;; defined in org-entities.el
5305 (defvar org-struct-menu)
5306 (defvar org-org-menu)
5307 (defvar org-tbl-menu)
5309 ;;;; Define the Org-mode
5311 ;; We use a before-change function to check if a table might need
5312 ;; an update.
5313 (defvar org-table-may-need-update t
5314 "Indicates that a table might need an update.
5315 This variable is set by `org-before-change-function'.
5316 `org-table-align' sets it back to nil.")
5317 (defun org-before-change-function (beg end)
5318 "Every change indicates that a table might need an update."
5319 (setq org-table-may-need-update t))
5320 (defvar org-mode-map)
5321 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5322 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5323 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5324 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5325 (defvar org-table-buffer-is-an nil)
5327 (defvar bidi-paragraph-direction)
5328 (defvar buffer-face-mode-face)
5330 (require 'outline)
5331 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5332 (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"))
5333 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5335 ;; Other stuff we need.
5336 (require 'time-date)
5337 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5338 (require 'easymenu)
5339 (require 'overlay)
5341 ;; (require 'org-macs) moved higher up in the file before it is first used
5342 (require 'org-entities)
5343 ;; (require 'org-compat) moved higher up in the file before it is first used
5344 (require 'org-faces)
5345 (require 'org-list)
5346 (require 'org-pcomplete)
5347 (require 'org-src)
5348 (require 'org-footnote)
5349 (require 'org-macro)
5351 ;; babel
5352 (require 'ob)
5354 ;;;###autoload
5355 (define-derived-mode org-mode outline-mode "Org"
5356 "Outline-based notes management and organizer, alias
5357 \"Carsten's outline-mode for keeping track of everything.\"
5359 Org-mode develops organizational tasks around a NOTES file which
5360 contains information about projects as plain text. Org-mode is
5361 implemented on top of outline-mode, which is ideal to keep the content
5362 of large files well structured. It supports ToDo items, deadlines and
5363 time stamps, which magically appear in the diary listing of the Emacs
5364 calendar. Tables are easily created with a built-in table editor.
5365 Plain text URL-like links connect to websites, emails (VM), Usenet
5366 messages (Gnus), BBDB entries, and any files related to the project.
5367 For printing and sharing of notes, an Org-mode file (or a part of it)
5368 can be exported as a structured ASCII or HTML file.
5370 The following commands are available:
5372 \\{org-mode-map}"
5374 ;; Get rid of Outline menus, they are not needed
5375 ;; Need to do this here because define-derived-mode sets up
5376 ;; the keymap so late. Still, it is a waste to call this each time
5377 ;; we switch another buffer into org-mode.
5378 (if (featurep 'xemacs)
5379 (when (boundp 'outline-mode-menu-heading)
5380 ;; Assume this is Greg's port, it uses easymenu
5381 (easy-menu-remove outline-mode-menu-heading)
5382 (easy-menu-remove outline-mode-menu-show)
5383 (easy-menu-remove outline-mode-menu-hide))
5384 (define-key org-mode-map [menu-bar headings] 'undefined)
5385 (define-key org-mode-map [menu-bar hide] 'undefined)
5386 (define-key org-mode-map [menu-bar show] 'undefined))
5388 (org-load-modules-maybe)
5389 (easy-menu-add org-org-menu)
5390 (easy-menu-add org-tbl-menu)
5391 (org-install-agenda-files-menu)
5392 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5393 (add-to-invisibility-spec '(org-cwidth))
5394 (add-to-invisibility-spec '(org-hide-block . t))
5395 (when (featurep 'xemacs)
5396 (org-set-local 'line-move-ignore-invisible t))
5397 (org-set-local 'outline-regexp org-outline-regexp)
5398 (org-set-local 'outline-level 'org-outline-level)
5399 (setq bidi-paragraph-direction 'left-to-right)
5400 (when (and org-ellipsis
5401 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5402 (fboundp 'make-glyph-code))
5403 (unless org-display-table
5404 (setq org-display-table (make-display-table)))
5405 (set-display-table-slot
5406 org-display-table 4
5407 (vconcat (mapcar
5408 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5409 org-ellipsis)))
5410 (if (stringp org-ellipsis) org-ellipsis "..."))))
5411 (setq buffer-display-table org-display-table))
5412 (org-set-regexps-and-options-for-tags)
5413 (org-set-regexps-and-options)
5414 (org-set-font-lock-defaults)
5415 (when (and org-tag-faces (not org-tags-special-faces-re))
5416 ;; tag faces set outside customize.... force initialization.
5417 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5418 ;; Calc embedded
5419 (org-set-local 'calc-embedded-open-mode "# ")
5420 ;; Modify a few syntax entries
5421 (modify-syntax-entry ?@ "w")
5422 (modify-syntax-entry ?\" "\"")
5423 (if org-startup-truncated (setq truncate-lines t))
5424 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5425 (org-set-local 'font-lock-unfontify-region-function
5426 'org-unfontify-region)
5427 ;; Activate before-change-function
5428 (org-set-local 'org-table-may-need-update t)
5429 (org-add-hook 'before-change-functions 'org-before-change-function nil
5430 'local)
5431 ;; Check for running clock before killing a buffer
5432 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5433 ;; Initialize macros templates.
5434 (org-macro-initialize-templates)
5435 ;; Initialize radio targets.
5436 (org-update-radio-target-regexp)
5437 ;; Indentation.
5438 (org-set-local 'indent-line-function 'org-indent-line)
5439 (org-set-local 'indent-region-function 'org-indent-region)
5440 ;; Filling and auto-filling.
5441 (org-setup-filling)
5442 ;; Comments.
5443 (org-setup-comments-handling)
5444 ;; Initialize cache.
5445 (org-element-cache-reset)
5446 ;; Beginning/end of defun
5447 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5448 (org-set-local 'end-of-defun-function 'org-forward-element)
5449 ;; Next error for sparse trees
5450 (org-set-local 'next-error-function 'org-occur-next-match)
5451 ;; Make sure dependence stuff works reliably, even for users who set it
5452 ;; too late :-(
5453 (if org-enforce-todo-dependencies
5454 (add-hook 'org-blocker-hook
5455 'org-block-todo-from-children-or-siblings-or-parent)
5456 (remove-hook 'org-blocker-hook
5457 'org-block-todo-from-children-or-siblings-or-parent))
5458 (if org-enforce-todo-checkbox-dependencies
5459 (add-hook 'org-blocker-hook
5460 'org-block-todo-from-checkboxes)
5461 (remove-hook 'org-blocker-hook
5462 'org-block-todo-from-checkboxes))
5464 ;; Align options lines
5465 (org-set-local
5466 'align-mode-rules-list
5467 '((org-in-buffer-settings
5468 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5469 (modes . '(org-mode)))))
5471 ;; Imenu
5472 (org-set-local 'imenu-create-index-function
5473 'org-imenu-get-tree)
5475 ;; Make isearch reveal context
5476 (if (or (featurep 'xemacs)
5477 (not (boundp 'outline-isearch-open-invisible-function)))
5478 ;; Emacs 21 and XEmacs make use of the hook
5479 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5480 ;; Emacs 22 deals with this through a special variable
5481 (org-set-local 'outline-isearch-open-invisible-function
5482 (lambda (&rest ignore) (org-show-context 'isearch)))
5483 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5485 ;; Setup the pcomplete hooks
5486 (set (make-local-variable 'pcomplete-command-completion-function)
5487 'org-pcomplete-initial)
5488 (set (make-local-variable 'pcomplete-command-name-function)
5489 'org-command-at-point)
5490 (set (make-local-variable 'pcomplete-default-completion-function)
5491 'ignore)
5492 (set (make-local-variable 'pcomplete-parse-arguments-function)
5493 'org-parse-arguments)
5494 (set (make-local-variable 'pcomplete-termination-string) "")
5495 (when (>= emacs-major-version 23)
5496 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5498 ;; If empty file that did not turn on org-mode automatically, make it to.
5499 (if (and org-insert-mode-line-in-empty-file
5500 (org-called-interactively-p 'any)
5501 (= (point-min) (point-max)))
5502 (insert "# -*- mode: org -*-\n\n"))
5503 (unless org-inhibit-startup
5504 (org-unmodified
5505 (and org-startup-with-beamer-mode (org-beamer-mode))
5506 (when org-startup-align-all-tables
5507 (org-table-map-tables 'org-table-align 'quietly))
5508 (when org-startup-with-inline-images
5509 (org-display-inline-images))
5510 (when org-startup-with-latex-preview
5511 (org-preview-latex-fragment))
5512 (unless org-inhibit-startup-visibility-stuff
5513 (org-set-startup-visibility))))
5514 ;; Try to set org-hide correctly
5515 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5517 ;; Update `customize-package-emacs-version-alist'
5518 (add-to-list 'customize-package-emacs-version-alist
5519 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5520 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5521 ("8.0" . "24.4")))
5523 (defvar org-mode-transpose-word-syntax-table
5524 (let ((st (make-syntax-table)))
5525 (mapc (lambda(c) (modify-syntax-entry
5526 (string-to-char (car c)) "w p" st))
5527 org-emphasis-alist)
5528 st))
5530 (when (fboundp 'abbrev-table-put)
5531 (abbrev-table-put org-mode-abbrev-table
5532 :parents (list text-mode-abbrev-table)))
5534 (defsubst org-fix-ellipsis-at-bol ()
5535 (save-excursion (goto-char (window-start)) (recenter 0)))
5537 (defun org-find-invisible-foreground ()
5538 (let ((candidates (remove
5539 "unspecified-bg"
5540 (nconc
5541 (list (face-background 'default)
5542 (face-background 'org-default))
5543 (mapcar
5544 (lambda (alist)
5545 (when (boundp alist)
5546 (cdr (assoc 'background-color (symbol-value alist)))))
5547 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5548 (list (face-foreground 'org-hide))))))
5549 (car (remove nil candidates))))
5551 (defun org-current-time (&optional rounding-minutes past)
5552 "Current time, possibly rounded to ROUNDING-MINUTES.
5553 When ROUNDING-MINUTES is not an integer, fall back on the car of
5554 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5555 the rounding returns a past time."
5556 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5557 (car org-time-stamp-rounding-minutes)))
5558 (time (decode-time)) res)
5559 (if (< r 1)
5560 (current-time)
5561 (setq res
5562 (apply 'encode-time
5563 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5564 (nthcdr 2 time))))
5565 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5566 (seconds-to-time (- (org-float-time res) (* r 60)))
5567 res))))
5569 (defun org-today ()
5570 "Return today date, considering `org-extend-today-until'."
5571 (time-to-days
5572 (time-subtract (current-time)
5573 (list 0 (* 3600 org-extend-today-until) 0))))
5575 ;;;; Font-Lock stuff, including the activators
5577 (defvar org-mouse-map (make-sparse-keymap))
5578 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5579 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5580 (when org-mouse-1-follows-link
5581 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5582 (when org-tab-follows-link
5583 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5584 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5586 (require 'font-lock)
5588 (defconst org-non-link-chars "]\t\n\r<>")
5589 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5590 "shell" "elisp" "doi" "message"))
5591 (defvar org-link-types-re nil
5592 "Matches a link that has a url-like prefix like \"http:\"")
5593 (defvar org-link-re-with-space nil
5594 "Matches a link with spaces, optional angular brackets around it.")
5595 (defvar org-link-re-with-space2 nil
5596 "Matches a link with spaces, optional angular brackets around it.")
5597 (defvar org-link-re-with-space3 nil
5598 "Matches a link with spaces, only for internal part in bracket links.")
5599 (defvar org-angle-link-re nil
5600 "Matches link with angular brackets, spaces are allowed.")
5601 (defvar org-plain-link-re nil
5602 "Matches plain link, without spaces.")
5603 (defvar org-bracket-link-regexp nil
5604 "Matches a link in double brackets.")
5605 (defvar org-bracket-link-analytic-regexp nil
5606 "Regular expression used to analyze links.
5607 Here is what the match groups contain after a match:
5608 1: http:
5609 2: http
5610 3: path
5611 4: [desc]
5612 5: desc")
5613 (defvar org-bracket-link-analytic-regexp++ nil
5614 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5615 (defvar org-any-link-re nil
5616 "Regular expression matching any link.")
5618 (defconst org-match-sexp-depth 3
5619 "Number of stacked braces for sub/superscript matching.")
5621 (defun org-create-multibrace-regexp (left right n)
5622 "Create a regular expression which will match a balanced sexp.
5623 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5624 as single character strings.
5625 The regexp returned will match the entire expression including the
5626 delimiters. It will also define a single group which contains the
5627 match except for the outermost delimiters. The maximum depth of
5628 stacked delimiters is N. Escaping delimiters is not possible."
5629 (let* ((nothing (concat "[^" left right "]*?"))
5630 (or "\\|")
5631 (re nothing)
5632 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5633 (while (> n 1)
5634 (setq n (1- n)
5635 re (concat re or next)
5636 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5637 (concat left "\\(" re "\\)" right)))
5639 (defvar org-match-substring-regexp
5640 (concat
5641 "\\(\\S-\\)\\([_^]\\)\\("
5642 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5643 "\\|"
5644 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5645 "\\|"
5646 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5647 "The regular expression matching a sub- or superscript.")
5649 (defvar org-match-substring-with-braces-regexp
5650 (concat
5651 "\\(\\S-\\)\\([_^]\\)\\("
5652 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5653 "\\)")
5654 "The regular expression matching a sub- or superscript, forcing braces.")
5656 (defun org-make-link-regexps ()
5657 "Update the link regular expressions.
5658 This should be called after the variable `org-link-types' has changed."
5659 (setq org-link-types-re
5660 (concat
5661 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5662 org-link-re-with-space
5663 (concat
5664 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5665 "\\([^" org-non-link-chars " ]"
5666 "[^" org-non-link-chars "]*"
5667 "[^" org-non-link-chars " ]\\)>?")
5668 org-link-re-with-space2
5669 (concat
5670 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5671 "\\([^" org-non-link-chars " ]"
5672 "[^\t\n\r]*"
5673 "[^" org-non-link-chars " ]\\)>?")
5674 org-link-re-with-space3
5675 (concat
5676 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5677 "\\([^" org-non-link-chars " ]"
5678 "[^\t\n\r]*\\)")
5679 org-angle-link-re
5680 (concat
5681 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^" org-non-link-chars "]*"
5684 "\\)>")
5685 org-plain-link-re
5686 (concat
5687 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5688 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5689 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5690 org-bracket-link-regexp
5691 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5692 org-bracket-link-analytic-regexp
5693 (concat
5694 "\\[\\["
5695 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5696 "\\([^]]+\\)"
5697 "\\]"
5698 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5699 "\\]")
5700 org-bracket-link-analytic-regexp++
5701 (concat
5702 "\\[\\["
5703 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5704 "\\([^]]+\\)"
5705 "\\]"
5706 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5707 "\\]")
5708 org-any-link-re
5709 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5710 org-angle-link-re "\\)\\|\\("
5711 org-plain-link-re "\\)")))
5713 (org-make-link-regexps)
5715 (defvar org-emph-face nil)
5717 (defun org-do-emphasis-faces (limit)
5718 "Run through the buffer and add overlays to emphasized strings."
5719 (let (rtn a)
5720 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5721 (if (not (= (char-after (match-beginning 3))
5722 (char-after (match-beginning 4))))
5723 (progn
5724 (setq rtn t)
5725 (setq a (assoc (match-string 3) org-emphasis-alist))
5726 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5727 'face
5728 (nth 1 a))
5729 (and (nth 2 a)
5730 (org-remove-flyspell-overlays-in
5731 (match-beginning 0) (match-end 0)))
5732 (add-text-properties (match-beginning 2) (match-end 2)
5733 '(font-lock-multiline t org-emphasis t))
5734 (when org-hide-emphasis-markers
5735 (add-text-properties (match-end 4) (match-beginning 5)
5736 '(invisible org-link))
5737 (add-text-properties (match-beginning 3) (match-end 3)
5738 '(invisible org-link)))))
5739 (backward-char 1))
5740 rtn))
5742 (defun org-emphasize (&optional char)
5743 "Insert or change an emphasis, i.e. a font like bold or italic.
5744 If there is an active region, change that region to a new emphasis.
5745 If there is no region, just insert the marker characters and position
5746 the cursor between them.
5747 CHAR should be the marker character. If it is a space, it means to
5748 remove the emphasis of the selected region.
5749 If CHAR is not given (for example in an interactive call) it will be
5750 prompted for."
5751 (interactive)
5752 (let ((erc org-emphasis-regexp-components)
5753 (prompt "")
5754 (string "") beg end move c s)
5755 (if (org-region-active-p)
5756 (setq beg (region-beginning) end (region-end)
5757 string (buffer-substring beg end))
5758 (setq move t))
5760 (unless char
5761 (message "Emphasis marker or tag: [%s]"
5762 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5763 (setq char (read-char-exclusive)))
5764 (if (equal char ?\ )
5765 (setq s "" move nil)
5766 (unless (assoc (char-to-string char) org-emphasis-alist)
5767 (user-error "No such emphasis marker: \"%c\"" char))
5768 (setq s (char-to-string char)))
5769 (while (and (> (length string) 1)
5770 (equal (substring string 0 1) (substring string -1))
5771 (assoc (substring string 0 1) org-emphasis-alist))
5772 (setq string (substring string 1 -1)))
5773 (setq string (concat s string s))
5774 (if beg (delete-region beg end))
5775 (unless (or (bolp)
5776 (string-match (concat "[" (nth 0 erc) "\n]")
5777 (char-to-string (char-before (point)))))
5778 (insert " "))
5779 (unless (or (eobp)
5780 (string-match (concat "[" (nth 1 erc) "\n]")
5781 (char-to-string (char-after (point)))))
5782 (insert " ") (backward-char 1))
5783 (insert string)
5784 (and move (backward-char 1))))
5786 (defconst org-nonsticky-props
5787 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5789 (defsubst org-rear-nonsticky-at (pos)
5790 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5792 (defun org-activate-plain-links (limit)
5793 "Run through the buffer and add overlays to links."
5794 (let (f hl)
5795 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5796 (not (org-in-src-block-p)))
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (setq f (get-text-property (match-beginning 0) 'face))
5799 (setq hl (org-match-string-no-properties 0))
5800 (if (or (eq f 'org-tag)
5801 (and (listp f) (memq 'org-tag f)))
5803 (add-text-properties (match-beginning 0) (match-end 0)
5804 (list 'mouse-face 'highlight
5805 'face 'org-link
5806 'htmlize-link `(:uri ,hl)
5807 'keymap org-mouse-map))
5808 (org-rear-nonsticky-at (match-end 0)))
5809 t)))
5811 (defun org-activate-code (limit)
5812 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5813 (progn
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (remove-text-properties (match-beginning 0) (match-end 0)
5816 '(display t invisible t intangible t))
5817 t)))
5819 (defcustom org-src-fontify-natively nil
5820 "When non-nil, fontify code in code blocks."
5821 :type 'boolean
5822 :version "24.1"
5823 :group 'org-appearance
5824 :group 'org-babel)
5826 (defcustom org-allow-promoting-top-level-subtree nil
5827 "When non-nil, allow promoting a top level subtree.
5828 The leading star of the top level headline will be replaced
5829 by a #."
5830 :type 'boolean
5831 :version "24.1"
5832 :group 'org-appearance)
5834 (defun org-fontify-meta-lines-and-blocks (limit)
5835 (condition-case nil
5836 (org-fontify-meta-lines-and-blocks-1 limit)
5837 (error (message "org-mode fontification error"))))
5839 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5840 "Fontify #+ lines and blocks."
5841 (let ((case-fold-search t))
5842 (if (re-search-forward
5843 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5844 limit t)
5845 (let ((beg (match-beginning 0))
5846 (block-start (match-end 0))
5847 (block-end nil)
5848 (lang (match-string 7))
5849 (beg1 (line-beginning-position 2))
5850 (dc1 (downcase (match-string 2)))
5851 (dc3 (downcase (match-string 3)))
5852 end end1 quoting block-type ovl)
5853 (cond
5854 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5855 ;; a single line of backend-specific content
5856 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5857 (remove-text-properties (match-beginning 0) (match-end 0)
5858 '(display t invisible t intangible t))
5859 (add-text-properties (match-beginning 1) (match-end 3)
5860 '(font-lock-fontified t face org-meta-line))
5861 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5862 '(font-lock-fontified t face org-block))
5863 ; for backend-specific code
5865 ((and (match-end 4) (equal dc3 "+begin"))
5866 ;; Truly a block
5867 (setq block-type (downcase (match-string 5))
5868 quoting (member block-type org-protecting-blocks))
5869 (when (re-search-forward
5870 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5871 nil t) ;; on purpose, we look further than LIMIT
5872 (setq end (min (point-max) (match-end 0))
5873 end1 (min (point-max) (1- (match-beginning 0))))
5874 (setq block-end (match-beginning 0))
5875 (when quoting
5876 (org-remove-flyspell-overlays-in beg1 end1)
5877 (remove-text-properties beg end
5878 '(display t invisible t intangible t)))
5879 (add-text-properties
5880 beg end '(font-lock-fontified t font-lock-multiline t))
5881 (add-text-properties beg beg1 '(face org-meta-line))
5882 (org-remove-flyspell-overlays-in beg beg1)
5883 (add-text-properties ; For end_src
5884 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5885 (org-remove-flyspell-overlays-in end1 end)
5886 (cond
5887 ((and lang (not (string= lang "")) org-src-fontify-natively)
5888 (org-src-font-lock-fontify-block lang block-start block-end)
5889 ;; remove old background overlays
5890 (mapc (lambda (ov)
5891 (if (eq (overlay-get ov 'face) 'org-block-background)
5892 (delete-overlay ov)))
5893 (overlays-at (/ (+ beg1 block-end) 2)))
5894 ;; add a background overlay
5895 (setq ovl (make-overlay beg1 block-end))
5896 (overlay-put ovl 'face 'org-block-background)
5897 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5898 (quoting
5899 (add-text-properties beg1 (min (point-max) (1+ end1))
5900 '(face org-block))) ; end of source block
5901 ((not org-fontify-quote-and-verse-blocks))
5902 ((string= block-type "quote")
5903 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5904 ((string= block-type "verse")
5905 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5906 (add-text-properties beg beg1 '(face org-block-begin-line))
5907 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5908 '(face org-block-end-line))
5910 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5911 (org-remove-flyspell-overlays-in
5912 (match-beginning 0)
5913 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5914 (add-text-properties
5915 beg (match-end 3)
5916 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5917 '(font-lock-fontified t invisible t)
5918 '(font-lock-fontified t face org-document-info-keyword)))
5919 (add-text-properties
5920 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5921 (if (string-equal dc1 "+title:")
5922 '(font-lock-fontified t face org-document-title)
5923 '(font-lock-fontified t face org-document-info))))
5924 ((or (equal dc1 "+results")
5925 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5926 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5927 "+call:" "+header:" "+headers:" "+name:"))
5928 (and (match-end 4) (equal dc3 "+attr")))
5929 (org-remove-flyspell-overlays-in
5930 (match-beginning 0)
5931 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5932 (add-text-properties
5933 beg (match-end 0)
5934 '(font-lock-fontified t face org-meta-line))
5936 ((member dc3 '(" " ""))
5937 (org-remove-flyspell-overlays-in beg (match-end 0))
5938 (add-text-properties
5939 beg (match-end 0)
5940 '(font-lock-fontified t face font-lock-comment-face)))
5941 ((not (member (char-after beg) '(?\ ?\t)))
5942 ;; just any other in-buffer setting, but not indented
5943 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5944 (add-text-properties
5945 beg (match-end 0)
5946 '(font-lock-fontified t face org-meta-line))
5948 (t nil))))))
5950 (defun org-fontify-drawers (limit)
5951 "Fontify drawers."
5952 (when (re-search-forward org-drawer-regexp limit t)
5953 (add-text-properties
5954 (match-beginning 0) (match-end 0)
5955 '(font-lock-fontified t face org-special-keyword))
5956 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (defun org-activate-angle-links (limit)
5960 "Run through the buffer and add overlays to links."
5961 (if (and (re-search-forward org-angle-link-re limit t)
5962 (not (org-in-src-block-p)))
5963 (progn
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (add-text-properties (match-beginning 0) (match-end 0)
5966 (list 'mouse-face 'highlight
5967 'keymap org-mouse-map))
5968 (org-rear-nonsticky-at (match-end 0))
5969 t)))
5971 (defun org-activate-footnote-links (limit)
5972 "Run through the buffer and add overlays to footnotes."
5973 (let ((fn (org-footnote-next-reference-or-definition limit)))
5974 (when fn
5975 (let* ((beg (nth 1 fn))
5976 (end (nth 2 fn))
5977 (label (car fn))
5978 (referencep (/= (line-beginning-position) beg)))
5979 (when (and referencep (nth 3 fn))
5980 (save-excursion
5981 (goto-char beg)
5982 (search-forward (or label "fn:"))
5983 (org-remove-flyspell-overlays-in beg (match-end 0))))
5984 (add-text-properties beg end
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map
5987 'help-echo
5988 (if referencep "Footnote reference"
5989 "Footnote definition")
5990 'font-lock-fontified t
5991 'font-lock-multiline t
5992 'face 'org-footnote))))))
5994 (defun org-activate-bracket-links (limit)
5995 "Run through the buffer and add overlays to bracketed links."
5996 (if (and (re-search-forward org-bracket-link-regexp limit t)
5997 (not (org-in-src-block-p)))
5998 (let* ((hl (org-match-string-no-properties 1))
5999 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6000 (ip (org-maybe-intangible
6001 (list 'invisible 'org-link
6002 'keymap org-mouse-map 'mouse-face 'highlight
6003 'font-lock-multiline t 'help-echo help
6004 'htmlize-link `(:uri ,hl))))
6005 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6006 'font-lock-multiline t 'help-echo help
6007 'htmlize-link `(:uri ,hl))))
6008 ;; We need to remove the invisible property here. Table narrowing
6009 ;; may have made some of this invisible.
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6011 (remove-text-properties (match-beginning 0) (match-end 0)
6012 '(invisible nil))
6013 (if (match-end 3)
6014 (progn
6015 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6016 (org-rear-nonsticky-at (match-beginning 3))
6017 (add-text-properties (match-beginning 3) (match-end 3) vp)
6018 (org-rear-nonsticky-at (match-end 3))
6019 (add-text-properties (match-end 3) (match-end 0) ip)
6020 (org-rear-nonsticky-at (match-end 0)))
6021 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6022 (org-rear-nonsticky-at (match-beginning 1))
6023 (add-text-properties (match-beginning 1) (match-end 1) vp)
6024 (org-rear-nonsticky-at (match-end 1))
6025 (add-text-properties (match-end 1) (match-end 0) ip)
6026 (org-rear-nonsticky-at (match-end 0)))
6027 t)))
6029 (defun org-activate-dates (limit)
6030 "Run through the buffer and add overlays to dates."
6031 (if (and (re-search-forward org-tsr-regexp-both limit t)
6032 (not (equal (char-before (match-beginning 0)) 91)))
6033 (progn
6034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6035 (add-text-properties (match-beginning 0) (match-end 0)
6036 (list 'mouse-face 'highlight
6037 'keymap org-mouse-map))
6038 (org-rear-nonsticky-at (match-end 0))
6039 (when org-display-custom-times
6040 (if (match-end 3)
6041 (org-display-custom-time (match-beginning 3) (match-end 3)))
6042 (org-display-custom-time (match-beginning 1) (match-end 1)))
6043 t)))
6045 (defvar org-target-link-regexp nil
6046 "Regular expression matching radio targets in plain text.")
6047 (make-variable-buffer-local 'org-target-link-regexp)
6048 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6049 "Regular expression matching a link target.")
6050 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6051 "Regular expression matching a radio target.")
6052 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6053 "Regular expression matching any target.")
6055 (defun org-activate-target-links (limit)
6056 "Run through the buffer and add overlays to target matches."
6057 (when org-target-link-regexp
6058 (let ((case-fold-search t))
6059 (if (re-search-forward org-target-link-regexp limit t)
6060 (progn
6061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (add-text-properties (match-beginning 0) (match-end 0)
6063 (list 'mouse-face 'highlight
6064 'keymap org-mouse-map
6065 'help-echo "Radio target link"
6066 'org-linked-text t))
6067 (org-rear-nonsticky-at (match-end 0))
6068 t)))))
6070 (defun org-update-radio-target-regexp ()
6071 "Find all radio targets in this file and update the regular expression."
6072 (interactive)
6073 (when (memq 'radio org-activate-links)
6074 (setq org-target-link-regexp
6075 (org-make-target-link-regexp (org-all-targets 'radio)))
6076 (org-restart-font-lock)))
6078 (defun org-hide-wide-columns (limit)
6079 (let (s e)
6080 (setq s (text-property-any (point) (or limit (point-max))
6081 'org-cwidth t))
6082 (when s
6083 (setq e (next-single-property-change s 'org-cwidth))
6084 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6085 (goto-char e)
6086 t)))
6088 (defvar org-latex-and-related-regexp nil
6089 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6090 (defvar org-match-substring-regexp)
6091 (defvar org-match-substring-with-braces-regexp)
6093 (defun org-compute-latex-and-related-regexp ()
6094 "Compute regular expression for LaTeX, entities and sub/superscript.
6095 Result depends on variable `org-highlight-latex-and-related'."
6096 (org-set-local
6097 'org-latex-and-related-regexp
6098 (let* ((re-sub
6099 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6100 ((eq org-use-sub-superscripts '{})
6101 (list org-match-substring-with-braces-regexp))
6102 (org-use-sub-superscripts (list org-match-substring-regexp))))
6103 (re-latex
6104 (when (memq 'latex org-highlight-latex-and-related)
6105 (let ((matchers (plist-get org-format-latex-options :matchers)))
6106 (delq nil
6107 (mapcar (lambda (x)
6108 (and (member (car x) matchers) (nth 1 x)))
6109 org-latex-regexps)))))
6110 (re-entities
6111 (when (memq 'entities org-highlight-latex-and-related)
6112 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6113 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6115 (defun org-do-latex-and-related (limit)
6116 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6117 LIMIT bounds the search for syntax to highlight. Stop at first
6118 highlighted object, if any. Return t if some highlighting was
6119 done, nil otherwise."
6120 (when (org-string-nw-p org-latex-and-related-regexp)
6121 (catch 'found
6122 (while (re-search-forward org-latex-and-related-regexp limit t)
6123 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6124 'face))
6125 '(org-code org-verbatim underline))
6126 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6127 '(?_ ?^))
6129 0)))
6130 (font-lock-prepend-text-property
6131 (+ offset (match-beginning 0)) (match-end 0)
6132 'face 'org-latex-and-related)
6133 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6134 '(font-lock-multiline t)))
6135 (throw 'found t)))
6136 nil)))
6138 (defun org-restart-font-lock ()
6139 "Restart `font-lock-mode', to force refontification."
6140 (when (and (boundp 'font-lock-mode) font-lock-mode)
6141 (font-lock-mode -1)
6142 (font-lock-mode 1)))
6144 (defun org-all-targets (&optional radio)
6145 "Return a list of all targets in this file.
6146 When optional argument RADIO is non-nil, only find radio
6147 targets."
6148 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6149 (save-excursion
6150 (goto-char (point-min))
6151 (while (re-search-forward re nil t)
6152 ;; Make sure point is really within the object.
6153 (backward-char)
6154 (let ((obj (org-element-context)))
6155 (when (memq (org-element-type obj) '(radio-target target))
6156 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6157 rtn)))
6159 (defun org-make-target-link-regexp (targets)
6160 "Make regular expression matching all strings in TARGETS.
6161 The regular expression finds the targets also if there is a line break
6162 between words."
6163 (and targets
6164 (concat
6165 "\\<\\("
6166 (mapconcat
6167 (lambda (x)
6168 (setq x (regexp-quote x))
6169 (while (string-match " +" x)
6170 (setq x (replace-match "\\s-+" t t x)))
6172 targets
6173 "\\|")
6174 "\\)\\>")))
6176 (defun org-activate-tags (limit)
6177 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6178 (progn
6179 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6180 (add-text-properties (match-beginning 1) (match-end 1)
6181 (list 'mouse-face 'highlight
6182 'keymap org-mouse-map))
6183 (org-rear-nonsticky-at (match-end 1))
6184 t)))
6186 (defun org-outline-level ()
6187 "Compute the outline level of the heading at point.
6188 If this is called at a normal headline, the level is the number of stars.
6189 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6190 (save-excursion
6191 (if (not (condition-case nil
6192 (org-back-to-heading t)
6193 (error nil)))
6195 (looking-at org-outline-regexp)
6196 (1- (- (match-end 0) (match-beginning 0))))))
6198 (defvar org-font-lock-keywords nil)
6200 (defsubst org-re-property (property &optional literal)
6201 "Return a regexp matching a PROPERTY line.
6202 Match group 3 will be set to the value if it exists."
6203 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6204 (if literal property (regexp-quote property))
6205 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6207 (defconst org-property-re
6208 (org-re-property ".*?" 'literal)
6209 "Regular expression matching a property line.
6210 There are four matching groups:
6211 1: :PROPKEY: including the leading and trailing colon,
6212 2: PROPKEY without the leading and trailing colon,
6213 3: PROPVAL without leading or trailing spaces,
6214 4: the indentation of the current line,
6215 5: trailing whitespace.")
6217 (defvar org-font-lock-hook nil
6218 "Functions to be called for special font lock stuff.")
6220 (defvar org-font-lock-set-keywords-hook nil
6221 "Functions that can manipulate `org-font-lock-extra-keywords'.
6222 This is called after `org-font-lock-extra-keywords' is defined, but before
6223 it is installed to be used by font lock. This can be useful if something
6224 needs to be inserted at a specific position in the font-lock sequence.")
6226 (defun org-font-lock-hook (limit)
6227 "Run `org-font-lock-hook' within LIMIT."
6228 (run-hook-with-args 'org-font-lock-hook limit))
6230 (defun org-set-font-lock-defaults ()
6231 "Set font lock defaults for the current buffer."
6232 (let* ((em org-fontify-emphasized-text)
6233 (lk org-activate-links)
6234 (org-font-lock-extra-keywords
6235 (list
6236 ;; Call the hook
6237 '(org-font-lock-hook)
6238 ;; Headlines
6239 `(,(if org-fontify-whole-heading-line
6240 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6241 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6242 (1 (org-get-level-face 1))
6243 (2 (org-get-level-face 2))
6244 (3 (org-get-level-face 3)))
6245 ;; Table lines
6246 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6247 (1 'org-table t))
6248 ;; Table internals
6249 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6250 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6251 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6252 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6253 ;; Drawers
6254 '(org-fontify-drawers)
6255 ;; Properties
6256 (list org-property-re
6257 '(1 'org-special-keyword t)
6258 '(3 'org-property-value t))
6259 ;; Links
6260 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6261 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6262 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6263 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6264 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6265 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6266 (if (memq 'footnote lk) '(org-activate-footnote-links))
6267 ;; Targets.
6268 (list org-any-target-regexp '(0 'org-target t))
6269 ;; Diary sexps.
6270 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6271 ;; Macro
6272 '("{{{.+?}}}" (0 'org-macro t))
6273 '(org-hide-wide-columns (0 nil append))
6274 ;; TODO keyword
6275 (list (format org-heading-keyword-regexp-format
6276 org-todo-regexp)
6277 '(2 (org-get-todo-face 2) t))
6278 ;; DONE
6279 (if org-fontify-done-headline
6280 (list (format org-heading-keyword-regexp-format
6281 (concat
6282 "\\(?:"
6283 (mapconcat 'regexp-quote org-done-keywords "\\|")
6284 "\\)"))
6285 '(2 'org-headline-done t))
6286 nil)
6287 ;; Priorities
6288 '(org-font-lock-add-priority-faces)
6289 ;; Tags
6290 '(org-font-lock-add-tag-faces)
6291 ;; Tags groups
6292 (if (and org-group-tags org-tag-groups-alist)
6293 (list (concat org-outline-regexp-bol ".+\\(:"
6294 (regexp-opt (mapcar 'car org-tag-groups-alist))
6295 ":\\).*$")
6296 '(1 'org-tag-group prepend)))
6297 ;; Special keywords
6298 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6299 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6300 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6301 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6302 ;; Emphasis
6303 (if em
6304 (if (featurep 'xemacs)
6305 '(org-do-emphasis-faces (0 nil append))
6306 '(org-do-emphasis-faces)))
6307 ;; Checkboxes
6308 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6309 1 'org-checkbox prepend)
6310 (if (cdr (assq 'checkbox org-list-automatic-rules))
6311 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6312 (0 (org-get-checkbox-statistics-face) t)))
6313 ;; Description list items
6314 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6315 1 'org-list-dt prepend)
6316 ;; ARCHIVEd headings
6317 (list (concat
6318 org-outline-regexp-bol
6319 "\\(.*:" org-archive-tag ":.*\\)")
6320 '(1 'org-archived prepend))
6321 ;; Specials
6322 '(org-do-latex-and-related)
6323 '(org-fontify-entities)
6324 '(org-raise-scripts)
6325 ;; Code
6326 '(org-activate-code (1 'org-code t))
6327 ;; COMMENT
6328 (list (format org-heading-keyword-regexp-format
6329 (concat "\\("
6330 org-comment-string "\\|" org-quote-string
6331 "\\)"))
6332 '(2 'org-special-keyword t))
6333 ;; Blocks and meta lines
6334 '(org-fontify-meta-lines-and-blocks))))
6335 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6336 (run-hooks 'org-font-lock-set-keywords-hook)
6337 ;; Now set the full font-lock-keywords
6338 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6339 (org-set-local 'font-lock-defaults
6340 '(org-font-lock-keywords t nil nil backward-paragraph))
6341 (kill-local-variable 'font-lock-keywords) nil))
6343 (defun org-toggle-pretty-entities ()
6344 "Toggle the composition display of entities as UTF8 characters."
6345 (interactive)
6346 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6347 (org-restart-font-lock)
6348 (if org-pretty-entities
6349 (message "Entities are now displayed as UTF8 characters")
6350 (save-restriction
6351 (widen)
6352 (org-decompose-region (point-min) (point-max))
6353 (message "Entities are now displayed as plain text"))))
6355 (defvar org-custom-properties-overlays nil
6356 "List of overlays used for custom properties.")
6357 (make-variable-buffer-local 'org-custom-properties-overlays)
6359 (defun org-toggle-custom-properties-visibility ()
6360 "Display or hide properties in `org-custom-properties'."
6361 (interactive)
6362 (if org-custom-properties-overlays
6363 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6364 (setq org-custom-properties-overlays nil))
6365 (unless (not org-custom-properties)
6366 (save-excursion
6367 (save-restriction
6368 (widen)
6369 (goto-char (point-min))
6370 (while (re-search-forward org-property-re nil t)
6371 (mapc (lambda(p)
6372 (when (equal p (substring (match-string 1) 1 -1))
6373 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6374 (overlay-put o 'invisible t)
6375 (overlay-put o 'org-custom-property t)
6376 (push o org-custom-properties-overlays))))
6377 org-custom-properties)))))))
6379 (defun org-fontify-entities (limit)
6380 "Find an entity to fontify."
6381 (let (ee)
6382 (when org-pretty-entities
6383 (catch 'match
6384 (while (re-search-forward
6385 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6386 limit t)
6387 (if (and (not (org-in-indented-comment-line))
6388 (setq ee (org-entity-get (match-string 1)))
6389 (= (length (nth 6 ee)) 1))
6390 (let*
6391 ((end (if (equal (match-string 2) "{}")
6392 (match-end 2)
6393 (match-end 1))))
6394 (add-text-properties
6395 (match-beginning 0) end
6396 (list 'font-lock-fontified t))
6397 (compose-region (match-beginning 0) end
6398 (nth 6 ee) nil)
6399 (backward-char 1)
6400 (throw 'match t))))
6401 nil))))
6403 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6404 "Fontify string S like in Org-mode."
6405 (with-temp-buffer
6406 (insert s)
6407 (let ((org-odd-levels-only odd-levels))
6408 (org-mode)
6409 (font-lock-fontify-buffer)
6410 (buffer-string))))
6412 (defvar org-m nil)
6413 (defvar org-l nil)
6414 (defvar org-f nil)
6415 (defun org-get-level-face (n)
6416 "Get the right face for match N in font-lock matching of headlines."
6417 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6418 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6419 (if org-cycle-level-faces
6420 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6421 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6422 (cond
6423 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6424 ((eq n 2) org-f)
6425 (t (if org-level-color-stars-only nil org-f))))
6428 (defun org-get-todo-face (kwd)
6429 "Get the right face for a TODO keyword KWD.
6430 If KWD is a number, get the corresponding match group."
6431 (if (numberp kwd) (setq kwd (match-string kwd)))
6432 (or (org-face-from-face-or-color
6433 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6434 (and (member kwd org-done-keywords) 'org-done)
6435 'org-todo))
6437 (defun org-face-from-face-or-color (context inherit face-or-color)
6438 "Create a face list that inherits INHERIT, but sets the foreground color.
6439 When FACE-OR-COLOR is not a string, just return it."
6440 (if (stringp face-or-color)
6441 (list :inherit inherit
6442 (cdr (assoc context org-faces-easy-properties))
6443 face-or-color)
6444 face-or-color))
6446 (defun org-font-lock-add-tag-faces (limit)
6447 "Add the special tag faces."
6448 (when (and org-tag-faces org-tags-special-faces-re)
6449 (while (re-search-forward org-tags-special-faces-re limit t)
6450 (add-text-properties (match-beginning 1) (match-end 1)
6451 (list 'face (org-get-tag-face 1)
6452 'font-lock-fontified t))
6453 (backward-char 1))))
6455 (defun org-font-lock-add-priority-faces (limit)
6456 "Add the special priority faces."
6457 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6458 (when (save-match-data (org-at-heading-p))
6459 (add-text-properties
6460 (match-beginning 0) (match-end 0)
6461 (list 'face (or (org-face-from-face-or-color
6462 'priority 'org-priority
6463 (cdr (assoc (char-after (match-beginning 1))
6464 org-priority-faces)))
6465 'org-priority)
6466 'font-lock-fontified t)))))
6468 (defun org-get-tag-face (kwd)
6469 "Get the right face for a TODO keyword KWD.
6470 If KWD is a number, get the corresponding match group."
6471 (if (numberp kwd) (setq kwd (match-string kwd)))
6472 (or (org-face-from-face-or-color
6473 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6474 'org-tag))
6476 (defun org-unfontify-region (beg end &optional maybe_loudly)
6477 "Remove fontification and activation overlays from links."
6478 (font-lock-default-unfontify-region beg end)
6479 (let* ((buffer-undo-list t)
6480 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6481 (inhibit-modification-hooks t)
6482 deactivate-mark buffer-file-name buffer-file-truename)
6483 (org-decompose-region beg end)
6484 (remove-text-properties beg end
6485 '(mouse-face t keymap t org-linked-text t
6486 invisible t intangible t
6487 org-emphasis t))
6488 (org-remove-font-lock-display-properties beg end)))
6490 (defconst org-script-display '(((raise -0.3) (height 0.7))
6491 ((raise 0.3) (height 0.7))
6492 ((raise -0.5))
6493 ((raise 0.5)))
6494 "Display properties for showing superscripts and subscripts.")
6496 (defun org-remove-font-lock-display-properties (beg end)
6497 "Remove specific display properties that have been added by font lock.
6498 The will remove the raise properties that are used to show superscripts
6499 and subscripts."
6500 (let (next prop)
6501 (while (< beg end)
6502 (setq next (next-single-property-change beg 'display nil end)
6503 prop (get-text-property beg 'display))
6504 (if (member prop org-script-display)
6505 (put-text-property beg next 'display nil))
6506 (setq beg next))))
6508 (defun org-raise-scripts (limit)
6509 "Add raise properties to sub/superscripts."
6510 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6511 (if (re-search-forward
6512 (if (eq org-use-sub-superscripts t)
6513 org-match-substring-regexp
6514 org-match-substring-with-braces-regexp)
6515 limit t)
6516 (let* ((pos (point)) table-p comment-p
6517 (mpos (match-beginning 3))
6518 (emph-p (get-text-property mpos 'org-emphasis))
6519 (link-p (get-text-property mpos 'mouse-face))
6520 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6521 (goto-char (point-at-bol))
6522 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6523 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6524 (goto-char pos)
6525 ;; Handle a_b^c
6526 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6527 (if (or comment-p emph-p link-p keyw-p)
6529 (put-text-property (match-beginning 3) (match-end 0)
6530 'display
6531 (if (equal (char-after (match-beginning 2)) ?^)
6532 (nth (if table-p 3 1) org-script-display)
6533 (nth (if table-p 2 0) org-script-display)))
6534 (add-text-properties (match-beginning 2) (match-end 2)
6535 (list 'invisible t
6536 'org-dwidth t 'org-dwidth-n 1))
6537 (if (and (eq (char-after (match-beginning 3)) ?{)
6538 (eq (char-before (match-end 3)) ?}))
6539 (progn
6540 (add-text-properties
6541 (match-beginning 3) (1+ (match-beginning 3))
6542 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6543 (add-text-properties
6544 (1- (match-end 3)) (match-end 3)
6545 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6546 t)))))
6548 ;;;; Visibility cycling, including org-goto and indirect buffer
6550 ;;; Cycling
6552 (defvar org-cycle-global-status nil)
6553 (make-variable-buffer-local 'org-cycle-global-status)
6554 (put 'org-cycle-global-status 'org-state t)
6555 (defvar org-cycle-subtree-status nil)
6556 (make-variable-buffer-local 'org-cycle-subtree-status)
6557 (put 'org-cycle-subtree-status 'org-state t)
6559 (defvar org-inlinetask-min-level)
6561 (defun org-unlogged-message (&rest args)
6562 "Display a message, but avoid logging it in the *Messages* buffer."
6563 (let ((message-log-max nil))
6564 (apply 'message args)))
6566 ;;;###autoload
6567 (defun org-cycle (&optional arg)
6568 "TAB-action and visibility cycling for Org-mode.
6570 This is the command invoked in Org-mode by the TAB key. Its main purpose
6571 is outline visibility cycling, but it also invokes other actions
6572 in special contexts.
6574 - When this function is called with a prefix argument, rotate the entire
6575 buffer through 3 states (global cycling)
6576 1. OVERVIEW: Show only top-level headlines.
6577 2. CONTENTS: Show all headlines of all levels, but no body text.
6578 3. SHOW ALL: Show everything.
6579 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6580 determined by the variable `org-startup-folded', and by any VISIBILITY
6581 properties in the buffer.
6582 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6583 including any drawers.
6585 - When inside a table, re-align the table and move to the next field.
6587 - When point is at the beginning of a headline, rotate the subtree started
6588 by this line through 3 different states (local cycling)
6589 1. FOLDED: Only the main headline is shown.
6590 2. CHILDREN: The main headline and the direct children are shown.
6591 From this state, you can move to one of the children
6592 and zoom in further.
6593 3. SUBTREE: Show the entire subtree, including body text.
6594 If there is no subtree, switch directly from CHILDREN to FOLDED.
6596 - When point is at the beginning of an empty headline and the variable
6597 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6598 of the headline by demoting and promoting it to likely levels. This
6599 speeds up creation document structure by pressing TAB once or several
6600 times right after creating a new headline.
6602 - When there is a numeric prefix, go up to a heading with level ARG, do
6603 a `show-subtree' and return to the previous cursor position. If ARG
6604 is negative, go up that many levels.
6606 - When point is not at the beginning of a headline, execute the global
6607 binding for TAB, which is re-indenting the line. See the option
6608 `org-cycle-emulate-tab' for details.
6610 - Special case: if point is at the beginning of the buffer and there is
6611 no headline in line 1, this function will act as if called with prefix arg
6612 (C-u TAB, same as S-TAB) also when called without prefix arg.
6613 But only if also the variable `org-cycle-global-at-bob' is t."
6614 (interactive "P")
6615 (org-load-modules-maybe)
6616 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6617 (and org-cycle-level-after-item/entry-creation
6618 (or (org-cycle-level)
6619 (org-cycle-item-indentation))))
6620 (let* ((limit-level
6621 (or org-cycle-max-level
6622 (and (boundp 'org-inlinetask-min-level)
6623 org-inlinetask-min-level
6624 (1- org-inlinetask-min-level))))
6625 (nstars (and limit-level
6626 (if org-odd-levels-only
6627 (and limit-level (1- (* limit-level 2)))
6628 limit-level)))
6629 (org-outline-regexp
6630 (if (not (derived-mode-p 'org-mode))
6631 outline-regexp
6632 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6633 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6634 (not (looking-at org-outline-regexp))))
6635 (org-cycle-hook
6636 (if bob-special
6637 (delq 'org-optimize-window-after-visibility-change
6638 (copy-sequence org-cycle-hook))
6639 org-cycle-hook))
6640 (pos (point)))
6642 (if (or bob-special (equal arg '(4)))
6643 ;; special case: use global cycling
6644 (setq arg t))
6646 (cond
6648 ((equal arg '(16))
6649 (setq last-command 'dummy)
6650 (org-set-startup-visibility)
6651 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6653 ((equal arg '(64))
6654 (show-all)
6655 (org-unlogged-message "Entire buffer visible, including drawers"))
6657 ;; Table: enter it or move to the next field.
6658 ((org-at-table-p 'any)
6659 (if (org-at-table.el-p)
6660 (message "Use C-c ' to edit table.el tables")
6661 (if arg (org-table-edit-field t)
6662 (org-table-justify-field-maybe)
6663 (call-interactively 'org-table-next-field))))
6665 ((run-hook-with-args-until-success
6666 'org-tab-after-check-for-table-hook))
6668 ;; Global cycling: delegate to `org-cycle-internal-global'.
6669 ((eq arg t) (org-cycle-internal-global))
6671 ;; Drawers: delegate to `org-flag-drawer'.
6672 ((save-excursion
6673 (beginning-of-line 1)
6674 (looking-at org-drawer-regexp))
6675 (org-flag-drawer ; toggle block visibility
6676 (not (get-char-property (match-end 0) 'invisible))))
6678 ;; Show-subtree, ARG levels up from here.
6679 ((integerp arg)
6680 (save-excursion
6681 (org-back-to-heading)
6682 (outline-up-heading (if (< arg 0) (- arg)
6683 (- (funcall outline-level) arg)))
6684 (org-show-subtree)))
6686 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6687 ((and (featurep 'org-inlinetask)
6688 (org-inlinetask-at-task-p)
6689 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6690 (org-inlinetask-toggle-visibility))
6692 ((org-try-cdlatex-tab))
6694 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6695 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6696 (save-excursion (beginning-of-line 1)
6697 (looking-at org-outline-regexp)))
6698 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6699 (org-cycle-internal-local))
6701 ;; From there: TAB emulation and template completion.
6702 (buffer-read-only (org-back-to-heading))
6704 ((run-hook-with-args-until-success
6705 'org-tab-after-check-for-cycling-hook))
6707 ((org-try-structure-completion))
6709 ((run-hook-with-args-until-success
6710 'org-tab-before-tab-emulation-hook))
6712 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6713 (or (not (bolp))
6714 (not (looking-at org-outline-regexp))))
6715 (call-interactively (global-key-binding "\t")))
6717 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6718 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6719 (or (and (eq org-cycle-emulate-tab 'white)
6720 (= (match-end 0) (point-at-eol)))
6721 (and (eq org-cycle-emulate-tab 'whitestart)
6722 (>= (match-end 0) pos))))
6724 (eq org-cycle-emulate-tab t))
6725 (call-interactively (global-key-binding "\t")))
6727 (t (save-excursion
6728 (org-back-to-heading)
6729 (org-cycle)))))))
6731 (defun org-cycle-internal-global ()
6732 "Do the global cycling action."
6733 ;; Hack to avoid display of messages for .org attachments in Gnus
6734 (let ((ga (string-match "\\*fontification" (buffer-name))))
6735 (cond
6736 ((and (eq last-command this-command)
6737 (eq org-cycle-global-status 'overview))
6738 ;; We just created the overview - now do table of contents
6739 ;; This can be slow in very large buffers, so indicate action
6740 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6741 (unless ga (org-unlogged-message "CONTENTS..."))
6742 (org-content)
6743 (unless ga (org-unlogged-message "CONTENTS...done"))
6744 (setq org-cycle-global-status 'contents)
6745 (run-hook-with-args 'org-cycle-hook 'contents))
6747 ((and (eq last-command this-command)
6748 (eq org-cycle-global-status 'contents))
6749 ;; We just showed the table of contents - now show everything
6750 (run-hook-with-args 'org-pre-cycle-hook 'all)
6751 (show-all)
6752 (unless ga (org-unlogged-message "SHOW ALL"))
6753 (setq org-cycle-global-status 'all)
6754 (run-hook-with-args 'org-cycle-hook 'all))
6757 ;; Default action: go to overview
6758 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6759 (org-overview)
6760 (unless ga (org-unlogged-message "OVERVIEW"))
6761 (setq org-cycle-global-status 'overview)
6762 (run-hook-with-args 'org-cycle-hook 'overview)))))
6764 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6766 (defun org-cycle-internal-local ()
6767 "Do the local cycling action."
6768 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6769 ;; First, determine end of headline (EOH), end of subtree or item
6770 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6771 (save-excursion
6772 (if (org-at-item-p)
6773 (progn
6774 (beginning-of-line)
6775 (setq struct (org-list-struct))
6776 (setq eoh (point-at-eol))
6777 (setq eos (org-list-get-item-end-before-blank (point) struct))
6778 (setq has-children (org-list-has-child-p (point) struct)))
6779 (org-back-to-heading)
6780 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6781 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6782 (setq has-children
6783 (or (save-excursion
6784 (let ((level (funcall outline-level)))
6785 (outline-next-heading)
6786 (and (org-at-heading-p t)
6787 (> (funcall outline-level) level))))
6788 (save-excursion
6789 (org-list-search-forward (org-item-beginning-re) eos t)))))
6790 ;; Determine end invisible part of buffer (EOL)
6791 (beginning-of-line 2)
6792 ;; XEmacs doesn't have `next-single-char-property-change'
6793 (if (featurep 'xemacs)
6794 (while (and (not (eobp)) ;; this is like `next-line'
6795 (get-char-property (1- (point)) 'invisible))
6796 (beginning-of-line 2))
6797 (while (and (not (eobp)) ;; this is like `next-line'
6798 (get-char-property (1- (point)) 'invisible))
6799 (goto-char (next-single-char-property-change (point) 'invisible))
6800 (and (eolp) (beginning-of-line 2))))
6801 (setq eol (point)))
6802 ;; Find out what to do next and set `this-command'
6803 (cond
6804 ((= eos eoh)
6805 ;; Nothing is hidden behind this heading
6806 (unless (org-before-first-heading-p)
6807 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6808 (org-unlogged-message "EMPTY ENTRY")
6809 (setq org-cycle-subtree-status nil)
6810 (save-excursion
6811 (goto-char eos)
6812 (outline-next-heading)
6813 (if (outline-invisible-p) (org-flag-heading nil))))
6814 ((and (or (>= eol eos)
6815 (not (string-match "\\S-" (buffer-substring eol eos))))
6816 (or has-children
6817 (not (setq children-skipped
6818 org-cycle-skip-children-state-if-no-children))))
6819 ;; Entire subtree is hidden in one line: children view
6820 (unless (org-before-first-heading-p)
6821 (run-hook-with-args 'org-pre-cycle-hook 'children))
6822 (if (org-at-item-p)
6823 (org-list-set-item-visibility (point-at-bol) struct 'children)
6824 (org-show-entry)
6825 (org-with-limited-levels (show-children))
6826 ;; FIXME: This slows down the func way too much.
6827 ;; How keep drawers hidden in subtree anyway?
6828 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6829 ;; (org-cycle-hide-drawers 'subtree))
6831 ;; Fold every list in subtree to top-level items.
6832 (when (eq org-cycle-include-plain-lists 'integrate)
6833 (save-excursion
6834 (org-back-to-heading)
6835 (while (org-list-search-forward (org-item-beginning-re) eos t)
6836 (beginning-of-line 1)
6837 (let* ((struct (org-list-struct))
6838 (prevs (org-list-prevs-alist struct))
6839 (end (org-list-get-bottom-point struct)))
6840 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6841 (org-list-get-all-items (point) struct prevs))
6842 (goto-char (if (< end eos) end eos)))))))
6843 (org-unlogged-message "CHILDREN")
6844 (save-excursion
6845 (goto-char eos)
6846 (outline-next-heading)
6847 (if (outline-invisible-p) (org-flag-heading nil)))
6848 (setq org-cycle-subtree-status 'children)
6849 (unless (org-before-first-heading-p)
6850 (run-hook-with-args 'org-cycle-hook 'children)))
6851 ((or children-skipped
6852 (and (eq last-command this-command)
6853 (eq org-cycle-subtree-status 'children)))
6854 ;; We just showed the children, or no children are there,
6855 ;; now show everything.
6856 (unless (org-before-first-heading-p)
6857 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6858 (outline-flag-region eoh eos nil)
6859 (org-unlogged-message
6860 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6861 (setq org-cycle-subtree-status 'subtree)
6862 (unless (org-before-first-heading-p)
6863 (run-hook-with-args 'org-cycle-hook 'subtree)))
6865 ;; Default action: hide the subtree.
6866 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6867 (outline-flag-region eoh eos t)
6868 (org-unlogged-message "FOLDED")
6869 (setq org-cycle-subtree-status 'folded)
6870 (unless (org-before-first-heading-p)
6871 (run-hook-with-args 'org-cycle-hook 'folded))))))
6873 ;;;###autoload
6874 (defun org-global-cycle (&optional arg)
6875 "Cycle the global visibility. For details see `org-cycle'.
6876 With \\[universal-argument] prefix arg, switch to startup visibility.
6877 With a numeric prefix, show all headlines up to that level."
6878 (interactive "P")
6879 (let ((org-cycle-include-plain-lists
6880 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6881 (cond
6882 ((integerp arg)
6883 (show-all)
6884 (hide-sublevels arg)
6885 (setq org-cycle-global-status 'contents))
6886 ((equal arg '(4))
6887 (org-set-startup-visibility)
6888 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6890 (org-cycle '(4))))))
6892 (defun org-set-startup-visibility ()
6893 "Set the visibility required by startup options and properties."
6894 (cond
6895 ((eq org-startup-folded t)
6896 (org-cycle '(4)))
6897 ((eq org-startup-folded 'content)
6898 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6899 (org-cycle '(4)) (org-cycle '(4)))))
6900 (unless (eq org-startup-folded 'showeverything)
6901 (if org-hide-block-startup (org-hide-block-all))
6902 (org-set-visibility-according-to-property 'no-cleanup)
6903 (org-cycle-hide-archived-subtrees 'all)
6904 (org-cycle-hide-drawers 'all)
6905 (org-cycle-show-empty-lines t)))
6907 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6908 "Switch subtree visibilities according to :VISIBILITY: property."
6909 (interactive)
6910 (let (org-show-entry-below state)
6911 (save-excursion
6912 (goto-char (point-min))
6913 (while (re-search-forward
6914 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6915 nil t)
6916 (setq state (match-string 1))
6917 (save-excursion
6918 (org-back-to-heading t)
6919 (hide-subtree)
6920 (org-reveal)
6921 (cond
6922 ((equal state '("fold" "folded"))
6923 (hide-subtree))
6924 ((equal state "children")
6925 (org-show-hidden-entry)
6926 (show-children))
6927 ((equal state "content")
6928 (save-excursion
6929 (save-restriction
6930 (org-narrow-to-subtree)
6931 (org-content))))
6932 ((member state '("all" "showall"))
6933 (show-subtree)))))
6934 (unless no-cleanup
6935 (org-cycle-hide-archived-subtrees 'all)
6936 (org-cycle-hide-drawers 'all)
6937 (org-cycle-show-empty-lines 'all)))))
6939 ;; This function uses outline-regexp instead of the more fundamental
6940 ;; org-outline-regexp so that org-cycle-global works outside of Org
6941 ;; buffers, where outline-regexp is needed.
6942 (defun org-overview ()
6943 "Switch to overview mode, showing only top-level headlines.
6944 Really, this shows all headlines with level equal or greater than the level
6945 of the first headline in the buffer. This is important, because if the
6946 first headline is not level one, then (hide-sublevels 1) gives confusing
6947 results."
6948 (interactive)
6949 (let ((pos (point))
6950 (level (save-excursion
6951 (goto-char (point-min))
6952 (if (re-search-forward (concat "^" outline-regexp) nil t)
6953 (progn
6954 (goto-char (match-beginning 0))
6955 (funcall outline-level))))))
6956 (and level (hide-sublevels level))
6957 (recenter '(4))
6958 (goto-char pos)))
6960 (defun org-content (&optional arg)
6961 "Show all headlines in the buffer, like a table of contents.
6962 With numerical argument N, show content up to level N."
6963 (interactive "P")
6964 (save-excursion
6965 ;; Visit all headings and show their offspring
6966 (and (integerp arg) (org-overview))
6967 (goto-char (point-max))
6968 (catch 'exit
6969 (while (and (progn (condition-case nil
6970 (outline-previous-visible-heading 1)
6971 (error (goto-char (point-min))))
6973 (looking-at org-outline-regexp))
6974 (if (integerp arg)
6975 (show-children (1- arg))
6976 (show-branches))
6977 (if (bobp) (throw 'exit nil))))))
6980 (defun org-optimize-window-after-visibility-change (state)
6981 "Adjust the window after a change in outline visibility.
6982 This function is the default value of the hook `org-cycle-hook'."
6983 (when (get-buffer-window (current-buffer))
6984 (cond
6985 ((eq state 'content) nil)
6986 ((eq state 'all) nil)
6987 ((eq state 'folded) nil)
6988 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6989 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6991 (defun org-remove-empty-overlays-at (pos)
6992 "Remove outline overlays that do not contain non-white stuff."
6993 (mapc
6994 (lambda (o)
6995 (and (eq 'outline (overlay-get o 'invisible))
6996 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6997 (overlay-end o))))
6998 (delete-overlay o)))
6999 (overlays-at pos)))
7001 (defun org-clean-visibility-after-subtree-move ()
7002 "Fix visibility issues after moving a subtree."
7003 ;; First, find a reasonable region to look at:
7004 ;; Start two siblings above, end three below
7005 (let* ((beg (save-excursion
7006 (and (org-get-last-sibling)
7007 (org-get-last-sibling))
7008 (point)))
7009 (end (save-excursion
7010 (and (org-get-next-sibling)
7011 (org-get-next-sibling)
7012 (org-get-next-sibling))
7013 (if (org-at-heading-p)
7014 (point-at-eol)
7015 (point))))
7016 (level (looking-at "\\*+"))
7017 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7018 (save-excursion
7019 (save-restriction
7020 (narrow-to-region beg end)
7021 (when re
7022 ;; Properly fold already folded siblings
7023 (goto-char (point-min))
7024 (while (re-search-forward re nil t)
7025 (if (and (not (outline-invisible-p))
7026 (save-excursion
7027 (goto-char (point-at-eol)) (outline-invisible-p)))
7028 (hide-entry))))
7029 (org-cycle-show-empty-lines 'overview)
7030 (org-cycle-hide-drawers 'overview)))))
7032 (defun org-cycle-show-empty-lines (state)
7033 "Show empty lines above all visible headlines.
7034 The region to be covered depends on STATE when called through
7035 `org-cycle-hook'. Lisp program can use t for STATE to get the
7036 entire buffer covered. Note that an empty line is only shown if there
7037 are at least `org-cycle-separator-lines' empty lines before the headline."
7038 (when (not (= org-cycle-separator-lines 0))
7039 (save-excursion
7040 (let* ((n (abs org-cycle-separator-lines))
7041 (re (cond
7042 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7043 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7044 (t (let ((ns (number-to-string (- n 2))))
7045 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7046 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7047 beg end b e)
7048 (cond
7049 ((memq state '(overview contents t))
7050 (setq beg (point-min) end (point-max)))
7051 ((memq state '(children folded))
7052 (setq beg (point) end (progn (org-end-of-subtree t t)
7053 (beginning-of-line 2)
7054 (point)))))
7055 (when beg
7056 (goto-char beg)
7057 (while (re-search-forward re end t)
7058 (unless (get-char-property (match-end 1) 'invisible)
7059 (setq e (match-end 1))
7060 (if (< org-cycle-separator-lines 0)
7061 (setq b (save-excursion
7062 (goto-char (match-beginning 0))
7063 (org-back-over-empty-lines)
7064 (if (save-excursion
7065 (goto-char (max (point-min) (1- (point))))
7066 (org-at-heading-p))
7067 (1- (point))
7068 (point))))
7069 (setq b (match-beginning 1)))
7070 (outline-flag-region b e nil)))))))
7071 ;; Never hide empty lines at the end of the file.
7072 (save-excursion
7073 (goto-char (point-max))
7074 (outline-previous-heading)
7075 (outline-end-of-heading)
7076 (if (and (looking-at "[ \t\n]+")
7077 (= (match-end 0) (point-max)))
7078 (outline-flag-region (point) (match-end 0) nil))))
7080 (defun org-show-empty-lines-in-parent ()
7081 "Move to the parent and re-show empty lines before visible headlines."
7082 (save-excursion
7083 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7084 (org-cycle-show-empty-lines context))))
7086 (defun org-files-list ()
7087 "Return `org-agenda-files' list, plus all open org-mode files.
7088 This is useful for operations that need to scan all of a user's
7089 open and agenda-wise Org files."
7090 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7091 (dolist (buf (buffer-list))
7092 (with-current-buffer buf
7093 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7094 (let ((file (expand-file-name (buffer-file-name))))
7095 (unless (member file files)
7096 (push file files))))))
7097 files))
7099 (defsubst org-entry-beginning-position ()
7100 "Return the beginning position of the current entry."
7101 (save-excursion (outline-back-to-heading t) (point)))
7103 (defsubst org-entry-end-position ()
7104 "Return the end position of the current entry."
7105 (save-excursion (outline-next-heading) (point)))
7107 (defun org-cycle-hide-drawers (state &optional exceptions)
7108 "Re-hide all drawers after a visibility state change.
7109 When non-nil, optional argument EXCEPTIONS is a list of strings
7110 specifying which drawers should not be hidden."
7111 (when (and (derived-mode-p 'org-mode)
7112 (not (memq state '(overview folded contents))))
7113 (save-excursion
7114 (let* ((globalp (memq state '(contents all)))
7115 (beg (if globalp (point-min) (point)))
7116 (end (if globalp (point-max)
7117 (if (eq state 'children)
7118 (save-excursion (outline-next-heading) (point))
7119 (org-end-of-subtree t)))))
7120 (goto-char beg)
7121 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7122 (unless (member-ignore-case (match-string 1) exceptions)
7123 (let ((drawer (org-element-at-point)))
7124 (when (memq (org-element-type drawer) '(drawer property-drawer))
7125 (org-flag-drawer t drawer)
7126 ;; Make sure to skip drawer entirely or we might flag
7127 ;; it another time when matching its ending line with
7128 ;; `org-drawer-regexp'.
7129 (goto-char (org-element-property :end drawer))))))))))
7131 (defun org-cycle-hide-inline-tasks (state)
7132 "Re-hide inline tasks when switching to 'contents or 'children
7133 visibility state."
7134 (case state
7135 (contents
7136 (when (org-bound-and-true-p org-inlinetask-min-level)
7137 (hide-sublevels (1- org-inlinetask-min-level))))
7138 (children
7139 (when (featurep 'org-inlinetask)
7140 (save-excursion
7141 (while (and (outline-next-heading)
7142 (org-inlinetask-at-task-p))
7143 (org-inlinetask-toggle-visibility)
7144 (org-inlinetask-goto-end)))))))
7146 (defun org-flag-drawer (flag &optional element)
7147 "When FLAG is non-nil, hide the drawer we are at.
7148 Otherwise make it visible. When optional argument ELEMENT is
7149 a parsed drawer, as returned by `org-element-at-point', hide or
7150 show that drawer instead."
7151 (let ((drawer (or element (org-element-at-point))))
7152 (when (memq (org-element-type drawer) '(drawer property-drawer))
7153 (save-excursion
7154 (goto-char (org-element-property :post-affiliated drawer))
7155 (outline-flag-region
7156 (line-end-position)
7157 (progn (goto-char (org-element-property :end drawer))
7158 (skip-chars-backward " \r\t\n")
7159 (line-end-position))
7160 flag)))))
7162 (defun org-subtree-end-visible-p ()
7163 "Is the end of the current subtree visible?"
7164 (pos-visible-in-window-p
7165 (save-excursion (org-end-of-subtree t) (point))))
7167 (defun org-first-headline-recenter (&optional N)
7168 "Move cursor to the first headline and recenter the headline.
7169 Optional argument N means put the headline into the Nth line of the window."
7170 (goto-char (point-min))
7171 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7172 (beginning-of-line)
7173 (recenter (prefix-numeric-value N))))
7175 ;;; Saving and restoring visibility
7177 (defun org-outline-overlay-data (&optional use-markers)
7178 "Return a list of the locations of all outline overlays.
7179 These are overlays with the `invisible' property value `outline'.
7180 The return value is a list of cons cells, with start and stop
7181 positions for each overlay.
7182 If USE-MARKERS is set, return the positions as markers."
7183 (let (beg end)
7184 (save-excursion
7185 (save-restriction
7186 (widen)
7187 (delq nil
7188 (mapcar (lambda (o)
7189 (when (eq (overlay-get o 'invisible) 'outline)
7190 (setq beg (overlay-start o)
7191 end (overlay-end o))
7192 (and beg end (> end beg)
7193 (if use-markers
7194 (cons (move-marker (make-marker) beg)
7195 (move-marker (make-marker) end))
7196 (cons beg end)))))
7197 (overlays-in (point-min) (point-max))))))))
7199 (defun org-set-outline-overlay-data (data)
7200 "Create visibility overlays for all positions in DATA.
7201 DATA should have been made by `org-outline-overlay-data'."
7202 (let (o)
7203 (save-excursion
7204 (save-restriction
7205 (widen)
7206 (show-all)
7207 (mapc (lambda (c)
7208 (outline-flag-region (car c) (cdr c) t))
7209 data)))))
7211 ;;; Folding of blocks
7213 (defvar org-hide-block-overlays nil
7214 "Overlays hiding blocks.")
7215 (make-variable-buffer-local 'org-hide-block-overlays)
7217 (defun org-block-map (function &optional start end)
7218 "Call FUNCTION at the head of all source blocks in the current buffer.
7219 Optional arguments START and END can be used to limit the range."
7220 (let ((start (or start (point-min)))
7221 (end (or end (point-max))))
7222 (save-excursion
7223 (goto-char start)
7224 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7225 (save-excursion
7226 (save-match-data
7227 (goto-char (match-beginning 0))
7228 (funcall function)))))))
7230 (defun org-hide-block-toggle-all ()
7231 "Toggle the visibility of all blocks in the current buffer."
7232 (org-block-map #'org-hide-block-toggle))
7234 (defun org-hide-block-all ()
7235 "Fold all blocks in the current buffer."
7236 (interactive)
7237 (org-show-block-all)
7238 (org-block-map #'org-hide-block-toggle-maybe))
7240 (defun org-show-block-all ()
7241 "Unfold all blocks in the current buffer."
7242 (interactive)
7243 (mapc 'delete-overlay org-hide-block-overlays)
7244 (setq org-hide-block-overlays nil))
7246 (defun org-hide-block-toggle-maybe ()
7247 "Toggle visibility of block at point."
7248 (interactive)
7249 (let ((case-fold-search t))
7250 (if (save-excursion
7251 (beginning-of-line 1)
7252 (looking-at org-block-regexp))
7253 (progn (org-hide-block-toggle)
7254 t) ;; to signal that we took action
7255 nil))) ;; to signal that we did not
7257 (defun org-hide-block-toggle (&optional force)
7258 "Toggle the visibility of the current block."
7259 (interactive)
7260 (save-excursion
7261 (beginning-of-line)
7262 (if (re-search-forward org-block-regexp nil t)
7263 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7264 (end (match-end 0)) ;; end of entire body
7266 (if (memq t (mapcar (lambda (overlay)
7267 (eq (overlay-get overlay 'invisible)
7268 'org-hide-block))
7269 (overlays-at start)))
7270 (if (or (not force) (eq force 'off))
7271 (mapc (lambda (ov)
7272 (when (member ov org-hide-block-overlays)
7273 (setq org-hide-block-overlays
7274 (delq ov org-hide-block-overlays)))
7275 (when (eq (overlay-get ov 'invisible)
7276 'org-hide-block)
7277 (delete-overlay ov)))
7278 (overlays-at start)))
7279 (setq ov (make-overlay start end))
7280 (overlay-put ov 'invisible 'org-hide-block)
7281 ;; make the block accessible to isearch
7282 (overlay-put
7283 ov 'isearch-open-invisible
7284 (lambda (ov)
7285 (when (member ov org-hide-block-overlays)
7286 (setq org-hide-block-overlays
7287 (delq ov org-hide-block-overlays)))
7288 (when (eq (overlay-get ov 'invisible)
7289 'org-hide-block)
7290 (delete-overlay ov))))
7291 (push ov org-hide-block-overlays)))
7292 (user-error "Not looking at a source block"))))
7294 ;; org-tab-after-check-for-cycling-hook
7295 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7296 ;; Remove overlays when changing major mode
7297 (add-hook 'org-mode-hook
7298 (lambda () (org-add-hook 'change-major-mode-hook
7299 'org-show-block-all 'append 'local)))
7301 ;;; Org-goto
7303 (defvar org-goto-window-configuration nil)
7304 (defvar org-goto-marker nil)
7305 (defvar org-goto-map)
7306 (defun org-goto-map ()
7307 "Set the keymap `org-goto'."
7308 (setq org-goto-map
7309 (let ((map (make-sparse-keymap)))
7310 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7311 mouse-drag-region universal-argument org-occur))
7312 cmd)
7313 (while (setq cmd (pop cmds))
7314 (substitute-key-definition cmd cmd map global-map)))
7315 (suppress-keymap map)
7316 (org-defkey map "\C-m" 'org-goto-ret)
7317 (org-defkey map [(return)] 'org-goto-ret)
7318 (org-defkey map [(left)] 'org-goto-left)
7319 (org-defkey map [(right)] 'org-goto-right)
7320 (org-defkey map [(control ?g)] 'org-goto-quit)
7321 (org-defkey map "\C-i" 'org-cycle)
7322 (org-defkey map [(tab)] 'org-cycle)
7323 (org-defkey map [(down)] 'outline-next-visible-heading)
7324 (org-defkey map [(up)] 'outline-previous-visible-heading)
7325 (if org-goto-auto-isearch
7326 (if (fboundp 'define-key-after)
7327 (define-key-after map [t] 'org-goto-local-auto-isearch)
7328 nil)
7329 (org-defkey map "q" 'org-goto-quit)
7330 (org-defkey map "n" 'outline-next-visible-heading)
7331 (org-defkey map "p" 'outline-previous-visible-heading)
7332 (org-defkey map "f" 'outline-forward-same-level)
7333 (org-defkey map "b" 'outline-backward-same-level)
7334 (org-defkey map "u" 'outline-up-heading))
7335 (org-defkey map "/" 'org-occur)
7336 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7337 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7338 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7339 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7340 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7341 map)))
7343 (defconst org-goto-help
7344 "Browse buffer copy, to find location or copy text.%s
7345 RET=jump to location C-g=quit and return to previous location
7346 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7348 (defvar org-goto-start-pos) ; dynamically scoped parameter
7350 (defun org-goto (&optional alternative-interface)
7351 "Look up a different location in the current file, keeping current visibility.
7353 When you want look-up or go to a different location in a
7354 document, the fastest way is often to fold the entire buffer and
7355 then dive into the tree. This method has the disadvantage, that
7356 the previous location will be folded, which may not be what you
7357 want.
7359 This command works around this by showing a copy of the current
7360 buffer in an indirect buffer, in overview mode. You can dive
7361 into the tree in that copy, use org-occur and incremental search
7362 to find a location. When pressing RET or `Q', the command
7363 returns to the original buffer in which the visibility is still
7364 unchanged. After RET it will also jump to the location selected
7365 in the indirect buffer and expose the headline hierarchy above.
7367 With a prefix argument, use the alternative interface: e.g. if
7368 `org-goto-interface' is 'outline use 'outline-path-completion."
7369 (interactive "P")
7370 (org-goto-map)
7371 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7372 (org-refile-use-outline-path t)
7373 (org-refile-target-verify-function nil)
7374 (interface
7375 (if (not alternative-interface)
7376 org-goto-interface
7377 (if (eq org-goto-interface 'outline)
7378 'outline-path-completion
7379 'outline)))
7380 (org-goto-start-pos (point))
7381 (selected-point
7382 (if (eq interface 'outline)
7383 (car (org-get-location (current-buffer) org-goto-help))
7384 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7385 (org-refile-check-position pa)
7386 (nth 3 pa)))))
7387 (if selected-point
7388 (progn
7389 (org-mark-ring-push org-goto-start-pos)
7390 (goto-char selected-point)
7391 (if (or (outline-invisible-p) (org-invisible-p2))
7392 (org-show-context 'org-goto)))
7393 (message "Quit"))))
7395 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7396 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7397 (defvar org-goto-local-auto-isearch-map) ; defined below
7399 (defun org-get-location (buf help)
7400 "Let the user select a location in the Org-mode buffer BUF.
7401 This function uses a recursive edit. It returns the selected position
7402 or nil."
7403 (org-no-popups
7404 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7405 (isearch-hide-immediately nil)
7406 (isearch-search-fun-function
7407 (lambda () 'org-goto-local-search-headings))
7408 (org-goto-selected-point org-goto-exit-command))
7409 (save-excursion
7410 (save-window-excursion
7411 (delete-other-windows)
7412 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7413 (org-pop-to-buffer-same-window
7414 (condition-case nil
7415 (make-indirect-buffer (current-buffer) "*org-goto*")
7416 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7417 (with-output-to-temp-buffer "*Org Help*"
7418 (princ (format help (if org-goto-auto-isearch
7419 " Just type for auto-isearch."
7420 " n/p/f/b/u to navigate, q to quit."))))
7421 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7422 (setq buffer-read-only nil)
7423 (let ((org-startup-truncated t)
7424 (org-startup-folded nil)
7425 (org-startup-align-all-tables nil))
7426 (org-mode)
7427 (org-overview))
7428 (setq buffer-read-only t)
7429 (if (and (boundp 'org-goto-start-pos)
7430 (integer-or-marker-p org-goto-start-pos))
7431 (let ((org-show-hierarchy-above t)
7432 (org-show-siblings t)
7433 (org-show-following-heading t))
7434 (goto-char org-goto-start-pos)
7435 (and (outline-invisible-p) (org-show-context)))
7436 (goto-char (point-min)))
7437 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7438 (message "Select location and press RET")
7439 (use-local-map org-goto-map)
7440 (recursive-edit)))
7441 (kill-buffer "*org-goto*")
7442 (cons org-goto-selected-point org-goto-exit-command))))
7444 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7445 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7446 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7447 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7449 (defun org-goto-local-search-headings (string bound noerror)
7450 "Search and make sure that any matches are in headlines."
7451 (catch 'return
7452 (while (if isearch-forward
7453 (search-forward string bound noerror)
7454 (search-backward string bound noerror))
7455 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7456 (and (member :headline context)
7457 (not (member :tags context))))
7458 (throw 'return (point))))))
7460 (defun org-goto-local-auto-isearch ()
7461 "Start isearch."
7462 (interactive)
7463 (goto-char (point-min))
7464 (let ((keys (this-command-keys)))
7465 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7466 (isearch-mode t)
7467 (isearch-process-search-char (string-to-char keys)))))
7469 (defun org-goto-ret (&optional arg)
7470 "Finish `org-goto' by going to the new location."
7471 (interactive "P")
7472 (setq org-goto-selected-point (point)
7473 org-goto-exit-command 'return)
7474 (throw 'exit nil))
7476 (defun org-goto-left ()
7477 "Finish `org-goto' by going to the new location."
7478 (interactive)
7479 (if (org-at-heading-p)
7480 (progn
7481 (beginning-of-line 1)
7482 (setq org-goto-selected-point (point)
7483 org-goto-exit-command 'left)
7484 (throw 'exit nil))
7485 (user-error "Not on a heading")))
7487 (defun org-goto-right ()
7488 "Finish `org-goto' by going to the new location."
7489 (interactive)
7490 (if (org-at-heading-p)
7491 (progn
7492 (setq org-goto-selected-point (point)
7493 org-goto-exit-command 'right)
7494 (throw 'exit nil))
7495 (user-error "Not on a heading")))
7497 (defun org-goto-quit ()
7498 "Finish `org-goto' without cursor motion."
7499 (interactive)
7500 (setq org-goto-selected-point nil)
7501 (setq org-goto-exit-command 'quit)
7502 (throw 'exit nil))
7504 ;;; Indirect buffer display of subtrees
7506 (defvar org-indirect-dedicated-frame nil
7507 "This is the frame being used for indirect tree display.")
7508 (defvar org-last-indirect-buffer nil)
7510 (defun org-tree-to-indirect-buffer (&optional arg)
7511 "Create indirect buffer and narrow it to current subtree.
7512 With a numerical prefix ARG, go up to this level and then take that tree.
7513 If ARG is negative, go up that many levels.
7515 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7516 indirect buffer previously made with this command, to avoid proliferation of
7517 indirect buffers. However, when you call the command with a \
7518 \\[universal-argument] prefix, or
7519 when `org-indirect-buffer-display' is `new-frame', the last buffer
7520 is kept so that you can work with several indirect buffers at the same time.
7521 If `org-indirect-buffer-display' is `dedicated-frame', the \
7522 \\[universal-argument] prefix also
7523 requests that a new frame be made for the new buffer, so that the dedicated
7524 frame is not changed."
7525 (interactive "P")
7526 (let ((cbuf (current-buffer))
7527 (cwin (selected-window))
7528 (pos (point))
7529 beg end level heading ibuf)
7530 (save-excursion
7531 (org-back-to-heading t)
7532 (when (numberp arg)
7533 (setq level (org-outline-level))
7534 (if (< arg 0) (setq arg (+ level arg)))
7535 (while (> (setq level (org-outline-level)) arg)
7536 (org-up-heading-safe)))
7537 (setq beg (point)
7538 heading (org-get-heading))
7539 (org-end-of-subtree t t)
7540 (if (org-at-heading-p) (backward-char 1))
7541 (setq end (point)))
7542 (if (and (buffer-live-p org-last-indirect-buffer)
7543 (not (eq org-indirect-buffer-display 'new-frame))
7544 (not arg))
7545 (kill-buffer org-last-indirect-buffer))
7546 (setq ibuf (org-get-indirect-buffer cbuf heading)
7547 org-last-indirect-buffer ibuf)
7548 (cond
7549 ((or (eq org-indirect-buffer-display 'new-frame)
7550 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7551 (select-frame (make-frame))
7552 (delete-other-windows)
7553 (org-pop-to-buffer-same-window ibuf)
7554 (org-set-frame-title heading))
7555 ((eq org-indirect-buffer-display 'dedicated-frame)
7556 (raise-frame
7557 (select-frame (or (and org-indirect-dedicated-frame
7558 (frame-live-p org-indirect-dedicated-frame)
7559 org-indirect-dedicated-frame)
7560 (setq org-indirect-dedicated-frame (make-frame)))))
7561 (delete-other-windows)
7562 (org-pop-to-buffer-same-window ibuf)
7563 (org-set-frame-title (concat "Indirect: " heading)))
7564 ((eq org-indirect-buffer-display 'current-window)
7565 (org-pop-to-buffer-same-window ibuf))
7566 ((eq org-indirect-buffer-display 'other-window)
7567 (pop-to-buffer ibuf))
7568 (t (error "Invalid value")))
7569 (if (featurep 'xemacs)
7570 (save-excursion (org-mode) (turn-on-font-lock)))
7571 (narrow-to-region beg end)
7572 (show-all)
7573 (goto-char pos)
7574 (run-hook-with-args 'org-cycle-hook 'all)
7575 (and (window-live-p cwin) (select-window cwin))))
7577 (defun org-get-indirect-buffer (&optional buffer heading)
7578 (setq buffer (or buffer (current-buffer)))
7579 (let ((n 1) (base (buffer-name buffer)) bname)
7580 (while (buffer-live-p
7581 (get-buffer
7582 (setq bname
7583 (concat base "-"
7584 (if heading (concat heading "-" (number-to-string n))
7585 (number-to-string n))))))
7586 (setq n (1+ n)))
7587 (condition-case nil
7588 (make-indirect-buffer buffer bname 'clone)
7589 (error (make-indirect-buffer buffer bname)))))
7591 (defun org-set-frame-title (title)
7592 "Set the title of the current frame to the string TITLE."
7593 ;; FIXME: how to name a single frame in XEmacs???
7594 (unless (featurep 'xemacs)
7595 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7597 ;;;; Structure editing
7599 ;;; Inserting headlines
7601 (defun org-previous-line-empty-p (&optional next)
7602 "Is the previous line a blank line?
7603 When NEXT is non-nil, check the next line instead."
7604 (save-excursion
7605 (and (not (bobp))
7606 (or (beginning-of-line (if next 2 0)) t)
7607 (save-match-data
7608 (looking-at "[ \t]*$")))))
7610 (defun org-insert-heading (&optional arg invisible-ok)
7611 "Insert a new heading or item with same depth at point.
7612 If point is in a plain list and ARG is nil, create a new list item.
7613 With one universal prefix argument, insert a heading even in lists.
7614 With two universal prefix arguments, insert the heading at the end
7615 of the parent subtree.
7617 If point is at the beginning of a headline, insert a sibling before
7618 the current headline. If point is not at the beginning, split the line
7619 and create a new headline with the text in the current line after point
7620 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7622 If point is at the beginning of a normal line, turn this line into
7623 a heading.
7625 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7626 This is important for non-interactive uses of the command."
7627 (interactive "P")
7628 (if (org-called-interactively-p 'any) (org-reveal))
7629 (let ((itemp (org-in-item-p))
7630 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7631 (respect-content (or org-insert-heading-respect-content
7632 (equal arg '(16))))
7633 (initial-content "")
7634 (adjust-empty-lines t))
7636 (cond
7638 ((or (= (buffer-size) 0)
7639 (and (not (save-excursion
7640 (and (ignore-errors (org-back-to-heading invisible-ok))
7641 (org-at-heading-p))))
7642 (or arg (not itemp))))
7643 ;; At beginning of buffer or so high up that only a heading
7644 ;; makes sense.
7645 (insert
7646 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7647 (if (org-in-src-block-p) ",* " "* "))
7648 (run-hooks 'org-insert-heading-hook))
7650 ((and itemp (not (equal arg '(4))))
7651 ;; Insert an item
7652 (org-insert-item))
7655 ;; Insert a heading
7656 (save-restriction
7657 (widen)
7658 (let* ((level nil)
7659 (on-heading (org-at-heading-p))
7660 (empty-line-p (if on-heading
7661 (org-previous-line-empty-p)
7662 ;; We will decide later
7663 nil))
7664 ;; Get a level string to fall back on
7665 (fix-level
7666 (save-excursion
7667 (org-back-to-heading t)
7668 (if (org-previous-line-empty-p) (setq empty-line-p t))
7669 (looking-at org-outline-regexp)
7670 (make-string (1- (length (match-string 0))) ?*)))
7671 (stars
7672 (save-excursion
7673 (condition-case nil
7674 (progn
7675 (org-back-to-heading invisible-ok)
7676 (when (and (not on-heading)
7677 (featurep 'org-inlinetask)
7678 (integerp org-inlinetask-min-level)
7679 (>= (length (match-string 0))
7680 org-inlinetask-min-level))
7681 ;; Find a heading level before the inline task
7682 (while (and (setq level (org-up-heading-safe))
7683 (>= level org-inlinetask-min-level)))
7684 (if (org-at-heading-p)
7685 (org-back-to-heading invisible-ok)
7686 (error "This should not happen")))
7687 (unless (and (save-excursion
7688 (save-match-data
7689 (org-backward-heading-same-level
7690 1 invisible-ok))
7691 (= (point) (match-beginning 0)))
7692 (not (org-previous-line-empty-p t)))
7693 (setq empty-line-p (or empty-line-p
7694 (org-previous-line-empty-p))))
7695 (match-string 0))
7696 (error (or fix-level "* ")))))
7697 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7698 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7699 pos hide-previous previous-pos)
7701 ;; If we insert after content, move there and clean up whitespace
7702 (when respect-content
7703 (org-end-of-subtree nil t)
7704 (skip-chars-backward " \r\n")
7705 (and (looking-at "[ \t]+") (replace-match ""))
7706 (unless (eobp) (forward-char 1))
7707 (when (looking-at "^\\*")
7708 (unless (bobp) (backward-char 1))
7709 (insert "\n")))
7711 ;; If we are splitting, grab the text that should be moved to the new headline
7712 (when may-split
7713 (if (org-on-heading-p)
7714 ;; This is a heading, we split intelligently (keeping tags)
7715 (let ((pos (point)))
7716 (goto-char (point-at-bol))
7717 (unless (looking-at org-complex-heading-regexp)
7718 (error "This should not happen"))
7719 (when (and (match-beginning 4)
7720 (> pos (match-beginning 4))
7721 (< pos (match-end 4)))
7722 (setq initial-content (buffer-substring pos (match-end 4)))
7723 (goto-char pos)
7724 (delete-region (point) (match-end 4))
7725 (if (looking-at "[ \t]*$")
7726 (replace-match "")
7727 (insert (make-string (length initial-content) ?\ )))
7728 (setq initial-content (org-trim initial-content)))
7729 (goto-char pos))
7730 ;; a normal line
7731 (unless (bolp)
7732 (setq initial-content (buffer-substring (point) (point-at-eol)))
7733 (delete-region (point) (point-at-eol))
7734 (setq initial-content (org-trim initial-content)))))
7736 ;; If we are at the beginning of the line, insert before it. Else after
7737 (cond
7738 ((and (bolp) (looking-at "[ \t]*$")))
7739 ((and (bolp) (not (looking-at "[ \t]*$")))
7740 (open-line 1))
7742 (goto-char (point-at-eol))
7743 (insert "\n")))
7745 ;; Insert the new heading
7746 (insert stars)
7747 (just-one-space)
7748 (insert initial-content)
7749 (when adjust-empty-lines
7750 (if (or (not blank)
7751 (and blank (not (org-previous-line-empty-p))))
7752 (org-N-empty-lines-before-current (if blank 1 0))))
7753 (run-hooks 'org-insert-heading-hook)))))))
7755 (defun org-N-empty-lines-before-current (N)
7756 "Make the number of empty lines before current exactly N.
7757 So this will delete or add empty lines."
7758 (save-excursion
7759 (goto-char (point-at-bol))
7760 (if (looking-back "\\s-+" nil 'greedy)
7761 (replace-match ""))
7762 (or (bobp) (insert "\n"))
7763 (while (> N 0)
7764 (insert "\n")
7765 (setq N (1- N)))))
7767 (defun org-get-heading (&optional no-tags no-todo)
7768 "Return the heading of the current entry, without the stars.
7769 When NO-TAGS is non-nil, don't include tags.
7770 When NO-TODO is non-nil, don't include TODO keywords."
7771 (save-excursion
7772 (org-back-to-heading t)
7773 (cond
7774 ((and no-tags no-todo)
7775 (looking-at org-complex-heading-regexp)
7776 (match-string 4))
7777 (no-tags
7778 (looking-at (concat org-outline-regexp
7779 "\\(.*?\\)"
7780 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7781 (match-string 1))
7782 (no-todo
7783 (looking-at org-todo-line-regexp)
7784 (match-string 3))
7785 (t (looking-at org-heading-regexp)
7786 (match-string 2)))))
7788 (defvar orgstruct-mode) ; defined below
7790 (defun org-heading-components ()
7791 "Return the components of the current heading.
7792 This is a list with the following elements:
7793 - the level as an integer
7794 - the reduced level, different if `org-odd-levels-only' is set.
7795 - the TODO keyword, or nil
7796 - the priority character, like ?A, or nil if no priority is given
7797 - the headline text itself, or the tags string if no headline text
7798 - the tags string, or nil."
7799 (save-excursion
7800 (org-back-to-heading t)
7801 (if (let (case-fold-search)
7802 (looking-at
7803 (if orgstruct-mode
7804 org-heading-regexp
7805 org-complex-heading-regexp)))
7806 (if orgstruct-mode
7807 (list (length (match-string 1))
7808 (org-reduced-level (length (match-string 1)))
7811 (match-string 2)
7812 nil)
7813 (list (length (match-string 1))
7814 (org-reduced-level (length (match-string 1)))
7815 (org-match-string-no-properties 2)
7816 (and (match-end 3) (aref (match-string 3) 2))
7817 (org-match-string-no-properties 4)
7818 (org-match-string-no-properties 5))))))
7820 (defun org-get-entry ()
7821 "Get the entry text, after heading, entire subtree."
7822 (save-excursion
7823 (org-back-to-heading t)
7824 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7826 (defun org-insert-heading-after-current ()
7827 "Insert a new heading with same level as current, after current subtree."
7828 (interactive)
7829 (org-back-to-heading)
7830 (org-insert-heading)
7831 (org-move-subtree-down)
7832 (end-of-line 1))
7834 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7835 "Insert heading with `org-insert-heading-respect-content' set to t."
7836 (interactive "P")
7837 (let ((org-insert-heading-respect-content t))
7838 (org-insert-heading '(4) invisible-ok)))
7840 (defun org-insert-todo-heading-respect-content (&optional force-state)
7841 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7842 (interactive "P")
7843 (let ((org-insert-heading-respect-content t))
7844 (org-insert-todo-heading force-state '(4))))
7846 (defun org-insert-todo-heading (arg &optional force-heading)
7847 "Insert a new heading with the same level and TODO state as current heading.
7848 If the heading has no TODO state, or if the state is DONE, use the first
7849 state (TODO by default). Also one prefix arg, force first state. With two
7850 prefix args, force inserting at the end of the parent subtree."
7851 (interactive "P")
7852 (when (or force-heading (not (org-insert-item 'checkbox)))
7853 (org-insert-heading (or (and (equal arg '(16)) '(16))
7854 force-heading))
7855 (save-excursion
7856 (org-back-to-heading)
7857 (outline-previous-heading)
7858 (looking-at org-todo-line-regexp))
7859 (let*
7860 ((new-mark-x
7861 (if (or arg
7862 (not (match-beginning 2))
7863 (member (match-string 2) org-done-keywords))
7864 (car org-todo-keywords-1)
7865 (match-string 2)))
7866 (new-mark
7868 (run-hook-with-args-until-success
7869 'org-todo-get-default-hook new-mark-x nil)
7870 new-mark-x)))
7871 (beginning-of-line 1)
7872 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7873 (if org-treat-insert-todo-heading-as-state-change
7874 (org-todo new-mark)
7875 (insert new-mark " "))))
7876 (when org-provide-todo-statistics
7877 (org-update-parent-todo-statistics))))
7879 (defun org-insert-subheading (arg)
7880 "Insert a new subheading and demote it.
7881 Works for outline headings and for plain lists alike."
7882 (interactive "P")
7883 (org-insert-heading arg)
7884 (cond
7885 ((org-at-heading-p) (org-do-demote))
7886 ((org-at-item-p) (org-indent-item))))
7888 (defun org-insert-todo-subheading (arg)
7889 "Insert a new subheading with TODO keyword or checkbox and demote it.
7890 Works for outline headings and for plain lists alike."
7891 (interactive "P")
7892 (org-insert-todo-heading arg)
7893 (cond
7894 ((org-at-heading-p) (org-do-demote))
7895 ((org-at-item-p) (org-indent-item))))
7897 ;;; Promotion and Demotion
7899 (defvar org-after-demote-entry-hook nil
7900 "Hook run after an entry has been demoted.
7901 The cursor will be at the beginning of the entry.
7902 When a subtree is being demoted, the hook will be called for each node.")
7904 (defvar org-after-promote-entry-hook nil
7905 "Hook run after an entry has been promoted.
7906 The cursor will be at the beginning of the entry.
7907 When a subtree is being promoted, the hook will be called for each node.")
7909 (defun org-promote-subtree ()
7910 "Promote the entire subtree.
7911 See also `org-promote'."
7912 (interactive)
7913 (save-excursion
7914 (org-with-limited-levels (org-map-tree 'org-promote)))
7915 (org-fix-position-after-promote))
7917 (defun org-demote-subtree ()
7918 "Demote the entire subtree. See `org-demote'.
7919 See also `org-promote'."
7920 (interactive)
7921 (save-excursion
7922 (org-with-limited-levels (org-map-tree 'org-demote)))
7923 (org-fix-position-after-promote))
7926 (defun org-do-promote ()
7927 "Promote the current heading higher up the tree.
7928 If the region is active in `transient-mark-mode', promote all headings
7929 in the region."
7930 (interactive)
7931 (save-excursion
7932 (if (org-region-active-p)
7933 (org-map-region 'org-promote (region-beginning) (region-end))
7934 (org-promote)))
7935 (org-fix-position-after-promote))
7937 (defun org-do-demote ()
7938 "Demote the current heading lower down the tree.
7939 If the region is active in `transient-mark-mode', demote all headings
7940 in the region."
7941 (interactive)
7942 (save-excursion
7943 (if (org-region-active-p)
7944 (org-map-region 'org-demote (region-beginning) (region-end))
7945 (org-demote)))
7946 (org-fix-position-after-promote))
7948 (defun org-fix-position-after-promote ()
7949 "Make sure that after pro/demotion cursor position is right."
7950 (let ((pos (point)))
7951 (when (save-excursion
7952 (beginning-of-line 1)
7953 (looking-at org-todo-line-regexp)
7954 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7955 (cond ((eobp) (insert " "))
7956 ((eolp) (insert " "))
7957 ((equal (char-after) ?\ ) (forward-char 1))))))
7959 (defun org-current-level ()
7960 "Return the level of the current entry, or nil if before the first headline.
7961 The level is the number of stars at the beginning of the headline."
7962 (save-excursion
7963 (org-with-limited-levels
7964 (if (ignore-errors (org-back-to-heading t))
7965 (funcall outline-level)))))
7967 (defun org-get-previous-line-level ()
7968 "Return the outline depth of the last headline before the current line.
7969 Returns 0 for the first headline in the buffer, and nil if before the
7970 first headline."
7971 (let ((current-level (org-current-level))
7972 (prev-level (when (> (line-number-at-pos) 1)
7973 (save-excursion
7974 (beginning-of-line 0)
7975 (org-current-level)))))
7976 (cond ((null current-level) nil) ; Before first headline
7977 ((null prev-level) 0) ; At first headline
7978 (prev-level))))
7980 (defun org-reduced-level (l)
7981 "Compute the effective level of a heading.
7982 This takes into account the setting of `org-odd-levels-only'."
7983 (cond
7984 ((zerop l) 0)
7985 (org-odd-levels-only (1+ (floor (/ l 2))))
7986 (t l)))
7988 (defun org-level-increment ()
7989 "Return the number of stars that will be added or removed at a
7990 time to headlines when structure editing, based on the value of
7991 `org-odd-levels-only'."
7992 (if org-odd-levels-only 2 1))
7994 (defun org-get-valid-level (level &optional change)
7995 "Rectify a level change under the influence of `org-odd-levels-only'
7996 LEVEL is a current level, CHANGE is by how much the level should be
7997 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7998 even level numbers will become the next higher odd number."
7999 (if org-odd-levels-only
8000 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8001 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8002 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8003 (max 1 (+ level (or change 0)))))
8005 (if (boundp 'define-obsolete-function-alias)
8006 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8007 (define-obsolete-function-alias 'org-get-legal-level
8008 'org-get-valid-level)
8009 (define-obsolete-function-alias 'org-get-legal-level
8010 'org-get-valid-level "23.1")))
8012 (defun org-promote ()
8013 "Promote the current heading higher up the tree.
8014 If the region is active in `transient-mark-mode', promote all headings
8015 in the region."
8016 (org-back-to-heading t)
8017 (let* ((level (save-match-data (funcall outline-level)))
8018 (after-change-functions (remove 'flyspell-after-change-function
8019 after-change-functions))
8020 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8021 (diff (abs (- level (length up-head) -1))))
8022 (cond ((and (= level 1) org-called-with-limited-levels
8023 org-allow-promoting-top-level-subtree)
8024 (replace-match "# " nil t))
8025 ((= level 1)
8026 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8027 (t (replace-match up-head nil t)))
8028 ;; Fixup tag positioning
8029 (unless (= level 1)
8030 (and org-auto-align-tags (org-set-tags nil t))
8031 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8032 (run-hooks 'org-after-promote-entry-hook)))
8034 (defun org-demote ()
8035 "Demote the current heading lower down the tree.
8036 If the region is active in `transient-mark-mode', demote all headings
8037 in the region."
8038 (org-back-to-heading t)
8039 (let* ((level (save-match-data (funcall outline-level)))
8040 (after-change-functions (remove 'flyspell-after-change-function
8041 after-change-functions))
8042 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8043 (diff (abs (- level (length down-head) -1))))
8044 (replace-match down-head nil t)
8045 ;; Fixup tag positioning
8046 (and org-auto-align-tags (org-set-tags nil t))
8047 (if org-adapt-indentation (org-fixup-indentation diff))
8048 (run-hooks 'org-after-demote-entry-hook)))
8050 (defun org-cycle-level ()
8051 "Cycle the level of an empty headline through possible states.
8052 This goes first to child, then to parent, level, then up the hierarchy.
8053 After top level, it switches back to sibling level."
8054 (interactive)
8055 (let ((org-adapt-indentation nil))
8056 (when (org-point-at-end-of-empty-headline)
8057 (setq this-command 'org-cycle-level) ; Only needed for caching
8058 (let ((cur-level (org-current-level))
8059 (prev-level (org-get-previous-line-level)))
8060 (cond
8061 ;; If first headline in file, promote to top-level.
8062 ((= prev-level 0)
8063 (loop repeat (/ (- cur-level 1) (org-level-increment))
8064 do (org-do-promote)))
8065 ;; If same level as prev, demote one.
8066 ((= prev-level cur-level)
8067 (org-do-demote))
8068 ;; If parent is top-level, promote to top level if not already.
8069 ((= prev-level 1)
8070 (loop repeat (/ (- cur-level 1) (org-level-increment))
8071 do (org-do-promote)))
8072 ;; If top-level, return to prev-level.
8073 ((= cur-level 1)
8074 (loop repeat (/ (- prev-level 1) (org-level-increment))
8075 do (org-do-demote)))
8076 ;; If less than prev-level, promote one.
8077 ((< cur-level prev-level)
8078 (org-do-promote))
8079 ;; If deeper than prev-level, promote until higher than
8080 ;; prev-level.
8081 ((> cur-level prev-level)
8082 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8083 do (org-do-promote))))
8084 t))))
8086 (defun org-map-tree (fun)
8087 "Call FUN for every heading underneath the current one."
8088 (org-back-to-heading)
8089 (let ((level (funcall outline-level)))
8090 (save-excursion
8091 (funcall fun)
8092 (while (and (progn
8093 (outline-next-heading)
8094 (> (funcall outline-level) level))
8095 (not (eobp)))
8096 (funcall fun)))))
8098 (defun org-map-region (fun beg end)
8099 "Call FUN for every heading between BEG and END."
8100 (let ((org-ignore-region t))
8101 (save-excursion
8102 (setq end (copy-marker end))
8103 (goto-char beg)
8104 (if (and (re-search-forward org-outline-regexp-bol nil t)
8105 (< (point) end))
8106 (funcall fun))
8107 (while (and (progn
8108 (outline-next-heading)
8109 (< (point) end))
8110 (not (eobp)))
8111 (funcall fun)))))
8113 (defvar org-property-end-re) ; silence byte-compiler
8114 (defun org-fixup-indentation (diff)
8115 "Change the indentation in the current entry by DIFF.
8116 However, if any line in the current entry has no indentation, or if it
8117 would end up with no indentation after the change, nothing at all is done."
8118 (save-excursion
8119 (let ((end (save-excursion (outline-next-heading)
8120 (point-marker)))
8121 (prohibit (if (> diff 0)
8122 "^\\S-"
8123 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8124 col)
8125 (unless (save-excursion (end-of-line 1)
8126 (re-search-forward prohibit end t))
8127 (while (and (< (point) end)
8128 (re-search-forward "^[ \t]+" end t))
8129 (goto-char (match-end 0))
8130 (setq col (current-column))
8131 (if (< diff 0) (replace-match ""))
8132 (org-indent-to-column (+ diff col))))
8133 (move-marker end nil))))
8135 (defun org-convert-to-odd-levels ()
8136 "Convert an org-mode file with all levels allowed to one with odd levels.
8137 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8138 level 5 etc."
8139 (interactive)
8140 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8141 (let ((outline-level 'org-outline-level)
8142 (org-odd-levels-only nil) n)
8143 (save-excursion
8144 (goto-char (point-min))
8145 (while (re-search-forward "^\\*\\*+ " nil t)
8146 (setq n (- (length (match-string 0)) 2))
8147 (while (>= (setq n (1- n)) 0)
8148 (org-demote))
8149 (end-of-line 1))))))
8151 (defun org-convert-to-oddeven-levels ()
8152 "Convert an org-mode file with only odd levels to one with odd/even levels.
8153 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8154 file contains a section with an even level, conversion would
8155 destroy the structure of the file. An error is signaled in this
8156 case."
8157 (interactive)
8158 (goto-char (point-min))
8159 ;; First check if there are no even levels
8160 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8161 (org-show-context t)
8162 (error "Not all levels are odd in this file. Conversion not possible"))
8163 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8164 (let ((outline-regexp org-outline-regexp)
8165 (outline-level 'org-outline-level)
8166 (org-odd-levels-only nil) n)
8167 (save-excursion
8168 (goto-char (point-min))
8169 (while (re-search-forward "^\\*\\*+ " nil t)
8170 (setq n (/ (1- (length (match-string 0))) 2))
8171 (while (>= (setq n (1- n)) 0)
8172 (org-promote))
8173 (end-of-line 1))))))
8175 (defun org-tr-level (n)
8176 "Make N odd if required."
8177 (if org-odd-levels-only (1+ (/ n 2)) n))
8179 ;;; Vertical tree motion, cutting and pasting of subtrees
8181 (defun org-move-subtree-up (&optional arg)
8182 "Move the current subtree up past ARG headlines of the same level."
8183 (interactive "p")
8184 (org-move-subtree-down (- (prefix-numeric-value arg))))
8186 (defun org-move-subtree-down (&optional arg)
8187 "Move the current subtree down past ARG headlines of the same level."
8188 (interactive "p")
8189 (setq arg (prefix-numeric-value arg))
8190 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8191 'org-get-last-sibling))
8192 (ins-point (make-marker))
8193 (cnt (abs arg))
8194 (col (current-column))
8195 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8196 ;; Select the tree
8197 (org-back-to-heading)
8198 (setq beg0 (point))
8199 (save-excursion
8200 (setq ne-beg (org-back-over-empty-lines))
8201 (setq beg (point)))
8202 (save-match-data
8203 (save-excursion (outline-end-of-heading)
8204 (setq folded (outline-invisible-p)))
8205 (outline-end-of-subtree))
8206 (outline-next-heading)
8207 (setq ne-end (org-back-over-empty-lines))
8208 (setq end (point))
8209 (goto-char beg0)
8210 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8211 ;; include less whitespace
8212 (save-excursion
8213 (goto-char beg)
8214 (forward-line (- ne-beg ne-end))
8215 (setq beg (point))))
8216 ;; Find insertion point, with error handling
8217 (while (> cnt 0)
8218 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8219 (progn (goto-char beg0)
8220 (user-error "Cannot move past superior level or buffer limit")))
8221 (setq cnt (1- cnt)))
8222 (if (> arg 0)
8223 ;; Moving forward - still need to move over subtree
8224 (progn (org-end-of-subtree t t)
8225 (save-excursion
8226 (org-back-over-empty-lines)
8227 (or (bolp) (newline)))))
8228 (setq ne-ins (org-back-over-empty-lines))
8229 (move-marker ins-point (point))
8230 (setq txt (buffer-substring beg end))
8231 (org-save-markers-in-region beg end)
8232 (delete-region beg end)
8233 (org-remove-empty-overlays-at beg)
8234 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8235 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8236 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8237 (let ((bbb (point)))
8238 (insert-before-markers txt)
8239 (org-reinstall-markers-in-region bbb)
8240 (move-marker ins-point bbb))
8241 (or (bolp) (insert "\n"))
8242 (setq ins-end (point))
8243 (goto-char ins-point)
8244 (org-skip-whitespace)
8245 (when (and (< arg 0)
8246 (org-first-sibling-p)
8247 (> ne-ins ne-beg))
8248 ;; Move whitespace back to beginning
8249 (save-excursion
8250 (goto-char ins-end)
8251 (let ((kill-whole-line t))
8252 (kill-line (- ne-ins ne-beg)) (point)))
8253 (insert (make-string (- ne-ins ne-beg) ?\n)))
8254 (move-marker ins-point nil)
8255 (if folded
8256 (hide-subtree)
8257 (org-show-entry)
8258 (show-children)
8259 (org-cycle-hide-drawers 'children))
8260 (org-clean-visibility-after-subtree-move)
8261 ;; move back to the initial column we were at
8262 (move-to-column col)))
8264 (defvar org-subtree-clip ""
8265 "Clipboard for cut and paste of subtrees.
8266 This is actually only a copy of the kill, because we use the normal kill
8267 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8269 (defvar org-subtree-clip-folded nil
8270 "Was the last copied subtree folded?
8271 This is used to fold the tree back after pasting.")
8273 (defun org-cut-subtree (&optional n)
8274 "Cut the current subtree into the clipboard.
8275 With prefix arg N, cut this many sequential subtrees.
8276 This is a short-hand for marking the subtree and then cutting it."
8277 (interactive "p")
8278 (org-copy-subtree n 'cut))
8280 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8281 "Copy the current subtree it in the clipboard.
8282 With prefix arg N, copy this many sequential subtrees.
8283 This is a short-hand for marking the subtree and then copying it.
8284 If CUT is non-nil, actually cut the subtree.
8285 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8286 of some markers in the region, even if CUT is non-nil. This is
8287 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8288 (interactive "p")
8289 (let (beg end folded (beg0 (point)))
8290 (if (org-called-interactively-p 'any)
8291 (org-back-to-heading nil) ; take what looks like a subtree
8292 (org-back-to-heading t)) ; take what is really there
8293 (setq beg (point))
8294 (skip-chars-forward " \t\r\n")
8295 (save-match-data
8296 (if nosubtrees
8297 (outline-next-heading)
8298 (save-excursion (outline-end-of-heading)
8299 (setq folded (outline-invisible-p)))
8300 (condition-case nil
8301 (org-forward-heading-same-level (1- n) t)
8302 (error nil))
8303 (org-end-of-subtree t t)))
8304 (setq end (point))
8305 (goto-char beg0)
8306 (when (> end beg)
8307 (setq org-subtree-clip-folded folded)
8308 (when (or cut force-store-markers)
8309 (org-save-markers-in-region beg end))
8310 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8311 (setq org-subtree-clip (current-kill 0))
8312 (message "%s: Subtree(s) with %d characters"
8313 (if cut "Cut" "Copied")
8314 (length org-subtree-clip)))))
8316 (defun org-paste-subtree (&optional level tree for-yank)
8317 "Paste the clipboard as a subtree, with modification of headline level.
8318 The entire subtree is promoted or demoted in order to match a new headline
8319 level.
8321 If the cursor is at the beginning of a headline, the same level as
8322 that headline is used to paste the tree.
8324 If not, the new level is derived from the *visible* headings
8325 before and after the insertion point, and taken to be the inferior headline
8326 level of the two. So if the previous visible heading is level 3 and the
8327 next is level 4 (or vice versa), level 4 will be used for insertion.
8328 This makes sure that the subtree remains an independent subtree and does
8329 not swallow low level entries.
8331 You can also force a different level, either by using a numeric prefix
8332 argument, or by inserting the heading marker by hand. For example, if the
8333 cursor is after \"*****\", then the tree will be shifted to level 5.
8335 If optional TREE is given, use this text instead of the kill ring.
8337 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8338 move back over whitespace before inserting, and move point to the end of
8339 the inserted text when done."
8340 (interactive "P")
8341 (setq tree (or tree (and kill-ring (current-kill 0))))
8342 (unless (org-kill-is-subtree-p tree)
8343 (user-error "%s"
8344 (substitute-command-keys
8345 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8346 (org-with-limited-levels
8347 (let* ((visp (not (outline-invisible-p)))
8348 (txt tree)
8349 (^re_ "\\(\\*+\\)[ \t]*")
8350 (old-level (if (string-match org-outline-regexp-bol txt)
8351 (- (match-end 0) (match-beginning 0) 1)
8352 -1))
8353 (force-level (cond (level (prefix-numeric-value level))
8354 ((and (looking-at "[ \t]*$")
8355 (string-match
8356 "^\\*+$" (buffer-substring
8357 (point-at-bol) (point))))
8358 (- (match-end 1) (match-beginning 1)))
8359 ((and (bolp)
8360 (looking-at org-outline-regexp))
8361 (- (match-end 0) (point) 1))))
8362 (previous-level (save-excursion
8363 (condition-case nil
8364 (progn
8365 (outline-previous-visible-heading 1)
8366 (if (looking-at ^re_)
8367 (- (match-end 0) (match-beginning 0) 1)
8369 (error 1))))
8370 (next-level (save-excursion
8371 (condition-case nil
8372 (progn
8373 (or (looking-at org-outline-regexp)
8374 (outline-next-visible-heading 1))
8375 (if (looking-at ^re_)
8376 (- (match-end 0) (match-beginning 0) 1)
8378 (error 1))))
8379 (new-level (or force-level (max previous-level next-level)))
8380 (shift (if (or (= old-level -1)
8381 (= new-level -1)
8382 (= old-level new-level))
8384 (- new-level old-level)))
8385 (delta (if (> shift 0) -1 1))
8386 (func (if (> shift 0) 'org-demote 'org-promote))
8387 (org-odd-levels-only nil)
8388 beg end newend)
8389 ;; Remove the forced level indicator
8390 (if force-level
8391 (delete-region (point-at-bol) (point)))
8392 ;; Paste
8393 (beginning-of-line (if (bolp) 1 2))
8394 (setq beg (point))
8395 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8396 (insert-before-markers txt)
8397 (unless (string-match "\n\\'" txt) (insert "\n"))
8398 (setq newend (point))
8399 (org-reinstall-markers-in-region beg)
8400 (setq end (point))
8401 (goto-char beg)
8402 (skip-chars-forward " \t\n\r")
8403 (setq beg (point))
8404 (if (and (outline-invisible-p) visp)
8405 (save-excursion (outline-show-heading)))
8406 ;; Shift if necessary
8407 (unless (= shift 0)
8408 (save-restriction
8409 (narrow-to-region beg end)
8410 (while (not (= shift 0))
8411 (org-map-region func (point-min) (point-max))
8412 (setq shift (+ delta shift)))
8413 (goto-char (point-min))
8414 (setq newend (point-max))))
8415 (when (or (org-called-interactively-p 'interactive) for-yank)
8416 (message "Clipboard pasted as level %d subtree" new-level))
8417 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8418 kill-ring
8419 (eq org-subtree-clip (current-kill 0))
8420 org-subtree-clip-folded)
8421 ;; The tree was folded before it was killed/copied
8422 (hide-subtree))
8423 (and for-yank (goto-char newend)))))
8425 (defun org-kill-is-subtree-p (&optional txt)
8426 "Check if the current kill is an outline subtree, or a set of trees.
8427 Returns nil if kill does not start with a headline, or if the first
8428 headline level is not the largest headline level in the tree.
8429 So this will actually accept several entries of equal levels as well,
8430 which is OK for `org-paste-subtree'.
8431 If optional TXT is given, check this string instead of the current kill."
8432 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8433 (re (org-get-limited-outline-regexp))
8434 (^re (concat "^" re))
8435 (start-level (and kill
8436 (string-match
8437 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8438 kill)
8439 (- (match-end 2) (match-beginning 2) 1)))
8440 (start (1+ (or (match-beginning 2) -1))))
8441 (if (not start-level)
8442 (progn
8443 nil) ;; does not even start with a heading
8444 (catch 'exit
8445 (while (setq start (string-match ^re kill (1+ start)))
8446 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8447 (throw 'exit nil)))
8448 t))))
8450 (defvar org-markers-to-move nil
8451 "Markers that should be moved with a cut-and-paste operation.
8452 Those markers are stored together with their positions relative to
8453 the start of the region.")
8455 (defun org-save-markers-in-region (beg end)
8456 "Check markers in region.
8457 If these markers are between BEG and END, record their position relative
8458 to BEG, so that after moving the block of text, we can put the markers back
8459 into place.
8460 This function gets called just before an entry or tree gets cut from the
8461 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8462 called immediately, to move the markers with the entries."
8463 (setq org-markers-to-move nil)
8464 (when (featurep 'org-clock)
8465 (org-clock-save-markers-for-cut-and-paste beg end))
8466 (when (featurep 'org-agenda)
8467 (org-agenda-save-markers-for-cut-and-paste beg end)))
8469 (defun org-check-and-save-marker (marker beg end)
8470 "Check if MARKER is between BEG and END.
8471 If yes, remember the marker and the distance to BEG."
8472 (when (and (marker-buffer marker)
8473 (equal (marker-buffer marker) (current-buffer)))
8474 (if (and (>= marker beg) (< marker end))
8475 (push (cons marker (- marker beg)) org-markers-to-move))))
8477 (defun org-reinstall-markers-in-region (beg)
8478 "Move all remembered markers to their position relative to BEG."
8479 (mapc (lambda (x)
8480 (move-marker (car x) (+ beg (cdr x))))
8481 org-markers-to-move)
8482 (setq org-markers-to-move nil))
8484 (defun org-narrow-to-subtree ()
8485 "Narrow buffer to the current subtree."
8486 (interactive)
8487 (save-excursion
8488 (save-match-data
8489 (org-with-limited-levels
8490 (narrow-to-region
8491 (progn (org-back-to-heading t) (point))
8492 (progn (org-end-of-subtree t t)
8493 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8494 (point)))))))
8496 (defun org-narrow-to-block ()
8497 "Narrow buffer to the current block."
8498 (interactive)
8499 (let* ((case-fold-search t)
8500 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8501 "^[ \t]*#\\+end_.*")))
8502 (if blockp
8503 (narrow-to-region (car blockp) (cdr blockp))
8504 (user-error "Not in a block"))))
8506 (eval-when-compile
8507 (defvar org-property-drawer-re))
8509 (defvar org-property-start-re) ;; defined below
8510 (defun org-clone-subtree-with-time-shift (n &optional shift)
8511 "Clone the task (subtree) at point N times.
8512 The clones will be inserted as siblings.
8514 In interactive use, the user will be prompted for the number of
8515 clones to be produced. If the entry has a timestamp, the user
8516 will also be prompted for a time shift, which may be a repeater
8517 as used in time stamps, for example `+3d'. To disable this,
8518 you can call the function with a universal prefix argument.
8520 When a valid repeater is given and the entry contains any time
8521 stamps, the clones will become a sequence in time, with time
8522 stamps in the subtree shifted for each clone produced. If SHIFT
8523 is nil or the empty string, time stamps will be left alone. The
8524 ID property of the original subtree is removed.
8526 If the original subtree did contain time stamps with a repeater,
8527 the following will happen:
8528 - the repeater will be removed in each clone
8529 - an additional clone will be produced, with the current, unshifted
8530 date(s) in the entry.
8531 - the original entry will be placed *after* all the clones, with
8532 repeater intact.
8533 - the start days in the repeater in the original entry will be shifted
8534 to past the last clone.
8535 In this way you can spell out a number of instances of a repeating task,
8536 and still retain the repeater to cover future instances of the task."
8537 (interactive "nNumber of clones to produce: ")
8538 (let ((shift
8539 (or shift
8540 (if (and (not (equal current-prefix-arg '(4)))
8541 (save-excursion
8542 (re-search-forward org-ts-regexp-both
8543 (save-excursion
8544 (org-end-of-subtree t)
8545 (point)) t)))
8546 (read-from-minibuffer
8547 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8548 ""))) ;; No time shift
8549 (n-no-remove -1)
8550 (drawer-re org-drawer-regexp)
8551 beg end template task idprop
8552 shift-n shift-what doshift nmin nmax)
8553 (if (not (and (integerp n) (> n 0)))
8554 (error "Invalid number of replications %s" n))
8555 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8556 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8557 shift)))
8558 (error "Invalid shift specification %s" shift))
8559 (when doshift
8560 (setq shift-n (string-to-number (match-string 1 shift))
8561 shift-what (cdr (assoc (match-string 2 shift)
8562 '(("d" . day) ("w" . week)
8563 ("m" . month) ("y" . year))))))
8564 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8565 (setq nmin 1 nmax n)
8566 (org-back-to-heading t)
8567 (setq beg (point))
8568 (setq idprop (org-entry-get nil "ID"))
8569 (org-end-of-subtree t t)
8570 (or (bolp) (insert "\n"))
8571 (setq end (point))
8572 (setq template (buffer-substring beg end))
8573 (when (and doshift
8574 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8575 (delete-region beg end)
8576 (setq end beg)
8577 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8578 (goto-char end)
8579 (loop for n from nmin to nmax do
8580 ;; prepare clone
8581 (with-temp-buffer
8582 (insert template)
8583 (org-mode)
8584 (goto-char (point-min))
8585 (org-show-subtree)
8586 (and idprop (if org-clone-delete-id
8587 (org-entry-delete nil "ID")
8588 (org-id-get-create t)))
8589 (unless (= n 0)
8590 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8591 (kill-whole-line))
8592 (goto-char (point-min))
8593 (while (re-search-forward drawer-re nil t)
8594 (org-remove-empty-drawer-at (point))))
8595 (goto-char (point-min))
8596 (when doshift
8597 (while (re-search-forward org-ts-regexp-both nil t)
8598 (org-timestamp-change (* n shift-n) shift-what))
8599 (unless (= n n-no-remove)
8600 (goto-char (point-min))
8601 (while (re-search-forward org-ts-regexp nil t)
8602 (save-excursion
8603 (goto-char (match-beginning 0))
8604 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8605 (delete-region (match-beginning 1) (match-end 1)))))))
8606 (setq task (buffer-string)))
8607 (insert task))
8608 (goto-char beg)))
8610 ;;; Outline Sorting
8612 (defun org-sort (with-case)
8613 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8614 Optional argument WITH-CASE means sort case-sensitively."
8615 (interactive "P")
8616 (cond
8617 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8618 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8620 (org-call-with-arg 'org-sort-entries with-case))))
8622 (defun org-sort-remove-invisible (s)
8623 "Remove invisible links from string S."
8624 (remove-text-properties 0 (length s) org-rm-props s)
8625 (while (string-match org-bracket-link-regexp s)
8626 (setq s (replace-match (if (match-end 2)
8627 (match-string 3 s)
8628 (match-string 1 s)) t t s)))
8629 (let ((st (format " %s " s)))
8630 (while (string-match org-emph-re st)
8631 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8632 (setq s (substring st 1 -1)))
8635 (defvar org-priority-regexp) ; defined later in the file
8637 (defvar org-after-sorting-entries-or-items-hook nil
8638 "Hook that is run after a bunch of entries or items have been sorted.
8639 When children are sorted, the cursor is in the parent line when this
8640 hook gets called. When a region or a plain list is sorted, the cursor
8641 will be in the first entry of the sorted region/list.")
8643 (defun org-sort-entries
8644 (&optional with-case sorting-type getkey-func compare-func property)
8645 "Sort entries on a certain level of an outline tree.
8646 If there is an active region, the entries in the region are sorted.
8647 Else, if the cursor is before the first entry, sort the top-level items.
8648 Else, the children of the entry at point are sorted.
8650 Sorting can be alphabetically, numerically, by date/time as given by
8651 a time stamp, by a property, by priority order, or by a custom function.
8653 The command prompts for the sorting type unless it has been given to the
8654 function through the SORTING-TYPE argument, which needs to be a character,
8655 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8656 precise meaning of each character:
8658 n Numerically, by converting the beginning of the entry/item to a number.
8659 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8660 o By order of TODO keywords.
8661 t By date/time, either the first active time stamp in the entry, or, if
8662 none exist, by the first inactive one.
8663 s By the scheduled date/time.
8664 d By deadline date/time.
8665 c By creation time, which is assumed to be the first inactive time stamp
8666 at the beginning of a line.
8667 p By priority according to the cookie.
8668 r By the value of a property.
8670 Capital letters will reverse the sort order.
8672 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8673 called with point at the beginning of the record. It must return either
8674 a string or a number that should serve as the sorting key for that record.
8676 Comparing entries ignores case by default. However, with an optional argument
8677 WITH-CASE, the sorting considers case as well.
8679 Sorting is done against the visible part of the headlines, it ignores hidden
8680 links.
8682 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8683 (interactive "P")
8684 (let ((case-func (if with-case 'identity 'downcase))
8685 (cmstr
8686 ;; The clock marker is lost when using `sort-subr', let's
8687 ;; store the clocking string.
8688 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8689 (save-excursion
8690 (goto-char org-clock-marker)
8691 (looking-back "^.*") (match-string-no-properties 0))))
8692 start beg end stars re re2
8693 txt what tmp)
8694 ;; Find beginning and end of region to sort
8695 (cond
8696 ((org-region-active-p)
8697 ;; we will sort the region
8698 (setq end (region-end)
8699 what "region")
8700 (goto-char (region-beginning))
8701 (if (not (org-at-heading-p)) (outline-next-heading))
8702 (setq start (point)))
8703 ((or (org-at-heading-p)
8704 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8705 ;; we will sort the children of the current headline
8706 (org-back-to-heading)
8707 (setq start (point)
8708 end (progn (org-end-of-subtree t t)
8709 (or (bolp) (insert "\n"))
8710 (org-back-over-empty-lines)
8711 (point))
8712 what "children")
8713 (goto-char start)
8714 (show-subtree)
8715 (outline-next-heading))
8717 ;; we will sort the top-level entries in this file
8718 (goto-char (point-min))
8719 (or (org-at-heading-p) (outline-next-heading))
8720 (setq start (point))
8721 (goto-char (point-max))
8722 (beginning-of-line 1)
8723 (when (looking-at ".*?\\S-")
8724 ;; File ends in a non-white line
8725 (end-of-line 1)
8726 (insert "\n"))
8727 (setq end (point-max))
8728 (setq what "top-level")
8729 (goto-char start)
8730 (show-all)))
8732 (setq beg (point))
8733 (if (>= beg end) (user-error "Nothing to sort"))
8735 (looking-at "\\(\\*+\\)")
8736 (setq stars (match-string 1)
8737 re (concat "^" (regexp-quote stars) " +")
8738 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8739 txt (buffer-substring beg end))
8740 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8741 (if (and (not (equal stars "*")) (string-match re2 txt))
8742 (user-error "Region to sort contains a level above the first entry"))
8744 (unless sorting-type
8745 (message
8746 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8747 [t]ime [s]cheduled [d]eadline [c]reated
8748 A/N/P/R/O/F/T/S/D/C means reversed:"
8749 what)
8750 (setq sorting-type (read-char-exclusive))
8752 (unless getkey-func
8753 (and (= (downcase sorting-type) ?f)
8754 (setq getkey-func
8755 (org-icompleting-read "Sort using function: "
8756 obarray 'fboundp t nil nil))
8757 (setq getkey-func (intern getkey-func))))
8759 (and (= (downcase sorting-type) ?r)
8760 (not property)
8761 (setq property
8762 (org-icompleting-read "Property: "
8763 (mapcar 'list (org-buffer-property-keys t))
8764 nil t))))
8766 (message "Sorting entries...")
8768 (save-restriction
8769 (narrow-to-region start end)
8770 (let ((dcst (downcase sorting-type))
8771 (case-fold-search nil)
8772 (now (current-time)))
8773 (sort-subr
8774 (/= dcst sorting-type)
8775 ;; This function moves to the beginning character of the "record" to
8776 ;; be sorted.
8777 (lambda nil
8778 (if (re-search-forward re nil t)
8779 (goto-char (match-beginning 0))
8780 (goto-char (point-max))))
8781 ;; This function moves to the last character of the "record" being
8782 ;; sorted.
8783 (lambda nil
8784 (save-match-data
8785 (condition-case nil
8786 (outline-forward-same-level 1)
8787 (error
8788 (goto-char (point-max))))))
8789 ;; This function returns the value that gets sorted against.
8790 (lambda nil
8791 (cond
8792 ((= dcst ?n)
8793 (if (looking-at org-complex-heading-regexp)
8794 (string-to-number (org-sort-remove-invisible (match-string 4)))
8795 nil))
8796 ((= dcst ?a)
8797 (if (looking-at org-complex-heading-regexp)
8798 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8799 nil))
8800 ((= dcst ?t)
8801 (let ((end (save-excursion (outline-next-heading) (point))))
8802 (if (or (re-search-forward org-ts-regexp end t)
8803 (re-search-forward org-ts-regexp-both end t))
8804 (org-time-string-to-seconds (match-string 0))
8805 (org-float-time now))))
8806 ((= dcst ?c)
8807 (let ((end (save-excursion (outline-next-heading) (point))))
8808 (if (re-search-forward
8809 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8810 end t)
8811 (org-time-string-to-seconds (match-string 0))
8812 (org-float-time now))))
8813 ((= dcst ?s)
8814 (let ((end (save-excursion (outline-next-heading) (point))))
8815 (if (re-search-forward org-scheduled-time-regexp end t)
8816 (org-time-string-to-seconds (match-string 1))
8817 (org-float-time now))))
8818 ((= dcst ?d)
8819 (let ((end (save-excursion (outline-next-heading) (point))))
8820 (if (re-search-forward org-deadline-time-regexp end t)
8821 (org-time-string-to-seconds (match-string 1))
8822 (org-float-time now))))
8823 ((= dcst ?p)
8824 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8825 (string-to-char (match-string 2))
8826 org-default-priority))
8827 ((= dcst ?r)
8828 (or (org-entry-get nil property) ""))
8829 ((= dcst ?o)
8830 (if (looking-at org-complex-heading-regexp)
8831 (- 9999 (length (member (match-string 2)
8832 org-todo-keywords-1)))))
8833 ((= dcst ?f)
8834 (if getkey-func
8835 (progn
8836 (setq tmp (funcall getkey-func))
8837 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8838 tmp)
8839 (error "Invalid key function `%s'" getkey-func)))
8840 (t (error "Invalid sorting type `%c'" sorting-type))))
8842 (cond
8843 ((= dcst ?a) 'string<)
8844 ((= dcst ?f) compare-func)
8845 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8846 (run-hooks 'org-after-sorting-entries-or-items-hook)
8847 ;; Reset the clock marker if needed
8848 (when cmstr
8849 (save-excursion
8850 (goto-char start)
8851 (search-forward cmstr nil t)
8852 (move-marker org-clock-marker (point))))
8853 (message "Sorting entries...done")))
8855 (defun org-do-sort (table what &optional with-case sorting-type)
8856 "Sort TABLE of WHAT according to SORTING-TYPE.
8857 The user will be prompted for the SORTING-TYPE if the call to this
8858 function does not specify it. WHAT is only for the prompt, to indicate
8859 what is being sorted. The sorting key will be extracted from
8860 the car of the elements of the table.
8861 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8862 (unless sorting-type
8863 (message
8864 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8865 what)
8866 (setq sorting-type (read-char-exclusive)))
8867 (let ((dcst (downcase sorting-type))
8868 extractfun comparefun)
8869 ;; Define the appropriate functions
8870 (cond
8871 ((= dcst ?n)
8872 (setq extractfun 'string-to-number
8873 comparefun (if (= dcst sorting-type) '< '>)))
8874 ((= dcst ?a)
8875 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8876 (lambda(x) (downcase (org-sort-remove-invisible x))))
8877 comparefun (if (= dcst sorting-type)
8878 'string<
8879 (lambda (a b) (and (not (string< a b))
8880 (not (string= a b)))))))
8881 ((= dcst ?t)
8882 (setq extractfun
8883 (lambda (x)
8884 (if (or (string-match org-ts-regexp x)
8885 (string-match org-ts-regexp-both x))
8886 (org-float-time
8887 (org-time-string-to-time (match-string 0 x)))
8889 comparefun (if (= dcst sorting-type) '< '>)))
8890 (t (error "Invalid sorting type `%c'" sorting-type)))
8892 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8893 table)
8894 (lambda (a b) (funcall comparefun (car a) (car b))))))
8897 ;;; The orgstruct minor mode
8899 ;; Define a minor mode which can be used in other modes in order to
8900 ;; integrate the org-mode structure editing commands.
8902 ;; This is really a hack, because the org-mode structure commands use
8903 ;; keys which normally belong to the major mode. Here is how it
8904 ;; works: The minor mode defines all the keys necessary to operate the
8905 ;; structure commands, but wraps the commands into a function which
8906 ;; tests if the cursor is currently at a headline or a plain list
8907 ;; item. If that is the case, the structure command is used,
8908 ;; temporarily setting many Org-mode variables like regular
8909 ;; expressions for filling etc. However, when any of those keys is
8910 ;; used at a different location, function uses `key-binding' to look
8911 ;; up if the key has an associated command in another currently active
8912 ;; keymap (minor modes, major mode, global), and executes that
8913 ;; command. There might be problems if any of the keys is otherwise
8914 ;; used as a prefix key.
8916 (defcustom orgstruct-heading-prefix-regexp ""
8917 "Regexp that matches the custom prefix of Org headlines in
8918 orgstruct(++)-mode."
8919 :group 'org
8920 :version "24.4"
8921 :package-version '(Org . "8.3")
8922 :type 'regexp)
8923 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8925 (defcustom orgstruct-setup-hook nil
8926 "Hook run after orgstruct-mode-map is filled."
8927 :group 'org
8928 :version "24.4"
8929 :package-version '(Org . "8.0")
8930 :type 'hook)
8932 (defvar orgstruct-initialized nil)
8934 (defvar org-local-vars nil
8935 "List of local variables, for use by `orgstruct-mode'.")
8937 ;;;###autoload
8938 (define-minor-mode orgstruct-mode
8939 "Toggle the minor mode `orgstruct-mode'.
8940 This mode is for using Org-mode structure commands in other
8941 modes. The following keys behave as if Org-mode were active, if
8942 the cursor is on a headline, or on a plain list item (both as
8943 defined by Org-mode)."
8944 nil " OrgStruct" (make-sparse-keymap)
8945 (funcall (if orgstruct-mode
8946 'add-to-invisibility-spec
8947 'remove-from-invisibility-spec)
8948 '(outline . t))
8949 (when orgstruct-mode
8950 (org-load-modules-maybe)
8951 (unless orgstruct-initialized
8952 (orgstruct-setup)
8953 (setq orgstruct-initialized t))))
8955 ;;;###autoload
8956 (defun turn-on-orgstruct ()
8957 "Unconditionally turn on `orgstruct-mode'."
8958 (orgstruct-mode 1))
8960 (defvar org-fb-vars nil)
8961 (make-variable-buffer-local 'org-fb-vars)
8962 (defun orgstruct++-mode (&optional arg)
8963 "Toggle `orgstruct-mode', the enhanced version of it.
8964 In addition to setting orgstruct-mode, this also exports all
8965 indentation and autofilling variables from org-mode into the
8966 buffer. It will also recognize item context in multiline items."
8967 (interactive "P")
8968 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8969 (if (< arg 1)
8970 (progn (orgstruct-mode -1)
8971 (mapc (lambda(v)
8972 (org-set-local (car v)
8973 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8974 org-fb-vars))
8975 (orgstruct-mode 1)
8976 (setq org-fb-vars nil)
8977 (unless org-local-vars
8978 (setq org-local-vars (org-get-local-variables)))
8979 (let (var val)
8980 (mapc
8981 (lambda (x)
8982 (when (string-match
8983 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8984 (symbol-name (car x)))
8985 (setq var (car x) val (nth 1 x))
8986 (push (list var `(quote ,(eval var))) org-fb-vars)
8987 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8988 org-local-vars)
8989 (org-set-local 'orgstruct-is-++ t))))
8991 (defvar orgstruct-is-++ nil
8992 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8993 (make-variable-buffer-local 'orgstruct-is-++)
8995 ;;;###autoload
8996 (defun turn-on-orgstruct++ ()
8997 "Unconditionally turn on `orgstruct++-mode'."
8998 (orgstruct++-mode 1))
9000 (defun orgstruct-error ()
9001 "Error when there is no default binding for a structure key."
9002 (interactive)
9003 (funcall (if (fboundp 'user-error)
9004 'user-error
9005 'error)
9006 "This key has no function outside structure elements"))
9008 (defun orgstruct-setup ()
9009 "Setup orgstruct keymap."
9010 (dolist (cell '((org-demote . t)
9011 (org-metaleft . t)
9012 (org-metaright . t)
9013 (org-promote . t)
9014 (org-shiftmetaleft . t)
9015 (org-shiftmetaright . t)
9016 org-backward-element
9017 org-backward-heading-same-level
9018 org-ctrl-c-ret
9019 org-ctrl-c-minus
9020 org-ctrl-c-star
9021 org-cycle
9022 org-forward-heading-same-level
9023 org-insert-heading
9024 org-insert-heading-respect-content
9025 org-kill-note-or-show-branches
9026 org-mark-subtree
9027 org-meta-return
9028 org-metadown
9029 org-metaup
9030 org-narrow-to-subtree
9031 org-promote-subtree
9032 org-reveal
9033 org-shiftdown
9034 org-shiftleft
9035 org-shiftmetadown
9036 org-shiftmetaup
9037 org-shiftright
9038 org-shifttab
9039 org-shifttab
9040 org-shiftup
9041 org-show-subtree
9042 org-sort
9043 org-up-element
9044 outline-demote
9045 outline-next-visible-heading
9046 outline-previous-visible-heading
9047 outline-promote
9048 outline-up-heading
9049 show-children))
9050 (let ((f (or (car-safe cell) cell))
9051 (disable-when-heading-prefix (cdr-safe cell)))
9052 (when (fboundp f)
9053 (let ((new-bindings))
9054 (dolist (binding (nconc (where-is-internal f org-mode-map)
9055 (where-is-internal f outline-mode-map)))
9056 (push binding new-bindings)
9057 ;; TODO use local-function-key-map
9058 (dolist (rep '(("<tab>" . "TAB")
9059 ("<return>" . "RET")
9060 ("<escape>" . "ESC")
9061 ("<delete>" . "DEL")))
9062 (setq binding (read-kbd-macro
9063 (let ((case-fold-search))
9064 (replace-regexp-in-string
9065 (regexp-quote (cdr rep))
9066 (car rep)
9067 (key-description binding)))))
9068 (pushnew binding new-bindings :test 'equal)))
9069 (dolist (binding new-bindings)
9070 (let ((key (lookup-key orgstruct-mode-map binding)))
9071 (when (or (not key) (numberp key))
9072 (condition-case nil
9073 (org-defkey orgstruct-mode-map
9074 binding
9075 (orgstruct-make-binding f binding disable-when-heading-prefix))
9076 (error nil)))))))))
9077 (run-hooks 'orgstruct-setup-hook))
9079 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9080 "Create a function for binding in the structure minor mode.
9081 FUN is the command to call inside a table. KEY is the key that
9082 should be checked in for a command to execute outside of tables.
9083 Non-nil `disable-when-heading-prefix' means to disable the command
9084 if `orgstruct-heading-prefix-regexp' is not empty."
9085 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9086 (let ((nname name)
9087 (i 0))
9088 (while (fboundp (intern nname))
9089 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9090 (setq name (intern nname)))
9091 (eval
9092 (let ((bindings '((org-heading-regexp
9093 (concat "^"
9094 orgstruct-heading-prefix-regexp
9095 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9096 (org-outline-regexp
9097 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9098 (org-outline-regexp-bol
9099 (concat "^" org-outline-regexp))
9100 (outline-regexp org-outline-regexp)
9101 (outline-heading-end-regexp "\n")
9102 (outline-level 'org-outline-level)
9103 (outline-heading-alist))))
9104 `(defun ,name (arg)
9105 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9106 "Outside of structure, run the binding of `"
9107 (key-description key) "'."
9108 (when disable-when-heading-prefix
9109 (concat
9110 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9111 "back to the default binding due to limitations of Org's implementation of\n"
9112 "`" (symbol-name fun) "'.")))
9113 (interactive "p")
9114 (let* ((disable
9115 ,(and disable-when-heading-prefix
9116 '(not (string= orgstruct-heading-prefix-regexp ""))))
9117 (fallback
9118 (or disable
9119 (not
9120 (let* ,bindings
9121 (org-context-p 'headline 'item
9122 ,(when (memq fun
9123 '(org-insert-heading
9124 org-insert-heading-respect-content
9125 org-meta-return))
9126 '(when orgstruct-is-++
9127 'item-body))))))))
9128 (if fallback
9129 (let* ((orgstruct-mode)
9130 (binding
9131 (loop with key = ,key
9132 for rep in
9133 '(nil
9134 ("<\\([^>]*\\)tab>" . "\\1TAB")
9135 ("<\\([^>]*\\)return>" . "\\1RET")
9136 ("<\\([^>]*\\)escape>" . "\\1ESC")
9137 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9139 (when rep
9140 (setq key (read-kbd-macro
9141 (let ((case-fold-search))
9142 (replace-regexp-in-string
9143 (car rep)
9144 (cdr rep)
9145 (key-description key))))))
9146 thereis (key-binding key))))
9147 (if (keymapp binding)
9148 (set-temporary-overlay-map binding)
9149 (let ((func (or binding
9150 (unless disable
9151 'orgstruct-error))))
9152 (when func
9153 (call-interactively func)))))
9154 (org-run-like-in-org-mode
9155 (lambda ()
9156 (interactive)
9157 (let* ,bindings
9158 (call-interactively ',fun)))))))))
9159 name))
9161 (defun org-contextualize-keys (alist contexts)
9162 "Return valid elements in ALIST depending on CONTEXTS.
9164 `org-agenda-custom-commands' or `org-capture-templates' are the
9165 values used for ALIST, and `org-agenda-custom-commands-contexts'
9166 or `org-capture-templates-contexts' are the associated contexts
9167 definitions."
9168 (let ((contexts
9169 ;; normalize contexts
9170 (mapcar
9171 (lambda(c) (cond ((listp (cadr c))
9172 (list (car c) (car c) (cadr c)))
9173 ((string= "" (cadr c))
9174 (list (car c) (car c) (caddr c)))
9175 (t c))) contexts))
9176 (a alist) c r s)
9177 ;; loop over all commands or templates
9178 (while (setq c (pop a))
9179 (let (vrules repl)
9180 (cond
9181 ((not (assoc (car c) contexts))
9182 (push c r))
9183 ((and (assoc (car c) contexts)
9184 (setq vrules (org-contextualize-validate-key
9185 (car c) contexts)))
9186 (mapc (lambda (vr)
9187 (when (not (equal (car vr) (cadr vr)))
9188 (setq repl vr))) vrules)
9189 (if (not repl) (push c r)
9190 (push (cadr repl) s)
9191 (push
9192 (cons (car c)
9193 (cdr (or (assoc (cadr repl) alist)
9194 (error "Undefined key `%s' as contextual replacement for `%s'"
9195 (cadr repl) (car c)))))
9196 r))))))
9197 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9198 (delq
9200 (delete-dups
9201 (mapcar (lambda (x)
9202 (let ((tpl (car x)))
9203 (when (not (delq
9205 (mapcar (lambda(y)
9206 (equal y tpl)) s))) x)))
9207 (reverse r))))))
9209 (defun org-contextualize-validate-key (key contexts)
9210 "Check CONTEXTS for agenda or capture KEY."
9211 (let (r rr res)
9212 (while (setq r (pop contexts))
9213 (mapc
9214 (lambda (rr)
9215 (when
9216 (and (equal key (car r))
9217 (if (functionp rr) (funcall rr)
9218 (or (and (eq (car rr) 'in-file)
9219 (buffer-file-name)
9220 (string-match (cdr rr) (buffer-file-name)))
9221 (and (eq (car rr) 'in-mode)
9222 (string-match (cdr rr) (symbol-name major-mode)))
9223 (and (eq (car rr) 'in-buffer)
9224 (string-match (cdr rr) (buffer-name)))
9225 (when (and (eq (car rr) 'not-in-file)
9226 (buffer-file-name))
9227 (not (string-match (cdr rr) (buffer-file-name))))
9228 (when (eq (car rr) 'not-in-mode)
9229 (not (string-match (cdr rr) (symbol-name major-mode))))
9230 (when (eq (car rr) 'not-in-buffer)
9231 (not (string-match (cdr rr) (buffer-name)))))))
9232 (push r res)))
9233 (car (last r))))
9234 (delete-dups (delq nil res))))
9236 (defun org-context-p (&rest contexts)
9237 "Check if local context is any of CONTEXTS.
9238 Possible values in the list of contexts are `table', `headline', and `item'."
9239 (let ((pos (point)))
9240 (goto-char (point-at-bol))
9241 (prog1 (or (and (memq 'table contexts)
9242 (looking-at "[ \t]*|"))
9243 (and (memq 'headline contexts)
9244 (looking-at org-outline-regexp))
9245 (and (memq 'item contexts)
9246 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9247 (and (memq 'item-body contexts)
9248 (org-in-item-p)))
9249 (goto-char pos))))
9251 (defun org-get-local-variables ()
9252 "Return a list of all local variables in an Org mode buffer."
9253 (let (varlist)
9254 (with-current-buffer (get-buffer-create "*Org tmp*")
9255 (erase-buffer)
9256 (org-mode)
9257 (setq varlist (buffer-local-variables)))
9258 (kill-buffer "*Org tmp*")
9259 (delq nil
9260 (mapcar
9261 (lambda (x)
9262 (setq x
9263 (if (symbolp x)
9264 (list x)
9265 (list (car x) (cdr x))))
9266 (if (and (not (get (car x) 'org-state))
9267 (string-match
9268 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9269 (symbol-name (car x))))
9270 x nil))
9271 varlist))))
9273 (defun org-clone-local-variables (from-buffer &optional regexp)
9274 "Clone local variables from FROM-BUFFER.
9275 Optional argument REGEXP selects variables to clone."
9276 (mapc
9277 (lambda (pair)
9278 (and (symbolp (car pair))
9279 (or (null regexp)
9280 (string-match regexp (symbol-name (car pair))))
9281 (set (make-local-variable (car pair))
9282 (cdr pair))))
9283 (buffer-local-variables from-buffer)))
9285 ;;;###autoload
9286 (defun org-run-like-in-org-mode (cmd)
9287 "Run a command, pretending that the current buffer is in Org-mode.
9288 This will temporarily bind local variables that are typically bound in
9289 Org-mode to the values they have in Org-mode, and then interactively
9290 call CMD."
9291 (org-load-modules-maybe)
9292 (unless org-local-vars
9293 (setq org-local-vars (org-get-local-variables)))
9294 (let (binds)
9295 (dolist (var org-local-vars)
9296 (when (or (not (boundp (car var)))
9297 (eq (symbol-value (car var))
9298 (default-value (car var))))
9299 (push (list (car var) `(quote ,(cadr var))) binds)))
9300 (eval `(let ,binds
9301 (call-interactively (quote ,cmd))))))
9303 ;;;; Archiving
9305 (defun org-get-category (&optional pos force-refresh)
9306 "Get the category applying to position POS."
9307 (save-match-data
9308 (if force-refresh (org-refresh-category-properties))
9309 (let ((pos (or pos (point))))
9310 (or (get-text-property pos 'org-category)
9311 (progn (org-refresh-category-properties)
9312 (get-text-property pos 'org-category))))))
9314 (defun org-refresh-category-properties ()
9315 "Refresh category text properties in the buffer."
9316 (let ((case-fold-search t)
9317 (inhibit-read-only t)
9318 (def-cat (cond
9319 ((null org-category)
9320 (if buffer-file-name
9321 (file-name-sans-extension
9322 (file-name-nondirectory buffer-file-name))
9323 "???"))
9324 ((symbolp org-category) (symbol-name org-category))
9325 (t org-category)))
9326 beg end cat pos optionp)
9327 (org-with-silent-modifications
9328 (save-excursion
9329 (save-restriction
9330 (widen)
9331 (goto-char (point-min))
9332 (put-text-property (point) (point-max) 'org-category def-cat)
9333 (while (re-search-forward
9334 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9335 (setq pos (match-end 0)
9336 optionp (equal (char-after (match-beginning 0)) ?#)
9337 cat (org-trim (match-string 2)))
9338 (if optionp
9339 (setq beg (point-at-bol) end (point-max))
9340 (org-back-to-heading t)
9341 (setq beg (point) end (org-end-of-subtree t t)))
9342 (put-text-property beg end 'org-category cat)
9343 (put-text-property beg end 'org-category-position beg)
9344 (goto-char pos)))))))
9346 (defun org-refresh-properties (dprop tprop)
9347 "Refresh buffer text properties.
9348 DPROP is the drawer property and TPROP is the corresponding text
9349 property to set."
9350 (let ((case-fold-search t)
9351 (inhibit-read-only t) p)
9352 (org-with-silent-modifications
9353 (save-excursion
9354 (save-restriction
9355 (widen)
9356 (goto-char (point-min))
9357 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9358 (setq p (org-match-string-no-properties 1))
9359 (save-excursion
9360 (org-back-to-heading t)
9361 (put-text-property
9362 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9365 ;;;; Link Stuff
9367 ;;; Link abbreviations
9369 (defun org-link-expand-abbrev (link)
9370 "Apply replacements as defined in `org-link-abbrev-alist'."
9371 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9372 (let* ((key (match-string 1 link))
9373 (as (or (assoc key org-link-abbrev-alist-local)
9374 (assoc key org-link-abbrev-alist)))
9375 (tag (and (match-end 2) (match-string 3 link)))
9376 rpl)
9377 (if (not as)
9378 link
9379 (setq rpl (cdr as))
9380 (cond
9381 ((symbolp rpl) (funcall rpl tag))
9382 ((string-match "%(\\([^)]+\\))" rpl)
9383 (replace-match
9384 (save-match-data
9385 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9386 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9387 ((string-match "%h" rpl)
9388 (replace-match (url-hexify-string (or tag "")) t t rpl))
9389 (t (concat rpl tag)))))
9390 link))
9392 ;;; Storing and inserting links
9394 (defvar org-insert-link-history nil
9395 "Minibuffer history for links inserted with `org-insert-link'.")
9397 (defvar org-stored-links nil
9398 "Contains the links stored with `org-store-link'.")
9400 (defvar org-store-link-plist nil
9401 "Plist with info about the most recently link created with `org-store-link'.")
9403 (defvar org-link-protocols nil
9404 "Link protocols added to Org-mode using `org-add-link-type'.")
9406 (defvar org-store-link-functions nil
9407 "List of functions that are called to create and store a link.
9408 Each function will be called in turn until one returns a non-nil
9409 value. Each function should check if it is responsible for creating
9410 this link (for example by looking at the major mode).
9411 If not, it must exit and return nil.
9412 If yes, it should return a non-nil value after a calling
9413 `org-store-link-props' with a list of properties and values.
9414 Special properties are:
9416 :type The link prefix, like \"http\". This must be given.
9417 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9418 This is obligatory as well.
9419 :description Optional default description for the second pair
9420 of brackets in an Org-mode link. The user can still change
9421 this when inserting this link into an Org-mode buffer.
9423 In addition to these, any additional properties can be specified
9424 and then used in capture templates.")
9426 (defun org-add-link-type (type &optional follow export)
9427 "Add TYPE to the list of `org-link-types'.
9428 Re-compute all regular expressions depending on `org-link-types'
9430 FOLLOW and EXPORT are two functions.
9432 FOLLOW should take the link path as the single argument and do whatever
9433 is necessary to follow the link, for example find a file or display
9434 a mail message.
9436 EXPORT should format the link path for export to one of the export formats.
9437 It should be a function accepting three arguments:
9439 path the path of the link, the text after the prefix (like \"http:\")
9440 desc the description of the link, if any, or a description added by
9441 org-export-normalize-links if there is none
9442 format the export format, a symbol like `html' or `latex' or `ascii'..
9444 The function may use the FORMAT information to return different values
9445 depending on the format. The return value will be put literally into
9446 the exported file. If the return value is nil, this means Org should
9447 do what it normally does with links which do not have EXPORT defined.
9449 Org-mode has a built-in default for exporting links. If you are happy with
9450 this default, there is no need to define an export function for the link
9451 type. For a simple example of an export function, see `org-bbdb.el'."
9452 (add-to-list 'org-link-types type t)
9453 (org-make-link-regexps)
9454 (if (assoc type org-link-protocols)
9455 (setcdr (assoc type org-link-protocols) (list follow export))
9456 (push (list type follow export) org-link-protocols)))
9458 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9459 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9461 ;;;###autoload
9462 (defun org-store-link (arg)
9463 "\\<org-mode-map>Store an org-link to the current location.
9464 This link is added to `org-stored-links' and can later be inserted
9465 into an org-buffer with \\[org-insert-link].
9467 For some link types, a prefix arg is interpreted.
9468 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9469 For file links, arg negates `org-context-in-file-links'.
9471 A double prefix arg force skipping storing functions that are not
9472 part of Org's core.
9474 A triple prefix arg force storing a link for each line in the
9475 active region."
9476 (interactive "P")
9477 (org-load-modules-maybe)
9478 (if (and (equal arg '(64)) (org-region-active-p))
9479 (save-excursion
9480 (let ((end (region-end)))
9481 (goto-char (region-beginning))
9482 (set-mark (point))
9483 (while (< (point-at-eol) end)
9484 (move-end-of-line 1) (activate-mark)
9485 (let (current-prefix-arg)
9486 (call-interactively 'org-store-link))
9487 (move-beginning-of-line 2)
9488 (set-mark (point)))))
9489 (org-with-limited-levels
9490 (setq org-store-link-plist nil)
9491 (let (link cpltxt desc description search
9492 txt custom-id agenda-link sfuns sfunsn)
9493 (cond
9495 ;; Store a link using an external link type
9496 ((and (not (equal arg '(16)))
9497 (setq sfuns
9498 (delq
9499 nil (mapcar (lambda (f)
9500 (let (fs) (if (funcall f) (push f fs))))
9501 org-store-link-functions))
9502 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9503 (or (and (cdr sfuns)
9504 (funcall (intern
9505 (completing-read
9506 "Which function for creating the link? "
9507 sfunsn t (car sfunsn)))))
9508 (funcall (caar sfuns)))
9509 (setq link (plist-get org-store-link-plist :link)
9510 desc (or (plist-get org-store-link-plist
9511 :description) link))))
9513 ;; Store a link from a source code buffer
9514 ((org-src-edit-buffer-p)
9515 (let (label gc)
9516 (while (or (not label)
9517 (save-excursion
9518 (save-restriction
9519 (widen)
9520 (goto-char (point-min))
9521 (re-search-forward
9522 (regexp-quote (format org-coderef-label-format label))
9523 nil t))))
9524 (when label (message "Label exists already") (sit-for 2))
9525 (setq label (read-string "Code line label: " label)))
9526 (end-of-line 1)
9527 (setq link (format org-coderef-label-format label))
9528 (setq gc (- 79 (length link)))
9529 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9530 (insert link)
9531 (setq link (concat "(" label ")") desc nil)))
9533 ;; We are in the agenda, link to referenced location
9534 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9535 (let ((m (or (get-text-property (point) 'org-hd-marker)
9536 (get-text-property (point) 'org-marker))))
9537 (when m
9538 (org-with-point-at m
9539 (setq agenda-link
9540 (if (org-called-interactively-p 'any)
9541 (call-interactively 'org-store-link)
9542 (org-store-link nil)))))))
9544 ((eq major-mode 'calendar-mode)
9545 (let ((cd (calendar-cursor-to-date)))
9546 (setq link
9547 (format-time-string
9548 (car org-time-stamp-formats)
9549 (apply 'encode-time
9550 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9551 nil nil nil))))
9552 (org-store-link-props :type "calendar" :date cd)))
9554 ((eq major-mode 'help-mode)
9555 (setq link (concat "help:" (save-excursion
9556 (goto-char (point-min))
9557 (looking-at "^[^ ]+")
9558 (match-string 0))))
9559 (org-store-link-props :type "help"))
9561 ((eq major-mode 'w3-mode)
9562 (setq cpltxt (if (and (buffer-name)
9563 (not (string-match "Untitled" (buffer-name))))
9564 (buffer-name)
9565 (url-view-url t))
9566 link (url-view-url t))
9567 (org-store-link-props :type "w3" :url (url-view-url t)))
9569 ((eq major-mode 'image-mode)
9570 (setq cpltxt (concat "file:"
9571 (abbreviate-file-name buffer-file-name))
9572 link cpltxt)
9573 (org-store-link-props :type "image" :file buffer-file-name))
9575 ;; In dired, store a link to the file of the current line
9576 ((eq major-mode 'dired-mode)
9577 (let ((file (dired-get-filename nil t)))
9578 (setq file (if file
9579 (abbreviate-file-name
9580 (expand-file-name (dired-get-filename nil t)))
9581 ;; otherwise, no file so use current directory.
9582 default-directory))
9583 (setq cpltxt (concat "file:" file)
9584 link cpltxt)))
9586 ((setq search (run-hook-with-args-until-success
9587 'org-create-file-search-functions))
9588 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9589 "::" search))
9590 (setq cpltxt (or description link)))
9592 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9593 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9594 (cond
9595 ;; Store a link using the target at point
9596 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9597 (setq cpltxt
9598 (concat "file:"
9599 (abbreviate-file-name
9600 (buffer-file-name (buffer-base-buffer)))
9601 "::" (match-string 1))
9602 link cpltxt))
9603 ((and (featurep 'org-id)
9604 (or (eq org-id-link-to-org-use-id t)
9605 (and (org-called-interactively-p 'any)
9606 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9607 (and (eq org-id-link-to-org-use-id
9608 'create-if-interactive-and-no-custom-id)
9609 (not custom-id))))
9610 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9611 ;; Store a link using the ID at point
9612 (setq link (condition-case nil
9613 (prog1 (org-id-store-link)
9614 (setq desc (plist-get org-store-link-plist
9615 :description)))
9616 (error
9617 ;; Probably before first headline, link only to file
9618 (concat "file:"
9619 (abbreviate-file-name
9620 (buffer-file-name (buffer-base-buffer))))))))
9622 ;; Just link to current headline
9623 (setq cpltxt (concat "file:"
9624 (abbreviate-file-name
9625 (buffer-file-name (buffer-base-buffer)))))
9626 ;; Add a context search string
9627 (when (org-xor org-context-in-file-links arg)
9628 (let* ((ee (org-element-at-point))
9629 (et (org-element-type ee))
9630 (ev (plist-get (cadr ee) :value))
9631 (ek (plist-get (cadr ee) :key))
9632 (eok (and (stringp ek) (string-match "name" ek))))
9633 (setq txt (cond
9634 ((org-at-heading-p) nil)
9635 ((and (eq et 'keyword) eok) ev)
9636 ((org-region-active-p)
9637 (buffer-substring (region-beginning) (region-end)))))
9638 (when (or (null txt) (string-match "\\S-" txt))
9639 (setq cpltxt
9640 (concat cpltxt "::"
9641 (condition-case nil
9642 (org-make-org-heading-search-string txt)
9643 (error "")))
9644 desc (or (and (eq et 'keyword) eok ev)
9645 (nth 4 (ignore-errors (org-heading-components)))
9646 "NONE")))))
9647 (if (string-match "::\\'" cpltxt)
9648 (setq cpltxt (substring cpltxt 0 -2)))
9649 (setq link cpltxt))))
9651 ((buffer-file-name (buffer-base-buffer))
9652 ;; Just link to this file here.
9653 (setq cpltxt (concat "file:"
9654 (abbreviate-file-name
9655 (buffer-file-name (buffer-base-buffer)))))
9656 ;; Add a context string.
9657 (when (org-xor org-context-in-file-links arg)
9658 (setq txt (if (org-region-active-p)
9659 (buffer-substring (region-beginning) (region-end))
9660 (buffer-substring (point-at-bol) (point-at-eol))))
9661 ;; Only use search option if there is some text.
9662 (when (string-match "\\S-" txt)
9663 (setq cpltxt
9664 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9665 desc "NONE")))
9666 (setq link cpltxt))
9668 ((org-called-interactively-p 'interactive)
9669 (user-error "No method for storing a link from this buffer"))
9671 (t (setq link nil)))
9673 ;; We're done setting link and desc, clean up
9674 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9675 (setq link (or link cpltxt)
9676 desc (or desc cpltxt))
9677 (cond ((equal desc "NONE") (setq desc nil))
9678 ((string-match org-bracket-link-analytic-regexp desc)
9679 (let ((d0 (match-string 3 desc))
9680 (p0 (match-string 5 desc)))
9681 (setq desc
9682 (replace-regexp-in-string
9683 org-bracket-link-regexp
9684 (concat (or p0 d0)
9685 (if (equal (length (match-string 0 desc))
9686 (length desc)) "*" "")) desc)))))
9688 ;; Return the link
9689 (if (not (and (or (org-called-interactively-p 'any)
9690 executing-kbd-macro) link))
9691 (or agenda-link (and link (org-make-link-string link desc)))
9692 (push (list link desc) org-stored-links)
9693 (message "Stored: %s" (or desc link))
9694 (when custom-id
9695 (setq link (concat "file:" (abbreviate-file-name
9696 (buffer-file-name)) "::#" custom-id))
9697 (push (list link desc) org-stored-links)))))))
9699 (defun org-store-link-props (&rest plist)
9700 "Store link properties, extract names and addresses."
9701 (let (x adr)
9702 (when (setq x (plist-get plist :from))
9703 (setq adr (mail-extract-address-components x))
9704 (setq plist (plist-put plist :fromname (car adr)))
9705 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9706 (when (setq x (plist-get plist :to))
9707 (setq adr (mail-extract-address-components x))
9708 (setq plist (plist-put plist :toname (car adr)))
9709 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9710 (let ((from (plist-get plist :from))
9711 (to (plist-get plist :to)))
9712 (when (and from to org-from-is-user-regexp)
9713 (setq plist
9714 (plist-put plist :fromto
9715 (if (string-match org-from-is-user-regexp from)
9716 (concat "to %t")
9717 (concat "from %f"))))))
9718 (setq org-store-link-plist plist))
9720 (defun org-add-link-props (&rest plist)
9721 "Add these properties to the link property list."
9722 (let (key value)
9723 (while plist
9724 (setq key (pop plist) value (pop plist))
9725 (setq org-store-link-plist
9726 (plist-put org-store-link-plist key value)))))
9728 (defun org-email-link-description (&optional fmt)
9729 "Return the description part of an email link.
9730 This takes information from `org-store-link-plist' and formats it
9731 according to FMT (default from `org-email-link-description-format')."
9732 (setq fmt (or fmt org-email-link-description-format))
9733 (let* ((p org-store-link-plist)
9734 (to (plist-get p :toaddress))
9735 (from (plist-get p :fromaddress))
9736 (table
9737 (list
9738 (cons "%c" (plist-get p :fromto))
9739 (cons "%F" (plist-get p :from))
9740 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9741 (cons "%T" (plist-get p :to))
9742 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9743 (cons "%s" (plist-get p :subject))
9744 (cons "%d" (plist-get p :date))
9745 (cons "%m" (plist-get p :message-id)))))
9746 (when (string-match "%c" fmt)
9747 ;; Check if the user wrote this message
9748 (if (and org-from-is-user-regexp from to
9749 (save-match-data (string-match org-from-is-user-regexp from)))
9750 (setq fmt (replace-match "to %t" t t fmt))
9751 (setq fmt (replace-match "from %f" t t fmt))))
9752 (org-replace-escapes fmt table)))
9754 (defun org-make-org-heading-search-string (&optional string)
9755 "Make search string for the current headline or STRING."
9756 (let ((s (or string
9757 (and (derived-mode-p 'org-mode)
9758 (save-excursion
9759 (org-back-to-heading t)
9760 (org-element-property :raw-value (org-element-at-point))))))
9761 (lines org-context-in-file-links))
9762 (or string (setq s (concat "*" s))) ; Add * for headlines
9763 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9764 (when (and string (integerp lines) (> lines 0))
9765 (let ((slines (org-split-string s "\n")))
9766 (when (< lines (length slines))
9767 (setq s (mapconcat
9768 'identity
9769 (reverse (nthcdr (- (length slines) lines)
9770 (reverse slines))) "\n")))))
9771 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9773 (defun org-make-link-string (link &optional description)
9774 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9775 (unless (string-match "\\S-" link)
9776 (error "Empty link"))
9777 (when (and description
9778 (stringp description)
9779 (not (string-match "\\S-" description)))
9780 (setq description nil))
9781 (when (stringp description)
9782 ;; Remove brackets from the description, they are fatal.
9783 (while (string-match "\\[" description)
9784 (setq description (replace-match "{" t t description)))
9785 (while (string-match "\\]" description)
9786 (setq description (replace-match "}" t t description))))
9787 (when (equal link description)
9788 ;; No description needed, it is identical
9789 (setq description nil))
9790 (when (and (not description)
9791 (not (string-match (org-image-file-name-regexp) link))
9792 (not (equal link (org-link-escape link))))
9793 (setq description (org-extract-attributes link)))
9794 (setq link
9795 (cond ((string-match (org-image-file-name-regexp) link) link)
9796 ((string-match org-link-types-re link)
9797 (concat (match-string 1 link)
9798 (org-link-escape (substring link (match-end 1)))))
9799 (t (org-link-escape link))))
9800 (concat "[[" link "]"
9801 (if description (concat "[" description "]") "")
9802 "]"))
9804 (defconst org-link-escape-chars
9805 ;;%20 %2B %3B %3D %5B %5D
9806 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9807 "List of characters that should be escaped in link.
9808 This is the list that is used for internal purposes.")
9810 (defconst org-link-escape-chars-browser
9811 ;;%20 %22
9812 '(?\ ?\")
9813 "List of escapes for characters that are problematic in links.
9814 This is the list that is used before handing over to the browser.")
9816 (defun org-link-escape (text &optional table merge)
9817 "Return percent escaped representation of TEXT.
9818 TEXT is a string with the text to escape.
9819 Optional argument TABLE is a list with characters that should be
9820 escaped. When nil, `org-link-escape-chars' is used.
9821 If optional argument MERGE is set, merge TABLE into
9822 `org-link-escape-chars'."
9823 (cond
9824 ((and table merge)
9825 (mapc (lambda (defchr)
9826 (unless (member defchr table)
9827 (setq table (cons defchr table)))) org-link-escape-chars))
9828 ((null table)
9829 (setq table org-link-escape-chars)))
9830 (mapconcat
9831 (lambda (char)
9832 (if (or (member char table)
9833 (and (or (< char 32) (= char ?\%) (> char 126))
9834 org-url-hexify-p))
9835 (mapconcat (lambda (sequence-element)
9836 (format "%%%.2X" sequence-element))
9837 (or (encode-coding-char char 'utf-8)
9838 (error "Unable to percent escape character: %s"
9839 (char-to-string char))) "")
9840 (char-to-string char))) text ""))
9842 (defun org-link-escape-browser (text)
9843 (if (org-string-match-p
9844 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9845 text)
9846 (org-link-escape text org-link-escape-chars-browser)
9847 text))
9849 (defun org-link-unescape (str)
9850 "Unhex hexified Unicode strings as returned from the JavaScript function
9851 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9852 (unless (and (null str) (string= "" str))
9853 (let ((pos 0) (case-fold-search t) unhexed)
9854 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9855 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9856 (setq str (replace-match unhexed t t str))
9857 (setq pos (+ pos (length unhexed))))))
9858 str)
9860 (defun org-link-unescape-compound (hex)
9861 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9862 Note: this function also decodes single byte encodings like
9863 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9864 (save-match-data
9865 (let* ((bytes (cdr (split-string hex "%")))
9866 (ret "")
9867 (eat 0)
9868 (sum 0))
9869 (while bytes
9870 (let* ((val (string-to-number (pop bytes) 16))
9871 (shift-xor
9872 (if (= 0 eat)
9873 (cond
9874 ((>= val 252) (cons 6 252))
9875 ((>= val 248) (cons 5 248))
9876 ((>= val 240) (cons 4 240))
9877 ((>= val 224) (cons 3 224))
9878 ((>= val 192) (cons 2 192))
9879 (t (cons 0 0)))
9880 (cons 6 128))))
9881 (if (>= val 192) (setq eat (car shift-xor)))
9882 (setq val (logxor val (cdr shift-xor)))
9883 (setq sum (+ (lsh sum (car shift-xor)) val))
9884 (if (> eat 0) (setq eat (- eat 1)))
9885 (cond
9886 ((= 0 eat) ;multi byte
9887 (setq ret (concat ret (org-char-to-string sum)))
9888 (setq sum 0))
9889 ((not bytes) ; single byte(s)
9890 (setq ret (org-link-unescape-single-byte-sequence hex))))
9891 )) ;; end (while bytes
9892 ret )))
9894 (defun org-link-unescape-single-byte-sequence (hex)
9895 "Unhexify hex-encoded single byte character sequences."
9896 (mapconcat (lambda (byte)
9897 (char-to-string (string-to-number byte 16)))
9898 (cdr (split-string hex "%")) ""))
9900 (defun org-xor (a b)
9901 "Exclusive or."
9902 (if a (not b) b))
9904 (defun org-fixup-message-id-for-http (s)
9905 "Replace special characters in a message id, so it can be used in an http query."
9906 (when (string-match "%" s)
9907 (setq s (mapconcat (lambda (c)
9908 (if (eq c ?%)
9909 "%25"
9910 (char-to-string c)))
9911 s "")))
9912 (while (string-match "<" s)
9913 (setq s (replace-match "%3C" t t s)))
9914 (while (string-match ">" s)
9915 (setq s (replace-match "%3E" t t s)))
9916 (while (string-match "@" s)
9917 (setq s (replace-match "%40" t t s)))
9920 (defun org-link-prettify (link)
9921 "Return a human-readable representation of LINK.
9922 The car of LINK must be a raw link the cdr of LINK must be either
9923 a link description or nil."
9924 (let ((desc (or (cadr link) "<no description>")))
9925 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9926 "<" (car link) ">")))
9928 ;;;###autoload
9929 (defun org-insert-link-global ()
9930 "Insert a link like Org-mode does.
9931 This command can be called in any mode to insert a link in Org-mode syntax."
9932 (interactive)
9933 (org-load-modules-maybe)
9934 (org-run-like-in-org-mode 'org-insert-link))
9936 (defun org-insert-all-links (&optional keep)
9937 "Insert all links in `org-stored-links'."
9938 (interactive "P")
9939 (let ((links (copy-sequence org-stored-links)) l)
9940 (while (setq l (if keep (pop links) (pop org-stored-links)))
9941 (insert "- ")
9942 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9943 (insert "\n"))))
9945 (defun org-link-fontify-links-to-this-file ()
9946 "Fontify links to the current file in `org-stored-links'."
9947 (let ((f (buffer-file-name)) a b)
9948 (setq a (mapcar (lambda(l)
9949 (let ((ll (car l)))
9950 (when (and (string-match "^file:\\(.+\\)::" ll)
9951 (equal f (expand-file-name (match-string 1 ll))))
9952 ll)))
9953 org-stored-links))
9954 (when (featurep 'org-id)
9955 (setq b (mapcar (lambda(l)
9956 (let ((ll (car l)))
9957 (when (and (string-match "^id:\\(.+\\)$" ll)
9958 (equal f (expand-file-name
9959 (or (org-id-find-id-file
9960 (match-string 1 ll)) ""))))
9961 ll)))
9962 org-stored-links)))
9963 (mapcar (lambda(l)
9964 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9965 (delq nil (append a b)))))
9967 (defvar org-link-links-in-this-file nil)
9968 (defun org-insert-link (&optional complete-file link-location default-description)
9969 "Insert a link. At the prompt, enter the link.
9971 Completion can be used to insert any of the link protocol prefixes like
9972 http or ftp in use.
9974 The history can be used to select a link previously stored with
9975 `org-store-link'. When the empty string is entered (i.e. if you just
9976 press RET at the prompt), the link defaults to the most recently
9977 stored link. As SPC triggers completion in the minibuffer, you need to
9978 use M-SPC or C-q SPC to force the insertion of a space character.
9980 You will also be prompted for a description, and if one is given, it will
9981 be displayed in the buffer instead of the link.
9983 If there is already a link at point, this command will allow you to edit link
9984 and description parts.
9986 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9987 be selected using completion. The path to the file will be relative to the
9988 current directory if the file is in the current directory or a subdirectory.
9989 Otherwise, the link will be the absolute path as completed in the minibuffer
9990 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9991 option `org-link-file-path-type'.
9993 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9994 the current directory or below.
9996 With three \\[universal-argument] prefixes, negate the meaning of
9997 `org-keep-stored-link-after-insertion'.
9999 If `org-make-link-description-function' is non-nil, this function will be
10000 called with the link target, and the result will be the default
10001 link description.
10003 If the LINK-LOCATION parameter is non-nil, this value will be
10004 used as the link location instead of reading one interactively.
10006 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10007 be used as the default description."
10008 (interactive "P")
10009 (let* ((wcf (current-window-configuration))
10010 (origbuf (current-buffer))
10011 (region (if (org-region-active-p)
10012 (buffer-substring (region-beginning) (region-end))))
10013 (remove (and region (list (region-beginning) (region-end))))
10014 (desc region)
10015 tmphist ; byte-compile incorrectly complains about this
10016 (link link-location)
10017 (abbrevs org-link-abbrev-alist-local)
10018 entry file all-prefixes auto-desc)
10019 (cond
10020 (link-location) ; specified by arg, just use it.
10021 ((org-in-regexp org-bracket-link-regexp 1)
10022 ;; We do have a link at point, and we are going to edit it.
10023 (setq remove (list (match-beginning 0) (match-end 0)))
10024 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10025 (setq link (read-string "Link: "
10026 (org-link-unescape
10027 (org-match-string-no-properties 1)))))
10028 ((or (org-in-regexp org-angle-link-re)
10029 (org-in-regexp org-plain-link-re))
10030 ;; Convert to bracket link
10031 (setq remove (list (match-beginning 0) (match-end 0))
10032 link (read-string "Link: "
10033 (org-remove-angle-brackets (match-string 0)))))
10034 ((member complete-file '((4) (16)))
10035 ;; Completing read for file names.
10036 (setq link (org-file-complete-link complete-file)))
10038 ;; Read link, with completion for stored links.
10039 (org-link-fontify-links-to-this-file)
10040 (org-switch-to-buffer-other-window "*Org Links*")
10041 (with-current-buffer "*Org Links*"
10042 (erase-buffer)
10043 (insert "Insert a link.
10044 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10045 (when org-stored-links
10046 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10047 (insert (mapconcat 'org-link-prettify
10048 (reverse org-stored-links) "\n")))
10049 (goto-char (point-min)))
10050 (let ((cw (selected-window)))
10051 (select-window (get-buffer-window "*Org Links*" 'visible))
10052 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10053 (unless (pos-visible-in-window-p (point-max))
10054 (org-fit-window-to-buffer))
10055 (and (window-live-p cw) (select-window cw)))
10056 ;; Fake a link history, containing the stored links.
10057 (setq tmphist (append (mapcar 'car org-stored-links)
10058 org-insert-link-history))
10059 (setq all-prefixes (append (mapcar 'car abbrevs)
10060 (mapcar 'car org-link-abbrev-alist)
10061 org-link-types))
10062 (unwind-protect
10063 (progn
10064 (setq link
10065 (org-completing-read
10066 "Link: "
10067 (append
10068 (mapcar (lambda (x) (concat x ":"))
10069 all-prefixes)
10070 (mapcar 'car org-stored-links))
10071 nil nil nil
10072 'tmphist
10073 (caar org-stored-links)))
10074 (if (not (string-match "\\S-" link))
10075 (user-error "No link selected"))
10076 (mapc (lambda(l)
10077 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10078 org-stored-links)
10079 (if (or (member link all-prefixes)
10080 (and (equal ":" (substring link -1))
10081 (member (substring link 0 -1) all-prefixes)
10082 (setq link (substring link 0 -1))))
10083 (setq link (with-current-buffer origbuf
10084 (org-link-try-special-completion link)))))
10085 (set-window-configuration wcf)
10086 (kill-buffer "*Org Links*"))
10087 (setq entry (assoc link org-stored-links))
10088 (or entry (push link org-insert-link-history))
10089 (setq desc (or desc (nth 1 entry)))))
10091 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10092 (not org-keep-stored-link-after-insertion))
10093 (setq org-stored-links (delq (assoc link org-stored-links)
10094 org-stored-links)))
10096 (if (and (string-match org-plain-link-re link)
10097 (not (string-match org-ts-regexp link)))
10098 ;; URL-like link, normalize the use of angular brackets.
10099 (setq link (org-remove-angle-brackets link)))
10101 ;; Check if we are linking to the current file with a search
10102 ;; option If yes, simplify the link by using only the search
10103 ;; option.
10104 (when (and buffer-file-name
10105 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10106 (let* ((path (match-string 1 link))
10107 (case-fold-search nil)
10108 (search (match-string 2 link)))
10109 (save-match-data
10110 (if (equal (file-truename buffer-file-name) (file-truename path))
10111 ;; We are linking to this same file, with a search option
10112 (setq link search)))))
10114 ;; Check if we can/should use a relative path. If yes, simplify the link
10115 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10116 (let* ((type (match-string 1 link))
10117 (path (match-string 2 link))
10118 (origpath path)
10119 (case-fold-search nil))
10120 (cond
10121 ((or (eq org-link-file-path-type 'absolute)
10122 (equal complete-file '(16)))
10123 (setq path (abbreviate-file-name (expand-file-name path))))
10124 ((eq org-link-file-path-type 'noabbrev)
10125 (setq path (expand-file-name path)))
10126 ((eq org-link-file-path-type 'relative)
10127 (setq path (file-relative-name path)))
10129 (save-match-data
10130 (if (string-match (concat "^" (regexp-quote
10131 (expand-file-name
10132 (file-name-as-directory
10133 default-directory))))
10134 (expand-file-name path))
10135 ;; We are linking a file with relative path name.
10136 (setq path (substring (expand-file-name path)
10137 (match-end 0)))
10138 (setq path (abbreviate-file-name (expand-file-name path)))))))
10139 (setq link (concat type path))
10140 (if (equal desc origpath)
10141 (setq desc path))))
10143 (if org-make-link-description-function
10144 (setq desc
10145 (or (condition-case nil
10146 (funcall org-make-link-description-function link desc)
10147 (error (progn (message "Can't get link description from `%s'"
10148 (symbol-name org-make-link-description-function))
10149 (sit-for 2) nil)))
10150 (read-string "Description: " default-description)))
10151 (if default-description (setq desc default-description)
10152 (setq desc (or (and auto-desc desc)
10153 (read-string "Description: " desc)))))
10155 (unless (string-match "\\S-" desc) (setq desc nil))
10156 (if remove (apply 'delete-region remove))
10157 (insert (org-make-link-string link desc))))
10159 (defun org-link-try-special-completion (type)
10160 "If there is completion support for link type TYPE, offer it."
10161 (let ((fun (intern (concat "org-" type "-complete-link"))))
10162 (if (functionp fun)
10163 (funcall fun)
10164 (read-string "Link (no completion support): " (concat type ":")))))
10166 (defun org-file-complete-link (&optional arg)
10167 "Create a file link using completion."
10168 (let (file link)
10169 (setq file (org-iread-file-name "File: "))
10170 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10171 (pwd1 (file-name-as-directory (abbreviate-file-name
10172 (expand-file-name ".")))))
10173 (cond
10174 ((equal arg '(16))
10175 (setq link (concat
10176 "file:"
10177 (abbreviate-file-name (expand-file-name file)))))
10178 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10179 (setq link (concat "file:" (match-string 1 file))))
10180 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10181 (expand-file-name file))
10182 (setq link (concat
10183 "file:" (match-string 1 (expand-file-name file)))))
10184 (t (setq link (concat "file:" file)))))
10185 link))
10187 (defun org-iread-file-name (&rest args)
10188 "Read-file-name using `ido-mode' speedup if available.
10189 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10190 See `read-file-name' for a description of parameters."
10191 (org-without-partial-completion
10192 (if (and org-completion-use-ido
10193 (fboundp 'ido-read-file-name)
10194 (boundp 'ido-mode) ido-mode
10195 (listp (second args)))
10196 (let ((ido-enter-matching-directory nil))
10197 (apply 'ido-read-file-name args))
10198 (apply 'read-file-name args))))
10200 (defun org-completing-read (&rest args)
10201 "Completing-read with SPACE being a normal character."
10202 (let ((enable-recursive-minibuffers t)
10203 (minibuffer-local-completion-map
10204 (copy-keymap minibuffer-local-completion-map)))
10205 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10206 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10207 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10208 (apply 'org-icompleting-read args)))
10210 (defun org-completing-read-no-i (&rest args)
10211 (let (org-completion-use-ido org-completion-use-iswitchb)
10212 (apply 'org-completing-read args)))
10214 (defun org-iswitchb-completing-read (prompt choices &rest args)
10215 "Use iswitch as a completing-read replacement to choose from choices.
10216 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10217 from."
10218 (let* ((iswitchb-use-virtual-buffers nil)
10219 (iswitchb-make-buflist-hook
10220 (lambda ()
10221 (setq iswitchb-temp-buflist choices))))
10222 (iswitchb-read-buffer prompt)))
10224 (defun org-icompleting-read (&rest args)
10225 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10226 (org-without-partial-completion
10227 (if (and org-completion-use-ido
10228 (fboundp 'ido-completing-read)
10229 (boundp 'ido-mode) ido-mode
10230 (listp (second args)))
10231 (let ((ido-enter-matching-directory nil))
10232 (apply 'ido-completing-read (concat (car args))
10233 (if (consp (car (nth 1 args)))
10234 (mapcar 'car (nth 1 args))
10235 (nth 1 args))
10236 (cddr args)))
10237 (if (and org-completion-use-iswitchb
10238 (boundp 'iswitchb-mode) iswitchb-mode
10239 (listp (second args)))
10240 (apply 'org-iswitchb-completing-read (concat (car args))
10241 (if (consp (car (nth 1 args)))
10242 (mapcar 'car (nth 1 args))
10243 (nth 1 args))
10244 (cddr args))
10245 (apply 'completing-read args)))))
10247 (defun org-extract-attributes (s)
10248 "Extract the attributes cookie from a string and set as text property."
10249 (let (a attr (start 0) key value)
10250 (save-match-data
10251 (when (string-match "{{\\([^}]+\\)}}$" s)
10252 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10253 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10254 (setq key (match-string 1 a) value (match-string 2 a)
10255 start (match-end 0)
10256 attr (plist-put attr (intern key) value))))
10257 (org-add-props s nil 'org-attr attr))
10260 ;;; Opening/following a link
10262 (defvar org-link-search-failed nil)
10264 (defvar org-open-link-functions nil
10265 "Hook for functions finding a plain text link.
10266 These functions must take a single argument, the link content.
10267 They will be called for links that look like [[link text][description]]
10268 when LINK TEXT does not have a protocol like \"http:\" and does not look
10269 like a filename (e.g. \"./blue.png\").
10271 These functions will be called *before* Org attempts to resolve the
10272 link by doing text searches in the current buffer - so if you want a
10273 link \"[[target]]\" to still find \"<<target>>\", your function should
10274 handle this as a special case.
10276 When the function does handle the link, it must return a non-nil value.
10277 If it decides that it is not responsible for this link, it must return
10278 nil to indicate that that Org-mode can continue with other options
10279 like exact and fuzzy text search.")
10281 (defun org-next-link (&optional search-backward)
10282 "Move forward to the next link.
10283 If the link is in hidden text, expose it."
10284 (interactive "P")
10285 (when (and org-link-search-failed (eq this-command last-command))
10286 (goto-char (point-min))
10287 (message "Link search wrapped back to beginning of buffer"))
10288 (setq org-link-search-failed nil)
10289 (let* ((pos (point))
10290 (ct (org-context))
10291 (a (assoc :link ct))
10292 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10293 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10294 ((looking-at org-any-link-re)
10295 ;; Don't stay stuck at link without an org-link face
10296 (forward-char (if search-backward -1 1))))
10297 (if (funcall srch-fun org-any-link-re nil t)
10298 (progn
10299 (goto-char (match-beginning 0))
10300 (if (outline-invisible-p) (org-show-context)))
10301 (goto-char pos)
10302 (setq org-link-search-failed t)
10303 (message "No further link found"))))
10305 (defun org-previous-link ()
10306 "Move backward to the previous link.
10307 If the link is in hidden text, expose it."
10308 (interactive)
10309 (funcall 'org-next-link t))
10311 (defun org-translate-link (s)
10312 "Translate a link string if a translation function has been defined."
10313 (if (and org-link-translation-function
10314 (fboundp org-link-translation-function)
10315 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10316 (progn
10317 (setq s (funcall org-link-translation-function
10318 (match-string 1 s) (match-string 2 s)))
10319 (concat (car s) ":" (cdr s)))
10322 (defun org-translate-link-from-planner (type path)
10323 "Translate a link from Emacs Planner syntax so that Org can follow it.
10324 This is still an experimental function, your mileage may vary."
10325 (cond
10326 ((member type '("http" "https" "news" "ftp"))
10327 ;; standard Internet links are the same.
10328 nil)
10329 ((and (equal type "irc") (string-match "^//" path))
10330 ;; Planner has two / at the beginning of an irc link, we have 1.
10331 ;; We should have zero, actually....
10332 (setq path (substring path 1)))
10333 ((and (equal type "lisp") (string-match "^/" path))
10334 ;; Planner has a slash, we do not.
10335 (setq type "elisp" path (substring path 1)))
10336 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10337 ;; A typical message link. Planner has the id after the final slash,
10338 ;; we separate it with a hash mark
10339 (setq path (concat (match-string 1 path) "#"
10340 (org-remove-angle-brackets (match-string 2 path))))))
10341 (cons type path))
10343 (defun org-find-file-at-mouse (ev)
10344 "Open file link or URL at mouse."
10345 (interactive "e")
10346 (mouse-set-point ev)
10347 (org-open-at-point 'in-emacs))
10349 (defun org-open-at-mouse (ev)
10350 "Open file link or URL at mouse.
10351 See the docstring of `org-open-file' for details."
10352 (interactive "e")
10353 (mouse-set-point ev)
10354 (if (eq major-mode 'org-agenda-mode)
10355 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10356 (org-open-at-point))
10358 (defvar org-window-config-before-follow-link nil
10359 "The window configuration before following a link.
10360 This is saved in case the need arises to restore it.")
10362 (defvar org-open-link-marker (make-marker)
10363 "Marker pointing to the location where `org-open-at-point; was called.")
10365 ;;;###autoload
10366 (defun org-open-at-point-global ()
10367 "Follow a link like Org-mode does.
10368 This command can be called in any mode to follow a link that has
10369 Org-mode syntax."
10370 (interactive)
10371 (org-run-like-in-org-mode 'org-open-at-point))
10373 ;;;###autoload
10374 (defun org-open-link-from-string (s &optional arg reference-buffer)
10375 "Open a link in the string S, as if it was in Org-mode."
10376 (interactive "sLink: \nP")
10377 (let ((reference-buffer (or reference-buffer (current-buffer))))
10378 (with-temp-buffer
10379 (let ((org-inhibit-startup (not reference-buffer)))
10380 (org-mode)
10381 (insert s)
10382 (goto-char (point-min))
10383 (when reference-buffer
10384 (setq org-link-abbrev-alist-local
10385 (with-current-buffer reference-buffer
10386 org-link-abbrev-alist-local)))
10387 (org-open-at-point arg reference-buffer)))))
10389 (defvar org-open-at-point-functions nil
10390 "Hook that is run when following a link at point.
10392 Functions in this hook must return t if they identify and follow
10393 a link at point. If they don't find anything interesting at point,
10394 they must return nil.")
10396 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10397 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10398 (defun org-open-at-point (&optional arg reference-buffer)
10399 "Open link at or after point.
10400 If there is no link at point, this function will search forward up to
10401 the end of the current line.
10402 Normally, files will be opened by an appropriate application. If the
10403 optional prefix argument ARG is non-nil, Emacs will visit the file.
10404 With a double prefix argument, try to open outside of Emacs, in the
10405 application the system uses for this file type."
10406 (interactive "P")
10407 ;; if in a code block, then open the block's results
10408 (unless (call-interactively #'org-babel-open-src-block-result)
10409 (org-load-modules-maybe)
10410 (move-marker org-open-link-marker (point))
10411 (setq org-window-config-before-follow-link (current-window-configuration))
10412 (org-remove-occur-highlights nil nil t)
10413 (cond
10414 ((and (org-at-heading-p)
10415 (not (org-at-timestamp-p t))
10416 (not (org-in-regexp
10417 (concat org-plain-link-re "\\|"
10418 org-bracket-link-regexp "\\|"
10419 org-angle-link-re "\\|"
10420 "[ \t]:[^ \t\n]+:[ \t]*$")))
10421 (not (get-text-property (point) 'org-linked-text)))
10422 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10423 (lk0 (car lkall))
10424 (lk (if (stringp lk0) (list lk0) lk0))
10425 (lkend (cdr lkall)))
10426 (mapcar (lambda(l)
10427 (search-forward l nil lkend)
10428 (goto-char (match-beginning 0))
10429 (org-open-at-point))
10430 lk))
10431 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10432 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10433 ((and (org-at-timestamp-p t)
10434 (not (org-in-regexp org-bracket-link-regexp)))
10435 (org-follow-timestamp-link))
10436 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10437 (not (org-in-regexp org-any-link-re)))
10438 (org-footnote-action))
10440 (let (type path link line search (pos (point)))
10441 (catch 'match
10442 (save-excursion
10443 (skip-chars-forward "^]\n\r")
10444 (when (org-in-regexp org-bracket-link-regexp 1)
10445 (setq link (org-extract-attributes
10446 (org-link-unescape (org-match-string-no-properties 1))))
10447 (while (string-match " *\n *" link)
10448 (setq link (replace-match " " t t link)))
10449 (setq link (org-link-expand-abbrev link))
10450 (cond
10451 ((or (file-name-absolute-p link)
10452 (string-match "^\\.\\.?/" link))
10453 (setq type "file" path link))
10454 ((string-match org-link-re-with-space3 link)
10455 (setq type (match-string 1 link) path (match-string 2 link)))
10456 ((string-match "^help:+\\(.+\\)" link)
10457 (setq type "help" path (match-string 1 link)))
10458 (t (setq type "thisfile" path link)))
10459 (throw 'match t)))
10461 (when (get-text-property (point) 'org-linked-text)
10462 (setq type "thisfile"
10463 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10464 (1+ (point)) (point))
10465 path (buffer-substring
10466 (or (previous-single-property-change pos 'org-linked-text)
10467 (point-min))
10468 (or (next-single-property-change pos 'org-linked-text)
10469 (point-max)))
10470 ;; Ensure we will search for a <<<radio>>> link, not
10471 ;; a simple reference like <<ref>>
10472 path (concat "<" path))
10473 (throw 'match t))
10475 (save-excursion
10476 (when (or (org-in-regexp org-angle-link-re)
10477 (let ((match (org-in-regexp org-plain-link-re)))
10478 ;; Check a plain link is not within a bracket link
10479 (and match
10480 (save-excursion
10481 (progn
10482 (goto-char (car match))
10483 (not (org-in-regexp org-bracket-link-regexp))))))
10484 (let ((line_ending (save-excursion (end-of-line) (point))))
10485 ;; We are in a line before a plain or bracket link
10486 (or (re-search-forward org-plain-link-re line_ending t)
10487 (re-search-forward org-bracket-link-regexp line_ending t))))
10488 (setq type (match-string 1)
10489 path (org-link-unescape (match-string 2)))
10490 (throw 'match t)))
10491 (save-excursion
10492 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10493 (setq type "tags"
10494 path (match-string 1))
10495 (while (string-match ":" path)
10496 (setq path (replace-match "+" t t path)))
10497 (throw 'match t)))
10498 (when (org-in-regexp "<\\([^><\n]+\\)>")
10499 (setq type "tree-match"
10500 path (match-string 1))
10501 (throw 'match t)))
10502 (unless path
10503 (user-error "No link found"))
10505 ;; switch back to reference buffer
10506 ;; needed when if called in a temporary buffer through
10507 ;; org-open-link-from-string
10508 (with-current-buffer (or reference-buffer (current-buffer))
10510 ;; Remove any trailing spaces in path
10511 (if (string-match " +\\'" path)
10512 (setq path (replace-match "" t t path)))
10513 (if (and org-link-translation-function
10514 (fboundp org-link-translation-function))
10515 ;; Check if we need to translate the link
10516 (let ((tmp (funcall org-link-translation-function type path)))
10517 (setq type (car tmp) path (cdr tmp))))
10519 (cond
10521 ((assoc type org-link-protocols)
10522 (funcall (nth 1 (assoc type org-link-protocols)) path))
10524 ((equal type "help")
10525 (let ((f-or-v (intern path)))
10526 (cond ((fboundp f-or-v)
10527 (describe-function f-or-v))
10528 ((boundp f-or-v)
10529 (describe-variable f-or-v))
10530 (t (error "Not a known function or variable")))))
10532 ((equal type "mailto")
10533 (let ((cmd (car org-link-mailto-program))
10534 (args (cdr org-link-mailto-program)) args1
10535 (address path) (subject "") a)
10536 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10537 (setq address (match-string 1 path)
10538 subject (org-link-escape (match-string 2 path))))
10539 (while args
10540 (cond
10541 ((not (stringp (car args))) (push (pop args) args1))
10542 (t (setq a (pop args))
10543 (if (string-match "%a" a)
10544 (setq a (replace-match address t t a)))
10545 (if (string-match "%s" a)
10546 (setq a (replace-match subject t t a)))
10547 (push a args1))))
10548 (apply cmd (nreverse args1))))
10550 ((member type '("http" "https" "ftp" "news"))
10551 ;; In the example of the http Org link
10552 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10553 ;; to open a browser with +subject:"Release 8.2" in the
10554 ;; query field the variable `path' contains
10555 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10556 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10557 ;; and `org-link-escape-browser' converts wrong to
10558 ;; [...]=%252Bsubject:%22Release+8.2%22.
10560 ;; `url-encode-url' is available since Emacs 24.3.1 and
10561 ;; `org-link-escape-browser' can be removed altogether
10562 ;; once Org drops support for Emacs 24.1 and 24.2.
10563 (browse-url (funcall (if (fboundp 'url-encode-url)
10564 #'url-encode-url
10565 #'org-link-escape-browser)
10566 (concat type ":" path))))
10568 ((string= type "doi")
10569 ;; See comments for type http above
10570 (browse-url (funcall (if (fboundp 'url-encode-url)
10571 #'url-encode-url
10572 #'org-link-escape-browser)
10573 (concat org-doi-server-url path))))
10575 ((member type '("message"))
10576 (browse-url (concat type ":" path)))
10578 ((string= type "tags")
10579 (org-tags-view arg path))
10581 ((string= type "tree-match")
10582 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10584 ((string= type "file")
10585 (if (string-match "::\\([0-9]+\\)\\'" path)
10586 (setq line (string-to-number (match-string 1 path))
10587 path (substring path 0 (match-beginning 0)))
10588 (if (string-match "::\\(.+\\)\\'" path)
10589 (setq search (match-string 1 path)
10590 path (substring path 0 (match-beginning 0)))))
10591 (if (string-match "[*?{]" (file-name-nondirectory path))
10592 (dired path)
10593 (org-open-file path arg line search)))
10595 ((string= type "shell")
10596 (let ((buf (generate-new-buffer "*Org Shell Output"))
10597 (cmd path))
10598 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10599 (string-match org-confirm-shell-link-not-regexp cmd))
10600 (not org-confirm-shell-link-function)
10601 (funcall org-confirm-shell-link-function
10602 (format "Execute \"%s\" in shell? "
10603 (org-add-props cmd nil
10604 'face 'org-warning))))
10605 (progn
10606 (message "Executing %s" cmd)
10607 (shell-command cmd buf)
10608 (if (featurep 'midnight)
10609 (setq clean-buffer-list-kill-buffer-names
10610 (cons buf clean-buffer-list-kill-buffer-names))))
10611 (error "Abort"))))
10613 ((string= type "elisp")
10614 (let ((cmd path))
10615 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10616 (string-match org-confirm-elisp-link-not-regexp cmd))
10617 (not org-confirm-elisp-link-function)
10618 (funcall org-confirm-elisp-link-function
10619 (format "Execute \"%s\" as elisp? "
10620 (org-add-props cmd nil
10621 'face 'org-warning))))
10622 (message "%s => %s" cmd
10623 (if (equal (string-to-char cmd) ?\()
10624 (eval (read cmd))
10625 (call-interactively (read cmd))))
10626 (error "Abort"))))
10628 ((and (string= type "thisfile")
10629 (or (run-hook-with-args-until-success
10630 'org-open-link-functions path)
10631 (and link
10632 (string-match "^id:" link)
10633 (or (featurep 'org-id) (require 'org-id))
10634 (progn
10635 (funcall (nth 1 (assoc "id" org-link-protocols))
10636 (substring path 3))
10637 t)))))
10639 ((string= type "thisfile")
10640 (if arg
10641 (switch-to-buffer-other-window
10642 (org-get-buffer-for-internal-link (current-buffer)))
10643 (org-mark-ring-push))
10644 (let ((cmd `(org-link-search
10645 ,path
10646 ,(cond ((equal arg '(4)) ''occur)
10647 ((equal arg '(16)) ''org-occur))
10648 ,pos)))
10649 (condition-case nil (let ((org-link-search-inhibit-query t))
10650 (eval cmd))
10651 (error (progn (widen) (eval cmd))))))
10653 (t (browse-url-at-point)))))))
10654 (move-marker org-open-link-marker nil)
10655 (run-hook-with-args 'org-follow-link-hook)))
10657 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10658 "Offer links in the current entry and return the selected link.
10659 If there is only one link, return it.
10660 If NTH is an integer, return the NTH link found.
10661 If ZERO is a string, check also this string for a link, and if
10662 there is one, return it."
10663 (with-current-buffer buffer
10664 (save-excursion
10665 (save-restriction
10666 (widen)
10667 (goto-char marker)
10668 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10669 "\\(" org-angle-link-re "\\)\\|"
10670 "\\(" org-plain-link-re "\\)"))
10671 (cnt ?0)
10672 (in-emacs (if (integerp nth) nil nth))
10673 have-zero end links link c)
10674 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10675 (push (match-string 0 zero) links)
10676 (setq cnt (1- cnt) have-zero t))
10677 (save-excursion
10678 (org-back-to-heading t)
10679 (setq end (save-excursion (outline-next-heading) (point)))
10680 (while (re-search-forward re end t)
10681 (push (match-string 0) links))
10682 (setq links (org-uniquify (reverse links))))
10683 (cond
10684 ((null links)
10685 (message "No links"))
10686 ((equal (length links) 1)
10687 (setq link (car links)))
10688 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10689 (setq link (nth (if have-zero nth (1- nth)) links)))
10690 (t ; we have to select a link
10691 (save-excursion
10692 (save-window-excursion
10693 (delete-other-windows)
10694 (with-output-to-temp-buffer "*Select Link*"
10695 (mapc (lambda (l)
10696 (if (not (string-match org-bracket-link-regexp l))
10697 (princ (format "[%c] %s\n" (incf cnt)
10698 (org-remove-angle-brackets l)))
10699 (if (match-end 3)
10700 (princ (format "[%c] %s (%s)\n" (incf cnt)
10701 (match-string 3 l) (match-string 1 l)))
10702 (princ (format "[%c] %s\n" (incf cnt)
10703 (match-string 1 l))))))
10704 links))
10705 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10706 (message "Select link to open, RET to open all:")
10707 (setq c (read-char-exclusive))
10708 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10709 (when (equal c ?q) (error "Abort"))
10710 (if (equal c ?\C-m)
10711 (setq link links)
10712 (setq nth (- c ?0))
10713 (if have-zero (setq nth (1+ nth)))
10714 (unless (and (integerp nth) (>= (length links) nth))
10715 (user-error "Invalid link selection"))
10716 (setq link (nth (1- nth) links)))))
10717 (cons link end))))))
10719 ;; Add special file links that specify the way of opening
10721 (org-add-link-type "file+sys" 'org-open-file-with-system)
10722 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10723 (defun org-open-file-with-system (path)
10724 "Open file at PATH using the system way of opening it."
10725 (org-open-file path 'system))
10726 (defun org-open-file-with-emacs (path)
10727 "Open file at PATH in Emacs."
10728 (org-open-file path 'emacs))
10731 ;;; File search
10733 (defvar org-create-file-search-functions nil
10734 "List of functions to construct the right search string for a file link.
10735 These functions are called in turn with point at the location to
10736 which the link should point.
10738 A function in the hook should first test if it would like to
10739 handle this file type, for example by checking the `major-mode'
10740 or the file extension. If it decides not to handle this file, it
10741 should just return nil to give other functions a chance. If it
10742 does handle the file, it must return the search string to be used
10743 when following the link. The search string will be part of the
10744 file link, given after a double colon, and `org-open-at-point'
10745 will automatically search for it. If special measures must be
10746 taken to make the search successful, another function should be
10747 added to the companion hook `org-execute-file-search-functions',
10748 which see.
10750 A function in this hook may also use `setq' to set the variable
10751 `description' to provide a suggestion for the descriptive text to
10752 be used for this link when it gets inserted into an Org-mode
10753 buffer with \\[org-insert-link].")
10755 (defvar org-execute-file-search-functions nil
10756 "List of functions to execute a file search triggered by a link.
10758 Functions added to this hook must accept a single argument, the
10759 search string that was part of the file link, the part after the
10760 double colon. The function must first check if it would like to
10761 handle this search, for example by checking the `major-mode' or
10762 the file extension. If it decides not to handle this search, it
10763 should just return nil to give other functions a chance. If it
10764 does handle the search, it must return a non-nil value to keep
10765 other functions from trying.
10767 Each function can access the current prefix argument through the
10768 variable `current-prefix-arg'. Note that a single prefix is used
10769 to force opening a link in Emacs, so it may be good to only use a
10770 numeric or double prefix to guide the search function.
10772 In case this is needed, a function in this hook can also restore
10773 the window configuration before `org-open-at-point' was called using:
10775 (set-window-configuration org-window-config-before-follow-link)")
10777 (defun org-link-search (s &optional type avoid-pos stealth)
10778 "Search for a link search option.
10779 If S is surrounded by forward slashes, it is interpreted as a
10780 regular expression. In org-mode files, this will create an `org-occur'
10781 sparse tree. In ordinary files, `occur' will be used to list matches.
10782 If the current buffer is in `dired-mode', grep will be used to search
10783 in all files. If AVOID-POS is given, ignore matches near that position.
10785 When optional argument STEALTH is non-nil, do not modify
10786 visibility around point, thus ignoring
10787 `org-show-hierarchy-above', `org-show-following-heading' and
10788 `org-show-siblings' variables."
10789 (let ((case-fold-search t)
10790 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10791 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10792 (append '(("") (" ") ("\t") ("\n"))
10793 org-emphasis-alist)
10794 "\\|") "\\)"))
10795 (pos (point))
10796 (pre nil) (post nil)
10797 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10798 (cond
10799 ;; First check if there are any special search functions
10800 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10801 ;; Now try the builtin stuff
10802 ((and (equal (string-to-char s0) ?#)
10803 (> (length s0) 1)
10804 (save-excursion
10805 (goto-char (point-min))
10806 (and
10807 (re-search-forward
10808 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10809 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10810 (setq type 'dedicated
10811 pos (match-beginning 0))))
10812 ;; There is an exact target for this
10813 (goto-char pos)
10814 (org-back-to-heading t)))
10815 ((save-excursion
10816 (goto-char (point-min))
10817 (and
10818 (re-search-forward
10819 (concat "<<" (regexp-quote s0) ">>") nil t)
10820 (setq type 'dedicated
10821 pos (match-beginning 0))))
10822 ;; There is an exact target for this
10823 (goto-char pos))
10824 ((save-excursion
10825 (goto-char (point-min))
10826 (and
10827 (re-search-forward
10828 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10829 (setq type 'dedicated pos (match-beginning 0))))
10830 ;; Found an element with a matching #+name affiliated keyword.
10831 (goto-char pos))
10832 ((and (string-match "^(\\(.*\\))$" s0)
10833 (save-excursion
10834 (goto-char (point-min))
10835 (and
10836 (re-search-forward
10837 (concat "[^[]" (regexp-quote
10838 (format org-coderef-label-format
10839 (match-string 1 s0))))
10840 nil t)
10841 (setq type 'dedicated
10842 pos (1+ (match-beginning 0))))))
10843 ;; There is a coderef target for this
10844 (goto-char pos))
10845 ((string-match "^/\\(.*\\)/$" s)
10846 ;; A regular expression
10847 (cond
10848 ((derived-mode-p 'org-mode)
10849 (org-occur (match-string 1 s)))
10850 (t (org-do-occur (match-string 1 s)))))
10851 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10852 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10853 (goto-char (point-min))
10854 (cond
10855 ((let (case-fold-search)
10856 (re-search-forward (format org-complex-heading-regexp-format
10857 (regexp-quote s))
10858 nil t))
10859 ;; OK, found a match
10860 (setq type 'dedicated)
10861 (goto-char (match-beginning 0)))
10862 ((and (not org-link-search-inhibit-query)
10863 (eq org-link-search-must-match-exact-headline 'query-to-create)
10864 (y-or-n-p "No match - create this as a new heading? "))
10865 (goto-char (point-max))
10866 (or (bolp) (newline))
10867 (insert "* " s "\n")
10868 (beginning-of-line 0))
10870 (goto-char pos)
10871 (error "No match"))))
10873 ;; A normal search string
10874 (when (equal (string-to-char s) ?*)
10875 ;; Anchor on headlines, post may include tags.
10876 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10877 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10878 s (substring s 1)))
10879 (remove-text-properties
10880 0 (length s)
10881 '(face nil mouse-face nil keymap nil fontified nil) s)
10882 ;; Make a series of regular expressions to find a match
10883 (setq words (org-split-string s "[ \n\r\t]+")
10885 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10886 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10887 "\\)" markers)
10888 re2a_ (concat "\\(" (mapconcat 'downcase words
10889 "[ \t\r\n]+") "\\)[ \t\r\n]")
10890 re2a (concat "[ \t\r\n]" re2a_)
10891 re4_ (concat "\\(" (mapconcat 'downcase words
10892 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10893 re4 (concat "[^a-zA-Z_]" re4_)
10895 re1 (concat pre re2 post)
10896 re3 (concat pre (if pre re4_ re4) post)
10897 re5 (concat pre ".*" re4)
10898 re2 (concat pre re2)
10899 re2a (concat pre (if pre re2a_ re2a))
10900 re4 (concat pre (if pre re4_ re4))
10901 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10902 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10903 re5 "\\)"))
10904 (cond
10905 ((eq type 'org-occur) (org-occur reall))
10906 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10907 (t (goto-char (point-min))
10908 (setq type 'fuzzy)
10909 (if (or (and (org-search-not-self 1 re0 nil t)
10910 (setq type 'dedicated))
10911 (org-search-not-self 1 re1 nil t)
10912 (org-search-not-self 1 re2 nil t)
10913 (org-search-not-self 1 re2a nil t)
10914 (org-search-not-self 1 re3 nil t)
10915 (org-search-not-self 1 re4 nil t)
10916 (org-search-not-self 1 re5 nil t))
10917 (goto-char (match-beginning 1))
10918 (goto-char pos)
10919 (error "No match"))))))
10920 (and (derived-mode-p 'org-mode)
10921 (not stealth)
10922 (org-show-context 'link-search))
10923 type))
10925 (defun org-search-not-self (group &rest args)
10926 "Execute `re-search-forward', but only accept matches that do not
10927 enclose the position of `org-open-link-marker'."
10928 (let ((m org-open-link-marker))
10929 (catch 'exit
10930 (while (apply 're-search-forward args)
10931 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10932 (goto-char (match-end group))
10933 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10934 (> (match-beginning 0) (marker-position m))
10935 (< (match-end 0) (marker-position m)))
10936 (save-match-data
10937 (or (not (org-in-regexp
10938 org-bracket-link-analytic-regexp 1))
10939 (not (match-end 4)) ; no description
10940 (and (<= (match-beginning 4) (point))
10941 (>= (match-end 4) (point))))))
10942 (throw 'exit (point))))))))
10944 (defun org-get-buffer-for-internal-link (buffer)
10945 "Return a buffer to be used for displaying the link target of internal links."
10946 (cond
10947 ((not org-display-internal-link-with-indirect-buffer)
10948 buffer)
10949 ((string-match "(Clone)$" (buffer-name buffer))
10950 (message "Buffer is already a clone, not making another one")
10951 ;; we also do not modify visibility in this case
10952 buffer)
10953 (t ; make a new indirect buffer for displaying the link
10954 (let* ((bn (buffer-name buffer))
10955 (ibn (concat bn "(Clone)"))
10956 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10957 (with-current-buffer ib (org-overview))
10958 ib))))
10960 (defun org-do-occur (regexp &optional cleanup)
10961 "Call the Emacs command `occur'.
10962 If CLEANUP is non-nil, remove the printout of the regular expression
10963 in the *Occur* buffer. This is useful if the regex is long and not useful
10964 to read."
10965 (occur regexp)
10966 (when cleanup
10967 (let ((cwin (selected-window)) win beg end)
10968 (when (setq win (get-buffer-window "*Occur*"))
10969 (select-window win))
10970 (goto-char (point-min))
10971 (when (re-search-forward "match[a-z]+" nil t)
10972 (setq beg (match-end 0))
10973 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10974 (setq end (1- (match-beginning 0)))))
10975 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10976 (goto-char (point-min))
10977 (select-window cwin))))
10979 ;;; The mark ring for links jumps
10981 (defvar org-mark-ring nil
10982 "Mark ring for positions before jumps in Org-mode.")
10983 (defvar org-mark-ring-last-goto nil
10984 "Last position in the mark ring used to go back.")
10985 ;; Fill and close the ring
10986 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10987 (loop for i from 1 to org-mark-ring-length do
10988 (push (make-marker) org-mark-ring))
10989 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10990 org-mark-ring)
10992 (defun org-mark-ring-push (&optional pos buffer)
10993 "Put the current position or POS into the mark ring and rotate it."
10994 (interactive)
10995 (setq pos (or pos (point)))
10996 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10997 (move-marker (car org-mark-ring)
10998 (or pos (point))
10999 (or buffer (current-buffer)))
11000 (message "%s"
11001 (substitute-command-keys
11002 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11004 (defun org-mark-ring-goto (&optional n)
11005 "Jump to the previous position in the mark ring.
11006 With prefix arg N, jump back that many stored positions. When
11007 called several times in succession, walk through the entire ring.
11008 Org-mode commands jumping to a different position in the current file,
11009 or to another Org-mode file, automatically push the old position
11010 onto the ring."
11011 (interactive "p")
11012 (let (p m)
11013 (if (eq last-command this-command)
11014 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11015 (setq p org-mark-ring))
11016 (setq org-mark-ring-last-goto p)
11017 (setq m (car p))
11018 (org-pop-to-buffer-same-window (marker-buffer m))
11019 (goto-char m)
11020 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11022 (defun org-remove-angle-brackets (s)
11023 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11024 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11026 (defun org-add-angle-brackets (s)
11027 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11028 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11030 (defun org-remove-double-quotes (s)
11031 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11032 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11035 ;;; Following specific links
11037 (defun org-follow-timestamp-link ()
11038 "Open an agenda view for the time-stamp date/range at point."
11039 (cond
11040 ((org-at-date-range-p t)
11041 (let ((org-agenda-start-on-weekday)
11042 (t1 (match-string 1))
11043 (t2 (match-string 2)) tt1 tt2)
11044 (setq tt1 (time-to-days (org-time-string-to-time t1))
11045 tt2 (time-to-days (org-time-string-to-time t2)))
11046 (let ((org-agenda-buffer-tmp-name
11047 (format "*Org Agenda(a:%s)"
11048 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11049 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11050 ((org-at-timestamp-p t)
11051 (let ((org-agenda-buffer-tmp-name
11052 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11053 (org-agenda-list nil (time-to-days (org-time-string-to-time
11054 (substring (match-string 1) 0 10)))
11055 1)))
11056 (t (error "This should not happen"))))
11059 ;;; Following file links
11060 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11061 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11062 (declare-function mailcap-mime-info
11063 "mailcap" (string &optional request no-decode))
11064 (defvar org-wait nil)
11065 (defun org-open-file (path &optional in-emacs line search)
11066 "Open the file at PATH.
11067 First, this expands any special file name abbreviations. Then the
11068 configuration variable `org-file-apps' is checked if it contains an
11069 entry for this file type, and if yes, the corresponding command is launched.
11071 If no application is found, Emacs simply visits the file.
11073 With optional prefix argument IN-EMACS, Emacs will visit the file.
11074 With a double \\[universal-argument] \\[universal-argument] \
11075 prefix arg, Org tries to avoid opening in Emacs
11076 and to use an external application to visit the file.
11078 Optional LINE specifies a line to go to, optional SEARCH a string
11079 to search for. If LINE or SEARCH is given, the file will be
11080 opened in Emacs, unless an entry from org-file-apps that makes
11081 use of groups in a regexp matches.
11083 If you want to change the way frames are used when following a
11084 link, please customize `org-link-frame-setup'.
11086 If the file does not exist, an error is thrown."
11087 (let* ((file (if (equal path "")
11088 buffer-file-name
11089 (substitute-in-file-name (expand-file-name path))))
11090 (file-apps (append org-file-apps (org-default-apps)))
11091 (apps (org-remove-if
11092 'org-file-apps-entry-match-against-dlink-p file-apps))
11093 (apps-dlink (org-remove-if-not
11094 'org-file-apps-entry-match-against-dlink-p file-apps))
11095 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11096 (dirp (if remp nil (file-directory-p file)))
11097 (file (if (and dirp org-open-directory-means-index-dot-org)
11098 (concat (file-name-as-directory file) "index.org")
11099 file))
11100 (a-m-a-p (assq 'auto-mode apps))
11101 (dfile (downcase file))
11102 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11103 (link (cond ((and (eq line nil)
11104 (eq search nil))
11105 file)
11106 (line
11107 (concat file "::" (number-to-string line)))
11108 (search
11109 (concat file "::" search))))
11110 (dlink (downcase link))
11111 (old-buffer (current-buffer))
11112 (old-pos (point))
11113 (old-mode major-mode)
11114 ext cmd link-match-data)
11115 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11116 (setq ext (match-string 1 dfile))
11117 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11118 (setq ext (match-string 1 dfile))))
11119 (cond
11120 ((member in-emacs '((16) system))
11121 (setq cmd (cdr (assoc 'system apps))))
11122 (in-emacs (setq cmd 'emacs))
11124 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11125 (and dirp (cdr (assoc 'directory apps)))
11126 ; first, try matching against apps-dlink
11127 ; if we get a match here, store the match data for later
11128 (let ((match (assoc-default dlink apps-dlink
11129 'string-match)))
11130 (if match
11131 (progn (setq link-match-data (match-data))
11132 match)
11133 (progn (setq in-emacs (or in-emacs line search))
11134 nil))) ; if we have no match in apps-dlink,
11135 ; always open the file in emacs if line or search
11136 ; is given (for backwards compatibility)
11137 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11138 'string-match)
11139 (cdr (assoc ext apps))
11140 (cdr (assoc t apps))))))
11141 (when (eq cmd 'system)
11142 (setq cmd (cdr (assoc 'system apps))))
11143 (when (eq cmd 'default)
11144 (setq cmd (cdr (assoc t apps))))
11145 (when (eq cmd 'mailcap)
11146 (require 'mailcap)
11147 (mailcap-parse-mailcaps)
11148 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11149 (command (mailcap-mime-info mime-type)))
11150 (if (stringp command)
11151 (setq cmd command)
11152 (setq cmd 'emacs))))
11153 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11154 (not (file-exists-p file))
11155 (not org-open-non-existing-files))
11156 (user-error "No such file: %s" file))
11157 (cond
11158 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11159 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11160 (while (string-match "['\"]%s['\"]" cmd)
11161 (setq cmd (replace-match "%s" t t cmd)))
11162 (while (string-match "%s" cmd)
11163 (setq cmd (replace-match
11164 (save-match-data
11165 (shell-quote-argument
11166 (convert-standard-filename file)))
11167 t t cmd)))
11169 ;; Replace "%1", "%2" etc. in command with group matches from regex
11170 (save-match-data
11171 (let ((match-index 1)
11172 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11173 (set-match-data link-match-data)
11174 (while (<= match-index number-of-groups)
11175 (let ((regex (concat "%" (number-to-string match-index)))
11176 (replace-with (match-string match-index dlink)))
11177 (while (string-match regex cmd)
11178 (setq cmd (replace-match replace-with t t cmd))))
11179 (setq match-index (+ match-index 1)))))
11181 (save-window-excursion
11182 (message "Running %s...done" cmd)
11183 (start-process-shell-command cmd nil cmd)
11184 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11185 ((or (stringp cmd)
11186 (eq cmd 'emacs))
11187 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11188 (widen)
11189 (if line (progn (org-goto-line line)
11190 (if (derived-mode-p 'org-mode)
11191 (org-reveal)))
11192 (if search (org-link-search search))))
11193 ((consp cmd)
11194 (let ((file (convert-standard-filename file)))
11195 (save-match-data
11196 (set-match-data link-match-data)
11197 (eval cmd))))
11198 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11199 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11200 (or (not (equal old-buffer (current-buffer)))
11201 (not (equal old-pos (point))))
11202 (org-mark-ring-push old-pos old-buffer))))
11204 (defun org-file-apps-entry-match-against-dlink-p (entry)
11205 "This function returns non-nil if `entry' uses a regular
11206 expression which should be matched against the whole link by
11207 org-open-file.
11209 It assumes that is the case when the entry uses a regular
11210 expression which has at least one grouping construct and the
11211 action is either a lisp form or a command string containing
11212 '%1', i.e. using at least one subexpression match as a
11213 parameter."
11214 (let ((selector (car entry))
11215 (action (cdr entry)))
11216 (if (stringp selector)
11217 (and (> (regexp-opt-depth selector) 0)
11218 (or (and (stringp action)
11219 (string-match "%[0-9]" action))
11220 (consp action)))
11221 nil)))
11223 (defun org-default-apps ()
11224 "Return the default applications for this operating system."
11225 (cond
11226 ((eq system-type 'darwin)
11227 org-file-apps-defaults-macosx)
11228 ((eq system-type 'windows-nt)
11229 org-file-apps-defaults-windowsnt)
11230 (t org-file-apps-defaults-gnu)))
11232 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11233 "Convert extensions to regular expressions in the cars of LIST.
11234 Also, weed out any non-string entries, because the return value is used
11235 only for regexp matching.
11236 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11237 point to the symbol `emacs', indicating that the file should
11238 be opened in Emacs."
11239 (append
11240 (delq nil
11241 (mapcar (lambda (x)
11242 (if (not (stringp (car x)))
11244 (if (string-match "\\W" (car x))
11246 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11247 list))
11248 (if add-auto-mode
11249 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11251 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11252 (defun org-file-remote-p (file)
11253 "Test whether FILE specifies a location on a remote system.
11254 Return non-nil if the location is indeed remote.
11256 For example, the filename \"/user@host:/foo\" specifies a location
11257 on the system \"/user@host:\"."
11258 (cond ((fboundp 'file-remote-p)
11259 (file-remote-p file))
11260 ((fboundp 'tramp-handle-file-remote-p)
11261 (tramp-handle-file-remote-p file))
11262 ((and (boundp 'ange-ftp-name-format)
11263 (string-match (car ange-ftp-name-format) file))
11264 t)))
11267 ;;;; Refiling
11269 (defun org-get-org-file ()
11270 "Read a filename, with default directory `org-directory'."
11271 (let ((default (or org-default-notes-file remember-data-file)))
11272 (read-file-name (format "File name [%s]: " default)
11273 (file-name-as-directory org-directory)
11274 default)))
11276 (defun org-notes-order-reversed-p ()
11277 "Check if the current file should receive notes in reversed order."
11278 (cond
11279 ((not org-reverse-note-order) nil)
11280 ((eq t org-reverse-note-order) t)
11281 ((not (listp org-reverse-note-order)) nil)
11282 (t (catch 'exit
11283 (let ((all org-reverse-note-order)
11284 entry)
11285 (while (setq entry (pop all))
11286 (if (string-match (car entry) buffer-file-name)
11287 (throw 'exit (cdr entry))))
11288 nil)))))
11290 (defvar org-refile-target-table nil
11291 "The list of refile targets, created by `org-refile'.")
11293 (defvar org-agenda-new-buffers nil
11294 "Buffers created to visit agenda files.")
11296 (defvar org-refile-cache nil
11297 "Cache for refile targets.")
11299 (defvar org-refile-markers nil
11300 "All the markers used for caching refile locations.")
11302 (defun org-refile-marker (pos)
11303 "Get a new refile marker, but only if caching is in use."
11304 (if (not org-refile-use-cache)
11306 (let ((m (make-marker)))
11307 (move-marker m pos)
11308 (push m org-refile-markers)
11309 m)))
11311 (defun org-refile-cache-clear ()
11312 "Clear the refile cache and disable all the markers."
11313 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11314 (setq org-refile-markers nil)
11315 (setq org-refile-cache nil)
11316 (message "Refile cache has been cleared"))
11318 (defun org-refile-cache-check-set (set)
11319 "Check if all the markers in the cache still have live buffers."
11320 (let (marker)
11321 (catch 'exit
11322 (while (and set (setq marker (nth 3 (pop set))))
11323 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11324 (when (and marker (null (marker-buffer marker)))
11325 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11326 (sit-for 3)
11327 (throw 'exit nil)))
11328 t)))
11330 (defun org-refile-cache-put (set &rest identifiers)
11331 "Push the refile targets SET into the cache, under IDENTIFIERS."
11332 (let* ((key (sha1 (prin1-to-string identifiers)))
11333 (entry (assoc key org-refile-cache)))
11334 (if entry
11335 (setcdr entry set)
11336 (push (cons key set) org-refile-cache))))
11338 (defun org-refile-cache-get (&rest identifiers)
11339 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11340 (cond
11341 ((not org-refile-cache) nil)
11342 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11344 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11345 org-refile-cache))))
11346 (and set (org-refile-cache-check-set set) set)))))
11348 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11349 "Produce a table with refile targets."
11350 (let ((case-fold-search nil)
11351 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11352 (entries (or org-refile-targets '((nil . (:level . 1)))))
11353 targets tgs txt re files f desc descre fast-path-p level pos0)
11354 (message "Getting targets...")
11355 (with-current-buffer (or default-buffer (current-buffer))
11356 (while (setq entry (pop entries))
11357 (setq files (car entry) desc (cdr entry))
11358 (setq fast-path-p nil)
11359 (cond
11360 ((null files) (setq files (list (current-buffer))))
11361 ((eq files 'org-agenda-files)
11362 (setq files (org-agenda-files 'unrestricted)))
11363 ((and (symbolp files) (fboundp files))
11364 (setq files (funcall files)))
11365 ((and (symbolp files) (boundp files))
11366 (setq files (symbol-value files))))
11367 (if (stringp files) (setq files (list files)))
11368 (cond
11369 ((eq (car desc) :tag)
11370 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11371 ((eq (car desc) :todo)
11372 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11373 ((eq (car desc) :regexp)
11374 (setq descre (cdr desc)))
11375 ((eq (car desc) :level)
11376 (setq descre (concat "^\\*\\{" (number-to-string
11377 (if org-odd-levels-only
11378 (1- (* 2 (cdr desc)))
11379 (cdr desc)))
11380 "\\}[ \t]")))
11381 ((eq (car desc) :maxlevel)
11382 (setq fast-path-p t)
11383 (setq descre (concat "^\\*\\{1," (number-to-string
11384 (if org-odd-levels-only
11385 (1- (* 2 (cdr desc)))
11386 (cdr desc)))
11387 "\\}[ \t]")))
11388 (t (error "Bad refiling target description %s" desc)))
11389 (while (setq f (pop files))
11390 (with-current-buffer
11391 (if (bufferp f) f (org-get-agenda-file-buffer f))
11393 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11394 (progn
11395 (if (bufferp f) (setq f (buffer-file-name
11396 (buffer-base-buffer f))))
11397 (setq f (and f (expand-file-name f)))
11398 (if (eq org-refile-use-outline-path 'file)
11399 (push (list (file-name-nondirectory f) f nil nil) tgs))
11400 (save-excursion
11401 (save-restriction
11402 (widen)
11403 (goto-char (point-min))
11404 (while (re-search-forward descre nil t)
11405 (goto-char (setq pos0 (point-at-bol)))
11406 (catch 'next
11407 (when org-refile-target-verify-function
11408 (save-match-data
11409 (or (funcall org-refile-target-verify-function)
11410 (throw 'next t))))
11411 (when (and (looking-at org-complex-heading-regexp)
11412 (not (member (match-string 4) excluded-entries))
11413 (match-string 4))
11414 (setq level (org-reduced-level
11415 (- (match-end 1) (match-beginning 1)))
11416 txt (org-link-display-format (match-string 4))
11417 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11418 re (format org-complex-heading-regexp-format
11419 (regexp-quote (match-string 4))))
11420 (when org-refile-use-outline-path
11421 (setq txt (mapconcat
11422 'org-protect-slash
11423 (append
11424 (if (eq org-refile-use-outline-path
11425 'file)
11426 (list (file-name-nondirectory
11427 (buffer-file-name
11428 (buffer-base-buffer))))
11429 (if (eq org-refile-use-outline-path
11430 'full-file-path)
11431 (list (buffer-file-name
11432 (buffer-base-buffer)))))
11433 (org-get-outline-path fast-path-p
11434 level txt)
11435 (list txt))
11436 "/")))
11437 (push (list txt f re (org-refile-marker (point)))
11438 tgs)))
11439 (when (= (point) pos0)
11440 ;; verification function has not moved point
11441 (goto-char (point-at-eol))))))))
11442 (when org-refile-use-cache
11443 (org-refile-cache-put tgs (buffer-file-name) descre))
11444 (setq targets (append tgs targets))))))
11445 (message "Getting targets...done")
11446 (nreverse targets)))
11448 (defun org-protect-slash (s)
11449 (while (string-match "/" s)
11450 (setq s (replace-match "\\" t t s)))
11453 (defvar org-olpa (make-vector 20 nil))
11455 (defun org-get-outline-path (&optional fastp level heading)
11456 "Return the outline path to the current entry, as a list.
11458 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11459 routine which makes outline path derivations for an entire file,
11460 avoiding backtracing. Refile target collection makes use of that."
11461 (if fastp
11462 (progn
11463 (if (> level 19)
11464 (error "Outline path failure, more than 19 levels"))
11465 (loop for i from level upto 19 do
11466 (aset org-olpa i nil))
11467 (prog1
11468 (delq nil (append org-olpa nil))
11469 (aset org-olpa level heading)))
11470 (let (rtn case-fold-search)
11471 (save-excursion
11472 (save-restriction
11473 (widen)
11474 (while (org-up-heading-safe)
11475 (when (looking-at org-complex-heading-regexp)
11476 (push (org-trim
11477 (replace-regexp-in-string
11478 ;; Remove statistical/checkboxes cookies
11479 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11480 (org-match-string-no-properties 4)))
11481 rtn)))
11482 rtn)))))
11484 (defun org-format-outline-path (path &optional width prefix separator)
11485 "Format the outline path PATH for display.
11486 WIDTH is the maximum number of characters that is available.
11487 PREFIX is a prefix to be included in the returned string,
11488 such as the file name.
11489 SEPARATOR is inserted between the different parts of the path,
11490 the default is \"/\"."
11491 (setq width (or width 79))
11492 (if prefix (setq width (- width (length prefix))))
11493 (if (not path)
11494 (or prefix "")
11495 (let* ((nsteps (length path))
11496 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11497 (maxwidth (if (<= total-width width)
11498 10000 ;; everything fits
11499 ;; we need to shorten the level headings
11500 (/ (- width nsteps) nsteps)))
11501 (org-odd-levels-only nil)
11502 (n 0)
11503 (total (1+ (length prefix))))
11504 (setq maxwidth (max maxwidth 10))
11505 (concat prefix
11506 (if prefix (or separator "/"))
11507 (mapconcat
11508 (lambda (h)
11509 (setq n (1+ n))
11510 (if (and (= n nsteps) (< maxwidth 10000))
11511 (setq maxwidth (- total-width total)))
11512 (if (< (length h) maxwidth)
11513 (progn (setq total (+ total (length h) 1)) h)
11514 (setq h (substring h 0 (- maxwidth 2))
11515 total (+ total maxwidth 1))
11516 (if (string-match "[ \t]+\\'" h)
11517 (setq h (substring h 0 (match-beginning 0))))
11518 (setq h (concat h "..")))
11519 (org-add-props h nil 'face
11520 (nth (% (1- n) org-n-level-faces)
11521 org-level-faces))
11523 path (or separator "/"))))))
11525 (defun org-display-outline-path (&optional file current separator just-return-string)
11526 "Display the current outline path in the echo area.
11528 If FILE is non-nil, prepend the output with the file name.
11529 If CURRENT is non-nil, append the current heading to the output.
11530 SEPARATOR is passed through to `org-format-outline-path'. It separates
11531 the different parts of the path and defaults to \"/\".
11532 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11533 (interactive "P")
11534 (let* (case-fold-search
11535 (bfn (buffer-file-name (buffer-base-buffer)))
11536 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11537 res)
11538 (if current (setq path (append path
11539 (save-excursion
11540 (org-back-to-heading t)
11541 (if (looking-at org-complex-heading-regexp)
11542 (list (match-string 4)))))))
11543 (setq res
11544 (org-format-outline-path
11545 path
11546 (1- (frame-width))
11547 (and file bfn (concat (file-name-nondirectory bfn) separator))
11548 separator))
11549 (if just-return-string
11550 (org-no-properties res)
11551 (org-unlogged-message "%s" res))))
11553 (defvar org-refile-history nil
11554 "History for refiling operations.")
11556 (defvar org-after-refile-insert-hook nil
11557 "Hook run after `org-refile' has inserted its stuff at the new location.
11558 Note that this is still *before* the stuff will be removed from
11559 the *old* location.")
11561 (defvar org-capture-last-stored-marker)
11562 (defvar org-refile-keep nil
11563 "Non-nil means `org-refile' will copy instead of refile.")
11565 (defun org-copy ()
11566 "Like `org-refile', but copy."
11567 (interactive)
11568 (let ((org-refile-keep t))
11569 (funcall 'org-refile nil nil nil "Copy")))
11571 (defun org-refile (&optional goto default-buffer rfloc msg)
11572 "Move the entry or entries at point to another heading.
11573 The list of target headings is compiled using the information in
11574 `org-refile-targets', which see.
11576 At the target location, the entry is filed as a subitem of the target
11577 heading. Depending on `org-reverse-note-order', the new subitem will
11578 either be the first or the last subitem.
11580 If there is an active region, all entries in that region will be moved.
11581 However, the region must fulfill the requirement that the first heading
11582 is the first one sets the top-level of the moved text - at most siblings
11583 below it are allowed.
11585 With prefix arg GOTO, the command will only visit the target location
11586 and not actually move anything.
11588 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11589 go to the location where the last refiling operation has put the subtree.
11591 With a numeric prefix argument of `2', refile to the running clock.
11593 With a numeric prefix argument of `3', emulate `org-refile-keep'
11594 being set to `t' and copy to the target location, don't move it.
11595 Beware that keeping refiled entries may result in duplicated ID
11596 properties.
11598 RFLOC can be a refile location obtained in a different way.
11600 MSG is a string to replace \"Refile\" in the default prompt with
11601 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11603 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11605 If you are using target caching (see `org-refile-use-cache'),
11606 you have to clear the target cache in order to find new targets.
11607 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11608 prefix argument (`C-u C-u C-u C-c C-w')."
11610 (interactive "P")
11611 (if (member goto '(0 (64)))
11612 (org-refile-cache-clear)
11613 (let* ((actionmsg (or msg "Refile"))
11614 (cbuf (current-buffer))
11615 (regionp (org-region-active-p))
11616 (region-start (and regionp (region-beginning)))
11617 (region-end (and regionp (region-end)))
11618 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11619 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11620 pos it nbuf file re level reversed)
11621 (setq last-command nil)
11622 (when regionp
11623 (goto-char region-start)
11624 (or (bolp) (goto-char (point-at-bol)))
11625 (setq region-start (point))
11626 (unless (or (org-kill-is-subtree-p
11627 (buffer-substring region-start region-end))
11628 (prog1 org-refile-active-region-within-subtree
11629 (let ((s (point-at-eol)))
11630 (org-toggle-heading)
11631 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11632 (user-error "The region is not a (sequence of) subtree(s)")))
11633 (if (equal goto '(16))
11634 (org-refile-goto-last-stored)
11635 (when (or
11636 (and (equal goto 2)
11637 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11638 (prog1
11639 (setq it (list (or org-clock-heading "running clock")
11640 (buffer-file-name
11641 (marker-buffer org-clock-hd-marker))
11643 (marker-position org-clock-hd-marker)))
11644 (setq goto nil)))
11645 (setq it (or rfloc
11646 (let (heading-text)
11647 (save-excursion
11648 (unless goto
11649 (org-back-to-heading t)
11650 (setq heading-text
11651 (nth 4 (org-heading-components))))
11653 (org-refile-get-location
11654 (cond (goto "Goto")
11655 (regionp (concat actionmsg " region to"))
11656 (t (concat actionmsg " subtree \""
11657 heading-text "\" to")))
11658 default-buffer
11659 (and (not (equal '(4) goto))
11660 org-refile-allow-creating-parent-nodes)
11661 goto))))))
11662 (setq file (nth 1 it)
11663 re (nth 2 it)
11664 pos (nth 3 it))
11665 (if (and (not goto)
11667 (equal (buffer-file-name) file)
11668 (if regionp
11669 (and (>= pos region-start)
11670 (<= pos region-end))
11671 (and (>= pos (point))
11672 (< pos (save-excursion
11673 (org-end-of-subtree t t))))))
11674 (error "Cannot refile to position inside the tree or region"))
11676 (setq nbuf (or (find-buffer-visiting file)
11677 (find-file-noselect file)))
11678 (if (and goto (not (equal goto 3)))
11679 (progn
11680 (org-pop-to-buffer-same-window nbuf)
11681 (goto-char pos)
11682 (org-show-context 'org-goto))
11683 (if regionp
11684 (progn
11685 (org-kill-new (buffer-substring region-start region-end))
11686 (org-save-markers-in-region region-start region-end))
11687 (org-copy-subtree 1 nil t))
11688 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11689 (find-file-noselect file)))
11690 (setq reversed (org-notes-order-reversed-p))
11691 (save-excursion
11692 (save-restriction
11693 (widen)
11694 (if pos
11695 (progn
11696 (goto-char pos)
11697 (looking-at org-outline-regexp)
11698 (setq level (org-get-valid-level (funcall outline-level) 1))
11699 (goto-char
11700 (if reversed
11701 (or (outline-next-heading) (point-max))
11702 (or (save-excursion (org-get-next-sibling))
11703 (org-end-of-subtree t t)
11704 (point-max)))))
11705 (setq level 1)
11706 (if (not reversed)
11707 (goto-char (point-max))
11708 (goto-char (point-min))
11709 (or (outline-next-heading) (goto-char (point-max)))))
11710 (if (not (bolp)) (newline))
11711 (org-paste-subtree level)
11712 (when org-log-refile
11713 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11714 (unless (eq org-log-refile 'note)
11715 (save-excursion (org-add-log-note))))
11716 (and org-auto-align-tags
11717 (let ((org-loop-over-headlines-in-active-region nil))
11718 (org-set-tags nil t)))
11719 (let ((bookmark-name (plist-get org-bookmark-names-plist
11720 :last-refile)))
11721 (when bookmark-name
11722 (with-demoted-errors
11723 (bookmark-set bookmark-name))))
11724 ;; If we are refiling for capture, make sure that the
11725 ;; last-capture pointers point here
11726 (when (org-bound-and-true-p org-refile-for-capture)
11727 (let ((bookmark-name (plist-get org-bookmark-names-plist
11728 :last-capture-marker)))
11729 (when bookmark-name
11730 (with-demoted-errors
11731 (bookmark-set bookmark-name))))
11732 (move-marker org-capture-last-stored-marker (point)))
11733 (if (fboundp 'deactivate-mark) (deactivate-mark))
11734 (run-hooks 'org-after-refile-insert-hook))))
11735 (unless org-refile-keep
11736 (if regionp
11737 (delete-region (point) (+ (point) (- region-end region-start)))
11738 (delete-region
11739 (and (org-back-to-heading t) (point))
11740 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11741 (when (featurep 'org-inlinetask)
11742 (org-inlinetask-remove-END-maybe))
11743 (setq org-markers-to-move nil)
11744 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11746 (defun org-refile-goto-last-stored ()
11747 "Go to the location where the last refile was stored."
11748 (interactive)
11749 (bookmark-jump "org-refile-last-stored")
11750 (message "This is the location of the last refile"))
11752 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11753 no-exclude)
11754 "Prompt the user for a refile location, using PROMPT.
11755 PROMPT should not be suffixed with a colon and a space, because
11756 this function appends the default value from
11757 `org-refile-history' automatically, if that is not empty.
11758 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11759 this is used for the GOTO interface."
11760 (let ((org-refile-targets org-refile-targets)
11761 (org-refile-use-outline-path org-refile-use-outline-path)
11762 excluded-entries)
11763 (when (and (derived-mode-p 'org-mode)
11764 (not org-refile-use-cache)
11765 (not no-exclude))
11766 (org-map-tree
11767 (lambda()
11768 (setq excluded-entries
11769 (append excluded-entries (list (org-get-heading t t)))))))
11770 (setq org-refile-target-table
11771 (org-refile-get-targets default-buffer excluded-entries)))
11772 (unless org-refile-target-table
11773 (user-error "No refile targets"))
11774 (let* ((cbuf (current-buffer))
11775 (partial-completion-mode nil)
11776 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11777 (cfunc (if (and org-refile-use-outline-path
11778 org-outline-path-complete-in-steps)
11779 'org-olpath-completing-read
11780 'org-icompleting-read))
11781 (extra (if org-refile-use-outline-path "/" ""))
11782 (cbnex (concat (buffer-name) extra))
11783 (filename (and cfn (expand-file-name cfn)))
11784 (tbl (mapcar
11785 (lambda (x)
11786 (if (and (not (member org-refile-use-outline-path
11787 '(file full-file-path)))
11788 (not (equal filename (nth 1 x))))
11789 (cons (concat (car x) extra " ("
11790 (file-name-nondirectory (nth 1 x)) ")")
11791 (cdr x))
11792 (cons (concat (car x) extra) (cdr x))))
11793 org-refile-target-table))
11794 (completion-ignore-case t)
11795 cdef
11796 (prompt (concat prompt
11797 (or (and (car org-refile-history)
11798 (concat " (default " (car org-refile-history) ")"))
11799 (and (assoc cbnex tbl) (setq cdef cbnex)
11800 (concat " (default " cbnex ")"))) ": "))
11801 pa answ parent-target child parent old-hist)
11802 (setq old-hist org-refile-history)
11803 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11804 nil 'org-refile-history (or cdef (car org-refile-history))))
11805 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11806 (org-refile-check-position pa)
11807 (if pa
11808 (progn
11809 (when (or (not org-refile-history)
11810 (not (eq old-hist org-refile-history))
11811 (not (equal (car pa) (car org-refile-history))))
11812 (setq org-refile-history
11813 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11814 org-refile-history
11815 (cdr org-refile-history))))
11816 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11817 (pop org-refile-history)))
11819 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11820 (progn
11821 (setq parent (match-string 1 answ)
11822 child (match-string 2 answ))
11823 (setq parent-target (or (assoc parent tbl)
11824 (assoc (concat parent "/") tbl)))
11825 (when (and parent-target
11826 (or (eq new-nodes t)
11827 (and (eq new-nodes 'confirm)
11828 (y-or-n-p (format "Create new node \"%s\"? "
11829 child)))))
11830 (org-refile-new-child parent-target child)))
11831 (user-error "Invalid target location")))))
11833 (declare-function org-string-nw-p "org-macs" (s))
11834 (defun org-refile-check-position (refile-pointer)
11835 "Check if the refile pointer matches the headline to which it points."
11836 (let* ((file (nth 1 refile-pointer))
11837 (re (nth 2 refile-pointer))
11838 (pos (nth 3 refile-pointer))
11839 buffer)
11840 (if (and (not (markerp pos)) (not file))
11841 (if file
11842 (user-error "Please save the buffer to a file before refiling")
11843 (user-error "Please indicate a target file in the refile path"))
11844 (when (org-string-nw-p re)
11845 (setq buffer (if (markerp pos)
11846 (marker-buffer pos)
11847 (or (find-buffer-visiting file)
11848 (find-file-noselect file))))
11849 (with-current-buffer buffer
11850 (save-excursion
11851 (save-restriction
11852 (widen)
11853 (goto-char pos)
11854 (beginning-of-line 1)
11855 (unless (org-looking-at-p re)
11856 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11858 (defun org-refile-new-child (parent-target child)
11859 "Use refile target PARENT-TARGET to add new CHILD below it."
11860 (unless parent-target
11861 (error "Cannot find parent for new node"))
11862 (let ((file (nth 1 parent-target))
11863 (pos (nth 3 parent-target))
11864 level)
11865 (with-current-buffer (or (find-buffer-visiting file)
11866 (find-file-noselect file))
11867 (save-excursion
11868 (save-restriction
11869 (widen)
11870 (if pos
11871 (goto-char pos)
11872 (goto-char (point-max))
11873 (if (not (bolp)) (newline)))
11874 (when (looking-at org-outline-regexp)
11875 (setq level (funcall outline-level))
11876 (org-end-of-subtree t t))
11877 (org-back-over-empty-lines)
11878 (insert "\n" (make-string
11879 (if pos (org-get-valid-level level 1) 1) ?*)
11880 " " child "\n")
11881 (beginning-of-line 0)
11882 (list (concat (car parent-target) "/" child) file "" (point)))))))
11884 (defun org-olpath-completing-read (prompt collection &rest args)
11885 "Read an outline path like a file name."
11886 (let ((thetable collection)
11887 (org-completion-use-ido nil) ; does not work with ido.
11888 (org-completion-use-iswitchb nil)) ; or iswitchb
11889 (apply
11890 'org-icompleting-read prompt
11891 (lambda (string predicate &optional flag)
11892 (let (rtn r f (l (length string)))
11893 (cond
11894 ((eq flag nil)
11895 ;; try completion
11896 (try-completion string thetable))
11897 ((eq flag t)
11898 ;; all-completions
11899 (setq rtn (all-completions string thetable predicate))
11900 (mapcar
11901 (lambda (x)
11902 (setq r (substring x l))
11903 (if (string-match " ([^)]*)$" x)
11904 (setq f (match-string 0 x))
11905 (setq f ""))
11906 (if (string-match "/" r)
11907 (concat string (substring r 0 (match-end 0)) f)
11909 rtn))
11910 ((eq flag 'lambda)
11911 ;; exact match?
11912 (assoc string thetable)))))
11913 args)))
11915 ;;;; Dynamic blocks
11917 (defun org-find-dblock (name)
11918 "Find the first dynamic block with name NAME in the buffer.
11919 If not found, stay at current position and return nil."
11920 (let ((case-fold-search t) pos)
11921 (save-excursion
11922 (goto-char (point-min))
11923 (setq pos (and (re-search-forward
11924 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11925 (match-beginning 0))))
11926 (if pos (goto-char pos))
11927 pos))
11929 (defun org-create-dblock (plist)
11930 "Create a dynamic block section, with parameters taken from PLIST.
11931 PLIST must contain a :name entry which is used as name of the block."
11932 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11933 (end-of-line 1)
11934 (newline))
11935 (let ((col (current-column))
11936 (name (plist-get plist :name)))
11937 (insert "#+BEGIN: " name)
11938 (while plist
11939 (if (eq (car plist) :name)
11940 (setq plist (cddr plist))
11941 (insert " " (prin1-to-string (pop plist)))))
11942 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11943 (beginning-of-line -2)))
11945 (defun org-prepare-dblock ()
11946 "Prepare dynamic block for refresh.
11947 This empties the block, puts the cursor at the insert position and returns
11948 the property list including an extra property :name with the block name."
11949 (unless (looking-at org-dblock-start-re)
11950 (user-error "Not at a dynamic block"))
11951 (let* ((begdel (1+ (match-end 0)))
11952 (name (org-no-properties (match-string 1)))
11953 (params (append (list :name name)
11954 (read (concat "(" (match-string 3) ")")))))
11955 (save-excursion
11956 (beginning-of-line 1)
11957 (skip-chars-forward " \t")
11958 (setq params (plist-put params :indentation-column (current-column))))
11959 (unless (re-search-forward org-dblock-end-re nil t)
11960 (error "Dynamic block not terminated"))
11961 (setq params
11962 (append params
11963 (list :content (buffer-substring
11964 begdel (match-beginning 0)))))
11965 (delete-region begdel (match-beginning 0))
11966 (goto-char begdel)
11967 (open-line 1)
11968 params))
11970 (defun org-map-dblocks (&optional command)
11971 "Apply COMMAND to all dynamic blocks in the current buffer.
11972 If COMMAND is not given, use `org-update-dblock'."
11973 (let ((cmd (or command 'org-update-dblock)))
11974 (save-excursion
11975 (goto-char (point-min))
11976 (while (re-search-forward org-dblock-start-re nil t)
11977 (goto-char (match-beginning 0))
11978 (save-excursion
11979 (condition-case nil
11980 (funcall cmd)
11981 (error (message "Error during update of dynamic block"))))
11982 (unless (re-search-forward org-dblock-end-re nil t)
11983 (error "Dynamic block not terminated"))))))
11985 (defun org-dblock-update (&optional arg)
11986 "User command for updating dynamic blocks.
11987 Update the dynamic block at point. With prefix ARG, update all dynamic
11988 blocks in the buffer."
11989 (interactive "P")
11990 (if arg
11991 (org-update-all-dblocks)
11992 (or (looking-at org-dblock-start-re)
11993 (org-beginning-of-dblock))
11994 (org-update-dblock)))
11996 (defun org-update-dblock ()
11997 "Update the dynamic block at point.
11998 This means to empty the block, parse for parameters and then call
11999 the correct writing function."
12000 (interactive)
12001 (save-window-excursion
12002 (let* ((pos (point))
12003 (line (org-current-line))
12004 (params (org-prepare-dblock))
12005 (name (plist-get params :name))
12006 (indent (plist-get params :indentation-column))
12007 (cmd (intern (concat "org-dblock-write:" name))))
12008 (message "Updating dynamic block `%s' at line %d..." name line)
12009 (funcall cmd params)
12010 (message "Updating dynamic block `%s' at line %d...done" name line)
12011 (goto-char pos)
12012 (when (and indent (> indent 0))
12013 (setq indent (make-string indent ?\ ))
12014 (save-excursion
12015 (org-beginning-of-dblock)
12016 (forward-line 1)
12017 (while (not (looking-at org-dblock-end-re))
12018 (insert indent)
12019 (beginning-of-line 2))
12020 (when (looking-at org-dblock-end-re)
12021 (and (looking-at "[ \t]+")
12022 (replace-match ""))
12023 (insert indent)))))))
12025 (defun org-beginning-of-dblock ()
12026 "Find the beginning of the dynamic block at point.
12027 Error if there is no such block at point."
12028 (let ((pos (point))
12029 beg)
12030 (end-of-line 1)
12031 (if (and (re-search-backward org-dblock-start-re nil t)
12032 (setq beg (match-beginning 0))
12033 (re-search-forward org-dblock-end-re nil t)
12034 (> (match-end 0) pos))
12035 (goto-char beg)
12036 (goto-char pos)
12037 (error "Not in a dynamic block"))))
12039 (defun org-update-all-dblocks ()
12040 "Update all dynamic blocks in the buffer.
12041 This function can be used in a hook."
12042 (interactive)
12043 (when (derived-mode-p 'org-mode)
12044 (org-map-dblocks 'org-update-dblock)))
12047 ;;;; Completion
12049 (declare-function org-export-backend-name "org-export" (cl-x))
12050 (declare-function org-export-backend-options "org-export" (cl-x))
12051 (defun org-get-export-keywords ()
12052 "Return a list of all currently understood export keywords.
12053 Export keywords include options, block names, attributes and
12054 keywords relative to each registered export back-end."
12055 (let (keywords)
12056 (dolist (backend
12057 (org-bound-and-true-p org-export--registered-backends)
12058 (delq nil keywords))
12059 ;; Back-end name (for keywords, like #+LATEX:)
12060 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12061 (dolist (option-entry (org-export-backend-options backend))
12062 ;; Back-end options.
12063 (push (nth 1 option-entry) keywords)))))
12065 (defconst org-options-keywords
12066 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12067 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12068 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12069 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12070 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12072 (defcustom org-structure-template-alist
12073 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12074 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12075 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12076 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12077 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12078 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12079 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12080 "<literal style=\"latex\">\n?\n</literal>")
12081 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12082 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12083 "<literal style=\"html\">\n?\n</literal>")
12084 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12085 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12086 ("A" "#+ASCII: " "")
12087 ("i" "#+INDEX: ?" "#+INDEX: ?")
12088 ("I" "#+INCLUDE: %file ?"
12089 "<include file=%file markup=\"?\">"))
12090 "Structure completion elements.
12091 This is a list of abbreviation keys and values. The value gets inserted
12092 if you type `<' followed by the key and then press the completion key,
12093 usually `M-TAB'. %file will be replaced by a file name after prompting
12094 for the file using completion. The cursor will be placed at the position
12095 of the `?` in the template.
12096 There are two templates for each key, the first uses the original Org syntax,
12097 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12098 the default when the /org-mtags.el/ module has been loaded. See also the
12099 variable `org-mtags-prefer-muse-templates'."
12100 :group 'org-completion
12101 :type '(repeat
12102 (list
12103 (string :tag "Key")
12104 (string :tag "Template")
12105 (string :tag "Muse Template"))))
12107 (defun org-try-structure-completion ()
12108 "Try to complete a structure template before point.
12109 This looks for strings like \"<e\" on an otherwise empty line and
12110 expands them."
12111 (let ((l (buffer-substring (point-at-bol) (point)))
12113 (when (and (looking-at "[ \t]*$")
12114 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12115 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12116 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12117 (match-beginning 1)) a)
12118 t)))
12120 (defun org-complete-expand-structure-template (start cell)
12121 "Expand a structure template."
12122 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12123 (rpl (nth (if musep 2 1) cell))
12124 (ind ""))
12125 (delete-region start (point))
12126 (when (string-match "\\`#\\+" rpl)
12127 (cond
12128 ((bolp))
12129 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12130 (setq ind (buffer-substring (point-at-bol) (point))))
12131 (t (newline))))
12132 (setq start (point))
12133 (if (string-match "%file" rpl)
12134 (setq rpl (replace-match
12135 (concat
12136 "\""
12137 (save-match-data
12138 (abbreviate-file-name (read-file-name "Include file: ")))
12139 "\"")
12140 t t rpl)))
12141 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12142 (concat "\n" ind)))
12143 (insert rpl)
12144 (if (re-search-backward "\\?" start t) (delete-char 1))))
12146 ;;;; TODO, DEADLINE, Comments
12148 (defun org-toggle-comment ()
12149 "Change the COMMENT state of an entry."
12150 (interactive)
12151 (save-excursion
12152 (org-back-to-heading)
12153 (let (case-fold-search)
12154 (cond
12155 ((looking-at (format org-heading-keyword-regexp-format
12156 org-comment-string))
12157 (goto-char (match-end 1))
12158 (looking-at (concat " +" org-comment-string))
12159 (replace-match "" t t)
12160 (when (eolp) (insert " ")))
12161 ((looking-at org-outline-regexp)
12162 (goto-char (match-end 0))
12163 (insert org-comment-string " "))))))
12165 (defvar org-last-todo-state-is-todo nil
12166 "This is non-nil when the last TODO state change led to a TODO state.
12167 If the last change removed the TODO tag or switched to DONE, then
12168 this is nil.")
12170 (defvar org-setting-tags nil) ; dynamically skipped
12172 (defvar org-todo-setup-filter-hook nil
12173 "Hook for functions that pre-filter todo specs.
12174 Each function takes a todo spec and returns either nil or the spec
12175 transformed into canonical form." )
12177 (defvar org-todo-get-default-hook nil
12178 "Hook for functions that get a default item for todo.
12179 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12180 nil or a string to be used for the todo mark." )
12182 (defvar org-agenda-headline-snapshot-before-repeat)
12184 (defun org-current-effective-time ()
12185 "Return current time adjusted for `org-extend-today-until' variable."
12186 (let* ((ct (org-current-time))
12187 (dct (decode-time ct))
12188 (ct1
12189 (cond
12190 (org-use-last-clock-out-time-as-effective-time
12191 (or (org-clock-get-last-clock-out-time) ct))
12192 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12193 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12194 (t ct))))
12195 ct1))
12197 (defun org-todo-yesterday (&optional arg)
12198 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12199 (interactive "P")
12200 (if (eq major-mode 'org-agenda-mode)
12201 (apply 'org-agenda-todo-yesterday arg)
12202 (let* ((hour (third (decode-time
12203 (org-current-time))))
12204 (org-extend-today-until (1+ hour)))
12205 (org-todo arg))))
12207 (defvar org-block-entry-blocking ""
12208 "First entry preventing the TODO state change.")
12210 (defun org-cancel-repeater ()
12211 "Cancel a repeater by setting its numeric value to zero."
12212 (interactive)
12213 (save-excursion
12214 (org-back-to-heading t)
12215 (let ((bound1 (point))
12216 (bound0 (save-excursion (outline-next-heading) (point))))
12217 (when (re-search-forward
12218 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12219 org-deadline-time-regexp "\\)\\|\\("
12220 org-ts-regexp "\\)")
12221 bound0 t)
12222 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12223 (replace-match "0" t nil nil 1))))))
12225 (defun org-todo (&optional arg)
12226 "Change the TODO state of an item.
12227 The state of an item is given by a keyword at the start of the heading,
12228 like
12229 *** TODO Write paper
12230 *** DONE Call mom
12232 The different keywords are specified in the variable `org-todo-keywords'.
12233 By default the available states are \"TODO\" and \"DONE\".
12234 So for this example: when the item starts with TODO, it is changed to DONE.
12235 When it starts with DONE, the DONE is removed. And when neither TODO nor
12236 DONE are present, add TODO at the beginning of the heading.
12238 With \\[universal-argument] prefix arg, use completion to determine the new \
12239 state.
12240 With numeric prefix arg, switch to that state.
12241 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12242 keywords (nextset).
12243 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12244 With a numeric prefix arg of 0, inhibit note taking for the change.
12245 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12247 When called through ELisp, arg is also interpreted in the following way:
12248 'none -> empty state
12249 \"\"(empty string) -> switch to empty state
12250 'done -> switch to DONE
12251 'nextset -> switch to the next set of keywords
12252 'previousset -> switch to the previous set of keywords
12253 \"WAITING\" -> switch to the specified keyword, but only if it
12254 really is a member of `org-todo-keywords'."
12255 (interactive "P")
12256 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12257 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12258 'region-start-level 'region))
12259 org-loop-over-headlines-in-active-region)
12260 (org-map-entries
12261 `(org-todo ,arg)
12262 org-loop-over-headlines-in-active-region
12263 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12264 (if (equal arg '(16)) (setq arg 'nextset))
12265 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12266 (let ((org-blocker-hook org-blocker-hook)
12267 commentp
12268 case-fold-search)
12269 (when (equal arg '(64))
12270 (setq arg nil org-blocker-hook nil))
12271 (when (and org-blocker-hook
12272 (or org-inhibit-blocking
12273 (org-entry-get nil "NOBLOCKING")))
12274 (setq org-blocker-hook nil))
12275 (save-excursion
12276 (catch 'exit
12277 (org-back-to-heading t)
12278 (when (looking-at (concat "^\\*+ " org-comment-string))
12279 (org-toggle-comment)
12280 (setq commentp t))
12281 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12282 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12283 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12284 (let* ((match-data (match-data))
12285 (startpos (point-at-bol))
12286 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12287 (org-log-done org-log-done)
12288 (org-log-repeat org-log-repeat)
12289 (org-todo-log-states org-todo-log-states)
12290 (org-inhibit-logging
12291 (if (equal arg 0)
12292 (progn (setq arg nil) 'note) org-inhibit-logging))
12293 (this (match-string 1))
12294 (hl-pos (match-beginning 0))
12295 (head (org-get-todo-sequence-head this))
12296 (ass (assoc head org-todo-kwd-alist))
12297 (interpret (nth 1 ass))
12298 (done-word (nth 3 ass))
12299 (final-done-word (nth 4 ass))
12300 (org-last-state (or this ""))
12301 (completion-ignore-case t)
12302 (member (member this org-todo-keywords-1))
12303 (tail (cdr member))
12304 (org-state (cond
12305 ((and org-todo-key-trigger
12306 (or (and (equal arg '(4))
12307 (eq org-use-fast-todo-selection 'prefix))
12308 (and (not arg) org-use-fast-todo-selection
12309 (not (eq org-use-fast-todo-selection
12310 'prefix)))))
12311 ;; Use fast selection
12312 (org-fast-todo-selection))
12313 ((and (equal arg '(4))
12314 (or (not org-use-fast-todo-selection)
12315 (not org-todo-key-trigger)))
12316 ;; Read a state with completion
12317 (org-icompleting-read
12318 "State: " (mapcar 'list org-todo-keywords-1)
12319 nil t))
12320 ((eq arg 'right)
12321 (if this
12322 (if tail (car tail) nil)
12323 (car org-todo-keywords-1)))
12324 ((eq arg 'left)
12325 (if (equal member org-todo-keywords-1)
12327 (if this
12328 (nth (- (length org-todo-keywords-1)
12329 (length tail) 2)
12330 org-todo-keywords-1)
12331 (org-last org-todo-keywords-1))))
12332 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12333 (setq arg nil))) ; hack to fall back to cycling
12334 (arg
12335 ;; user or caller requests a specific state
12336 (cond
12337 ((equal arg "") nil)
12338 ((eq arg 'none) nil)
12339 ((eq arg 'done) (or done-word (car org-done-keywords)))
12340 ((eq arg 'nextset)
12341 (or (car (cdr (member head org-todo-heads)))
12342 (car org-todo-heads)))
12343 ((eq arg 'previousset)
12344 (let ((org-todo-heads (reverse org-todo-heads)))
12345 (or (car (cdr (member head org-todo-heads)))
12346 (car org-todo-heads))))
12347 ((car (member arg org-todo-keywords-1)))
12348 ((stringp arg)
12349 (user-error "State `%s' not valid in this file" arg))
12350 ((nth (1- (prefix-numeric-value arg))
12351 org-todo-keywords-1))))
12352 ((null member) (or head (car org-todo-keywords-1)))
12353 ((equal this final-done-word) nil) ;; -> make empty
12354 ((null tail) nil) ;; -> first entry
12355 ((memq interpret '(type priority))
12356 (if (eq this-command last-command)
12357 (car tail)
12358 (if (> (length tail) 0)
12359 (or done-word (car org-done-keywords))
12360 nil)))
12362 (car tail))))
12363 (org-state (or
12364 (run-hook-with-args-until-success
12365 'org-todo-get-default-hook org-state org-last-state)
12366 org-state))
12367 (next (if org-state (concat " " org-state " ") " "))
12368 (change-plist (list :type 'todo-state-change :from this :to org-state
12369 :position startpos))
12370 dolog now-done-p)
12371 (when org-blocker-hook
12372 (setq org-last-todo-state-is-todo
12373 (not (member this org-done-keywords)))
12374 (unless (save-excursion
12375 (save-match-data
12376 (org-with-wide-buffer
12377 (run-hook-with-args-until-failure
12378 'org-blocker-hook change-plist))))
12379 (if (org-called-interactively-p 'interactive)
12380 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12381 this org-state org-block-entry-blocking)
12382 ;; fail silently
12383 (message "TODO state change from %s to %s blocked (by \"%s\")"
12384 this org-state org-block-entry-blocking)
12385 (throw 'exit nil))))
12386 (store-match-data match-data)
12387 (replace-match next t t)
12388 (unless (pos-visible-in-window-p hl-pos)
12389 (message "TODO state changed to %s" (org-trim next)))
12390 (unless head
12391 (setq head (org-get-todo-sequence-head org-state)
12392 ass (assoc head org-todo-kwd-alist)
12393 interpret (nth 1 ass)
12394 done-word (nth 3 ass)
12395 final-done-word (nth 4 ass)))
12396 (when (memq arg '(nextset previousset))
12397 (message "Keyword-Set %d/%d: %s"
12398 (- (length org-todo-sets) -1
12399 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12400 (length org-todo-sets)
12401 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12402 (setq org-last-todo-state-is-todo
12403 (not (member org-state org-done-keywords)))
12404 (setq now-done-p (and (member org-state org-done-keywords)
12405 (not (member this org-done-keywords))))
12406 (and logging (org-local-logging logging))
12407 (when (and (or org-todo-log-states org-log-done)
12408 (not (eq org-inhibit-logging t))
12409 (not (memq arg '(nextset previousset))))
12410 ;; we need to look at recording a time and note
12411 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12412 (nth 2 (assoc this org-todo-log-states))))
12413 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12414 (setq dolog 'time))
12415 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12416 (and org-state
12417 (member org-state org-not-done-keywords)
12418 (not (member this org-not-done-keywords))))
12419 ;; This is now a todo state and was not one before
12420 ;; If there was a CLOSED time stamp, get rid of it.
12421 (org-add-planning-info nil nil 'closed))
12422 (when (and now-done-p org-log-done)
12423 ;; It is now done, and it was not done before
12424 (org-add-planning-info 'closed (org-current-effective-time))
12425 (if (and (not dolog) (eq 'note org-log-done))
12426 (org-add-log-setup 'done org-state this 'findpos 'note)))
12427 (when (and org-state dolog)
12428 ;; This is a non-nil state, and we need to log it
12429 (org-add-log-setup 'state org-state this 'findpos dolog)))
12430 ;; Fixup tag positioning
12431 (org-todo-trigger-tag-changes org-state)
12432 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12433 (when org-provide-todo-statistics
12434 (org-update-parent-todo-statistics))
12435 (run-hooks 'org-after-todo-state-change-hook)
12436 (if (and arg (not (member org-state org-done-keywords)))
12437 (setq head (org-get-todo-sequence-head org-state)))
12438 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12439 ;; Do we need to trigger a repeat?
12440 (when now-done-p
12441 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12442 ;; This is for the agenda, take a snapshot of the headline.
12443 (save-match-data
12444 (setq org-agenda-headline-snapshot-before-repeat
12445 (org-get-heading))))
12446 (org-auto-repeat-maybe org-state))
12447 ;; Fixup cursor location if close to the keyword
12448 (if (and (outline-on-heading-p)
12449 (not (bolp))
12450 (save-excursion (beginning-of-line 1)
12451 (looking-at org-todo-line-regexp))
12452 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12453 (progn
12454 (goto-char (or (match-end 2) (match-end 1)))
12455 (and (looking-at " ") (just-one-space))))
12456 (when org-trigger-hook
12457 (save-excursion
12458 (run-hook-with-args 'org-trigger-hook change-plist)))
12459 (when commentp (org-toggle-comment))))))))
12461 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12462 "Block turning an entry into a TODO, using the hierarchy.
12463 This checks whether the current task should be blocked from state
12464 changes. Such blocking occurs when:
12466 1. The task has children which are not all in a completed state.
12468 2. A task has a parent with the property :ORDERED:, and there
12469 are siblings prior to the current task with incomplete
12470 status.
12472 3. The parent of the task is blocked because it has siblings that should
12473 be done first, or is child of a block grandparent TODO entry."
12475 (if (not org-enforce-todo-dependencies)
12476 t ; if locally turned off don't block
12477 (catch 'dont-block
12478 ;; If this is not a todo state change, or if this entry is already DONE,
12479 ;; do not block
12480 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12481 (member (plist-get change-plist :from)
12482 (cons 'done org-done-keywords))
12483 (member (plist-get change-plist :to)
12484 (cons 'todo org-not-done-keywords))
12485 (not (plist-get change-plist :to)))
12486 (throw 'dont-block t))
12487 ;; If this task has children, and any are undone, it's blocked
12488 (save-excursion
12489 (org-back-to-heading t)
12490 (let ((this-level (funcall outline-level)))
12491 (outline-next-heading)
12492 (let ((child-level (funcall outline-level)))
12493 (while (and (not (eobp))
12494 (> child-level this-level))
12495 ;; this todo has children, check whether they are all
12496 ;; completed
12497 (if (and (not (org-entry-is-done-p))
12498 (org-entry-is-todo-p))
12499 (progn (setq org-block-entry-blocking (org-get-heading))
12500 (throw 'dont-block nil)))
12501 (outline-next-heading)
12502 (setq child-level (funcall outline-level))))))
12503 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12504 ;; any previous siblings are undone, it's blocked
12505 (save-excursion
12506 (org-back-to-heading t)
12507 (let* ((pos (point))
12508 (parent-pos (and (org-up-heading-safe) (point))))
12509 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12510 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12511 (forward-line 1)
12512 (re-search-forward org-not-done-heading-regexp pos t))
12513 (setq org-block-entry-blocking (match-string 0))
12514 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12515 ;; Search further up the hierarchy, to see if an ancestor is blocked
12516 (while t
12517 (goto-char parent-pos)
12518 (if (not (looking-at org-not-done-heading-regexp))
12519 (throw 'dont-block t)) ; do not block, parent is not a TODO
12520 (setq pos (point))
12521 (setq parent-pos (and (org-up-heading-safe) (point)))
12522 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12523 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12524 (forward-line 1)
12525 (re-search-forward org-not-done-heading-regexp pos t)
12526 (setq org-block-entry-blocking (org-get-heading)))
12527 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12529 (defcustom org-track-ordered-property-with-tag nil
12530 "Should the ORDERED property also be shown as a tag?
12531 The ORDERED property decides if an entry should require subtasks to be
12532 completed in sequence. Since a property is not very visible, setting
12533 this option means that toggling the ORDERED property with the command
12534 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12535 not relevant for the behavior, but it makes things more visible.
12537 Note that toggling the tag with tags commands will not change the property
12538 and therefore not influence behavior!
12540 This can be t, meaning the tag ORDERED should be used, It can also be a
12541 string to select a different tag for this task."
12542 :group 'org-todo
12543 :type '(choice
12544 (const :tag "No tracking" nil)
12545 (const :tag "Track with ORDERED tag" t)
12546 (string :tag "Use other tag")))
12548 (defun org-toggle-ordered-property ()
12549 "Toggle the ORDERED property of the current entry.
12550 For better visibility, you can track the value of this property with a tag.
12551 See variable `org-track-ordered-property-with-tag'."
12552 (interactive)
12553 (let* ((t1 org-track-ordered-property-with-tag)
12554 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12555 (save-excursion
12556 (org-back-to-heading)
12557 (if (org-entry-get nil "ORDERED")
12558 (progn
12559 (org-delete-property "ORDERED")
12560 (and tag (org-toggle-tag tag 'off))
12561 (message "Subtasks can be completed in arbitrary order"))
12562 (org-entry-put nil "ORDERED" "t")
12563 (and tag (org-toggle-tag tag 'on))
12564 (message "Subtasks must be completed in sequence")))))
12566 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12567 (defun org-block-todo-from-checkboxes (change-plist)
12568 "Block turning an entry into a TODO, using checkboxes.
12569 This checks whether the current task should be blocked from state
12570 changes because there are unchecked boxes in this entry."
12571 (if (not org-enforce-todo-checkbox-dependencies)
12572 t ; if locally turned off don't block
12573 (catch 'dont-block
12574 ;; If this is not a todo state change, or if this entry is already DONE,
12575 ;; do not block
12576 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12577 (member (plist-get change-plist :from)
12578 (cons 'done org-done-keywords))
12579 (member (plist-get change-plist :to)
12580 (cons 'todo org-not-done-keywords))
12581 (not (plist-get change-plist :to)))
12582 (throw 'dont-block t))
12583 ;; If this task has checkboxes that are not checked, it's blocked
12584 (save-excursion
12585 (org-back-to-heading t)
12586 (let ((beg (point)) end)
12587 (outline-next-heading)
12588 (setq end (point))
12589 (goto-char beg)
12590 (if (org-list-search-forward
12591 (concat (org-item-beginning-re)
12592 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12593 "\\[[- ]\\]")
12594 end t)
12595 (progn
12596 (if (boundp 'org-blocked-by-checkboxes)
12597 (setq org-blocked-by-checkboxes t))
12598 (throw 'dont-block nil)))))
12599 t))) ; do not block
12601 (defun org-entry-blocked-p ()
12602 "Is the current entry blocked?"
12603 (org-with-silent-modifications
12604 (if (org-entry-get nil "NOBLOCKING")
12605 nil ;; Never block this entry
12606 (not (run-hook-with-args-until-failure
12607 'org-blocker-hook
12608 (list :type 'todo-state-change
12609 :position (point)
12610 :from 'todo
12611 :to 'done))))))
12613 (defun org-update-statistics-cookies (all)
12614 "Update the statistics cookie, either from TODO or from checkboxes.
12615 This should be called with the cursor in a line with a statistics cookie."
12616 (interactive "P")
12617 (if all
12618 (progn
12619 (org-update-checkbox-count 'all)
12620 (org-map-entries 'org-update-parent-todo-statistics))
12621 (if (not (org-at-heading-p))
12622 (org-update-checkbox-count)
12623 (let ((pos (point-marker))
12624 end l1 l2)
12625 (ignore-errors (org-back-to-heading t))
12626 (if (not (org-at-heading-p))
12627 (org-update-checkbox-count)
12628 (setq l1 (org-outline-level))
12629 (setq end (save-excursion
12630 (outline-next-heading)
12631 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12632 (point)))
12633 (if (and (save-excursion
12634 (re-search-forward
12635 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12636 (not (save-excursion (re-search-forward
12637 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12638 (org-update-checkbox-count)
12639 (if (and l2 (> l2 l1))
12640 (progn
12641 (goto-char end)
12642 (org-update-parent-todo-statistics))
12643 (goto-char pos)
12644 (beginning-of-line 1)
12645 (while (re-search-forward
12646 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12647 (point-at-eol) t)
12648 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12649 (goto-char pos)
12650 (move-marker pos nil)))))
12652 (defvar org-entry-property-inherited-from) ;; defined below
12653 (defun org-update-parent-todo-statistics ()
12654 "Update any statistics cookie in the parent of the current headline.
12655 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12656 the entire subtree and this will travel up the hierarchy and update
12657 statistics everywhere."
12658 (let* ((prop (save-excursion (org-up-heading-safe)
12659 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12660 (recursive (or (not org-hierarchical-todo-statistics)
12661 (and prop (string-match "\\<recursive\\>" prop))))
12662 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12664 (first t)
12665 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12666 level ltoggle l1 new ndel
12667 (cnt-all 0) (cnt-done 0) is-percent kwd
12668 checkbox-beg ov ovs ove cookie-present)
12669 (catch 'exit
12670 (save-excursion
12671 (beginning-of-line 1)
12672 (setq ltoggle (funcall outline-level))
12673 ;; Three situations are to consider:
12675 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12676 ;; to the top-level ancestor on the headline;
12678 ;; 2. If parent has "recursive" property, repeat up to the
12679 ;; headline setting that property, taking inheritance into
12680 ;; account;
12682 ;; 3. Else, move up to direct parent and proceed only once.
12683 (while (and (setq level (org-up-heading-safe))
12684 (or recursive first)
12685 (>= (point) lim))
12686 (setq first nil cookie-present nil)
12687 (unless (and level
12688 (not (string-match
12689 "\\<checkbox\\>"
12690 (downcase (or (org-entry-get nil "COOKIE_DATA")
12691 "")))))
12692 (throw 'exit nil))
12693 (while (re-search-forward box-re (point-at-eol) t)
12694 (setq cnt-all 0 cnt-done 0 cookie-present t)
12695 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12696 (save-match-data
12697 (unless (outline-next-heading) (throw 'exit nil))
12698 (while (and (looking-at org-complex-heading-regexp)
12699 (> (setq l1 (length (match-string 1))) level))
12700 (setq kwd (and (or recursive (= l1 ltoggle))
12701 (match-string 2)))
12702 (if (or (eq org-provide-todo-statistics 'all-headlines)
12703 (and (listp org-provide-todo-statistics)
12704 (or (member kwd org-provide-todo-statistics)
12705 (member kwd org-done-keywords))))
12706 (setq cnt-all (1+ cnt-all))
12707 (if (eq org-provide-todo-statistics t)
12708 (and kwd (setq cnt-all (1+ cnt-all)))))
12709 (and (member kwd org-done-keywords)
12710 (setq cnt-done (1+ cnt-done)))
12711 (outline-next-heading)))
12712 (setq new
12713 (if is-percent
12714 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12715 (format "[%d/%d]" cnt-done cnt-all))
12716 ndel (- (match-end 0) checkbox-beg))
12717 ;; handle overlays when updating cookie from column view
12718 (when (setq ov (car (overlays-at checkbox-beg)))
12719 (setq ovs (overlay-start ov) ove (overlay-end ov))
12720 (delete-overlay ov))
12721 (goto-char checkbox-beg)
12722 (insert new)
12723 (delete-region (point) (+ (point) ndel))
12724 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12725 (when ov (move-overlay ov ovs ove)))
12726 (when cookie-present
12727 (run-hook-with-args 'org-after-todo-statistics-hook
12728 cnt-done (- cnt-all cnt-done))))))
12729 (run-hooks 'org-todo-statistics-hook)))
12731 (defvar org-after-todo-statistics-hook nil
12732 "Hook that is called after a TODO statistics cookie has been updated.
12733 Each function is called with two arguments: the number of not-done entries
12734 and the number of done entries.
12736 For example, the following function, when added to this hook, will switch
12737 an entry to DONE when all children are done, and back to TODO when new
12738 entries are set to a TODO status. Note that this hook is only called
12739 when there is a statistics cookie in the headline!
12741 (defun org-summary-todo (n-done n-not-done)
12742 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12743 (let (org-log-done org-log-states) ; turn off logging
12744 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12747 (defvar org-todo-statistics-hook nil
12748 "Hook that is run whenever Org thinks TODO statistics should be updated.
12749 This hook runs even if there is no statistics cookie present, in which case
12750 `org-after-todo-statistics-hook' would not run.")
12752 (defun org-todo-trigger-tag-changes (state)
12753 "Apply the changes defined in `org-todo-state-tags-triggers'."
12754 (let ((l org-todo-state-tags-triggers)
12755 changes)
12756 (when (or (not state) (equal state ""))
12757 (setq changes (append changes (cdr (assoc "" l)))))
12758 (when (and (stringp state) (> (length state) 0))
12759 (setq changes (append changes (cdr (assoc state l)))))
12760 (when (member state org-not-done-keywords)
12761 (setq changes (append changes (cdr (assoc 'todo l)))))
12762 (when (member state org-done-keywords)
12763 (setq changes (append changes (cdr (assoc 'done l)))))
12764 (dolist (c changes)
12765 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12767 (defun org-local-logging (value)
12768 "Get logging settings from a property VALUE."
12769 (let* (words w a)
12770 ;; directly set the variables, they are already local.
12771 (setq org-log-done nil
12772 org-log-repeat nil
12773 org-todo-log-states nil)
12774 (setq words (org-split-string value))
12775 (while (setq w (pop words))
12776 (cond
12777 ((setq a (assoc w org-startup-options))
12778 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12779 (set (nth 1 a) (nth 2 a))))
12780 ((setq a (org-extract-log-state-settings w))
12781 (and (member (car a) org-todo-keywords-1)
12782 (push a org-todo-log-states)))))))
12784 (defun org-get-todo-sequence-head (kwd)
12785 "Return the head of the TODO sequence to which KWD belongs.
12786 If KWD is not set, check if there is a text property remembering the
12787 right sequence."
12788 (let (p)
12789 (cond
12790 ((not kwd)
12791 (or (get-text-property (point-at-bol) 'org-todo-head)
12792 (progn
12793 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12794 nil (point-at-eol)))
12795 (get-text-property p 'org-todo-head))))
12796 ((not (member kwd org-todo-keywords-1))
12797 (car org-todo-keywords-1))
12798 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12800 (defun org-fast-todo-selection ()
12801 "Fast TODO keyword selection with single keys.
12802 Returns the new TODO keyword, or nil if no state change should occur."
12803 (let* ((fulltable org-todo-key-alist)
12804 (done-keywords org-done-keywords) ;; needed for the faces.
12805 (maxlen (apply 'max (mapcar
12806 (lambda (x)
12807 (if (stringp (car x)) (string-width (car x)) 0))
12808 fulltable)))
12809 (expert nil)
12810 (fwidth (+ maxlen 3 1 3))
12811 (ncol (/ (- (window-width) 4) fwidth))
12812 tg cnt e c tbl
12813 groups ingroup)
12814 (save-excursion
12815 (save-window-excursion
12816 (if expert
12817 (set-buffer (get-buffer-create " *Org todo*"))
12818 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12819 (erase-buffer)
12820 (org-set-local 'org-done-keywords done-keywords)
12821 (setq tbl fulltable cnt 0)
12822 (while (setq e (pop tbl))
12823 (cond
12824 ((equal e '(:startgroup))
12825 (push '() groups) (setq ingroup t)
12826 (when (not (= cnt 0))
12827 (setq cnt 0)
12828 (insert "\n"))
12829 (insert "{ "))
12830 ((equal e '(:endgroup))
12831 (setq ingroup nil cnt 0)
12832 (insert "}\n"))
12833 ((equal e '(:newline))
12834 (when (not (= cnt 0))
12835 (setq cnt 0)
12836 (insert "\n")
12837 (setq e (car tbl))
12838 (while (equal (car tbl) '(:newline))
12839 (insert "\n")
12840 (setq tbl (cdr tbl)))))
12842 (setq tg (car e) c (cdr e))
12843 (if ingroup (push tg (car groups)))
12844 (setq tg (org-add-props tg nil 'face
12845 (org-get-todo-face tg)))
12846 (if (and (= cnt 0) (not ingroup)) (insert " "))
12847 (insert "[" c "] " tg (make-string
12848 (- fwidth 4 (length tg)) ?\ ))
12849 (when (= (setq cnt (1+ cnt)) ncol)
12850 (insert "\n")
12851 (if ingroup (insert " "))
12852 (setq cnt 0)))))
12853 (insert "\n")
12854 (goto-char (point-min))
12855 (if (not expert) (org-fit-window-to-buffer))
12856 (message "[a-z..]:Set [SPC]:clear")
12857 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12858 (cond
12859 ((or (= c ?\C-g)
12860 (and (= c ?q) (not (rassoc c fulltable))))
12861 (setq quit-flag t))
12862 ((= c ?\ ) nil)
12863 ((setq e (rassoc c fulltable) tg (car e))
12865 (t (setq quit-flag t)))))))
12867 (defun org-entry-is-todo-p ()
12868 (member (org-get-todo-state) org-not-done-keywords))
12870 (defun org-entry-is-done-p ()
12871 (member (org-get-todo-state) org-done-keywords))
12873 (defun org-get-todo-state ()
12874 "Return the TODO keyword of the current subtree."
12875 (save-excursion
12876 (org-back-to-heading t)
12877 (and (looking-at org-todo-line-regexp)
12878 (match-end 2)
12879 (match-string 2))))
12881 (defun org-at-date-range-p (&optional inactive-ok)
12882 "Is the cursor inside a date range?"
12883 (interactive)
12884 (save-excursion
12885 (catch 'exit
12886 (let ((pos (point)))
12887 (skip-chars-backward "^[<\r\n")
12888 (skip-chars-backward "<[")
12889 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12890 (>= (match-end 0) pos)
12891 (throw 'exit t))
12892 (skip-chars-backward "^<[\r\n")
12893 (skip-chars-backward "<[")
12894 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12895 (>= (match-end 0) pos)
12896 (throw 'exit t)))
12897 nil)))
12899 (defun org-get-repeat (&optional tagline)
12900 "Check if there is a deadline/schedule with repeater in this entry."
12901 (save-match-data
12902 (save-excursion
12903 (org-back-to-heading t)
12904 (and (re-search-forward (if tagline
12905 (concat tagline "\\s-*" org-repeat-re)
12906 org-repeat-re)
12907 (org-entry-end-position) t)
12908 (match-string-no-properties 1)))))
12910 (defvar org-last-changed-timestamp)
12911 (defvar org-last-inserted-timestamp)
12912 (defvar org-log-post-message)
12913 (defvar org-log-note-purpose)
12914 (defvar org-log-note-how)
12915 (defvar org-log-note-extra)
12916 (defun org-auto-repeat-maybe (done-word)
12917 "Check if the current headline contains a repeated deadline/schedule.
12918 If yes, set TODO state back to what it was and change the base date
12919 of repeating deadline/scheduled time stamps to new date.
12920 This function is run automatically after each state change to a DONE state."
12921 ;; last-state is dynamically scoped into this function
12922 (let* ((repeat (org-get-repeat))
12923 (aa (assoc org-last-state org-todo-kwd-alist))
12924 (interpret (nth 1 aa))
12925 (head (nth 2 aa))
12926 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12927 (msg "Entry repeats: ")
12928 (org-log-done nil)
12929 (org-todo-log-states nil)
12930 re type n what ts time to-state)
12931 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12932 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12933 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12934 org-todo-repeat-to-state))
12935 (unless (and to-state (member to-state org-todo-keywords-1))
12936 (setq to-state (if (eq interpret 'type) org-last-state head)))
12937 (org-todo to-state)
12938 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12939 (org-entry-put nil "LAST_REPEAT" (format-time-string
12940 (org-time-stamp-format t t))))
12941 (when org-log-repeat
12942 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12943 (memq 'org-add-log-note post-command-hook))
12944 ;; OK, we are already setup for some record
12945 (if (eq org-log-repeat 'note)
12946 ;; make sure we take a note, not only a time stamp
12947 (setq org-log-note-how 'note))
12948 ;; Set up for taking a record
12949 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12950 org-last-state
12951 'findpos org-log-repeat)))
12952 (org-back-to-heading t)
12953 (org-add-planning-info nil nil 'closed)
12954 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12955 org-deadline-time-regexp "\\)\\|\\("
12956 org-ts-regexp "\\)"))
12957 (while (re-search-forward
12958 re (save-excursion (outline-next-heading) (point)) t)
12959 (setq type (if (match-end 1) org-scheduled-string
12960 (if (match-end 3) org-deadline-string "Plain:"))
12961 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12962 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12963 (setq n (string-to-number (match-string 2 ts))
12964 what (match-string 3 ts))
12965 (if (equal what "w") (setq n (* n 7) what "d"))
12966 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12967 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12968 ;; Preparation, see if we need to modify the start date for the change
12969 (when (match-end 1)
12970 (setq time (save-match-data (org-time-string-to-time ts)))
12971 (cond
12972 ((equal (match-string 1 ts) ".")
12973 ;; Shift starting date to today
12974 (org-timestamp-change
12975 (- (org-today) (time-to-days time))
12976 'day))
12977 ((equal (match-string 1 ts) "+")
12978 (let ((nshiftmax 10) (nshift 0))
12979 (while (or (= nshift 0)
12980 (<= (time-to-days time)
12981 (time-to-days (current-time))))
12982 (when (= (incf nshift) nshiftmax)
12983 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12984 (error "Abort")))
12985 (org-timestamp-change n (cdr (assoc what whata)))
12986 (org-at-timestamp-p t)
12987 (setq ts (match-string 1))
12988 (setq time (save-match-data (org-time-string-to-time ts)))))
12989 (org-timestamp-change (- n) (cdr (assoc what whata)))
12990 ;; rematch, so that we have everything in place for the real shift
12991 (org-at-timestamp-p t)
12992 (setq ts (match-string 1))
12993 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12994 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12995 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12996 (setq org-log-post-message msg)
12997 (message "%s" msg))))
12999 (defun org-show-todo-tree (arg)
13000 "Make a compact tree which shows all headlines marked with TODO.
13001 The tree will show the lines where the regexp matches, and all higher
13002 headlines above the match.
13003 With a \\[universal-argument] prefix, prompt for a regexp to match.
13004 With a numeric prefix N, construct a sparse tree for the Nth element
13005 of `org-todo-keywords-1'."
13006 (interactive "P")
13007 (let ((case-fold-search nil)
13008 (kwd-re
13009 (cond ((null arg) org-not-done-regexp)
13010 ((equal arg '(4))
13011 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13012 (mapcar 'list org-todo-keywords-1))))
13013 (concat "\\("
13014 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13015 "\\)\\>")))
13016 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13017 (regexp-quote (nth (1- (prefix-numeric-value arg))
13018 org-todo-keywords-1)))
13019 (t (user-error "Invalid prefix argument: %s" arg)))))
13020 (message "%d TODO entries found"
13021 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13023 (defun org-deadline (arg &optional time)
13024 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13025 With one universal prefix argument, remove any deadline from the item.
13026 With two universal prefix arguments, prompt for a warning delay.
13027 With argument TIME, set the deadline at the corresponding date. TIME
13028 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13029 (interactive "P")
13030 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13031 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13032 'region-start-level 'region))
13033 org-loop-over-headlines-in-active-region)
13034 (org-map-entries
13035 `(org-deadline ',arg ,time)
13036 org-loop-over-headlines-in-active-region
13037 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13038 (let* ((old-date (org-entry-get nil "DEADLINE"))
13039 (old-date-time (if old-date (org-time-string-to-time old-date)))
13040 (repeater (and old-date
13041 (string-match
13042 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13043 old-date)
13044 (match-string 1 old-date))))
13045 (cond
13046 ((equal arg '(4))
13047 (when (and old-date org-log-redeadline)
13048 (org-add-log-setup 'deldeadline nil old-date 'findpos
13049 org-log-redeadline))
13050 (org-remove-timestamp-with-keyword org-deadline-string)
13051 (message "Item no longer has a deadline."))
13052 ((equal arg '(16))
13053 (save-excursion
13054 (org-back-to-heading t)
13055 (if (re-search-forward
13056 org-deadline-time-regexp
13057 (save-excursion (outline-next-heading) (point)) t)
13058 (let* ((rpl0 (match-string 1))
13059 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13060 (replace-match
13061 (concat org-deadline-string
13062 " <" rpl
13063 (format " -%dd"
13064 (abs
13065 (- (time-to-days
13066 (save-match-data
13067 (org-read-date nil t nil "Warn starting from" old-date-time)))
13068 (time-to-days old-date-time))))
13069 ">") t t))
13070 (user-error "No deadline information to update"))))
13072 (org-add-planning-info 'deadline time 'closed)
13073 (when (and old-date org-log-redeadline
13074 (not (equal old-date
13075 (substring org-last-inserted-timestamp 1 -1))))
13076 (org-add-log-setup 'redeadline nil old-date 'findpos
13077 org-log-redeadline))
13078 (when repeater
13079 (save-excursion
13080 (org-back-to-heading t)
13081 (when (re-search-forward (concat org-deadline-string " "
13082 org-last-inserted-timestamp)
13083 (save-excursion
13084 (outline-next-heading) (point)) t)
13085 (goto-char (1- (match-end 0)))
13086 (insert " " repeater)
13087 (setq org-last-inserted-timestamp
13088 (concat (substring org-last-inserted-timestamp 0 -1)
13089 " " repeater
13090 (substring org-last-inserted-timestamp -1))))))
13091 (message "Deadline on %s" org-last-inserted-timestamp))))))
13093 (defun org-schedule (arg &optional time)
13094 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13095 With one universal prefix argument, remove any scheduling date from the item.
13096 With two universal prefix arguments, prompt for a delay cookie.
13097 With argument TIME, scheduled at the corresponding date. TIME can
13098 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13099 (interactive "P")
13100 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13101 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13102 'region-start-level 'region))
13103 org-loop-over-headlines-in-active-region)
13104 (org-map-entries
13105 `(org-schedule ',arg ,time)
13106 org-loop-over-headlines-in-active-region
13107 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13108 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13109 (old-date-time (if old-date (org-time-string-to-time old-date)))
13110 (repeater (and old-date
13111 (string-match
13112 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13113 old-date)
13114 (match-string 1 old-date))))
13115 (cond
13116 ((equal arg '(4))
13117 (progn
13118 (when (and old-date org-log-reschedule)
13119 (org-add-log-setup 'delschedule nil old-date 'findpos
13120 org-log-reschedule))
13121 (org-remove-timestamp-with-keyword org-scheduled-string)
13122 (message "Item is no longer scheduled.")))
13123 ((equal arg '(16))
13124 (save-excursion
13125 (org-back-to-heading t)
13126 (if (re-search-forward
13127 org-scheduled-time-regexp
13128 (save-excursion (outline-next-heading) (point)) t)
13129 (let* ((rpl0 (match-string 1))
13130 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13131 (replace-match
13132 (concat org-scheduled-string
13133 " <" rpl
13134 (format " -%dd"
13135 (abs
13136 (- (time-to-days
13137 (save-match-data
13138 (org-read-date nil t nil "Delay until" old-date-time)))
13139 (time-to-days old-date-time))))
13140 ">") t t))
13141 (user-error "No scheduled information to update"))))
13143 (org-add-planning-info 'scheduled time 'closed)
13144 (when (and old-date org-log-reschedule
13145 (not (equal old-date
13146 (substring org-last-inserted-timestamp 1 -1))))
13147 (org-add-log-setup 'reschedule nil old-date 'findpos
13148 org-log-reschedule))
13149 (when repeater
13150 (save-excursion
13151 (org-back-to-heading t)
13152 (when (re-search-forward (concat org-scheduled-string " "
13153 org-last-inserted-timestamp)
13154 (save-excursion
13155 (outline-next-heading) (point)) t)
13156 (goto-char (1- (match-end 0)))
13157 (insert " " repeater)
13158 (setq org-last-inserted-timestamp
13159 (concat (substring org-last-inserted-timestamp 0 -1)
13160 " " repeater
13161 (substring org-last-inserted-timestamp -1))))))
13162 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13164 (defun org-get-scheduled-time (pom &optional inherit)
13165 "Get the scheduled time as a time tuple, of a format suitable
13166 for calling org-schedule with, or if there is no scheduling,
13167 returns nil."
13168 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13169 (when time
13170 (apply 'encode-time (org-parse-time-string time)))))
13172 (defun org-get-deadline-time (pom &optional inherit)
13173 "Get the deadline as a time tuple, of a format suitable for
13174 calling org-deadline with, or if there is no scheduling, returns
13175 nil."
13176 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13177 (when time
13178 (apply 'encode-time (org-parse-time-string time)))))
13180 (defun org-remove-timestamp-with-keyword (keyword)
13181 "Remove all time stamps with KEYWORD in the current entry."
13182 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13183 beg)
13184 (save-excursion
13185 (org-back-to-heading t)
13186 (setq beg (point))
13187 (outline-next-heading)
13188 (while (re-search-backward re beg t)
13189 (replace-match "")
13190 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13191 (equal (char-before) ?\ ))
13192 (backward-delete-char 1)
13193 (if (string-match "^[ \t]*$" (buffer-substring
13194 (point-at-bol) (point-at-eol)))
13195 (delete-region (point-at-bol)
13196 (min (point-max) (1+ (point-at-eol))))))))))
13198 (defvar org-time-was-given) ; dynamically scoped parameter
13199 (defvar org-end-time-was-given) ; dynamically scoped parameter
13201 (defun org-add-planning-info (what &optional time &rest remove)
13202 "Insert new timestamp with keyword in the line directly after the headline.
13203 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13204 If non is given, the user is prompted for a date.
13205 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13206 be removed."
13207 (interactive)
13208 (let (org-time-was-given org-end-time-was-given ts
13209 end default-time default-input)
13211 (catch 'exit
13212 (when (and (memq what '(scheduled deadline))
13213 (or (not time)
13214 (and (stringp time)
13215 (string-match "^[-+]+[0-9]" time))))
13216 ;; Try to get a default date/time from existing timestamp
13217 (save-excursion
13218 (org-back-to-heading t)
13219 (setq end (save-excursion (outline-next-heading) (point)))
13220 (when (re-search-forward (if (eq what 'scheduled)
13221 org-scheduled-time-regexp
13222 org-deadline-time-regexp)
13223 end t)
13224 (setq ts (match-string 1)
13225 default-time
13226 (apply 'encode-time (org-parse-time-string ts))
13227 default-input (and ts (org-get-compact-tod ts))))))
13228 (when what
13229 (setq time
13230 (if (stringp time)
13231 ;; This is a string (relative or absolute), set proper date
13232 (apply 'encode-time
13233 (org-read-date-analyze
13234 time default-time (decode-time default-time)))
13235 ;; If necessary, get the time from the user
13236 (or time (org-read-date nil 'to-time nil nil
13237 default-time default-input)))))
13239 (when (and org-insert-labeled-timestamps-at-point
13240 (member what '(scheduled deadline)))
13241 (insert
13242 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13243 (org-insert-time-stamp time org-time-was-given
13244 nil nil nil (list org-end-time-was-given))
13245 (setq what nil))
13246 (save-excursion
13247 (save-restriction
13248 (let (col list elt ts buffer-invisibility-spec)
13249 (org-back-to-heading t)
13250 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13251 (goto-char (match-end 1))
13252 (setq col (current-column))
13253 (goto-char (match-end 0))
13254 (if (eobp) (insert "\n") (forward-char 1))
13255 (when (and (not what)
13256 (not (looking-at
13257 (concat "[ \t]*"
13258 org-keyword-time-not-clock-regexp))))
13259 ;; Nothing to add, nothing to remove...... :-)
13260 (throw 'exit nil))
13261 (if (and (not (looking-at org-outline-regexp))
13262 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13263 "[^\r\n]*"))
13264 (not (equal (match-string 1) org-clock-string)))
13265 (narrow-to-region (match-beginning 0) (match-end 0))
13266 (insert-before-markers "\n")
13267 (backward-char 1)
13268 (narrow-to-region (point) (point))
13269 (and org-adapt-indentation (org-indent-to-column col)))
13270 ;; Check if we have to remove something.
13271 (setq list (cons what remove))
13272 (while list
13273 (setq elt (pop list))
13274 (when (or (and (eq elt 'scheduled)
13275 (re-search-forward org-scheduled-time-regexp nil t))
13276 (and (eq elt 'deadline)
13277 (re-search-forward org-deadline-time-regexp nil t))
13278 (and (eq elt 'closed)
13279 (re-search-forward org-closed-time-regexp nil t)))
13280 (replace-match "")
13281 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13282 (and (looking-at "[ \t]+") (replace-match ""))
13283 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13284 (when what
13285 (insert
13286 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13287 (cond ((eq what 'scheduled) org-scheduled-string)
13288 ((eq what 'deadline) org-deadline-string)
13289 ((eq what 'closed) org-closed-string))
13290 " ")
13291 (setq ts (org-insert-time-stamp
13292 time
13293 (or org-time-was-given
13294 (and (eq what 'closed) org-log-done-with-time))
13295 (eq what 'closed)
13296 nil nil (list org-end-time-was-given)))
13297 (insert
13298 (if (not (or (bolp) (eq (char-before) ?\ )
13299 (memq (char-after) '(32 10))
13300 (eobp))) " " ""))
13301 (end-of-line 1))
13302 (goto-char (point-min))
13303 (widen)
13304 (if (and (looking-at "[ \t]*\n")
13305 (equal (char-before) ?\n))
13306 (delete-region (1- (point)) (point-at-eol)))
13307 ts))))))
13309 (defvar org-log-note-marker (make-marker))
13310 (defvar org-log-note-purpose nil)
13311 (defvar org-log-note-state nil)
13312 (defvar org-log-note-previous-state nil)
13313 (defvar org-log-note-how nil)
13314 (defvar org-log-note-extra nil)
13315 (defvar org-log-note-window-configuration nil)
13316 (defvar org-log-note-return-to (make-marker))
13317 (defvar org-log-note-effective-time nil
13318 "Remembered current time so that dynamically scoped
13319 `org-extend-today-until' affects tha timestamps in state change
13320 log")
13322 (defvar org-log-post-message nil
13323 "Message to be displayed after a log note has been stored.
13324 The auto-repeater uses this.")
13326 (defun org-add-note ()
13327 "Add a note to the current entry.
13328 This is done in the same way as adding a state change note."
13329 (interactive)
13330 (org-add-log-setup 'note nil nil 'findpos nil))
13332 (defvar org-property-end-re)
13333 (defun org-add-log-setup (&optional purpose state prev-state
13334 findpos how extra)
13335 "Set up the post command hook to take a note.
13336 If this is about to TODO state change, the new state is expected in STATE.
13337 When FINDPOS is non-nil, find the correct position for the note in
13338 the current entry. If not, assume that it can be inserted at point.
13339 HOW is an indicator what kind of note should be created.
13340 EXTRA is additional text that will be inserted into the notes buffer."
13341 (let* ((org-log-into-drawer (org-log-into-drawer))
13342 (drawer (cond ((stringp org-log-into-drawer)
13343 org-log-into-drawer)
13344 (org-log-into-drawer "LOGBOOK"))))
13345 (save-restriction
13346 (save-excursion
13347 (when findpos
13348 (org-back-to-heading t)
13349 (narrow-to-region (point) (save-excursion
13350 (outline-next-heading) (point)))
13351 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13352 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13353 "[^\r\n]*\\)?"))
13354 (goto-char (match-end 0))
13355 (cond
13356 (drawer
13357 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13358 nil t)
13359 (progn
13360 (goto-char (match-end 0))
13361 (or org-log-states-order-reversed
13362 (and (re-search-forward org-property-end-re nil t)
13363 (goto-char (1- (match-beginning 0))))))
13364 (insert "\n:" drawer ":\n:END:")
13365 (beginning-of-line 0)
13366 (org-indent-line)
13367 (beginning-of-line 2)
13368 (org-indent-line)
13369 (end-of-line 0)))
13370 ((and org-log-state-notes-insert-after-drawers
13371 (save-excursion
13372 (forward-line) (looking-at org-drawer-regexp)))
13373 (forward-line)
13374 (while (looking-at org-drawer-regexp)
13375 (goto-char (match-end 0))
13376 (re-search-forward org-property-end-re (point-max) t)
13377 (forward-line))
13378 (forward-line -1)))
13379 (unless org-log-states-order-reversed
13380 (and (= (char-after) ?\n) (forward-char 1))
13381 (org-skip-over-state-notes)
13382 (skip-chars-backward " \t\n\r")))
13383 (move-marker org-log-note-marker (point))
13384 (setq org-log-note-purpose purpose
13385 org-log-note-state state
13386 org-log-note-previous-state prev-state
13387 org-log-note-how how
13388 org-log-note-extra extra
13389 org-log-note-effective-time (org-current-effective-time))
13390 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13392 (defun org-skip-over-state-notes ()
13393 "Skip past the list of State notes in an entry."
13394 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13395 (when (ignore-errors (goto-char (org-in-item-p)))
13396 (let* ((struct (org-list-struct))
13397 (prevs (org-list-prevs-alist struct)))
13398 (while (looking-at "[ \t]*- State")
13399 (goto-char (or (org-list-get-next-item (point) struct prevs)
13400 (org-list-get-item-end (point) struct)))))))
13402 (defun org-add-log-note (&optional purpose)
13403 "Pop up a window for taking a note, and add this note later at point."
13404 (remove-hook 'post-command-hook 'org-add-log-note)
13405 (setq org-log-note-window-configuration (current-window-configuration))
13406 (delete-other-windows)
13407 (move-marker org-log-note-return-to (point))
13408 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13409 (goto-char org-log-note-marker)
13410 (org-switch-to-buffer-other-window "*Org Note*")
13411 (erase-buffer)
13412 (if (memq org-log-note-how '(time state))
13413 (let (current-prefix-arg) (org-store-log-note))
13414 (let ((org-inhibit-startup t)) (org-mode))
13415 (insert (format "# Insert note for %s.
13416 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13417 (cond
13418 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13419 ((eq org-log-note-purpose 'done) "closed todo item")
13420 ((eq org-log-note-purpose 'state)
13421 (format "state change from \"%s\" to \"%s\""
13422 (or org-log-note-previous-state "")
13423 (or org-log-note-state "")))
13424 ((eq org-log-note-purpose 'reschedule)
13425 "rescheduling")
13426 ((eq org-log-note-purpose 'delschedule)
13427 "no longer scheduled")
13428 ((eq org-log-note-purpose 'redeadline)
13429 "changing deadline")
13430 ((eq org-log-note-purpose 'deldeadline)
13431 "removing deadline")
13432 ((eq org-log-note-purpose 'refile)
13433 "refiling")
13434 ((eq org-log-note-purpose 'note)
13435 "this entry")
13436 (t (error "This should not happen")))))
13437 (if org-log-note-extra (insert org-log-note-extra))
13438 (org-set-local 'org-finish-function 'org-store-log-note)
13439 (run-hooks 'org-log-buffer-setup-hook)))
13441 (defvar org-note-abort nil) ; dynamically scoped
13442 (defun org-store-log-note ()
13443 "Finish taking a log note, and insert it to where it belongs."
13444 (let ((txt (buffer-string)))
13445 (kill-buffer (current-buffer))
13446 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13447 lines ind bul)
13448 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13449 (setq txt (replace-match "" t t txt)))
13450 (if (string-match "\\s-+\\'" txt)
13451 (setq txt (replace-match "" t t txt)))
13452 (setq lines (org-split-string txt "\n"))
13453 (when (and note (string-match "\\S-" note))
13454 (setq note
13455 (org-replace-escapes
13456 note
13457 (list (cons "%u" (user-login-name))
13458 (cons "%U" user-full-name)
13459 (cons "%t" (format-time-string
13460 (org-time-stamp-format 'long 'inactive)
13461 org-log-note-effective-time))
13462 (cons "%T" (format-time-string
13463 (org-time-stamp-format 'long nil)
13464 org-log-note-effective-time))
13465 (cons "%d" (format-time-string
13466 (org-time-stamp-format nil 'inactive)
13467 org-log-note-effective-time))
13468 (cons "%D" (format-time-string
13469 (org-time-stamp-format nil nil)
13470 org-log-note-effective-time))
13471 (cons "%s" (if org-log-note-state
13472 (concat "\"" org-log-note-state "\"")
13473 ""))
13474 (cons "%S" (if org-log-note-previous-state
13475 (concat "\"" org-log-note-previous-state "\"")
13476 "\"\"")))))
13477 (if lines (setq note (concat note " \\\\")))
13478 (push note lines))
13479 (when (or current-prefix-arg org-note-abort)
13480 (when org-log-into-drawer
13481 (org-remove-empty-drawer-at org-log-note-marker))
13482 (setq lines nil))
13483 (when lines
13484 (with-current-buffer (marker-buffer org-log-note-marker)
13485 (save-excursion
13486 (goto-char org-log-note-marker)
13487 (move-marker org-log-note-marker nil)
13488 (end-of-line 1)
13489 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13490 (setq ind (save-excursion
13491 (if (ignore-errors (goto-char (org-in-item-p)))
13492 (let ((struct (org-list-struct)))
13493 (org-list-get-ind
13494 (org-list-get-top-point struct) struct))
13495 (skip-chars-backward " \r\t\n")
13496 (cond
13497 ((and (org-at-heading-p)
13498 org-adapt-indentation)
13499 (1+ (org-current-level)))
13500 ((org-at-heading-p) 0)
13501 (t (org-get-indentation))))))
13502 (setq bul (org-list-bullet-string "-"))
13503 (org-indent-line-to ind)
13504 (insert bul (pop lines))
13505 (let ((ind-body (+ (length bul) ind)))
13506 (while lines
13507 (insert "\n")
13508 (org-indent-line-to ind-body)
13509 (insert (pop lines))))
13510 (message "Note stored")
13511 (org-back-to-heading t)
13512 (org-cycle-hide-drawers 'children))
13513 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13514 ;; from within `org-add-log-note' because `buffer-undo-list'
13515 ;; is then modified outside of `org-with-remote-undo'.
13516 (when (eq this-command 'org-agenda-todo)
13517 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13518 ;; Don't add undo information when called from `org-agenda-todo'
13519 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13520 (set-window-configuration org-log-note-window-configuration)
13521 (with-current-buffer (marker-buffer org-log-note-return-to)
13522 (goto-char org-log-note-return-to))
13523 (move-marker org-log-note-return-to nil)
13524 (and org-log-post-message (message "%s" org-log-post-message))))
13526 (defun org-remove-empty-drawer-at (pos)
13527 "Remove an empty drawer at position POS.
13528 POS may also be a marker."
13529 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13530 (org-with-wide-buffer
13531 (goto-char pos)
13532 (let ((drawer (org-element-at-point)))
13533 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13534 (not (org-element-property :contents-begin drawer)))
13535 (delete-region (org-element-property :begin drawer)
13536 (progn (goto-char (org-element-property :end drawer))
13537 (skip-chars-backward " \r\t\n")
13538 (forward-line)
13539 (point))))))))
13541 (defvar org-ts-type nil)
13542 (defun org-sparse-tree (&optional arg type)
13543 "Create a sparse tree, prompt for the details.
13544 This command can create sparse trees. You first need to select the type
13545 of match used to create the tree:
13547 t Show all TODO entries.
13548 T Show entries with a specific TODO keyword.
13549 m Show entries selected by a tags/property match.
13550 p Enter a property name and its value (both with completion on existing
13551 names/values) and show entries with that property.
13552 r Show entries matching a regular expression (`/' can be used as well).
13553 b Show deadlines and scheduled items before a date.
13554 a Show deadlines and scheduled items after a date.
13555 d Show deadlines due within `org-deadline-warning-days'.
13556 D Show deadlines and scheduled items between a date range."
13557 (interactive "P")
13558 (let (ans kwd value ts-type)
13559 (setq type (or type org-sparse-tree-default-date-type))
13560 (setq org-ts-type type)
13561 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13562 (cond ((eq type 'all) "all timestamps")
13563 ((eq type 'scheduled) "only scheduled")
13564 ((eq type 'deadline) "only deadline")
13565 ((eq type 'active) "only active timestamps")
13566 ((eq type 'inactive) "only inactive timestamps")
13567 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13568 ((eq type 'closed) "with a closed time-stamp")
13569 (t "scheduled/deadline")))
13570 (setq ans (read-char-exclusive))
13571 (cond
13572 ((equal ans ?c)
13573 (org-sparse-tree
13574 arg (cadr (member type '(scheduled-or-deadline
13575 all scheduled deadline active inactive closed)))))
13576 ((equal ans ?d)
13577 (call-interactively 'org-check-deadlines))
13578 ((equal ans ?b)
13579 (call-interactively 'org-check-before-date))
13580 ((equal ans ?a)
13581 (call-interactively 'org-check-after-date))
13582 ((equal ans ?D)
13583 (call-interactively 'org-check-dates-range))
13584 ((equal ans ?t)
13585 (call-interactively 'org-show-todo-tree))
13586 ((equal ans ?T)
13587 (org-show-todo-tree '(4)))
13588 ((member ans '(?T ?m))
13589 (call-interactively 'org-match-sparse-tree))
13590 ((member ans '(?p ?P))
13591 (setq kwd (org-icompleting-read "Property: "
13592 (mapcar 'list (org-buffer-property-keys))))
13593 (setq value (org-icompleting-read "Value: "
13594 (mapcar 'list (org-property-values kwd))))
13595 (unless (string-match "\\`{.*}\\'" value)
13596 (setq value (concat "\"" value "\"")))
13597 (org-match-sparse-tree arg (concat kwd "=" value)))
13598 ((member ans '(?r ?R ?/))
13599 (call-interactively 'org-occur))
13600 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13602 (defvar org-occur-highlights nil
13603 "List of overlays used for occur matches.")
13604 (make-variable-buffer-local 'org-occur-highlights)
13605 (defvar org-occur-parameters nil
13606 "Parameters of the active org-occur calls.
13607 This is a list, each call to org-occur pushes as cons cell,
13608 containing the regular expression and the callback, onto the list.
13609 The list can contain several entries if `org-occur' has been called
13610 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13611 will only contain one set of parameters. When the highlights are
13612 removed (for example with `C-c C-c', or with the next edit (depending
13613 on `org-remove-highlights-with-change'), this variable is emptied
13614 as well.")
13615 (make-variable-buffer-local 'org-occur-parameters)
13617 (defun org-occur (regexp &optional keep-previous callback)
13618 "Make a compact tree which shows all matches of REGEXP.
13619 The tree will show the lines where the regexp matches, and all higher
13620 headlines above the match. It will also show the heading after the match,
13621 to make sure editing the matching entry is easy.
13622 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13623 call to `org-occur' will be kept, to allow stacking of calls to this
13624 command.
13625 If CALLBACK is non-nil, it is a function which is called to confirm
13626 that the match should indeed be shown."
13627 (interactive "sRegexp: \nP")
13628 (when (equal regexp "")
13629 (user-error "Regexp cannot be empty"))
13630 (unless keep-previous
13631 (org-remove-occur-highlights nil nil t))
13632 (push (cons regexp callback) org-occur-parameters)
13633 (let ((cnt 0))
13634 (save-excursion
13635 (goto-char (point-min))
13636 (if (or (not keep-previous) ; do not want to keep
13637 (not org-occur-highlights)) ; no previous matches
13638 ;; hide everything
13639 (org-overview))
13640 (while (re-search-forward regexp nil t)
13641 (when (or (not callback)
13642 (save-match-data (funcall callback)))
13643 (setq cnt (1+ cnt))
13644 (when org-highlight-sparse-tree-matches
13645 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13646 (org-show-context 'occur-tree))))
13647 (when org-remove-highlights-with-change
13648 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13649 nil 'local))
13650 (unless org-sparse-tree-open-archived-trees
13651 (org-hide-archived-subtrees (point-min) (point-max)))
13652 (run-hooks 'org-occur-hook)
13653 (if (org-called-interactively-p 'interactive)
13654 (message "%d match(es) for regexp %s" cnt regexp))
13655 cnt))
13657 (defun org-occur-next-match (&optional n reset)
13658 "Function for `next-error-function' to find sparse tree matches.
13659 N is the number of matches to move, when negative move backwards.
13660 RESET is entirely ignored - this function always goes back to the
13661 starting point when no match is found."
13662 (let* ((limit (if (< n 0) (point-min) (point-max)))
13663 (search-func (if (< n 0)
13664 'previous-single-char-property-change
13665 'next-single-char-property-change))
13666 (n (abs n))
13667 (pos (point))
13669 (catch 'exit
13670 (while (setq p1 (funcall search-func (point) 'org-type))
13671 (when (equal p1 limit)
13672 (goto-char pos)
13673 (error "No more matches"))
13674 (when (equal (get-char-property p1 'org-type) 'org-occur)
13675 (setq n (1- n))
13676 (when (= n 0)
13677 (goto-char p1)
13678 (throw 'exit (point))))
13679 (goto-char p1))
13680 (goto-char p1)
13681 (error "No more matches"))))
13683 (defun org-show-context (&optional key)
13684 "Make sure point and context are visible.
13685 How much context is shown depends upon the variables
13686 `org-show-hierarchy-above', `org-show-following-heading',
13687 `org-show-entry-below' and `org-show-siblings'."
13688 (let ((heading-p (org-at-heading-p t))
13689 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13690 (following-p (org-get-alist-option org-show-following-heading key))
13691 (entry-p (org-get-alist-option org-show-entry-below key))
13692 (siblings-p (org-get-alist-option org-show-siblings key)))
13693 ;; Show heading or entry text
13694 (if (and heading-p (not entry-p))
13695 (org-flag-heading nil) ; only show the heading
13696 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13697 (org-show-hidden-entry))) ; show entire entry
13698 (when following-p
13699 ;; Show next sibling, or heading below text
13700 (save-excursion
13701 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13702 (org-flag-heading nil))))
13703 (when siblings-p (org-show-siblings))
13704 (when hierarchy-p
13705 ;; show all higher headings, possibly with siblings
13706 (save-excursion
13707 (while (and (condition-case nil
13708 (progn (org-up-heading-all 1) t)
13709 (error nil))
13710 (not (bobp)))
13711 (org-flag-heading nil)
13712 (when siblings-p (org-show-siblings)))))
13713 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13715 (defvar org-reveal-start-hook nil
13716 "Hook run before revealing a location.")
13718 (defun org-reveal (&optional siblings)
13719 "Show current entry, hierarchy above it, and the following headline.
13720 This can be used to show a consistent set of context around locations
13721 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13722 not t for the search context.
13724 With optional argument SIBLINGS, on each level of the hierarchy all
13725 siblings are shown. This repairs the tree structure to what it would
13726 look like when opened with hierarchical calls to `org-cycle'.
13727 With double optional argument \\[universal-argument] \\[universal-argument], \
13728 go to the parent and show the
13729 entire tree."
13730 (interactive "P")
13731 (run-hooks 'org-reveal-start-hook)
13732 (let ((org-show-hierarchy-above t)
13733 (org-show-following-heading t)
13734 (org-show-siblings (if siblings t org-show-siblings)))
13735 (org-show-context nil))
13736 (when (equal siblings '(16))
13737 (save-excursion
13738 (when (org-up-heading-safe)
13739 (org-show-subtree)
13740 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13742 (defun org-highlight-new-match (beg end)
13743 "Highlight from BEG to END and mark the highlight is an occur headline."
13744 (let ((ov (make-overlay beg end)))
13745 (overlay-put ov 'face 'secondary-selection)
13746 (overlay-put ov 'org-type 'org-occur)
13747 (push ov org-occur-highlights)))
13749 (defun org-remove-occur-highlights (&optional beg end noremove)
13750 "Remove the occur highlights from the buffer.
13751 BEG and END are ignored. If NOREMOVE is nil, remove this function
13752 from the `before-change-functions' in the current buffer."
13753 (interactive)
13754 (unless org-inhibit-highlight-removal
13755 (mapc 'delete-overlay org-occur-highlights)
13756 (setq org-occur-highlights nil)
13757 (setq org-occur-parameters nil)
13758 (unless noremove
13759 (remove-hook 'before-change-functions
13760 'org-remove-occur-highlights 'local))))
13762 ;;;; Priorities
13764 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13765 "Regular expression matching the priority indicator.")
13767 (defvar org-remove-priority-next-time nil)
13769 (defun org-priority-up ()
13770 "Increase the priority of the current item."
13771 (interactive)
13772 (org-priority 'up))
13774 (defun org-priority-down ()
13775 "Decrease the priority of the current item."
13776 (interactive)
13777 (org-priority 'down))
13779 (defun org-priority (&optional action show)
13780 "Change the priority of an item.
13781 ACTION can be `set', `up', `down', or a character."
13782 (interactive "P")
13783 (if (equal action '(4))
13784 (org-show-priority)
13785 (unless org-enable-priority-commands
13786 (user-error "Priority commands are disabled"))
13787 (setq action (or action 'set))
13788 (let (current new news have remove)
13789 (save-excursion
13790 (org-back-to-heading t)
13791 (if (looking-at org-priority-regexp)
13792 (setq current (string-to-char (match-string 2))
13793 have t))
13794 (cond
13795 ((eq action 'remove)
13796 (setq remove t new ?\ ))
13797 ((or (eq action 'set)
13798 (if (featurep 'xemacs) (characterp action) (integerp action)))
13799 (if (not (eq action 'set))
13800 (setq new action)
13801 (message "Priority %c-%c, SPC to remove: "
13802 org-highest-priority org-lowest-priority)
13803 (save-match-data
13804 (setq new (read-char-exclusive))))
13805 (if (and (= (upcase org-highest-priority) org-highest-priority)
13806 (= (upcase org-lowest-priority) org-lowest-priority))
13807 (setq new (upcase new)))
13808 (cond ((equal new ?\ ) (setq remove t))
13809 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13810 (user-error "Priority must be between `%c' and `%c'"
13811 org-highest-priority org-lowest-priority))))
13812 ((eq action 'up)
13813 (setq new (if have
13814 (1- current) ; normal cycling
13815 ;; last priority was empty
13816 (if (eq last-command this-command)
13817 org-lowest-priority ; wrap around empty to lowest
13818 ;; default
13819 (if org-priority-start-cycle-with-default
13820 org-default-priority
13821 (1- org-default-priority))))))
13822 ((eq action 'down)
13823 (setq new (if have
13824 (1+ current) ; normal cycling
13825 ;; last priority was empty
13826 (if (eq last-command this-command)
13827 org-highest-priority ; wrap around empty to highest
13828 ;; default
13829 (if org-priority-start-cycle-with-default
13830 org-default-priority
13831 (1+ org-default-priority))))))
13832 (t (user-error "Invalid action")))
13833 (if (or (< (upcase new) org-highest-priority)
13834 (> (upcase new) org-lowest-priority))
13835 (if (and (memq action '(up down))
13836 (not have) (not (eq last-command this-command)))
13837 ;; `new' is from default priority
13838 (error
13839 "The default can not be set, see `org-default-priority' why")
13840 ;; normal cycling: `new' is beyond highest/lowest priority
13841 ;; and is wrapped around to the empty priority
13842 (setq remove t)))
13843 (setq news (format "%c" new))
13844 (if have
13845 (if remove
13846 (replace-match "" t t nil 1)
13847 (replace-match news t t nil 2))
13848 (if remove
13849 (user-error "No priority cookie found in line")
13850 (let ((case-fold-search nil))
13851 (looking-at org-todo-line-regexp))
13852 (if (match-end 2)
13853 (progn
13854 (goto-char (match-end 2))
13855 (insert " [#" news "]"))
13856 (goto-char (match-beginning 3))
13857 (insert "[#" news "] "))))
13858 (org-preserve-lc (org-set-tags nil 'align)))
13859 (if remove
13860 (message "Priority removed")
13861 (message "Priority of current item set to %s" news)))))
13863 (defun org-show-priority ()
13864 "Show the priority of the current item.
13865 This priority is composed of the main priority given with the [#A] cookies,
13866 and by additional input from the age of a schedules or deadline entry."
13867 (interactive)
13868 (let ((pri (if (eq major-mode 'org-agenda-mode)
13869 (org-get-at-bol 'priority)
13870 (save-excursion
13871 (save-match-data
13872 (beginning-of-line)
13873 (and (looking-at org-heading-regexp)
13874 (org-get-priority (match-string 0))))))))
13875 (message "Priority is %d" (if pri pri -1000))))
13877 (defun org-get-priority (s)
13878 "Find priority cookie and return priority."
13879 (save-match-data
13880 (if (functionp org-get-priority-function)
13881 (funcall org-get-priority-function)
13882 (if (not (string-match org-priority-regexp s))
13883 (* 1000 (- org-lowest-priority org-default-priority))
13884 (* 1000 (- org-lowest-priority
13885 (string-to-char (match-string 2 s))))))))
13887 ;;;; Tags
13889 (defvar org-agenda-archives-mode)
13890 (defvar org-map-continue-from nil
13891 "Position from where mapping should continue.
13892 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13894 (defvar org-scanner-tags nil
13895 "The current tag list while the tags scanner is running.")
13896 (defvar org-trust-scanner-tags nil
13897 "Should `org-get-tags-at' use the tags for the scanner.
13898 This is for internal dynamical scoping only.
13899 When this is non-nil, the function `org-get-tags-at' will return the value
13900 of `org-scanner-tags' instead of building the list by itself. This
13901 can lead to large speed-ups when the tags scanner is used in a file with
13902 many entries, and when the list of tags is retrieved, for example to
13903 obtain a list of properties. Building the tags list for each entry in such
13904 a file becomes an N^2 operation - but with this variable set, it scales
13905 as N.")
13907 (defun org-scan-tags (action matcher todo-only &optional start-level)
13908 "Sca headline tags with inheritance and produce output ACTION.
13910 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13911 or `agenda' to produce an entry list for an agenda view. It can also be
13912 a Lisp form or a function that should be called at each matched headline, in
13913 this case the return value is a list of all return values from these calls.
13915 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13916 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13917 only lines with a not-done TODO keyword are included in the output.
13918 This should be the same variable that was scoped into
13919 and set by `org-make-tags-matcher' when it constructed MATCHER.
13921 START-LEVEL can be a string with asterisks, reducing the scope to
13922 headlines matching this string."
13923 (require 'org-agenda)
13924 (let* ((re (concat "^"
13925 (if start-level
13926 ;; Get the correct level to match
13927 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13928 org-outline-regexp)
13929 " *\\(\\<\\("
13930 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13931 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13932 (props (list 'face 'default
13933 'done-face 'org-agenda-done
13934 'undone-face 'default
13935 'mouse-face 'highlight
13936 'org-not-done-regexp org-not-done-regexp
13937 'org-todo-regexp org-todo-regexp
13938 'org-complex-heading-regexp org-complex-heading-regexp
13939 'help-echo
13940 (format "mouse-2 or RET jump to org file %s"
13941 (abbreviate-file-name
13942 (or (buffer-file-name (buffer-base-buffer))
13943 (buffer-name (buffer-base-buffer)))))))
13944 (org-map-continue-from nil)
13945 lspos tags tags-list
13946 (tags-alist (list (cons 0 org-file-tags)))
13947 (llast 0) rtn rtn1 level category i txt
13948 todo marker entry priority)
13949 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13950 (setq action (list 'lambda nil action)))
13951 (save-excursion
13952 (goto-char (point-min))
13953 (when (eq action 'sparse-tree)
13954 (org-overview)
13955 (org-remove-occur-highlights))
13956 (while (let (case-fold-search)
13957 (re-search-forward re nil t))
13958 (setq org-map-continue-from nil)
13959 (catch :skip
13960 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13961 tags (if (match-end 4) (org-match-string-no-properties 4)))
13962 (goto-char (setq lspos (match-beginning 0)))
13963 (setq level (org-reduced-level (org-outline-level))
13964 category (org-get-category))
13965 (setq i llast llast level)
13966 ;; remove tag lists from same and sublevels
13967 (while (>= i level)
13968 (when (setq entry (assoc i tags-alist))
13969 (setq tags-alist (delete entry tags-alist)))
13970 (setq i (1- i)))
13971 ;; add the next tags
13972 (when tags
13973 (setq tags (org-split-string tags ":")
13974 tags-alist
13975 (cons (cons level tags) tags-alist)))
13976 ;; compile tags for current headline
13977 (setq tags-list
13978 (if org-use-tag-inheritance
13979 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13980 tags)
13981 org-scanner-tags tags-list)
13982 (when org-use-tag-inheritance
13983 (setcdr (car tags-alist)
13984 (mapcar (lambda (x)
13985 (setq x (copy-sequence x))
13986 (org-add-prop-inherited x))
13987 (cdar tags-alist))))
13988 (when (and tags org-use-tag-inheritance
13989 (or (not (eq t org-use-tag-inheritance))
13990 org-tags-exclude-from-inheritance))
13991 ;; selective inheritance, remove uninherited ones
13992 (setcdr (car tags-alist)
13993 (org-remove-uninherited-tags (cdar tags-alist))))
13994 (when (and
13996 ;; eval matcher only when the todo condition is OK
13997 (and (or (not todo-only) (member todo org-not-done-keywords))
13998 (let ((case-fold-search t) (org-trust-scanner-tags t))
13999 (eval matcher)))
14001 ;; Call the skipper, but return t if it does not skip,
14002 ;; so that the `and' form continues evaluating
14003 (progn
14004 (unless (eq action 'sparse-tree) (org-agenda-skip))
14007 ;; Check if timestamps are deselecting this entry
14008 (or (not todo-only)
14009 (and (member todo org-not-done-keywords)
14010 (or (not org-agenda-tags-todo-honor-ignore-options)
14011 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14013 ;; select this headline
14014 (cond
14015 ((eq action 'sparse-tree)
14016 (and org-highlight-sparse-tree-matches
14017 (org-get-heading) (match-end 0)
14018 (org-highlight-new-match
14019 (match-beginning 1) (match-end 1)))
14020 (org-show-context 'tags-tree))
14021 ((eq action 'agenda)
14022 (setq txt (org-agenda-format-item
14024 (concat
14025 (if (eq org-tags-match-list-sublevels 'indented)
14026 (make-string (1- level) ?.) "")
14027 (org-get-heading))
14028 level category
14029 tags-list)
14030 priority (org-get-priority txt))
14031 (goto-char lspos)
14032 (setq marker (org-agenda-new-marker))
14033 (org-add-props txt props
14034 'org-marker marker 'org-hd-marker marker 'org-category category
14035 'todo-state todo
14036 'priority priority 'type "tagsmatch")
14037 (push txt rtn))
14038 ((functionp action)
14039 (setq org-map-continue-from nil)
14040 (save-excursion
14041 (setq rtn1 (funcall action))
14042 (push rtn1 rtn)))
14043 (t (user-error "Invalid action")))
14045 ;; if we are to skip sublevels, jump to end of subtree
14046 (unless org-tags-match-list-sublevels
14047 (org-end-of-subtree t)
14048 (backward-char 1))))
14049 ;; Get the correct position from where to continue
14050 (if org-map-continue-from
14051 (goto-char org-map-continue-from)
14052 (and (= (point) lspos) (end-of-line 1)))))
14053 (when (and (eq action 'sparse-tree)
14054 (not org-sparse-tree-open-archived-trees))
14055 (org-hide-archived-subtrees (point-min) (point-max)))
14056 (nreverse rtn)))
14058 (defun org-remove-uninherited-tags (tags)
14059 "Remove all tags that are not inherited from the list TAGS."
14060 (cond
14061 ((eq org-use-tag-inheritance t)
14062 (if org-tags-exclude-from-inheritance
14063 (org-delete-all org-tags-exclude-from-inheritance tags)
14064 tags))
14065 ((not org-use-tag-inheritance) nil)
14066 ((stringp org-use-tag-inheritance)
14067 (delq nil (mapcar
14068 (lambda (x)
14069 (if (and (string-match org-use-tag-inheritance x)
14070 (not (member x org-tags-exclude-from-inheritance)))
14071 x nil))
14072 tags)))
14073 ((listp org-use-tag-inheritance)
14074 (delq nil (mapcar
14075 (lambda (x)
14076 (if (member x org-use-tag-inheritance) x nil))
14077 tags)))))
14079 (defun org-match-sparse-tree (&optional todo-only match)
14080 "Create a sparse tree according to tags string MATCH.
14081 MATCH can contain positive and negative selection of tags, like
14082 \"+WORK+URGENT-WITHBOSS\".
14083 If optional argument TODO-ONLY is non-nil, only select lines that are
14084 also TODO lines."
14085 (interactive "P")
14086 (org-agenda-prepare-buffers (list (current-buffer)))
14087 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14089 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14091 (defvar org-cached-props nil)
14092 (defun org-cached-entry-get (pom property)
14093 (if (or (eq t org-use-property-inheritance)
14094 (and (stringp org-use-property-inheritance)
14095 (string-match org-use-property-inheritance property))
14096 (and (listp org-use-property-inheritance)
14097 (member property org-use-property-inheritance)))
14098 ;; Caching is not possible, check it directly
14099 (org-entry-get pom property 'inherit)
14100 ;; Get all properties, so that we can do complicated checks easily
14101 (cdr (assoc property (or org-cached-props
14102 (setq org-cached-props
14103 (org-entry-properties pom)))))))
14105 (defun org-global-tags-completion-table (&optional files)
14106 "Return the list of all tags in all agenda buffer/files.
14107 Optional FILES argument is a list of files which can be used
14108 instead of the agenda files."
14109 (save-excursion
14110 (org-uniquify
14111 (delq nil
14112 (apply 'append
14113 (mapcar
14114 (lambda (file)
14115 (set-buffer (find-file-noselect file))
14116 (append (org-get-buffer-tags)
14117 (mapcar (lambda (x) (if (stringp (car-safe x))
14118 (list (car-safe x)) nil))
14119 org-tag-alist)))
14120 (if (and files (car files))
14121 files
14122 (org-agenda-files))))))))
14124 (defun org-make-tags-matcher (match)
14125 "Create the TAGS/TODO matcher form for the selection string MATCH.
14127 The variable `todo-only' is scoped dynamically into this function.
14128 It will be set to t if the matcher restricts matching to TODO entries,
14129 otherwise will not be touched.
14131 Returns a cons of the selection string MATCH and the constructed
14132 lisp form implementing the matcher. The matcher is to be evaluated
14133 at an Org entry, with point on the headline, and returns t if the
14134 entry matches the selection string MATCH. The returned lisp form
14135 references two variables with information about the entry, which
14136 must be bound around the form's evaluation: todo, the TODO keyword
14137 at the entry (or nil of none); and tags-list, the list of all tags
14138 at the entry including inherited ones. Additionally, the category
14139 of the entry (if any) must be specified as the text property
14140 'org-category on the headline.
14142 See also `org-scan-tags'.
14144 (declare (special todo-only))
14145 (unless (boundp 'todo-only)
14146 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14147 (unless match
14148 ;; Get a new match request, with completion against the global
14149 ;; tags table and the local tags in current buffer
14150 (let ((org-last-tags-completion-table
14151 (org-uniquify
14152 (delq nil (append (org-get-buffer-tags)
14153 (org-global-tags-completion-table))))))
14154 (setq match (org-completing-read-no-i
14155 "Match: " 'org-tags-completion-function nil nil nil
14156 'org-tags-history))))
14158 ;; Parse the string and create a lisp form
14159 (let ((match0 match)
14160 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14161 minus tag mm
14162 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14163 orterms term orlist re-p str-p level-p level-op time-p
14164 prop-p pn pv po gv rest (start 0) (ss 0))
14165 ;; Expand group tags
14166 (setq match (org-tags-expand match))
14168 ;; Check if there is a TODO part of this match, which would be the
14169 ;; part after a "/". TO make sure that this slash is not part of
14170 ;; a property value to be matched against, we also check that there
14171 ;; is no " after that slash.
14172 ;; First, find the last slash
14173 (while (string-match "/+" match ss)
14174 (setq start (match-beginning 0) ss (match-end 0)))
14175 (if (and (string-match "/+" match start)
14176 (not (save-match-data (string-match "\"" match start))))
14177 ;; match contains also a todo-matching request
14178 (progn
14179 (setq tagsmatch (substring match 0 (match-beginning 0))
14180 todomatch (substring match (match-end 0)))
14181 (if (string-match "^!" todomatch)
14182 (setq todo-only t todomatch (substring todomatch 1)))
14183 (if (string-match "^\\s-*$" todomatch)
14184 (setq todomatch nil)))
14185 ;; only matching tags
14186 (setq tagsmatch match todomatch nil))
14188 ;; Make the tags matcher
14189 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14190 (setq tagsmatcher t)
14191 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14192 (while (setq term (pop orterms))
14193 (while (and (equal (substring term -1) "\\") orterms)
14194 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14195 (while (string-match re term)
14196 (setq rest (substring term (match-end 0))
14197 minus (and (match-end 1)
14198 (equal (match-string 1 term) "-"))
14199 tag (save-match-data (replace-regexp-in-string
14200 "\\\\-" "-"
14201 (match-string 2 term)))
14202 re-p (equal (string-to-char tag) ?{)
14203 level-p (match-end 4)
14204 prop-p (match-end 5)
14205 mm (cond
14206 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14207 (level-p
14208 (setq level-op (org-op-to-function (match-string 3 term)))
14209 `(,level-op level ,(string-to-number
14210 (match-string 4 term))))
14211 (prop-p
14212 (setq pn (match-string 5 term)
14213 po (match-string 6 term)
14214 pv (match-string 7 term)
14215 re-p (equal (string-to-char pv) ?{)
14216 str-p (equal (string-to-char pv) ?\")
14217 time-p (save-match-data
14218 (string-match "^\"[[<].*[]>]\"$" pv))
14219 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14220 (if time-p (setq pv (org-matcher-time pv)))
14221 (setq po (org-op-to-function po (if time-p 'time str-p)))
14222 (cond
14223 ((equal pn "CATEGORY")
14224 (setq gv '(get-text-property (point) 'org-category)))
14225 ((equal pn "TODO")
14226 (setq gv 'todo))
14228 (setq gv `(org-cached-entry-get nil ,pn))))
14229 (if re-p
14230 (if (eq po 'org<>)
14231 `(not (string-match ,pv (or ,gv "")))
14232 `(string-match ,pv (or ,gv "")))
14233 (if str-p
14234 `(,po (or ,gv "") ,pv)
14235 `(,po (string-to-number (or ,gv ""))
14236 ,(string-to-number pv) ))))
14237 (t `(member ,tag tags-list)))
14238 mm (if minus (list 'not mm) mm)
14239 term rest)
14240 (push mm tagsmatcher))
14241 (push (if (> (length tagsmatcher) 1)
14242 (cons 'and tagsmatcher)
14243 (car tagsmatcher))
14244 orlist)
14245 (setq tagsmatcher nil))
14246 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14247 (setq tagsmatcher
14248 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14249 ;; Make the todo matcher
14250 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14251 (setq todomatcher t)
14252 (setq orterms (org-split-string todomatch "|") orlist nil)
14253 (while (setq term (pop orterms))
14254 (while (string-match re term)
14255 (setq minus (and (match-end 1)
14256 (equal (match-string 1 term) "-"))
14257 kwd (match-string 2 term)
14258 re-p (equal (string-to-char kwd) ?{)
14259 term (substring term (match-end 0))
14260 mm (if re-p
14261 `(string-match ,(substring kwd 1 -1) todo)
14262 (list 'equal 'todo kwd))
14263 mm (if minus (list 'not mm) mm))
14264 (push mm todomatcher))
14265 (push (if (> (length todomatcher) 1)
14266 (cons 'and todomatcher)
14267 (car todomatcher))
14268 orlist)
14269 (setq todomatcher nil))
14270 (setq todomatcher (if (> (length orlist) 1)
14271 (cons 'or orlist) (car orlist))))
14273 ;; Return the string and lisp forms of the matcher
14274 (setq matcher (if todomatcher
14275 (list 'and tagsmatcher todomatcher)
14276 tagsmatcher))
14277 (when todo-only
14278 (setq matcher (list 'and '(member todo org-not-done-keywords)
14279 matcher)))
14280 (cons match0 matcher)))
14282 (defun org-tags-expand (match &optional single-as-list downcased)
14283 "Expand group tags in MATCH.
14285 This replaces every group tag in MATCH with a regexp tag search.
14286 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14287 will be replaced like this:
14289 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14290 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14291 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14293 Replacing by a regexp preserves the structure of the match.
14294 E.g., this expansion
14296 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14298 will match anything tagged with \"Lab\" and \"Home\", or tagged
14299 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14301 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14302 assumed to be a single group tag, and the function will return
14303 the list of tags in this group.
14305 When DOWNCASE is non-nil, expand downcased TAGS."
14306 (if org-group-tags
14307 (let* ((case-fold-search t)
14308 (stable org-mode-syntax-table)
14309 (tal (or org-tag-groups-alist-for-agenda
14310 org-tag-groups-alist))
14311 (tal (if downcased
14312 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14313 (tml (mapcar 'car tal))
14314 (rtnmatch match) rpl)
14315 ;; @ and _ are allowed as word-components in tags
14316 (modify-syntax-entry ?@ "w" stable)
14317 (modify-syntax-entry ?_ "w" stable)
14318 (while (and tml
14319 (with-syntax-table stable
14320 (string-match
14321 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14322 (regexp-opt tml) "\\>\\)") rtnmatch)))
14323 (let* ((dir (match-string 1 rtnmatch))
14324 (tag (match-string 2 rtnmatch))
14325 (tag (if downcased (downcase tag) tag)))
14326 (setq tml (delete tag tml))
14327 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14328 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14329 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14330 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14331 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14332 (if single-as-list
14333 (or (reverse rpl) (list rtnmatch))
14334 rtnmatch))
14335 (if single-as-list (list (if downcased (downcase match) match))
14336 match)))
14338 (defun org-op-to-function (op &optional stringp)
14339 "Turn an operator into the appropriate function."
14340 (setq op
14341 (cond
14342 ((equal op "<" ) '(< string< org-time<))
14343 ((equal op ">" ) '(> org-string> org-time>))
14344 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14345 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14346 ((member op '("=" "==")) '(= string= org-time=))
14347 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14348 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14350 (defun org<> (a b) (not (= a b)))
14351 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14352 (defun org-string>= (a b) (not (string< a b)))
14353 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14354 (defun org-string<> (a b) (not (string= a b)))
14355 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14356 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14357 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14358 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14359 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14360 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14361 (defun org-2ft (s)
14362 "Convert S to a floating point time.
14363 If S is already a number, just return it. If it is a string, parse
14364 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14365 (cond
14366 ((numberp s) s)
14367 ((stringp s)
14368 (condition-case nil
14369 (float-time (apply 'encode-time (org-parse-time-string s)))
14370 (error 0.)))
14371 (t 0.)))
14373 (defun org-time-today ()
14374 "Time in seconds today at 0:00.
14375 Returns the float number of seconds since the beginning of the
14376 epoch to the beginning of today (00:00)."
14377 (float-time (apply 'encode-time
14378 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14380 (defun org-matcher-time (s)
14381 "Interpret a time comparison value."
14382 (save-match-data
14383 (cond
14384 ((string= s "<now>") (float-time))
14385 ((string= s "<today>") (org-time-today))
14386 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14387 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14388 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14389 (+ (org-time-today)
14390 (* (string-to-number (match-string 1 s))
14391 (cdr (assoc (match-string 2 s)
14392 '(("d" . 86400.0) ("w" . 604800.0)
14393 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14394 (t (org-2ft s)))))
14396 (defun org-match-any-p (re list)
14397 "Does re match any element of list?"
14398 (setq list (mapcar (lambda (x) (string-match re x)) list))
14399 (delq nil list))
14401 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14402 (defvar org-tags-overlay (make-overlay 1 1))
14403 (org-detach-overlay org-tags-overlay)
14405 (defun org-get-local-tags-at (&optional pos)
14406 "Get a list of tags defined in the current headline."
14407 (org-get-tags-at pos 'local))
14409 (defun org-get-local-tags ()
14410 "Get a list of tags defined in the current headline."
14411 (org-get-tags-at nil 'local))
14413 (defun org-get-tags-at (&optional pos local)
14414 "Get a list of all headline tags applicable at POS.
14415 POS defaults to point. If tags are inherited, the list contains
14416 the targets in the same sequence as the headlines appear, i.e.
14417 the tags of the current headline come last.
14418 When LOCAL is non-nil, only return tags from the current headline,
14419 ignore inherited ones."
14420 (interactive)
14421 (if (and org-trust-scanner-tags
14422 (or (not pos) (equal pos (point)))
14423 (not local))
14424 org-scanner-tags
14425 (let (tags ltags lastpos parent)
14426 (save-excursion
14427 (save-restriction
14428 (widen)
14429 (goto-char (or pos (point)))
14430 (save-match-data
14431 (catch 'done
14432 (condition-case nil
14433 (progn
14434 (org-back-to-heading t)
14435 (while (not (equal lastpos (point)))
14436 (setq lastpos (point))
14437 (when (looking-at
14438 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14439 (setq ltags (org-split-string
14440 (org-match-string-no-properties 1) ":"))
14441 (when parent
14442 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14443 (setq tags (append
14444 (if parent
14445 (org-remove-uninherited-tags ltags)
14446 ltags)
14447 tags)))
14448 (or org-use-tag-inheritance (throw 'done t))
14449 (if local (throw 'done t))
14450 (or (org-up-heading-safe) (error nil))
14451 (setq parent t)))
14452 (error nil)))))
14453 (if local
14454 tags
14455 (reverse (delete-dups
14456 (reverse (append
14457 (org-remove-uninherited-tags
14458 org-file-tags) tags)))))))))
14460 (defun org-add-prop-inherited (s)
14461 (add-text-properties 0 (length s) '(inherited t) s)
14464 (defun org-toggle-tag (tag &optional onoff)
14465 "Toggle the tag TAG for the current line.
14466 If ONOFF is `on' or `off', don't toggle but set to this state."
14467 (let (res current)
14468 (save-excursion
14469 (org-back-to-heading t)
14470 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14471 (point-at-eol) t)
14472 (progn
14473 (setq current (match-string 1))
14474 (replace-match ""))
14475 (setq current ""))
14476 (setq current (nreverse (org-split-string current ":")))
14477 (cond
14478 ((eq onoff 'on)
14479 (setq res t)
14480 (or (member tag current) (push tag current)))
14481 ((eq onoff 'off)
14482 (or (not (member tag current)) (setq current (delete tag current))))
14483 (t (if (member tag current)
14484 (setq current (delete tag current))
14485 (setq res t)
14486 (push tag current))))
14487 (end-of-line 1)
14488 (if current
14489 (progn
14490 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14491 (org-set-tags nil t))
14492 (delete-horizontal-space))
14493 (run-hooks 'org-after-tags-change-hook))
14494 res))
14496 (defun org-align-tags-here (to-col)
14497 ;; Assumes that this is a headline
14498 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14499 (beginning-of-line 1)
14500 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14501 (< pos (match-beginning 2)))
14502 (progn
14503 (setq tags-l (- (match-end 2) (match-beginning 2)))
14504 (goto-char (match-beginning 1))
14505 (insert " ")
14506 (delete-region (point) (1+ (match-beginning 2)))
14507 (setq ncol (max (current-column)
14508 (1+ col)
14509 (if (> to-col 0)
14510 to-col
14511 (- (abs to-col) tags-l))))
14512 (setq p (point))
14513 (insert (make-string (- ncol (current-column)) ?\ ))
14514 (setq ncol (current-column))
14515 (when indent-tabs-mode (tabify p (point-at-eol)))
14516 (org-move-to-column (min ncol col) t nil t))
14517 (goto-char pos))))
14519 (defun org-set-tags-command (&optional arg just-align)
14520 "Call the set-tags command for the current entry."
14521 (interactive "P")
14522 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14523 (org-set-tags arg just-align)
14524 (save-excursion
14525 (unless (and (org-region-active-p)
14526 org-loop-over-headlines-in-active-region)
14527 (org-back-to-heading t))
14528 (org-set-tags arg just-align))))
14530 (defun org-set-tags-to (data)
14531 "Set the tags of the current entry to DATA, replacing the current tags.
14532 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14533 If DATA is nil or the empty string, any tags will be removed."
14534 (interactive "sTags: ")
14535 (setq data
14536 (cond
14537 ((eq data nil) "")
14538 ((equal data "") "")
14539 ((stringp data)
14540 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14541 ":"))
14542 ((listp data)
14543 (concat ":" (mapconcat 'identity data ":") ":"))))
14544 (when data
14545 (save-excursion
14546 (org-back-to-heading t)
14547 (when (looking-at org-complex-heading-regexp)
14548 (if (match-end 5)
14549 (progn
14550 (goto-char (match-beginning 5))
14551 (insert data)
14552 (delete-region (point) (point-at-eol))
14553 (org-set-tags nil 'align))
14554 (goto-char (point-at-eol))
14555 (insert " " data)
14556 (org-set-tags nil 'align)))
14557 (beginning-of-line 1)
14558 (if (looking-at ".*?\\([ \t]+\\)$")
14559 (delete-region (match-beginning 1) (match-end 1))))))
14561 (defun org-align-all-tags ()
14562 "Align the tags i all headings."
14563 (interactive)
14564 (save-excursion
14565 (or (ignore-errors (org-back-to-heading t))
14566 (outline-next-heading))
14567 (if (org-at-heading-p)
14568 (org-set-tags t)
14569 (message "No headings"))))
14571 (defvar org-indent-indentation-per-level)
14572 (defun org-set-tags (&optional arg just-align)
14573 "Set the tags for the current headline.
14574 With prefix ARG, realign all tags in headings in the current buffer."
14575 (interactive "P")
14576 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14577 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14578 'region-start-level 'region))
14579 org-loop-over-headlines-in-active-region)
14580 (org-map-entries
14581 ;; We don't use ARG and JUST-ALIGN here these args are not
14582 ;; useful when looping over headlines
14583 `(org-set-tags)
14584 org-loop-over-headlines-in-active-region
14585 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14586 (let* ((re org-outline-regexp-bol)
14587 (current (unless arg (org-get-tags-string)))
14588 (col (current-column))
14589 (org-setting-tags t)
14590 table current-tags inherited-tags ; computed below when needed
14591 tags p0 c0 c1 rpl di tc level)
14592 (if arg
14593 (save-excursion
14594 (goto-char (point-min))
14595 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14596 (while (re-search-forward re nil t)
14597 (org-set-tags nil t)
14598 (end-of-line 1)))
14599 (message "All tags realigned to column %d" org-tags-column))
14600 (if just-align
14601 (setq tags current)
14602 ;; Get a new set of tags from the user
14603 (save-excursion
14604 (setq table (append org-tag-persistent-alist
14605 (or org-tag-alist (org-get-buffer-tags))
14606 (and
14607 org-complete-tags-always-offer-all-agenda-tags
14608 (org-global-tags-completion-table
14609 (org-agenda-files))))
14610 org-last-tags-completion-table table
14611 current-tags (org-split-string current ":")
14612 inherited-tags (nreverse
14613 (nthcdr (length current-tags)
14614 (nreverse (org-get-tags-at))))
14615 tags
14616 (if (or (eq t org-use-fast-tag-selection)
14617 (and org-use-fast-tag-selection
14618 (delq nil (mapcar 'cdr table))))
14619 (org-fast-tag-selection
14620 current-tags inherited-tags table
14621 (if org-fast-tag-selection-include-todo
14622 org-todo-key-alist))
14623 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14624 (org-trim
14625 (org-icompleting-read "Tags: "
14626 'org-tags-completion-function
14627 nil nil current 'org-tags-history))))))
14628 (while (string-match "[-+&]+" tags)
14629 ;; No boolean logic, just a list
14630 (setq tags (replace-match ":" t t tags))))
14632 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14634 (if org-tags-sort-function
14635 (setq tags (mapconcat 'identity
14636 (sort (org-split-string
14637 tags (org-re "[^[:alnum:]_@#%]+"))
14638 org-tags-sort-function) ":")))
14640 (if (string-match "\\`[\t ]*\\'" tags)
14641 (setq tags "")
14642 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14643 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14645 ;; Insert new tags at the correct column
14646 (beginning-of-line 1)
14647 (setq level (or (and (looking-at org-outline-regexp)
14648 (- (match-end 0) (point) 1))
14650 (cond
14651 ((and (equal current "") (equal tags "")))
14652 ((re-search-forward
14653 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14654 (point-at-eol) t)
14655 (if (equal tags "")
14656 (setq rpl "")
14657 (goto-char (match-beginning 0))
14658 (setq c0 (current-column)
14659 ;; compute offset for the case of org-indent-mode active
14660 di (if org-indent-mode
14661 (* (1- org-indent-indentation-per-level) (1- level))
14663 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14664 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14665 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14666 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14667 (replace-match rpl t t)
14668 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14669 tags)
14670 (t (error "Tags alignment failed")))
14671 (org-move-to-column col)
14672 (unless just-align
14673 (run-hooks 'org-after-tags-change-hook))))))
14675 (defun org-change-tag-in-region (beg end tag off)
14676 "Add or remove TAG for each entry in the region.
14677 This works in the agenda, and also in an org-mode buffer."
14678 (interactive
14679 (list (region-beginning) (region-end)
14680 (let ((org-last-tags-completion-table
14681 (if (derived-mode-p 'org-mode)
14682 (org-uniquify
14683 (delq nil (append (org-get-buffer-tags)
14684 (org-global-tags-completion-table))))
14685 (org-global-tags-completion-table))))
14686 (org-icompleting-read
14687 "Tag: " 'org-tags-completion-function nil nil nil
14688 'org-tags-history))
14689 (progn
14690 (message "[s]et or [r]emove? ")
14691 (equal (read-char-exclusive) ?r))))
14692 (if (fboundp 'deactivate-mark) (deactivate-mark))
14693 (let ((agendap (equal major-mode 'org-agenda-mode))
14694 l1 l2 m buf pos newhead (cnt 0))
14695 (goto-char end)
14696 (setq l2 (1- (org-current-line)))
14697 (goto-char beg)
14698 (setq l1 (org-current-line))
14699 (loop for l from l1 to l2 do
14700 (org-goto-line l)
14701 (setq m (get-text-property (point) 'org-hd-marker))
14702 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14703 (and agendap m))
14704 (setq buf (if agendap (marker-buffer m) (current-buffer))
14705 pos (if agendap m (point)))
14706 (with-current-buffer buf
14707 (save-excursion
14708 (save-restriction
14709 (goto-char pos)
14710 (setq cnt (1+ cnt))
14711 (org-toggle-tag tag (if off 'off 'on))
14712 (setq newhead (org-get-heading)))))
14713 (and agendap (org-agenda-change-all-lines newhead m))))
14714 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14716 (defun org-tags-completion-function (string predicate &optional flag)
14717 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14718 (confirm (lambda (x) (stringp (car x)))))
14719 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14720 (setq s1 (match-string 1 string)
14721 s2 (match-string 2 string))
14722 (setq s1 "" s2 string))
14723 (cond
14724 ((eq flag nil)
14725 ;; try completion
14726 (setq rtn (try-completion s2 ctable confirm))
14727 (if (stringp rtn)
14728 (setq rtn
14729 (concat s1 s2 (substring rtn (length s2))
14730 (if (and org-add-colon-after-tag-completion
14731 (assoc rtn ctable))
14732 ":" ""))))
14733 rtn)
14734 ((eq flag t)
14735 ;; all-completions
14736 (all-completions s2 ctable confirm))
14737 ((eq flag 'lambda)
14738 ;; exact match?
14739 (assoc s2 ctable)))))
14741 (defun org-fast-tag-insert (kwd tags face &optional end)
14742 "Insert KDW, and the TAGS, the latter with face FACE.
14743 Also insert END."
14744 (insert (format "%-12s" (concat kwd ":"))
14745 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14746 (or end "")))
14748 (defun org-fast-tag-show-exit (flag)
14749 (save-excursion
14750 (org-goto-line 3)
14751 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14752 (replace-match ""))
14753 (when flag
14754 (end-of-line 1)
14755 (org-move-to-column (- (window-width) 19) t)
14756 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14758 (defun org-set-current-tags-overlay (current prefix)
14759 "Add an overlay to CURRENT tag with PREFIX."
14760 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14761 (if (featurep 'xemacs)
14762 (org-overlay-display org-tags-overlay (concat prefix s)
14763 'secondary-selection)
14764 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14765 (org-overlay-display org-tags-overlay (concat prefix s)))))
14767 (defvar org-last-tag-selection-key nil)
14768 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14769 "Fast tag selection with single keys.
14770 CURRENT is the current list of tags in the headline, INHERITED is the
14771 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14772 possibly with grouping information. TODO-TABLE is a similar table with
14773 TODO keywords, should these have keys assigned to them.
14774 If the keys are nil, a-z are automatically assigned.
14775 Returns the new tags string, or nil to not change the current settings."
14776 (let* ((fulltable (append table todo-table))
14777 (maxlen (apply 'max (mapcar
14778 (lambda (x)
14779 (if (stringp (car x)) (string-width (car x)) 0))
14780 fulltable)))
14781 (buf (current-buffer))
14782 (expert (eq org-fast-tag-selection-single-key 'expert))
14783 (buffer-tags nil)
14784 (fwidth (+ maxlen 3 1 3))
14785 (ncol (/ (- (window-width) 4) fwidth))
14786 (i-face 'org-done)
14787 (c-face 'org-todo)
14788 tg cnt e c char c1 c2 ntable tbl rtn
14789 ov-start ov-end ov-prefix
14790 (exit-after-next org-fast-tag-selection-single-key)
14791 (done-keywords org-done-keywords)
14792 groups ingroup)
14793 (save-excursion
14794 (beginning-of-line 1)
14795 (if (looking-at
14796 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14797 (setq ov-start (match-beginning 1)
14798 ov-end (match-end 1)
14799 ov-prefix "")
14800 (setq ov-start (1- (point-at-eol))
14801 ov-end (1+ ov-start))
14802 (skip-chars-forward "^\n\r")
14803 (setq ov-prefix
14804 (concat
14805 (buffer-substring (1- (point)) (point))
14806 (if (> (current-column) org-tags-column)
14808 (make-string (- org-tags-column (current-column)) ?\ ))))))
14809 (move-overlay org-tags-overlay ov-start ov-end)
14810 (save-window-excursion
14811 (if expert
14812 (set-buffer (get-buffer-create " *Org tags*"))
14813 (delete-other-windows)
14814 (split-window-vertically)
14815 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14816 (erase-buffer)
14817 (org-set-local 'org-done-keywords done-keywords)
14818 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14819 (org-fast-tag-insert "Current" current c-face "\n\n")
14820 (org-fast-tag-show-exit exit-after-next)
14821 (org-set-current-tags-overlay current ov-prefix)
14822 (setq tbl fulltable char ?a cnt 0)
14823 (while (setq e (pop tbl))
14824 (cond
14825 ((equal (car e) :startgroup)
14826 (push '() groups) (setq ingroup t)
14827 (when (not (= cnt 0))
14828 (setq cnt 0)
14829 (insert "\n"))
14830 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14831 ((equal (car e) :endgroup)
14832 (setq ingroup nil cnt 0)
14833 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14834 ((equal e '(:newline))
14835 (when (not (= cnt 0))
14836 (setq cnt 0)
14837 (insert "\n")
14838 (setq e (car tbl))
14839 (while (equal (car tbl) '(:newline))
14840 (insert "\n")
14841 (setq tbl (cdr tbl)))))
14842 ((equal e '(:grouptags)) nil)
14844 (setq tg (copy-sequence (car e)) c2 nil)
14845 (if (cdr e)
14846 (setq c (cdr e))
14847 ;; automatically assign a character.
14848 (setq c1 (string-to-char
14849 (downcase (substring
14850 tg (if (= (string-to-char tg) ?@) 1 0)))))
14851 (if (or (rassoc c1 ntable) (rassoc c1 table))
14852 (while (or (rassoc char ntable) (rassoc char table))
14853 (setq char (1+ char)))
14854 (setq c2 c1))
14855 (setq c (or c2 char)))
14856 (if ingroup (push tg (car groups)))
14857 (setq tg (org-add-props tg nil 'face
14858 (cond
14859 ((not (assoc tg table))
14860 (org-get-todo-face tg))
14861 ((member tg current) c-face)
14862 ((member tg inherited) i-face))))
14863 (if (equal (caar tbl) :grouptags)
14864 (org-add-props tg nil 'face 'org-tag-group))
14865 (if (and (= cnt 0) (not ingroup)) (insert " "))
14866 (insert "[" c "] " tg (make-string
14867 (- fwidth 4 (length tg)) ?\ ))
14868 (push (cons tg c) ntable)
14869 (when (= (setq cnt (1+ cnt)) ncol)
14870 (insert "\n")
14871 (if ingroup (insert " "))
14872 (setq cnt 0)))))
14873 (setq ntable (nreverse ntable))
14874 (insert "\n")
14875 (goto-char (point-min))
14876 (if (not expert) (org-fit-window-to-buffer))
14877 (setq rtn
14878 (catch 'exit
14879 (while t
14880 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14881 (if (not groups) "no " "")
14882 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14883 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14884 (setq org-last-tag-selection-key c)
14885 (cond
14886 ((= c ?\r) (throw 'exit t))
14887 ((= c ?!)
14888 (setq groups (not groups))
14889 (goto-char (point-min))
14890 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14891 ((= c ?\C-c)
14892 (if (not expert)
14893 (org-fast-tag-show-exit
14894 (setq exit-after-next (not exit-after-next)))
14895 (setq expert nil)
14896 (delete-other-windows)
14897 (set-window-buffer (split-window-vertically) " *Org tags*")
14898 (org-switch-to-buffer-other-window " *Org tags*")
14899 (org-fit-window-to-buffer)))
14900 ((or (= c ?\C-g)
14901 (and (= c ?q) (not (rassoc c ntable))))
14902 (org-detach-overlay org-tags-overlay)
14903 (setq quit-flag t))
14904 ((= c ?\ )
14905 (setq current nil)
14906 (if exit-after-next (setq exit-after-next 'now)))
14907 ((= c ?\t)
14908 (condition-case nil
14909 (setq tg (org-icompleting-read
14910 "Tag: "
14911 (or buffer-tags
14912 (with-current-buffer buf
14913 (org-get-buffer-tags)))))
14914 (quit (setq tg "")))
14915 (when (string-match "\\S-" tg)
14916 (add-to-list 'buffer-tags (list tg))
14917 (if (member tg current)
14918 (setq current (delete tg current))
14919 (push tg current)))
14920 (if exit-after-next (setq exit-after-next 'now)))
14921 ((setq e (rassoc c todo-table) tg (car e))
14922 (with-current-buffer buf
14923 (save-excursion (org-todo tg)))
14924 (if exit-after-next (setq exit-after-next 'now)))
14925 ((setq e (rassoc c ntable) tg (car e))
14926 (if (member tg current)
14927 (setq current (delete tg current))
14928 (loop for g in groups do
14929 (if (member tg g)
14930 (mapc (lambda (x)
14931 (setq current (delete x current)))
14932 g)))
14933 (push tg current))
14934 (if exit-after-next (setq exit-after-next 'now))))
14936 ;; Create a sorted list
14937 (setq current
14938 (sort current
14939 (lambda (a b)
14940 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14941 (if (eq exit-after-next 'now) (throw 'exit t))
14942 (goto-char (point-min))
14943 (beginning-of-line 2)
14944 (delete-region (point) (point-at-eol))
14945 (org-fast-tag-insert "Current" current c-face)
14946 (org-set-current-tags-overlay current ov-prefix)
14947 (while (re-search-forward
14948 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14949 (setq tg (match-string 1))
14950 (add-text-properties
14951 (match-beginning 1) (match-end 1)
14952 (list 'face
14953 (cond
14954 ((member tg current) c-face)
14955 ((member tg inherited) i-face)
14956 (t (get-text-property (match-beginning 1) 'face))))))
14957 (goto-char (point-min)))))
14958 (org-detach-overlay org-tags-overlay)
14959 (if rtn
14960 (mapconcat 'identity current ":")
14961 nil))))
14963 (defun org-get-tags-string ()
14964 "Get the TAGS string in the current headline."
14965 (unless (org-at-heading-p t)
14966 (user-error "Not on a heading"))
14967 (save-excursion
14968 (beginning-of-line 1)
14969 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14970 (org-match-string-no-properties 1)
14971 "")))
14973 (defun org-get-tags ()
14974 "Get the list of tags specified in the current headline."
14975 (org-split-string (org-get-tags-string) ":"))
14977 (defun org-get-buffer-tags ()
14978 "Get a table of all tags used in the buffer, for completion."
14979 (let (tags)
14980 (save-excursion
14981 (goto-char (point-min))
14982 (while (re-search-forward
14983 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14984 (when (equal (char-after (point-at-bol 0)) ?*)
14985 (mapc (lambda (x) (add-to-list 'tags x))
14986 (org-split-string (org-match-string-no-properties 1) ":")))))
14987 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14988 (mapcar 'list tags)))
14990 ;;;; The mapping API
14992 (defun org-map-entries (func &optional match scope &rest skip)
14993 "Call FUNC at each headline selected by MATCH in SCOPE.
14995 FUNC is a function or a lisp form. The function will be called without
14996 arguments, with the cursor positioned at the beginning of the headline.
14997 The return values of all calls to the function will be collected and
14998 returned as a list.
15000 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15001 does not need to preserve point. After evaluation, the cursor will be
15002 moved to the end of the line (presumably of the headline of the
15003 processed entry) and search continues from there. Under some
15004 circumstances, this may not produce the wanted results. For example,
15005 if you have removed (e.g. archived) the current (sub)tree it could
15006 mean that the next entry will be skipped entirely. In such cases, you
15007 can specify the position from where search should continue by making
15008 FUNC set the variable `org-map-continue-from' to the desired buffer
15009 position.
15011 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15012 Only headlines that are matched by this query will be considered during
15013 the iteration. When MATCH is nil or t, all headlines will be
15014 visited by the iteration.
15016 SCOPE determines the scope of this command. It can be any of:
15018 nil The current buffer, respecting the restriction if any
15019 tree The subtree started with the entry at point
15020 region The entries within the active region, if any
15021 region-start-level
15022 The entries within the active region, but only those at
15023 the same level than the first one.
15024 file The current buffer, without restriction
15025 file-with-archives
15026 The current buffer, and any archives associated with it
15027 agenda All agenda files
15028 agenda-with-archives
15029 All agenda files with any archive files associated with them
15030 \(file1 file2 ...)
15031 If this is a list, all files in the list will be scanned
15033 The remaining args are treated as settings for the skipping facilities of
15034 the scanner. The following items can be given here:
15036 archive skip trees with the archive tag
15037 comment skip trees with the COMMENT keyword
15038 function or Emacs Lisp form:
15039 will be used as value for `org-agenda-skip-function', so
15040 whenever the function returns a position, FUNC will not be
15041 called for that entry and search will continue from the
15042 position returned
15044 If your function needs to retrieve the tags including inherited tags
15045 at the *current* entry, you can use the value of the variable
15046 `org-scanner-tags' which will be much faster than getting the value
15047 with `org-get-tags-at'. If your function gets properties with
15048 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15049 to t around the call to `org-entry-properties' to get the same speedup.
15050 Note that if your function moves around to retrieve tags and properties at
15051 a *different* entry, you cannot use these techniques."
15052 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15053 (not (org-region-active-p)))
15054 (let* ((org-agenda-archives-mode nil) ; just to make sure
15055 (org-agenda-skip-archived-trees (memq 'archive skip))
15056 (org-agenda-skip-comment-trees (memq 'comment skip))
15057 (org-agenda-skip-function
15058 (car (org-delete-all '(comment archive) skip)))
15059 (org-tags-match-list-sublevels t)
15060 (start-level (eq scope 'region-start-level))
15061 matcher file res
15062 org-todo-keywords-for-agenda
15063 org-done-keywords-for-agenda
15064 org-todo-keyword-alist-for-agenda
15065 org-tag-alist-for-agenda
15066 todo-only)
15068 (cond
15069 ((eq match t) (setq matcher t))
15070 ((eq match nil) (setq matcher t))
15071 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15073 (save-window-excursion
15074 (save-restriction
15075 (cond ((eq scope 'tree)
15076 (org-back-to-heading t)
15077 (org-narrow-to-subtree)
15078 (setq scope nil))
15079 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15080 (org-region-active-p))
15081 ;; If needed, set start-level to a string like "2"
15082 (when start-level
15083 (save-excursion
15084 (goto-char (region-beginning))
15085 (unless (org-at-heading-p) (outline-next-heading))
15086 (setq start-level (org-current-level))))
15087 (narrow-to-region (region-beginning)
15088 (save-excursion
15089 (goto-char (region-end))
15090 (unless (and (bolp) (org-at-heading-p))
15091 (outline-next-heading))
15092 (point)))
15093 (setq scope nil)))
15095 (if (not scope)
15096 (progn
15097 (org-agenda-prepare-buffers
15098 (list (buffer-file-name (current-buffer))))
15099 (setq res (org-scan-tags func matcher todo-only start-level)))
15100 ;; Get the right scope
15101 (cond
15102 ((and scope (listp scope) (symbolp (car scope)))
15103 (setq scope (eval scope)))
15104 ((eq scope 'agenda)
15105 (setq scope (org-agenda-files t)))
15106 ((eq scope 'agenda-with-archives)
15107 (setq scope (org-agenda-files t))
15108 (setq scope (org-add-archive-files scope)))
15109 ((eq scope 'file)
15110 (setq scope (list (buffer-file-name))))
15111 ((eq scope 'file-with-archives)
15112 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15113 (org-agenda-prepare-buffers scope)
15114 (while (setq file (pop scope))
15115 (with-current-buffer (org-find-base-buffer-visiting file)
15116 (save-excursion
15117 (save-restriction
15118 (widen)
15119 (goto-char (point-min))
15120 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15121 res)))
15123 ;;;; Properties
15125 ;;; Setting and retrieving properties
15127 (defconst org-special-properties
15128 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15129 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15130 "The special properties valid in Org-mode.
15132 These are properties that are not defined in the property drawer,
15133 but in some other way.")
15135 (defconst org-default-properties
15136 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15137 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15138 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15139 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15140 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15141 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15142 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15143 "Some properties that are used by Org-mode for various purposes.
15144 Being in this list makes sure that they are offered for completion.")
15146 (defun org-property-action ()
15147 "Do an action on properties."
15148 (interactive)
15149 (let (c)
15150 (org-at-property-p)
15151 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15152 (setq c (read-char-exclusive))
15153 (cond
15154 ((equal c ?s)
15155 (call-interactively 'org-set-property))
15156 ((equal c ?d)
15157 (call-interactively 'org-delete-property))
15158 ((equal c ?D)
15159 (call-interactively 'org-delete-property-globally))
15160 ((equal c ?c)
15161 (call-interactively 'org-compute-property-at-point))
15162 (t (user-error "No such property action %c" c)))))
15164 (defun org-inc-effort ()
15165 "Increment the value of the effort property in the current entry."
15166 (interactive)
15167 (org-set-effort nil t))
15169 (defvar org-clock-effort) ;; Defined in org-clock.el
15170 (defvar org-clock-current-task) ;; Defined in org-clock.el
15171 (defun org-set-effort (&optional value increment)
15172 "Set the effort property of the current entry.
15173 With numerical prefix arg, use the nth allowed value, 0 stands for the
15174 10th allowed value.
15176 When INCREMENT is non-nil, set the property to the next allowed value."
15177 (interactive "P")
15178 (if (equal value 0) (setq value 10))
15179 (let* ((completion-ignore-case t)
15180 (prop org-effort-property)
15181 (cur (org-entry-get nil prop))
15182 (allowed (org-property-get-allowed-values nil prop 'table))
15183 (existing (mapcar 'list (org-property-values prop)))
15184 (heading (nth 4 (org-heading-components)))
15186 (val (cond
15187 ((stringp value) value)
15188 ((and allowed (integerp value))
15189 (or (car (nth (1- value) allowed))
15190 (car (org-last allowed))))
15191 ((and allowed increment)
15192 (or (caadr (member (list cur) allowed))
15193 (user-error "Allowed effort values are not set")))
15194 (allowed
15195 (message "Select 1-9,0, [RET%s]: %s"
15196 (if cur (concat "=" cur) "")
15197 (mapconcat 'car allowed " "))
15198 (setq rpl (read-char-exclusive))
15199 (if (equal rpl ?\r)
15201 (setq rpl (- rpl ?0))
15202 (if (equal rpl 0) (setq rpl 10))
15203 (if (and (> rpl 0) (<= rpl (length allowed)))
15204 (car (nth (1- rpl) allowed))
15205 (org-completing-read "Effort: " allowed nil))))
15207 (let (org-completion-use-ido org-completion-use-iswitchb)
15208 (org-completing-read
15209 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15210 (concat "[" cur "]") "")
15211 ": ")
15212 existing nil nil "" nil cur))))))
15213 (unless (equal (org-entry-get nil prop) val)
15214 (org-entry-put nil prop val))
15215 (save-excursion
15216 (org-back-to-heading t)
15217 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15218 (when (string= heading org-clock-current-task)
15219 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15220 (org-clock-update-mode-line))
15221 (message "%s is now %s" prop val)))
15223 (defun org-at-property-p ()
15224 "Is cursor inside a property drawer?"
15225 (save-excursion
15226 (when (equal 'node-property (car (org-element-at-point)))
15227 (beginning-of-line 1)
15228 (looking-at org-property-re))))
15230 (defun org-get-property-block (&optional beg end force)
15231 "Return the (beg . end) range of the body of the property drawer.
15232 BEG and END are the beginning and end of the current subtree, or of
15233 the part before the first headline. If they are not given, they will
15234 be found. If the drawer does not exist and FORCE is non-nil, create
15235 the drawer."
15236 (catch 'exit
15237 (save-excursion
15238 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15239 (progn (org-back-to-heading t) (point))))
15240 (end (or end (and (not (outline-next-heading)) (point-max))
15241 (point))))
15242 (goto-char beg)
15243 (if (re-search-forward org-property-start-re end t)
15244 (setq beg (1+ (match-end 0)))
15245 (if force
15246 (save-excursion
15247 (org-insert-property-drawer)
15248 (setq end (progn (outline-next-heading) (point))))
15249 (throw 'exit nil))
15250 (goto-char beg)
15251 (if (re-search-forward org-property-start-re end t)
15252 (setq beg (1+ (match-end 0)))))
15253 (if (re-search-forward org-property-end-re end t)
15254 (setq end (match-beginning 0))
15255 (or force (throw 'exit nil))
15256 (goto-char beg)
15257 (setq end beg)
15258 (org-indent-line)
15259 (insert ":END:\n"))
15260 (cons beg end)))))
15262 (defun org-entry-properties (&optional pom which specific)
15263 "Get all properties of the entry at point-or-marker POM.
15264 This includes the TODO keyword, the tags, time strings for deadline,
15265 scheduled, and clocking, and any additional properties defined in the
15266 entry. The return value is an alist, keys may occur multiple times
15267 if the property key was used several times.
15268 POM may also be nil, in which case the current entry is used.
15269 If WHICH is nil or `all', get all properties. If WHICH is
15270 `special' or `standard', only get that subclass. If WHICH
15271 is a string only get exactly this property. SPECIFIC can be a string, the
15272 specific property we are interested in. Specifying it can speed
15273 things up because then unnecessary parsing is avoided."
15274 (setq which (or which 'all))
15275 (org-with-wide-buffer
15276 (org-with-point-at pom
15277 (let ((clockstr (substring org-clock-string 0 -1))
15278 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15279 (case-fold-search nil)
15280 beg end range props sum-props key key1 value string clocksum clocksumt)
15281 (when (and (derived-mode-p 'org-mode)
15282 (ignore-errors (org-back-to-heading t)))
15283 (setq beg (point))
15284 (setq sum-props (get-text-property (point) 'org-summaries))
15285 (setq clocksum (get-text-property (point) :org-clock-minutes)
15286 clocksumt (get-text-property (point) :org-clock-minutes-today))
15287 (outline-next-heading)
15288 (setq end (point))
15289 (when (memq which '(all special))
15290 ;; Get the special properties, like TODO and tags
15291 (goto-char beg)
15292 (when (and (or (not specific) (string= specific "TODO"))
15293 (looking-at org-todo-line-regexp) (match-end 2))
15294 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15295 (when (and (or (not specific) (string= specific "PRIORITY"))
15296 (looking-at org-priority-regexp))
15297 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15298 (when (or (not specific) (string= specific "FILE"))
15299 (push (cons "FILE" buffer-file-name) props))
15300 (when (and (or (not specific) (string= specific "TAGS"))
15301 (setq value (org-get-tags-string))
15302 (string-match "\\S-" value))
15303 (push (cons "TAGS" value) props))
15304 (when (and (or (not specific) (string= specific "ALLTAGS"))
15305 (setq value (org-get-tags-at)))
15306 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15307 ":"))
15308 props))
15309 (when (or (not specific) (string= specific "BLOCKED"))
15310 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15311 (when (or (not specific)
15312 (member specific
15313 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15314 "TIMESTAMP" "TIMESTAMP_IA")))
15315 (catch 'match
15316 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15317 (setq key (if (match-end 1)
15318 (substring (org-match-string-no-properties 1)
15319 0 -1))
15320 string (if (equal key clockstr)
15321 (org-trim
15322 (buffer-substring-no-properties
15323 (match-beginning 3) (goto-char
15324 (point-at-eol))))
15325 (substring (org-match-string-no-properties 3)
15326 1 -1)))
15327 ;; Get the correct property name from the key. This is
15328 ;; necessary if the user has configured time keywords.
15329 (setq key1 (concat key ":"))
15330 (cond
15331 ((not key)
15332 (setq key
15333 (if (= (char-after (match-beginning 3)) ?\[)
15334 "TIMESTAMP_IA" "TIMESTAMP")))
15335 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15336 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15337 ((equal key1 org-closed-string) (setq key "CLOSED"))
15338 ((equal key1 org-clock-string) (setq key "CLOCK")))
15339 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15340 (progn
15341 (push (cons key string) props)
15342 ;; no need to search further if match is found
15343 (throw 'match t))
15344 (when (or (equal key "CLOCK") (not (assoc key props)))
15345 (push (cons key string) props)))))))
15347 (when (memq which '(all standard))
15348 ;; Get the standard properties, like :PROP: ...
15349 (setq range (org-get-property-block beg end))
15350 (when range
15351 (goto-char (car range))
15352 (while (re-search-forward org-property-re
15353 (cdr range) t)
15354 (setq key (org-match-string-no-properties 2)
15355 value (org-trim (or (org-match-string-no-properties 3) "")))
15356 (unless (member key excluded)
15357 (push (cons key (or value "")) props)))))
15358 (if clocksum
15359 (push (cons "CLOCKSUM"
15360 (org-columns-number-to-string (/ (float clocksum) 60.)
15361 'add_times))
15362 props))
15363 (if clocksumt
15364 (push (cons "CLOCKSUM_T"
15365 (org-columns-number-to-string (/ (float clocksumt) 60.)
15366 'add_times))
15367 props))
15368 (unless (assoc "CATEGORY" props)
15369 (push (cons "CATEGORY" (org-get-category)) props))
15370 (append sum-props (nreverse props)))))))
15372 (defun org-entry-get (pom property &optional inherit literal-nil)
15373 "Get value of PROPERTY for entry or content at point-or-marker POM.
15374 If INHERIT is non-nil and the entry does not have the property,
15375 then also check higher levels of the hierarchy.
15376 If INHERIT is the symbol `selective', use inheritance only if the setting
15377 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15378 If the property is present but empty, the return value is the empty string.
15379 If the property is not present at all, nil is returned.
15381 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15382 do not interpret it as the list atom nil. This is used for inheritance
15383 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15384 (org-with-point-at pom
15385 (if (and inherit (if (eq inherit 'selective)
15386 (org-property-inherit-p property)
15388 (org-entry-get-with-inheritance property literal-nil)
15389 (if (member property org-special-properties)
15390 ;; We need a special property. Use `org-entry-properties'
15391 ;; to retrieve it, but specify the wanted property
15392 (cdr (assoc property (org-entry-properties nil 'special property)))
15393 (org-with-wide-buffer
15394 (let ((range (org-get-property-block)))
15395 (when (and range (not (eq (car range) (cdr range))))
15396 (let* ((props
15397 (list (or (assoc property org-file-properties)
15398 (assoc property org-global-properties)
15399 (assoc property org-global-properties-fixed))))
15400 (ap (lambda (key)
15401 (when (re-search-forward
15402 (org-re-property key) (cdr range) t)
15403 (setq props
15404 (org-update-property-plist
15406 (if (match-end 3)
15407 (org-match-string-no-properties 3) "")
15408 props)))))
15409 val)
15410 (goto-char (car range))
15411 (funcall ap property)
15412 (goto-char (car range))
15413 (while (funcall ap (concat property "+")))
15414 (setq val (cdr (assoc property props)))
15415 (when val (if literal-nil val (org-not-nil val)))))))))))
15417 (defun org-property-or-variable-value (var &optional inherit)
15418 "Check if there is a property fixing the value of VAR.
15419 If yes, return this value. If not, return the current value of the variable."
15420 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15421 (if (and prop (stringp prop) (string-match "\\S-" prop))
15422 (read prop)
15423 (symbol-value var))))
15425 (defun org-entry-delete (pom property)
15426 "Delete the property PROPERTY from entry at point-or-marker POM."
15427 (unless (member property org-special-properties)
15428 (org-with-point-at pom
15429 (let ((range (org-get-property-block)))
15430 (if (and range
15431 (goto-char (car range))
15432 (re-search-forward
15433 (org-re-property property)
15434 (cdr range) t))
15435 (progn
15436 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15437 (org-remove-empty-drawer-at (car range))
15439 nil)))))
15441 ;; Multi-values properties are properties that contain multiple values
15442 ;; These values are assumed to be single words, separated by whitespace.
15443 (defun org-entry-add-to-multivalued-property (pom property value)
15444 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15445 (let* ((old (org-entry-get pom property))
15446 (values (and old (org-split-string old "[ \t]"))))
15447 (setq value (org-entry-protect-space value))
15448 (unless (member value values)
15449 (setq values (append values (list value)))
15450 (org-entry-put pom property
15451 (mapconcat 'identity values " ")))))
15453 (defun org-entry-remove-from-multivalued-property (pom property value)
15454 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15455 (let* ((old (org-entry-get pom property))
15456 (values (and old (org-split-string old "[ \t]"))))
15457 (setq value (org-entry-protect-space value))
15458 (when (member value values)
15459 (setq values (delete value values))
15460 (org-entry-put pom property
15461 (mapconcat 'identity values " ")))))
15463 (defun org-entry-member-in-multivalued-property (pom property value)
15464 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15465 (let* ((old (org-entry-get pom property))
15466 (values (and old (org-split-string old "[ \t]"))))
15467 (setq value (org-entry-protect-space value))
15468 (member value values)))
15470 (defun org-entry-get-multivalued-property (pom property)
15471 "Return a list of values in a multivalued property."
15472 (let* ((value (org-entry-get pom property))
15473 (values (and value (org-split-string value "[ \t]"))))
15474 (mapcar 'org-entry-restore-space values)))
15476 (defun org-entry-put-multivalued-property (pom property &rest values)
15477 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15478 VALUES should be a list of strings. Spaces will be protected."
15479 (org-entry-put pom property
15480 (mapconcat 'org-entry-protect-space values " "))
15481 (let* ((value (org-entry-get pom property))
15482 (values (and value (org-split-string value "[ \t]"))))
15483 (mapcar 'org-entry-restore-space values)))
15485 (defun org-entry-protect-space (s)
15486 "Protect spaces and newline in string S."
15487 (while (string-match " " s)
15488 (setq s (replace-match "%20" t t s)))
15489 (while (string-match "\n" s)
15490 (setq s (replace-match "%0A" t t s)))
15493 (defun org-entry-restore-space (s)
15494 "Restore spaces and newline in string S."
15495 (while (string-match "%20" s)
15496 (setq s (replace-match " " t t s)))
15497 (while (string-match "%0A" s)
15498 (setq s (replace-match "\n" t t s)))
15501 (defvar org-entry-property-inherited-from (make-marker)
15502 "Marker pointing to the entry from where a property was inherited.
15503 Each call to `org-entry-get-with-inheritance' will set this marker to the
15504 location of the entry where the inheritance search matched. If there was
15505 no match, the marker will point nowhere.
15506 Note that also `org-entry-get' calls this function, if the INHERIT flag
15507 is set.")
15509 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15510 "Get PROPERTY of entry or content at point, search higher levels if needed.
15511 The search will stop at the first ancestor which has the property defined.
15512 If the value found is \"nil\", return nil to show that the property
15513 should be considered as undefined (this is the meaning of nil here).
15514 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15515 (move-marker org-entry-property-inherited-from nil)
15516 (let (tmp)
15517 (save-excursion
15518 (save-restriction
15519 (widen)
15520 (catch 'ex
15521 (while t
15522 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15523 (or (ignore-errors (org-back-to-heading t))
15524 (goto-char (point-min)))
15525 (move-marker org-entry-property-inherited-from (point))
15526 (throw 'ex tmp))
15527 (or (ignore-errors (org-up-heading-safe))
15528 (throw 'ex nil))))))
15529 (setq tmp (or tmp
15530 (cdr (assoc property org-file-properties))
15531 (cdr (assoc property org-global-properties))
15532 (cdr (assoc property org-global-properties-fixed))))
15533 (if literal-nil tmp (org-not-nil tmp))))
15535 (defvar org-property-changed-functions nil
15536 "Hook called when the value of a property has changed.
15537 Each hook function should accept two arguments, the name of the property
15538 and the new value.")
15540 (defun org-entry-put (pom property value)
15541 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15542 (org-with-point-at pom
15543 (org-back-to-heading t)
15544 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15545 range)
15546 (cond
15547 ((equal property "TODO")
15548 (when (and (stringp value) (string-match "\\S-" value)
15549 (not (member value org-todo-keywords-1)))
15550 (user-error "\"%s\" is not a valid TODO state" value))
15551 (if (or (not value)
15552 (not (string-match "\\S-" value)))
15553 (setq value 'none))
15554 (org-todo value)
15555 (org-set-tags nil 'align))
15556 ((equal property "PRIORITY")
15557 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15558 (string-to-char value) ?\ ))
15559 (org-set-tags nil 'align))
15560 ((equal property "CLOCKSUM")
15561 (if (not (re-search-forward
15562 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15563 (error "Cannot find a clock log")
15564 (goto-char (- (match-end 1) 2))
15565 (cond
15566 ((eq value 'earlier) (org-timestamp-down))
15567 ((eq value 'later) (org-timestamp-up)))
15568 (org-clock-sum-current-item)))
15569 ((equal property "SCHEDULED")
15570 (if (re-search-forward org-scheduled-time-regexp end t)
15571 (cond
15572 ((eq value 'earlier) (org-timestamp-change -1 'day))
15573 ((eq value 'later) (org-timestamp-change 1 'day))
15574 (t (call-interactively 'org-schedule)))
15575 (call-interactively 'org-schedule)))
15576 ((equal property "DEADLINE")
15577 (if (re-search-forward org-deadline-time-regexp end t)
15578 (cond
15579 ((eq value 'earlier) (org-timestamp-change -1 'day))
15580 ((eq value 'later) (org-timestamp-change 1 'day))
15581 (t (call-interactively 'org-deadline)))
15582 (call-interactively 'org-deadline)))
15583 ((member property org-special-properties)
15584 (error "The %s property can not yet be set with `org-entry-put'"
15585 property))
15586 (t ; a non-special property
15587 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15588 (setq range (org-get-property-block beg end 'force))
15589 (goto-char (car range))
15590 (if (re-search-forward
15591 (org-re-property property) (cdr range) t)
15592 (progn
15593 (delete-region (match-beginning 0) (match-end 0))
15594 (goto-char (match-beginning 0)))
15595 (goto-char (cdr range))
15596 (insert "\n")
15597 (backward-char 1)
15598 (org-indent-line))
15599 (insert ":" property ":")
15600 (and value (insert " " value))
15601 (org-indent-line)))))
15602 (run-hook-with-args 'org-property-changed-functions property value)))
15604 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15605 "Get all property keys in the current buffer.
15606 With INCLUDE-SPECIALS, also list the special properties that reflect things
15607 like tags and TODO state.
15608 With INCLUDE-DEFAULTS, also include properties that has special meaning
15609 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15610 and others.
15611 With INCLUDE-COLUMNS, also include property names given in COLUMN
15612 formats in the current buffer."
15613 (let (rtn range cfmt s p)
15614 (save-excursion
15615 (save-restriction
15616 (widen)
15617 (goto-char (point-min))
15618 (while (re-search-forward org-property-start-re nil t)
15619 (setq range (org-get-property-block))
15620 (goto-char (car range))
15621 (while (re-search-forward org-property-re
15622 (cdr range) t)
15623 (add-to-list 'rtn (org-match-string-no-properties 2)))
15624 (outline-next-heading))))
15626 (when include-specials
15627 (setq rtn (append org-special-properties rtn)))
15629 (when include-defaults
15630 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15631 (add-to-list 'rtn org-effort-property))
15633 (when include-columns
15634 (save-excursion
15635 (save-restriction
15636 (widen)
15637 (goto-char (point-min))
15638 (while (re-search-forward
15639 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15640 nil t)
15641 (setq cfmt (match-string 2) s 0)
15642 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15643 cfmt s)
15644 (setq s (match-end 0)
15645 p (match-string 1 cfmt))
15646 (unless (or (equal p "ITEM")
15647 (member p org-special-properties))
15648 (add-to-list 'rtn (match-string 1 cfmt))))))))
15650 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15652 (defun org-property-values (key)
15653 "Return a list of all values of property KEY in the current buffer."
15654 (save-excursion
15655 (save-restriction
15656 (widen)
15657 (goto-char (point-min))
15658 (let ((re (org-re-property key))
15659 values)
15660 (while (re-search-forward re nil t)
15661 (add-to-list 'values (org-trim (match-string 3))))
15662 (delete "" values)))))
15664 (defun org-insert-property-drawer ()
15665 "Insert a property drawer into the current entry."
15666 (org-back-to-heading t)
15667 (looking-at org-outline-regexp)
15668 (let ((indent (if org-adapt-indentation
15669 (- (match-end 0) (match-beginning 0))
15671 (beg (point))
15672 (re (concat "^[ \t]*" org-keyword-time-regexp))
15673 end hiddenp)
15674 (outline-next-heading)
15675 (setq end (point))
15676 (goto-char beg)
15677 (while (re-search-forward re end t))
15678 (setq hiddenp (outline-invisible-p))
15679 (end-of-line 1)
15680 (and (equal (char-after) ?\n) (forward-char 1))
15681 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15682 (if (member (match-string 1) '("CLOCK:" ":END:"))
15683 ;; just skip this line
15684 (beginning-of-line 2)
15685 ;; Drawer start, find the end
15686 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15687 (beginning-of-line 1)))
15688 (org-skip-over-state-notes)
15689 (skip-chars-backward " \t\n\r")
15690 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15691 (forward-char 1))
15692 (goto-char (point-at-eol))
15693 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15694 (beginning-of-line 0)
15695 (org-indent-to-column indent)
15696 (beginning-of-line 2)
15697 (org-indent-to-column indent)
15698 (beginning-of-line 0)
15699 (if hiddenp
15700 (save-excursion
15701 (org-back-to-heading t)
15702 (hide-entry))
15703 (org-flag-drawer t))))
15705 (defun org-insert-drawer (&optional arg drawer)
15706 "Insert a drawer at point.
15708 Optional argument DRAWER, when non-nil, is a string representing
15709 drawer's name. Otherwise, the user is prompted for a name.
15711 If a region is active, insert the drawer around that region
15712 instead.
15714 Point is left between drawer's boundaries."
15715 (interactive "P")
15716 (let* ((drawer (if arg "PROPERTIES"
15717 (or drawer (read-from-minibuffer "Drawer: ")))))
15718 (cond
15719 ;; With C-u, fall back on `org-insert-property-drawer'
15720 (arg (org-insert-property-drawer))
15722 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15723 (user-error "Invalid drawer name"))
15724 ;; With an active region, insert a drawer at point.
15725 ((not (org-region-active-p))
15726 (progn
15727 (unless (bolp) (insert "\n"))
15728 (insert (format ":%s:\n\n:END:\n" drawer))
15729 (forward-line -2)))
15730 ;; Otherwise, insert the drawer at point
15732 (let ((rbeg (region-beginning))
15733 (rend (copy-marker (region-end))))
15734 (unwind-protect
15735 (progn
15736 (goto-char rbeg)
15737 (beginning-of-line)
15738 (when (save-excursion
15739 (re-search-forward org-outline-regexp-bol rend t))
15740 (user-error "Drawers cannot contain headlines"))
15741 ;; Position point at the beginning of the first
15742 ;; non-blank line in region. Insert drawer's opening
15743 ;; there, then indent it.
15744 (org-skip-whitespace)
15745 (beginning-of-line)
15746 (insert ":" drawer ":\n")
15747 (forward-line -1)
15748 (indent-for-tab-command)
15749 ;; Move point to the beginning of the first blank line
15750 ;; after the last non-blank line in region. Insert
15751 ;; drawer's closing, then indent it.
15752 (goto-char rend)
15753 (skip-chars-backward " \r\t\n")
15754 (insert "\n:END:")
15755 (deactivate-mark t)
15756 (indent-for-tab-command)
15757 (unless (eolp) (insert "\n")))
15758 ;; Clear marker, whatever the outcome of insertion is.
15759 (set-marker rend nil)))))))
15761 (defvar org-property-set-functions-alist nil
15762 "Property set function alist.
15763 Each entry should have the following format:
15765 (PROPERTY . READ-FUNCTION)
15767 The read function will be called with the same argument as
15768 `org-completing-read'.")
15770 (defun org-set-property-function (property)
15771 "Get the function that should be used to set PROPERTY.
15772 This is computed according to `org-property-set-functions-alist'."
15773 (or (cdr (assoc property org-property-set-functions-alist))
15774 'org-completing-read))
15776 (defun org-read-property-value (property)
15777 "Read PROPERTY value from user."
15778 (let* ((completion-ignore-case t)
15779 (allowed (org-property-get-allowed-values nil property 'table))
15780 (cur (org-entry-get nil property))
15781 (prompt (concat property " value"
15782 (if (and cur (string-match "\\S-" cur))
15783 (concat " [" cur "]") "") ": "))
15784 (set-function (org-set-property-function property))
15785 (val (if allowed
15786 (funcall set-function prompt allowed nil
15787 (not (get-text-property 0 'org-unrestricted
15788 (caar allowed))))
15789 (let (org-completion-use-ido org-completion-use-iswitchb)
15790 (funcall set-function prompt
15791 (mapcar 'list (org-property-values property))
15792 nil nil "" nil cur)))))
15793 (if (equal val "")
15795 val)))
15797 (defvar org-last-set-property nil)
15798 (defvar org-last-set-property-value nil)
15799 (defun org-read-property-name ()
15800 "Read a property name."
15801 (let* ((completion-ignore-case t)
15802 (keys (org-buffer-property-keys nil t t))
15803 (default-prop (or (save-excursion
15804 (save-match-data
15805 (beginning-of-line)
15806 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15807 (null (string= (match-string 1) "END"))
15808 (match-string 1))))
15809 org-last-set-property))
15810 (property (org-icompleting-read
15811 (concat "Property"
15812 (if default-prop (concat " [" default-prop "]") "")
15813 ": ")
15814 (mapcar 'list keys)
15815 nil nil nil nil
15816 default-prop)))
15817 (if (member property keys)
15818 property
15819 (or (cdr (assoc (downcase property)
15820 (mapcar (lambda (x) (cons (downcase x) x))
15821 keys)))
15822 property))))
15824 (defun org-set-property-and-value (use-last)
15825 "Allow to set [PROPERTY]: [value] direction from prompt.
15826 When use-default, don't even ask, just use the last
15827 \"[PROPERTY]: [value]\" string from the history."
15828 (interactive "P")
15829 (let* ((completion-ignore-case t)
15830 (pv (or (and use-last org-last-set-property-value)
15831 (org-completing-read
15832 "Enter a \"[Property]: [value]\" pair: "
15833 nil nil nil nil nil
15834 org-last-set-property-value)))
15835 prop val)
15836 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15837 (setq prop (match-string 1 pv)
15838 val (match-string 2 pv))
15839 (org-set-property prop val))))
15841 (defun org-set-property (property value)
15842 "In the current entry, set PROPERTY to VALUE.
15843 When called interactively, this will prompt for a property name, offering
15844 completion on existing and default properties. And then it will prompt
15845 for a value, offering completion either on allowed values (via an inherited
15846 xxx_ALL property) or on existing values in other instances of this property
15847 in the current file."
15848 (interactive (list nil nil))
15849 (let* ((property (or property (org-read-property-name)))
15850 (value (or value (org-read-property-value property)))
15851 (fn (cdr (assoc property org-properties-postprocess-alist))))
15852 (setq org-last-set-property property)
15853 (setq org-last-set-property-value (concat property ": " value))
15854 ;; Possibly postprocess the inserted value:
15855 (when fn (setq value (funcall fn value)))
15856 (unless (equal (org-entry-get nil property) value)
15857 (org-entry-put nil property value))))
15859 (defun org-delete-property (property)
15860 "In the current entry, delete PROPERTY."
15861 (interactive
15862 (let* ((completion-ignore-case t)
15863 (prop (org-icompleting-read "Property: "
15864 (org-entry-properties nil 'standard))))
15865 (list prop)))
15866 (message "Property %s %s" property
15867 (if (org-entry-delete nil property)
15868 "deleted"
15869 "was not present in the entry")))
15871 (defun org-delete-property-globally (property)
15872 "Remove PROPERTY globally, from all entries."
15873 (interactive
15874 (let* ((completion-ignore-case t)
15875 (prop (org-icompleting-read
15876 "Globally remove property: "
15877 (mapcar 'list (org-buffer-property-keys)))))
15878 (list prop)))
15879 (save-excursion
15880 (save-restriction
15881 (widen)
15882 (goto-char (point-min))
15883 (let ((cnt 0))
15884 (while (re-search-forward
15885 (org-re-property property)
15886 nil t)
15887 (setq cnt (1+ cnt))
15888 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15889 (message "Property \"%s\" removed from %d entries" property cnt)))))
15891 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15893 (defun org-compute-property-at-point ()
15894 "Compute the property at point.
15895 This looks for an enclosing column format, extracts the operator and
15896 then applies it to the property in the column format's scope."
15897 (interactive)
15898 (unless (org-at-property-p)
15899 (user-error "Not at a property"))
15900 (let ((prop (org-match-string-no-properties 2)))
15901 (org-columns-get-format-and-top-level)
15902 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15903 (user-error "No operator defined for property %s" prop))
15904 (org-columns-compute prop)))
15906 (defvar org-property-allowed-value-functions nil
15907 "Hook for functions supplying allowed values for a specific property.
15908 The functions must take a single argument, the name of the property, and
15909 return a flat list of allowed values. If \":ETC\" is one of
15910 the values, this means that these values are intended as defaults for
15911 completion, but that other values should be allowed too.
15912 The functions must return nil if they are not responsible for this
15913 property.")
15915 (defun org-property-get-allowed-values (pom property &optional table)
15916 "Get allowed values for the property PROPERTY.
15917 When TABLE is non-nil, return an alist that can directly be used for
15918 completion."
15919 (let (vals)
15920 (cond
15921 ((equal property "TODO")
15922 (setq vals (org-with-point-at pom
15923 (append org-todo-keywords-1 '("")))))
15924 ((equal property "PRIORITY")
15925 (let ((n org-lowest-priority))
15926 (while (>= n org-highest-priority)
15927 (push (char-to-string n) vals)
15928 (setq n (1- n)))))
15929 ((member property org-special-properties))
15930 ((setq vals (run-hook-with-args-until-success
15931 'org-property-allowed-value-functions property)))
15933 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15934 (when (and vals (string-match "\\S-" vals))
15935 (setq vals (car (read-from-string (concat "(" vals ")"))))
15936 (setq vals (mapcar (lambda (x)
15937 (cond ((stringp x) x)
15938 ((numberp x) (number-to-string x))
15939 ((symbolp x) (symbol-name x))
15940 (t "???")))
15941 vals)))))
15942 (when (member ":ETC" vals)
15943 (setq vals (remove ":ETC" vals))
15944 (org-add-props (car vals) '(org-unrestricted t)))
15945 (if table (mapcar 'list vals) vals)))
15947 (defun org-property-previous-allowed-value (&optional previous)
15948 "Switch to the next allowed value for this property."
15949 (interactive)
15950 (org-property-next-allowed-value t))
15952 (defun org-property-next-allowed-value (&optional previous)
15953 "Switch to the next allowed value for this property."
15954 (interactive)
15955 (unless (org-at-property-p)
15956 (user-error "Not at a property"))
15957 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15958 (key (match-string 2))
15959 (value (match-string 3))
15960 (allowed (or (org-property-get-allowed-values (point) key)
15961 (and (member value '("[ ]" "[-]" "[X]"))
15962 '("[ ]" "[X]"))))
15963 (heading (save-match-data (nth 4 (org-heading-components))))
15964 nval)
15965 (unless allowed
15966 (user-error "Allowed values for this property have not been defined"))
15967 (if previous (setq allowed (reverse allowed)))
15968 (if (member value allowed)
15969 (setq nval (car (cdr (member value allowed)))))
15970 (setq nval (or nval (car allowed)))
15971 (if (equal nval value)
15972 (user-error "Only one allowed value for this property"))
15973 (org-at-property-p)
15974 (replace-match (concat " :" key ": " nval) t t)
15975 (org-indent-line)
15976 (beginning-of-line 1)
15977 (skip-chars-forward " \t")
15978 (when (equal prop org-effort-property)
15979 (save-excursion
15980 (org-back-to-heading t)
15981 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15982 (when (string= org-clock-current-task heading)
15983 (setq org-clock-effort nval)
15984 (org-clock-update-mode-line)))
15985 (run-hook-with-args 'org-property-changed-functions key nval)))
15987 (defun org-find-olp (path &optional this-buffer)
15988 "Return a marker pointing to the entry at outline path OLP.
15989 If anything goes wrong, throw an error.
15990 You can wrap this call to catch the error like this:
15992 (condition-case msg
15993 (org-mobile-locate-entry (match-string 4))
15994 (error (nth 1 msg)))
15996 The return value will then be either a string with the error message,
15997 or a marker if everything is OK.
15999 If THIS-BUFFER is set, the outline path does not contain a file,
16000 only headings."
16001 (let* ((file (if this-buffer buffer-file-name (pop path)))
16002 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16003 (level 1)
16004 (lmin 1)
16005 (lmax 1)
16006 limit re end found pos heading cnt flevel)
16007 (unless buffer (error "File not found :%s" file))
16008 (with-current-buffer buffer
16009 (save-excursion
16010 (save-restriction
16011 (widen)
16012 (setq limit (point-max))
16013 (goto-char (point-min))
16014 (while (setq heading (pop path))
16015 (setq re (format org-complex-heading-regexp-format
16016 (regexp-quote heading)))
16017 (setq cnt 0 pos (point))
16018 (while (re-search-forward re end t)
16019 (setq level (- (match-end 1) (match-beginning 1)))
16020 (if (and (>= level lmin) (<= level lmax))
16021 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16022 (when (= cnt 0) (error "Heading not found on level %d: %s"
16023 lmax heading))
16024 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16025 lmax heading))
16026 (goto-char found)
16027 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16028 (setq end (save-excursion (org-end-of-subtree t t))))
16029 (when (org-at-heading-p)
16030 (point-marker)))))))
16032 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16033 "Find node HEADING in BUFFER.
16034 Return a marker to the heading if it was found, or nil if not.
16035 If POS-ONLY is set, return just the position instead of a marker.
16037 The heading text must match exact, but it may have a TODO keyword,
16038 a priority cookie and tags in the standard locations."
16039 (with-current-buffer (or buffer (current-buffer))
16040 (save-excursion
16041 (save-restriction
16042 (widen)
16043 (goto-char (point-min))
16044 (let (case-fold-search)
16045 (if (re-search-forward
16046 (format org-complex-heading-regexp-format
16047 (regexp-quote heading)) nil t)
16048 (if pos-only
16049 (match-beginning 0)
16050 (move-marker (make-marker) (match-beginning 0)))))))))
16052 (defun org-find-exact-heading-in-directory (heading &optional dir)
16053 "Find Org node headline HEADING in all .org files in directory DIR.
16054 When the target headline is found, return a marker to this location."
16055 (let ((files (directory-files (or dir default-directory)
16056 nil "\\`[^.#].*\\.org\\'"))
16057 file visiting m buffer)
16058 (catch 'found
16059 (while (setq file (pop files))
16060 (message "trying %s" file)
16061 (setq visiting (org-find-base-buffer-visiting file))
16062 (setq buffer (or visiting (find-file-noselect file)))
16063 (setq m (org-find-exact-headline-in-buffer
16064 heading buffer))
16065 (when (and (not m) (not visiting)) (kill-buffer buffer))
16066 (and m (throw 'found m))))))
16068 (defun org-find-entry-with-id (ident)
16069 "Locate the entry that contains the ID property with exact value IDENT.
16070 IDENT can be a string, a symbol or a number, this function will search for
16071 the string representation of it.
16072 Return the position where this entry starts, or nil if there is no such entry."
16073 (interactive "sID: ")
16074 (let ((id (cond
16075 ((stringp ident) ident)
16076 ((symbol-name ident) (symbol-name ident))
16077 ((numberp ident) (number-to-string ident))
16078 (t (error "IDENT %s must be a string, symbol or number" ident))))
16079 (case-fold-search nil))
16080 (save-excursion
16081 (save-restriction
16082 (widen)
16083 (goto-char (point-min))
16084 (when (re-search-forward
16085 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16086 nil t)
16087 (org-back-to-heading t)
16088 (point))))))
16090 ;;;; Timestamps
16092 (defvar org-last-changed-timestamp nil)
16093 (defvar org-last-inserted-timestamp nil
16094 "The last time stamp inserted with `org-insert-time-stamp'.")
16095 (defvar org-ts-what) ; dynamically scoped parameter
16097 (defun org-time-stamp (arg &optional inactive)
16098 "Prompt for a date/time and insert a time stamp.
16099 If the user specifies a time like HH:MM or if this command is
16100 called with at least one prefix argument, the time stamp contains
16101 the date and the time. Otherwise, only the date is be included.
16103 All parts of a date not specified by the user is filled in from
16104 the current date/time. So if you just press return without
16105 typing anything, the time stamp will represent the current
16106 date/time.
16108 If there is already a timestamp at the cursor, it will be
16109 modified.
16111 With two universal prefix arguments, insert an active timestamp
16112 with the current time without prompting the user.
16114 When called from lisp, the timestamp is inactive if INACTIVE is
16115 non-nil."
16116 (interactive "P")
16117 (let* ((ts nil)
16118 (default-time
16119 ;; Default time is either today, or, when entering a range,
16120 ;; the range start.
16121 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16122 (save-excursion
16123 (re-search-backward
16124 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16125 (- (point) 20) t)))
16126 (apply 'encode-time (org-parse-time-string (match-string 1)))
16127 (current-time)))
16128 (default-input (and ts (org-get-compact-tod ts)))
16129 (repeater (save-excursion
16130 (save-match-data
16131 (beginning-of-line)
16132 (when (re-search-forward
16133 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16134 (save-excursion (progn (end-of-line) (point))) t)
16135 (match-string 0)))))
16136 org-time-was-given org-end-time-was-given time)
16137 (cond
16138 ((and (org-at-timestamp-p t)
16139 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16140 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16141 (insert "--")
16142 (setq time (let ((this-command this-command))
16143 (org-read-date arg 'totime nil nil
16144 default-time default-input inactive)))
16145 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16146 ((org-at-timestamp-p t)
16147 (setq time (let ((this-command this-command))
16148 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16149 (when (org-at-timestamp-p t) ; just to get the match data
16150 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16151 (replace-match "")
16152 (setq org-last-changed-timestamp
16153 (org-insert-time-stamp
16154 time (or org-time-was-given arg)
16155 inactive nil nil (list org-end-time-was-given)))
16156 (when repeater (goto-char (1- (point))) (insert " " repeater)
16157 (setq org-last-changed-timestamp
16158 (concat (substring org-last-inserted-timestamp 0 -1)
16159 " " repeater ">"))))
16160 (message "Timestamp updated"))
16161 ((equal arg '(16))
16162 (org-insert-time-stamp (current-time) t inactive))
16164 (setq time (let ((this-command this-command))
16165 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16166 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16167 nil nil (list org-end-time-was-given))))))
16169 ;; FIXME: can we use this for something else, like computing time differences?
16170 (defun org-get-compact-tod (s)
16171 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16172 (let* ((t1 (match-string 1 s))
16173 (h1 (string-to-number (match-string 2 s)))
16174 (m1 (string-to-number (match-string 3 s)))
16175 (t2 (and (match-end 4) (match-string 5 s)))
16176 (h2 (and t2 (string-to-number (match-string 6 s))))
16177 (m2 (and t2 (string-to-number (match-string 7 s))))
16178 dh dm)
16179 (if (not t2)
16181 (setq dh (- h2 h1) dm (- m2 m1))
16182 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16183 (concat t1 "+" (number-to-string dh)
16184 (and (/= 0 dm) (format ":%02d" dm)))))))
16186 (defun org-time-stamp-inactive (&optional arg)
16187 "Insert an inactive time stamp.
16188 An inactive time stamp is enclosed in square brackets instead of angle
16189 brackets. It is inactive in the sense that it does not trigger agenda entries,
16190 does not link to the calendar and cannot be changed with the S-cursor keys.
16191 So these are more for recording a certain time/date."
16192 (interactive "P")
16193 (org-time-stamp arg 'inactive))
16195 (defvar org-date-ovl (make-overlay 1 1))
16196 (overlay-put org-date-ovl 'face 'org-date-selected)
16197 (org-detach-overlay org-date-ovl)
16199 (defvar org-ans1) ; dynamically scoped parameter
16200 (defvar org-ans2) ; dynamically scoped parameter
16202 (defvar org-plain-time-of-day-regexp) ; defined below
16204 (defvar org-overriding-default-time nil) ; dynamically scoped
16205 (defvar org-read-date-overlay nil)
16206 (defvar org-dcst nil) ; dynamically scoped
16207 (defvar org-read-date-history nil)
16208 (defvar org-read-date-final-answer nil)
16209 (defvar org-read-date-analyze-futurep nil)
16210 (defvar org-read-date-analyze-forced-year nil)
16211 (defvar org-read-date-inactive)
16213 (defvar org-read-date-minibuffer-local-map
16214 (let* ((org-replace-disputed-keys nil)
16215 (map (make-sparse-keymap)))
16216 (set-keymap-parent map minibuffer-local-map)
16217 (org-defkey map (kbd ".")
16218 (lambda () (interactive)
16219 ;; Are we at the beginning of the prompt?
16220 (if (looking-back "^[^:]+: ")
16221 (org-eval-in-calendar '(calendar-goto-today))
16222 (insert "."))))
16223 (org-defkey map (kbd "C-.")
16224 (lambda () (interactive)
16225 (org-eval-in-calendar '(calendar-goto-today))))
16226 (org-defkey map [(meta shift left)]
16227 (lambda () (interactive)
16228 (org-eval-in-calendar '(calendar-backward-month 1))))
16229 (org-defkey map [(meta shift right)]
16230 (lambda () (interactive)
16231 (org-eval-in-calendar '(calendar-forward-month 1))))
16232 (org-defkey map [(meta shift up)]
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-backward-year 1))))
16235 (org-defkey map [(meta shift down)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-forward-year 1))))
16238 (org-defkey map [?\e (shift left)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-backward-month 1))))
16241 (org-defkey map [?\e (shift right)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-forward-month 1))))
16244 (org-defkey map [?\e (shift up)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-backward-year 1))))
16247 (org-defkey map [?\e (shift down)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-forward-year 1))))
16250 (org-defkey map [(shift up)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-backward-week 1))))
16253 (org-defkey map [(shift down)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-forward-week 1))))
16256 (org-defkey map [(shift left)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-backward-day 1))))
16259 (org-defkey map [(shift right)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-forward-day 1))))
16262 (org-defkey map "!"
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(diary-view-entries))
16265 (message "")))
16266 (org-defkey map ">"
16267 (lambda () (interactive)
16268 (org-eval-in-calendar '(scroll-calendar-left 1))))
16269 (org-defkey map "<"
16270 (lambda () (interactive)
16271 (org-eval-in-calendar '(scroll-calendar-right 1))))
16272 (org-defkey map "\C-v"
16273 (lambda () (interactive)
16274 (org-eval-in-calendar
16275 '(calendar-scroll-left-three-months 1))))
16276 (org-defkey map "\M-v"
16277 (lambda () (interactive)
16278 (org-eval-in-calendar
16279 '(calendar-scroll-right-three-months 1))))
16280 map)
16281 "Keymap for minibuffer commands when using `org-read-date'.")
16283 (defvar org-def)
16284 (defvar org-defdecode)
16285 (defvar org-with-time)
16287 (defun org-read-date (&optional org-with-time to-time from-string prompt
16288 default-time default-input inactive)
16289 "Read a date, possibly a time, and make things smooth for the user.
16290 The prompt will suggest to enter an ISO date, but you can also enter anything
16291 which will at least partially be understood by `parse-time-string'.
16292 Unrecognized parts of the date will default to the current day, month, year,
16293 hour and minute. If this command is called to replace a timestamp at point,
16294 or to enter the second timestamp of a range, the default time is taken
16295 from the existing stamp. Furthermore, the command prefers the future,
16296 so if you are giving a date where the year is not given, and the day-month
16297 combination is already past in the current year, it will assume you
16298 mean next year. For details, see the manual. A few examples:
16300 3-2-5 --> 2003-02-05
16301 feb 15 --> currentyear-02-15
16302 2/15 --> currentyear-02-15
16303 sep 12 9 --> 2009-09-12
16304 12:45 --> today 12:45
16305 22 sept 0:34 --> currentyear-09-22 0:34
16306 12 --> currentyear-currentmonth-12
16307 Fri --> nearest Friday after today
16308 -Tue --> last Tuesday
16309 etc.
16311 Furthermore you can specify a relative date by giving, as the *first* thing
16312 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16313 change in days weeks, months, years.
16314 With a single plus or minus, the date is relative to today. With a double
16315 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16316 +4d --> four days from today
16317 +4 --> same as above
16318 +2w --> two weeks from today
16319 ++5 --> five days from default date
16321 The function understands only English month and weekday abbreviations.
16323 While prompting, a calendar is popped up - you can also select the
16324 date with the mouse (button 1). The calendar shows a period of three
16325 months. To scroll it to other months, use the keys `>' and `<'.
16326 If you don't like the calendar, turn it off with
16327 \(setq org-read-date-popup-calendar nil)
16329 With optional argument TO-TIME, the date will immediately be converted
16330 to an internal time.
16331 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16332 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16333 still enter a time, and this function will inform the calling routine
16334 about this change. The calling routine may then choose to change the
16335 format used to insert the time stamp into the buffer to include the time.
16336 With optional argument FROM-STRING, read from this string instead from
16337 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16338 the time/date that is used for everything that is not specified by the
16339 user."
16340 (require 'parse-time)
16341 (let* ((org-time-stamp-rounding-minutes
16342 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16343 (org-dcst org-display-custom-times)
16344 (ct (org-current-time))
16345 (org-def (or org-overriding-default-time default-time ct))
16346 (org-defdecode (decode-time org-def))
16347 (dummy (progn
16348 (when (< (nth 2 org-defdecode) org-extend-today-until)
16349 (setcar (nthcdr 2 org-defdecode) -1)
16350 (setcar (nthcdr 1 org-defdecode) 59)
16351 (setq org-def (apply 'encode-time org-defdecode)
16352 org-defdecode (decode-time org-def)))))
16353 (mouse-autoselect-window nil) ; Don't let the mouse jump
16354 (calendar-frame-setup nil)
16355 (calendar-setup nil)
16356 (calendar-move-hook nil)
16357 (calendar-view-diary-initially-flag nil)
16358 (calendar-view-holidays-initially-flag nil)
16359 (timestr (format-time-string
16360 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16361 (prompt (concat (if prompt (concat prompt " ") "")
16362 (format "Date+time [%s]: " timestr)))
16363 ans (org-ans0 "") org-ans1 org-ans2 final)
16365 (cond
16366 (from-string (setq ans from-string))
16367 (org-read-date-popup-calendar
16368 (save-excursion
16369 (save-window-excursion
16370 (calendar)
16371 (org-eval-in-calendar '(setq cursor-type nil) t)
16372 (unwind-protect
16373 (progn
16374 (calendar-forward-day (- (time-to-days org-def)
16375 (calendar-absolute-from-gregorian
16376 (calendar-current-date))))
16377 (org-eval-in-calendar nil t)
16378 (let* ((old-map (current-local-map))
16379 (map (copy-keymap calendar-mode-map))
16380 (minibuffer-local-map
16381 (copy-keymap org-read-date-minibuffer-local-map)))
16382 (org-defkey map (kbd "RET") 'org-calendar-select)
16383 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16384 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16385 (unwind-protect
16386 (progn
16387 (use-local-map map)
16388 (setq org-read-date-inactive inactive)
16389 (add-hook 'post-command-hook 'org-read-date-display)
16390 (setq org-ans0 (read-string prompt default-input
16391 'org-read-date-history nil))
16392 ;; org-ans0: from prompt
16393 ;; org-ans1: from mouse click
16394 ;; org-ans2: from calendar motion
16395 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16396 (remove-hook 'post-command-hook 'org-read-date-display)
16397 (use-local-map old-map)
16398 (when org-read-date-overlay
16399 (delete-overlay org-read-date-overlay)
16400 (setq org-read-date-overlay nil)))))
16401 (bury-buffer "*Calendar*")))))
16403 (t ; Naked prompt only
16404 (unwind-protect
16405 (setq ans (read-string prompt default-input
16406 'org-read-date-history timestr))
16407 (when org-read-date-overlay
16408 (delete-overlay org-read-date-overlay)
16409 (setq org-read-date-overlay nil)))))
16411 (setq final (org-read-date-analyze ans org-def org-defdecode))
16413 (when org-read-date-analyze-forced-year
16414 (message "Year was forced into %s"
16415 (if org-read-date-force-compatible-dates
16416 "compatible range (1970-2037)"
16417 "range representable on this machine"))
16418 (ding))
16420 ;; One round trip to get rid of 34th of August and stuff like that....
16421 (setq final (decode-time (apply 'encode-time final)))
16423 (setq org-read-date-final-answer ans)
16425 (if to-time
16426 (apply 'encode-time final)
16427 (if (and (boundp 'org-time-was-given) org-time-was-given)
16428 (format "%04d-%02d-%02d %02d:%02d"
16429 (nth 5 final) (nth 4 final) (nth 3 final)
16430 (nth 2 final) (nth 1 final))
16431 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16433 (defun org-read-date-display ()
16434 "Display the current date prompt interpretation in the minibuffer."
16435 (when org-read-date-display-live
16436 (when org-read-date-overlay
16437 (delete-overlay org-read-date-overlay))
16438 (when (minibufferp (current-buffer))
16439 (save-excursion
16440 (end-of-line 1)
16441 (while (not (equal (buffer-substring
16442 (max (point-min) (- (point) 4)) (point))
16443 " "))
16444 (insert " ")))
16445 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16446 " " (or org-ans1 org-ans2)))
16447 (org-end-time-was-given nil)
16448 (f (org-read-date-analyze ans org-def org-defdecode))
16449 (fmts (if org-dcst
16450 org-time-stamp-custom-formats
16451 org-time-stamp-formats))
16452 (fmt (if (or org-with-time
16453 (and (boundp 'org-time-was-given) org-time-was-given))
16454 (cdr fmts)
16455 (car fmts)))
16456 (txt (format-time-string fmt (apply 'encode-time f)))
16457 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16458 (txt (concat "=> " txt)))
16459 (when (and org-end-time-was-given
16460 (string-match org-plain-time-of-day-regexp txt))
16461 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16462 org-end-time-was-given
16463 (substring txt (match-end 0)))))
16464 (when org-read-date-analyze-futurep
16465 (setq txt (concat txt " (=>F)")))
16466 (setq org-read-date-overlay
16467 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16468 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16470 (defun org-read-date-analyze (ans org-def org-defdecode)
16471 "Analyze the combined answer of the date prompt."
16472 ;; FIXME: cleanup and comment
16473 (let ((nowdecode (decode-time (current-time)))
16474 delta deltan deltaw deltadef year month day
16475 hour minute second wday pm h2 m2 tl wday1
16476 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16477 (setq org-read-date-analyze-futurep nil
16478 org-read-date-analyze-forced-year nil)
16479 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16480 (setq ans "+0"))
16482 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16483 (setq ans (replace-match "" t t ans)
16484 deltan (car delta)
16485 deltaw (nth 1 delta)
16486 deltadef (nth 2 delta)))
16488 ;; Check if there is an iso week date in there. If yes, store the
16489 ;; info and postpone interpreting it until the rest of the parsing
16490 ;; is done.
16491 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16492 (setq iso-year (if (match-end 1)
16493 (org-small-year-to-year
16494 (string-to-number (match-string 1 ans))))
16495 iso-weekday (if (match-end 3)
16496 (string-to-number (match-string 3 ans)))
16497 iso-week (string-to-number (match-string 2 ans)))
16498 (setq ans (replace-match "" t t ans)))
16500 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16501 (when (string-match
16502 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16503 (setq year (if (match-end 2)
16504 (string-to-number (match-string 2 ans))
16505 (progn (setq kill-year t)
16506 (string-to-number (format-time-string "%Y"))))
16507 month (string-to-number (match-string 3 ans))
16508 day (string-to-number (match-string 4 ans)))
16509 (if (< year 100) (setq year (+ 2000 year)))
16510 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16511 t nil ans)))
16513 ;; Help matching dotted european dates
16514 (when (string-match
16515 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16516 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16517 (setq kill-year t)
16518 (string-to-number (format-time-string "%Y")))
16519 day (string-to-number (match-string 1 ans))
16520 month (string-to-number (match-string 2 ans))
16521 ans (replace-match (format "%04d-%02d-%02d" year month day)
16522 t nil ans)))
16524 ;; Help matching american dates, like 5/30 or 5/30/7
16525 (when (string-match
16526 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16527 (setq year (if (match-end 4)
16528 (string-to-number (match-string 4 ans))
16529 (progn (setq kill-year t)
16530 (string-to-number (format-time-string "%Y"))))
16531 month (string-to-number (match-string 1 ans))
16532 day (string-to-number (match-string 2 ans)))
16533 (if (< year 100) (setq year (+ 2000 year)))
16534 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16535 t nil ans)))
16536 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16537 ;; If there is a time with am/pm, and *no* time without it, we convert
16538 ;; so that matching will be successful.
16539 (loop for i from 1 to 2 do ; twice, for end time as well
16540 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16541 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16542 (setq hour (string-to-number (match-string 1 ans))
16543 minute (if (match-end 3)
16544 (string-to-number (match-string 3 ans))
16546 pm (equal ?p
16547 (string-to-char (downcase (match-string 4 ans)))))
16548 (if (and (= hour 12) (not pm))
16549 (setq hour 0)
16550 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16551 (setq ans (replace-match (format "%02d:%02d" hour minute)
16552 t t ans))))
16554 ;; Check if a time range is given as a duration
16555 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16556 (setq hour (string-to-number (match-string 1 ans))
16557 h2 (+ hour (string-to-number (match-string 3 ans)))
16558 minute (string-to-number (match-string 2 ans))
16559 m2 (+ minute (if (match-end 5) (string-to-number
16560 (match-string 5 ans))0)))
16561 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16562 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16563 t t ans)))
16565 ;; Check if there is a time range
16566 (when (boundp 'org-end-time-was-given)
16567 (setq org-time-was-given nil)
16568 (when (and (string-match org-plain-time-of-day-regexp ans)
16569 (match-end 8))
16570 (setq org-end-time-was-given (match-string 8 ans))
16571 (setq ans (concat (substring ans 0 (match-beginning 7))
16572 (substring ans (match-end 7))))))
16574 (setq tl (parse-time-string ans)
16575 day (or (nth 3 tl) (nth 3 org-defdecode))
16576 month (or (nth 4 tl)
16577 (if (and org-read-date-prefer-future
16578 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16579 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16580 (nth 4 org-defdecode)))
16581 year (or (and (not kill-year) (nth 5 tl))
16582 (if (and org-read-date-prefer-future
16583 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16584 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16585 (nth 5 org-defdecode)))
16586 hour (or (nth 2 tl) (nth 2 org-defdecode))
16587 minute (or (nth 1 tl) (nth 1 org-defdecode))
16588 second (or (nth 0 tl) 0)
16589 wday (nth 6 tl))
16591 (when (and (eq org-read-date-prefer-future 'time)
16592 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16593 (equal day (nth 3 nowdecode))
16594 (equal month (nth 4 nowdecode))
16595 (equal year (nth 5 nowdecode))
16596 (nth 2 tl)
16597 (or (< (nth 2 tl) (nth 2 nowdecode))
16598 (and (= (nth 2 tl) (nth 2 nowdecode))
16599 (nth 1 tl)
16600 (< (nth 1 tl) (nth 1 nowdecode)))))
16601 (setq day (1+ day)
16602 futurep t))
16604 ;; Special date definitions below
16605 (cond
16606 (iso-week
16607 ;; There was an iso week
16608 (require 'cal-iso)
16609 (setq futurep nil)
16610 (setq year (or iso-year year)
16611 day (or iso-weekday wday 1)
16612 wday nil ; to make sure that the trigger below does not match
16613 iso-date (calendar-gregorian-from-absolute
16614 (calendar-absolute-from-iso
16615 (list iso-week day year))))
16616 ; FIXME: Should we also push ISO weeks into the future?
16617 ; (when (and org-read-date-prefer-future
16618 ; (not iso-year)
16619 ; (< (calendar-absolute-from-gregorian iso-date)
16620 ; (time-to-days (current-time))))
16621 ; (setq year (1+ year)
16622 ; iso-date (calendar-gregorian-from-absolute
16623 ; (calendar-absolute-from-iso
16624 ; (list iso-week day year)))))
16625 (setq month (car iso-date)
16626 year (nth 2 iso-date)
16627 day (nth 1 iso-date)))
16628 (deltan
16629 (setq futurep nil)
16630 (unless deltadef
16631 (let ((now (decode-time (current-time))))
16632 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16633 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16634 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16635 ((equal deltaw "m") (setq month (+ month deltan)))
16636 ((equal deltaw "y") (setq year (+ year deltan)))))
16637 ((and wday (not (nth 3 tl)))
16638 ;; Weekday was given, but no day, so pick that day in the week
16639 ;; on or after the derived date.
16640 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16641 (unless (equal wday wday1)
16642 (setq day (+ day (% (- wday wday1 -7) 7))))))
16643 (if (and (boundp 'org-time-was-given)
16644 (nth 2 tl))
16645 (setq org-time-was-given t))
16646 (if (< year 100) (setq year (+ 2000 year)))
16647 ;; Check of the date is representable
16648 (if org-read-date-force-compatible-dates
16649 (progn
16650 (if (< year 1970)
16651 (setq year 1970 org-read-date-analyze-forced-year t))
16652 (if (> year 2037)
16653 (setq year 2037 org-read-date-analyze-forced-year t)))
16654 (condition-case nil
16655 (ignore (encode-time second minute hour day month year))
16656 (error
16657 (setq year (nth 5 org-defdecode))
16658 (setq org-read-date-analyze-forced-year t))))
16659 (setq org-read-date-analyze-futurep futurep)
16660 (list second minute hour day month year)))
16662 (defvar parse-time-weekdays)
16663 (defun org-read-date-get-relative (s today default)
16664 "Check string S for special relative date string.
16665 TODAY and DEFAULT are internal times, for today and for a default.
16666 Return shift list (N what def-flag)
16667 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16668 N is the number of WHATs to shift.
16669 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16670 the DEFAULT date rather than TODAY."
16671 (require 'parse-time)
16672 (when (and
16673 (string-match
16674 (concat
16675 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16676 "\\([0-9]+\\)?"
16677 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16678 "\\([ \t]\\|$\\)") s)
16679 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16680 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16681 (string-to-char (substring (match-string 1 s) -1))
16682 ?+))
16683 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16684 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16685 (what (if (match-end 3) (match-string 3 s) "d"))
16686 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16687 (date (if rel default today))
16688 (wday (nth 6 (decode-time date)))
16689 delta)
16690 (if wday1
16691 (progn
16692 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16693 (if (= delta 0) (setq delta 7))
16694 (if (= dir ?-)
16695 (progn
16696 (setq delta (- delta 7))
16697 (if (= delta 0) (setq delta -7))))
16698 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16699 (list delta "d" rel))
16700 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16702 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16703 "Turn a user-specified date into the internal representation.
16704 The internal representation needed by the calendar is (month day year).
16705 This is a wrapper to handle the brain-dead convention in calendar that
16706 user function argument order change dependent on argument order."
16707 (if (boundp 'calendar-date-style)
16708 (cond
16709 ((eq calendar-date-style 'american)
16710 (list arg1 arg2 arg3))
16711 ((eq calendar-date-style 'european)
16712 (list arg2 arg1 arg3))
16713 ((eq calendar-date-style 'iso)
16714 (list arg2 arg3 arg1)))
16715 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16716 (if (org-bound-and-true-p european-calendar-style)
16717 (list arg2 arg1 arg3)
16718 (list arg1 arg2 arg3)))))
16720 (defun org-eval-in-calendar (form &optional keepdate)
16721 "Eval FORM in the calendar window and return to current window.
16722 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16723 otherwise stick to the current value of `org-ans2'."
16724 (let ((sf (selected-frame))
16725 (sw (selected-window)))
16726 (select-window (get-buffer-window "*Calendar*" t))
16727 (eval form)
16728 (when (and (not keepdate) (calendar-cursor-to-date))
16729 (let* ((date (calendar-cursor-to-date))
16730 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16731 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16732 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16733 (select-window sw)
16734 (org-select-frame-set-input-focus sf)))
16736 (defun org-calendar-select ()
16737 "Return to `org-read-date' with the date currently selected.
16738 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16739 (interactive)
16740 (when (calendar-cursor-to-date)
16741 (let* ((date (calendar-cursor-to-date))
16742 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16743 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16744 (if (active-minibuffer-window) (exit-minibuffer))))
16746 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16747 "Insert a date stamp for the date given by the internal TIME.
16748 WITH-HM means use the stamp format that includes the time of the day.
16749 INACTIVE means use square brackets instead of angular ones, so that the
16750 stamp will not contribute to the agenda.
16751 PRE and POST are optional strings to be inserted before and after the
16752 stamp.
16753 The command returns the inserted time stamp."
16754 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16755 stamp)
16756 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16757 (insert-before-markers (or pre ""))
16758 (when (listp extra)
16759 (setq extra (car extra))
16760 (if (and (stringp extra)
16761 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16762 (setq extra (format "-%02d:%02d"
16763 (string-to-number (match-string 1 extra))
16764 (string-to-number (match-string 2 extra))))
16765 (setq extra nil)))
16766 (when extra
16767 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16768 (insert-before-markers (setq stamp (format-time-string fmt time)))
16769 (insert-before-markers (or post ""))
16770 (setq org-last-inserted-timestamp stamp)))
16772 (defun org-toggle-time-stamp-overlays ()
16773 "Toggle the use of custom time stamp formats."
16774 (interactive)
16775 (setq org-display-custom-times (not org-display-custom-times))
16776 (unless org-display-custom-times
16777 (let ((p (point-min)) (bmp (buffer-modified-p)))
16778 (while (setq p (next-single-property-change p 'display))
16779 (if (and (get-text-property p 'display)
16780 (eq (get-text-property p 'face) 'org-date))
16781 (remove-text-properties
16782 p (setq p (next-single-property-change p 'display))
16783 '(display t))))
16784 (set-buffer-modified-p bmp)))
16785 (if (featurep 'xemacs)
16786 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16787 (org-restart-font-lock)
16788 (setq org-table-may-need-update t)
16789 (if org-display-custom-times
16790 (message "Time stamps are overlaid with custom format")
16791 (message "Time stamp overlays removed")))
16793 (defun org-display-custom-time (beg end)
16794 "Overlay modified time stamp format over timestamp between BEG and END."
16795 (let* ((ts (buffer-substring beg end))
16796 t1 w1 with-hm tf time str w2 (off 0))
16797 (save-match-data
16798 (setq t1 (org-parse-time-string ts t))
16799 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16800 (setq off (- (match-end 0) (match-beginning 0)))))
16801 (setq end (- end off))
16802 (setq w1 (- end beg)
16803 with-hm (and (nth 1 t1) (nth 2 t1))
16804 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16805 time (org-fix-decoded-time t1)
16806 str (org-add-props
16807 (format-time-string
16808 (substring tf 1 -1) (apply 'encode-time time))
16809 nil 'mouse-face 'highlight)
16810 w2 (length str))
16811 (if (not (= w2 w1))
16812 (add-text-properties (1+ beg) (+ 2 beg)
16813 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16814 (if (featurep 'xemacs)
16815 (progn
16816 (put-text-property beg end 'invisible t)
16817 (put-text-property beg end 'end-glyph (make-glyph str)))
16818 (put-text-property beg end 'display str))))
16820 (defun org-translate-time (string)
16821 "Translate all timestamps in STRING to custom format.
16822 But do this only if the variable `org-display-custom-times' is set."
16823 (when org-display-custom-times
16824 (save-match-data
16825 (let* ((start 0)
16826 (re org-ts-regexp-both)
16827 t1 with-hm inactive tf time str beg end)
16828 (while (setq start (string-match re string start))
16829 (setq beg (match-beginning 0)
16830 end (match-end 0)
16831 t1 (save-match-data
16832 (org-parse-time-string (substring string beg end) t))
16833 with-hm (and (nth 1 t1) (nth 2 t1))
16834 inactive (equal (substring string beg (1+ beg)) "[")
16835 tf (funcall (if with-hm 'cdr 'car)
16836 org-time-stamp-custom-formats)
16837 time (org-fix-decoded-time t1)
16838 str (format-time-string
16839 (concat
16840 (if inactive "[" "<") (substring tf 1 -1)
16841 (if inactive "]" ">"))
16842 (apply 'encode-time time))
16843 string (replace-match str t t string)
16844 start (+ start (length str)))))))
16845 string)
16847 (defun org-fix-decoded-time (time)
16848 "Set 0 instead of nil for the first 6 elements of time.
16849 Don't touch the rest."
16850 (let ((n 0))
16851 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16853 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16855 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16856 "Difference between TIMESTAMP-STRING and now in days.
16857 If SECONDS is non-nil, return the difference in seconds."
16858 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16859 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16860 (funcall fdiff (current-time)))))
16862 (defun org-deadline-close (timestamp-string &optional ndays)
16863 "Is the time in TIMESTAMP-STRING close to the current date?"
16864 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16865 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16866 (not (org-entry-is-done-p))))
16868 (defun org-get-wdays (ts &optional delay zero-delay)
16869 "Get the deadline lead time appropriate for timestring TS.
16870 When DELAY is non-nil, get the delay time for scheduled items
16871 instead of the deadline lead time. When ZERO-DELAY is non-nil
16872 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16873 don't try to find the delay cookie in the scheduled timestamp."
16874 (let ((tv (if delay org-scheduled-delay-days
16875 org-deadline-warning-days)))
16876 (cond
16877 ((or (and delay (< tv 0))
16878 (and delay zero-delay (<= tv 0))
16879 (and (not delay) (<= tv 0)))
16880 ;; Enforce this value no matter what
16881 (- tv))
16882 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16883 ;; lead time is specified.
16884 (floor (* (string-to-number (match-string 1 ts))
16885 (cdr (assoc (match-string 2 ts)
16886 '(("d" . 1) ("w" . 7)
16887 ("m" . 30.4) ("y" . 365.25)
16888 ("h" . 0.041667)))))))
16889 ;; go for the default.
16890 (t tv))))
16892 (defun org-calendar-select-mouse (ev)
16893 "Return to `org-read-date' with the date currently selected.
16894 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16895 (interactive "e")
16896 (mouse-set-point ev)
16897 (when (calendar-cursor-to-date)
16898 (let* ((date (calendar-cursor-to-date))
16899 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16900 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16901 (if (active-minibuffer-window) (exit-minibuffer))))
16903 (defun org-check-deadlines (ndays)
16904 "Check if there are any deadlines due or past due.
16905 A deadline is considered due if it happens within `org-deadline-warning-days'
16906 days from today's date. If the deadline appears in an entry marked DONE,
16907 it is not shown. The prefix arg NDAYS can be used to test that many
16908 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16909 (interactive "P")
16910 (let* ((org-warn-days
16911 (cond
16912 ((equal ndays '(4)) 100000)
16913 (ndays (prefix-numeric-value ndays))
16914 (t (abs org-deadline-warning-days))))
16915 (case-fold-search nil)
16916 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16917 (callback
16918 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16920 (message "%d deadlines past-due or due within %d days"
16921 (org-occur regexp nil callback)
16922 org-warn-days)))
16924 (defsubst org-re-timestamp (type)
16925 "Return a regexp for timestamp TYPE.
16926 Allowed values for TYPE are:
16928 all: all timestamps
16929 active: only active timestamps (<...>)
16930 inactive: only inactive timestamps ([...])
16931 scheduled: only scheduled timestamps
16932 deadline: only deadline timestamps
16933 closed: only closed time-stamps
16935 When TYPE is nil, fall back on returning a regexp that matches
16936 both scheduled and deadline timestamps."
16937 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16938 ((eq type 'active) org-ts-regexp)
16939 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16940 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16941 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16942 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16943 ((eq type 'scheduled-or-deadline)
16944 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16946 (defun org-check-before-date (date)
16947 "Check if there are deadlines or scheduled entries before DATE."
16948 (interactive (list (org-read-date)))
16949 (let ((case-fold-search nil)
16950 (regexp (org-re-timestamp org-ts-type))
16951 (callback
16952 (lambda () (time-less-p
16953 (org-time-string-to-time (match-string 1))
16954 (org-time-string-to-time date)))))
16955 (message "%d entries before %s"
16956 (org-occur regexp nil callback) date)))
16958 (defun org-check-after-date (date)
16959 "Check if there are deadlines or scheduled entries after DATE."
16960 (interactive (list (org-read-date)))
16961 (let ((case-fold-search nil)
16962 (regexp (org-re-timestamp org-ts-type))
16963 (callback
16964 (lambda () (not
16965 (time-less-p
16966 (org-time-string-to-time (match-string 1))
16967 (org-time-string-to-time date))))))
16968 (message "%d entries after %s"
16969 (org-occur regexp nil callback) date)))
16971 (defun org-check-dates-range (start-date end-date)
16972 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16973 (interactive (list (org-read-date nil nil nil "Range starts")
16974 (org-read-date nil nil nil "Range end")))
16975 (let ((case-fold-search nil)
16976 (regexp (org-re-timestamp org-ts-type))
16977 (callback
16978 (lambda ()
16979 (let ((match (match-string 1)))
16980 (and
16981 (not (time-less-p
16982 (org-time-string-to-time match)
16983 (org-time-string-to-time start-date)))
16984 (time-less-p
16985 (org-time-string-to-time match)
16986 (org-time-string-to-time end-date)))))))
16987 (message "%d entries between %s and %s"
16988 (org-occur regexp nil callback) start-date end-date)))
16990 (defun org-evaluate-time-range (&optional to-buffer)
16991 "Evaluate a time range by computing the difference between start and end.
16992 Normally the result is just printed in the echo area, but with prefix arg
16993 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16994 If the time range is actually in a table, the result is inserted into the
16995 next column.
16996 For time difference computation, a year is assumed to be exactly 365
16997 days in order to avoid rounding problems."
16998 (interactive "P")
17000 (org-clock-update-time-maybe)
17001 (save-excursion
17002 (unless (org-at-date-range-p t)
17003 (goto-char (point-at-bol))
17004 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17005 (if (not (org-at-date-range-p t))
17006 (user-error "Not at a time-stamp range, and none found in current line")))
17007 (let* ((ts1 (match-string 1))
17008 (ts2 (match-string 2))
17009 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17010 (match-end (match-end 0))
17011 (time1 (org-time-string-to-time ts1))
17012 (time2 (org-time-string-to-time ts2))
17013 (t1 (org-float-time time1))
17014 (t2 (org-float-time time2))
17015 (diff (abs (- t2 t1)))
17016 (negative (< (- t2 t1) 0))
17017 ;; (ys (floor (* 365 24 60 60)))
17018 (ds (* 24 60 60))
17019 (hs (* 60 60))
17020 (fy "%dy %dd %02d:%02d")
17021 (fy1 "%dy %dd")
17022 (fd "%dd %02d:%02d")
17023 (fd1 "%dd")
17024 (fh "%02d:%02d")
17025 y d h m align)
17026 (if havetime
17027 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17029 d (floor (/ diff ds)) diff (mod diff ds)
17030 h (floor (/ diff hs)) diff (mod diff hs)
17031 m (floor (/ diff 60)))
17032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17034 d (floor (+ (/ diff ds) 0.5))
17035 h 0 m 0))
17036 (if (not to-buffer)
17037 (message "%s" (org-make-tdiff-string y d h m))
17038 (if (org-at-table-p)
17039 (progn
17040 (goto-char match-end)
17041 (setq align t)
17042 (and (looking-at " *|") (goto-char (match-end 0))))
17043 (goto-char match-end))
17044 (if (looking-at
17045 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17046 (replace-match ""))
17047 (if negative (insert " -"))
17048 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17049 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17050 (insert " " (format fh h m))))
17051 (if align (org-table-align))
17052 (message "Time difference inserted")))))
17054 (defun org-make-tdiff-string (y d h m)
17055 (let ((fmt "")
17056 (l nil))
17057 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17058 l (push y l)))
17059 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17060 l (push d l)))
17061 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17062 l (push h l)))
17063 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17064 l (push m l)))
17065 (apply 'format fmt (nreverse l))))
17067 (defun org-time-string-to-time (s &optional buffer pos)
17068 "Convert a timestamp string into internal time."
17069 (condition-case errdata
17070 (apply 'encode-time (org-parse-time-string s))
17071 (error (error "Bad timestamp `%s'%s\nError was: %s"
17072 s (if (not (and buffer pos))
17074 (format " at %d in buffer `%s'" pos buffer))
17075 (cdr errdata)))))
17077 (defun org-time-string-to-seconds (s)
17078 "Convert a timestamp string to a number of seconds."
17079 (org-float-time (org-time-string-to-time s)))
17081 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17082 "Convert a time stamp to an absolute day number.
17083 If there is a specifier for a cyclic time stamp, get the closest
17084 date to DAYNR.
17085 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17086 The variable `date' is bound by the calendar when this is called."
17087 (cond
17088 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17089 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17090 daynr
17091 (+ daynr 1000)))
17092 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17093 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17094 (time-to-days (current-time))) (match-string 0 s)
17095 prefer show-all))
17096 (t (time-to-days
17097 (condition-case errdata
17098 (apply 'encode-time (org-parse-time-string s))
17099 (error (error "Bad timestamp `%s'%s\nError was: %s"
17100 s (if (not (and buffer pos))
17102 (format " at %d in buffer `%s'" pos buffer))
17103 (cdr errdata))))))))
17105 (defun org-days-to-iso-week (days)
17106 "Return the iso week number."
17107 (require 'cal-iso)
17108 (car (calendar-iso-from-absolute days)))
17110 (defun org-small-year-to-year (year)
17111 "Convert 2-digit years into 4-digit years.
17112 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17113 The year 2000 cannot be abbreviated. Any year larger than 99
17114 is returned unchanged."
17115 (if (< year 38)
17116 (setq year (+ 2000 year))
17117 (if (< year 100)
17118 (setq year (+ 1900 year))))
17119 year)
17121 (defun org-time-from-absolute (d)
17122 "Return the time corresponding to date D.
17123 D may be an absolute day number, or a calendar-type list (month day year)."
17124 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17125 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17127 (defun org-calendar-holiday ()
17128 "List of holidays, for Diary display in Org-mode."
17129 (require 'holidays)
17130 (let ((hl (funcall
17131 (if (fboundp 'calendar-check-holidays)
17132 'calendar-check-holidays 'check-calendar-holidays) date)))
17133 (if hl (mapconcat 'identity hl "; "))))
17135 (defun org-diary-sexp-entry (sexp entry date)
17136 "Process a SEXP diary ENTRY for DATE."
17137 (require 'diary-lib)
17138 (let ((result (if calendar-debug-sexp
17139 (let ((stack-trace-on-error t))
17140 (eval (car (read-from-string sexp))))
17141 (condition-case nil
17142 (eval (car (read-from-string sexp)))
17143 (error
17144 (beep)
17145 (message "Bad sexp at line %d in %s: %s"
17146 (org-current-line)
17147 (buffer-file-name) sexp)
17148 (sleep-for 2))))))
17149 (cond ((stringp result) (split-string result "; "))
17150 ((and (consp result)
17151 (not (consp (cdr result)))
17152 (stringp (cdr result))) (cdr result))
17153 ((and (consp result)
17154 (stringp (car result))) result)
17155 (result entry))))
17157 (defun org-diary-to-ical-string (frombuf)
17158 "Get iCalendar entries from diary entries in buffer FROMBUF.
17159 This uses the icalendar.el library."
17160 (let* ((tmpdir (if (featurep 'xemacs)
17161 (temp-directory)
17162 temporary-file-directory))
17163 (tmpfile (make-temp-name
17164 (expand-file-name "orgics" tmpdir)))
17165 buf rtn b e)
17166 (with-current-buffer frombuf
17167 (icalendar-export-region (point-min) (point-max) tmpfile)
17168 (setq buf (find-buffer-visiting tmpfile))
17169 (set-buffer buf)
17170 (goto-char (point-min))
17171 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17172 (setq b (match-beginning 0)))
17173 (goto-char (point-max))
17174 (if (re-search-backward "^END:VEVENT" nil t)
17175 (setq e (match-end 0)))
17176 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17177 (kill-buffer buf)
17178 (delete-file tmpfile)
17179 rtn))
17181 (defun org-closest-date (start current change prefer show-all)
17182 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17183 When PREFER is `past', return a date that is either CURRENT or past.
17184 When PREFER is `future', return a date that is either CURRENT or future.
17185 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17186 ;; Make the proper lists from the dates
17187 (catch 'exit
17188 (let ((a1 '(("h" . hour)
17189 ("d" . day)
17190 ("w" . week)
17191 ("m" . month)
17192 ("y" . year)))
17193 (shour (nth 2 (org-parse-time-string start)))
17194 dn dw sday cday n1 n2 n0
17195 d m y y1 y2 date1 date2 nmonths nm ny m2)
17197 (setq start (org-date-to-gregorian start)
17198 current (org-date-to-gregorian
17199 (if show-all
17200 current
17201 (time-to-days (current-time))))
17202 sday (calendar-absolute-from-gregorian start)
17203 cday (calendar-absolute-from-gregorian current))
17205 (if (<= cday sday) (throw 'exit sday))
17207 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17208 (setq dn (string-to-number (match-string 1 change))
17209 dw (cdr (assoc (match-string 2 change) a1)))
17210 (user-error "Invalid change specifier: %s" change))
17211 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17212 (cond
17213 ((eq dw 'hour)
17214 (let ((missing-hours
17215 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17216 dn)))
17217 (setq n1 (if (zerop missing-hours) cday
17218 (- cday (1+ (floor (/ missing-hours 24)))))
17219 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17220 ((eq dw 'day)
17221 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17222 n2 (+ n1 dn)))
17223 ((eq dw 'year)
17224 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17225 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17226 (setq date1 (list m d y1)
17227 n1 (calendar-absolute-from-gregorian date1)
17228 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17229 n2 (calendar-absolute-from-gregorian date2)))
17230 ((eq dw 'month)
17231 ;; approx number of month between the two dates
17232 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17233 ;; How often does dn fit in there?
17234 (setq d (nth 1 start) m (car start) y (nth 2 start)
17235 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17236 m (+ m nm)
17237 ny (floor (/ m 12))
17238 y (+ y ny)
17239 m (- m (* ny 12)))
17240 (while (> m 12) (setq m (- m 12) y (1+ y)))
17241 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17242 (setq m2 (+ m dn) y2 y)
17243 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17244 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17245 (while (<= n2 cday)
17246 (setq n1 n2 m m2 y y2)
17247 (setq m2 (+ m dn) y2 y)
17248 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17249 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17250 ;; Make sure n1 is the earlier date
17251 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17252 (if show-all
17253 (cond
17254 ((eq prefer 'past) (if (= cday n2) n2 n1))
17255 ((eq prefer 'future) (if (= cday n1) n1 n2))
17256 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17257 (cond
17258 ((eq prefer 'past) (if (= cday n2) n2 n1))
17259 ((eq prefer 'future) (if (= cday n1) n1 n2))
17260 (t (if (= cday n1) n1 n2)))))))
17262 (defun org-date-to-gregorian (date)
17263 "Turn any specification of DATE into a Gregorian date for the calendar."
17264 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17265 ((and (listp date) (= (length date) 3)) date)
17266 ((stringp date)
17267 (setq date (org-parse-time-string date))
17268 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17269 ((listp date)
17270 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17272 (defun org-parse-time-string (s &optional nodefault)
17273 "Parse the standard Org-mode time string.
17274 This should be a lot faster than the normal `parse-time-string'.
17275 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17276 hour and minute fields will be nil if not given."
17277 (cond ((string-match org-ts-regexp0 s)
17278 (list 0
17279 (if (or (match-beginning 8) (not nodefault))
17280 (string-to-number (or (match-string 8 s) "0")))
17281 (if (or (match-beginning 7) (not nodefault))
17282 (string-to-number (or (match-string 7 s) "0")))
17283 (string-to-number (match-string 4 s))
17284 (string-to-number (match-string 3 s))
17285 (string-to-number (match-string 2 s))
17286 nil nil nil))
17287 ((string-match "^<[^>]+>$" s)
17288 (decode-time (seconds-to-time (org-matcher-time s))))
17289 (t (error "Not a standard Org-mode time string: %s" s))))
17291 (defun org-timestamp-up (&optional arg)
17292 "Increase the date item at the cursor by one.
17293 If the cursor is on the year, change the year. If it is on the month,
17294 the day or the time, change that.
17295 With prefix ARG, change by that many units."
17296 (interactive "p")
17297 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17299 (defun org-timestamp-down (&optional arg)
17300 "Decrease the date item at the cursor by one.
17301 If the cursor is on the year, change the year. If it is on the month,
17302 the day or the time, change that.
17303 With prefix ARG, change by that many units."
17304 (interactive "p")
17305 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17307 (defun org-timestamp-up-day (&optional arg)
17308 "Increase the date in the time stamp by one day.
17309 With prefix ARG, change that many days."
17310 (interactive "p")
17311 (if (and (not (org-at-timestamp-p t))
17312 (org-at-heading-p))
17313 (org-todo 'up)
17314 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17316 (defun org-timestamp-down-day (&optional arg)
17317 "Decrease the date in the time stamp by one day.
17318 With prefix ARG, change that many days."
17319 (interactive "p")
17320 (if (and (not (org-at-timestamp-p t))
17321 (org-at-heading-p))
17322 (org-todo 'down)
17323 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17325 (defun org-at-timestamp-p (&optional inactive-ok)
17326 "Determine if the cursor is in or at a timestamp."
17327 (interactive)
17328 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17329 (pos (point))
17330 (ans (or (looking-at tsr)
17331 (save-excursion
17332 (skip-chars-backward "^[<\n\r\t")
17333 (if (> (point) (point-min)) (backward-char 1))
17334 (and (looking-at tsr)
17335 (> (- (match-end 0) pos) -1))))))
17336 (and ans
17337 (boundp 'org-ts-what)
17338 (setq org-ts-what
17339 (cond
17340 ((= pos (match-beginning 0)) 'bracket)
17341 ;; Point is considered to be "on the bracket" whether
17342 ;; it's really on it or right after it.
17343 ((= pos (1- (match-end 0))) 'bracket)
17344 ((= pos (match-end 0)) 'after)
17345 ((org-pos-in-match-range pos 2) 'year)
17346 ((org-pos-in-match-range pos 3) 'month)
17347 ((org-pos-in-match-range pos 7) 'hour)
17348 ((org-pos-in-match-range pos 8) 'minute)
17349 ((or (org-pos-in-match-range pos 4)
17350 (org-pos-in-match-range pos 5)) 'day)
17351 ((and (> pos (or (match-end 8) (match-end 5)))
17352 (< pos (match-end 0)))
17353 (- pos (or (match-end 8) (match-end 5))))
17354 (t 'day))))
17355 ans))
17357 (defun org-toggle-timestamp-type ()
17358 "Toggle the type (<active> or [inactive]) of a time stamp."
17359 (interactive)
17360 (when (org-at-timestamp-p t)
17361 (let ((beg (match-beginning 0)) (end (match-end 0))
17362 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17363 (save-excursion
17364 (goto-char beg)
17365 (while (re-search-forward "[][<>]" end t)
17366 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17367 t t)))
17368 (message "Timestamp is now %sactive"
17369 (if (equal (char-after beg) ?<) "" "in")))))
17371 (defun org-at-clock-log-p nil
17372 "Is the cursor on the clock log line?"
17373 (save-excursion
17374 (move-beginning-of-line 1)
17375 (looking-at "^[ \t]*CLOCK:")))
17377 (defvar org-clock-history) ; defined in org-clock.el
17378 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17379 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17380 "Change the date in the time stamp at point.
17381 The date will be changed by N times WHAT. WHAT can be `day', `month',
17382 `year', `minute', `second'. If WHAT is not given, the cursor position
17383 in the timestamp determines what will be changed.
17384 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17385 (let ((origin (point)) origin-cat
17386 with-hm inactive
17387 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17388 org-ts-what
17389 extra rem
17390 ts time time0 fixnext clrgx)
17391 (if (not (org-at-timestamp-p t))
17392 (user-error "Not at a timestamp"))
17393 (if (and (not what) (eq org-ts-what 'bracket))
17394 (org-toggle-timestamp-type)
17395 ;; Point isn't on brackets. Remember the part of the time-stamp
17396 ;; the point was in. Indeed, size of time-stamps may change,
17397 ;; but point must be kept in the same category nonetheless.
17398 (setq origin-cat org-ts-what)
17399 (if (and (not what) (not (eq org-ts-what 'day))
17400 org-display-custom-times
17401 (get-text-property (point) 'display)
17402 (not (get-text-property (1- (point)) 'display)))
17403 (setq org-ts-what 'day))
17404 (setq org-ts-what (or what org-ts-what)
17405 inactive (= (char-after (match-beginning 0)) ?\[)
17406 ts (match-string 0))
17407 (replace-match "")
17408 (when (string-match
17409 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17411 (setq extra (match-string 1 ts))
17412 (if suppress-tmp-delay
17413 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17414 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17415 (setq with-hm t))
17416 (setq time0 (org-parse-time-string ts))
17417 (when (and updown
17418 (eq org-ts-what 'minute)
17419 (not current-prefix-arg))
17420 ;; This looks like s-up and s-down. Change by one rounding step.
17421 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17422 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17423 (setcar (cdr time0) (+ (nth 1 time0)
17424 (if (> n 0) (- rem) (- dm rem))))))
17425 (setq time
17426 (encode-time (or (car time0) 0)
17427 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17428 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17429 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17430 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17431 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17432 (nthcdr 6 time0)))
17433 (when (and (member org-ts-what '(hour minute))
17434 extra
17435 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17436 (setq extra (org-modify-ts-extra
17437 extra
17438 (if (eq org-ts-what 'hour) 2 5)
17439 n dm)))
17440 (when (integerp org-ts-what)
17441 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17442 (if (eq what 'calendar)
17443 (let ((cal-date (org-get-date-from-calendar)))
17444 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17445 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17446 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17447 (setcar time0 (or (car time0) 0))
17448 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17449 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17450 (setq time (apply 'encode-time time0))))
17451 ;; Insert the new time-stamp, and ensure point stays in the same
17452 ;; category as before (i.e. not after the last position in that
17453 ;; category).
17454 (let ((pos (point)))
17455 ;; Stay before inserted string. `save-excursion' is of no use.
17456 (setq org-last-changed-timestamp
17457 (org-insert-time-stamp time with-hm inactive nil nil extra))
17458 (goto-char pos))
17459 (save-match-data
17460 (looking-at org-ts-regexp3)
17461 (goto-char (cond
17462 ;; `day' category ends before `hour' if any, or at
17463 ;; the end of the day name.
17464 ((eq origin-cat 'day)
17465 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17466 ((eq origin-cat 'hour) (min (match-end 7) origin))
17467 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17468 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17469 ;; `year' and `month' have both fixed size: point
17470 ;; couldn't have moved into another part.
17471 (t origin))))
17472 ;; Update clock if on a CLOCK line.
17473 (org-clock-update-time-maybe)
17474 ;; Maybe adjust the closest clock in `org-clock-history'
17475 (when org-clock-adjust-closest
17476 (if (not (and (org-at-clock-log-p)
17477 (< 1 (length (delq nil (mapcar 'marker-position
17478 org-clock-history))))))
17479 (message "No clock to adjust")
17480 (cond ((save-excursion ; fix previous clock?
17481 (re-search-backward org-ts-regexp0 nil t)
17482 (org-looking-back (concat org-clock-string " \\[")))
17483 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17484 ((save-excursion ; fix next clock?
17485 (re-search-backward org-ts-regexp0 nil t)
17486 (looking-at (concat org-ts-regexp0 "\\] =>")))
17487 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17488 (save-window-excursion
17489 ;; Find closest clock to point, adjust the previous/next one in history
17490 (let* ((p (save-excursion (org-back-to-heading t)))
17491 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17492 (clfixnth
17493 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17494 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17495 (if (not clfixpos)
17496 (message "No clock to adjust")
17497 (save-excursion
17498 (org-goto-marker-or-bmk clfixpos)
17499 (org-show-subtree)
17500 (when (re-search-forward clrgx nil t)
17501 (goto-char (match-beginning 1))
17502 (let (org-clock-adjust-closest)
17503 (org-timestamp-change n org-ts-what updown))
17504 (message "Clock adjusted in %s for heading: %s"
17505 (file-name-nondirectory (buffer-file-name))
17506 (org-get-heading t t)))))))))
17507 ;; Try to recenter the calendar window, if any.
17508 (if (and org-calendar-follow-timestamp-change
17509 (get-buffer-window "*Calendar*" t)
17510 (memq org-ts-what '(day month year)))
17511 (org-recenter-calendar (time-to-days time))))))
17513 (defun org-modify-ts-extra (s pos n dm)
17514 "Change the different parts of the lead-time and repeat fields in timestamp."
17515 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17516 ng h m new rem)
17517 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17518 (cond
17519 ((or (org-pos-in-match-range pos 2)
17520 (org-pos-in-match-range pos 3))
17521 (setq m (string-to-number (match-string 3 s))
17522 h (string-to-number (match-string 2 s)))
17523 (if (org-pos-in-match-range pos 2)
17524 (setq h (+ h n))
17525 (setq n (* dm (org-no-warnings (signum n))))
17526 (when (not (= 0 (setq rem (% m dm))))
17527 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17528 (setq m (+ m n)))
17529 (if (< m 0) (setq m (+ m 60) h (1- h)))
17530 (if (> m 59) (setq m (- m 60) h (1+ h)))
17531 (setq h (min 24 (max 0 h)))
17532 (setq ng 1 new (format "-%02d:%02d" h m)))
17533 ((org-pos-in-match-range pos 6)
17534 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17535 ((org-pos-in-match-range pos 5)
17536 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17538 ((org-pos-in-match-range pos 9)
17539 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17540 ((org-pos-in-match-range pos 8)
17541 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17543 (when ng
17544 (setq s (concat
17545 (substring s 0 (match-beginning ng))
17547 (substring s (match-end ng))))))
17550 (defun org-recenter-calendar (date)
17551 "If the calendar is visible, recenter it to DATE."
17552 (let ((cwin (get-buffer-window "*Calendar*" t)))
17553 (when cwin
17554 (let ((calendar-move-hook nil))
17555 (with-selected-window cwin
17556 (calendar-goto-date (if (listp date) date
17557 (calendar-gregorian-from-absolute date))))))))
17559 (defun org-goto-calendar (&optional arg)
17560 "Go to the Emacs calendar at the current date.
17561 If there is a time stamp in the current line, go to that date.
17562 A prefix ARG can be used to force the current date."
17563 (interactive "P")
17564 (let ((tsr org-ts-regexp) diff
17565 (calendar-move-hook nil)
17566 (calendar-view-holidays-initially-flag nil)
17567 (calendar-view-diary-initially-flag nil))
17568 (if (or (org-at-timestamp-p)
17569 (save-excursion
17570 (beginning-of-line 1)
17571 (looking-at (concat ".*" tsr))))
17572 (let ((d1 (time-to-days (current-time)))
17573 (d2 (time-to-days
17574 (org-time-string-to-time (match-string 1)))))
17575 (setq diff (- d2 d1))))
17576 (calendar)
17577 (calendar-goto-today)
17578 (if (and diff (not arg)) (calendar-forward-day diff))))
17580 (defun org-get-date-from-calendar ()
17581 "Return a list (month day year) of date at point in calendar."
17582 (with-current-buffer "*Calendar*"
17583 (save-match-data
17584 (calendar-cursor-to-date))))
17586 (defun org-date-from-calendar ()
17587 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17588 If there is already a time stamp at the cursor position, update it."
17589 (interactive)
17590 (if (org-at-timestamp-p t)
17591 (org-timestamp-change 0 'calendar)
17592 (let ((cal-date (org-get-date-from-calendar)))
17593 (org-insert-time-stamp
17594 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17596 (defcustom org-effort-durations
17597 `(("h" . 60)
17598 ("d" . ,(* 60 8))
17599 ("w" . ,(* 60 8 5))
17600 ("m" . ,(* 60 8 5 4))
17601 ("y" . ,(* 60 8 5 40)))
17602 "Conversion factor to minutes for an effort modifier.
17604 Each entry has the form (MODIFIER . MINUTES).
17606 In an effort string, a number followed by MODIFIER is multiplied
17607 by the specified number of MINUTES to obtain an effort in
17608 minutes.
17610 For example, if the value of this variable is ((\"hours\" . 60)), then an
17611 effort string \"2hours\" is equivalent to 120 minutes."
17612 :group 'org-agenda
17613 :version "24.1"
17614 :type '(alist :key-type (string :tag "Modifier")
17615 :value-type (number :tag "Minutes")))
17617 (defun org-minutes-to-clocksum-string (m)
17618 "Format number of minutes as a clocksum string.
17619 The format is determined by `org-time-clocksum-format',
17620 `org-time-clocksum-use-fractional' and
17621 `org-time-clocksum-fractional-format' and
17622 `org-time-clocksum-use-effort-durations'."
17623 (let ((clocksum "")
17624 (m (round m)) ; Don't allow fractions of minutes
17625 h d w mo y fmt n)
17626 (setq h (if org-time-clocksum-use-effort-durations
17627 (cdr (assoc "h" org-effort-durations)) 60)
17628 d (if org-time-clocksum-use-effort-durations
17629 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17630 w (if org-time-clocksum-use-effort-durations
17631 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17632 mo (if org-time-clocksum-use-effort-durations
17633 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17634 y (if org-time-clocksum-use-effort-durations
17635 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17636 ;; fractional format
17637 (if org-time-clocksum-use-fractional
17638 (cond
17639 ;; single format string
17640 ((stringp org-time-clocksum-fractional-format)
17641 (format org-time-clocksum-fractional-format (/ m (float h))))
17642 ;; choice of fractional formats for different time units
17643 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17644 (> (/ (truncate m) (* y d h)) 0))
17645 (format fmt (/ m (* y d (float h)))))
17646 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17647 (> (/ (truncate m) (* mo d h)) 0))
17648 (format fmt (/ m (* mo d (float h)))))
17649 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17650 (> (/ (truncate m) (* w d h)) 0))
17651 (format fmt (/ m (* w d (float h)))))
17652 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17653 (> (/ (truncate m) (* d h)) 0))
17654 (format fmt (/ m (* d (float h)))))
17655 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17656 (> (/ (truncate m) h) 0))
17657 (format fmt (/ m (float h))))
17658 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17659 (format fmt m))
17660 ;; fall back to smallest time unit with a format
17661 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17662 (format fmt (/ m (float h))))
17663 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17664 (format fmt (/ m (* d (float h)))))
17665 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17666 (format fmt (/ m (* w d (float h)))))
17667 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17668 (format fmt (/ m (* mo d (float h)))))
17669 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17670 (format fmt (/ m (* y d (float h))))))
17671 ;; standard (non-fractional) format, with single format string
17672 (if (stringp org-time-clocksum-format)
17673 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17674 ;; separate formats components
17675 (and (setq fmt (plist-get org-time-clocksum-format :years))
17676 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17677 (plist-get org-time-clocksum-format :require-years))
17678 (setq clocksum (concat clocksum (format fmt n))
17679 m (- m (* n y d h))))
17680 (and (setq fmt (plist-get org-time-clocksum-format :months))
17681 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17682 (plist-get org-time-clocksum-format :require-months))
17683 (setq clocksum (concat clocksum (format fmt n))
17684 m (- m (* n mo d h))))
17685 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17686 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17687 (plist-get org-time-clocksum-format :require-weeks))
17688 (setq clocksum (concat clocksum (format fmt n))
17689 m (- m (* n w d h))))
17690 (and (setq fmt (plist-get org-time-clocksum-format :days))
17691 (or (> (setq n (/ (truncate m) (* d h))) 0)
17692 (plist-get org-time-clocksum-format :require-days))
17693 (setq clocksum (concat clocksum (format fmt n))
17694 m (- m (* n d h))))
17695 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17696 (or (> (setq n (/ (truncate m) h)) 0)
17697 (plist-get org-time-clocksum-format :require-hours))
17698 (setq clocksum (concat clocksum (format fmt n))
17699 m (- m (* n h))))
17700 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17701 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17702 (setq clocksum (concat clocksum (format fmt m))))
17703 ;; return formatted time duration
17704 clocksum))))
17706 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17707 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17708 "Org mode version 8.0")
17710 (defun org-hours-to-clocksum-string (n)
17711 (org-minutes-to-clocksum-string (* n 60)))
17713 (defun org-hh:mm-string-to-minutes (s)
17714 "Convert a string H:MM to a number of minutes.
17715 If the string is just a number, interpret it as minutes.
17716 In fact, the first hh:mm or number in the string will be taken,
17717 there can be extra stuff in the string.
17718 If no number is found, the return value is 0."
17719 (cond
17720 ((integerp s) s)
17721 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17722 (+ (* (string-to-number (match-string 1 s)) 60)
17723 (string-to-number (match-string 2 s))))
17724 ((string-match "\\([0-9]+\\)" s)
17725 (string-to-number (match-string 1 s)))
17726 (t 0)))
17728 (defcustom org-image-actual-width t
17729 "Should we use the actual width of images when inlining them?
17731 When set to `t', always use the image width.
17733 When set to a number, use imagemagick (when available) to set
17734 the image's width to this value.
17736 When set to a number in a list, try to get the width from any
17737 #+ATTR.* keyword if it matches a width specification like
17739 #+ATTR_HTML: :width 300px
17741 and fall back on that number if none is found.
17743 When set to nil, try to get the width from an #+ATTR.* keyword
17744 and fall back on the original width if none is found.
17746 This requires Emacs >= 24.1, build with imagemagick support."
17747 :group 'org-appearance
17748 :version "24.4"
17749 :package-version '(Org . "8.0")
17750 :type '(choice
17751 (const :tag "Use the image width" t)
17752 (integer :tag "Use a number of pixels")
17753 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17754 (const :tag "Use #+ATTR* or don't resize" nil)))
17756 (defcustom org-agenda-inhibit-startup nil
17757 "Inhibit startup when preparing agenda buffers.
17758 When this variable is `t' (the default), the initialization of
17759 the Org agenda buffers is inhibited: e.g. the visibility state
17760 is not set, the tables are not re-aligned, etc."
17761 :type 'boolean
17762 :version "24.3"
17763 :group 'org-agenda)
17765 (defcustom org-agenda-ignore-drawer-properties nil
17766 "Avoid updating text properties when building the agenda.
17767 Properties are used to prepare buffers for effort estimates, appointments,
17768 and subtree-local categories.
17769 If you don't use these in the agenda, you can add them to this list and
17770 agenda building will be a bit faster.
17771 The value is a list, with zero or more of the symbols `effort', `appt',
17772 or `category'."
17773 :type '(set :greedy t
17774 (const effort)
17775 (const appt)
17776 (const category))
17777 :version "24.3"
17778 :group 'org-agenda)
17780 (defun org-duration-string-to-minutes (s &optional output-to-string)
17781 "Convert a duration string S to minutes.
17783 A bare number is interpreted as minutes, modifiers can be set by
17784 customizing `org-effort-durations' (which see).
17786 Entries containing a colon are interpreted as H:MM by
17787 `org-hh:mm-string-to-minutes'."
17788 (let ((result 0)
17789 (re (concat "\\([0-9.]+\\) *\\("
17790 (regexp-opt (mapcar 'car org-effort-durations))
17791 "\\)")))
17792 (while (string-match re s)
17793 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17794 (string-to-number (match-string 1 s))))
17795 (setq s (replace-match "" nil t s)))
17796 (setq result (floor result))
17797 (incf result (org-hh:mm-string-to-minutes s))
17798 (if output-to-string (number-to-string result) result)))
17800 ;;;; Files
17802 (defun org-save-all-org-buffers ()
17803 "Save all Org-mode buffers without user confirmation."
17804 (interactive)
17805 (message "Saving all Org-mode buffers...")
17806 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17807 (when (featurep 'org-id) (org-id-locations-save))
17808 (message "Saving all Org-mode buffers... done"))
17810 (defun org-revert-all-org-buffers ()
17811 "Revert all Org-mode buffers.
17812 Prompt for confirmation when there are unsaved changes.
17813 Be sure you know what you are doing before letting this function
17814 overwrite your changes.
17816 This function is useful in a setup where one tracks org files
17817 with a version control system, to revert on one machine after pulling
17818 changes from another. I believe the procedure must be like this:
17820 1. M-x org-save-all-org-buffers
17821 2. Pull changes from the other machine, resolve conflicts
17822 3. M-x org-revert-all-org-buffers"
17823 (interactive)
17824 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17825 (user-error "Abort"))
17826 (save-excursion
17827 (save-window-excursion
17828 (mapc
17829 (lambda (b)
17830 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17831 (with-current-buffer b buffer-file-name))
17832 (org-pop-to-buffer-same-window b)
17833 (revert-buffer t 'no-confirm)))
17834 (buffer-list))
17835 (when (and (featurep 'org-id) org-id-track-globally)
17836 (org-id-locations-load)))))
17838 ;;;; Agenda files
17840 ;;;###autoload
17841 (defun org-switchb (&optional arg)
17842 "Switch between Org buffers.
17843 With one prefix argument, restrict available buffers to files.
17844 With two prefix arguments, restrict available buffers to agenda files.
17846 Defaults to `iswitchb' for buffer name completion.
17847 Set `org-completion-use-ido' to make it use ido instead."
17848 (interactive "P")
17849 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17850 ((equal arg '(16)) (org-buffer-list 'agenda))
17851 (t (org-buffer-list))))
17852 (org-completion-use-iswitchb org-completion-use-iswitchb)
17853 (org-completion-use-ido org-completion-use-ido))
17854 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17855 (setq org-completion-use-iswitchb t))
17856 (org-pop-to-buffer-same-window
17857 (org-icompleting-read "Org buffer: "
17858 (mapcar 'list (mapcar 'buffer-name blist))
17859 nil t))))
17861 ;;; Define some older names previously used for this functionality
17862 ;;;###autoload
17863 (defalias 'org-ido-switchb 'org-switchb)
17864 ;;;###autoload
17865 (defalias 'org-iswitchb 'org-switchb)
17867 (defun org-buffer-list (&optional predicate exclude-tmp)
17868 "Return a list of Org buffers.
17869 PREDICATE can be `export', `files' or `agenda'.
17871 export restrict the list to Export buffers.
17872 files restrict the list to buffers visiting Org files.
17873 agenda restrict the list to buffers visiting agenda files.
17875 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17876 (let* ((bfn nil)
17877 (agenda-files (and (eq predicate 'agenda)
17878 (mapcar 'file-truename (org-agenda-files t))))
17879 (filter
17880 (cond
17881 ((eq predicate 'files)
17882 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17883 ((eq predicate 'export)
17884 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17885 ((eq predicate 'agenda)
17886 (lambda (b)
17887 (with-current-buffer b
17888 (and (derived-mode-p 'org-mode)
17889 (setq bfn (buffer-file-name b))
17890 (member (file-truename bfn) agenda-files)))))
17891 (t (lambda (b) (with-current-buffer b
17892 (or (derived-mode-p 'org-mode)
17893 (string-match "\*Org .*Export"
17894 (buffer-name b)))))))))
17895 (delq nil
17896 (mapcar
17897 (lambda(b)
17898 (if (and (funcall filter b)
17899 (or (not exclude-tmp)
17900 (not (string-match "tmp" (buffer-name b)))))
17902 nil))
17903 (buffer-list)))))
17905 (defun org-agenda-files (&optional unrestricted archives)
17906 "Get the list of agenda files.
17907 Optional UNRESTRICTED means return the full list even if a restriction
17908 is currently in place.
17909 When ARCHIVES is t, include all archive files that are really being
17910 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17911 `org-agenda-archives-mode' is t."
17912 (let ((files
17913 (cond
17914 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17915 ((stringp org-agenda-files) (org-read-agenda-file-list))
17916 ((listp org-agenda-files) org-agenda-files)
17917 (t (error "Invalid value of `org-agenda-files'")))))
17918 (setq files (apply 'append
17919 (mapcar (lambda (f)
17920 (if (file-directory-p f)
17921 (directory-files
17922 f t org-agenda-file-regexp)
17923 (list f)))
17924 files)))
17925 (when org-agenda-skip-unavailable-files
17926 (setq files (delq nil
17927 (mapcar (function
17928 (lambda (file)
17929 (and (file-readable-p file) file)))
17930 files))))
17931 (when (or (eq archives t)
17932 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17933 (setq files (org-add-archive-files files)))
17934 files))
17936 (defun org-agenda-file-p (&optional file)
17937 "Return non-nil, if FILE is an agenda file.
17938 If FILE is omitted, use the file associated with the current
17939 buffer."
17940 (member (or file (buffer-file-name))
17941 (org-agenda-files t)))
17943 (defun org-edit-agenda-file-list ()
17944 "Edit the list of agenda files.
17945 Depending on setup, this either uses customize to edit the variable
17946 `org-agenda-files', or it visits the file that is holding the list. In the
17947 latter case, the buffer is set up in a way that saving it automatically kills
17948 the buffer and restores the previous window configuration."
17949 (interactive)
17950 (if (stringp org-agenda-files)
17951 (let ((cw (current-window-configuration)))
17952 (find-file org-agenda-files)
17953 (org-set-local 'org-window-configuration cw)
17954 (org-add-hook 'after-save-hook
17955 (lambda ()
17956 (set-window-configuration
17957 (prog1 org-window-configuration
17958 (kill-buffer (current-buffer))))
17959 (org-install-agenda-files-menu)
17960 (message "New agenda file list installed"))
17961 nil 'local)
17962 (message "%s" (substitute-command-keys
17963 "Edit list and finish with \\[save-buffer]")))
17964 (customize-variable 'org-agenda-files)))
17966 (defun org-store-new-agenda-file-list (list)
17967 "Set new value for the agenda file list and save it correctly."
17968 (if (stringp org-agenda-files)
17969 (let ((fe (org-read-agenda-file-list t)) b u)
17970 (while (setq b (find-buffer-visiting org-agenda-files))
17971 (kill-buffer b))
17972 (with-temp-file org-agenda-files
17973 (insert
17974 (mapconcat
17975 (lambda (f) ;; Keep un-expanded entries.
17976 (if (setq u (assoc f fe))
17977 (cdr u)
17979 list "\n")
17980 "\n")))
17981 (let ((org-mode-hook nil) (org-inhibit-startup t)
17982 (org-insert-mode-line-in-empty-file nil))
17983 (setq org-agenda-files list)
17984 (customize-save-variable 'org-agenda-files org-agenda-files))))
17986 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17987 "Read the list of agenda files from a file.
17988 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17989 filenames, used by `org-store-new-agenda-file-list' to write back
17990 un-expanded file names."
17991 (when (file-directory-p org-agenda-files)
17992 (error "`org-agenda-files' cannot be a single directory"))
17993 (when (stringp org-agenda-files)
17994 (with-temp-buffer
17995 (insert-file-contents org-agenda-files)
17996 (mapcar
17997 (lambda (f)
17998 (let ((e (expand-file-name (substitute-in-file-name f)
17999 org-directory)))
18000 (if pair-with-expansion
18001 (cons e f)
18002 e)))
18003 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18005 ;;;###autoload
18006 (defun org-cycle-agenda-files ()
18007 "Cycle through the files in `org-agenda-files'.
18008 If the current buffer visits an agenda file, find the next one in the list.
18009 If the current buffer does not, find the first agenda file."
18010 (interactive)
18011 (let* ((fs (org-agenda-files t))
18012 (files (append fs (list (car fs))))
18013 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18014 file)
18015 (unless files (user-error "No agenda files"))
18016 (catch 'exit
18017 (while (setq file (pop files))
18018 (if (equal (file-truename file) tcf)
18019 (when (car files)
18020 (find-file (car files))
18021 (throw 'exit t))))
18022 (find-file (car fs)))
18023 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18025 (defun org-agenda-file-to-front (&optional to-end)
18026 "Move/add the current file to the top of the agenda file list.
18027 If the file is not present in the list, it is added to the front. If it is
18028 present, it is moved there. With optional argument TO-END, add/move to the
18029 end of the list."
18030 (interactive "P")
18031 (let ((org-agenda-skip-unavailable-files nil)
18032 (file-alist (mapcar (lambda (x)
18033 (cons (file-truename x) x))
18034 (org-agenda-files t)))
18035 (ctf (file-truename
18036 (or buffer-file-name
18037 (user-error "Please save the current buffer to a file"))))
18038 x had)
18039 (setq x (assoc ctf file-alist) had x)
18041 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18042 (if to-end
18043 (setq file-alist (append (delq x file-alist) (list x)))
18044 (setq file-alist (cons x (delq x file-alist))))
18045 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18046 (org-install-agenda-files-menu)
18047 (message "File %s to %s of agenda file list"
18048 (if had "moved" "added") (if to-end "end" "front"))))
18050 (defun org-remove-file (&optional file)
18051 "Remove current file from the list of files in variable `org-agenda-files'.
18052 These are the files which are being checked for agenda entries.
18053 Optional argument FILE means use this file instead of the current."
18054 (interactive)
18055 (let* ((org-agenda-skip-unavailable-files nil)
18056 (file (or file buffer-file-name
18057 (user-error "Current buffer does not visit a file")))
18058 (true-file (file-truename file))
18059 (afile (abbreviate-file-name file))
18060 (files (delq nil (mapcar
18061 (lambda (x)
18062 (if (equal true-file
18063 (file-truename x))
18064 nil x))
18065 (org-agenda-files t)))))
18066 (if (not (= (length files) (length (org-agenda-files t))))
18067 (progn
18068 (org-store-new-agenda-file-list files)
18069 (org-install-agenda-files-menu)
18070 (message "Removed file: %s" afile))
18071 (message "File was not in list: %s (not removed)" afile))))
18073 (defun org-file-menu-entry (file)
18074 (vector file (list 'find-file file) t))
18076 (defun org-check-agenda-file (file)
18077 "Make sure FILE exists. If not, ask user what to do."
18078 (when (not (file-exists-p file))
18079 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18080 (abbreviate-file-name file))
18081 (let ((r (downcase (read-char-exclusive))))
18082 (cond
18083 ((equal r ?r)
18084 (org-remove-file file)
18085 (throw 'nextfile t))
18086 (t (error "Abort"))))))
18088 (defun org-get-agenda-file-buffer (file)
18089 "Get a buffer visiting FILE. If the buffer needs to be created, add
18090 it to the list of buffers which might be released later."
18091 (let ((buf (org-find-base-buffer-visiting file)))
18092 (if buf
18093 buf ; just return it
18094 ;; Make a new buffer and remember it
18095 (setq buf (find-file-noselect file))
18096 (if buf (push buf org-agenda-new-buffers))
18097 buf)))
18099 (defun org-release-buffers (blist)
18100 "Release all buffers in list, asking the user for confirmation when needed.
18101 When a buffer is unmodified, it is just killed. When modified, it is saved
18102 \(if the user agrees) and then killed."
18103 (let (buf file)
18104 (while (setq buf (pop blist))
18105 (setq file (buffer-file-name buf))
18106 (when (and (buffer-modified-p buf)
18107 file
18108 (y-or-n-p (format "Save file %s? " file)))
18109 (with-current-buffer buf (save-buffer)))
18110 (kill-buffer buf))))
18112 (defun org-agenda-prepare-buffers (files)
18113 "Create buffers for all agenda files, protect archived trees and comments."
18114 (interactive)
18115 (let ((pa '(:org-archived t))
18116 (pc '(:org-comment t))
18117 (pall '(:org-archived t :org-comment t))
18118 (inhibit-read-only t)
18119 (org-inhibit-startup org-agenda-inhibit-startup)
18120 (rea (concat ":" org-archive-tag ":"))
18121 file re pos)
18122 (setq org-tag-alist-for-agenda nil
18123 org-tag-groups-alist-for-agenda nil)
18124 (save-window-excursion
18125 (save-restriction
18126 (while (setq file (pop files))
18127 (catch 'nextfile
18128 (if (bufferp file)
18129 (set-buffer file)
18130 (org-check-agenda-file file)
18131 (set-buffer (org-get-agenda-file-buffer file)))
18132 (widen)
18133 (org-set-regexps-and-options-for-tags)
18134 (setq pos (point))
18135 (goto-char (point-min))
18136 (let ((case-fold-search t))
18137 (when (search-forward "#+setupfile" nil t)
18138 ;; Don't set all regexps and options systematically as
18139 ;; this is only run for setting agenda tags from setup
18140 ;; file
18141 (org-set-regexps-and-options)))
18142 (or (memq 'category org-agenda-ignore-drawer-properties)
18143 (org-refresh-category-properties))
18144 (or (memq 'effort org-agenda-ignore-drawer-properties)
18145 (org-refresh-properties org-effort-property 'org-effort))
18146 (or (memq 'appt org-agenda-ignore-drawer-properties)
18147 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18148 (setq org-todo-keywords-for-agenda
18149 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18150 (setq org-done-keywords-for-agenda
18151 (append org-done-keywords-for-agenda org-done-keywords))
18152 (setq org-todo-keyword-alist-for-agenda
18153 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18154 (setq org-tag-alist-for-agenda
18155 (org-uniquify
18156 (append org-tag-alist-for-agenda
18157 org-tag-alist
18158 org-tag-persistent-alist)))
18159 (if org-group-tags
18160 (setq org-tag-groups-alist-for-agenda
18161 (org-uniquify-alist
18162 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18163 (org-with-silent-modifications
18164 (save-excursion
18165 (remove-text-properties (point-min) (point-max) pall)
18166 (when org-agenda-skip-archived-trees
18167 (goto-char (point-min))
18168 (while (re-search-forward rea nil t)
18169 (if (org-at-heading-p t)
18170 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18171 (goto-char (point-min))
18172 (setq re (format org-heading-keyword-regexp-format
18173 org-comment-string))
18174 (while (re-search-forward re nil t)
18175 (add-text-properties
18176 (match-beginning 0) (org-end-of-subtree t) pc))))
18177 (goto-char pos)))))
18178 (setq org-todo-keywords-for-agenda
18179 (org-uniquify org-todo-keywords-for-agenda))
18180 (setq org-todo-keyword-alist-for-agenda
18181 (org-uniquify org-todo-keyword-alist-for-agenda))))
18184 ;;;; CDLaTeX minor mode
18186 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18187 "Keymap for the minor `org-cdlatex-mode'.")
18189 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18190 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18191 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18192 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18193 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18195 (defvar org-cdlatex-texmathp-advice-is-done nil
18196 "Flag remembering if we have applied the advice to texmathp already.")
18198 (define-minor-mode org-cdlatex-mode
18199 "Toggle the minor `org-cdlatex-mode'.
18200 This mode supports entering LaTeX environment and math in LaTeX fragments
18201 in Org-mode.
18202 \\{org-cdlatex-mode-map}"
18203 nil " OCDL" nil
18204 (when org-cdlatex-mode
18205 (require 'cdlatex)
18206 (run-hooks 'cdlatex-mode-hook)
18207 (cdlatex-compute-tables))
18208 (unless org-cdlatex-texmathp-advice-is-done
18209 (setq org-cdlatex-texmathp-advice-is-done t)
18210 (defadvice texmathp (around org-math-always-on activate)
18211 "Always return t in org-mode buffers.
18212 This is because we want to insert math symbols without dollars even outside
18213 the LaTeX math segments. If Orgmode thinks that point is actually inside
18214 an embedded LaTeX fragment, let texmathp do its job.
18215 \\[org-cdlatex-mode-map]"
18216 (interactive)
18217 (let (p)
18218 (cond
18219 ((not (derived-mode-p 'org-mode)) ad-do-it)
18220 ((eq this-command 'cdlatex-math-symbol)
18221 (setq ad-return-value t
18222 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18224 (let ((p (org-inside-LaTeX-fragment-p)))
18225 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18226 (setq ad-return-value t
18227 texmathp-why '("Org-mode embedded math" . 0))
18228 (if p ad-do-it)))))))))
18230 (defun turn-on-org-cdlatex ()
18231 "Unconditionally turn on `org-cdlatex-mode'."
18232 (org-cdlatex-mode 1))
18234 (defun org-try-cdlatex-tab ()
18235 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18236 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18237 - inside a LaTeX fragment, or
18238 - after the first word in a line, where an abbreviation expansion could
18239 insert a LaTeX environment."
18240 (when org-cdlatex-mode
18241 (cond
18242 ;; Before any word on the line: No expansion possible.
18243 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18244 ;; Just after first word on the line: Expand it. Make sure it
18245 ;; cannot happen on headlines, though.
18246 ((save-excursion
18247 (skip-chars-backward "a-zA-Z0-9*")
18248 (skip-chars-backward " \t")
18249 (and (bolp) (not (org-at-heading-p))))
18250 (cdlatex-tab) t)
18251 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18253 (defun org-cdlatex-underscore-caret (&optional arg)
18254 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18255 Revert to the normal definition outside of these fragments."
18256 (interactive "P")
18257 (if (org-inside-LaTeX-fragment-p)
18258 (call-interactively 'cdlatex-sub-superscript)
18259 (let (org-cdlatex-mode)
18260 (call-interactively (key-binding (vector last-input-event))))))
18262 (defun org-cdlatex-math-modify (&optional arg)
18263 "Execute `cdlatex-math-modify' in LaTeX fragments.
18264 Revert to the normal definition outside of these fragments."
18265 (interactive "P")
18266 (if (org-inside-LaTeX-fragment-p)
18267 (call-interactively 'cdlatex-math-modify)
18268 (let (org-cdlatex-mode)
18269 (call-interactively (key-binding (vector last-input-event))))))
18273 ;;;; LaTeX fragments
18275 (defun org-inside-LaTeX-fragment-p ()
18276 "Test if point is inside a LaTeX fragment.
18277 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18278 sequence appearing also before point.
18279 Even though the matchers for math are configurable, this function assumes
18280 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18281 delimiters are skipped when they have been removed by customization.
18282 The return value is nil, or a cons cell with the delimiter and the
18283 position of this delimiter.
18285 This function does a reasonably good job, but can locally be fooled by
18286 for example currency specifications. For example it will assume being in
18287 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18288 fragments that are properly closed, but during editing, we have to live
18289 with the uncertainty caused by missing closing delimiters. This function
18290 looks only before point, not after."
18291 (catch 'exit
18292 (let ((pos (point))
18293 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18294 (lim (progn
18295 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18296 (point)))
18297 dd-on str (start 0) m re)
18298 (goto-char pos)
18299 (when dodollar
18300 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18301 re (nth 1 (assoc "$" org-latex-regexps)))
18302 (while (string-match re str start)
18303 (cond
18304 ((= (match-end 0) (length str))
18305 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18306 ((= (match-end 0) (- (length str) 5))
18307 (throw 'exit nil))
18308 (t (setq start (match-end 0))))))
18309 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18310 (goto-char pos)
18311 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18312 (and (match-beginning 2) (throw 'exit nil))
18313 ;; count $$
18314 (while (re-search-backward "\\$\\$" lim t)
18315 (setq dd-on (not dd-on)))
18316 (goto-char pos)
18317 (if dd-on (cons "$$" m))))))
18319 (defun org-inside-latex-macro-p ()
18320 "Is point inside a LaTeX macro or its arguments?"
18321 (save-match-data
18322 (org-in-regexp
18323 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18325 (defvar org-latex-fragment-image-overlays nil
18326 "List of overlays carrying the images of latex fragments.")
18327 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18329 (defun org-remove-latex-fragment-image-overlays ()
18330 "Remove all overlays with LaTeX fragment images in current buffer."
18331 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18332 (setq org-latex-fragment-image-overlays nil))
18334 (defun org-preview-latex-fragment (&optional subtree)
18335 "Preview the LaTeX fragment at point, or all locally or globally.
18336 If the cursor is in a LaTeX fragment, create the image and overlay
18337 it over the source code. If there is no fragment at point, display
18338 all fragments in the current text, from one headline to the next. With
18339 prefix SUBTREE, display all fragments in the current subtree. With a
18340 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18341 the cursor is before the first headline,
18342 display all fragments in the buffer.
18343 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18344 (interactive "P")
18345 (unless buffer-file-name
18346 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18347 (when (display-graphic-p)
18348 (org-remove-latex-fragment-image-overlays)
18349 (save-excursion
18350 (save-restriction
18351 (let (beg end at msg)
18352 (cond
18353 ((or (equal subtree '(16))
18354 (not (save-excursion
18355 (re-search-backward org-outline-regexp-bol nil t))))
18356 (setq beg (point-min) end (point-max)
18357 msg "Creating images for buffer...%s"))
18358 ((equal subtree '(4))
18359 (org-back-to-heading)
18360 (setq beg (point) end (org-end-of-subtree t)
18361 msg "Creating images for subtree...%s"))
18363 (if (setq at (org-inside-LaTeX-fragment-p))
18364 (goto-char (max (point-min) (- (cdr at) 2)))
18365 (org-back-to-heading))
18366 (setq beg (point) end (progn (outline-next-heading) (point))
18367 msg (if at "Creating image...%s"
18368 "Creating images for entry...%s"))))
18369 (message msg "")
18370 (narrow-to-region beg end)
18371 (goto-char beg)
18372 (org-format-latex
18373 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18374 (file-name-nondirectory
18375 buffer-file-name)))
18376 default-directory 'overlays msg at 'forbuffer
18377 org-latex-create-formula-image-program)
18378 (message msg "done. Use `C-c C-c' to remove images."))))))
18380 (defun org-format-latex (prefix &optional dir overlays msg at
18381 forbuffer processing-type)
18382 "Replace LaTeX fragments with links to an image, and produce images.
18383 Some of the options can be changed using the variable
18384 `org-format-latex-options'."
18385 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18386 (let* ((prefixnodir (file-name-nondirectory prefix))
18387 (absprefix (expand-file-name prefix dir))
18388 (todir (file-name-directory absprefix))
18389 (opt org-format-latex-options)
18390 (optnew org-format-latex-options)
18391 (matchers (plist-get opt :matchers))
18392 (re-list org-latex-regexps)
18393 (cnt 0) txt hash link beg end re e checkdir
18394 string
18395 m n block-type block linkfile movefile ov)
18396 ;; Check the different regular expressions
18397 (while (setq e (pop re-list))
18398 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18399 block (if block-type "\n\n" ""))
18400 (when (member m matchers)
18401 (goto-char (point-min))
18402 (while (re-search-forward re nil t)
18403 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18404 (or (not overlays)
18405 (not (eq (get-char-property (match-beginning n)
18406 'org-overlay-type)
18407 'org-latex-overlay))))
18408 (cond
18409 ((eq processing-type 'verbatim))
18410 ((eq processing-type 'mathjax)
18411 ;; Prepare for MathJax processing.
18412 (setq string (match-string n))
18413 (when (member m '("$" "$1"))
18414 (save-excursion
18415 (delete-region (match-beginning n) (match-end n))
18416 (goto-char (match-beginning n))
18417 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18418 ((or (eq processing-type 'dvipng)
18419 (eq processing-type 'imagemagick))
18420 ;; Process to an image.
18421 (setq txt (match-string n)
18422 beg (match-beginning n) end (match-end n)
18423 cnt (1+ cnt))
18424 (let ((face (face-at-point))
18425 (fg (plist-get opt :foreground))
18426 (bg (plist-get opt :background))
18427 ;; Ensure full list is printed.
18428 print-length print-level)
18429 (when forbuffer
18430 ;; Get the colors from the face at point.
18431 (goto-char beg)
18432 (when (eq fg 'auto)
18433 (setq fg (face-attribute face :foreground nil 'default)))
18434 (when (eq bg 'auto)
18435 (setq bg (face-attribute face :background nil 'default)))
18436 (setq optnew (copy-sequence opt))
18437 (plist-put optnew :foreground fg)
18438 (plist-put optnew :background bg))
18439 (setq hash (sha1 (prin1-to-string
18440 (list org-format-latex-header
18441 org-latex-default-packages-alist
18442 org-latex-packages-alist
18443 org-format-latex-options
18444 forbuffer txt fg bg)))
18445 linkfile (format "%s_%s.png" prefix hash)
18446 movefile (format "%s_%s.png" absprefix hash)))
18447 (setq link (concat block "[[file:" linkfile "]]" block))
18448 (if msg (message msg cnt))
18449 (goto-char beg)
18450 (unless checkdir ; Ensure the directory exists.
18451 (setq checkdir t)
18452 (or (file-directory-p todir) (make-directory todir t)))
18453 (unless (file-exists-p movefile)
18454 (org-create-formula-image
18455 txt movefile optnew forbuffer processing-type))
18456 (if overlays
18457 (progn
18458 (mapc (lambda (o)
18459 (if (eq (overlay-get o 'org-overlay-type)
18460 'org-latex-overlay)
18461 (delete-overlay o)))
18462 (overlays-in beg end))
18463 (setq ov (make-overlay beg end))
18464 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18465 (if (featurep 'xemacs)
18466 (progn
18467 (overlay-put ov 'invisible t)
18468 (overlay-put
18469 ov 'end-glyph
18470 (make-glyph (vector 'png :file movefile))))
18471 (overlay-put
18472 ov 'display
18473 (list 'image :type 'png :file movefile :ascent 'center)))
18474 (push ov org-latex-fragment-image-overlays)
18475 (goto-char end))
18476 (delete-region beg end)
18477 (insert (org-add-props link
18478 (list 'org-latex-src
18479 (replace-regexp-in-string
18480 "\"" "" txt)
18481 'org-latex-src-embed-type
18482 (if block-type 'paragraph 'character))))))
18483 ((eq processing-type 'mathml)
18484 ;; Process to MathML
18485 (unless (save-match-data (org-format-latex-mathml-available-p))
18486 (user-error "LaTeX to MathML converter not configured"))
18487 (setq txt (match-string n)
18488 beg (match-beginning n) end (match-end n)
18489 cnt (1+ cnt))
18490 (if msg (message msg cnt))
18491 (goto-char beg)
18492 (delete-region beg end)
18493 (insert (org-format-latex-as-mathml
18494 txt block-type prefix dir)))
18496 (error "Unknown conversion type %s for LaTeX fragments"
18497 processing-type)))))))))
18499 (defun org-create-math-formula (latex-frag &optional mathml-file)
18500 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18501 Use `org-latex-to-mathml-convert-command'. If the conversion is
18502 sucessful, return the portion between \"<math...> </math>\"
18503 elements otherwise return nil. When MATHML-FILE is specified,
18504 write the results in to that file. When invoked as an
18505 interactive command, prompt for LATEX-FRAG, with initial value
18506 set to the current active region and echo the results for user
18507 inspection."
18508 (interactive (list (let ((frag (when (org-region-active-p)
18509 (buffer-substring-no-properties
18510 (region-beginning) (region-end)))))
18511 (read-string "LaTeX Fragment: " frag nil frag))))
18512 (unless latex-frag (error "Invalid LaTeX fragment"))
18513 (let* ((tmp-in-file (file-relative-name
18514 (make-temp-name (expand-file-name "ltxmathml-in"))))
18515 (ignore (write-region latex-frag nil tmp-in-file))
18516 (tmp-out-file (file-relative-name
18517 (make-temp-name (expand-file-name "ltxmathml-out"))))
18518 (cmd (format-spec
18519 org-latex-to-mathml-convert-command
18520 `((?j . ,(shell-quote-argument
18521 (expand-file-name org-latex-to-mathml-jar-file)))
18522 (?I . ,(shell-quote-argument tmp-in-file))
18523 (?o . ,(shell-quote-argument tmp-out-file)))))
18524 mathml shell-command-output)
18525 (when (org-called-interactively-p 'any)
18526 (unless (org-format-latex-mathml-available-p)
18527 (user-error "LaTeX to MathML converter not configured")))
18528 (message "Running %s" cmd)
18529 (setq shell-command-output (shell-command-to-string cmd))
18530 (setq mathml
18531 (when (file-readable-p tmp-out-file)
18532 (with-current-buffer (find-file-noselect tmp-out-file t)
18533 (goto-char (point-min))
18534 (when (re-search-forward
18535 (concat
18536 (regexp-quote
18537 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18538 "\\(.\\|\n\\)*"
18539 (regexp-quote "</math>")) nil t)
18540 (prog1 (match-string 0) (kill-buffer))))))
18541 (cond
18542 (mathml
18543 (setq mathml
18544 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18545 (when mathml-file
18546 (write-region mathml nil mathml-file))
18547 (when (org-called-interactively-p 'any)
18548 (message mathml)))
18549 ((message "LaTeX to MathML conversion failed")
18550 (message shell-command-output)))
18551 (delete-file tmp-in-file)
18552 (when (file-exists-p tmp-out-file)
18553 (delete-file tmp-out-file))
18554 mathml))
18556 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18557 prefix &optional dir)
18558 "Use `org-create-math-formula' but check local cache first."
18559 (let* ((absprefix (expand-file-name prefix dir))
18560 (print-length nil) (print-level nil)
18561 (formula-id (concat
18562 "formula-"
18563 (sha1
18564 (prin1-to-string
18565 (list latex-frag
18566 org-latex-to-mathml-convert-command)))))
18567 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18568 (formula-cache-dir (file-name-directory formula-cache)))
18570 (unless (file-directory-p formula-cache-dir)
18571 (make-directory formula-cache-dir t))
18573 (unless (file-exists-p formula-cache)
18574 (org-create-math-formula latex-frag formula-cache))
18576 (if (file-exists-p formula-cache)
18577 ;; Successful conversion. Return the link to MathML file.
18578 (org-add-props
18579 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18580 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18581 'org-latex-src-embed-type (if latex-frag-type
18582 'paragraph 'character)))
18583 ;; Failed conversion. Return the LaTeX fragment verbatim
18584 latex-frag)))
18586 (defun org-create-formula-image (string tofile options buffer &optional type)
18587 "Create an image from LaTeX source using dvipng or convert.
18588 This function calls either `org-create-formula-image-with-dvipng'
18589 or `org-create-formula-image-with-imagemagick' depending on the
18590 value of `org-latex-create-formula-image-program' or on the value
18591 of the optional TYPE variable.
18593 Note: ultimately these two function should be combined as they
18594 share a good deal of logic."
18595 (org-check-external-command
18596 "latex" "needed to convert LaTeX fragments to images")
18597 (funcall
18598 (case (or type org-latex-create-formula-image-program)
18599 ('dvipng
18600 (org-check-external-command
18601 "dvipng" "needed to convert LaTeX fragments to images")
18602 #'org-create-formula-image-with-dvipng)
18603 ('imagemagick
18604 (org-check-external-command
18605 "convert" "you need to install imagemagick")
18606 #'org-create-formula-image-with-imagemagick)
18607 (t (error
18608 "Invalid value of `org-latex-create-formula-image-program'")))
18609 string tofile options buffer))
18611 (declare-function org-export-get-backend "ox" (name))
18612 (declare-function org-export--get-global-options "ox" (&optional backend))
18613 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18614 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18615 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18616 (defun org-create-formula--latex-header ()
18617 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18618 (let ((info (org-combine-plists (org-export--get-global-options
18619 (org-export-get-backend 'latex))
18620 (org-export--get-inbuffer-options
18621 (org-export-get-backend 'latex)))))
18622 (org-latex-guess-babel-language
18623 (org-latex-guess-inputenc
18624 (org-splice-latex-header
18625 org-format-latex-header
18626 org-latex-default-packages-alist
18627 org-latex-packages-alist t
18628 (plist-get info :latex-header)))
18629 info)))
18631 ;; This function borrows from Ganesh Swami's latex2png.el
18632 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18633 "This calls dvipng."
18634 (require 'ox-latex)
18635 (let* ((tmpdir (if (featurep 'xemacs)
18636 (temp-directory)
18637 temporary-file-directory))
18638 (texfilebase (make-temp-name
18639 (expand-file-name "orgtex" tmpdir)))
18640 (texfile (concat texfilebase ".tex"))
18641 (dvifile (concat texfilebase ".dvi"))
18642 (pngfile (concat texfilebase ".png"))
18643 (fnh (if (featurep 'xemacs)
18644 (font-height (face-font 'default))
18645 (face-attribute 'default :height nil)))
18646 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18647 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18648 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18649 "Black"))
18650 (bg (or (plist-get options (if buffer :background :html-background))
18651 "Transparent")))
18652 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18653 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18654 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18655 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18656 (let ((latex-header (org-create-formula--latex-header)))
18657 (with-temp-file texfile
18658 (insert latex-header)
18659 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18660 (let ((dir default-directory))
18661 (condition-case nil
18662 (progn
18663 (cd tmpdir)
18664 (call-process "latex" nil nil nil texfile))
18665 (error nil))
18666 (cd dir))
18667 (if (not (file-exists-p dvifile))
18668 (progn (message "Failed to create dvi file from %s" texfile) nil)
18669 (condition-case nil
18670 (if (featurep 'xemacs)
18671 (call-process "dvipng" nil nil nil
18672 "-fg" fg "-bg" bg
18673 "-T" "tight"
18674 "-o" pngfile
18675 dvifile)
18676 (call-process "dvipng" nil nil nil
18677 "-fg" fg "-bg" bg
18678 "-D" dpi
18679 ;;"-x" scale "-y" scale
18680 "-T" "tight"
18681 "-o" pngfile
18682 dvifile))
18683 (error nil))
18684 (if (not (file-exists-p pngfile))
18685 (if org-format-latex-signal-error
18686 (error "Failed to create png file from %s" texfile)
18687 (message "Failed to create png file from %s" texfile)
18688 nil)
18689 ;; Use the requested file name and clean up
18690 (copy-file pngfile tofile 'replace)
18691 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18692 (if (file-exists-p (concat texfilebase e))
18693 (delete-file (concat texfilebase e))))
18694 pngfile))))
18696 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18697 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18698 "This calls convert, which is included into imagemagick."
18699 (require 'ox-latex)
18700 (let* ((tmpdir (if (featurep 'xemacs)
18701 (temp-directory)
18702 temporary-file-directory))
18703 (texfilebase (make-temp-name
18704 (expand-file-name "orgtex" tmpdir)))
18705 (texfile (concat texfilebase ".tex"))
18706 (pdffile (concat texfilebase ".pdf"))
18707 (pngfile (concat texfilebase ".png"))
18708 (fnh (if (featurep 'xemacs)
18709 (font-height (face-font 'default))
18710 (face-attribute 'default :height nil)))
18711 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18712 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18713 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18714 "black"))
18715 (bg (or (plist-get options (if buffer :background :html-background))
18716 "white")))
18717 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18718 (setq fg (org-latex-color-format fg)))
18719 (if (eq bg 'default) (setq bg (org-latex-color :background))
18720 (setq bg (org-latex-color-format
18721 (if (string= bg "Transparent") "white" bg))))
18722 (let ((latex-header (org-create-formula--latex-header)))
18723 (with-temp-file texfile
18724 (insert latex-header)
18725 (insert "\n\\begin{document}\n"
18726 "\\definecolor{fg}{rgb}{" fg "}\n"
18727 "\\definecolor{bg}{rgb}{" bg "}\n"
18728 "\n\\pagecolor{bg}\n"
18729 "\n{\\color{fg}\n"
18730 string
18731 "\n}\n"
18732 "\n\\end{document}\n")))
18733 (org-latex-compile texfile t)
18734 (if (not (file-exists-p pdffile))
18735 (progn (message "Failed to create pdf file from %s" texfile) nil)
18736 (condition-case nil
18737 (if (featurep 'xemacs)
18738 (call-process "convert" nil nil nil
18739 "-density" "96"
18740 "-trim"
18741 "-antialias"
18742 pdffile
18743 "-quality" "100"
18744 ;; "-sharpen" "0x1.0"
18745 pngfile)
18746 (call-process "convert" nil nil nil
18747 "-density" dpi
18748 "-trim"
18749 "-antialias"
18750 pdffile
18751 "-quality" "100"
18752 ;; "-sharpen" "0x1.0"
18753 pngfile))
18754 (error nil))
18755 (if (not (file-exists-p pngfile))
18756 (if org-format-latex-signal-error
18757 (error "Failed to create png file from %s" texfile)
18758 (message "Failed to create png file from %s" texfile)
18759 nil)
18760 ;; Use the requested file name and clean up
18761 (copy-file pngfile tofile 'replace)
18762 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18763 (if (file-exists-p (concat texfilebase e))
18764 (delete-file (concat texfilebase e))))
18765 pngfile))))
18767 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18768 "Fill a LaTeX header template TPL.
18769 In the template, the following place holders will be recognized:
18771 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18772 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18773 [PACKAGES] \\usepackage statements for PKG
18774 [NO-PACKAGES] do not include PKG
18775 [EXTRA] the string EXTRA
18776 [NO-EXTRA] do not include EXTRA
18778 For backward compatibility, if both the positive and the negative place
18779 holder is missing, the positive one (without the \"NO-\") will be
18780 assumed to be present at the end of the template.
18781 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18782 EXTRA is a string.
18783 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18784 (let (rpl (end ""))
18785 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18786 (setq rpl (if (or (match-end 1) (not def-pkg))
18787 "" (org-latex-packages-to-string def-pkg snippets-p t))
18788 tpl (replace-match rpl t t tpl))
18789 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18791 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18792 (setq rpl (if (or (match-end 1) (not pkg))
18793 "" (org-latex-packages-to-string pkg snippets-p t))
18794 tpl (replace-match rpl t t tpl))
18795 (if pkg (setq end
18796 (concat end "\n"
18797 (org-latex-packages-to-string pkg snippets-p)))))
18799 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18800 (setq rpl (if (or (match-end 1) (not extra))
18801 "" (concat extra "\n"))
18802 tpl (replace-match rpl t t tpl))
18803 (if (and extra (string-match "\\S-" extra))
18804 (setq end (concat end "\n" extra))))
18806 (if (string-match "\\S-" end)
18807 (concat tpl "\n" end)
18808 tpl)))
18810 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18811 "Turn an alist of packages into a string with the \\usepackage macros."
18812 (setq pkg (mapconcat (lambda(p)
18813 (cond
18814 ((stringp p) p)
18815 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18816 (format "%% Package %s omitted" (cadr p)))
18817 ((equal "" (car p))
18818 (format "\\usepackage{%s}" (cadr p)))
18820 (format "\\usepackage[%s]{%s}"
18821 (car p) (cadr p)))))
18823 "\n"))
18824 (if newline (concat pkg "\n") pkg))
18826 (defun org-dvipng-color (attr)
18827 "Return a RGB color specification for dvipng."
18828 (apply 'format "rgb %s %s %s"
18829 (mapcar 'org-normalize-color
18830 (if (featurep 'xemacs)
18831 (color-rgb-components
18832 (face-property 'default
18833 (cond ((eq attr :foreground) 'foreground)
18834 ((eq attr :background) 'background))))
18835 (color-values (face-attribute 'default attr nil))))))
18837 (defun org-dvipng-color-format (color-name)
18838 "Convert COLOR-NAME to a RGB color value for dvipng."
18839 (apply 'format "rgb %s %s %s"
18840 (mapcar 'org-normalize-color
18841 (color-values color-name))))
18843 (defun org-latex-color (attr)
18844 "Return a RGB color for the LaTeX color package."
18845 (apply 'format "%s,%s,%s"
18846 (mapcar 'org-normalize-color
18847 (if (featurep 'xemacs)
18848 (color-rgb-components
18849 (face-property 'default
18850 (cond ((eq attr :foreground) 'foreground)
18851 ((eq attr :background) 'background))))
18852 (color-values (face-attribute 'default attr nil))))))
18854 (defun org-latex-color-format (color-name)
18855 "Convert COLOR-NAME to a RGB color value."
18856 (apply 'format "%s,%s,%s"
18857 (mapcar 'org-normalize-color
18858 (color-values color-name))))
18860 (defun org-normalize-color (value)
18861 "Return string to be used as color value for an RGB component."
18862 (format "%g" (/ value 65535.0)))
18866 ;; Image display
18868 (defvar org-inline-image-overlays nil)
18869 (make-variable-buffer-local 'org-inline-image-overlays)
18871 (defun org-toggle-inline-images (&optional include-linked)
18872 "Toggle the display of inline images.
18873 INCLUDE-LINKED is passed to `org-display-inline-images'."
18874 (interactive "P")
18875 (if org-inline-image-overlays
18876 (progn
18877 (org-remove-inline-images)
18878 (message "Inline image display turned off"))
18879 (org-display-inline-images include-linked)
18880 (if (and (org-called-interactively-p)
18881 org-inline-image-overlays)
18882 (message "%d images displayed inline"
18883 (length org-inline-image-overlays))
18884 (message "No images to display inline"))))
18886 (defun org-redisplay-inline-images ()
18887 "Refresh the display of inline images."
18888 (interactive)
18889 (if (not org-inline-image-overlays)
18890 (org-toggle-inline-images)
18891 (org-toggle-inline-images)
18892 (org-toggle-inline-images)))
18894 (defun org-display-inline-images (&optional include-linked refresh beg end)
18895 "Display inline images.
18897 An inline image is a link which follows either of these
18898 conventions:
18900 1. Its path is a file with an extension matching return value
18901 from `image-file-name-regexp' and it has no contents.
18903 2. Its description consists in a single link of the previous
18904 type.
18906 When optional argument INCLUDE-LINKED is non-nil, also links with
18907 a text description part will be inlined. This can be nice for
18908 a quick look at those images, but it does not reflect what
18909 exported files will look like.
18911 When optional argument REFRESH is non-nil, refresh existing
18912 images between BEG and END. This will create new image displays
18913 only if necessary. BEG and END default to the buffer
18914 boundaries."
18915 (interactive "P")
18916 (when (display-graphic-p)
18917 (unless refresh
18918 (org-remove-inline-images)
18919 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18920 (org-with-wide-buffer
18921 (goto-char (or beg (point-min)))
18922 (let ((case-fold-search t)
18923 (file-extension-re (org-image-file-name-regexp)))
18924 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18925 (let ((link (save-match-data (org-element-context))))
18926 ;; Check if we're at an inline image.
18927 (when (and (equal (org-element-property :type link) "file")
18928 (or include-linked
18929 (not (org-element-property :contents-begin link)))
18930 (let ((parent (org-element-property :parent link)))
18931 (or (not (eq (org-element-type parent) 'link))
18932 (not (cdr (org-element-contents parent)))))
18933 (org-string-match-p file-extension-re
18934 (org-element-property :path link)))
18935 (let ((file (expand-file-name (org-element-property :path link))))
18936 (when (file-exists-p file)
18937 (let ((width
18938 ;; Apply `org-image-actual-width' specifications.
18939 (cond
18940 ((not (image-type-available-p 'imagemagick)) nil)
18941 ((eq org-image-actual-width t) nil)
18942 ((listp org-image-actual-width)
18944 ;; First try to find a width among
18945 ;; attributes associated to the paragraph
18946 ;; containing link.
18947 (let ((paragraph
18948 (let ((e link))
18949 (while (and (setq e (org-element-property
18950 :parent e))
18951 (not (eq (org-element-type e)
18952 'paragraph))))
18953 e)))
18954 (when paragraph
18955 (save-excursion
18956 (goto-char (org-element-property :begin paragraph))
18957 (when (save-match-data
18958 (re-search-forward
18959 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18960 (org-element-property
18961 :post-affiliated paragraph)
18963 (string-to-number (match-string 1))))))
18964 ;; Otherwise, fall-back to provided number.
18965 (car org-image-actual-width)))
18966 ((numberp org-image-actual-width)
18967 org-image-actual-width)))
18968 (old (get-char-property-and-overlay
18969 (org-element-property :begin link)
18970 'org-image-overlay)))
18971 (if (and (car-safe old) refresh)
18972 (image-refresh (overlay-get (cdr old) 'display))
18973 (let ((image (save-match-data
18974 (create-image file
18975 (and width 'imagemagick)
18977 :width width))))
18978 (when image
18979 (let* ((link
18980 ;; If inline image is the description
18981 ;; of another link, be sure to
18982 ;; consider the latter as the one to
18983 ;; apply the overlay on.
18984 (let ((parent
18985 (org-element-property :parent link)))
18986 (if (eq (org-element-type parent) 'link)
18987 parent
18988 link)))
18989 (ov (make-overlay
18990 (org-element-property :begin link)
18991 (progn
18992 (goto-char
18993 (org-element-property :end link))
18994 (skip-chars-backward " \t")
18995 (point)))))
18996 (overlay-put ov 'display image)
18997 (overlay-put ov 'face 'default)
18998 (overlay-put ov 'org-image-overlay t)
18999 (overlay-put
19000 ov 'modification-hooks
19001 (list 'org-display-inline-remove-overlay))
19002 (push ov org-inline-image-overlays)))))))))))))))
19004 (define-obsolete-function-alias
19005 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19007 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19008 "Remove inline-display overlay if a corresponding region is modified."
19009 (let ((inhibit-modification-hooks t))
19010 (when (and ov after)
19011 (delete ov org-inline-image-overlays)
19012 (delete-overlay ov))))
19014 (defun org-remove-inline-images ()
19015 "Remove inline display of images."
19016 (interactive)
19017 (mapc 'delete-overlay org-inline-image-overlays)
19018 (setq org-inline-image-overlays nil))
19020 ;;;; Key bindings
19022 ;; Outline functions from `outline-mode-prefix-map'
19023 ;; that can be remapped in Org:
19024 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19025 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19026 (define-key org-mode-map [remap outline-forward-same-level]
19027 'org-forward-heading-same-level)
19028 (define-key org-mode-map [remap outline-backward-same-level]
19029 'org-backward-heading-same-level)
19030 (define-key org-mode-map [remap show-branches]
19031 'org-kill-note-or-show-branches)
19032 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19033 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19034 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19036 ;; Outline functions from `outline-mode-prefix-map' that can not
19037 ;; be remapped in Org:
19039 ;; - the column "key binding" shows whether the Outline function is still
19040 ;; available in Org mode on the same key that it has been bound to in
19041 ;; Outline mode:
19042 ;; - "overridden": key used for a different functionality in Org mode
19043 ;; - else: key still bound to the same Outline function in Org mode
19045 ;; | Outline function | key binding | Org replacement |
19046 ;; |------------------------------------+-------------+-----------------------|
19047 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19048 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19049 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19050 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19051 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19052 ;; | `show-entry' | overridden | no replacement |
19053 ;; | `show-children' | `C-c C-i' | visibility cycling |
19054 ;; | `show-branches' | `C-c C-k' | still same function |
19055 ;; | `show-subtree' | overridden | visibility cycling |
19056 ;; | `show-all' | overridden | no replacement |
19057 ;; | `hide-subtree' | overridden | visibility cycling |
19058 ;; | `hide-body' | overridden | no replacement |
19059 ;; | `hide-entry' | overridden | visibility cycling |
19060 ;; | `hide-leaves' | overridden | no replacement |
19061 ;; | `hide-sublevels' | overridden | no replacement |
19062 ;; | `hide-other' | overridden | no replacement |
19064 ;; Make `C-c C-x' a prefix key
19065 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19067 ;; TAB key with modifiers
19068 (org-defkey org-mode-map "\C-i" 'org-cycle)
19069 (org-defkey org-mode-map [(tab)] 'org-cycle)
19070 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19071 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19072 ;; The following line is necessary under Suse GNU/Linux
19073 (unless (featurep 'xemacs)
19074 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19075 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19076 (define-key org-mode-map [backtab] 'org-shifttab)
19078 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19079 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19080 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19082 ;; Cursor keys with modifiers
19083 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19084 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19085 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19086 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19088 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19089 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19090 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19091 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19093 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19094 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19095 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19096 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19098 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19099 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19100 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19101 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19103 ;; Babel keys
19104 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19105 (mapc (lambda (pair)
19106 (define-key org-babel-map (car pair) (cdr pair)))
19107 org-babel-key-bindings)
19109 ;;; Extra keys for tty access.
19110 ;; We only set them when really needed because otherwise the
19111 ;; menus don't show the simple keys
19113 (when (or org-use-extra-keys
19114 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19115 (not window-system))
19116 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19117 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19118 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19119 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19120 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19121 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19122 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19123 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19124 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19125 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19126 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19127 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19128 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19129 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19130 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19131 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19132 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19133 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19134 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19135 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19136 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19137 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19138 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19139 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19140 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19141 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19142 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19143 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19145 ;; All the other keys
19147 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19148 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19149 (if (boundp 'narrow-map)
19150 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19151 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19152 (if (boundp 'narrow-map)
19153 (org-defkey narrow-map "b" 'org-narrow-to-block)
19154 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19155 (if (boundp 'narrow-map)
19156 (org-defkey narrow-map "e" 'org-narrow-to-element)
19157 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19158 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19159 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19160 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19161 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19162 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19163 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19164 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19165 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19166 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19167 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19168 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19169 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19170 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19171 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19172 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19173 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19174 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19175 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19176 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19177 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19178 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19179 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19180 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19181 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19182 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19183 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19184 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19185 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19186 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19187 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19188 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19189 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19190 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19191 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19192 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19193 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19194 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19195 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19196 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19197 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19198 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19199 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19200 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19201 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19202 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19203 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19204 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19205 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19206 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19207 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19208 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19209 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19210 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19211 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19212 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19213 (org-defkey org-mode-map "\C-c^" 'org-sort)
19214 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19215 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19216 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19217 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19218 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19219 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19220 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19221 (org-defkey org-mode-map "\C-m" 'org-return)
19222 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19223 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19224 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19225 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19226 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19227 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19228 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19229 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19230 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19231 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19232 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19233 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19234 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19235 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19236 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19237 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19238 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19239 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19240 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19241 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19242 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19243 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19244 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19246 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19247 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19248 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19250 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19251 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19252 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19253 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19254 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19255 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19256 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19257 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19258 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19259 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19260 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19261 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19262 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19263 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19264 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19265 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19266 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19267 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19268 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19269 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19270 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19271 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19272 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19274 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19275 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19276 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19277 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19278 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19280 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19282 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19284 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19285 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19287 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19290 (when (featurep 'xemacs)
19291 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19294 (defconst org-speed-commands-default
19296 ("Outline Navigation")
19297 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19298 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19299 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19300 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19301 ("F" . org-next-block)
19302 ("B" . org-previous-block)
19303 ("u" . (org-speed-move-safe 'outline-up-heading))
19304 ("j" . org-goto)
19305 ("g" . (org-refile t))
19306 ("Outline Visibility")
19307 ("c" . org-cycle)
19308 ("C" . org-shifttab)
19309 (" " . org-display-outline-path)
19310 ("s" . org-narrow-to-subtree)
19311 ("=" . org-columns)
19312 ("Outline Structure Editing")
19313 ("U" . org-shiftmetaup)
19314 ("D" . org-shiftmetadown)
19315 ("r" . org-metaright)
19316 ("l" . org-metaleft)
19317 ("R" . org-shiftmetaright)
19318 ("L" . org-shiftmetaleft)
19319 ("i" . (progn (forward-char 1) (call-interactively
19320 'org-insert-heading-respect-content)))
19321 ("^" . org-sort)
19322 ("w" . org-refile)
19323 ("a" . org-archive-subtree-default-with-confirmation)
19324 ("@" . org-mark-subtree)
19325 ("#" . org-toggle-comment)
19326 ("Clock Commands")
19327 ("I" . org-clock-in)
19328 ("O" . org-clock-out)
19329 ("Meta Data Editing")
19330 ("t" . org-todo)
19331 ("," . (org-priority))
19332 ("0" . (org-priority ?\ ))
19333 ("1" . (org-priority ?A))
19334 ("2" . (org-priority ?B))
19335 ("3" . (org-priority ?C))
19336 (":" . org-set-tags-command)
19337 ("e" . org-set-effort)
19338 ("E" . org-inc-effort)
19339 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19340 (org-entry-put (point) "APPT_WARNTIME" m)))
19341 ("Agenda Views etc")
19342 ("v" . org-agenda)
19343 ("/" . org-sparse-tree)
19344 ("Misc")
19345 ("o" . org-open-at-point)
19346 ("?" . org-speed-command-help)
19347 ("<" . (org-agenda-set-restriction-lock 'subtree))
19348 (">" . (org-agenda-remove-restriction-lock))
19350 "The default speed commands.")
19352 (defun org-print-speed-command (e)
19353 (if (> (length (car e)) 1)
19354 (progn
19355 (princ "\n")
19356 (princ (car e))
19357 (princ "\n")
19358 (princ (make-string (length (car e)) ?-))
19359 (princ "\n"))
19360 (princ (car e))
19361 (princ " ")
19362 (if (symbolp (cdr e))
19363 (princ (symbol-name (cdr e)))
19364 (prin1 (cdr e)))
19365 (princ "\n")))
19367 (defun org-speed-command-help ()
19368 "Show the available speed commands."
19369 (interactive)
19370 (if (not org-use-speed-commands)
19371 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19372 (with-output-to-temp-buffer "*Help*"
19373 (princ "User-defined Speed commands\n===========================\n")
19374 (mapc 'org-print-speed-command org-speed-commands-user)
19375 (princ "\n")
19376 (princ "Built-in Speed commands\n=======================\n")
19377 (mapc 'org-print-speed-command org-speed-commands-default))
19378 (with-current-buffer "*Help*"
19379 (setq truncate-lines t))))
19381 (defun org-speed-move-safe (cmd)
19382 "Execute CMD, but make sure that the cursor always ends up in a headline.
19383 If not, return to the original position and throw an error."
19384 (interactive)
19385 (let ((pos (point)))
19386 (call-interactively cmd)
19387 (unless (and (bolp) (org-at-heading-p))
19388 (goto-char pos)
19389 (error "Boundary reached while executing %s" cmd))))
19391 (defvar org-self-insert-command-undo-counter 0)
19393 (defvar org-table-auto-blank-field) ; defined in org-table.el
19394 (defvar org-speed-command nil)
19396 (define-obsolete-function-alias
19397 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19399 (defun org-speed-command-activate (keys)
19400 "Hook for activating single-letter speed commands.
19401 `org-speed-commands-default' specifies a minimal command set.
19402 Use `org-speed-commands-user' for further customization."
19403 (when (or (and (bolp) (looking-at org-outline-regexp))
19404 (and (functionp org-use-speed-commands)
19405 (funcall org-use-speed-commands)))
19406 (cdr (assoc keys (append org-speed-commands-user
19407 org-speed-commands-default)))))
19409 (define-obsolete-function-alias
19410 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19412 (defun org-babel-speed-command-activate (keys)
19413 "Hook for activating single-letter code block commands."
19414 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19415 (cdr (assoc keys org-babel-key-bindings))))
19417 (defcustom org-speed-command-hook
19418 '(org-speed-command-default-hook org-babel-speed-command-hook)
19419 "Hook for activating speed commands at strategic locations.
19420 Hook functions are called in sequence until a valid handler is
19421 found.
19423 Each hook takes a single argument, a user-pressed command key
19424 which is also a `self-insert-command' from the global map.
19426 Within the hook, examine the cursor position and the command key
19427 and return nil or a valid handler as appropriate. Handler could
19428 be one of an interactive command, a function, or a form.
19430 Set `org-use-speed-commands' to non-nil value to enable this
19431 hook. The default setting is `org-speed-command-activate'."
19432 :group 'org-structure
19433 :version "24.1"
19434 :type 'hook)
19436 (defun org-self-insert-command (N)
19437 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19438 If the cursor is in a table looking at whitespace, the whitespace is
19439 overwritten, and the table is not marked as requiring realignment."
19440 (interactive "p")
19441 (org-check-before-invisible-edit 'insert)
19442 (cond
19443 ((and org-use-speed-commands
19444 (setq org-speed-command
19445 (run-hook-with-args-until-success
19446 'org-speed-command-hook (this-command-keys))))
19447 (cond
19448 ((commandp org-speed-command)
19449 (setq this-command org-speed-command)
19450 (call-interactively org-speed-command))
19451 ((functionp org-speed-command)
19452 (funcall org-speed-command))
19453 ((and org-speed-command (listp org-speed-command))
19454 (eval org-speed-command))
19455 (t (let (org-use-speed-commands)
19456 (call-interactively 'org-self-insert-command)))))
19457 ((and
19458 (org-table-p)
19459 (progn
19460 ;; check if we blank the field, and if that triggers align
19461 (and (featurep 'org-table) org-table-auto-blank-field
19462 (member last-command
19463 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19464 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19465 ;; got extra space, this field does not determine column width
19466 (let (org-table-may-need-update) (org-table-blank-field))
19467 ;; no extra space, this field may determine column width
19468 (org-table-blank-field)))
19470 (eq N 1)
19471 (looking-at "[^|\n]* |"))
19472 (let (org-table-may-need-update)
19473 (goto-char (1- (match-end 0)))
19474 (backward-delete-char 1)
19475 (goto-char (match-beginning 0))
19476 (self-insert-command N)))
19478 (setq org-table-may-need-update t)
19479 (self-insert-command N)
19480 (org-fix-tags-on-the-fly)
19481 (if org-self-insert-cluster-for-undo
19482 (if (not (eq last-command 'org-self-insert-command))
19483 (setq org-self-insert-command-undo-counter 1)
19484 (if (>= org-self-insert-command-undo-counter 20)
19485 (setq org-self-insert-command-undo-counter 1)
19486 (and (> org-self-insert-command-undo-counter 0)
19487 buffer-undo-list (listp buffer-undo-list)
19488 (not (cadr buffer-undo-list)) ; remove nil entry
19489 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19490 (setq org-self-insert-command-undo-counter
19491 (1+ org-self-insert-command-undo-counter))))))))
19493 (defun org-check-before-invisible-edit (kind)
19494 "Check is editing if kind KIND would be dangerous with invisible text around.
19495 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19496 ;; First, try to get out of here as quickly as possible, to reduce overhead
19497 (if (and org-catch-invisible-edits
19498 (or (not (boundp 'visible-mode)) (not visible-mode))
19499 (or (get-char-property (point) 'invisible)
19500 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19501 ;; OK, we need to take a closer look
19502 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19503 (invisible-before-point (if (bobp) nil (get-char-property
19504 (1- (point)) 'invisible)))
19505 (border-and-ok-direction
19507 ;; Check if we are acting predictably before invisible text
19508 (and invisible-at-point (not invisible-before-point)
19509 (memq kind '(insert delete-backward)))
19510 ;; Check if we are acting predictably after invisible text
19511 ;; This works not well, and I have turned it off. It seems
19512 ;; better to always show and stop after invisible text.
19513 ;; (and (not invisible-at-point) invisible-before-point
19514 ;; (memq kind '(insert delete)))
19516 (when (or (memq invisible-at-point '(outline org-hide-block t))
19517 (memq invisible-before-point '(outline org-hide-block t)))
19518 (if (eq org-catch-invisible-edits 'error)
19519 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19520 (if (and org-custom-properties-overlays
19521 (y-or-n-p "Display invisible properties in this buffer? "))
19522 (org-toggle-custom-properties-visibility)
19523 ;; Make the area visible
19524 (save-excursion
19525 (if invisible-before-point
19526 (goto-char (previous-single-char-property-change
19527 (point) 'invisible)))
19528 (org-cycle))
19529 (cond
19530 ((eq org-catch-invisible-edits 'show)
19531 ;; That's it, we do the edit after showing
19532 (message
19533 "Unfolding invisible region around point before editing")
19534 (sit-for 1))
19535 ((and (eq org-catch-invisible-edits 'smart)
19536 border-and-ok-direction)
19537 (message "Unfolding invisible region around point before editing"))
19539 ;; Don't do the edit, make the user repeat it in full visibility
19540 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19542 (defun org-fix-tags-on-the-fly ()
19543 (when (and (equal (char-after (point-at-bol)) ?*)
19544 (org-at-heading-p))
19545 (org-align-tags-here org-tags-column)))
19547 (defun org-delete-backward-char (N)
19548 "Like `delete-backward-char', insert whitespace at field end in tables.
19549 When deleting backwards, in tables this function will insert whitespace in
19550 front of the next \"|\" separator, to keep the table aligned. The table will
19551 still be marked for re-alignment if the field did fill the entire column,
19552 because, in this case the deletion might narrow the column."
19553 (interactive "p")
19554 (save-match-data
19555 (org-check-before-invisible-edit 'delete-backward)
19556 (if (and (org-table-p)
19557 (eq N 1)
19558 (string-match "|" (buffer-substring (point-at-bol) (point)))
19559 (looking-at ".*?|"))
19560 (let ((pos (point))
19561 (noalign (looking-at "[^|\n\r]* |"))
19562 (c org-table-may-need-update))
19563 (backward-delete-char N)
19564 (if (not overwrite-mode)
19565 (progn
19566 (skip-chars-forward "^|")
19567 (insert " ")
19568 (goto-char (1- pos))))
19569 ;; noalign: if there were two spaces at the end, this field
19570 ;; does not determine the width of the column.
19571 (if noalign (setq org-table-may-need-update c)))
19572 (backward-delete-char N)
19573 (org-fix-tags-on-the-fly))))
19575 (defun org-delete-char (N)
19576 "Like `delete-char', but insert whitespace at field end in tables.
19577 When deleting characters, in tables this function will insert whitespace in
19578 front of the next \"|\" separator, to keep the table aligned. The table will
19579 still be marked for re-alignment if the field did fill the entire column,
19580 because, in this case the deletion might narrow the column."
19581 (interactive "p")
19582 (save-match-data
19583 (org-check-before-invisible-edit 'delete)
19584 (if (and (org-table-p)
19585 (not (bolp))
19586 (not (= (char-after) ?|))
19587 (eq N 1))
19588 (if (looking-at ".*?|")
19589 (let ((pos (point))
19590 (noalign (looking-at "[^|\n\r]* |"))
19591 (c org-table-may-need-update))
19592 (replace-match
19593 (concat (substring (match-string 0) 1 -1) " |") nil t)
19594 (goto-char pos)
19595 ;; noalign: if there were two spaces at the end, this field
19596 ;; does not determine the width of the column.
19597 (if noalign (setq org-table-may-need-update c)))
19598 (delete-char N))
19599 (delete-char N)
19600 (org-fix-tags-on-the-fly))))
19602 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19603 (put 'org-self-insert-command 'delete-selection
19604 (lambda ()
19605 (not (run-hook-with-args-until-success
19606 'self-insert-uses-region-functions))))
19607 (put 'orgtbl-self-insert-command 'delete-selection
19608 (lambda ()
19609 (not (run-hook-with-args-until-success
19610 'self-insert-uses-region-functions))))
19611 (put 'org-delete-char 'delete-selection 'supersede)
19612 (put 'org-delete-backward-char 'delete-selection 'supersede)
19613 (put 'org-yank 'delete-selection 'yank)
19615 ;; Make `flyspell-mode' delay after some commands
19616 (put 'org-self-insert-command 'flyspell-delayed t)
19617 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19618 (put 'org-delete-char 'flyspell-delayed t)
19619 (put 'org-delete-backward-char 'flyspell-delayed t)
19621 ;; Make pabbrev-mode expand after org-mode commands
19622 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19623 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19625 (defun org-remap (map &rest commands)
19626 "In MAP, remap the functions given in COMMANDS.
19627 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19628 (let (new old)
19629 (while commands
19630 (setq old (pop commands) new (pop commands))
19631 (if (fboundp 'command-remapping)
19632 (org-defkey map (vector 'remap old) new)
19633 (substitute-key-definition old new map global-map)))))
19635 (defun org-transpose-words ()
19636 "Transpose words for Org.
19637 This uses the `org-mode-transpose-word-syntax-table' syntax
19638 table, which interprets characters in `org-emphasis-alist' as
19639 word constituents."
19640 (interactive)
19641 (with-syntax-table org-mode-transpose-word-syntax-table
19642 (call-interactively 'transpose-words)))
19643 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19645 (when (eq org-enable-table-editor 'optimized)
19646 ;; If the user wants maximum table support, we need to hijack
19647 ;; some standard editing functions
19648 (org-remap org-mode-map
19649 'self-insert-command 'org-self-insert-command
19650 'delete-char 'org-delete-char
19651 'delete-backward-char 'org-delete-backward-char)
19652 (org-defkey org-mode-map "|" 'org-force-self-insert))
19654 (defvar org-ctrl-c-ctrl-c-hook nil
19655 "Hook for functions attaching themselves to `C-c C-c'.
19657 This can be used to add additional functionality to the C-c C-c
19658 key which executes context-dependent commands. This hook is run
19659 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19660 run after the last test.
19662 Each function will be called with no arguments. The function
19663 must check if the context is appropriate for it to act. If yes,
19664 it should do its thing and then return a non-nil value. If the
19665 context is wrong, just do nothing and return nil.")
19667 (defvar org-ctrl-c-ctrl-c-final-hook nil
19668 "Hook for functions attaching themselves to `C-c C-c'.
19670 This can be used to add additional functionality to the C-c C-c
19671 key which executes context-dependent commands. This hook is run
19672 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19673 before the first test.
19675 Each function will be called with no arguments. The function
19676 must check if the context is appropriate for it to act. If yes,
19677 it should do its thing and then return a non-nil value. If the
19678 context is wrong, just do nothing and return nil.")
19680 (defvar org-tab-first-hook nil
19681 "Hook for functions to attach themselves to TAB.
19682 See `org-ctrl-c-ctrl-c-hook' for more information.
19683 This hook runs as the first action when TAB is pressed, even before
19684 `org-cycle' messes around with the `outline-regexp' to cater for
19685 inline tasks and plain list item folding.
19686 If any function in this hook returns t, any other actions that
19687 would have been caused by TAB (such as table field motion or visibility
19688 cycling) will not occur.")
19690 (defvar org-tab-after-check-for-table-hook nil
19691 "Hook for functions to attach themselves to TAB.
19692 See `org-ctrl-c-ctrl-c-hook' for more information.
19693 This hook runs after it has been established that the cursor is not in a
19694 table, but before checking if the cursor is in a headline or if global cycling
19695 should be done.
19696 If any function in this hook returns t, not other actions like visibility
19697 cycling will be done.")
19699 (defvar org-tab-after-check-for-cycling-hook nil
19700 "Hook for functions to attach themselves to TAB.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.
19702 This hook runs after it has been established that not table field motion and
19703 not visibility should be done because of current context. This is probably
19704 the place where a package like yasnippets can hook in.")
19706 (defvar org-tab-before-tab-emulation-hook nil
19707 "Hook for functions to attach themselves to TAB.
19708 See `org-ctrl-c-ctrl-c-hook' for more information.
19709 This hook runs after every other options for TAB have been exhausted, but
19710 before indentation and \t insertion takes place.")
19712 (defvar org-metaleft-hook nil
19713 "Hook for functions attaching themselves to `M-left'.
19714 See `org-ctrl-c-ctrl-c-hook' for more information.")
19715 (defvar org-metaright-hook nil
19716 "Hook for functions attaching themselves to `M-right'.
19717 See `org-ctrl-c-ctrl-c-hook' for more information.")
19718 (defvar org-metaup-hook nil
19719 "Hook for functions attaching themselves to `M-up'.
19720 See `org-ctrl-c-ctrl-c-hook' for more information.")
19721 (defvar org-metadown-hook nil
19722 "Hook for functions attaching themselves to `M-down'.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.")
19724 (defvar org-shiftmetaleft-hook nil
19725 "Hook for functions attaching themselves to `M-S-left'.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-shiftmetaright-hook nil
19728 "Hook for functions attaching themselves to `M-S-right'.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-shiftmetaup-hook nil
19731 "Hook for functions attaching themselves to `M-S-up'.
19732 See `org-ctrl-c-ctrl-c-hook' for more information.")
19733 (defvar org-shiftmetadown-hook nil
19734 "Hook for functions attaching themselves to `M-S-down'.
19735 See `org-ctrl-c-ctrl-c-hook' for more information.")
19736 (defvar org-metareturn-hook nil
19737 "Hook for functions attaching themselves to `M-RET'.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftup-hook nil
19740 "Hook for functions attaching themselves to `S-up'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-shiftup-final-hook nil
19743 "Hook for functions attaching themselves to `S-up'.
19744 This one runs after all other options except shift-select have been excluded.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.")
19746 (defvar org-shiftdown-hook nil
19747 "Hook for functions attaching themselves to `S-down'.
19748 See `org-ctrl-c-ctrl-c-hook' for more information.")
19749 (defvar org-shiftdown-final-hook nil
19750 "Hook for functions attaching themselves to `S-down'.
19751 This one runs after all other options except shift-select have been excluded.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-shiftleft-hook nil
19754 "Hook for functions attaching themselves to `S-left'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-shiftleft-final-hook nil
19757 "Hook for functions attaching themselves to `S-left'.
19758 This one runs after all other options except shift-select have been excluded.
19759 See `org-ctrl-c-ctrl-c-hook' for more information.")
19760 (defvar org-shiftright-hook nil
19761 "Hook for functions attaching themselves to `S-right'.
19762 See `org-ctrl-c-ctrl-c-hook' for more information.")
19763 (defvar org-shiftright-final-hook nil
19764 "Hook for functions attaching themselves to `S-right'.
19765 This one runs after all other options except shift-select have been excluded.
19766 See `org-ctrl-c-ctrl-c-hook' for more information.")
19768 (defun org-modifier-cursor-error ()
19769 "Throw an error, a modified cursor command was applied in wrong context."
19770 (user-error "This command is active in special context like tables, headlines or items"))
19772 (defun org-shiftselect-error ()
19773 "Throw an error because Shift-Cursor command was applied in wrong context."
19774 (if (and (boundp 'shift-select-mode) shift-select-mode)
19775 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19776 (user-error "This command works only in special context like headlines or timestamps")))
19778 (defun org-call-for-shift-select (cmd)
19779 (let ((this-command-keys-shift-translated t))
19780 (call-interactively cmd)))
19782 (defun org-shifttab (&optional arg)
19783 "Global visibility cycling or move to previous table field.
19784 Call `org-table-previous-field' within a table.
19785 When ARG is nil, cycle globally through visibility states.
19786 When ARG is a numeric prefix, show contents of this level."
19787 (interactive "P")
19788 (cond
19789 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19790 ((integerp arg)
19791 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19792 (message "Content view to level: %d" arg)
19793 (org-content (prefix-numeric-value arg2))
19794 (org-cycle-show-empty-lines t)
19795 (setq org-cycle-global-status 'overview)))
19796 (t (call-interactively 'org-global-cycle))))
19798 (defun org-shiftmetaleft ()
19799 "Promote subtree or delete table column.
19800 Calls `org-promote-subtree', `org-outdent-item-tree', or
19801 `org-table-delete-column', depending on context. See the
19802 individual commands for more information."
19803 (interactive)
19804 (cond
19805 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19806 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19807 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19808 ((if (not (org-region-active-p)) (org-at-item-p)
19809 (save-excursion (goto-char (region-beginning))
19810 (org-at-item-p)))
19811 (call-interactively 'org-outdent-item-tree))
19812 (t (org-modifier-cursor-error))))
19814 (defun org-shiftmetaright ()
19815 "Demote subtree or insert table column.
19816 Calls `org-demote-subtree', `org-indent-item-tree', or
19817 `org-table-insert-column', depending on context. See the
19818 individual commands for more information."
19819 (interactive)
19820 (cond
19821 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19822 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19823 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19824 ((if (not (org-region-active-p)) (org-at-item-p)
19825 (save-excursion (goto-char (region-beginning))
19826 (org-at-item-p)))
19827 (call-interactively 'org-indent-item-tree))
19828 (t (org-modifier-cursor-error))))
19830 (defun org-shiftmetaup (&optional arg)
19831 "Move subtree up or kill table row.
19832 Calls `org-move-subtree-up' or `org-table-kill-row' or
19833 `org-move-item-up' or `org-timestamp-up', depending on context.
19834 See the individual commands for more information."
19835 (interactive "P")
19836 (cond
19837 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19838 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19839 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19840 ((org-at-item-p) (call-interactively 'org-move-item-up))
19841 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19842 (call-interactively 'org-timestamp-up)))
19843 (t (call-interactively 'org-drag-line-backward))))
19845 (defun org-shiftmetadown (&optional arg)
19846 "Move subtree down or insert table row.
19847 Calls `org-move-subtree-down' or `org-table-insert-row' or
19848 `org-move-item-down' or `org-timestamp-up', depending on context.
19849 See the individual commands for more information."
19850 (interactive "P")
19851 (cond
19852 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19853 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19854 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19855 ((org-at-item-p) (call-interactively 'org-move-item-down))
19856 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19857 (call-interactively 'org-timestamp-down)))
19858 (t (call-interactively 'org-drag-line-forward))))
19860 (defsubst org-hidden-tree-error ()
19861 (user-error
19862 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19864 (defun org-metaleft (&optional arg)
19865 "Promote heading or move table column to left.
19866 Calls `org-do-promote' or `org-table-move-column', depending on context.
19867 With no specific context, calls the Emacs default `backward-word'.
19868 See the individual commands for more information."
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-metaleft-hook))
19872 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19873 ((org-with-limited-levels
19874 (or (org-at-heading-p)
19875 (and (org-region-active-p)
19876 (save-excursion
19877 (goto-char (region-beginning))
19878 (org-at-heading-p)))))
19879 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19880 (call-interactively 'org-do-promote))
19881 ;; At an inline task.
19882 ((org-at-heading-p)
19883 (call-interactively 'org-inlinetask-promote))
19884 ((or (org-at-item-p)
19885 (and (org-region-active-p)
19886 (save-excursion
19887 (goto-char (region-beginning))
19888 (org-at-item-p))))
19889 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19890 (call-interactively 'org-outdent-item))
19891 (t (call-interactively 'backward-word))))
19893 (defun org-metaright (&optional arg)
19894 "Demote a subtree, a list item or move table column to right.
19895 In front of a drawer or a block keyword, indent it correctly.
19896 With no specific context, calls the Emacs default `forward-word'.
19897 See the individual commands for more information."
19898 (interactive "P")
19899 (cond
19900 ((run-hook-with-args-until-success 'org-metaright-hook))
19901 ((org-at-table-p) (call-interactively 'org-table-move-column))
19902 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19903 ((org-at-block-p) (call-interactively 'org-indent-block))
19904 ((org-with-limited-levels
19905 (or (org-at-heading-p)
19906 (and (org-region-active-p)
19907 (save-excursion
19908 (goto-char (region-beginning))
19909 (org-at-heading-p)))))
19910 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19911 (call-interactively 'org-do-demote))
19912 ;; At an inline task.
19913 ((org-at-heading-p)
19914 (call-interactively 'org-inlinetask-demote))
19915 ((or (org-at-item-p)
19916 (and (org-region-active-p)
19917 (save-excursion
19918 (goto-char (region-beginning))
19919 (org-at-item-p))))
19920 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19921 (call-interactively 'org-indent-item))
19922 (t (call-interactively 'forward-word))))
19924 (defun org-check-for-hidden (what)
19925 "Check if there are hidden headlines/items in the current visual line.
19926 WHAT can be either `headlines' or `items'. If the current line is
19927 an outline or item heading and it has a folded subtree below it,
19928 this function returns t, nil otherwise."
19929 (let ((re (cond
19930 ((eq what 'headlines) org-outline-regexp-bol)
19931 ((eq what 'items) (org-item-beginning-re))
19932 (t (error "This should not happen"))))
19933 beg end)
19934 (save-excursion
19935 (catch 'exit
19936 (unless (org-region-active-p)
19937 (setq beg (point-at-bol))
19938 (beginning-of-line 2)
19939 (while (and (not (eobp)) ;; this is like `next-line'
19940 (get-char-property (1- (point)) 'invisible))
19941 (beginning-of-line 2))
19942 (setq end (point))
19943 (goto-char beg)
19944 (goto-char (point-at-eol))
19945 (setq end (max end (point)))
19946 (while (re-search-forward re end t)
19947 (if (get-char-property (match-beginning 0) 'invisible)
19948 (throw 'exit t))))
19949 nil))))
19951 (defun org-metaup (&optional arg)
19952 "Move subtree up or move table row up.
19953 Calls `org-move-subtree-up' or `org-table-move-row' or
19954 `org-move-item-up', depending on context. See the individual commands
19955 for more information."
19956 (interactive "P")
19957 (cond
19958 ((run-hook-with-args-until-success 'org-metaup-hook))
19959 ((org-region-active-p)
19960 (let* ((a (min (region-beginning) (region-end)))
19961 (b (1- (max (region-beginning) (region-end))))
19962 (c (save-excursion (goto-char a)
19963 (move-beginning-of-line 0)))
19964 (d (save-excursion (goto-char a)
19965 (move-end-of-line 0) (point))))
19966 (transpose-regions a b c d)
19967 (goto-char c)))
19968 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19969 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19970 ((org-at-item-p) (call-interactively 'org-move-item-up))
19971 (t (org-drag-element-backward))))
19973 (defun org-metadown (&optional arg)
19974 "Move subtree down or move table row down.
19975 Calls `org-move-subtree-down' or `org-table-move-row' or
19976 `org-move-item-down', depending on context. See the individual
19977 commands for more information."
19978 (interactive "P")
19979 (cond
19980 ((run-hook-with-args-until-success 'org-metadown-hook))
19981 ((org-region-active-p)
19982 (let* ((a (min (region-beginning) (region-end)))
19983 (b (max (region-beginning) (region-end)))
19984 (c (save-excursion (goto-char b)
19985 (move-beginning-of-line 1)))
19986 (d (save-excursion (goto-char b)
19987 (move-end-of-line 1) (1+ (point)))))
19988 (transpose-regions a b c d)
19989 (goto-char d)))
19990 ((org-at-table-p) (call-interactively 'org-table-move-row))
19991 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19992 ((org-at-item-p) (call-interactively 'org-move-item-down))
19993 (t (org-drag-element-forward))))
19995 (defun org-shiftup (&optional arg)
19996 "Increase item in timestamp or increase priority of current headline.
19997 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19998 depending on context. See the individual commands for more information."
19999 (interactive "P")
20000 (cond
20001 ((run-hook-with-args-until-success 'org-shiftup-hook))
20002 ((and org-support-shift-select (org-region-active-p))
20003 (org-call-for-shift-select 'previous-line))
20004 ((org-at-timestamp-p t)
20005 (call-interactively (if org-edit-timestamp-down-means-later
20006 'org-timestamp-down 'org-timestamp-up)))
20007 ((and (not (eq org-support-shift-select 'always))
20008 org-enable-priority-commands
20009 (org-at-heading-p))
20010 (call-interactively 'org-priority-up))
20011 ((and (not org-support-shift-select) (org-at-item-p))
20012 (call-interactively 'org-previous-item))
20013 ((org-clocktable-try-shift 'up arg))
20014 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20015 (org-support-shift-select
20016 (org-call-for-shift-select 'previous-line))
20017 (t (org-shiftselect-error))))
20019 (defun org-shiftdown (&optional arg)
20020 "Decrease item in timestamp or decrease priority of current headline.
20021 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20022 depending on context. See the individual commands for more information."
20023 (interactive "P")
20024 (cond
20025 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20026 ((and org-support-shift-select (org-region-active-p))
20027 (org-call-for-shift-select 'next-line))
20028 ((org-at-timestamp-p t)
20029 (call-interactively (if org-edit-timestamp-down-means-later
20030 'org-timestamp-up 'org-timestamp-down)))
20031 ((and (not (eq org-support-shift-select 'always))
20032 org-enable-priority-commands
20033 (org-at-heading-p))
20034 (call-interactively 'org-priority-down))
20035 ((and (not org-support-shift-select) (org-at-item-p))
20036 (call-interactively 'org-next-item))
20037 ((org-clocktable-try-shift 'down arg))
20038 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20039 (org-support-shift-select
20040 (org-call-for-shift-select 'next-line))
20041 (t (org-shiftselect-error))))
20043 (defun org-shiftright (&optional arg)
20044 "Cycle the thing at point or in the current line, depending on context.
20045 Depending on context, this does one of the following:
20047 - switch a timestamp at point one day into the future
20048 - on a headline, switch to the next TODO keyword.
20049 - on an item, switch entire list to the next bullet type
20050 - on a property line, switch to the next allowed value
20051 - on a clocktable definition line, move time block into the future"
20052 (interactive "P")
20053 (cond
20054 ((run-hook-with-args-until-success 'org-shiftright-hook))
20055 ((and org-support-shift-select (org-region-active-p))
20056 (org-call-for-shift-select 'forward-char))
20057 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20058 ((and (not (eq org-support-shift-select 'always))
20059 (org-at-heading-p))
20060 (let ((org-inhibit-logging
20061 (not org-treat-S-cursor-todo-selection-as-state-change))
20062 (org-inhibit-blocking
20063 (not org-treat-S-cursor-todo-selection-as-state-change)))
20064 (org-call-with-arg 'org-todo 'right)))
20065 ((or (and org-support-shift-select
20066 (not (eq org-support-shift-select 'always))
20067 (org-at-item-bullet-p))
20068 (and (not org-support-shift-select) (org-at-item-p)))
20069 (org-call-with-arg 'org-cycle-list-bullet nil))
20070 ((and (not (eq org-support-shift-select 'always))
20071 (org-at-property-p))
20072 (call-interactively 'org-property-next-allowed-value))
20073 ((org-clocktable-try-shift 'right arg))
20074 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20075 (org-support-shift-select
20076 (org-call-for-shift-select 'forward-char))
20077 (t (org-shiftselect-error))))
20079 (defun org-shiftleft (&optional arg)
20080 "Cycle the thing at point or in the current line, depending on context.
20081 Depending on context, this does one of the following:
20083 - switch a timestamp at point one day into the past
20084 - on a headline, switch to the previous TODO keyword.
20085 - on an item, switch entire list to the previous bullet type
20086 - on a property line, switch to the previous allowed value
20087 - on a clocktable definition line, move time block into the past"
20088 (interactive "P")
20089 (cond
20090 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20091 ((and org-support-shift-select (org-region-active-p))
20092 (org-call-for-shift-select 'backward-char))
20093 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20094 ((and (not (eq org-support-shift-select 'always))
20095 (org-at-heading-p))
20096 (let ((org-inhibit-logging
20097 (not org-treat-S-cursor-todo-selection-as-state-change))
20098 (org-inhibit-blocking
20099 (not org-treat-S-cursor-todo-selection-as-state-change)))
20100 (org-call-with-arg 'org-todo 'left)))
20101 ((or (and org-support-shift-select
20102 (not (eq org-support-shift-select 'always))
20103 (org-at-item-bullet-p))
20104 (and (not org-support-shift-select) (org-at-item-p)))
20105 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20106 ((and (not (eq org-support-shift-select 'always))
20107 (org-at-property-p))
20108 (call-interactively 'org-property-previous-allowed-value))
20109 ((org-clocktable-try-shift 'left arg))
20110 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20111 (org-support-shift-select
20112 (org-call-for-shift-select 'backward-char))
20113 (t (org-shiftselect-error))))
20115 (defun org-shiftcontrolright ()
20116 "Switch to next TODO set."
20117 (interactive)
20118 (cond
20119 ((and org-support-shift-select (org-region-active-p))
20120 (org-call-for-shift-select 'forward-word))
20121 ((and (not (eq org-support-shift-select 'always))
20122 (org-at-heading-p))
20123 (org-call-with-arg 'org-todo 'nextset))
20124 (org-support-shift-select
20125 (org-call-for-shift-select 'forward-word))
20126 (t (org-shiftselect-error))))
20128 (defun org-shiftcontrolleft ()
20129 "Switch to previous TODO set."
20130 (interactive)
20131 (cond
20132 ((and org-support-shift-select (org-region-active-p))
20133 (org-call-for-shift-select 'backward-word))
20134 ((and (not (eq org-support-shift-select 'always))
20135 (org-at-heading-p))
20136 (org-call-with-arg 'org-todo 'previousset))
20137 (org-support-shift-select
20138 (org-call-for-shift-select 'backward-word))
20139 (t (org-shiftselect-error))))
20141 (defun org-shiftcontrolup (&optional n)
20142 "Change timestamps synchronously up in CLOCK log lines.
20143 Optional argument N tells to change by that many units."
20144 (interactive "P")
20145 (cond ((and (not org-support-shift-select)
20146 (org-at-clock-log-p)
20147 (org-at-timestamp-p t))
20148 (org-clock-timestamps-up n))
20149 (t (org-shiftselect-error))))
20151 (defun org-shiftcontroldown (&optional n)
20152 "Change timestamps synchronously down in CLOCK log lines.
20153 Optional argument N tells to change by that many units."
20154 (interactive "P")
20155 (cond ((and (not org-support-shift-select)
20156 (org-at-clock-log-p)
20157 (org-at-timestamp-p t))
20158 (org-clock-timestamps-down n))
20159 (t (org-shiftselect-error))))
20161 (defun org-ctrl-c-ret ()
20162 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20163 (interactive)
20164 (cond
20165 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20166 (t (call-interactively 'org-insert-heading))))
20168 (defun org-find-visible ()
20169 (let ((s (point)))
20170 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20171 (get-char-property s 'invisible)))
20173 (defun org-find-invisible ()
20174 (let ((s (point)))
20175 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20176 (not (get-char-property s 'invisible))))
20179 (defun org-copy-visible (beg end)
20180 "Copy the visible parts of the region."
20181 (interactive "r")
20182 (let (snippets s)
20183 (save-excursion
20184 (save-restriction
20185 (narrow-to-region beg end)
20186 (setq s (goto-char (point-min)))
20187 (while (not (= (point) (point-max)))
20188 (goto-char (org-find-invisible))
20189 (push (buffer-substring s (point)) snippets)
20190 (setq s (goto-char (org-find-visible))))))
20191 (kill-new (apply 'concat (nreverse snippets)))))
20193 (defun org-copy-special ()
20194 "Copy region in table or copy current subtree.
20195 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20196 See the individual commands for more information."
20197 (interactive)
20198 (call-interactively
20199 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20201 (defun org-cut-special ()
20202 "Cut region in table or cut current subtree.
20203 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20204 See the individual commands for more information."
20205 (interactive)
20206 (call-interactively
20207 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20209 (defun org-paste-special (arg)
20210 "Paste rectangular region into table, or past subtree relative to level.
20211 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20212 See the individual commands for more information."
20213 (interactive "P")
20214 (if (org-at-table-p)
20215 (org-table-paste-rectangle)
20216 (org-paste-subtree arg)))
20218 (defsubst org-in-fixed-width-region-p ()
20219 "Is point in a fixed-width region?"
20220 (save-match-data
20221 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20223 (defun org-edit-special (&optional arg)
20224 "Call a special editor for the element at point.
20225 When at a table, call the formula editor with `org-table-edit-formulas'.
20226 When in a source code block, call `org-edit-src-code'.
20227 When in a fixed-width region, call `org-edit-fixed-width-region'.
20228 When at an #+INCLUDE keyword, visit the included file.
20229 On a link, call `ffap' to visit the link at point.
20230 Otherwise, return a user error."
20231 (interactive "P")
20232 (let ((element (org-element-at-point)))
20233 (assert (not buffer-read-only) nil
20234 "Buffer is read-only: %s" (buffer-name))
20235 (case (org-element-type element)
20236 (src-block
20237 (if (not arg) (org-edit-src-code)
20238 (let* ((info (org-babel-get-src-block-info))
20239 (lang (nth 0 info))
20240 (params (nth 2 info))
20241 (session (cdr (assq :session params))))
20242 (if (not session) (org-edit-src-code)
20243 ;; At a src-block with a session and function called with
20244 ;; an ARG: switch to the buffer related to the inferior
20245 ;; process.
20246 (switch-to-buffer
20247 (funcall (intern (concat "org-babel-prep-session:" lang))
20248 session params))))))
20249 (keyword
20250 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20251 (find-file
20252 (org-remove-double-quotes
20253 (car (org-split-string (org-element-property :value element)))))
20254 (user-error "No special environment to edit here")))
20255 (table
20256 (if (eq (org-element-property :type element) 'table.el)
20257 (org-edit-src-code)
20258 (call-interactively 'org-table-edit-formulas)))
20259 ;; Only Org tables contain `table-row' type elements.
20260 (table-row (call-interactively 'org-table-edit-formulas))
20261 ((example-block export-block) (org-edit-src-code))
20262 (fixed-width (org-edit-fixed-width-region))
20263 (otherwise
20264 ;; No notable element at point. Though, we may be at a link,
20265 ;; which is an object. Thus, scan deeper.
20266 (if (eq (org-element-type (org-element-context element)) 'link)
20267 (call-interactively 'ffap)
20268 (user-error "No special environment to edit here"))))))
20270 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20271 (defun org-ctrl-c-ctrl-c (&optional arg)
20272 "Set tags in headline, or update according to changed information at point.
20274 This command does many different things, depending on context:
20276 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20277 this is what we do.
20279 - If the cursor is on a statistics cookie, update it.
20281 - If the cursor is in a headline, prompt for tags and insert them
20282 into the current line, aligned to `org-tags-column'. When called
20283 with prefix arg, realign all tags in the current buffer.
20285 - If the cursor is in one of the special #+KEYWORD lines, this
20286 triggers scanning the buffer for these lines and updating the
20287 information.
20289 - If the cursor is inside a table, realign the table. This command
20290 works even if the automatic table editor has been turned off.
20292 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20293 the entire table.
20295 - If the cursor is at a footnote reference or definition, jump to
20296 the corresponding definition or references, respectively.
20298 - If the cursor is a the beginning of a dynamic block, update it.
20300 - If the current buffer is a capture buffer, close note and file it.
20302 - If the cursor is on a <<<target>>>, update radio targets and
20303 corresponding links in this buffer.
20305 - If the cursor is on a numbered item in a plain list, renumber the
20306 ordered list.
20308 - If the cursor is on a checkbox, toggle it.
20310 - If the cursor is on a code block, evaluate it. The variable
20311 `org-confirm-babel-evaluate' can be used to control prompting
20312 before code block evaluation, by default every code block
20313 evaluation requires confirmation. Code block evaluation can be
20314 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20315 (interactive "P")
20316 (cond
20317 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20318 org-occur-highlights
20319 org-latex-fragment-image-overlays)
20320 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20321 (org-remove-occur-highlights)
20322 (org-remove-latex-fragment-image-overlays)
20323 (message "Temporary highlights/overlays removed from current buffer"))
20324 ((and (local-variable-p 'org-finish-function (current-buffer))
20325 (fboundp org-finish-function))
20326 (funcall org-finish-function))
20327 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20329 (let* ((context (org-element-context)) (type (org-element-type context)))
20330 ;; Test if point is within a blank line.
20331 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20332 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20333 (user-error "C-c C-c can do nothing useful at this location"))
20334 (case type
20335 ;; When at a link, act according to the parent instead.
20336 (link (setq context (org-element-property :parent context))
20337 (setq type (org-element-type context)))
20338 ;; Unsupported object types: check parent element instead.
20339 ((bold code entity export-snippet inline-babel-call inline-src-block
20340 italic latex-fragment line-break macro strike-through subscript
20341 superscript underline verbatim)
20342 (while (and (setq context (org-element-property :parent context))
20343 (not (memq (setq type (org-element-type context))
20344 '(paragraph verse-block)))))))
20345 ;; For convenience: at the first line of a paragraph on the
20346 ;; same line as an item, apply function on that item instead.
20347 (when (eq type 'paragraph)
20348 (let ((parent (org-element-property :parent context)))
20349 (when (and (eq (org-element-type parent) 'item)
20350 (= (point-at-bol) (org-element-property :begin parent)))
20351 (setq context parent type 'item))))
20352 ;; Act according to type of element or object at point.
20353 (case type
20354 (clock (org-clock-update-time-maybe))
20355 (dynamic-block
20356 (save-excursion
20357 (goto-char (org-element-property :post-affiliated context))
20358 (org-update-dblock)))
20359 (footnote-definition
20360 (goto-char (org-element-property :post-affiliated context))
20361 (call-interactively 'org-footnote-action))
20362 (footnote-reference (call-interactively 'org-footnote-action))
20363 ((headline inlinetask)
20364 (save-excursion (goto-char (org-element-property :begin context))
20365 (call-interactively 'org-set-tags)))
20366 (item
20367 ;; At an item: a double C-u set checkbox to "[-]"
20368 ;; unconditionally, whereas a single one will toggle its
20369 ;; presence. Without an universal argument, if the item
20370 ;; has a checkbox, toggle it. Otherwise repair the list.
20371 (let* ((box (org-element-property :checkbox context))
20372 (struct (org-element-property :structure context))
20373 (old-struct (copy-tree struct))
20374 (parents (org-list-parents-alist struct))
20375 (prevs (org-list-prevs-alist struct))
20376 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20377 (org-list-set-checkbox
20378 (org-element-property :begin context) struct
20379 (cond ((equal arg '(16)) "[-]")
20380 ((and (not box) (equal arg '(4))) "[ ]")
20381 ((or (not box) (equal arg '(4))) nil)
20382 ((eq box 'on) "[ ]")
20383 (t "[X]")))
20384 ;; Mimic `org-list-write-struct' but with grabbing
20385 ;; a return value from `org-list-struct-fix-box'.
20386 (org-list-struct-fix-ind struct parents 2)
20387 (org-list-struct-fix-item-end struct)
20388 (org-list-struct-fix-bul struct prevs)
20389 (org-list-struct-fix-ind struct parents)
20390 (let ((block-item
20391 (org-list-struct-fix-box struct parents prevs orderedp)))
20392 (if (and box (equal struct old-struct))
20393 (if (equal arg '(16))
20394 (message "Checkboxes already reset")
20395 (user-error "Cannot toggle this checkbox: %s"
20396 (if (eq box 'on)
20397 "all subitems checked"
20398 "unchecked subitems")))
20399 (org-list-struct-apply-struct struct old-struct)
20400 (org-update-checkbox-count-maybe))
20401 (when block-item
20402 (message "Checkboxes were removed due to empty box at line %d"
20403 (org-current-line block-item))))))
20404 (keyword
20405 (let ((org-inhibit-startup-visibility-stuff t)
20406 (org-startup-align-all-tables nil))
20407 (when (boundp 'org-table-coordinate-overlays)
20408 (mapc 'delete-overlay org-table-coordinate-overlays)
20409 (setq org-table-coordinate-overlays nil))
20410 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20411 (message "Local setup has been refreshed"))
20412 (plain-list
20413 ;; At a plain list, with a double C-u argument, set
20414 ;; checkboxes of each item to "[-]", whereas a single one
20415 ;; will toggle their presence according to the state of the
20416 ;; first item in the list. Without an argument, repair the
20417 ;; list.
20418 (let* ((begin (org-element-property :contents-begin context))
20419 (beginm (move-marker (make-marker) begin))
20420 (struct (org-element-property :structure context))
20421 (old-struct (copy-tree struct))
20422 (first-box (save-excursion
20423 (goto-char begin)
20424 (looking-at org-list-full-item-re)
20425 (match-string-no-properties 3)))
20426 (new-box (cond ((equal arg '(16)) "[-]")
20427 ((equal arg '(4)) (unless first-box "[ ]"))
20428 ((equal first-box "[X]") "[ ]")
20429 (t "[X]"))))
20430 (cond
20431 (arg
20432 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20433 (org-list-get-all-items
20434 begin struct (org-list-prevs-alist struct))))
20435 ((and first-box (eq (point) begin))
20436 ;; For convenience, when point is at bol on the first
20437 ;; item of the list and no argument is provided, simply
20438 ;; toggle checkbox of that item, if any.
20439 (org-list-set-checkbox begin struct new-box)))
20440 (org-list-write-struct
20441 struct (org-list-parents-alist struct) old-struct)
20442 (org-update-checkbox-count-maybe)
20443 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20444 ((property-drawer node-property)
20445 (call-interactively 'org-property-action))
20446 ((radio-target target)
20447 (call-interactively 'org-update-radio-target-regexp))
20448 (statistics-cookie
20449 (call-interactively 'org-update-statistics-cookies))
20450 ((table table-cell table-row)
20451 ;; At a table, recalculate every field and align it. Also
20452 ;; send the table if necessary. If the table has
20453 ;; a `table.el' type, just give up. At a table row or
20454 ;; cell, maybe recalculate line but always align table.
20455 (if (eq (org-element-property :type context) 'table.el)
20456 (message "Use C-c ' to edit table.el tables")
20457 (let ((org-enable-table-editor t))
20458 (if (or (eq type 'table)
20459 ;; Check if point is at a TBLFM line.
20460 (and (eq type 'table-row)
20461 (= (point) (org-element-property :end context))))
20462 (save-excursion
20463 (if (org-at-TBLFM-p)
20464 (progn (require 'org-table)
20465 (org-table-calc-current-TBLFM))
20466 (goto-char (org-element-property :contents-begin context))
20467 (org-call-with-arg 'org-table-recalculate (or arg t))
20468 (orgtbl-send-table 'maybe)))
20469 (org-table-maybe-eval-formula)
20470 (cond (arg (call-interactively 'org-table-recalculate))
20471 ((org-table-maybe-recalculate-line))
20472 (t (org-table-align)))))))
20473 (timestamp (org-timestamp-change 0 'day))
20474 (otherwise
20475 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20476 (user-error
20477 "C-c C-c can do nothing useful at this location")))))))))
20479 (defun org-mode-restart ()
20480 "Restart Org-mode, to scan again for special lines.
20481 Also updates the keyword regular expressions."
20482 (interactive)
20483 ;; this will set the mode *and* set file local variables.
20484 (normal-mode)
20485 ;; but it may leave us in some unrelated mode
20486 (unless (derived-mode-p "org-mode")
20487 (org-mode))
20488 (message "Org-mode restarted"))
20490 (defun org-kill-note-or-show-branches ()
20491 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20492 (interactive)
20493 (if (not org-finish-function)
20494 (progn
20495 (hide-subtree)
20496 (call-interactively 'show-branches))
20497 (let ((org-note-abort t))
20498 (funcall org-finish-function))))
20500 (defun org-open-line (n)
20501 "Insert a new row in tables, call `open-line' elsewhere.
20502 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20503 (interactive "*p")
20504 (cond
20505 ((not org-special-ctrl-o)
20506 (open-line n))
20507 ((org-at-table-p)
20508 (org-table-insert-row))
20510 (open-line n))))
20512 (defun org-return (&optional indent)
20513 "Goto next table row or insert a newline.
20514 Calls `org-table-next-row' or `newline', depending on context.
20515 See the individual commands for more information."
20516 (interactive)
20517 (let (org-ts-what)
20518 (cond
20519 ((or (bobp) (org-in-src-block-p))
20520 (if indent (newline-and-indent) (newline)))
20521 ((org-at-table-p)
20522 (org-table-justify-field-maybe)
20523 (call-interactively 'org-table-next-row))
20524 ;; when `newline-and-indent' is called within a list, make sure
20525 ;; text moved stays inside the item.
20526 ((and (org-in-item-p) indent)
20527 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20528 (progn
20529 (save-match-data (newline))
20530 (org-indent-line-to (length (match-string 0))))
20531 (let ((ind (org-get-indentation)))
20532 (newline)
20533 (if (org-looking-back org-list-end-re)
20534 (org-indent-line)
20535 (org-indent-line-to ind)))))
20536 ((and org-return-follows-link
20537 (org-at-timestamp-p t)
20538 (not (eq org-ts-what 'after)))
20539 (org-follow-timestamp-link))
20540 ((and org-return-follows-link
20541 (let ((tprop (get-text-property (point) 'face)))
20542 (or (eq tprop 'org-link)
20543 (and (listp tprop) (memq 'org-link tprop)))))
20544 (call-interactively 'org-open-at-point))
20545 ((and (org-at-heading-p)
20546 (looking-at
20547 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20548 (org-show-entry)
20549 (end-of-line 1)
20550 (newline))
20551 (t (if indent (newline-and-indent) (newline))))))
20553 (defun org-return-indent ()
20554 "Goto next table row or insert a newline and indent.
20555 Calls `org-table-next-row' or `newline-and-indent', depending on
20556 context. See the individual commands for more information."
20557 (interactive)
20558 (org-return t))
20560 (defun org-ctrl-c-star ()
20561 "Compute table, or change heading status of lines.
20562 Calls `org-table-recalculate' or `org-toggle-heading',
20563 depending on context."
20564 (interactive)
20565 (cond
20566 ((org-at-table-p)
20567 (call-interactively 'org-table-recalculate))
20569 ;; Convert all lines in region to list items
20570 (call-interactively 'org-toggle-heading))))
20572 (defun org-ctrl-c-minus ()
20573 "Insert separator line in table or modify bullet status of line.
20574 Also turns a plain line or a region of lines into list items.
20575 Calls `org-table-insert-hline', `org-toggle-item', or
20576 `org-cycle-list-bullet', depending on context."
20577 (interactive)
20578 (cond
20579 ((org-at-table-p)
20580 (call-interactively 'org-table-insert-hline))
20581 ((org-region-active-p)
20582 (call-interactively 'org-toggle-item))
20583 ((org-in-item-p)
20584 (call-interactively 'org-cycle-list-bullet))
20586 (call-interactively 'org-toggle-item))))
20588 (defun org-toggle-item (arg)
20589 "Convert headings or normal lines to items, items to normal lines.
20590 If there is no active region, only the current line is considered.
20592 If the first non blank line in the region is a headline, convert
20593 all headlines to items, shifting text accordingly.
20595 If it is an item, convert all items to normal lines.
20597 If it is normal text, change region into a list of items.
20598 With a prefix argument ARG, change the region in a single item."
20599 (interactive "P")
20600 (let ((shift-text
20601 (function
20602 ;; Shift text in current section to IND, from point to END.
20603 ;; The function leaves point to END line.
20604 (lambda (ind end)
20605 (let ((min-i 1000) (end (copy-marker end)))
20606 ;; First determine the minimum indentation (MIN-I) of
20607 ;; the text.
20608 (save-excursion
20609 (catch 'exit
20610 (while (< (point) end)
20611 (let ((i (org-get-indentation)))
20612 (cond
20613 ;; Skip blank lines and inline tasks.
20614 ((looking-at "^[ \t]*$"))
20615 ((looking-at org-outline-regexp-bol))
20616 ;; We can't find less than 0 indentation.
20617 ((zerop i) (throw 'exit (setq min-i 0)))
20618 ((< i min-i) (setq min-i i))))
20619 (forward-line))))
20620 ;; Then indent each line so that a line indented to
20621 ;; MIN-I becomes indented to IND. Ignore blank lines
20622 ;; and inline tasks in the process.
20623 (let ((delta (- ind min-i)))
20624 (while (< (point) end)
20625 (unless (or (looking-at "^[ \t]*$")
20626 (looking-at org-outline-regexp-bol))
20627 (org-indent-line-to (+ (org-get-indentation) delta)))
20628 (forward-line)))))))
20629 (skip-blanks
20630 (function
20631 ;; Return beginning of first non-blank line, starting from
20632 ;; line at POS.
20633 (lambda (pos)
20634 (save-excursion
20635 (goto-char pos)
20636 (skip-chars-forward " \r\t\n")
20637 (point-at-bol)))))
20638 beg end)
20639 ;; Determine boundaries of changes.
20640 (if (org-region-active-p)
20641 (setq beg (funcall skip-blanks (region-beginning))
20642 end (copy-marker (region-end)))
20643 (setq beg (funcall skip-blanks (point-at-bol))
20644 end (copy-marker (point-at-eol))))
20645 ;; Depending on the starting line, choose an action on the text
20646 ;; between BEG and END.
20647 (org-with-limited-levels
20648 (save-excursion
20649 (goto-char beg)
20650 (cond
20651 ;; Case 1. Start at an item: de-itemize. Note that it only
20652 ;; happens when a region is active: `org-ctrl-c-minus'
20653 ;; would call `org-cycle-list-bullet' otherwise.
20654 ((org-at-item-p)
20655 (while (< (point) end)
20656 (when (org-at-item-p)
20657 (skip-chars-forward " \t")
20658 (delete-region (point) (match-end 0)))
20659 (forward-line)))
20660 ;; Case 2. Start at an heading: convert to items.
20661 ((org-at-heading-p)
20662 (let* ((bul (org-list-bullet-string "-"))
20663 (bul-len (length bul))
20664 ;; Indentation of the first heading. It should be
20665 ;; relative to the indentation of its parent, if any.
20666 (start-ind (save-excursion
20667 (cond
20668 ((not org-adapt-indentation) 0)
20669 ((not (outline-previous-heading)) 0)
20670 (t (length (match-string 0))))))
20671 ;; Level of first heading. Further headings will be
20672 ;; compared to it to determine hierarchy in the list.
20673 (ref-level (org-reduced-level (org-outline-level))))
20674 (while (< (point) end)
20675 (let* ((level (org-reduced-level (org-outline-level)))
20676 (delta (max 0 (- level ref-level))))
20677 ;; If current headline is less indented than the first
20678 ;; one, set it as reference, in order to preserve
20679 ;; subtrees.
20680 (when (< level ref-level) (setq ref-level level))
20681 (replace-match bul t t)
20682 (org-indent-line-to (+ start-ind (* delta bul-len)))
20683 ;; Ensure all text down to END (or SECTION-END) belongs
20684 ;; to the newly created item.
20685 (let ((section-end (save-excursion
20686 (or (outline-next-heading) (point)))))
20687 (forward-line)
20688 (funcall shift-text
20689 (+ start-ind (* (1+ delta) bul-len))
20690 (min end section-end)))))))
20691 ;; Case 3. Normal line with ARG: make the first line of region
20692 ;; an item, and shift indentation of others lines to
20693 ;; set them as item's body.
20694 (arg (let* ((bul (org-list-bullet-string "-"))
20695 (bul-len (length bul))
20696 (ref-ind (org-get-indentation)))
20697 (skip-chars-forward " \t")
20698 (insert bul)
20699 (forward-line)
20700 (while (< (point) end)
20701 ;; Ensure that lines less indented than first one
20702 ;; still get included in item body.
20703 (funcall shift-text
20704 (+ ref-ind bul-len)
20705 (min end (save-excursion (or (outline-next-heading)
20706 (point)))))
20707 (forward-line))))
20708 ;; Case 4. Normal line without ARG: turn each non-item line
20709 ;; into an item.
20711 (while (< (point) end)
20712 (unless (or (org-at-heading-p) (org-at-item-p))
20713 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20714 (replace-match
20715 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20716 (forward-line))))))))
20718 (defun org-toggle-heading (&optional nstars)
20719 "Convert headings to normal text, or items or text to headings.
20720 If there is no active region, only convert the current line.
20722 With a \\[universal-argument] prefix, convert the whole list at
20723 point into heading.
20725 In a region:
20727 - If the first non blank line is a headline, remove the stars
20728 from all headlines in the region.
20730 - If it is a normal line, turn each and every normal line (i.e.,
20731 not an heading or an item) in the region into headings. If you
20732 want to convert only the first line of this region, use one
20733 universal prefix argument.
20735 - If it is a plain list item, turn all plain list items into headings.
20737 When converting a line into a heading, the number of stars is chosen
20738 such that the lines become children of the current entry. However,
20739 when a numeric prefix argument is given, its value determines the
20740 number of stars to add."
20741 (interactive "P")
20742 (let ((skip-blanks
20743 (function
20744 ;; Return beginning of first non-blank line, starting from
20745 ;; line at POS.
20746 (lambda (pos)
20747 (save-excursion
20748 (goto-char pos)
20749 (while (org-at-comment-p) (forward-line))
20750 (skip-chars-forward " \r\t\n")
20751 (point-at-bol)))))
20752 beg end toggled)
20753 ;; Determine boundaries of changes. If a universal prefix has
20754 ;; been given, put the list in a region. If region ends at a bol,
20755 ;; do not consider the last line to be in the region.
20757 (when (and current-prefix-arg (org-at-item-p))
20758 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20759 (org-mark-element))
20761 (if (org-region-active-p)
20762 (setq beg (funcall skip-blanks (region-beginning))
20763 end (copy-marker (save-excursion
20764 (goto-char (region-end))
20765 (if (bolp) (point) (point-at-eol)))))
20766 (setq beg (funcall skip-blanks (point-at-bol))
20767 end (copy-marker (point-at-eol))))
20768 ;; Ensure inline tasks don't count as headings.
20769 (org-with-limited-levels
20770 (save-excursion
20771 (goto-char beg)
20772 (cond
20773 ;; Case 1. Started at an heading: de-star headings.
20774 ((org-at-heading-p)
20775 (while (< (point) end)
20776 (when (org-at-heading-p t)
20777 (looking-at org-outline-regexp) (replace-match "")
20778 (setq toggled t))
20779 (forward-line)))
20780 ;; Case 2. Started at an item: change items into headlines.
20781 ;; One star will be added by `org-list-to-subtree'.
20782 ((org-at-item-p)
20783 (let* ((stars (make-string
20784 ;; subtract the star that will be added again by
20785 ;; `org-list-to-subtree'
20786 (if (numberp nstars) (1- nstars)
20787 (or (org-current-level) 0))
20788 ?*))
20789 (add-stars
20790 (cond (nstars "") ; stars from prefix only
20791 ((equal stars "") "") ; before first heading
20792 (org-odd-levels-only "*") ; inside heading, odd
20793 (t "")))) ; inside heading, oddeven
20794 (while (< (point) end)
20795 (when (org-at-item-p)
20796 ;; Pay attention to cases when region ends before list.
20797 (let* ((struct (org-list-struct))
20798 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20799 (save-restriction
20800 (narrow-to-region (point) list-end)
20801 (insert
20802 (org-list-to-subtree
20803 (org-list-parse-list t)
20804 '(:istart (concat stars add-stars (funcall get-stars depth))
20805 :icount (concat stars add-stars (funcall get-stars depth)))))))
20806 (setq toggled t))
20807 (forward-line))))
20808 ;; Case 3. Started at normal text: make every line an heading,
20809 ;; skipping headlines and items.
20810 (t (let* ((stars
20811 (make-string
20812 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20813 (add-stars
20814 (cond (nstars "") ; stars from prefix only
20815 ((equal stars "") "*") ; before first heading
20816 (org-odd-levels-only "**") ; inside heading, odd
20817 (t "*"))) ; inside heading, oddeven
20818 (rpl (concat stars add-stars " "))
20819 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20820 (while (< (point) (if (equal nstars '(4)) lend end))
20821 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20822 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20823 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20824 (forward-line)))))))
20825 (unless toggled (message "Cannot toggle heading from here"))))
20827 (defun org-meta-return (&optional arg)
20828 "Insert a new heading or wrap a region in a table.
20829 Calls `org-insert-heading' or `org-table-wrap-region', depending
20830 on context. See the individual commands for more information."
20831 (interactive "P")
20832 (org-check-before-invisible-edit 'insert)
20833 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20834 (let* ((element (org-element-at-point))
20835 (type (org-element-type element)))
20836 (when (eq type 'table-row)
20837 (setq element (org-element-property :parent element))
20838 (setq type 'table))
20839 (if (and (eq type 'table)
20840 (eq (org-element-property :type element) 'org)
20841 (>= (point) (org-element-property :contents-begin element))
20842 (< (point) (org-element-property :contents-end element)))
20843 (call-interactively 'org-table-wrap-region)
20844 (call-interactively 'org-insert-heading)))))
20846 ;;; Menu entries
20848 (defsubst org-in-subtree-not-table-p ()
20849 "Are we in a subtree and not in a table?"
20850 (and (not (org-before-first-heading-p))
20851 (not (org-at-table-p))))
20853 ;; Define the Org-mode menus
20854 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20855 '("Tbl"
20856 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20857 ["Next Field" org-cycle (org-at-table-p)]
20858 ["Previous Field" org-shifttab (org-at-table-p)]
20859 ["Next Row" org-return (org-at-table-p)]
20860 "--"
20861 ["Blank Field" org-table-blank-field (org-at-table-p)]
20862 ["Edit Field" org-table-edit-field (org-at-table-p)]
20863 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20864 "--"
20865 ("Column"
20866 ["Move Column Left" org-metaleft (org-at-table-p)]
20867 ["Move Column Right" org-metaright (org-at-table-p)]
20868 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20869 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20870 ("Row"
20871 ["Move Row Up" org-metaup (org-at-table-p)]
20872 ["Move Row Down" org-metadown (org-at-table-p)]
20873 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20874 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20875 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20876 "--"
20877 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20878 ("Rectangle"
20879 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20880 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20881 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20882 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20883 "--"
20884 ("Calculate"
20885 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20886 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20887 ["Edit Formulas" org-edit-special (org-at-table-p)]
20888 "--"
20889 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20890 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20891 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20892 "--"
20893 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20894 "--"
20895 ["Sum Column/Rectangle" org-table-sum
20896 (or (org-at-table-p) (org-region-active-p))]
20897 ["Which Column?" org-table-current-column (org-at-table-p)])
20898 ["Debug Formulas"
20899 org-table-toggle-formula-debugger
20900 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20901 ["Show Col/Row Numbers"
20902 org-table-toggle-coordinate-overlays
20903 :style toggle
20904 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20905 "--"
20906 ["Create" org-table-create (and (not (org-at-table-p))
20907 org-enable-table-editor)]
20908 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20909 ["Import from File" org-table-import (not (org-at-table-p))]
20910 ["Export to File" org-table-export (org-at-table-p)]
20911 "--"
20912 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20914 (easy-menu-define org-org-menu org-mode-map "Org menu"
20915 '("Org"
20916 ("Show/Hide"
20917 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20918 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20919 ["Sparse Tree..." org-sparse-tree t]
20920 ["Reveal Context" org-reveal t]
20921 ["Show All" show-all t]
20922 "--"
20923 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20924 "--"
20925 ["New Heading" org-insert-heading t]
20926 ("Navigate Headings"
20927 ["Up" outline-up-heading t]
20928 ["Next" outline-next-visible-heading t]
20929 ["Previous" outline-previous-visible-heading t]
20930 ["Next Same Level" outline-forward-same-level t]
20931 ["Previous Same Level" outline-backward-same-level t]
20932 "--"
20933 ["Jump" org-goto t])
20934 ("Edit Structure"
20935 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20936 "--"
20937 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20938 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20939 "--"
20940 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20941 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20942 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20943 "--"
20944 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20945 "--"
20946 ["Copy visible text" org-copy-visible t]
20947 "--"
20948 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20949 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20950 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20951 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20952 "--"
20953 ["Sort Region/Children" org-sort t]
20954 "--"
20955 ["Convert to odd levels" org-convert-to-odd-levels t]
20956 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20957 ("Editing"
20958 ["Emphasis..." org-emphasize t]
20959 ["Edit Source Example" org-edit-special t]
20960 "--"
20961 ["Footnote new/jump" org-footnote-action t]
20962 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20963 ("Archive"
20964 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20965 "--"
20966 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20967 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20968 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20970 "--"
20971 ("Hyperlinks"
20972 ["Store Link (Global)" org-store-link t]
20973 ["Find existing link to here" org-occur-link-in-agenda-files t]
20974 ["Insert Link" org-insert-link t]
20975 ["Follow Link" org-open-at-point t]
20976 "--"
20977 ["Next link" org-next-link t]
20978 ["Previous link" org-previous-link t]
20979 "--"
20980 ["Descriptive Links"
20981 org-toggle-link-display
20982 :style radio
20983 :selected org-descriptive-links
20985 ["Literal Links"
20986 org-toggle-link-display
20987 :style radio
20988 :selected (not org-descriptive-links)])
20989 "--"
20990 ("TODO Lists"
20991 ["TODO/DONE/-" org-todo t]
20992 ("Select keyword"
20993 ["Next keyword" org-shiftright (org-at-heading-p)]
20994 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20995 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20996 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20997 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20998 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20999 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21000 "--"
21001 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21002 :selected org-enforce-todo-dependencies :style toggle :active t]
21003 "Settings for tree at point"
21004 ["Do Children sequentially" org-toggle-ordered-property :style radio
21005 :selected (org-entry-get nil "ORDERED")
21006 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21007 ["Do Children parallel" org-toggle-ordered-property :style radio
21008 :selected (not (org-entry-get nil "ORDERED"))
21009 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21010 "--"
21011 ["Set Priority" org-priority t]
21012 ["Priority Up" org-shiftup t]
21013 ["Priority Down" org-shiftdown t]
21014 "--"
21015 ["Get news from all feeds" org-feed-update-all t]
21016 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21017 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21018 ("TAGS and Properties"
21019 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21020 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21021 "--"
21022 ["Set property" org-set-property (not (org-before-first-heading-p))]
21023 ["Column view of properties" org-columns t]
21024 ["Insert Column View DBlock" org-insert-columns-dblock t])
21025 ("Dates and Scheduling"
21026 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21027 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21028 ("Change Date"
21029 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21030 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21031 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21032 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21033 ["Compute Time Range" org-evaluate-time-range t]
21034 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21035 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21036 "--"
21037 ["Custom time format" org-toggle-time-stamp-overlays
21038 :style radio :selected org-display-custom-times]
21039 "--"
21040 ["Goto Calendar" org-goto-calendar t]
21041 ["Date from Calendar" org-date-from-calendar t]
21042 "--"
21043 ["Start/Restart Timer" org-timer-start t]
21044 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21045 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21046 ["Insert Timer String" org-timer t]
21047 ["Insert Timer Item" org-timer-item t])
21048 ("Logging work"
21049 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21050 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21051 ["Clock out" org-clock-out t]
21052 ["Clock cancel" org-clock-cancel t]
21053 "--"
21054 ["Mark as default task" org-clock-mark-default-task t]
21055 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21056 ["Goto running clock" org-clock-goto t]
21057 "--"
21058 ["Display times" org-clock-display t]
21059 ["Create clock table" org-clock-report t]
21060 "--"
21061 ["Record DONE time"
21062 (progn (setq org-log-done (not org-log-done))
21063 (message "Switching to %s will %s record a timestamp"
21064 (car org-done-keywords)
21065 (if org-log-done "automatically" "not")))
21066 :style toggle :selected org-log-done])
21067 "--"
21068 ["Agenda Command..." org-agenda t]
21069 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21070 ("File List for Agenda")
21071 ("Special views current file"
21072 ["TODO Tree" org-show-todo-tree t]
21073 ["Check Deadlines" org-check-deadlines t]
21074 ["Timeline" org-timeline t]
21075 ["Tags/Property tree" org-match-sparse-tree t])
21076 "--"
21077 ["Export/Publish..." org-export-dispatch t]
21078 ("LaTeX"
21079 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21080 :selected org-cdlatex-mode]
21081 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21082 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21083 ["Modify math symbol" org-cdlatex-math-modify
21084 (org-inside-LaTeX-fragment-p)]
21085 ["Insert citation" org-reftex-citation t]
21086 "--"
21087 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21088 "--"
21089 ("MobileOrg"
21090 ["Push Files and Views" org-mobile-push t]
21091 ["Get Captured and Flagged" org-mobile-pull t]
21092 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21093 "--"
21094 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21095 "--"
21096 ("Documentation"
21097 ["Show Version" org-version t]
21098 ["Info Documentation" org-info t])
21099 ("Customize"
21100 ["Browse Org Group" org-customize t]
21101 "--"
21102 ["Expand This Menu" org-create-customize-menu
21103 (fboundp 'customize-menu-create)])
21104 ["Send bug report" org-submit-bug-report t]
21105 "--"
21106 ("Refresh/Reload"
21107 ["Refresh setup current buffer" org-mode-restart t]
21108 ["Reload Org (after update)" org-reload t]
21109 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21112 (defun org-info (&optional node)
21113 "Read documentation for Org-mode in the info system.
21114 With optional NODE, go directly to that node."
21115 (interactive)
21116 (info (format "(org)%s" (or node ""))))
21118 ;;;###autoload
21119 (defun org-submit-bug-report ()
21120 "Submit a bug report on Org-mode via mail.
21122 Don't hesitate to report any problems or inaccurate documentation.
21124 If you don't have setup sending mail from (X)Emacs, please copy the
21125 output buffer into your mail program, as it gives us important
21126 information about your Org-mode version and configuration."
21127 (interactive)
21128 (require 'reporter)
21129 (org-load-modules-maybe)
21130 (org-require-autoloaded-modules)
21131 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21132 (reporter-submit-bug-report
21133 "emacs-orgmode@gnu.org"
21134 (org-version nil 'full)
21135 (let (list)
21136 (save-window-excursion
21137 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21138 (delete-other-windows)
21139 (erase-buffer)
21140 (insert "You are about to submit a bug report to the Org-mode mailing list.
21142 We would like to add your full Org-mode and Outline configuration to the
21143 bug report. This greatly simplifies the work of the maintainer and
21144 other experts on the mailing list.
21146 HOWEVER, some variables you have customized may contain private
21147 information. The names of customers, colleagues, or friends, might
21148 appear in the form of file names, tags, todo states, or search strings.
21149 If you answer yes to the prompt, you might want to check and remove
21150 such private information before sending the email.")
21151 (add-text-properties (point-min) (point-max) '(face org-warning))
21152 (when (yes-or-no-p "Include your Org-mode configuration ")
21153 (mapatoms
21154 (lambda (v)
21155 (and (boundp v)
21156 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21157 (or (and (symbol-value v)
21158 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21159 (and
21160 (get v 'custom-type) (get v 'standard-value)
21161 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21162 (push v list)))))
21163 (kill-buffer (get-buffer "*Warn about privacy*"))
21164 list))
21165 nil nil
21166 "Remember to cover the basics, that is, what you expected to happen and
21167 what in fact did happen. You don't know how to make a good report? See
21169 http://orgmode.org/manual/Feedback.html#Feedback
21171 Your bug report will be posted to the Org-mode mailing list.
21172 ------------------------------------------------------------------------")
21173 (save-excursion
21174 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21175 (replace-match "\\1Bug: \\3 [\\2]")))))
21178 (defun org-install-agenda-files-menu ()
21179 (let ((bl (buffer-list)))
21180 (save-excursion
21181 (while bl
21182 (set-buffer (pop bl))
21183 (if (derived-mode-p 'org-mode) (setq bl nil)))
21184 (when (derived-mode-p 'org-mode)
21185 (easy-menu-change
21186 '("Org") "File List for Agenda"
21187 (append
21188 (list
21189 ["Edit File List" (org-edit-agenda-file-list) t]
21190 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21191 ["Remove Current File from List" org-remove-file t]
21192 ["Cycle through agenda files" org-cycle-agenda-files t]
21193 ["Occur in all agenda files" org-occur-in-agenda-files t]
21194 "--")
21195 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21197 ;;;; Documentation
21199 (defun org-require-autoloaded-modules ()
21200 (interactive)
21201 (mapc 'require
21202 '(org-agenda org-archive org-attach org-clock org-colview org-id
21203 org-table org-timer)))
21205 ;;;###autoload
21206 (defun org-reload (&optional uncompiled)
21207 "Reload all org lisp files.
21208 With prefix arg UNCOMPILED, load the uncompiled versions."
21209 (interactive "P")
21210 (require 'loadhist)
21211 (let* ((org-dir (org-find-library-dir "org"))
21212 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21213 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21214 (remove-re (mapconcat 'identity
21215 (mapcar (lambda (f) (concat "^" f "$"))
21216 (list (if (featurep 'xemacs)
21217 "org-colview"
21218 "org-colview-xemacs")
21219 "org" "org-loaddefs" "org-version"))
21220 "\\|"))
21221 (feats (delete-dups
21222 (mapcar 'file-name-sans-extension
21223 (mapcar 'file-name-nondirectory
21224 (delq nil
21225 (mapcar 'feature-file
21226 features))))))
21227 (lfeat (append
21228 (sort
21229 (setq feats
21230 (delq nil (mapcar
21231 (lambda (f)
21232 (if (and (string-match feature-re f)
21233 (not (string-match remove-re f)))
21234 f nil))
21235 feats)))
21236 'string-lessp)
21237 (list "org-version" "org")))
21238 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21239 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21240 load-uncore load-misses)
21241 (setq load-misses
21242 (delq 't
21243 (mapcar (lambda (f)
21244 (or (org-load-noerror-mustsuffix (concat org-dir f))
21245 (and (string= org-dir contrib-dir)
21246 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21247 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21248 (add-to-list 'load-uncore f 'append)
21251 lfeat)))
21252 (if load-uncore
21253 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21254 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21255 (if load-misses
21256 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21257 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21258 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21260 ;;;###autoload
21261 (defun org-customize ()
21262 "Call the customize function with org as argument."
21263 (interactive)
21264 (org-load-modules-maybe)
21265 (org-require-autoloaded-modules)
21266 (customize-browse 'org))
21268 (defun org-create-customize-menu ()
21269 "Create a full customization menu for Org-mode, insert it into the menu."
21270 (interactive)
21271 (org-load-modules-maybe)
21272 (org-require-autoloaded-modules)
21273 (if (fboundp 'customize-menu-create)
21274 (progn
21275 (easy-menu-change
21276 '("Org") "Customize"
21277 `(["Browse Org group" org-customize t]
21278 "--"
21279 ,(customize-menu-create 'org)
21280 ["Set" Custom-set t]
21281 ["Save" Custom-save t]
21282 ["Reset to Current" Custom-reset-current t]
21283 ["Reset to Saved" Custom-reset-saved t]
21284 ["Reset to Standard Settings" Custom-reset-standard t]))
21285 (message "\"Org\"-menu now contains full customization menu"))
21286 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21288 ;;;; Miscellaneous stuff
21290 ;;; Generally useful functions
21292 (defun org-get-at-bol (property)
21293 "Get text property PROPERTY at beginning of line."
21294 (get-text-property (point-at-bol) property))
21296 (defun org-find-text-property-in-string (prop s)
21297 "Return the first non-nil value of property PROP in string S."
21298 (or (get-text-property 0 prop s)
21299 (get-text-property (or (next-single-property-change 0 prop s) 0)
21300 prop s)))
21302 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21303 "Display the given MESSAGE as a warning."
21304 (if (fboundp 'display-warning)
21305 (display-warning 'org message
21306 (if (featurep 'xemacs) 'warning :warning))
21307 (let ((buf (get-buffer-create "*Org warnings*")))
21308 (with-current-buffer buf
21309 (goto-char (point-max))
21310 (insert "Warning (Org): " message)
21311 (unless (bolp)
21312 (newline)))
21313 (display-buffer buf)
21314 (sit-for 0))))
21316 (defun org-eval (form)
21317 "Eval FORM and return result."
21318 (condition-case error
21319 (eval form)
21320 (error (format "%%![Error: %s]" error))))
21322 (defun org-in-clocktable-p ()
21323 "Check if the cursor is in a clocktable."
21324 (let ((pos (point)) start)
21325 (save-excursion
21326 (end-of-line 1)
21327 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21328 (setq start (match-beginning 0))
21329 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21330 (>= (match-end 0) pos)
21331 start))))
21333 (defun org-in-commented-line ()
21334 "Is point in a line starting with `#'?"
21335 (equal (char-after (point-at-bol)) ?#))
21337 (defun org-in-indented-comment-line ()
21338 "Is point in a line starting with `#' after some white space?"
21339 (save-excursion
21340 (save-match-data
21341 (goto-char (point-at-bol))
21342 (looking-at "[ \t]*#"))))
21344 (defun org-in-verbatim-emphasis ()
21345 (save-match-data
21346 (and (org-in-regexp org-emph-re 2)
21347 (>= (point) (match-beginning 3))
21348 (<= (point) (match-end 4))
21349 (member (match-string 3) '("=" "~")))))
21351 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21352 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21353 (if (and marker (marker-buffer marker)
21354 (buffer-live-p (marker-buffer marker)))
21355 (progn
21356 (org-pop-to-buffer-same-window (marker-buffer marker))
21357 (if (or (> marker (point-max)) (< marker (point-min)))
21358 (widen))
21359 (goto-char marker)
21360 (org-show-context 'org-goto))
21361 (if bookmark
21362 (bookmark-jump bookmark)
21363 (error "Cannot find location"))))
21365 (defun org-quote-csv-field (s)
21366 "Quote field for inclusion in CSV material."
21367 (if (string-match "[\",]" s)
21368 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21371 (defun org-force-self-insert (N)
21372 "Needed to enforce self-insert under remapping."
21373 (interactive "p")
21374 (self-insert-command N))
21376 (defun org-string-width (s)
21377 "Compute width of string, ignoring invisible characters.
21378 This ignores character with invisibility property `org-link', and also
21379 characters with property `org-cwidth', because these will become invisible
21380 upon the next fontification round."
21381 (let (b l)
21382 (when (or (eq t buffer-invisibility-spec)
21383 (assq 'org-link buffer-invisibility-spec))
21384 (while (setq b (text-property-any 0 (length s)
21385 'invisible 'org-link s))
21386 (setq s (concat (substring s 0 b)
21387 (substring s (or (next-single-property-change
21388 b 'invisible s) (length s)))))))
21389 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21390 (setq s (concat (substring s 0 b)
21391 (substring s (or (next-single-property-change
21392 b 'org-cwidth s) (length s))))))
21393 (setq l (string-width s) b -1)
21394 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21395 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21398 (defun org-shorten-string (s maxlength)
21399 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21400 If the string is shorter or has length MAXLENGTH, just return the
21401 original string. If it is longer, the functions finds a space in the
21402 string, breaks this string off at that locations and adds three dots
21403 as ellipsis. Including the ellipsis, the string will not be longer
21404 than MAXLENGTH. If finding a good breaking point in the string does
21405 not work, the string is just chopped off in the middle of a word
21406 if necessary."
21407 (if (<= (length s) maxlength)
21409 (let* ((n (max (- maxlength 4) 1))
21410 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21411 (if (string-match re s)
21412 (concat (match-string 1 s) "...")
21413 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21415 (defun org-get-indentation (&optional line)
21416 "Get the indentation of the current line, interpreting tabs.
21417 When LINE is given, assume it represents a line and compute its indentation."
21418 (if line
21419 (if (string-match "^ *" (org-remove-tabs line))
21420 (match-end 0))
21421 (save-excursion
21422 (beginning-of-line 1)
21423 (skip-chars-forward " \t")
21424 (current-column))))
21426 (defun org-get-string-indentation (s)
21427 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21428 (let ((n -1) (i 0) (w tab-width) c)
21429 (catch 'exit
21430 (while (< (setq n (1+ n)) (length s))
21431 (setq c (aref s n))
21432 (cond ((= c ?\ ) (setq i (1+ i)))
21433 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21434 (t (throw 'exit t)))))
21437 (defun org-remove-tabs (s &optional width)
21438 "Replace tabulators in S with spaces.
21439 Assumes that s is a single line, starting in column 0."
21440 (setq width (or width tab-width))
21441 (while (string-match "\t" s)
21442 (setq s (replace-match
21443 (make-string
21444 (- (* width (/ (+ (match-beginning 0) width) width))
21445 (match-beginning 0)) ?\ )
21446 t t s)))
21449 (defun org-fix-indentation (line ind)
21450 "Fix indentation in LINE.
21451 IND is a cons cell with target and minimum indentation.
21452 If the current indentation in LINE is smaller than the minimum,
21453 leave it alone. If it is larger than ind, set it to the target."
21454 (let* ((l (org-remove-tabs line))
21455 (i (org-get-indentation l))
21456 (i1 (car ind)) (i2 (cdr ind)))
21457 (if (>= i i2) (setq l (substring line i2)))
21458 (if (> i1 0)
21459 (concat (make-string i1 ?\ ) l)
21460 l)))
21462 (defun org-remove-indentation (code &optional n)
21463 "Remove the maximum common indentation from the lines in CODE.
21464 N may optionally be the number of spaces to remove."
21465 (with-temp-buffer
21466 (insert code)
21467 (org-do-remove-indentation n)
21468 (buffer-string)))
21470 (defun org-do-remove-indentation (&optional n)
21471 "Remove the maximum common indentation from the buffer."
21472 (untabify (point-min) (point-max))
21473 (let ((min 10000) re)
21474 (if n
21475 (setq min n)
21476 (goto-char (point-min))
21477 (while (re-search-forward "^ *[^ \n]" nil t)
21478 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21479 (unless (or (= min 0) (= min 10000))
21480 (setq re (format "^ \\{%d\\}" min))
21481 (goto-char (point-min))
21482 (while (re-search-forward re nil t)
21483 (replace-match "")
21484 (end-of-line 1))
21485 min)))
21487 (defun org-fill-template (template alist)
21488 "Find each %key of ALIST in TEMPLATE and replace it."
21489 (let ((case-fold-search nil)
21490 entry key value)
21491 (setq alist (sort (copy-sequence alist)
21492 (lambda (a b) (< (length (car a)) (length (car b))))))
21493 (while (setq entry (pop alist))
21494 (setq template
21495 (replace-regexp-in-string
21496 (concat "%" (regexp-quote (car entry)))
21497 (or (cdr entry) "") template t t)))
21498 template))
21500 (defun org-base-buffer (buffer)
21501 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21502 (if (not buffer)
21503 buffer
21504 (or (buffer-base-buffer buffer)
21505 buffer)))
21507 (defun org-trim (s)
21508 "Remove whitespace at beginning and end of string."
21509 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21510 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21513 (defun org-wrap (string &optional width lines)
21514 "Wrap string to either a number of lines, or a width in characters.
21515 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21516 that costs. If there is a word longer than WIDTH, the text is actually
21517 wrapped to the length of that word.
21518 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21519 many lines, whatever width that takes.
21520 The return value is a list of lines, without newlines at the end."
21521 (let* ((words (org-split-string string "[ \t\n]+"))
21522 (maxword (apply 'max (mapcar 'org-string-width words)))
21523 w ll)
21524 (cond (width
21525 (org-do-wrap words (max maxword width)))
21526 (lines
21527 (setq w maxword)
21528 (setq ll (org-do-wrap words maxword))
21529 (if (<= (length ll) lines)
21531 (setq ll words)
21532 (while (> (length ll) lines)
21533 (setq w (1+ w))
21534 (setq ll (org-do-wrap words w)))
21535 ll))
21536 (t (error "Cannot wrap this")))))
21538 (defun org-do-wrap (words width)
21539 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21540 (let (lines line)
21541 (while words
21542 (setq line (pop words))
21543 (while (and words (< (+ (length line) (length (car words))) width))
21544 (setq line (concat line " " (pop words))))
21545 (setq lines (push line lines)))
21546 (nreverse lines)))
21548 (defun org-split-string (string &optional separators)
21549 "Splits STRING into substrings at SEPARATORS.
21550 No empty strings are returned if there are matches at the beginning
21551 and end of string."
21552 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21553 (start 0)
21554 notfirst
21555 (list nil))
21556 (while (and (string-match rexp string
21557 (if (and notfirst
21558 (= start (match-beginning 0))
21559 (< start (length string)))
21560 (1+ start) start))
21561 (< (match-beginning 0) (length string)))
21562 (setq notfirst t)
21563 (or (eq (match-beginning 0) 0)
21564 (and (eq (match-beginning 0) (match-end 0))
21565 (eq (match-beginning 0) start))
21566 (setq list
21567 (cons (substring string start (match-beginning 0))
21568 list)))
21569 (setq start (match-end 0)))
21570 (or (eq start (length string))
21571 (setq list
21572 (cons (substring string start)
21573 list)))
21574 (nreverse list)))
21576 (defun org-quote-vert (s)
21577 "Replace \"|\" with \"\\vert\"."
21578 (while (string-match "|" s)
21579 (setq s (replace-match "\\vert" t t s)))
21582 (defun org-uuidgen-p (s)
21583 "Is S an ID created by UUIDGEN?"
21584 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21586 (defun org-in-src-block-p (&optional inside)
21587 "Whether point is in a code source block.
21588 When INSIDE is non-nil, don't consider we are within a src block
21589 when point is at #+BEGIN_SRC or #+END_SRC."
21590 (let ((case-fold-search t) ov)
21591 (or (and (setq ov (overlays-at (point)))
21592 (memq 'org-block-background
21593 (overlay-properties (car ov))))
21594 (and (not inside)
21595 (save-match-data
21596 (save-excursion
21597 (beginning-of-line)
21598 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21600 (defun org-context ()
21601 "Return a list of contexts of the current cursor position.
21602 If several contexts apply, all are returned.
21603 Each context entry is a list with a symbol naming the context, and
21604 two positions indicating start and end of the context. Possible
21605 contexts are:
21607 :headline anywhere in a headline
21608 :headline-stars on the leading stars in a headline
21609 :todo-keyword on a TODO keyword (including DONE) in a headline
21610 :tags on the TAGS in a headline
21611 :priority on the priority cookie in a headline
21612 :item on the first line of a plain list item
21613 :item-bullet on the bullet/number of a plain list item
21614 :checkbox on the checkbox in a plain list item
21615 :table in an org-mode table
21616 :table-special on a special filed in a table
21617 :table-table in a table.el table
21618 :clocktable in a clocktable
21619 :src-block in a source block
21620 :link on a hyperlink
21621 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21622 :target on a <<target>>
21623 :radio-target on a <<<radio-target>>>
21624 :latex-fragment on a LaTeX fragment
21625 :latex-preview on a LaTeX fragment with overlaid preview image
21627 This function expects the position to be visible because it uses font-lock
21628 faces as a help to recognize the following contexts: :table-special, :link,
21629 and :keyword."
21630 (let* ((f (get-text-property (point) 'face))
21631 (faces (if (listp f) f (list f)))
21632 (case-fold-search t)
21633 (p (point)) clist o)
21634 ;; First the large context
21635 (cond
21636 ((org-at-heading-p t)
21637 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21638 (when (progn
21639 (beginning-of-line 1)
21640 (looking-at org-todo-line-tags-regexp))
21641 (push (org-point-in-group p 1 :headline-stars) clist)
21642 (push (org-point-in-group p 2 :todo-keyword) clist)
21643 (push (org-point-in-group p 4 :tags) clist))
21644 (goto-char p)
21645 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21646 (if (looking-at "\\[#[A-Z0-9]\\]")
21647 (push (org-point-in-group p 0 :priority) clist)))
21649 ((org-at-item-p)
21650 (push (org-point-in-group p 2 :item-bullet) clist)
21651 (push (list :item (point-at-bol)
21652 (save-excursion (org-end-of-item) (point)))
21653 clist)
21654 (and (org-at-item-checkbox-p)
21655 (push (org-point-in-group p 0 :checkbox) clist)))
21657 ((org-at-table-p)
21658 (push (list :table (org-table-begin) (org-table-end)) clist)
21659 (if (memq 'org-formula faces)
21660 (push (list :table-special
21661 (previous-single-property-change p 'face)
21662 (next-single-property-change p 'face)) clist)))
21663 ((org-at-table-p 'any)
21664 (push (list :table-table) clist)))
21665 (goto-char p)
21667 (let ((case-fold-search t))
21668 ;; New the "medium" contexts: clocktables, source blocks
21669 (cond ((org-in-clocktable-p)
21670 (push (list :clocktable
21671 (and (or (looking-at "#\\+BEGIN: clocktable")
21672 (search-backward "#+BEGIN: clocktable" nil t))
21673 (match-beginning 0))
21674 (and (re-search-forward "#\\+END:?" nil t)
21675 (match-end 0))) clist))
21676 ((org-in-src-block-p)
21677 (push (list :src-block
21678 (and (or (looking-at "#\\+BEGIN_SRC")
21679 (search-backward "#+BEGIN_SRC" nil t))
21680 (match-beginning 0))
21681 (and (search-forward "#+END_SRC" nil t)
21682 (match-beginning 0))) clist))))
21683 (goto-char p)
21685 ;; Now the small context
21686 (cond
21687 ((org-at-timestamp-p)
21688 (push (org-point-in-group p 0 :timestamp) clist))
21689 ((memq 'org-link faces)
21690 (push (list :link
21691 (previous-single-property-change p 'face)
21692 (next-single-property-change p 'face)) clist))
21693 ((memq 'org-special-keyword faces)
21694 (push (list :keyword
21695 (previous-single-property-change p 'face)
21696 (next-single-property-change p 'face)) clist))
21697 ((org-at-target-p)
21698 (push (org-point-in-group p 0 :target) clist)
21699 (goto-char (1- (match-beginning 0)))
21700 (if (looking-at org-radio-target-regexp)
21701 (push (org-point-in-group p 0 :radio-target) clist))
21702 (goto-char p))
21703 ((setq o (car (delq nil
21704 (mapcar
21705 (lambda (x)
21706 (if (memq x org-latex-fragment-image-overlays) x))
21707 (overlays-at (point))))))
21708 (push (list :latex-fragment
21709 (overlay-start o) (overlay-end o)) clist)
21710 (push (list :latex-preview
21711 (overlay-start o) (overlay-end o)) clist))
21712 ((org-inside-LaTeX-fragment-p)
21713 ;; FIXME: positions wrong.
21714 (push (list :latex-fragment (point) (point)) clist)))
21716 (setq clist (nreverse (delq nil clist)))
21717 clist))
21719 ;; FIXME: Compare with at-regexp-p Do we need both?
21720 (defun org-in-regexp (re &optional nlines visually)
21721 "Check if point is inside a match of regexp.
21722 Normally only the current line is checked, but you can include NLINES extra
21723 lines both before and after point into the search.
21724 If VISUALLY is set, require that the cursor is not after the match but
21725 really on, so that the block visually is on the match."
21726 (catch 'exit
21727 (let ((pos (point))
21728 (eol (point-at-eol (+ 1 (or nlines 0))))
21729 (inc (if visually 1 0)))
21730 (save-excursion
21731 (beginning-of-line (- 1 (or nlines 0)))
21732 (while (re-search-forward re eol t)
21733 (if (and (<= (match-beginning 0) pos)
21734 (>= (+ inc (match-end 0)) pos))
21735 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21737 (defun org-at-regexp-p (regexp)
21738 "Is point inside a match of REGEXP in the current line?"
21739 (catch 'exit
21740 (save-excursion
21741 (let ((pos (point)) (end (point-at-eol)))
21742 (beginning-of-line 1)
21743 (while (re-search-forward regexp end t)
21744 (if (and (<= (match-beginning 0) pos)
21745 (>= (match-end 0) pos))
21746 (throw 'exit t)))
21747 nil))))
21749 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21750 "Non-nil when point is between matches of START-RE and END-RE.
21752 Also return a non-nil value when point is on one of the matches.
21754 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21755 buffer positions. Default values are the positions of headlines
21756 surrounding the point.
21758 The functions returns a cons cell whose car (resp. cdr) is the
21759 position before START-RE (resp. after END-RE)."
21760 (save-match-data
21761 (let ((pos (point))
21762 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21763 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21764 beg end)
21765 (save-excursion
21766 ;; Point is on a block when on START-RE or if START-RE can be
21767 ;; found before it...
21768 (and (or (org-at-regexp-p start-re)
21769 (re-search-backward start-re limit-up t))
21770 (setq beg (match-beginning 0))
21771 ;; ... and END-RE after it...
21772 (goto-char (match-end 0))
21773 (re-search-forward end-re limit-down t)
21774 (> (setq end (match-end 0)) pos)
21775 ;; ... without another START-RE in-between.
21776 (goto-char (match-beginning 0))
21777 (not (re-search-backward start-re (1+ beg) t))
21778 ;; Return value.
21779 (cons beg end))))))
21781 (defun org-in-block-p (names)
21782 "Non-nil when point belongs to a block whose name belongs to NAMES.
21784 NAMES is a list of strings containing names of blocks.
21786 Return first block name matched, or nil. Beware that in case of
21787 nested blocks, the returned name may not belong to the closest
21788 block from point."
21789 (save-match-data
21790 (catch 'exit
21791 (let ((case-fold-search t)
21792 (lim-up (save-excursion (outline-previous-heading)))
21793 (lim-down (save-excursion (outline-next-heading))))
21794 (mapc (lambda (name)
21795 (let ((n (regexp-quote name)))
21796 (when (org-between-regexps-p
21797 (concat "^[ \t]*#\\+begin_" n)
21798 (concat "^[ \t]*#\\+end_" n)
21799 lim-up lim-down)
21800 (throw 'exit n))))
21801 names))
21802 nil)))
21804 (defun org-in-drawer-p ()
21805 "Non-nil if point is within a drawer.
21806 If point is within a drawer, return it, as parsed data."
21807 (let ((element (save-match-data (org-element-at-point))))
21808 (while (and element (not (memq (org-element-type element)
21809 '(drawer property-drawer))))
21810 (setq element (org-element-property :parent element)))
21811 element))
21813 (defun org-occur-in-agenda-files (regexp &optional nlines)
21814 "Call `multi-occur' with buffers for all agenda files."
21815 (interactive "sOrg-files matching: \np")
21816 (let* ((files (org-agenda-files))
21817 (tnames (mapcar 'file-truename files))
21818 (extra org-agenda-text-search-extra-files)
21820 (when (eq (car extra) 'agenda-archives)
21821 (setq extra (cdr extra))
21822 (setq files (org-add-archive-files files)))
21823 (while (setq f (pop extra))
21824 (unless (member (file-truename f) tnames)
21825 (add-to-list 'files f 'append)
21826 (add-to-list 'tnames (file-truename f) 'append)))
21827 (multi-occur
21828 (mapcar (lambda (x)
21829 (with-current-buffer
21830 (or (get-file-buffer x) (find-file-noselect x))
21831 (widen)
21832 (current-buffer)))
21833 files)
21834 regexp)))
21836 (if (boundp 'occur-mode-find-occurrence-hook)
21837 ;; Emacs 23
21838 (add-hook 'occur-mode-find-occurrence-hook
21839 (lambda ()
21840 (when (derived-mode-p 'org-mode)
21841 (org-reveal))))
21842 ;; Emacs 22
21843 (defadvice occur-mode-goto-occurrence
21844 (after org-occur-reveal activate)
21845 (and (derived-mode-p 'org-mode) (org-reveal)))
21846 (defadvice occur-mode-goto-occurrence-other-window
21847 (after org-occur-reveal activate)
21848 (and (derived-mode-p 'org-mode) (org-reveal)))
21849 (defadvice occur-mode-display-occurrence
21850 (after org-occur-reveal activate)
21851 (when (derived-mode-p 'org-mode)
21852 (let ((pos (occur-mode-find-occurrence)))
21853 (with-current-buffer (marker-buffer pos)
21854 (save-excursion
21855 (goto-char pos)
21856 (org-reveal)))))))
21858 (defun org-occur-link-in-agenda-files ()
21859 "Create a link and search for it in the agendas.
21860 The link is not stored in `org-stored-links', it is just created
21861 for the search purpose."
21862 (interactive)
21863 (let ((link (condition-case nil
21864 (org-store-link nil)
21865 (error "Unable to create a link to here"))))
21866 (org-occur-in-agenda-files (regexp-quote link))))
21868 (defun org-reverse-string (string)
21869 "Return the reverse of STRING."
21870 (apply 'string (reverse (string-to-list string))))
21872 (defun org-uniquify-alist (alist)
21873 "Merge elements of ALIST with the same key.
21875 For example, in this alist:
21877 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21878 => '((a 1 3) (b 2))
21880 merge (a 1) and (a 3) into (a 1 3).
21882 The function returns the new ALIST."
21883 (let (rtn)
21884 (mapc
21885 (lambda (e)
21886 (let (n)
21887 (if (not (assoc (car e) rtn))
21888 (push e rtn)
21889 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21890 (setq rtn (assq-delete-all (car e) rtn))
21891 (push n rtn))))
21892 alist)
21893 rtn))
21895 (defun org-delete-all (elts list)
21896 "Remove all elements in ELTS from LIST."
21897 (while elts
21898 (setq list (delete (pop elts) list)))
21899 list)
21901 (defun org-count (cl-item cl-seq)
21902 "Count the number of occurrences of ITEM in SEQ.
21903 Taken from `count' in cl-seq.el with all keyword arguments removed."
21904 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21905 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21906 (while (< cl-start cl-end)
21907 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21908 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21909 (setq cl-start (1+ cl-start)))
21910 cl-count))
21912 (defun org-remove-if (predicate seq)
21913 "Remove everything from SEQ that fulfills PREDICATE."
21914 (let (res e)
21915 (while seq
21916 (setq e (pop seq))
21917 (if (not (funcall predicate e)) (push e res)))
21918 (nreverse res)))
21920 (defun org-remove-if-not (predicate seq)
21921 "Remove everything from SEQ that does not fulfill PREDICATE."
21922 (let (res e)
21923 (while seq
21924 (setq e (pop seq))
21925 (if (funcall predicate e) (push e res)))
21926 (nreverse res)))
21928 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21929 "Reduce two-argument FUNCTION across SEQ.
21930 Taken from `reduce' in cl-seq.el with all keyword arguments but
21931 \":initial-value\" removed."
21932 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21933 (cadr (memq :initial-value cl-keys)))
21934 (cl-seq (pop cl-seq))
21935 (t (funcall cl-func)))))
21936 (while cl-seq
21937 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21938 cl-accum))
21940 (defun org-every (pred seq)
21941 "Return true if PREDICATE is true of every element of SEQ.
21942 Adapted from `every' in cl.el."
21943 (catch 'org-every
21944 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21947 (defun org-some (pred seq)
21948 "Return true if PREDICATE is true of any element of SEQ.
21949 Adapted from `some' in cl.el."
21950 (catch 'org-some
21951 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21952 nil))
21954 (defun org-back-over-empty-lines ()
21955 "Move backwards over whitespace, to the beginning of the first empty line.
21956 Returns the number of empty lines passed."
21957 (let ((pos (point)))
21958 (if (cdr (assoc 'heading org-blank-before-new-entry))
21959 (skip-chars-backward " \t\n\r")
21960 (unless (eobp)
21961 (forward-line -1)))
21962 (beginning-of-line 2)
21963 (goto-char (min (point) pos))
21964 (count-lines (point) pos)))
21966 (defun org-skip-whitespace ()
21967 (skip-chars-forward " \t\n\r"))
21969 (defun org-point-in-group (point group &optional context)
21970 "Check if POINT is in match-group GROUP.
21971 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21972 match. If the match group does not exist or point is not inside it,
21973 return nil."
21974 (and (match-beginning group)
21975 (>= point (match-beginning group))
21976 (<= point (match-end group))
21977 (if context
21978 (list context (match-beginning group) (match-end group))
21979 t)))
21981 (defun org-switch-to-buffer-other-window (&rest args)
21982 "Switch to buffer in a second window on the current frame.
21983 In particular, do not allow pop-up frames.
21984 Returns the newly created buffer."
21985 (org-no-popups
21986 (apply 'switch-to-buffer-other-window args)))
21988 (defun org-combine-plists (&rest plists)
21989 "Create a single property list from all plists in PLISTS.
21990 The process starts by copying the first list, and then setting properties
21991 from the other lists. Settings in the last list are the most significant
21992 ones and overrule settings in the other lists."
21993 (let ((rtn (copy-sequence (pop plists)))
21994 p v ls)
21995 (while plists
21996 (setq ls (pop plists))
21997 (while ls
21998 (setq p (pop ls) v (pop ls))
21999 (setq rtn (plist-put rtn p v))))
22000 rtn))
22002 (defun org-replace-escapes (string table)
22003 "Replace %-escapes in STRING with values in TABLE.
22004 TABLE is an association list with keys like \"%a\" and string values.
22005 The sequences in STRING may contain normal field width and padding information,
22006 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22007 so values can contain further %-escapes if they are define later in TABLE."
22008 (let ((tbl (copy-alist table))
22009 (case-fold-search nil)
22010 (pchg 0)
22011 e re rpl)
22012 (while (setq e (pop tbl))
22013 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22014 (when (and (cdr e) (string-match re (cdr e)))
22015 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22016 (safe "SREF"))
22017 (add-text-properties 0 3 (list 'sref sref) safe)
22018 (setcdr e (replace-match safe t t (cdr e)))))
22019 (while (string-match re string)
22020 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22021 (cdr e)))
22022 (setq string (replace-match rpl t t string))))
22023 (while (setq pchg (next-property-change pchg string))
22024 (let ((sref (get-text-property pchg 'sref string)))
22025 (when (and sref (string-match "SREF" string pchg))
22026 (setq string (replace-match sref t t string)))))
22027 string))
22029 (defun org-sublist (list start end)
22030 "Return a section of LIST, from START to END.
22031 Counting starts at 1."
22032 (let (rtn (c start))
22033 (setq list (nthcdr (1- start) list))
22034 (while (and list (<= c end))
22035 (push (pop list) rtn)
22036 (setq c (1+ c)))
22037 (nreverse rtn)))
22039 (defun org-find-base-buffer-visiting (file)
22040 "Like `find-buffer-visiting' but always return the base buffer and
22041 not an indirect buffer."
22042 (let ((buf (or (get-file-buffer file)
22043 (find-buffer-visiting file))))
22044 (if buf
22045 (or (buffer-base-buffer buf) buf)
22046 nil)))
22048 (defun org-image-file-name-regexp (&optional extensions)
22049 "Return regexp matching the file names of images.
22050 If EXTENSIONS is given, only match these."
22051 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22052 (image-file-name-regexp)
22053 (let ((image-file-name-extensions
22054 (or extensions
22055 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22056 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22057 (concat "\\."
22058 (regexp-opt (nconc (mapcar 'upcase
22059 image-file-name-extensions)
22060 image-file-name-extensions)
22062 "\\'"))))
22064 (defun org-file-image-p (file &optional extensions)
22065 "Return non-nil if FILE is an image."
22066 (save-match-data
22067 (string-match (org-image-file-name-regexp extensions) file)))
22069 (defun org-get-cursor-date (&optional with-time)
22070 "Return the date at cursor in as a time.
22071 This works in the calendar and in the agenda, anywhere else it just
22072 returns the current time.
22073 If WITH-TIME is non-nil, returns the time of the event at point (in
22074 the agenda) or the current time of the day."
22075 (let (date day defd tp tm hod mod)
22076 (when with-time
22077 (setq tp (get-text-property (point) 'time))
22078 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22079 (setq hod (string-to-number (match-string 1 tp))
22080 mod (string-to-number (match-string 2 tp))))
22081 (or tp (setq hod (nth 2 (decode-time (current-time)))
22082 mod (nth 1 (decode-time (current-time))))))
22083 (cond
22084 ((eq major-mode 'calendar-mode)
22085 (setq date (calendar-cursor-to-date)
22086 defd (encode-time 0 (or mod 0) (or hod 0)
22087 (nth 1 date) (nth 0 date) (nth 2 date))))
22088 ((eq major-mode 'org-agenda-mode)
22089 (setq day (get-text-property (point) 'day))
22090 (if day
22091 (setq date (calendar-gregorian-from-absolute day)
22092 defd (encode-time 0 (or mod 0) (or hod 0)
22093 (nth 1 date) (nth 0 date) (nth 2 date))))))
22094 (or defd (current-time))))
22096 (defun org-mark-subtree (&optional up)
22097 "Mark the current subtree.
22098 This puts point at the start of the current subtree, and mark at
22099 the end. If a numeric prefix UP is given, move up into the
22100 hierarchy of headlines by UP levels before marking the subtree."
22101 (interactive "P")
22102 (org-with-limited-levels
22103 (cond ((org-at-heading-p) (beginning-of-line))
22104 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22105 (t (outline-previous-visible-heading 1))))
22106 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22107 (if (org-called-interactively-p 'any)
22108 (call-interactively 'org-mark-element)
22109 (org-mark-element)))
22112 ;;; Indentation
22114 (defun org-indent-line ()
22115 "Indent line depending on context."
22116 (interactive)
22117 (let* ((pos (point))
22118 (itemp (org-at-item-p))
22119 (case-fold-search t)
22120 (org-drawer-regexp (or org-drawer-regexp "\000"))
22121 (inline-task-p (and (featurep 'org-inlinetask)
22122 (org-inlinetask-in-task-p)))
22123 (inline-re (and inline-task-p
22124 (org-inlinetask-outline-regexp)))
22125 column)
22126 (if (and orgstruct-is-++ (eq pos (point)))
22127 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22128 (indent-according-to-mode))
22129 (beginning-of-line 1)
22130 (cond
22131 ;; Headings
22132 ((looking-at org-outline-regexp) (setq column 0))
22133 ;; Footnote definition
22134 ((looking-at org-footnote-definition-re) (setq column 0))
22135 ;; Literal examples
22136 ((looking-at "[ \t]*:\\( \\|$\\)")
22137 (setq column (org-get-indentation))) ; do nothing
22138 ;; Lists
22139 ((ignore-errors (goto-char (org-in-item-p)))
22140 (setq column (if itemp
22141 (org-get-indentation)
22142 (org-list-item-body-column (point))))
22143 (goto-char pos))
22144 ;; Drawers
22145 ((and (looking-at "[ \t]*:END:")
22146 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22147 (save-excursion
22148 (goto-char (1- (match-beginning 1)))
22149 (setq column (current-column))))
22150 ;; Special blocks
22151 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22152 (save-excursion
22153 (re-search-backward
22154 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22155 (setq column (org-get-indentation (match-string 0))))
22156 ((and (not (looking-at "[ \t]*#\\+begin_"))
22157 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22158 (save-excursion
22159 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22160 (setq column
22161 (cond ((equal (downcase (match-string 1)) "src")
22162 ;; src blocks: let `org-edit-src-exit' handle them
22163 (org-get-indentation))
22164 ((equal (downcase (match-string 1)) "example")
22165 (max (org-get-indentation)
22166 (org-get-indentation (match-string 0))))
22168 (org-get-indentation (match-string 0))))))
22169 ;; This line has nothing special, look at the previous relevant
22170 ;; line to compute indentation
22172 (beginning-of-line 0)
22173 (while (and (not (bobp))
22174 (not (looking-at org-table-line-regexp))
22175 (not (looking-at org-drawer-regexp))
22176 ;; When point started in an inline task, do not move
22177 ;; above task starting line.
22178 (not (and inline-task-p (looking-at inline-re)))
22179 ;; Skip drawers, blocks, empty lines, verbatim,
22180 ;; comments, tables, footnotes definitions, lists,
22181 ;; inline tasks.
22182 (or (and (looking-at "[ \t]*:END:")
22183 (re-search-backward org-drawer-regexp nil t))
22184 (and (looking-at "[ \t]*#\\+end_")
22185 (re-search-backward "[ \t]*#\\+begin_"nil t))
22186 (looking-at "[ \t]*[\n:#|]")
22187 (looking-at org-footnote-definition-re)
22188 (and (not inline-task-p)
22189 (featurep 'org-inlinetask)
22190 (org-inlinetask-in-task-p)
22191 (or (org-inlinetask-goto-beginning) t))))
22192 (beginning-of-line 0))
22193 (cond
22194 ;; There was a list item above.
22195 ((ignore-errors (goto-char (org-in-item-p)))
22196 (goto-char (org-list-get-top-point (org-list-struct)))
22197 (setq column (org-get-indentation)))
22198 ;; There was an heading above.
22199 ((looking-at "\\*+[ \t]+")
22200 (if (not org-adapt-indentation)
22201 (setq column 0)
22202 (goto-char (match-end 0))
22203 (setq column (current-column))))
22204 ;; A drawer had started and is unfinished
22205 ((looking-at org-drawer-regexp)
22206 (goto-char (1- (match-beginning 1)))
22207 (setq column (current-column)))
22208 ;; Else, nothing noticeable found: get indentation and go on.
22209 (t (setq column (org-get-indentation))))))
22210 ;; Now apply indentation and move cursor accordingly
22211 (goto-char pos)
22212 (if (<= (current-column) (current-indentation))
22213 (org-indent-line-to column)
22214 (save-excursion (org-indent-line-to column)))
22215 ;; Special polishing for properties, see `org-property-format'
22216 (setq column (current-column))
22217 (beginning-of-line 1)
22218 (if (looking-at org-property-re)
22219 (replace-match (concat (match-string 4)
22220 (format org-property-format
22221 (match-string 1) (match-string 3)))
22222 t t))
22223 (org-move-to-column column))))
22225 (defun org-indent-drawer ()
22226 "Indent the drawer at point."
22227 (interactive)
22228 (let ((p (point))
22229 (e (and (save-excursion (re-search-forward ":END:" nil t))
22230 (match-end 0)))
22231 (folded
22232 (save-excursion
22233 (end-of-line)
22234 (when (overlays-at (point))
22235 (member 'invisible (overlay-properties
22236 (car (overlays-at (point)))))))))
22237 (when folded (org-cycle))
22238 (indent-for-tab-command)
22239 (while (and (move-beginning-of-line 2) (< (point) e))
22240 (indent-for-tab-command))
22241 (goto-char p)
22242 (when folded (org-cycle)))
22243 (message "Drawer at point indented"))
22245 (defun org-indent-block ()
22246 "Indent the block at point."
22247 (interactive)
22248 (let ((p (point))
22249 (case-fold-search t)
22250 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22251 (match-end 0)))
22252 (folded
22253 (save-excursion
22254 (end-of-line)
22255 (when (overlays-at (point))
22256 (member 'invisible (overlay-properties
22257 (car (overlays-at (point)))))))))
22258 (when folded (org-cycle))
22259 (indent-for-tab-command)
22260 (while (and (move-beginning-of-line 2) (< (point) e))
22261 (indent-for-tab-command))
22262 (goto-char p)
22263 (when folded (org-cycle)))
22264 (message "Block at point indented"))
22266 (defun org-indent-region (start end)
22267 "Indent region."
22268 (interactive "r")
22269 (save-excursion
22270 (let ((line-end (org-current-line end)))
22271 (goto-char start)
22272 (while (< (org-current-line) line-end)
22273 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22274 (t (call-interactively 'org-indent-line)))
22275 (move-beginning-of-line 2)))))
22278 ;;; Filling
22280 ;; We use our own fill-paragraph and auto-fill functions.
22282 ;; `org-fill-paragraph' relies on adaptive filling and context
22283 ;; checking. Appropriate `fill-prefix' is computed with
22284 ;; `org-adaptive-fill-function'.
22286 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22287 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22288 ;; `org-adaptive-fill-function' value. Internally,
22289 ;; `org-comment-line-break-function' breaks the line.
22291 ;; `org-setup-filling' installs filling and auto-filling related
22292 ;; variables during `org-mode' initialization.
22294 (defvar org-element-paragraph-separate) ; org-element.el
22295 (defun org-setup-filling ()
22296 (require 'org-element)
22297 ;; Prevent auto-fill from inserting unwanted new items.
22298 (when (boundp 'fill-nobreak-predicate)
22299 (org-set-local
22300 'fill-nobreak-predicate
22301 (org-uniquify
22302 (append fill-nobreak-predicate
22303 '(org-fill-line-break-nobreak-p
22304 org-fill-paragraph-with-timestamp-nobreak-p)))))
22305 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22306 (org-set-local 'paragraph-start paragraph-ending)
22307 (org-set-local 'paragraph-separate paragraph-ending))
22308 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22309 (org-set-local 'auto-fill-inhibit-regexp nil)
22310 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22311 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22312 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22314 (defun org-fill-line-break-nobreak-p ()
22315 "Non-nil when a new line at point would create an Org line break."
22316 (save-excursion
22317 (skip-chars-backward "[ \t]")
22318 (skip-chars-backward "\\\\")
22319 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22321 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22322 "Non-nil when a new line at point would split a timestamp."
22323 (and (org-at-timestamp-p t)
22324 (not (looking-at org-ts-regexp-both))))
22326 (declare-function message-in-body-p "message" ())
22327 (defvar orgtbl-line-start-regexp) ; From org-table.el
22328 (defun org-adaptive-fill-function ()
22329 "Compute a fill prefix for the current line.
22330 Return fill prefix, as a string, or nil if current line isn't
22331 meant to be filled. For convenience, if `adaptive-fill-regexp'
22332 matches in paragraphs or comments, use it."
22333 (catch 'exit
22334 (when (derived-mode-p 'message-mode)
22335 (save-excursion
22336 (beginning-of-line)
22337 (cond ((or (not (message-in-body-p))
22338 (looking-at orgtbl-line-start-regexp))
22339 (throw 'exit nil))
22340 ((looking-at message-cite-prefix-regexp)
22341 (throw 'exit (match-string-no-properties 0)))
22342 ((looking-at org-outline-regexp)
22343 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22344 (org-with-wide-buffer
22345 (let* ((p (line-beginning-position))
22346 (element (save-excursion
22347 (beginning-of-line)
22348 (or (ignore-errors (org-element-at-point))
22349 (user-error "An element cannot be parsed line %d"
22350 (line-number-at-pos (point))))))
22351 (type (org-element-type element))
22352 (post-affiliated (org-element-property :post-affiliated element)))
22353 (unless (and post-affiliated (< p post-affiliated))
22354 (case type
22355 (comment
22356 (save-excursion
22357 (beginning-of-line)
22358 (looking-at "[ \t]*")
22359 (concat (match-string 0) "# ")))
22360 (footnote-definition "")
22361 ((item plain-list)
22362 (make-string (org-list-item-body-column
22363 (or post-affiliated
22364 (org-element-property :begin element)))
22365 ? ))
22366 (paragraph
22367 ;; Fill prefix is usually the same as the current line,
22368 ;; unless the paragraph is at the beginning of an item.
22369 (let ((parent (org-element-property :parent element)))
22370 (save-excursion
22371 (beginning-of-line)
22372 (cond ((eq (org-element-type parent) 'item)
22373 (make-string (org-list-item-body-column
22374 (org-element-property :begin parent))
22375 ? ))
22376 ((and adaptive-fill-regexp
22377 ;; Locally disable
22378 ;; `adaptive-fill-function' to let
22379 ;; `fill-context-prefix' handle
22380 ;; `adaptive-fill-regexp' variable.
22381 (let (adaptive-fill-function)
22382 (fill-context-prefix
22383 post-affiliated
22384 (org-element-property :end element)))))
22385 ((looking-at "[ \t]+") (match-string 0))
22386 (t "")))))
22387 (comment-block
22388 ;; Only fill contents if P is within block boundaries.
22389 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22390 (forward-line)
22391 (point)))
22392 (cend (save-excursion
22393 (goto-char (org-element-property :end element))
22394 (skip-chars-backward " \r\t\n")
22395 (line-beginning-position))))
22396 (when (and (>= p cbeg) (< p cend))
22397 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22398 (match-string 0)
22399 ""))))))))))
22401 (declare-function message-goto-body "message" ())
22402 (defvar message-cite-prefix-regexp) ; From message.el
22403 (defun org-fill-paragraph (&optional justify)
22404 "Fill element at point, when applicable.
22406 This function only applies to comment blocks, comments, example
22407 blocks and paragraphs. Also, as a special case, re-align table
22408 when point is at one.
22410 If JUSTIFY is non-nil (interactively, with prefix argument),
22411 justify as well. If `sentence-end-double-space' is non-nil, then
22412 period followed by one space does not end a sentence, so don't
22413 break a line there. The variable `fill-column' controls the
22414 width for filling.
22416 For convenience, when point is at a plain list, an item or
22417 a footnote definition, try to fill the first paragraph within."
22418 (interactive)
22419 (if (and (derived-mode-p 'message-mode)
22420 (or (not (message-in-body-p))
22421 (save-excursion (move-beginning-of-line 1)
22422 (looking-at message-cite-prefix-regexp))))
22423 ;; First ensure filling is correct in message-mode.
22424 (let ((fill-paragraph-function
22425 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22426 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22427 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22428 (paragraph-separate
22429 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22430 (fill-paragraph nil))
22431 (with-syntax-table org-mode-transpose-word-syntax-table
22432 ;; Move to end of line in order to get the first paragraph
22433 ;; within a plain list or a footnote definition.
22434 (let ((element (save-excursion
22435 (end-of-line)
22436 (or (ignore-errors (org-element-at-point))
22437 (user-error "An element cannot be parsed line %d"
22438 (line-number-at-pos (point)))))))
22439 ;; First check if point is in a blank line at the beginning of
22440 ;; the buffer. In that case, ignore filling.
22441 (case (org-element-type element)
22442 ;; Use major mode filling function is src blocks.
22443 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22444 ;; Align Org tables, leave table.el tables as-is.
22445 (table-row (org-table-align) t)
22446 (table
22447 (when (eq (org-element-property :type element) 'org)
22448 (save-excursion
22449 (goto-char (org-element-property :post-affiliated element))
22450 (org-table-align)))
22452 (paragraph
22453 ;; Paragraphs may contain `line-break' type objects.
22454 (let ((beg (max (point-min)
22455 (org-element-property :contents-begin element)))
22456 (end (min (point-max)
22457 (org-element-property :contents-end element))))
22458 ;; Do nothing if point is at an affiliated keyword.
22459 (if (< (line-end-position) beg) t
22460 (when (derived-mode-p 'message-mode)
22461 ;; In `message-mode', do not fill following citation
22462 ;; in current paragraph nor text before message body.
22463 (let ((body-start (save-excursion (message-goto-body))))
22464 (when body-start (setq beg (max body-start beg))))
22465 (when (save-excursion
22466 (re-search-forward
22467 (concat "^" message-cite-prefix-regexp) end t))
22468 (setq end (match-beginning 0))))
22469 ;; Fill paragraph, taking line breaks into account.
22470 ;; For that, slice the paragraph using line breaks as
22471 ;; separators, and fill the parts in reverse order to
22472 ;; avoid messing with markers.
22473 (save-excursion
22474 (goto-char end)
22475 (mapc
22476 (lambda (pos)
22477 (fill-region-as-paragraph pos (point) justify)
22478 (goto-char pos))
22479 ;; Find the list of ending positions for line breaks
22480 ;; in the current paragraph. Add paragraph
22481 ;; beginning to include first slice.
22482 (nreverse
22483 (cons beg
22484 (org-element-map
22485 (org-element--parse-objects
22486 beg end nil (org-element-restriction 'paragraph))
22487 'line-break
22488 (lambda (lb) (org-element-property :end lb)))))))
22489 t)))
22490 ;; Contents of `comment-block' type elements should be
22491 ;; filled as plain text, but only if point is within block
22492 ;; markers.
22493 (comment-block
22494 (let* ((case-fold-search t)
22495 (beg (save-excursion
22496 (goto-char (org-element-property :begin element))
22497 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22498 (forward-line)
22499 (point)))
22500 (end (save-excursion
22501 (goto-char (org-element-property :end element))
22502 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22503 (line-beginning-position))))
22504 (if (or (< (point) beg) (> (point) end)) t
22505 (fill-region-as-paragraph
22506 (save-excursion (end-of-line)
22507 (re-search-backward "^[ \t]*$" beg 'move)
22508 (line-beginning-position))
22509 (save-excursion (beginning-of-line)
22510 (re-search-forward "^[ \t]*$" end 'move)
22511 (line-beginning-position))
22512 justify))))
22513 ;; Fill comments.
22514 (comment
22515 (let ((begin (org-element-property :post-affiliated element))
22516 (end (org-element-property :end element)))
22517 (when (and (>= (point) begin) (<= (point) end))
22518 (let ((begin (save-excursion
22519 (end-of-line)
22520 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22521 (progn (forward-line) (point))
22522 begin)))
22523 (end (save-excursion
22524 (end-of-line)
22525 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22526 (1- (line-beginning-position))
22527 (skip-chars-backward " \r\t\n")
22528 (line-end-position)))))
22529 ;; Do not fill comments when at a blank line.
22530 (when (> end begin)
22531 (let ((fill-prefix
22532 (save-excursion
22533 (beginning-of-line)
22534 (looking-at "[ \t]*#")
22535 (let ((comment-prefix (match-string 0)))
22536 (goto-char (match-end 0))
22537 (if (looking-at adaptive-fill-regexp)
22538 (concat comment-prefix (match-string 0))
22539 (concat comment-prefix " "))))))
22540 (save-excursion
22541 (fill-region-as-paragraph begin end justify))))))
22543 ;; Ignore every other element.
22544 (otherwise t))))))
22546 (defun org-auto-fill-function ()
22547 "Auto-fill function."
22548 ;; Check if auto-filling is meaningful.
22549 (let ((fc (current-fill-column)))
22550 (when (and fc (> (current-column) fc))
22551 (let* ((fill-prefix (org-adaptive-fill-function))
22552 ;; Enforce empty fill prefix, if required. Otherwise, it
22553 ;; will be computed again.
22554 (adaptive-fill-mode (not (equal fill-prefix ""))))
22555 (when fill-prefix (do-auto-fill))))))
22557 (defun org-comment-line-break-function (&optional soft)
22558 "Break line at point and indent, continuing comment if within one.
22559 The inserted newline is marked hard if variable
22560 `use-hard-newlines' is true, unless optional argument SOFT is
22561 non-nil."
22562 (if soft (insert-and-inherit ?\n) (newline 1))
22563 (save-excursion (forward-char -1) (delete-horizontal-space))
22564 (delete-horizontal-space)
22565 (indent-to-left-margin)
22566 (insert-before-markers-and-inherit fill-prefix))
22569 ;;; Comments
22571 ;; Org comments syntax is quite complex. It requires the entire line
22572 ;; to be just a comment. Also, even with the right syntax at the
22573 ;; beginning of line, some some elements (i.e. verse-block or
22574 ;; example-block) don't accept comments. Usual Emacs comment commands
22575 ;; cannot cope with those requirements. Therefore, Org replaces them.
22577 ;; Org still relies on `comment-dwim', but cannot trust
22578 ;; `comment-only-p'. So, `comment-region-function' and
22579 ;; `uncomment-region-function' both point
22580 ;; to`org-comment-or-uncomment-region'. Eventually,
22581 ;; `org-insert-comment' takes care of insertion of comments at the
22582 ;; beginning of line.
22584 ;; `org-setup-comments-handling' install comments related variables
22585 ;; during `org-mode' initialization.
22587 (defun org-setup-comments-handling ()
22588 (interactive)
22589 (org-set-local 'comment-use-syntax nil)
22590 (org-set-local 'comment-start "# ")
22591 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22592 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22593 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22594 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22596 (defun org-insert-comment ()
22597 "Insert an empty comment above current line.
22598 If the line is empty, insert comment at its beginning. When
22599 point is within a source block, comment according to the related
22600 major mode."
22601 (if (let ((element (org-element-at-point)))
22602 (and (eq (org-element-type element) 'src-block)
22603 (< (save-excursion
22604 (goto-char (org-element-property :post-affiliated element))
22605 (line-end-position))
22606 (point))
22607 (> (save-excursion
22608 (goto-char (org-element-property :end element))
22609 (skip-chars-backward " \r\t\n")
22610 (line-beginning-position))
22611 (point))))
22612 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22613 (beginning-of-line)
22614 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22615 (open-line 1))
22616 (org-indent-line)
22617 (insert "# ")))
22619 (defvar comment-empty-lines) ; From newcomment.el.
22620 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22621 "Comment or uncomment each non-blank line in the region.
22622 Uncomment each non-blank line between BEG and END if it only
22623 contains commented lines. Otherwise, comment them. If region is
22624 strictly within a source block, use appropriate comment syntax."
22625 (if (let ((element (org-element-at-point)))
22626 (and (eq (org-element-type element) 'src-block)
22627 (< (save-excursion
22628 (goto-char (org-element-property :post-affiliated element))
22629 (line-end-position))
22630 beg)
22631 (>= (save-excursion
22632 (goto-char (org-element-property :end element))
22633 (skip-chars-backward " \r\t\n")
22634 (line-beginning-position))
22635 end)))
22636 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22637 (save-restriction
22638 ;; Restrict region
22639 (narrow-to-region (save-excursion (goto-char beg)
22640 (skip-chars-forward " \r\t\n" end)
22641 (line-beginning-position))
22642 (save-excursion (goto-char end)
22643 (skip-chars-backward " \r\t\n" beg)
22644 (line-end-position)))
22645 (let ((uncommentp
22646 ;; UNCOMMENTP is non-nil when every non blank line between
22647 ;; BEG and END is a comment.
22648 (save-excursion
22649 (goto-char (point-min))
22650 (while (and (not (eobp))
22651 (let ((element (org-element-at-point)))
22652 (and (eq (org-element-type element) 'comment)
22653 (goto-char (min (point-max)
22654 (org-element-property
22655 :end element)))))))
22656 (eobp))))
22657 (if uncommentp
22658 ;; Only blank lines and comments in region: uncomment it.
22659 (save-excursion
22660 (goto-char (point-min))
22661 (while (not (eobp))
22662 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22663 (replace-match "" nil nil nil 1))
22664 (forward-line)))
22665 ;; Comment each line in region.
22666 (let ((min-indent (point-max)))
22667 ;; First find the minimum indentation across all lines.
22668 (save-excursion
22669 (goto-char (point-min))
22670 (while (and (not (eobp)) (not (zerop min-indent)))
22671 (unless (looking-at "[ \t]*$")
22672 (setq min-indent (min min-indent (current-indentation))))
22673 (forward-line)))
22674 ;; Then loop over all lines.
22675 (save-excursion
22676 (goto-char (point-min))
22677 (while (not (eobp))
22678 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22679 ;; Don't get fooled by invisible text (e.g. link path)
22680 ;; when moving to column MIN-INDENT.
22681 (let ((buffer-invisibility-spec nil))
22682 (org-move-to-column min-indent t))
22683 (insert comment-start))
22684 (forward-line)))))))))
22686 (defun org-comment-dwim (arg)
22687 (interactive "*P")
22688 "Call `comment-dwim' within a source edit buffer if needed."
22689 (if (org-in-src-block-p)
22690 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22691 (call-interactively #'comment-dwim)))
22694 ;;; Planning
22696 ;; This section contains tools to operate on timestamp objects, as
22697 ;; returned by, e.g. `org-element-context'.
22699 (defun org-timestamp-has-time-p (timestamp)
22700 "Non-nil when TIMESTAMP has a time specified."
22701 (org-element-property :hour-start timestamp))
22703 (defun org-timestamp-format (timestamp format &optional end utc)
22704 "Format a TIMESTAMP element into a string.
22706 FORMAT is a format specifier to be passed to
22707 `format-time-string'.
22709 When optional argument END is non-nil, use end of date-range or
22710 time-range, if possible.
22712 When optional argument UTC is non-nil, time will be expressed as
22713 Universal Time."
22714 (format-time-string
22715 format
22716 (apply 'encode-time
22717 (cons 0
22718 (mapcar
22719 (lambda (prop) (or (org-element-property prop timestamp) 0))
22720 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22721 '(:minute-start :hour-start :day-start :month-start
22722 :year-start)))))
22723 utc))
22725 (defun org-timestamp-split-range (timestamp &optional end)
22726 "Extract a timestamp object from a date or time range.
22728 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22729 the end of the range. Otherwise, extract its start.
22731 Return a new timestamp object sharing the same parent as
22732 TIMESTAMP."
22733 (let ((type (org-element-property :type timestamp)))
22734 (if (memq type '(active inactive diary)) timestamp
22735 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22736 ;; Set new type.
22737 (org-element-put-property
22738 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22739 ;; Copy start properties over end properties if END is
22740 ;; non-nil. Otherwise, copy end properties over `start' ones.
22741 (let ((p-alist '((:minute-start . :minute-end)
22742 (:hour-start . :hour-end)
22743 (:day-start . :day-end)
22744 (:month-start . :month-end)
22745 (:year-start . :year-end))))
22746 (dolist (p-cell p-alist)
22747 (org-element-put-property
22748 split-ts
22749 (funcall (if end 'car 'cdr) p-cell)
22750 (org-element-property
22751 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22752 ;; Eventually refresh `:raw-value'.
22753 (org-element-put-property split-ts :raw-value nil)
22754 (org-element-put-property
22755 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22757 (defun org-timestamp-translate (timestamp &optional boundary)
22758 "Apply `org-translate-time' on a TIMESTAMP object.
22759 When optional argument BOUNDARY is non-nil, it is either the
22760 symbol `start' or `end'. In this case, only translate the
22761 starting or ending part of TIMESTAMP if it is a date or time
22762 range. Otherwise, translate both parts."
22763 (if (and (not boundary)
22764 (memq (org-element-property :type timestamp)
22765 '(active-range inactive-range)))
22766 (concat
22767 (org-translate-time
22768 (org-element-property :raw-value
22769 (org-timestamp-split-range timestamp)))
22770 "--"
22771 (org-translate-time
22772 (org-element-property :raw-value
22773 (org-timestamp-split-range timestamp t))))
22774 (org-translate-time
22775 (org-element-property
22776 :raw-value
22777 (if (not boundary) timestamp
22778 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22782 ;;; Other stuff.
22784 (defun org-toggle-fixed-width-section (arg)
22785 "Toggle the fixed-width export.
22786 If there is no active region, the QUOTE keyword at the current headline is
22787 inserted or removed. When present, it causes the text between this headline
22788 and the next to be exported as fixed-width text, and unmodified.
22789 If there is an active region, this command adds or removes a colon as the
22790 first character of this line. If the first character of a line is a colon,
22791 this line is also exported in fixed-width font."
22792 (interactive "P")
22793 (let* ((cc 0)
22794 (regionp (org-region-active-p))
22795 (beg (if regionp (region-beginning) (point)))
22796 (end (if regionp (region-end)))
22797 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22798 (case-fold-search nil)
22799 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22800 off)
22801 (if regionp
22802 (save-excursion
22803 (goto-char beg)
22804 (setq cc (current-column))
22805 (beginning-of-line 1)
22806 (setq off (looking-at re))
22807 (while (> nlines 0)
22808 (setq nlines (1- nlines))
22809 (beginning-of-line 1)
22810 (cond
22811 (arg
22812 (org-move-to-column cc t)
22813 (insert ": \n")
22814 (forward-line -1))
22815 ((and off (looking-at re))
22816 (replace-match "" t t nil 1))
22817 ((not off) (org-move-to-column cc t) (insert ": ")))
22818 (forward-line 1)))
22819 (save-excursion
22820 (org-back-to-heading)
22821 (cond
22822 ((looking-at (format org-heading-keyword-regexp-format
22823 org-quote-string))
22824 (goto-char (match-end 1))
22825 (looking-at (concat " +" org-quote-string))
22826 (replace-match "" t t)
22827 (when (eolp) (insert " ")))
22828 ((looking-at org-outline-regexp)
22829 (goto-char (match-end 0))
22830 (insert org-quote-string " ")))))))
22832 (defun org-reftex-citation ()
22833 "Use reftex-citation to insert a citation into the buffer.
22834 This looks for a line like
22836 #+BIBLIOGRAPHY: foo plain option:-d
22838 and derives from it that foo.bib is the bibliography file relevant
22839 for this document. It then installs the necessary environment for RefTeX
22840 to work in this buffer and calls `reftex-citation' to insert a citation
22841 into the buffer.
22843 Export of such citations to both LaTeX and HTML is handled by the contributed
22844 package ox-bibtex by Taru Karttunen."
22845 (interactive)
22846 (let ((reftex-docstruct-symbol 'rds)
22847 (reftex-cite-format "\\cite{%l}")
22848 rds bib)
22849 (save-excursion
22850 (save-restriction
22851 (widen)
22852 (let ((case-fold-search t)
22853 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22854 (if (not (save-excursion
22855 (or (re-search-forward re nil t)
22856 (re-search-backward re nil t))))
22857 (error "No bibliography defined in file")
22858 (setq bib (concat (match-string 1) ".bib")
22859 rds (list (list 'bib bib)))))))
22860 (call-interactively 'reftex-citation)))
22862 ;;;; Functions extending outline functionality
22864 (defun org-beginning-of-line (&optional arg)
22865 "Go to the beginning of the current line. If that is invisible, continue
22866 to a visible line beginning. This makes the function of C-a more intuitive.
22867 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22868 first attempt, and only move to after the tags when the cursor is already
22869 beyond the end of the headline."
22870 (interactive "P")
22871 (let ((pos (point))
22872 (special (if (consp org-special-ctrl-a/e)
22873 (car org-special-ctrl-a/e)
22874 org-special-ctrl-a/e))
22875 deactivate-mark refpos)
22876 (if (org-bound-and-true-p visual-line-mode)
22877 (beginning-of-visual-line 1)
22878 (beginning-of-line 1))
22879 (if (and arg (fboundp 'move-beginning-of-line))
22880 (call-interactively 'move-beginning-of-line)
22881 (if (bobp)
22883 (backward-char 1)
22884 (if (org-truely-invisible-p)
22885 (while (and (not (bobp)) (org-truely-invisible-p))
22886 (backward-char 1)
22887 (beginning-of-line 1))
22888 (forward-char 1))))
22889 (when special
22890 (cond
22891 ((and (looking-at org-complex-heading-regexp)
22892 (= (char-after (match-end 1)) ?\ ))
22893 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22894 (point-at-eol)))
22895 (goto-char
22896 (if (eq special t)
22897 (cond ((> pos refpos) refpos)
22898 ((= pos (point)) refpos)
22899 (t (point)))
22900 (cond ((> pos (point)) (point))
22901 ((not (eq last-command this-command)) (point))
22902 (t refpos)))))
22903 ((org-at-item-p)
22904 ;; Being at an item and not looking at an the item means point
22905 ;; was previously moved to beginning of a visual line, which
22906 ;; doesn't contain the item. Therefore, do nothing special,
22907 ;; just stay here.
22908 (when (looking-at org-list-full-item-re)
22909 ;; Set special position at first white space character after
22910 ;; bullet, and check-box, if any.
22911 (let ((after-bullet
22912 (let ((box (match-end 3)))
22913 (if (not box) (match-end 1)
22914 (let ((after (char-after box)))
22915 (if (and after (= after ? )) (1+ box) box))))))
22916 ;; Special case: Move point to special position when
22917 ;; currently after it or at beginning of line.
22918 (if (eq special t)
22919 (when (or (> pos after-bullet) (= (point) pos))
22920 (goto-char after-bullet))
22921 ;; Reversed case: Move point to special position when
22922 ;; point was already at beginning of line and command is
22923 ;; repeated.
22924 (when (and (= (point) pos) (eq last-command this-command))
22925 (goto-char after-bullet))))))))
22926 (org-no-warnings
22927 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22928 (setq disable-point-adjustment
22929 (or (not (invisible-p (point)))
22930 (not (invisible-p (max (point-min) (1- (point))))))))
22932 (defun org-end-of-line (&optional arg)
22933 "Go to the end of the line.
22934 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22935 tags on the first attempt, and only move to after the tags when
22936 the cursor is already beyond the end of the headline."
22937 (interactive "P")
22938 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22939 org-special-ctrl-a/e))
22940 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22941 'end-of-visual-line)
22942 ((fboundp 'move-end-of-line) 'move-end-of-line)
22943 (t 'end-of-line)))
22944 deactivate-mark)
22945 (if (or (not special) arg) (call-interactively move-fun)
22946 (let* ((element (save-excursion (beginning-of-line)
22947 (org-element-at-point)))
22948 (type (org-element-type element)))
22949 (cond
22950 ((memq type '(headline inlinetask))
22951 (let ((pos (point)))
22952 (beginning-of-line 1)
22953 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22954 (if (eq special t)
22955 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22956 (goto-char (match-beginning 1))
22957 (goto-char (match-end 0)))
22958 (if (or (< pos (match-end 0))
22959 (not (eq this-command last-command)))
22960 (goto-char (match-end 0))
22961 (goto-char (match-beginning 1))))
22962 (call-interactively move-fun))))
22963 ((outline-invisible-p (line-end-position))
22964 ;; If element is hidden, `move-end-of-line' would put point
22965 ;; after it. Use `end-of-line' to stay on current line.
22966 (call-interactively 'end-of-line))
22967 (t (call-interactively move-fun)))))
22968 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22969 (setq disable-point-adjustment
22970 (or (not (invisible-p (point)))
22971 (not (invisible-p (max (point-min) (1- (point))))))))
22973 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22974 (define-key org-mode-map "\C-e" 'org-end-of-line)
22976 (defun org-backward-sentence (&optional arg)
22977 "Go to beginning of sentence, or beginning of table field.
22978 This will call `backward-sentence' or `org-table-beginning-of-field',
22979 depending on context."
22980 (interactive "P")
22981 (cond
22982 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22983 (t (call-interactively 'backward-sentence))))
22985 (defun org-forward-sentence (&optional arg)
22986 "Go to end of sentence, or end of table field.
22987 This will call `forward-sentence' or `org-table-end-of-field',
22988 depending on context."
22989 (interactive "P")
22990 (cond
22991 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22992 (t (call-interactively 'forward-sentence))))
22994 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22995 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22997 (defun org-kill-line (&optional arg)
22998 "Kill line, to tags or end of line."
22999 (interactive "P")
23000 (cond
23001 ((or (not org-special-ctrl-k)
23002 (bolp)
23003 (not (org-at-heading-p)))
23004 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23005 org-ctrl-k-protect-subtree)
23006 (if (or (eq org-ctrl-k-protect-subtree 'error)
23007 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23008 (user-error "C-k aborted as it would kill a hidden subtree")))
23009 (call-interactively
23010 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23011 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23012 (kill-region (point) (match-beginning 1))
23013 (org-set-tags nil t))
23014 (t (kill-region (point) (point-at-eol)))))
23016 (define-key org-mode-map "\C-k" 'org-kill-line)
23018 (defun org-yank (&optional arg)
23019 "Yank. If the kill is a subtree, treat it specially.
23020 This command will look at the current kill and check if is a single
23021 subtree, or a series of subtrees[1]. If it passes the test, and if the
23022 cursor is at the beginning of a line or after the stars of a currently
23023 empty headline, then the yank is handled specially. How exactly depends
23024 on the value of the following variables, both set by default.
23026 org-yank-folded-subtrees
23027 When set, the subtree(s) will be folded after insertion, but only
23028 if doing so would now swallow text after the yanked text.
23030 org-yank-adjusted-subtrees
23031 When set, the subtree will be promoted or demoted in order to
23032 fit into the local outline tree structure, which means that the level
23033 will be adjusted so that it becomes the smaller one of the two
23034 *visible* surrounding headings.
23036 Any prefix to this command will cause `yank' to be called directly with
23037 no special treatment. In particular, a simple \\[universal-argument] prefix \
23038 will just
23039 plainly yank the text as it is.
23041 \[1] The test checks if the first non-white line is a heading
23042 and if there are no other headings with fewer stars."
23043 (interactive "P")
23044 (org-yank-generic 'yank arg))
23046 (defun org-yank-generic (command arg)
23047 "Perform some yank-like command.
23049 This function implements the behavior described in the `org-yank'
23050 documentation. However, it has been generalized to work for any
23051 interactive command with similar behavior."
23053 ;; pretend to be command COMMAND
23054 (setq this-command command)
23056 (if arg
23057 (call-interactively command)
23059 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23060 (and (org-kill-is-subtree-p)
23061 (or (bolp)
23062 (and (looking-at "[ \t]*$")
23063 (string-match
23064 "\\`\\*+\\'"
23065 (buffer-substring (point-at-bol) (point)))))))
23066 swallowp)
23067 (cond
23068 ((and subtreep org-yank-folded-subtrees)
23069 (let ((beg (point))
23070 end)
23071 (if (and subtreep org-yank-adjusted-subtrees)
23072 (org-paste-subtree nil nil 'for-yank)
23073 (call-interactively command))
23075 (setq end (point))
23076 (goto-char beg)
23077 (when (and (bolp) subtreep
23078 (not (setq swallowp
23079 (org-yank-folding-would-swallow-text beg end))))
23080 (org-with-limited-levels
23081 (or (looking-at org-outline-regexp)
23082 (re-search-forward org-outline-regexp-bol end t))
23083 (while (and (< (point) end) (looking-at org-outline-regexp))
23084 (hide-subtree)
23085 (org-cycle-show-empty-lines 'folded)
23086 (condition-case nil
23087 (outline-forward-same-level 1)
23088 (error (goto-char end))))))
23089 (when swallowp
23090 (message
23091 "Inserted text not folded because that would swallow text"))
23093 (goto-char end)
23094 (skip-chars-forward " \t\n\r")
23095 (beginning-of-line 1)
23096 (push-mark beg 'nomsg)))
23097 ((and subtreep org-yank-adjusted-subtrees)
23098 (let ((beg (point-at-bol)))
23099 (org-paste-subtree nil nil 'for-yank)
23100 (push-mark beg 'nomsg)))
23102 (call-interactively command))))))
23104 (defun org-yank-folding-would-swallow-text (beg end)
23105 "Would hide-subtree at BEG swallow any text after END?"
23106 (let (level)
23107 (org-with-limited-levels
23108 (save-excursion
23109 (goto-char beg)
23110 (when (or (looking-at org-outline-regexp)
23111 (re-search-forward org-outline-regexp-bol end t))
23112 (setq level (org-outline-level)))
23113 (goto-char end)
23114 (skip-chars-forward " \t\r\n\v\f")
23115 (if (or (eobp)
23116 (and (bolp) (looking-at org-outline-regexp)
23117 (<= (org-outline-level) level)))
23118 nil ; Nothing would be swallowed
23119 t))))) ; something would swallow
23121 (define-key org-mode-map "\C-y" 'org-yank)
23123 (defun org-truely-invisible-p ()
23124 "Check if point is at a character currently not visible.
23125 This version does not only check the character property, but also
23126 `visible-mode'."
23127 ;; Early versions of noutline don't have `outline-invisible-p'.
23128 (if (org-bound-and-true-p visible-mode)
23130 (outline-invisible-p)))
23132 (defun org-invisible-p2 ()
23133 "Check if point is at a character currently not visible."
23134 (save-excursion
23135 (if (and (eolp) (not (bobp))) (backward-char 1))
23136 ;; Early versions of noutline don't have `outline-invisible-p'.
23137 (outline-invisible-p)))
23139 (defun org-back-to-heading (&optional invisible-ok)
23140 "Call `outline-back-to-heading', but provide a better error message."
23141 (condition-case nil
23142 (outline-back-to-heading invisible-ok)
23143 (error (error "Before first headline at position %d in buffer %s"
23144 (point) (current-buffer)))))
23146 (defun org-before-first-heading-p ()
23147 "Before first heading?"
23148 (save-excursion
23149 (end-of-line)
23150 (null (re-search-backward org-outline-regexp-bol nil t))))
23152 (defun org-at-heading-p (&optional ignored)
23153 (outline-on-heading-p t))
23154 ;; Compatibility alias with Org versions < 7.8.03
23155 (defalias 'org-on-heading-p 'org-at-heading-p)
23157 (defun org-at-comment-p nil
23158 "Is cursor in a line starting with a # character?"
23159 (save-excursion
23160 (beginning-of-line)
23161 (looking-at "^#")))
23163 (defun org-at-drawer-p nil
23164 "Is cursor at a drawer keyword?"
23165 (save-excursion
23166 (move-beginning-of-line 1)
23167 (looking-at org-drawer-regexp)))
23169 (defun org-at-block-p nil
23170 "Is cursor at a block keyword?"
23171 (save-excursion
23172 (move-beginning-of-line 1)
23173 (looking-at org-block-regexp)))
23175 (defun org-point-at-end-of-empty-headline ()
23176 "If point is at the end of an empty headline, return t, else nil.
23177 If the heading only contains a TODO keyword, it is still still considered
23178 empty."
23179 (and (looking-at "[ \t]*$")
23180 (when org-todo-line-regexp
23181 (save-excursion
23182 (beginning-of-line 1)
23183 (let ((case-fold-search nil))
23184 (looking-at org-todo-line-regexp)
23185 (string= (match-string 3) ""))))))
23187 (defun org-at-heading-or-item-p ()
23188 (or (org-at-heading-p) (org-at-item-p)))
23190 (defun org-at-target-p ()
23191 (or (org-in-regexp org-radio-target-regexp)
23192 (org-in-regexp org-target-regexp)))
23193 ;; Compatibility alias with Org versions < 7.8.03
23194 (defalias 'org-on-target-p 'org-at-target-p)
23196 (defun org-up-heading-all (arg)
23197 "Move to the heading line of which the present line is a subheading.
23198 This function considers both visible and invisible heading lines.
23199 With argument, move up ARG levels."
23200 (if (fboundp 'outline-up-heading-all)
23201 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23202 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23204 (defun org-up-heading-safe ()
23205 "Move to the heading line of which the present line is a subheading.
23206 This version will not throw an error. It will return the level of the
23207 headline found, or nil if no higher level is found.
23209 Also, this function will be a lot faster than `outline-up-heading',
23210 because it relies on stars being the outline starters. This can really
23211 make a significant difference in outlines with very many siblings."
23212 (let (start-level re)
23213 (org-back-to-heading t)
23214 (setq start-level (funcall outline-level))
23215 (if (equal start-level 1)
23217 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23218 (if (re-search-backward re nil t)
23219 (funcall outline-level)))))
23221 (defun org-first-sibling-p ()
23222 "Is this heading the first child of its parents?"
23223 (interactive)
23224 (let ((re org-outline-regexp-bol)
23225 level l)
23226 (unless (org-at-heading-p t)
23227 (user-error "Not at a heading"))
23228 (setq level (funcall outline-level))
23229 (save-excursion
23230 (if (not (re-search-backward re nil t))
23232 (setq l (funcall outline-level))
23233 (< l level)))))
23235 (defun org-goto-sibling (&optional previous)
23236 "Goto the next sibling, even if it is invisible.
23237 When PREVIOUS is set, go to the previous sibling instead. Returns t
23238 when a sibling was found. When none is found, return nil and don't
23239 move point."
23240 (let ((fun (if previous 're-search-backward 're-search-forward))
23241 (pos (point))
23242 (re org-outline-regexp-bol)
23243 level l)
23244 (when (condition-case nil (org-back-to-heading t) (error nil))
23245 (setq level (funcall outline-level))
23246 (catch 'exit
23247 (or previous (forward-char 1))
23248 (while (funcall fun re nil t)
23249 (setq l (funcall outline-level))
23250 (when (< l level) (goto-char pos) (throw 'exit nil))
23251 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23252 (goto-char pos)
23253 nil))))
23255 (defun org-show-siblings ()
23256 "Show all siblings of the current headline."
23257 (save-excursion
23258 (while (org-goto-sibling) (org-flag-heading nil)))
23259 (save-excursion
23260 (while (org-goto-sibling 'previous)
23261 (org-flag-heading nil))))
23263 (defun org-goto-first-child ()
23264 "Goto the first child, even if it is invisible.
23265 Return t when a child was found. Otherwise don't move point and
23266 return nil."
23267 (let (level (pos (point)) (re org-outline-regexp-bol))
23268 (when (condition-case nil (org-back-to-heading t) (error nil))
23269 (setq level (outline-level))
23270 (forward-char 1)
23271 (if (and (re-search-forward re nil t) (> (outline-level) level))
23272 (progn (goto-char (match-beginning 0)) t)
23273 (goto-char pos) nil))))
23275 (defun org-show-hidden-entry ()
23276 "Show an entry where even the heading is hidden."
23277 (save-excursion
23278 (org-show-entry)))
23280 (defun org-flag-heading (flag &optional entry)
23281 "Flag the current heading. FLAG non-nil means make invisible.
23282 When ENTRY is non-nil, show the entire entry."
23283 (save-excursion
23284 (org-back-to-heading t)
23285 ;; Check if we should show the entire entry
23286 (if entry
23287 (progn
23288 (org-show-entry)
23289 (save-excursion
23290 (and (outline-next-heading)
23291 (org-flag-heading nil))))
23292 (outline-flag-region (max (point-min) (1- (point)))
23293 (save-excursion (outline-end-of-heading) (point))
23294 flag))))
23296 (defun org-get-next-sibling ()
23297 "Move to next heading of the same level, and return point.
23298 If there is no such heading, return nil.
23299 This is like outline-next-sibling, but invisible headings are ok."
23300 (let ((level (funcall outline-level)))
23301 (outline-next-heading)
23302 (while (and (not (eobp)) (> (funcall outline-level) level))
23303 (outline-next-heading))
23304 (if (or (eobp) (< (funcall outline-level) level))
23306 (point))))
23308 (defun org-get-last-sibling ()
23309 "Move to previous heading of the same level, and return point.
23310 If there is no such heading, return nil."
23311 (let ((opoint (point))
23312 (level (funcall outline-level)))
23313 (outline-previous-heading)
23314 (when (and (/= (point) opoint) (outline-on-heading-p t))
23315 (while (and (> (funcall outline-level) level)
23316 (not (bobp)))
23317 (outline-previous-heading))
23318 (if (< (funcall outline-level) level)
23320 (point)))))
23322 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23323 "Goto to the end of a subtree."
23324 ;; This contains an exact copy of the original function, but it uses
23325 ;; `org-back-to-heading', to make it work also in invisible
23326 ;; trees. And is uses an invisible-ok argument.
23327 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23328 ;; Furthermore, when used inside Org, finding the end of a large subtree
23329 ;; with many children and grandchildren etc, this can be much faster
23330 ;; than the outline version.
23331 (org-back-to-heading invisible-ok)
23332 (let ((first t)
23333 (level (funcall outline-level)))
23334 (if (and (derived-mode-p 'org-mode) (< level 1000))
23335 ;; A true heading (not a plain list item), in Org-mode
23336 ;; This means we can easily find the end by looking
23337 ;; only for the right number of stars. Using a regexp to do
23338 ;; this is so much faster than using a Lisp loop.
23339 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23340 (forward-char 1)
23341 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23342 ;; something else, do it the slow way
23343 (while (and (not (eobp))
23344 (or first (> (funcall outline-level) level)))
23345 (setq first nil)
23346 (outline-next-heading)))
23347 (unless to-heading
23348 (if (memq (preceding-char) '(?\n ?\^M))
23349 (progn
23350 ;; Go to end of line before heading
23351 (forward-char -1)
23352 (if (memq (preceding-char) '(?\n ?\^M))
23353 ;; leave blank line before heading
23354 (forward-char -1))))))
23355 (point))
23357 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23358 "Use Org version in org-mode, for dramatic speed-up."
23359 (if (derived-mode-p 'org-mode)
23360 (progn
23361 (org-end-of-subtree nil t)
23362 (unless (eobp) (backward-char 1)))
23363 ad-do-it))
23365 (defun org-end-of-meta-data-and-drawers ()
23366 "Jump to the first text after meta data and drawers in the current entry.
23367 This will move over empty lines, lines with planning time stamps,
23368 clocking lines, and drawers."
23369 (org-back-to-heading t)
23370 (let ((end (save-excursion (outline-next-heading) (point)))
23371 (re (concat "\\(" org-drawer-regexp "\\)"
23372 "\\|" "[ \t]*" org-keyword-time-regexp)))
23373 (forward-line 1)
23374 (while (re-search-forward re end t)
23375 (if (not (match-end 1))
23376 ;; empty or planning line
23377 (forward-line 1)
23378 ;; a drawer, find the end
23379 (re-search-forward "^[ \t]*:END:" end 'move)
23380 (forward-line 1)))
23381 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23382 (point)))
23384 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23385 "Move forward to the ARG'th subheading at same level as this one.
23386 Stop at the first and last subheadings of a superior heading.
23387 Normally this only looks at visible headings, but when INVISIBLE-OK is
23388 non-nil it will also look at invisible ones."
23389 (interactive "p")
23390 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23391 (if (and arg (< arg 0))
23392 (goto-char (point-min))
23393 (outline-next-heading))
23394 (org-at-heading-p)
23395 (let ((level (- (match-end 0) (match-beginning 0) 1))
23396 (f (if (and arg (< arg 0))
23397 're-search-backward
23398 're-search-forward))
23399 (count (if arg (abs arg) 1))
23400 (result (point)))
23401 (while (and (prog1 (> count 0)
23402 (forward-char (if (and arg (< arg 0)) -1 1)))
23403 (funcall f org-outline-regexp-bol nil 'move))
23404 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23405 (cond ((< l level) (setq count 0))
23406 ((and (= l level)
23407 (or invisible-ok
23408 (progn
23409 (goto-char (line-beginning-position))
23410 (not (outline-invisible-p)))))
23411 (setq count (1- count))
23412 (when (eq l level)
23413 (setq result (point)))))))
23414 (goto-char result))
23415 (beginning-of-line 1)))
23417 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23418 "Move backward to the ARG'th subheading at same level as this one.
23419 Stop at the first and last subheadings of a superior heading."
23420 (interactive "p")
23421 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23423 (defun org-next-block (arg &optional backward block-regexp)
23424 "Jump to the next block.
23425 With a prefix argument ARG, jump forward ARG many source blocks.
23426 When BACKWARD is non-nil, jump to the previous block.
23427 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23428 (interactive "p")
23429 (let ((re (or block-regexp org-block-regexp))
23430 (re-search-fn (or (and backward 're-search-backward)
23431 're-search-forward)))
23432 (if (looking-at re) (forward-char 1))
23433 (condition-case nil
23434 (funcall re-search-fn re nil nil arg)
23435 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23436 (goto-char (match-beginning 0)) (org-show-context)))
23438 (defun org-previous-block (arg &optional block-regexp)
23439 "Jump to the previous block.
23440 With a prefix argument ARG, jump backward ARG many source blocks.
23441 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23442 (interactive "p")
23443 (org-next-block arg t block-regexp))
23445 (defun org-forward-paragraph ()
23446 "Move forward to beginning of next paragraph or equivalent.
23448 The function moves point to the beginning of the next visible
23449 structural element, which can be a paragraph, a table, a list
23450 item, etc. It also provides some special moves for convenience:
23452 - On an affiliated keyword, jump to the beginning of the
23453 relative element.
23454 - On an item or a footnote definition, move to the second
23455 element inside, if any.
23456 - On a table or a property drawer, jump after it.
23457 - On a verse or source block, stop after blank lines."
23458 (interactive)
23459 (when (eobp) (user-error "Cannot move further down"))
23460 (let* ((deactivate-mark nil)
23461 (element (org-element-at-point))
23462 (type (org-element-type element))
23463 (post-affiliated (org-element-property :post-affiliated element))
23464 (contents-begin (org-element-property :contents-begin element))
23465 (contents-end (org-element-property :contents-end element))
23466 (end (let ((end (org-element-property :end element)) (parent element))
23467 (while (and (setq parent (org-element-property :parent parent))
23468 (= (org-element-property :contents-end parent) end))
23469 (setq end (org-element-property :end parent)))
23470 end)))
23471 (cond ((not element)
23472 (skip-chars-forward " \r\t\n")
23473 (or (eobp) (beginning-of-line)))
23474 ;; On affiliated keywords, move to element's beginning.
23475 ((and post-affiliated (< (point) post-affiliated))
23476 (goto-char post-affiliated))
23477 ;; At a table row, move to the end of the table. Similarly,
23478 ;; at a node property, move to the end of the property
23479 ;; drawer.
23480 ((memq type '(node-property table-row))
23481 (goto-char (org-element-property
23482 :end (org-element-property :parent element))))
23483 ((memq type '(property-drawer table)) (goto-char end))
23484 ;; Consider blank lines as separators in verse and source
23485 ;; blocks to ease editing.
23486 ((memq type '(src-block verse-block))
23487 (when (eq type 'src-block)
23488 (setq contents-end
23489 (save-excursion (goto-char end)
23490 (skip-chars-backward " \r\t\n")
23491 (line-beginning-position))))
23492 (beginning-of-line)
23493 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23494 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23495 (goto-char end)
23496 (skip-chars-forward " \r\t\n")
23497 (if (= (point) contents-end) (goto-char end)
23498 (beginning-of-line))))
23499 ;; With no contents, just skip element.
23500 ((not contents-begin) (goto-char end))
23501 ;; If contents are invisible, skip the element altogether.
23502 ((outline-invisible-p (line-end-position))
23503 (case type
23504 (headline
23505 (org-with-limited-levels (outline-next-visible-heading 1)))
23506 ;; At a plain list, make sure we move to the next item
23507 ;; instead of skipping the whole list.
23508 (plain-list (forward-char)
23509 (org-forward-paragraph))
23510 (otherwise (goto-char end))))
23511 ((>= (point) contents-end) (goto-char end))
23512 ((>= (point) contents-begin)
23513 ;; This can only happen on paragraphs and plain lists.
23514 (case type
23515 (paragraph (goto-char end))
23516 ;; At a plain list, try to move to second element in
23517 ;; first item, if possible.
23518 (plain-list (end-of-line)
23519 (org-forward-paragraph))))
23520 ;; When contents start on the middle of a line (e.g. in
23521 ;; items and footnote definitions), try to reach first
23522 ;; element starting after current line.
23523 ((> (line-end-position) contents-begin)
23524 (end-of-line)
23525 (org-forward-paragraph))
23526 (t (goto-char contents-begin)))))
23528 (defun org-backward-paragraph ()
23529 "Move backward to start of previous paragraph or equivalent.
23531 The function moves point to the beginning of the current
23532 structural element, which can be a paragraph, a table, a list
23533 item, etc., or to the beginning of the previous visible one if
23534 point is already there. It also provides some special moves for
23535 convenience:
23537 - On an affiliated keyword, jump to the first one.
23538 - On a table or a property drawer, move to its beginning.
23539 - On a verse or source block, stop before blank lines."
23540 (interactive)
23541 (when (bobp) (user-error "Cannot move further up"))
23542 (let* ((deactivate-mark nil)
23543 (element (org-element-at-point))
23544 (type (org-element-type element))
23545 (contents-begin (org-element-property :contents-begin element))
23546 (contents-end (org-element-property :contents-end element))
23547 (post-affiliated (org-element-property :post-affiliated element))
23548 (begin (org-element-property :begin element)))
23549 (cond
23550 ((not element) (goto-char (point-min)))
23551 ((= (point) begin)
23552 (backward-char)
23553 (org-backward-paragraph))
23554 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23555 ((memq type '(node-property table-row))
23556 (goto-char (org-element-property
23557 :post-affiliated (org-element-property :parent element))))
23558 ((memq type '(property-drawer table)) (goto-char begin))
23559 ((memq type '(src-block verse-block))
23560 (when (eq type 'src-block)
23561 (setq contents-begin
23562 (save-excursion (goto-char begin) (forward-line) (point))))
23563 (if (= (point) contents-begin) (goto-char post-affiliated)
23564 ;; Inside a verse block, see blank lines as paragraph
23565 ;; separators.
23566 (let ((origin (point)))
23567 (skip-chars-backward " \r\t\n" contents-begin)
23568 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23569 (skip-chars-forward " \r\t\n" origin)
23570 (if (= (point) origin) (goto-char contents-begin)
23571 (beginning-of-line))))))
23572 ((not contents-begin) (goto-char (or post-affiliated begin)))
23573 ((eq type 'paragraph)
23574 (goto-char contents-begin)
23575 ;; When at first paragraph in an item or a footnote definition,
23576 ;; move directly to beginning of line.
23577 (let ((parent-contents
23578 (org-element-property
23579 :contents-begin (org-element-property :parent element))))
23580 (when (and parent-contents (= parent-contents contents-begin))
23581 (beginning-of-line))))
23582 ;; At the end of a greater element, move to the beginning of the
23583 ;; last element within.
23584 ((>= (point) contents-end)
23585 (goto-char (1- contents-end))
23586 (org-backward-paragraph))
23587 (t (goto-char (or post-affiliated begin))))
23588 ;; Ensure we never leave point invisible.
23589 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23591 (defun org-forward-element ()
23592 "Move forward by one element.
23593 Move to the next element at the same level, when possible."
23594 (interactive)
23595 (cond ((eobp) (user-error "Cannot move further down"))
23596 ((org-with-limited-levels (org-at-heading-p))
23597 (let ((origin (point)))
23598 (goto-char (org-end-of-subtree nil t))
23599 (unless (org-with-limited-levels (org-at-heading-p))
23600 (goto-char origin)
23601 (user-error "Cannot move further down"))))
23603 (let* ((elem (org-element-at-point))
23604 (end (org-element-property :end elem))
23605 (parent (org-element-property :parent elem)))
23606 (cond ((and parent (= (org-element-property :contents-end parent) end))
23607 (goto-char (org-element-property :end parent)))
23608 ((integer-or-marker-p end) (goto-char end))
23609 (t (message "No element at point")))))))
23611 (defun org-backward-element ()
23612 "Move backward by one element.
23613 Move to the previous element at the same level, when possible."
23614 (interactive)
23615 (cond ((bobp) (user-error "Cannot move further up"))
23616 ((org-with-limited-levels (org-at-heading-p))
23617 ;; At a headline, move to the previous one, if any, or stay
23618 ;; here.
23619 (let ((origin (point)))
23620 (org-with-limited-levels (org-backward-heading-same-level 1))
23621 ;; When current headline has no sibling above, move to its
23622 ;; parent.
23623 (when (= (point) origin)
23624 (or (org-with-limited-levels (org-up-heading-safe))
23625 (progn (goto-char origin)
23626 (user-error "Cannot move further up"))))))
23628 (let* ((elem (org-element-at-point))
23629 (beg (org-element-property :begin elem)))
23630 (cond
23631 ;; Move to beginning of current element if point isn't
23632 ;; there already.
23633 ((null beg) (message "No element at point"))
23634 ((/= (point) beg) (goto-char beg))
23635 (t (goto-char beg)
23636 (skip-chars-backward " \r\t\n")
23637 (unless (bobp)
23638 (let ((prev (org-element-at-point)))
23639 (goto-char (org-element-property :begin prev))
23640 (while (and (setq prev (org-element-property :parent prev))
23641 (<= (org-element-property :end prev) beg))
23642 (goto-char (org-element-property :begin prev)))))))))))
23644 (defun org-up-element ()
23645 "Move to upper element."
23646 (interactive)
23647 (if (org-with-limited-levels (org-at-heading-p))
23648 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23649 (let* ((elem (org-element-at-point))
23650 (parent (org-element-property :parent elem)))
23651 (if parent (goto-char (org-element-property :begin parent))
23652 (if (org-with-limited-levels (org-before-first-heading-p))
23653 (user-error "No surrounding element")
23654 (org-with-limited-levels (org-back-to-heading)))))))
23656 (defvar org-element-greater-elements)
23657 (defun org-down-element ()
23658 "Move to inner element."
23659 (interactive)
23660 (let ((element (org-element-at-point)))
23661 (cond
23662 ((memq (org-element-type element) '(plain-list table))
23663 (goto-char (org-element-property :contents-begin element))
23664 (forward-char))
23665 ((memq (org-element-type element) org-element-greater-elements)
23666 ;; If contents are hidden, first disclose them.
23667 (when (outline-invisible-p (line-end-position)) (org-cycle))
23668 (goto-char (or (org-element-property :contents-begin element)
23669 (user-error "No content for this element"))))
23670 (t (user-error "No inner element")))))
23672 (defun org-drag-element-backward ()
23673 "Move backward element at point."
23674 (interactive)
23675 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23676 (let* ((elem (org-element-at-point))
23677 (prev-elem
23678 (save-excursion
23679 (goto-char (org-element-property :begin elem))
23680 (skip-chars-backward " \r\t\n")
23681 (unless (bobp)
23682 (let* ((beg (org-element-property :begin elem))
23683 (prev (org-element-at-point))
23684 (up prev))
23685 (while (and (setq up (org-element-property :parent up))
23686 (<= (org-element-property :end prev) beg))
23687 (setq prev up))
23688 prev)))))
23689 ;; Error out if no previous element or previous element is
23690 ;; a parent of the current one.
23691 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23692 (user-error "Cannot drag element backward")
23693 (let ((pos (point)))
23694 (org-element-swap-A-B prev-elem elem)
23695 (goto-char (+ (org-element-property :begin prev-elem)
23696 (- pos (org-element-property :begin elem)))))))))
23698 (defun org-drag-element-forward ()
23699 "Move forward element at point."
23700 (interactive)
23701 (let* ((pos (point))
23702 (elem (org-element-at-point)))
23703 (when (= (point-max) (org-element-property :end elem))
23704 (user-error "Cannot drag element forward"))
23705 (goto-char (org-element-property :end elem))
23706 (let ((next-elem (org-element-at-point)))
23707 (when (or (org-element-nested-p elem next-elem)
23708 (and (eq (org-element-type next-elem) 'headline)
23709 (not (eq (org-element-type elem) 'headline))))
23710 (goto-char pos)
23711 (user-error "Cannot drag element forward"))
23712 ;; Compute new position of point: it's shifted by NEXT-ELEM
23713 ;; body's length (without final blanks) and by the length of
23714 ;; blanks between ELEM and NEXT-ELEM.
23715 (let ((size-next (- (save-excursion
23716 (goto-char (org-element-property :end next-elem))
23717 (skip-chars-backward " \r\t\n")
23718 (forward-line)
23719 ;; Small correction if buffer doesn't end
23720 ;; with a newline character.
23721 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23722 (org-element-property :begin next-elem)))
23723 (size-blank (- (org-element-property :end elem)
23724 (save-excursion
23725 (goto-char (org-element-property :end elem))
23726 (skip-chars-backward " \r\t\n")
23727 (forward-line)
23728 (point)))))
23729 (org-element-swap-A-B elem next-elem)
23730 (goto-char (+ pos size-next size-blank))))))
23732 (defun org-drag-line-forward (arg)
23733 "Drag the line at point ARG lines forward."
23734 (interactive "p")
23735 (dotimes (n (abs arg))
23736 (let ((c (current-column)))
23737 (if (< 0 arg)
23738 (progn
23739 (beginning-of-line 2)
23740 (transpose-lines 1)
23741 (beginning-of-line 0))
23742 (transpose-lines 1)
23743 (beginning-of-line -1))
23744 (org-move-to-column c))))
23746 (defun org-drag-line-backward (arg)
23747 "Drag the line at point ARG lines backward."
23748 (interactive "p")
23749 (org-drag-line-forward (- arg)))
23751 (defun org-mark-element ()
23752 "Put point at beginning of this element, mark at end.
23754 Interactively, if this command is repeated or (in Transient Mark
23755 mode) if the mark is active, it marks the next element after the
23756 ones already marked."
23757 (interactive)
23758 (let (deactivate-mark)
23759 (if (and (org-called-interactively-p 'any)
23760 (or (and (eq last-command this-command) (mark t))
23761 (and transient-mark-mode mark-active)))
23762 (set-mark
23763 (save-excursion
23764 (goto-char (mark))
23765 (goto-char (org-element-property :end (org-element-at-point)))))
23766 (let ((element (org-element-at-point)))
23767 (end-of-line)
23768 (push-mark (org-element-property :end element) t t)
23769 (goto-char (org-element-property :begin element))))))
23771 (defun org-narrow-to-element ()
23772 "Narrow buffer to current element."
23773 (interactive)
23774 (let ((elem (org-element-at-point)))
23775 (cond
23776 ((eq (car elem) 'headline)
23777 (narrow-to-region
23778 (org-element-property :begin elem)
23779 (org-element-property :end elem)))
23780 ((memq (car elem) org-element-greater-elements)
23781 (narrow-to-region
23782 (org-element-property :contents-begin elem)
23783 (org-element-property :contents-end elem)))
23785 (narrow-to-region
23786 (org-element-property :begin elem)
23787 (org-element-property :end elem))))))
23789 (defun org-transpose-element ()
23790 "Transpose current and previous elements, keeping blank lines between.
23791 Point is moved after both elements."
23792 (interactive)
23793 (org-skip-whitespace)
23794 (let ((end (org-element-property :end (org-element-at-point))))
23795 (org-drag-element-backward)
23796 (goto-char end)))
23798 (defun org-unindent-buffer ()
23799 "Un-indent the visible part of the buffer.
23800 Relative indentation (between items, inside blocks, etc.) isn't
23801 modified."
23802 (interactive)
23803 (unless (eq major-mode 'org-mode)
23804 (user-error "Cannot un-indent a buffer not in Org mode"))
23805 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23806 unindent-tree ; For byte-compiler.
23807 (unindent-tree
23808 (function
23809 (lambda (contents)
23810 (mapc
23811 (lambda (element)
23812 (if (memq (org-element-type element) '(headline section))
23813 (funcall unindent-tree (org-element-contents element))
23814 (save-excursion
23815 (save-restriction
23816 (narrow-to-region
23817 (org-element-property :begin element)
23818 (org-element-property :end element))
23819 (org-do-remove-indentation)))))
23820 (reverse contents))))))
23821 (funcall unindent-tree (org-element-contents parse-tree))))
23823 (defun org-show-subtree ()
23824 "Show everything after this heading at deeper levels."
23825 (interactive)
23826 (outline-flag-region
23827 (point)
23828 (save-excursion
23829 (org-end-of-subtree t t))
23830 nil))
23832 (defun org-show-entry ()
23833 "Show the body directly following this heading.
23834 Show the heading too, if it is currently invisible."
23835 (interactive)
23836 (save-excursion
23837 (condition-case nil
23838 (progn
23839 (org-back-to-heading t)
23840 (outline-flag-region
23841 (max (point-min) (1- (point)))
23842 (save-excursion
23843 (if (re-search-forward
23844 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23845 (match-beginning 1)
23846 (point-max)))
23847 nil)
23848 (org-cycle-hide-drawers 'children))
23849 (error nil))))
23851 (defun org-make-options-regexp (kwds &optional extra)
23852 "Make a regular expression for keyword lines."
23853 (concat
23854 "^#\\+\\("
23855 (mapconcat 'regexp-quote kwds "\\|")
23856 (if extra (concat "\\|" extra))
23857 "\\):[ \t]*\\(.*\\)"))
23859 ;; Make isearch reveal the necessary context
23860 (defun org-isearch-end ()
23861 "Reveal context after isearch exits."
23862 (when isearch-success ; only if search was successful
23863 (if (featurep 'xemacs)
23864 ;; Under XEmacs, the hook is run in the correct place,
23865 ;; we directly show the context.
23866 (org-show-context 'isearch)
23867 ;; In Emacs the hook runs *before* restoring the overlays.
23868 ;; So we have to use a one-time post-command-hook to do this.
23869 ;; (Emacs 22 has a special variable, see function `org-mode')
23870 (unless (and (boundp 'isearch-mode-end-hook-quit)
23871 isearch-mode-end-hook-quit)
23872 ;; Only when the isearch was not quitted.
23873 (org-add-hook 'post-command-hook 'org-isearch-post-command
23874 'append 'local)))
23875 (org-fix-ellipsis-at-bol)))
23877 (defun org-isearch-post-command ()
23878 "Remove self from hook, and show context."
23879 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23880 (org-show-context 'isearch))
23883 ;;;; Integration with and fixes for other packages
23885 ;;; Imenu support
23887 (defvar org-imenu-markers nil
23888 "All markers currently used by Imenu.")
23889 (make-variable-buffer-local 'org-imenu-markers)
23891 (defun org-imenu-new-marker (&optional pos)
23892 "Return a new marker for use by Imenu, and remember the marker."
23893 (let ((m (make-marker)))
23894 (move-marker m (or pos (point)))
23895 (push m org-imenu-markers)
23898 (defun org-imenu-get-tree ()
23899 "Produce the index for Imenu."
23900 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23901 (setq org-imenu-markers nil)
23902 (let* ((n org-imenu-depth)
23903 (re (concat "^" (org-get-limited-outline-regexp)))
23904 (subs (make-vector (1+ n) nil))
23905 (last-level 0)
23906 m level head0 head)
23907 (save-excursion
23908 (save-restriction
23909 (widen)
23910 (goto-char (point-max))
23911 (while (re-search-backward re nil t)
23912 (setq level (org-reduced-level (funcall outline-level)))
23913 (when (and (<= level n)
23914 (looking-at org-complex-heading-regexp)
23915 (setq head0 (org-match-string-no-properties 4)))
23916 (setq head (org-link-display-format head0)
23917 m (org-imenu-new-marker))
23918 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23919 (if (>= level last-level)
23920 (push (cons head m) (aref subs level))
23921 (push (cons head (aref subs (1+ level))) (aref subs level))
23922 (loop for i from (1+ level) to n do (aset subs i nil)))
23923 (setq last-level level)))))
23924 (aref subs 1)))
23926 (eval-after-load "imenu"
23927 '(progn
23928 (add-hook 'imenu-after-jump-hook
23929 (lambda ()
23930 (if (derived-mode-p 'org-mode)
23931 (org-show-context 'org-goto))))))
23933 (defun org-link-display-format (link)
23934 "Replace a link with its the description.
23935 If there is no description, use the link target."
23936 (save-match-data
23937 (if (string-match org-bracket-link-analytic-regexp link)
23938 (replace-match (if (match-end 5)
23939 (match-string 5 link)
23940 (concat (match-string 1 link)
23941 (match-string 3 link)))
23942 nil t link)
23943 link)))
23945 (defun org-toggle-link-display ()
23946 "Toggle the literal or descriptive display of links."
23947 (interactive)
23948 (if org-descriptive-links
23949 (progn (org-remove-from-invisibility-spec '(org-link))
23950 (org-restart-font-lock)
23951 (setq org-descriptive-links nil))
23952 (progn (add-to-invisibility-spec '(org-link))
23953 (org-restart-font-lock)
23954 (setq org-descriptive-links t))))
23956 ;; Speedbar support
23958 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23959 "Overlay marking the agenda restriction line in speedbar.")
23960 (overlay-put org-speedbar-restriction-lock-overlay
23961 'face 'org-agenda-restriction-lock)
23962 (overlay-put org-speedbar-restriction-lock-overlay
23963 'help-echo "Agendas are currently limited to this item.")
23964 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23966 (defun org-speedbar-set-agenda-restriction ()
23967 "Restrict future agenda commands to the location at point in speedbar.
23968 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23969 (interactive)
23970 (require 'org-agenda)
23971 (let (p m tp np dir txt)
23972 (cond
23973 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23974 'org-imenu t))
23975 (setq m (get-text-property p 'org-imenu-marker))
23976 (with-current-buffer (marker-buffer m)
23977 (goto-char m)
23978 (org-agenda-set-restriction-lock 'subtree)))
23979 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23980 'speedbar-function 'speedbar-find-file))
23981 (setq tp (previous-single-property-change
23982 (1+ p) 'speedbar-function)
23983 np (next-single-property-change
23984 tp 'speedbar-function)
23985 dir (speedbar-line-directory)
23986 txt (buffer-substring-no-properties (or tp (point-min))
23987 (or np (point-max))))
23988 (with-current-buffer (find-file-noselect
23989 (let ((default-directory dir))
23990 (expand-file-name txt)))
23991 (unless (derived-mode-p 'org-mode)
23992 (user-error "Cannot restrict to non-Org-mode file"))
23993 (org-agenda-set-restriction-lock 'file)))
23994 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23995 (move-overlay org-speedbar-restriction-lock-overlay
23996 (point-at-bol) (point-at-eol))
23997 (setq current-prefix-arg nil)
23998 (org-agenda-maybe-redo)))
24000 (defvar speedbar-file-key-map)
24001 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24002 (eval-after-load "speedbar"
24003 '(progn
24004 (speedbar-add-supported-extension ".org")
24005 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24006 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24007 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24008 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24009 (add-hook 'speedbar-visiting-tag-hook
24010 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24012 ;;; Fixes and Hacks for problems with other packages
24014 (defun org-mode-flyspell-verify ()
24015 "Function used for `flyspell-generic-check-word-predicate'."
24016 (if (org-at-heading-p)
24017 ;; At a headline or an inlinetask, check title only. This is
24018 ;; faster than relying on `org-element-at-point'.
24019 (and (save-excursion (beginning-of-line)
24020 (and (let ((case-fold-search t))
24021 (not (looking-at "\\*+ END[ \t]*$")))
24022 (looking-at org-complex-heading-regexp)))
24023 (match-beginning 4)
24024 (>= (point) (match-beginning 4))
24025 (or (not (match-beginning 5))
24026 (< (point) (match-beginning 5))))
24027 (let* ((element (org-element-at-point))
24028 (post-affiliated (org-element-property :post-affiliated element))
24029 (object-check
24030 (function
24031 ;; Non-nil if checks can be done for object at point.
24032 (lambda ()
24033 (let ((object (save-excursion
24034 (when (org-looking-at-p "\\>") (backward-char))
24035 (org-element-context element))))
24036 (case (org-element-type object)
24037 ;; Prevent checks in links due to keybinding conflict
24038 ;; with Flyspell.
24039 ((code entity export-snippet inline-babel-call
24040 inline-src-block line-break latex-fragment link macro
24041 statistics-cookie target timestamp verbatim)
24042 nil)
24043 (footnote-reference
24044 ;; Only in inline footnotes, within the definition.
24045 (and (eq (org-element-property :type object) 'inline)
24046 (< (save-excursion
24047 (goto-char (org-element-property :begin object))
24048 (search-forward ":" nil t 2))
24049 (point))))
24050 (otherwise t)))))))
24051 (cond
24052 ;; Ignore checks in all affiliated keywords but captions.
24053 ((and post-affiliated (< (point) post-affiliated))
24054 (and (save-excursion
24055 (beginning-of-line)
24056 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24057 (> (point) (match-end 0))
24058 (funcall object-check)))
24059 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24060 ((and org-log-into-drawer
24061 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24062 (parent element))
24063 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24064 (setq parent (org-element-property :parent parent)))
24065 (and parent
24066 (eq (compare-strings
24067 log nil nil
24068 (org-element-property :drawer-name parent) nil nil t)
24069 t))))
24070 nil)
24072 (case (org-element-type element)
24073 ((comment quote-section) t)
24074 (comment-block
24075 ;; Allow checks between block markers, not on them.
24076 (and (> (line-beginning-position)
24077 (org-element-property :post-affiliated element))
24078 (save-excursion
24079 (end-of-line)
24080 (skip-chars-forward " \r\t\n")
24081 (< (point) (org-element-property :end element)))))
24082 ;; Arbitrary list of keywords where checks are meaningful.
24083 ;; Make sure point is on the value part of the element.
24084 (keyword
24085 (and (member (org-element-property :key element)
24086 '("DESCRIPTION" "TITLE"))
24087 (< (save-excursion
24088 (beginning-of-line) (search-forward ":") (point))
24089 (point))))
24090 ;; Check is globally allowed in paragraphs verse blocks and
24091 ;; table rows (after affiliated keywords) but some objects
24092 ;; must not be affected.
24093 ((paragraph table-row verse-block)
24094 (and (>= (point) (org-element-property :contents-begin element))
24095 (< (point) (org-element-property :contents-end element))
24096 (funcall object-check)))))))))
24097 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24099 (defun org-remove-flyspell-overlays-in (beg end)
24100 "Remove flyspell overlays in region."
24101 (and (org-bound-and-true-p flyspell-mode)
24102 (fboundp 'flyspell-delete-region-overlays)
24103 (flyspell-delete-region-overlays beg end)))
24105 (eval-after-load "flyspell"
24106 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24108 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24109 (eval-after-load "bookmark"
24110 '(if (boundp 'bookmark-after-jump-hook)
24111 ;; We can use the hook
24112 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24113 ;; Hook not available, use advice
24114 (defadvice bookmark-jump (after org-make-visible activate)
24115 "Make the position visible."
24116 (org-bookmark-jump-unhide))))
24118 ;; Make sure saveplace shows the location if it was hidden
24119 (eval-after-load "saveplace"
24120 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24121 "Make the position visible."
24122 (org-bookmark-jump-unhide)))
24124 ;; Make sure ecb shows the location if it was hidden
24125 (eval-after-load "ecb"
24126 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24127 "Make hierarchy visible when jumping into location from ECB tree buffer."
24128 (if (derived-mode-p 'org-mode)
24129 (org-show-context))))
24131 (defun org-bookmark-jump-unhide ()
24132 "Unhide the current position, to show the bookmark location."
24133 (and (derived-mode-p 'org-mode)
24134 (or (outline-invisible-p)
24135 (save-excursion (goto-char (max (point-min) (1- (point))))
24136 (outline-invisible-p)))
24137 (org-show-context 'bookmark-jump)))
24139 ;; Make session.el ignore our circular variable
24140 (defvar session-globals-exclude)
24141 (eval-after-load "session"
24142 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24144 ;;;; Finish up
24146 (provide 'org)
24148 (run-hooks 'org-load-hook)
24150 ;;; org.el ends here